diff --git a/README.md b/README.md index a4f747ed1..4fc990046 100644 --- a/README.md +++ b/README.md @@ -57,11 +57,11 @@ The installation instructions below use the environment name, "weis-env," but an 2. Use conda to install the build dependencies. Note the differences between Windows and Mac/Linux build systems. Skip to point #3 if you are on the DOE HPC system Eagle - conda install -y cmake cython control dill git jsonschema make matplotlib-base numpy openmdao openpyxl pandas pip pytest python-benedict pyyaml ruamel_yaml scipy setuptools smt sortedcontainers swig + conda install -y cmake cython control dill git jsonschema make matplotlib-base numpy openmdao openpyxl pandas pip pyoptsparse pytest python-benedict pyyaml ruamel_yaml scipy setuptools simpy slycot smt sortedcontainers swig conda install -y petsc4py mpi4py # (Mac / Linux only) conda install -y compilers # (Mac only) conda install -y m2w64-toolchain libpython # (Windows only) - pip install simpy marmot-agents jsonmerge fatpack + pip install marmot-agents jsonmerge fatpack git clone https://github.com/WISDEM/WEIS.git cd WEIS git checkout branch_name # (Only if you want to switch git branch, say develop) @@ -69,9 +69,9 @@ The installation instructions below use the environment name, "weis-env," but an 3. Instructions specific for DOE HPC system Eagle - conda install -y cmake cython control dill git jsonschema make matplotlib-base numpy openmdao openpyxl pandas pip pytest python-benedict pyyaml ruamel_yaml scipy setuptools smt sortedcontainers swig - conda install -y petsc4py mpi4py - pip install simpy marmot-agents jsonmerge fatpack + conda install -y cmake cython control dill git jsonschema make matplotlib-base numpy openmdao openpyxl pandas pip pyoptsparse pytest python-benedict pyyaml ruamel_yaml scipy setuptools simpy slycot smt sortedcontainers swig + conda install -y petsc4py mpi4py + pip install marmot-agents jsonmerge fatpack git clone https://github.com/WISDEM/WEIS.git cd WEIS git checkout branch_name # (Only if you want to switch git branch, say develop) diff --git a/WISDEM/.github/workflows/CI_WISDEM.yml b/WISDEM/.github/workflows/CI_WISDEM.yml index 81db4b25b..30a3ea86b 100644 --- a/WISDEM/.github/workflows/CI_WISDEM.yml +++ b/WISDEM/.github/workflows/CI_WISDEM.yml @@ -32,7 +32,7 @@ jobs: #shell: pwsh # putting in a shell command makes for compile linking problems later # (if you use the shell here, cannot use 'compiler' package) run: | - conda install -y petsc4py mpi4py compilers nlopt + conda install -y petsc4py mpi4py compilers pyoptsparse # Install dependencies of WISDEM specific to windows - name: Add dependencies windows specific @@ -44,12 +44,26 @@ jobs: #- name: Setup tmate session # uses: mxschmitt/action-tmate@v3 - # Install WISDEM - - name: Install WISDEM + # Install WISDEM with setup + - name: Install WISDEM with setup shell: pwsh run: | python setup.py develop + # Install WISDEM with pip + - name: Install WISDEM with pip for Unix + if: false == contains( matrix.os, 'windows') + shell: pwsh + run: | + pip install -vv --no-deps -e . + + # Install WISDEM with pip + #- name: Install WISDEM with pip for Windows + # if: contains( matrix.os, 'windows') + # shell: pwsh + # run: | + # pip install -vv --no-deps --global-option --compiler=unix . + # Run all tests - name: Run tests if: contains( matrix.os, 'ubuntu') diff --git a/WISDEM/README.md b/WISDEM/README.md index 006c7f0c6..6faafda92 100644 --- a/WISDEM/README.md +++ b/WISDEM/README.md @@ -48,25 +48,19 @@ The installation instructions below use the environment name, "wisdem-env," but conda create -y --name wisdem-env python=3.8 conda activate wisdem-env -2. In order to directly use the examples in the repository and peek at the code when necessary, we recommend all users install WISDEM in *developer* mode. This is done by first installing WISDEM as a conda package to easily satisfy all dependencies, but then removing the WISDEM conda package and reinstalling from the Github source code. Note the differences between Windows and Mac/Linux build systems. For Linux, we recommend using the native compilers (for example, gcc and gfortran in the default GNU suite). +2. In order to directly use the examples in the repository and peek at the code when necessary, we recommend all users install WISDEM in *developer / editable* mode using the instructions here. If you really just want to use WISDEM as a library and lean on the documentation, you can always do `conda install wisdem` and be done. Note the differences between Windows and Mac/Linux build systems. For Linux, we recommend using the native compilers (for example, gcc and gfortran in the default GNU suite). - conda install -y wisdem git - conda remove -y --force wisdem - conda install -y compilers # (Mac only) + conda install -y cython git jsonschema make matplotlib nlopt numpy openmdao openpyxl pandas pip pyside2 pytest python-benedict pyyaml ruamel_yaml scipy setuptools simpy sortedcontainers swig + conda install -y pyoptsparse # (Linux only) + conda install -y compilers pyoptsparse # (Mac only) conda install -y m2w64-toolchain libpython # (Windows only) - pip install simpy marmot-agents nlopt + pip install marmot-agents git clone https://github.com/WISDEM/WISDEM.git cd WISDEM git checkout develop # If you want to switch WISDEM branches python setup.py develop -3. OPTIONAL: Install pyOptSparse, a package that provides a handful of additional optimization solvers and has OpenMDAO support: - - git clone https://github.com/evan-gaertner/pyoptsparse.git - pip install -e pyoptsparse - - **NOTE:** To use WISDEM again after installation is complete, you will always need to activate the conda environment first with `conda activate wisdem-env` diff --git a/WISDEM/docs/installation.rst b/WISDEM/docs/installation.rst index 883a78aed..562b56db3 100644 --- a/WISDEM/docs/installation.rst +++ b/WISDEM/docs/installation.rst @@ -13,7 +13,7 @@ Setup and activate the Anaconda environment from a prompt (Anaconda3 Power Shell .. code-block:: bash conda config --add channels conda-forge - conda create -y --name wisdem-env python=3.7 + conda create -y --name wisdem-env python=3.8 conda activate wisdem-env Note that any future occasion on which you wish to use WISDEM, you will only have to start with ``conda activate wisdem-env``. @@ -21,19 +21,24 @@ Note that any future occasion on which you wish to use WISDEM, you will only hav Install WISDEM ^^^^^^^^^^^^^^ -In order to directly use the examples in the repository and peek at the code when necessary, we recommend all users install WISDEM in *developer* mode. This is done by first installing WISDEM as a conda package to easily satisfy all dependencies, but then removing the WISDEM conda package and reinstalling from the Github source code. Note the differences between Windows and Mac build systems. For Linux, we recommend using the native compilers (for example, gcc and gfortran in the default GNU suite). +In order to directly use the examples in the repository and peek at the code when necessary, we recommend all users install WISDEM in *developer* mode. This is done by first installing WISDEM dependencies and then installing WISDEM from the Github source code. Note the differences between Windows and Mac build systems. For Linux, we recommend using the native compilers (for example, gcc and gfortran in the default GNU suite). .. code-block:: bash - conda install -y wisdem git - conda remove --force wisdem - pip install simpy marmot-agents nlopt + conda install -y cython git jsonschema make matplotlib nlopt numpy openmdao openpyxl pandas pip pyside2 pytest python-benedict pyyaml ruamel_yaml scipy setuptools simpy sortedcontainers swig + pip install marmot-agents + +For Linux systems: + +.. code-block:: bash + + conda install pyoptsparse For Mac systems: .. code-block:: bash - conda install compilers + conda install compilers pyoptsparse For Windows systems: @@ -50,16 +55,6 @@ Finally, for all systems: git checkout develop pip install -e . -Install pyOptSparse (`Optional`) -"""""""""""""""""""""""""""""""" - -`pyOptSparse `_ is a package that provides additional optimization solvers with OpenMDAO support: - -.. code-block:: bash - - git clone https://github.com/evan-gaertner/pyoptsparse.git - pip install -e pyoptsparse - Run Unit Tests ^^^^^^^^^^^^^^ diff --git a/WISDEM/environment.yml b/WISDEM/environment.yml index 88e2a8429..f7f0e827e 100644 --- a/WISDEM/environment.yml +++ b/WISDEM/environment.yml @@ -26,14 +26,15 @@ dependencies: - pyyaml - ruamel_yaml - scipy - - setuptools==58.4.0 + - setuptools + - simpy - sortedcontainers - swig - pip: - - simpy - marmot-agents # Needs to be done outside of environment file: # - m2w64-toolchain # [win] # - libpython # [win] # - compilers # [not win] # - petsc4py # [not win] +# - pyoptsparse # [not win] diff --git a/WISDEM/setup.py b/WISDEM/setup.py index 6e56239eb..1459a81ab 100644 --- a/WISDEM/setup.py +++ b/WISDEM/setup.py @@ -16,7 +16,7 @@ extra_compile_args=["-O2", "-fPIC", "-std=c11"], ) pyframeExt = Extension( - "wisdem.pyframe3dd._pyframe3dd", + "wisdem.pyframe3dd._pyframe3dd", sources=glob.glob(os.path.join("wisdem", "pyframe3dd", "src", "*.c")), extra_compile_args=["-O2", "-fPIC", "-std=c11"], ) @@ -29,7 +29,7 @@ # Top-level setup setup( name="WISDEM", - version="3.5.0", + version="3.5.1", description="Wind-Plant Integrated System Design & Engineering Model", long_description="""WISDEM is a Python package for conducting multidisciplinary analysis and optimization of wind turbines and plants. It is built on top of NASA's OpenMDAO library.""", @@ -43,7 +43,6 @@ "openmdao>=3.4", "openpyxl", "pandas", - "pyside2", "pytest", "python-benedict", "pyyaml", diff --git a/WISDEM/wisdem/postprocessing/__init__.py b/WISDEM/wisdem/postprocessing/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/WISDEM/wisdem/test/test_optimization_drivers/test_nlopt_driver.py b/WISDEM/wisdem/test/test_optimization_drivers/test_nlopt_driver.py index 2cc2b0e99..d182bd812 100644 --- a/WISDEM/wisdem/test/test_optimization_drivers/test_nlopt_driver.py +++ b/WISDEM/wisdem/test/test_optimization_drivers/test_nlopt_driver.py @@ -10,12 +10,11 @@ from openmdao.utils.general_utils import run_driver from openmdao.test_suite.components.sellar import SellarDerivatives, SellarDerivativesGrouped from openmdao.test_suite.groups.sin_fitter import SineFitter +from wisdem.optimization_drivers.nlopt_driver import NLoptDriver from openmdao.test_suite.components.paraboloid import Paraboloid from openmdao.test_suite.components.simple_comps import NonSquareArrayComp from openmdao.test_suite.components.expl_comp_array import TestExplCompArrayDense -from wisdem.optimization_drivers.nlopt_driver import NLoptDriver - try: import nlopt except ImportError: @@ -1001,9 +1000,11 @@ def test_call_final_setup(self): with self.assertRaises(RuntimeError) as cm: totals = prob.check_totals(method="fd", out_stream=False) - expected_msg = "Problem: run_model must be called before total derivatives can be checked." + # expected_msg = "Problem: run_model must be called before total derivatives can be checked." + expected_msg = "run_model must be called before total derivatives can be checked." - self.assertEqual(expected_msg, str(cm.exception)) + # self.assertEqual(expected_msg, str(cm.exception)) + self.assertTrue(str(cm.exception).find(expected_msg) >= 0) def test_LN_COBYLA_linear_constraint(self): # Bug where NLoptDriver tried to compute and cache the constraint derivatives for the diff --git a/environment.yml b/environment.yml index 25a8d1493..a416d8a9b 100644 --- a/environment.yml +++ b/environment.yml @@ -20,6 +20,7 @@ dependencies: - openpyxl - pandas - pip + - pyoptsparse - pyside2 - pytest - pytest-cov @@ -28,6 +29,8 @@ dependencies: - ruamel_yaml - scipy - setuptools + - simpy + - slycot - smt - sortedcontainers - swig @@ -36,7 +39,6 @@ dependencies: - fatpack - jsonmerge - marmot-agents - - simpy # Needs to be done outside of environment file: # - m2w64-toolchain # [win] # - libpython # [win] diff --git a/pyoptsparse/.coveragerc b/pyoptsparse/.coveragerc deleted file mode 100644 index 1fdce1d3c..000000000 --- a/pyoptsparse/.coveragerc +++ /dev/null @@ -1,16 +0,0 @@ -[report] -exclude_lines = - pragma: no cover - def __repr__ - raise AssertionError - raise NotImplementedError - if __name__ == .__main__.: - -[run] - -omit = - */build/* - */doc/* - */examples/* - */postprocessing/* - */test/* diff --git a/pyoptsparse/.github/ISSUE_TEMPLATE.md b/pyoptsparse/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index ec150016c..000000000 --- a/pyoptsparse/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -name: General issues template -about: For all issues -title: '' -labels: '' -assignees: '' - ---- - -## Type of issue -What types of issue is it? -_Select the appropriate type(s) that describe this issue_ - -- Bugfix (non-breaking change which fixes an issue) -- New feature (non-breaking change which adds functionality) -- Breaking change (non-backwards-compatible fix or feature) -- Documentation update -- Other (please describe) - - -## Description -A description of the issue. -### Steps to reproduce issue -1. … -2. … -3. … - -### Current behavior -… - -### Expected behavior -… - - -### Code version (if relevant) -**Python version:** … - -**External dependencies:** … - -**Internal packages:** … diff --git a/pyoptsparse/.github/PULL_REQUEST_TEMPLATE.md b/pyoptsparse/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 1c3b80f0b..000000000 --- a/pyoptsparse/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,24 +0,0 @@ -## Purpose -Explain the goal of this PR, if it addresses an existing issue be sure to link to it. Describe the big picture of your changes here, perhaps using a bullet list if multiple changes are done to accomplish a single goal. If it accomplishes multiple goals, it would be best to create separate PR's for each. - -## Type of change -What types of change is it? -_Select the appropriate type(s) that describe this PR_ - -- Bugfix (non-breaking change which fixes an issue) -- New feature (non-breaking change which adds functionality) -- Breaking change (non-backwards-compatible fix or feature) -- Code style update (formatting, renaming) -- Refactoring (no functional changes, no API changes) -- Documentation update -- Other (please describe) - -## Testing -Explain the steps needed to test the new code to verify that it does indeed address the issue and produce the expected behavior. - -## Checklist -_Put an `x` in the boxes that apply._ - -- [ ] I have run unit and regression tests which pass locally with my changes -- [ ] I have added new tests that prove my fix is effective or that my feature works -- [ ] I have added necessary documentation diff --git a/pyoptsparse/.gitignore b/pyoptsparse/.gitignore deleted file mode 100644 index 29ce00d72..000000000 --- a/pyoptsparse/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -syntax: glob -build/* -*.pyc -*.so -*.out - diff --git a/pyoptsparse/.travis.yml b/pyoptsparse/.travis.yml deleted file mode 100644 index 114ca4797..000000000 --- a/pyoptsparse/.travis.yml +++ /dev/null @@ -1,135 +0,0 @@ -branches: - only: - - master - -group: deprecated-2017Q4 - -filter_secrets: false - -os: -- linux - -language: generic - -env: - matrix: - - PY=2.7 NUMPY=1.14 - - PY=3.6 NUMPY=1.14 - -addons: - apt: - update: true - sources: - - ubuntu-toolchain-r-test - packages: - - gfortran - - libblas-dev - - liblapack-dev - - libopenmpi-dev - - openmpi-bin - ssh_known_hosts: - - web543.webfaction.com - -cache: - apt: true - directories: - - $HOME/.cache/pip - - $HOME/miniconda - -before_install: -# Check for existence of files to determine if cache exists -# If the dir doesn't exist, but is slated to be cached later, -# Travis unhelpfully creates it, which then causes "dir already exists" -# errors when you go to actually install the thing, so we must non-intuitively -# delete the file before re-creating it later. -- if [ -f $HOME/miniconda/bin/python$PY ]; then - echo "cached miniconda found -- nothing to do"; - else - NOT_CACHED_CONDA=1; - rm -rf $HOME/miniconda; - fi - - -- if [ -f $HOME/.cache/pip ]; then - echo "cached pip found -- nothing to do"; - else - NOT_CACHED_PIP=1; - rm -rf $HOME/.cache/pip; - fi - -# possibly save snopt library and remove old installation of pyoptsparse--all we want kept is the SNOPT. -- SNOPT_DIR=$HOME/miniconda/lib/python$PY/site-packages/pyoptsparse/pySNOPT; -- if [ -d $SNOPT_DIR ]; then - for file in $SNOPT_DIR/snopt*.so; do - if [[ -f $file ]]; then - cp -v $file $HOME; - echo "cached SNOPT object found -- keeping it for later use."; - break; - fi - done - fi - -- rm -rf $HOME/miniconda/lib/python$PY/site-packages/pyoptsparse; - -install: -- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then - openssl aes-256-cbc -K $encrypted_5ebcf5cee077_key -iv $encrypted_5ebcf5cee077_iv -in travis_deploy_rsa.enc -out /tmp/travis_deploy_rsa -d; - eval "$(ssh-agent -s)"; - chmod 600 /tmp/travis_deploy_rsa; - ssh-add /tmp/travis_deploy_rsa; - echo -e "Host web543.webfaction.com\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config; - fi - -- if [ "$NOT_CACHED_CONDA" ]; then - wget "https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh" -O miniconda.sh; - chmod +x miniconda.sh; - ./miniconda.sh -b -p $HOME/miniconda; - export PATH=$HOME/miniconda/bin:$PATH; - conda install --yes python=$PY; - conda install --yes numpy==$NUMPY scipy=0.19.1 swig pip; - else - export PATH=$HOME/miniconda/bin:$PATH; - fi - -- if [ "$NOT_CACHED_PIP" ]; then - pip install --upgrade pip; - pip install mpi4py; - pip install git+https://github.com/OpenMDAO/testflo.git; - pip install coverage; - pip install git+https://github.com/swryan/coveralls-python@work; - fi - -# for merge builds, grab the SNOPT source from secure SNOPT_LOCATION, -# and test building that library every time -- if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then - cd pyoptsparse/pySNOPT/source; - scp -r "$SNOPT_LOCATION/source/*" .; - cd ../../..; - fi - -- python setup.py build; -- python setup.py install; - -# for PRs, copy the cached SNOPT library into its proper place before testing -# PRs cannot access SNOPT otherwise due to encrypted SNOPT_LOCATION -- if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then - for file in $HOME/snopt*.so; do - if [[ -f $file ]]; then - mv -v $file $SNOPT_DIR; - break; - fi - done - fi - -# display summary of installed packages and their versions -- conda list; -- pip list; - -script: -- cd test; #coverage from root directory does not work. -- testflo -v --pre_announce --coverage --coverpkg pyoptsparse - -after_success: -- coveralls --rcfile=.coveragerc --output=coveralls.json; -- sed 's/\/home\/travis\/miniconda\/lib\/python'"$PY"'\/site-packages\///g' < coveralls.json > coveralls-upd.json; -- coveralls --upload=coveralls-upd.json; diff --git a/pyoptsparse/LICENSE.md b/pyoptsparse/LICENSE.md deleted file mode 100644 index 59872848c..000000000 --- a/pyoptsparse/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -# pyOptSparse - -pyOptSparse is a Python wrapper for using multiple optimization packages using the same API. -______________________________________________________________________________ - -Copyright (c) 2011 University of Toronto\ -Copyright (c) 2014 University of Michigan\ -Additional copyright (c) 2014 Gaetan K. W. Kenway, Ruben Perez, Charles A. Mader, and\ -Joaquim R. R. A. Martins\ -All rights reserved. -______________________________________________________________________________ - -pyOptSparse is licensed under the GNU Lesser General Public License (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at:\ -https://www.gnu.org/licenses/lgpl.html -______________________________________________________________________________ - -University of Michigan's Multidisciplinary Design Optimization Laboratory (MDO Lab)\ -College of Engineering, Aerospace Engineering Department\ -http://mdolab.engin.umich.edu/ -______________________________________________________________________________ diff --git a/pyoptsparse/README.md b/pyoptsparse/README.md deleted file mode 100644 index cb47dabcd..000000000 --- a/pyoptsparse/README.md +++ /dev/null @@ -1,53 +0,0 @@ -[Forked](https://github.com/mdolab/pyoptsparse) to include installation bug fixes for use with [WISDEM](https://github.com/WISDEM/WISDEM/). - -pyOptSparse - PYthon OPTimization (Sparse) Framework -==================================================== - -[![Build Status](https://travis-ci.org/OpenMDAO/pyoptsparse.svg?branch=master)](https://travis-ci.org/OpenMDAO/pyoptsparse) -[![Coverage Status](https://coveralls.io/repos/github/OpenMDAO/pyoptsparse/badge.svg?branch=master)](https://coveralls.io/github/OpenMDAO/pyoptsparse?branch=master) - -pyOptsparse is an object-oriented framework for formulating and solving nonlinear constrained optimization problems in an efficient, reusable, and portable manner. -It evolved from pyOpt through the usage of sparse matrices throughout the code. -Many optimization techniques can be used in pyOptSparse, including SNOPT, IPOPT, SLSQP, NSGA2, and more. -A visualization tool called OptView also comes packaged with pyOptSparse, which shows the optimization history through an interactive GUI. -An example output from OptView is shown below. - -![Example](doc/OptView.png) - -Documentation -------------- - -Please see the [documentation](http://mdolab.engin.umich.edu/docs/packages/pyoptsparse/doc/index.html) for installation details and API documentation. - -To locally build the documentation, enter the `doc` folder and enter `make html` in terminal. -You can then view the built documentation in the `_build` folder. - -Citation --------- - -Please cite pyOpt and the authors of the respective optimization -algorithms in any publication for which you find it useful. -For more background, theory, and figures, see the [pyOptSparse journal article](http://mdolab.engin.umich.edu/sites/default/files/pyOpt.pdf). - -Perez, R. E., Jansen, P. W., and Martins, J. R. R. A., “pyOpt: A Python-Based Object-Oriented Framework for Nonlinear -Constrained Optimization,” Structural and Multidisciplinary Optimization, Vol. 45, No. 1, January 2012, pp. 101–118. -doi:10.1007/s00158-011-0666-3. - -``` -@article{Perez2012a, - Author = {Ruben E. Perez and Peter W. Jansen and Joaquim R. R. A. Martins}, - Doi = {10.1007/s00158-011-0666-3}, - Journal = {Structural and Multidisciplinary Optimization}, - Month = {January}, - Number = {1}, - Pages = {101--118}, - Title = {{pyOpt}: A {Python}-Based Object-Oriented Framework for Nonlinear Constrained Optimization}, - Volume = {45}, - Year = {2012}, - Annote = {10.1007/s00158-011-0666-3}} -``` - -License -------- - -Copyright 2019 MDO Lab. See the LICENSE file for details. diff --git a/pyoptsparse/doc/Makefile b/pyoptsparse/doc/Makefile deleted file mode 100644 index 1a5e0c42d..000000000 --- a/pyoptsparse/doc/Makefile +++ /dev/null @@ -1,153 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pyoptsparse.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pyoptsparse.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/pyoptsparse" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pyoptsparse" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/pyoptsparse/doc/OptView.png b/pyoptsparse/doc/OptView.png deleted file mode 100644 index d8a04143b..000000000 Binary files a/pyoptsparse/doc/OptView.png and /dev/null differ diff --git a/pyoptsparse/doc/api/constraint.rst b/pyoptsparse/doc/api/constraint.rst deleted file mode 100644 index c956a3f78..000000000 --- a/pyoptsparse/doc/api/constraint.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _constraint: - -Constraint ----------- - -.. currentmodule:: pyoptsparse.pyoptsparse.pyOpt_constraint - -.. autoclass:: Constraint - :members: diff --git a/pyoptsparse/doc/api/gradient.rst b/pyoptsparse/doc/api/gradient.rst deleted file mode 100644 index af7d5ff18..000000000 --- a/pyoptsparse/doc/api/gradient.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _gradient: - -Gradient --------- - -.. currentmodule:: pyoptsparse.pyoptsparse.pyOpt_gradient - -.. autoclass:: Gradient - :members: diff --git a/pyoptsparse/doc/api/history.rst b/pyoptsparse/doc/api/history.rst deleted file mode 100644 index f2ce75caa..000000000 --- a/pyoptsparse/doc/api/history.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _history: - -History -------- - -.. currentmodule:: pyoptsparse.pyoptsparse.pyOpt_history - -.. autoclass:: History - :members: diff --git a/pyoptsparse/doc/api/optimization.rst b/pyoptsparse/doc/api/optimization.rst deleted file mode 100644 index 400736137..000000000 --- a/pyoptsparse/doc/api/optimization.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _optimization: - -Optimziation ------------- - -.. currentmodule:: pyoptsparse.pyoptsparse.pyOpt_optimization - -.. autoclass:: Optimization - :members: __init__, addVar, addVarGroup, delVar, delVarSet, addCon, addConGroup, printSparsity, getDVs, setDVs, setDVsFromHistory diff --git a/pyoptsparse/doc/api/optimizer.rst b/pyoptsparse/doc/api/optimizer.rst deleted file mode 100644 index af27c279c..000000000 --- a/pyoptsparse/doc/api/optimizer.rst +++ /dev/null @@ -1,12 +0,0 @@ -.. _optimizer: - -Optimzer --------- - -.. currentmodule:: pyoptsparse.pyoptsparse.pyOpt_optimizer - -.. autoclass:: Optimizer - :members: - -.. automodule:: pyoptsparse.pyoptsparse.pyOpt_optimizer - :members: OPT diff --git a/pyoptsparse/doc/api/variable.rst b/pyoptsparse/doc/api/variable.rst deleted file mode 100644 index 3653f22c9..000000000 --- a/pyoptsparse/doc/api/variable.rst +++ /dev/null @@ -1,9 +0,0 @@ -.. _variable: - -Variable --------- - -.. currentmodule:: pyoptsparse.pyoptsparse.pyOpt_variable - -.. autoclass:: Variable - :members: diff --git a/pyoptsparse/doc/changes.rst b/pyoptsparse/doc/changes.rst deleted file mode 100644 index 7a7ea21dd..000000000 --- a/pyoptsparse/doc/changes.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. _changes: - -Changes to pyOptSparse -====================== - -The following list summarizes some of the changes/improvements made to -pyOpt to get ``pyOptSparse``: - -* Elimination of n^2 scaling behaviour when adding large numbers of - design variables (>10,000) - -* Proper handling of all optimizers when run in parallel environment - (Only a single optimization instance is run, not nProc instances) - -* More flexible return specification of constraints - -* More flexible return specification of constraint *gradients* - -* Complete elimination of gradient indexing errors using dictionary - based returns - -* Substantial improvement of optimization script robustness through - indexing elimination - -* Automatic assembly of sparse jacobians with both dense and sparse - subblocks - -* Automatic conversion of sparse jacobian to dense for optimizers that - cannot handle sparse constraints - -* User specification of design variable scaling - -* User specificaiton of constraint scaling - -* Design variable returns in dictionary format only - -* Specification of linear constraints, dense or sparse - -* Sparse non-linear jacobians - -* New history file format. Uses naitve python shelve database - format. Much easier to retrieve optimization data after - optimization. - -* Fixed hot start bug where first call to user functions is a - gradient. It is now guaranteed, that the first call is to the - function evlaution, not the gradient. - -* Various bug fixes in SNOPT - -* Constraints can be *any* order, independent of what the individual - optimizer requires - -* Python 3.x compatibility diff --git a/pyoptsparse/doc/conf.py b/pyoptsparse/doc/conf.py deleted file mode 100644 index f2e413b9c..000000000 --- a/pyoptsparse/doc/conf.py +++ /dev/null @@ -1,250 +0,0 @@ -# -*- coding: utf-8 -*- -# -# pyOptSparse documentation build configuration file, created by -# sphinx-quickstart on Sat Dec 7 13:50:49 2013. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('../')) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode', 'numpydoc','sphinx.ext.autosummary'] -numpydoc_show_class_members = False - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'pyOptSparse' -copyright = u'2013, Gaetan Kenway' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = 'dev' -# The full version, including alpha/beta/rc tags. -release = 'dev' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme_path = ['themes'] -html_theme = 'mdolab_theme' - -html_static_path = ['_static'] - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'pyOptSparsedoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'pyOptSparse.tex', u'pyOptSparse Documentation', - u'Gaetan Kenway', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'pyoptsparse', u'pyOptSparse Documentation', - [u'Gaetan Kenway'], 1) -] - -# If true, show URL addresses after external links. -#man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------------ - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ('index', 'pyOptSparse', u'pyOptSparse Documentation', - u'Gaetan Kenway', 'pyOptSparse', 'One line description of project.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -#texinfo_appendices = [] - -# If false, no module index is generated. -#texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {}#'http://docs.python.org/': None} diff --git a/pyoptsparse/doc/guide.rst b/pyoptsparse/doc/guide.rst deleted file mode 100644 index 44551ac41..000000000 --- a/pyoptsparse/doc/guide.rst +++ /dev/null @@ -1,215 +0,0 @@ -.. _guide: - -Guide ------ - -``pyOptSparse`` is designed to solve general, constrained nonlinear -optimization problems of the form:: - - min f(x) w.r.t. x - - s.t. g_j_L <= g_j(x) <= g_j_U, j = 1, ..., m - x_i_L <= x_i <= x_i_U, i = 1, ..., n - -where: - -``x`` is the vector of ``n`` design variables -``f(x)`` is a nonlinear function -``g(x)`` is a set of ``m`` nonlinear functions - -Equality constraints are specified using the same upper and lower -bounds for the constraint. ie. g_j_L = g_j_U. The ordering of the -constraints is arbitrary; ``pyOptSparse`` reorders the problem -automatically depending on the requirements of each individual -optimizer. - -The optimization class is created using the following call:: - - >>> optProb = Optimization('name', objFun) - -The general template of the objective function is as follows:: - - def obj_fun(xdict): - funcs = {} - funcs['obj'] = function(x) - funcs['con_name'] = function(x) - fail = False # Or True if an analysis failed - - return funcs, fail - -where: - - * ``funcs`` is the dictionary of constraints and objective value(s) - - * ``fail`` is a Boolean. False for successful evaluation and True for unsuccessful - -If the Optimization problem is unconstrained, ``funcs`` will contain only the objective key(s). - -Design Variables -++++++++++++++++ - -The simplest way to add a single continuous variable with no bounds -(side constraints) and initial value of 0.0 is:: - - >>> optProb.addVar('var_name') - -This will result in a scalar variable included in the ``x`` dictionary -call to ``obj_fun`` which can be accessed by doing:: - - >>> x['var_name'] - -A more complex example will include lower bounds, upper bounds and a -non-zero initial value:: - - >>> optProb.addVar('var_name',lower=-10, upper=5, value=-2) - -The ``lower`` or ``upper`` keywords may be specified as ``None`` to -signify there is no bound on the variable. - -Finally, an additional keyword argument ``scale`` can be specified -which will perform an internal design variable scaling. The ``scale`` -keyword will result in the following:: - - x_optimizer = x_user * scale - -The purpose of the scale factor is ensure that design variables of -widely different magnitudes can be used in the same optimization. Is -it desirable to have the magnitude of all variables within an order of -magnitude or two of each other. - -The ``addVarGroup`` call is similar to ``addVar`` except that it adds -a group of 1 or more variables. These variables are then returned as a -numpy array within the x-dictionary. For example, to add 10 variables -with no lower bound, and a scale factor of 0.1:: - - >>> optProb.addVarGroup('con_group', 10, upper=2.5, scale=0.1) - - -Constraints -+++++++++++ - -The simplest way to add a single constraint with no bounds (ie not a -very useful constraint!) is:: - - >>> optProb.addCon('not_a_real_constraint') - -To include bounds on the constraints, use the ``lower`` and ``upper`` -keyword arguments. If ``lower`` and ``upper`` are the same, it will be -treated as an equality constraint:: - - >>> optProb.addCon('inequality_constraint', upper=10) - >>> optProb.addCOn('equality_constraint', lower=5, upper=5) - -Like design variables, it is often necessary to scale constraints such -that all constraint values are approximately the same order of -magnitude. This can be specified using the ``scale`` keyword:: - - >>> optProb.addCon('scaled_constraint', upper=10000, scale=1.0/10000) - -Even if the ``scale`` keyword is given, the ``lower`` and ``upper`` -bounds are given in their un-scaled form. Internally, ``pyOptSparse`` -will use the scaling factor to produce the following constraint:: - - con_optimizer = con_user * scale - -In the example above, the constraint values are divided by 10000, -which results in a upper bound (that the optimizer sees) of 1.0. - -Constraints may also be flagged as liner using the ``linear=True`` -keyword option. Some optimizers can perform special treatment on -linear constraint, often ensuring that they are always satisfied -exactly on every function call (SNOPT for example). Linear constraints -also require the use of the ``wrt`` and ``jac`` keyword -arguments. These are explained below. - -One of the major goals of ``pyOptSparse`` is to enable the use of -sparse constraint jacobians. (Hence the 'Sparse` in the name!). -Manually computing sparsity structure of the constraint Jacobian is -tedious at best and become even more complicated as optimization -scripts are modified by adding or deleting design variables and/or -constraints. ``pyOptSParse`` is designed to greatly facilitate the -assembly of sparse constraint jacobians, alleviating the user of thus -burden. The idea is that instead of the user computing a dense matrix -representing the constraint jacobian, a ``dictionary of keys`` -approach is used which allows incrementally specifying parts of the -constraint jacobain. Consider the optimization problem given below:: - - varA (3) varB (1) varC (3) - +--------------------------------+ - conA (2) | | X | X | - ---------------------------------- - conB (2) | X | | X | - ---------------------------------- - conC (4) | X | X | X | - ---------------------------------- - conD (3) | | | X | - +--------------------------------+ - -The ``X``'s denote which parts of the jacobian have non-zero -values. ``pyOptSparse`` does not determine the sparsity structure of -the jacobian automatally, it must be specified by the user during -calls to ``addCon`` and ``addConGroup``. By way of example, the code -that generates the hypothetical optimization problem is as follows:: - - optProb.addVarGroup('varA', 3) - optProb.addVarGroup('varB', 1) - optProb.addVarGroup('varC', 3) - - optProb.addConGroup('conA', 2, upper=0.0, wrt=['varB', 'varC']) - optProb.addConGroup('conB', 2, upper=0.0, wrt=['varC', 'varA']) - optProb.addConGroup('conC', 4, upper=0.0) - optProb.addConGroup('conD', 3, upper=0.0, wrt=['varC']) - -Note that the order of the ``wrt`` (which stands for with-respect-to) -is not significant. Furthermore, if the ``wrt`` argument is omitted -altogether, ``pyOptSparse`` assumes that the constraint is dense. - -Using the ``wrt`` keyword allows the user to determine the overall -sparsity structure of the constraint jacobian. However, we have -currently assumed that each of the blocks with an ``X`` in is a dense -sub-block. ``pyOptSparse`` allows each of the *sub-blocks* to itself -be sparse. ``pyOptSparse`` requires that this sparsity structure to be -specified when the constraint is added. This information is supplied -through the ``jac`` keyword argument. Lets say, that the (conD, varC) -block of the jacobian is actually a sparse and linear. By way of -example, the call instead may be as follows:: - - jac = sparse.lil_matrix((3,3)) - jac[0,0] = 1.0 - jac[1,1] = 4.0 - jac[2,2] = 5.0 - - optProb.addConGroup('conD', 3, upper=0.0, wrt=['varC'], linear=True, jac={'varC':jac}) - -We have created a linked list sparse matrix using -``scipy.sparse``. Any scipy sparse matrix format can be accepted. We -have then provided this constraint jacobian using the ``jac=`` keyword -argument. This argument is a dictionary, and the keys must match the -design variable sets given in the ``wrt`` to keyword. Essentially what -we have done is specified the which blocks of the constraint rows are -non-zero, and provided the sparsity structure of ones that are sparse. - -For linear constraints the values in ``jac`` are meaningful: They must -be the actual linear constraint jacobian values (which do not -change). For non-linear constraints, on the sparsity structure -(non-zero pattern) is significant. The values themselves will be -determined by a call the sens() function. - -Also note, that the ``wrt`` and ``jac`` keyword arguments are only -supported when user-supplied sensitivity is used. If one used the -automatic gradient in ``pyOptSparse`` the constraint jacobian will -necessarily be dense. - -Objectives -++++++++++ - -Each optimization will require at least one objective to be -added. This is accomplished using a the call:: - - otpProb.addObj('obj') - -What this does is tell ``pyOptSparse`` that the key ``obj`` in the -function returns will be taken as the objective. For optimizers that -can do multi-objective optimization, (NSGA2 for example) multiple -objectives can be added. Optimizers that can only handle one objective -enforce that only a single objective is added to the optimization description. diff --git a/pyoptsparse/doc/index.rst b/pyoptsparse/doc/index.rst deleted file mode 100644 index 787254ab1..000000000 --- a/pyoptsparse/doc/index.rst +++ /dev/null @@ -1,26 +0,0 @@ -.. pyOptSparse documentation master file, created by - sphinx-quickstart on Sat Dec 7 13:50:49 2013. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -.. _pyoptsparse: - -=========== -pyOptSparse -=========== - -PYthon OPTimization (Sparse) Framework - -`pyOptSparseSparse` is a replacement for pyOpt. - -.. toctree:: - :maxdepth: 2 - - introduction - changes - install - tutorial - guide - optimizers - reference - postprocessing diff --git a/pyoptsparse/doc/install.rst b/pyoptsparse/doc/install.rst deleted file mode 100644 index 2415b4a52..000000000 --- a/pyoptsparse/doc/install.rst +++ /dev/null @@ -1,80 +0,0 @@ -.. _install: - -Installation -============ - -Requirements ------------- -pyOpt has the following dependencies: - -* Python 2.7+ (Python 3.2+) -* Numpy 1.0+ -* Swig 1.3+ -* c/FORTRAN compiler (compatible with f2py) -* mpi4py - -Notes: - -* In Windows MinGW is recommended if c/FORTRAN compilers are not available -* In Linux, the python header files (python-dev) are also required. -* Compatibility on Windows 64bit has not been tested - -Building --------- - -The recommended approach to using pyOptSparse is to install -inplace. This does not require root access. From the ``pyoptsparse`` -directory run:: - - >>> python setup.py build_ext --inplace - -To use pyOptSparse in this case, the user should add the path of the -diretory containing ``pyoptsparse`` to the user's ``PYTHONPATH`` -enviromental variable. For example, if the pyoptsparse directory is -located at:: - - /home/user/hg/pyoptsparse - -The required line in the .bashrc file would be:: - - export PYTHONPATH=$PYTHONPATH:/home/user/hg/ - -To install the ``pyOptSparse`` package in a folder on the Python search path -(usually in a python site-packages or dist-packages folder) run: - ->>> python setup.py install --user - -This will install the package to ``~/.local`` which is typically found -automatically by Python. If a system wide install is desired the -command to run would be (requiring root access) - ->>> sudo python setup.py install - -SNOPT --------- -SNOPT is available for purchase `here -`_. Upon purchase, you should receive a zip file. Within the zip file, there is a folder called "src". To use SNOPT with pyoptsparse, paste all files from "src" except snopth.f into pyoptsparse/pySNOPT/source . - -Notes: - - * You may want to uninstall any previous version of pyOpt before installing a new - version, as there may be conflicts. - * Some optimizers are licensed and their sources are not included with this distribution. - To use them, please request their sources from the authors as indicated in the optimizer - LICENSE files, and place them in their respective source folders before installing the package. - * In Windows, if MinGW is used make sure to install for it the C, C++, and Fortran compilers and run: - - >>> python setup.py install --compiler=mingw32 - - * By default pyOpt will attempt to use compilers available on the system. To get a list of - available compilers and their corresponding flag on a specific system use: - - >>> python setup.py build --help-fcompiler - - * To see a list of all available ``setup.py`` options for building run - - >>> python setup.py build --help - - * In macOS, you may need to force an update of gcc using ‘brew uninstall gcc’ followed by a fresh - installation of gcc using ‘brew install gcc’ as ‘brew upgrade gcc’ can be insufficient if you - have recently updated your macOS version. diff --git a/pyoptsparse/doc/introduction.rst b/pyoptsparse/doc/introduction.rst deleted file mode 100644 index 3cbdf303b..000000000 --- a/pyoptsparse/doc/introduction.rst +++ /dev/null @@ -1,36 +0,0 @@ -.. _introduction: - -Introduction -============ - -``pyOptSparse`` is fairly extensive modification to the original pyOpt -framework originally written by Dr. Ruben E. Perez and -Peter W. Jansen. It is not backwards compatible with pyOpt and thus -optimization scripts will need to be modified to use ``pyOptSparse``. - -The original goal of pyOpt was to create an object-oriented -framework for formulating and solving nonlinear constrained -optimization problems. This goal remains the same with ``pyOptSparse``. - -From the pyOpt README some of the main pyOpt features are: - -* Object-oriented development maintains independence between - the optimization problem formulation and its solution by - different optimizers - -* Allows for easy integration of gradient-based, gradient-free, - and population-based optimization algorithms - -* Interfaces both open source as well as industrial optimizers - -* Ease the work required to do nested optimization and provides - automated solution refinement - -* On parallel systems it enables the use of optimizers when - running in a mpi parallel environment, allows for evaluation - of gradients in parallel, and can distribute function - evaluations for gradient-free optimizers - -* Optimization solution histories can be stored during the - optimization process. A partial history can also be used - to warm-restart the optimization diff --git a/pyoptsparse/doc/optimizers.rst b/pyoptsparse/doc/optimizers.rst deleted file mode 100644 index fb5ea1354..000000000 --- a/pyoptsparse/doc/optimizers.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. _optimizers: - -Optimizers -========== - -.. toctree:: - :maxdepth: 2 - - optimizers/pysnopt - optimizers/pyipopt - optimizers/pyslsqp - optimizers/pynlpql - optimizers/pyfsqp - optimizers/pynsga2 - optimizers/pypsqp - diff --git a/pyoptsparse/doc/optimizers/pyfsqp.rst b/pyoptsparse/doc/optimizers/pyfsqp.rst deleted file mode 100644 index e30d0aa7e..000000000 --- a/pyoptsparse/doc/optimizers/pyfsqp.rst +++ /dev/null @@ -1,16 +0,0 @@ -.. _fsqp: - -FSQP ----- -This code implements an SQP approach that is modified to generate -feasible iterates. In addition to handling general single objective -constrained nonlinear optimization problems, the code is also capable -of handling multiple competing linear and nonlinear objective -functions (minimax), linear and nonlinear inequality constraints, as -well as linear and nonlinear equality constraints - -.. currentmodule:: pyoptsparse.pyoptsparse.pyFSQP.pyFSQP - -.. autoclass:: FSQP - :members: __call__ - diff --git a/pyoptsparse/doc/optimizers/pyipopt.rst b/pyoptsparse/doc/optimizers/pyipopt.rst deleted file mode 100644 index 85d2bea24..000000000 --- a/pyoptsparse/doc/optimizers/pyipopt.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. _ipopt: - -IPOPT ------ - -Install instructions for ``pyIPOPT``. - -#. Download ``IPopt-3.11.7.tar.gz`` and put in the ``/pyoptsparse/pyoptsparse/pyIPOPT`` directory - -#. Untar - -#. Rename the directory from ``Ipopt-x.x.x`` to ``Ipopt`` - -#. Copy ``ma27ad.f`` from the ``pyOptSparse`` bitbucket page into the ``Ipopt/ThirdParty/HSLold/`` directory - -#. Go to:: - - Ipopt/ThirdParty/Blas/ - - and run:: - - sh ./get.Blas - - This will download a blas copy and ``Ipopt`` will use that. - -#. Go to:: - - Ipopt/ThirdParty/Lapack/ - - and run:: - - sh ./get.Lapack - -#. Run in the root directory - :: - $ ./configure --disable-linear-solver-loader - -#. Now make - :: - $ make install - -#. You must add the ``lib`` directory ``Ipopt`` to your - ``LD_LIBRARY_PATH`` variable for things to work right - :: - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/hg/pyoptsparse/pyoptsparse/pyIPOPT/Ipopt/lib - -#. Now the pyOptSparse builder (run from the root directory) should take care of the rest. - - -.. currentmodule:: pyoptsparse.pyoptsparse.pyIPOPT.pyIPOPT - -.. autoclass:: IPOPT - :members: __call__ - diff --git a/pyoptsparse/doc/optimizers/pynlpql.rst b/pyoptsparse/doc/optimizers/pynlpql.rst deleted file mode 100644 index 14e8eb7fe..000000000 --- a/pyoptsparse/doc/optimizers/pynlpql.rst +++ /dev/null @@ -1,19 +0,0 @@ -.. _nlpql: - -NLPQL ------ - -NLPQL is a sequential quadratic programming (SQP) method which solves -problems with smooth continuously differentiable objective function -and constraints. The algorithm uses a quadratic approximation of the -Lagrangian function and a linearization of the constraints. To -generate a search direction a quadratic subproblem is formulated and -solved. The line search can be performed with respect to two -alternative merit functions, and the Hessian approximation is updated -by a modified BFGS formula. - -.. currentmodule:: pyoptsparse.pyoptsparse.pyNLPQL.pyNLPQL - -.. autoclass:: NLPQL - :members: __call__ - diff --git a/pyoptsparse/doc/optimizers/pynsga2.rst b/pyoptsparse/doc/optimizers/pynsga2.rst deleted file mode 100644 index 60fe0de47..000000000 --- a/pyoptsparse/doc/optimizers/pynsga2.rst +++ /dev/null @@ -1,21 +0,0 @@ -.. _nsga2: - -NSGA2 ------ - -This optimizer is a non-dominating sorting genetic algorithm that -solves non-convex and non-smooth single and multiobjective -optimization problems. The algorithm attempts to perform global -optimization, while enforcing constraints using a tournament -selection-based strategy - -.. warning:: Currently, the Python wrapper currently does catch - exceptions. If there is **any** error in the user-supplied function, - you will get a seg-fault and no idea where it happened. Please make - sure the objective is without errors before trying to nsga2. - -.. currentmodule:: pyoptsparse.pyoptsparse.pyNSGA2.pyNSGA2 - -.. autoclass:: NSGA2 - :members: __call__ - diff --git a/pyoptsparse/doc/optimizers/pypsqp.rst b/pyoptsparse/doc/optimizers/pypsqp.rst deleted file mode 100644 index dba22ed31..000000000 --- a/pyoptsparse/doc/optimizers/pypsqp.rst +++ /dev/null @@ -1,12 +0,0 @@ -.. _psqp: - -PSQP ----- -This optimizer implements a sequential quadratic programming method -with a BFGS variable metric update - -.. currentmodule:: pyoptsparse.pyoptsparse.pyPSQP.pyPSQP - -.. autoclass:: PSQP - :members: __call__ - diff --git a/pyoptsparse/doc/optimizers/pyslsqp.rst b/pyoptsparse/doc/optimizers/pyslsqp.rst deleted file mode 100644 index 2e2f33d9e..000000000 --- a/pyoptsparse/doc/optimizers/pyslsqp.rst +++ /dev/null @@ -1,15 +0,0 @@ -.. _slsqp: - -SLSQP ------ -SLSQP optimizer is a sequential least squares programming algorithm -which uses the Han–Powell quasi–Newton method with a BFGS update of -the B–matrix and an L1–test function in the step–length algorithm. The -optimizer uses a slightly modified version of Lawson and Hanson’s NNLS -nonlinear least-squares solver. - -.. currentmodule:: pyoptsparse.pyoptsparse.pySLSQP.pySLSQP - -.. autoclass:: SLSQP - :members: __call__ - diff --git a/pyoptsparse/doc/optimizers/pysnopt.rst b/pyoptsparse/doc/optimizers/pysnopt.rst deleted file mode 100644 index 90d6b1ec2..000000000 --- a/pyoptsparse/doc/optimizers/pysnopt.rst +++ /dev/null @@ -1,18 +0,0 @@ -.. _snopt: - -SNOPT ------ -SNOPT is a sparse nonlinear optimizer that is particularly useful for -solving large-scale constrained problems with smooth objective -functions and constraints. The algorithm consists of a sequential -quadratic programming (SQP) algorithm that uses a smooth augmented -Lagrangian merit function, while making explicit provision for -infeasibility in the original problem and in the quadratic programming -subproblems. The Hessian of the Lagrangian is approximated using a -limited-memory quasi-Newton method. - -.. currentmodule:: pyoptsparse.pyoptsparse.pySNOPT.pySNOPT - -.. autoclass:: SNOPT - :members: __call__ - diff --git a/pyoptsparse/doc/postprocessing.rst b/pyoptsparse/doc/postprocessing.rst deleted file mode 100644 index 7f37d33f9..000000000 --- a/pyoptsparse/doc/postprocessing.rst +++ /dev/null @@ -1,147 +0,0 @@ -.. _postprocessing: - -Postprocessing -============== - -``OptView`` is designed to quickly and interactively visualize optimization histories. - -Requirements ------------- - -``OptView`` has the following dependency tree:: - - matplotlib (OptView) - \-backends - | \-backend_tkagg - | \-FigureCanvasTkAgg (OptView) - | \-NavigationToolbar2TkAgg (OptView) - \-pyplot (OptView) - mpl_toolkits - \-axes_grid1 - | \-host_subplot (OptView) - \-axisartist (OptView) - numpy (OptView) - -If you are successfully running ``pyOptSparse``, these packages are most likely -already installed. - -Although not necessary for most usage, the ``dill`` package is needed -if you wish to save an editable version of the graph produced in ``OptView``. -``dill`` can be installed via ``pip`` in a terminal using:: - - pip install dill - -``view_saved_figure.py`` can be used to reformat and view the saved figure. - -Usage ------ - -``OptView`` can be run via terminal as:: - - python OptView.py --histFile --outputDirectory - -Here, ``histFile`` is the name of the history file to be examined -(default is 'opt_hist.hst'). -``outputDirectory`` is the name of the desired output directory for -saved images (default is within the same folder as ``OptView.py``.) - -``OptView`` can also be ran from any directory by adding an alias line -to your ``.bashrc`` file such as:: - - alias OptView='python ~/hg/pyoptsparse/postprocessing/OptView.py - -Through this usage, ``OptView`` can be called from any directory as:: - - OptView histFile --outputDirectory - -Additionally, you can open multiple history files in the same ``OptView`` instance -by calling them via the command line:: - - OptView histFile1 histFile2 histFile3 --outputDirectory - -Each file's contents will be loaded into ``OptView`` with a flag appended to the end -of each variable or function name corresponding to the history file. The first one -listed will have '_A' added to the name, the second will have '_B' added, etc. -There is currently no limit to the number of history files than can be loaded. - -Features --------- - -``OptView`` has many options and features, including: - - * plotting multiple variables on a single plot - * producing stacked plots - * live searchable variable names - * hovering plot labels - * saving the figure to an image or pickling it for later formatting - * refreshing the optimization history on the fly - -Although some of these are self-explanatory, the layout and usage of ``OptView`` -will be explained below. - -GUI Layout -++++++++++ - -The window is divided into two sections. -The top is the canvas where the figure and graphs will be produced, -while the bottom grayed section contains user-selectable options. -Here, we will focus on the user options. - -The selectable variables are contained on the lefthand -side of the options panel in scrollable listboxes. -You can select multiple items from the listboxes using the normal selection -operators such as control and shift. -If a selected variable is an array, a third listbox should appear on the -righthand side of the options panel, allowing you to select specific -subvariables within the single array variable. - -There are three main options when selecting how to produce the graph(s): - - * Shared axes - all selected variables are plotted on a single pair of axes - * Multiple axes - each selected variable gets its own y-axis while all selected data shares an x-axis - * Stacked plots - each variable gets its own individual plot and the set is stacked vertically - -Most checkbox options should play well with any of these three main options, -though there are known issues with using the 'multiple axes' -option and delta values or for displaying arrays. - -There are seven checkbox options: - - * Absolute delta values - displays the absolute difference between one iteration's value and the previous - * Log scale - sets the y-axis as a log scale - * Min/max for arrays - only shows the minimum and maximum value of a variable for each iteration - * Show all for arrays - plots all variables within an array - * Show legend - reveals the legend for the plotted data - * Show bounds - shows the variable bounds as dashed lines - * Show 'major' iterations - a heuristic filter to remove the line search iterations from the plotting results; especially useful for SNOPT output - -Additionally, four buttons allow control of the plot: - - * Refresh history - reloads the history file; used if checking on an optimization run on the fly - * Save all figures - saves .png versions of a basic plot for each variable in the history file - * Save figure - saves a .png and .pickle version of the current plot (the .pickle version can be reformatted afterwards) - * Quit - exits the program - -Lastly, there some miscellaneous features: - - * A search box to cull the selectable variables - * A font size slider to control the text size on the plot - * Hoverable tooltips when the cursor is on a plot line - * A variable called `actual_iteration_number` that gives a translation between history file iteration number and run file iteration number. This is especially useful for debugging specific steps of an optimization or comparing values across different histories. - -More features are being developed on an as-needed basis. -Feel free to edit the code as you see fit and submit a pull request if you -would like to see a feature added. -Alternatively, you can submit an issue ticket to discuss possible features. - - -Parsing SNOPT Printout files ----------------------------- - -The script ``SNOPT_parse.py`` has been included in the ``postprocessing`` folder for extracting the optimality, feasibility and meric function values for each major iteration. It then generates a ``.dat`` file for use with Tecplot. - -The file can be run via terminal as:: - - python SNOPT_parse.py filename - -Here, ``filename`` is the name of the SNOPT printout file to be examined. If no filename is provided the default name ``SNOPT_print.out`` will be assumed. \ No newline at end of file diff --git a/pyoptsparse/doc/reference.rst b/pyoptsparse/doc/reference.rst deleted file mode 100644 index 907ef2b65..000000000 --- a/pyoptsparse/doc/reference.rst +++ /dev/null @@ -1,14 +0,0 @@ -.. _reference: - -pyOptSparse API Documentation -============================= - -.. toctree:: - :maxdepth: 2 - - api/optimization - api/optimizer - api/constraint - api/variable - api/gradient - api/history diff --git a/pyoptsparse/doc/themes/mdolab_theme/globaltoc.html b/pyoptsparse/doc/themes/mdolab_theme/globaltoc.html deleted file mode 100644 index 3bd8404aa..000000000 --- a/pyoptsparse/doc/themes/mdolab_theme/globaltoc.html +++ /dev/null @@ -1,3 +0,0 @@ -

Table of Contents

-{{ toctree(maxdepth=-1, titles_only=true) }} - diff --git a/pyoptsparse/doc/themes/mdolab_theme/layout.html b/pyoptsparse/doc/themes/mdolab_theme/layout.html deleted file mode 100644 index 8ee0d60f0..000000000 --- a/pyoptsparse/doc/themes/mdolab_theme/layout.html +++ /dev/null @@ -1,94 +0,0 @@ -{% extends "basic/layout.html" %} - -{# Collapsible sidebar script from default/layout.html in Sphinx #} -{% set script_files = script_files + ['_static/sidebar.js'] %} - -{# Add the google webfonts needed for the logo #} -{% block extrahead %} - -{% endblock %} - - -{% block header %} -
- {{ theme_logotext1 }}{{ theme_logotext2 }}{{ theme_logotext3 }} -
    -
  • -
  • Index
  • -
  • Modules
  • -
  • - {% block sidebarsearch %} - {% include "searchbox.html" %} - {% endblock %} -
  • -
-
-{% endblock %} - -{% block relbar1 %} - -{% endblock %} - -{# Silence the bottom relbar. #} -{% block relbar2 %}{% endblock %} - - -{%- block footer %} -
-

- {%- if edit_on_github %} - {{ edit_on_github_page_message }}   - {%- endif %} - {%- if show_source and has_source and sourcename %} - {{ _('Page Source') }} - {%- endif %}   - Back to Top

-

- {%- if show_copyright %} - {%- if hasdoc('copyright') %} - {% trans path=pathto('copyright'), copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %}
- {%- else %} - {% trans copyright=copyright|e %}© Copyright {{ copyright }}.{% endtrans %}
- {%- endif %} - {%- endif %} - {%- if show_sphinx %} - {% trans sphinx_version=sphinx_version|e %}Created using Sphinx {{ sphinx_version }}.{% endtrans %}   - {%- endif %} - {%- if last_updated %} - {% trans last_updated=last_updated|e %}Last built {{ last_updated }}.{% endtrans %}
- {%- endif %} -

-
-{%- endblock %} diff --git a/pyoptsparse/doc/themes/mdolab_theme/localtoc.html b/pyoptsparse/doc/themes/mdolab_theme/localtoc.html deleted file mode 100644 index 0a21ad004..000000000 --- a/pyoptsparse/doc/themes/mdolab_theme/localtoc.html +++ /dev/null @@ -1,3 +0,0 @@ -

Page Contents

-{{ toc }} - diff --git a/pyoptsparse/doc/themes/mdolab_theme/searchbox.html b/pyoptsparse/doc/themes/mdolab_theme/searchbox.html deleted file mode 100644 index 0d17cc149..000000000 --- a/pyoptsparse/doc/themes/mdolab_theme/searchbox.html +++ /dev/null @@ -1,7 +0,0 @@ -{%- if pagename != "search" %} -
- - - -
-{%- endif %} diff --git a/pyoptsparse/doc/themes/mdolab_theme/static/MDOLAB_text.png b/pyoptsparse/doc/themes/mdolab_theme/static/MDOLAB_text.png deleted file mode 100644 index 62dc68fc6..000000000 Binary files a/pyoptsparse/doc/themes/mdolab_theme/static/MDOLAB_text.png and /dev/null differ diff --git a/pyoptsparse/doc/themes/mdolab_theme/static/mdolab.css b/pyoptsparse/doc/themes/mdolab_theme/static/mdolab.css deleted file mode 100644 index af7ccf0bd..000000000 --- a/pyoptsparse/doc/themes/mdolab_theme/static/mdolab.css +++ /dev/null @@ -1,574 +0,0 @@ -/*! - * Bootstrap v1.4.0 - * - * Copyright 2011 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Heavily modified by Kyle Barbary for the AstroPy Project for use with Sphinx. - * Renamed, but not modified, to include in MDOLAB documentation by Gaetan Kenway - */ - -@import url("basic.css"); - -body { - background-color: #ffffff; - margin: 0; - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: 13px; - font-weight: normal; - line-height: 18px; - color: #404040; -} - -/* Hyperlinks ----------------------------------------------------------------*/ - -a { - color: #0069d6; - text-decoration: none; - line-height: inherit; - font-weight: inherit; -} - -a:hover { - color: #00438a; - text-decoration: underline; -} - -/* Typography ----------------------------------------------------------------*/ - -h1,h2,h3,h4,h5,h6 { - color: #404040; - margin: 0.7em 0 0 0; - line-height: 1.5em; -} -h1 { - font-size: 24px; - margin: 0; -} -h2 { - font-size: 21px; - line-height: 1.2em; - margin: 1em 0 0.5em 0; - border-bottom: 1px solid #404040; -} -h3 { - font-size: 18px; -} -h4 { - font-size: 16px; -} -h5 { - font-size: 14px; -} -h6 { - font-size: 13px; - text-transform: uppercase; -} - -p { - font-size: 13px; - font-weight: normal; - line-height: 18px; - margin-top: 0px; - margin-bottom: 9px; -} - -ul, ol { - margin-left: 0; - padding: 0 0 0 25px; -} -ul ul, ul ol, ol ol, ol ul { - margin-bottom: 0; -} -ul { - list-style: disc; -} -ol { - list-style: decimal; -} -li { - line-height: 18px; - color: #404040; -} -ul.unstyled { - list-style: none; - margin-left: 0; -} -dl { - margin-bottom: 18px; -} -dl dt, dl dd { - line-height: 18px; -} -dl dd { - margin-left: 9px; -} -hr { - margin: 20px 0 19px; - border: 0; - border-bottom: 1px solid #eee; -} -strong { - font-style: inherit; - font-weight: bold; -} -em { - font-style: italic; - font-weight: inherit; - line-height: inherit; -} -.muted { - color: #bfbfbf; -} - -address { - display: block; - line-height: 18px; - margin-bottom: 18px; -} -code, pre { - padding: 0 3px 2px; - font-family: Monaco, Andale Mono, Courier New, monospace; - font-size: 12px; - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; -} -tt { - font-family: Monaco, Andale Mono, Courier New, monospace; -} -code { - color: rgba(0, 0, 0, 0.75); - padding: 1px 3px; -} -pre { - display: block; - padding: 8.5px; - margin: 0 0 18px; - line-height: 18px; - font-size: 12px; - border: 1px solid #ddd; - border: 1px solid rgba(0, 0, 0, 0.12); - -webkit-border-radius: 3px; - -moz-border-radius: 3px; - border-radius: 3px; - white-space: pre; - white-space: pre-wrap; - word-wrap: break-word; -} - -img { - margin: 9px 0; -} - -/* format inline code with a rounded box */ -tt { - margin: 0 2px; - padding: 0 5px; - border: 1px solid #ddd; - border: 1px solid rgba(0, 0, 0, 0.12); - border-radius: 3px; - font-size: 0.95em; -} - -/* all code has same box background color, even in headers */ -h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt, pre, code, tt { - background-color: #f8f8f8; -} - -/* override box for links & other sphinx-specifc stuff */ -tt.xref, a tt, tt.descname, tt.descclassname { - padding: 0 1px 0 1px; - border: none; -} - -/* override box for related bar at the top of the page */ -.related tt { - border: none; - padding: 0 1px 0 1px; - background-color: transparent; - font-weight: bold; -} - -th { - background-color: #dddddd; -} - -.viewcode-back { - font-family: sans-serif; -} - -div.viewcode-block:target { - background-color: #f4debf; - border-top: 1px solid #ac9; - border-bottom: 1px solid #ac9; -} - -table.docutils { - border-spacing: 5px; - border-collapse: separate; -} - -/* Topbar --------------------------------------------------------------------*/ - -div.topbar { - height: 40px; - position: absolute; - top: 0; - left: 0; - right: 0; - z-index: 10000; - padding: 0px 10px; - background-color: #222; - background-color: #222222; - background-repeat: repeat-x; - background-image: -khtml-gradient(linear, left top, left bottom, from(#333333), to(#222222)); - background-image: -moz-linear-gradient(top, #333333, #222222); - background-image: -ms-linear-gradient(top, #333333, #222222); - background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #333333), color-stop(100%, #222222)); - background-image: -webkit-linear-gradient(top, #333333, #222222); - background-image: -o-linear-gradient(top, #333333, #222222); - background-image: linear-gradient(top, #333333, #222222); - filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0); -} - -div.topbar a.brand { - font-family: 'Source Sans Pro', sans-serif; - font-size: 26px; - color: #ffffff; - font-weight: 600; - text-decoration: none; - float: left; - display: block; - height: 32px; - padding: 8px 12px 0px 45px; - margin-left: -10px; - background: transparent url("small_0.png") no-repeat 10px 4px; -} - -#logotext1 { -} - -#logotext2 { - font-weight:200; - color: #ff5000; -} -#logotext3 { - font-weight:200; -} - -div.topbar .brand:hover, div.topbar ul li a.homelink:hover { - background-color: #333; - background-color: rgba(255, 255, 255, 0.05); -} - -div.topbar ul { - font-size: 110%; - list-style: none; - margin: 0; - padding: 0 0 0 10px; - float: right; - color: #bfbfbf; - text-align: center; - text-decoration: none; - height: 100%; -} -div.topbar ul li { - float: left; - display: inline; - height: 30px; - margin: 5px; - padding: 0px; -} - -div.topbar ul li a { - color: #bfbfbf; - text-decoration: none; - padding: 5px; - display: block; - height: auto; - text-align: center; - vertical-align: middle; - border-radius: 4px; -} - -div.topbar ul li a:hover { - color: #ffffff; - text-decoration: none; -} - -div.topbar ul li a.homelink { - width: 112px; - display: block; - height: 20px; - padding: 5px 0px; - background: transparent url("MDOLAB_text.png") no-repeat 10px 5px; -} - -div.topbar form { - text-align: left; - margin: 0 0 0 5px; - position: relative; - filter: alpha(opacity=100); - -khtml-opacity: 1; - -moz-opacity: 1; - opacity: 1; -} - -div.topbar input { - background-color: #444; - background-color: rgba(255, 255, 255, 0.3); - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; - font-size: normal; - font-weight: 13px; - line-height: 1; - padding: 4px 9px; - color: #ffffff; - color: rgba(255, 255, 255, 0.75); - border: 1px solid #111; - -webkit-border-radius: 4px; - -moz-border-radius: 4px; - border-radius: 4px; - -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); - -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); - box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0px rgba(255, 255, 255, 0.25); - -webkit-transition: none; - -moz-transition: none; - -ms-transition: none; - -o-transition: none; - transition: none; -} -div.topbar input:-moz-placeholder { - color: #e6e6e6; -} -div.topbar input::-webkit-input-placeholder { - color: #e6e6e6; -} -div.topbar input:hover { - background-color: #bfbfbf; - background-color: rgba(255, 255, 255, 0.5); - color: #ffffff; -} -div.topbar input:focus, div.topbar input.focused { - outline: 0; - background-color: #ffffff; - color: #404040; - text-shadow: 0 1px 0 #ffffff; - border: 0; - padding: 5px 10px; - -webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - -moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); - box-shadow: 0 0 3px rgba(0, 0, 0, 0.15); -} - - -/* Relation bar (breadcrumbs, prev, next) ------------------------------------*/ - -div.related { - height: 21px; - width: auto; - margin: 0 10px; - position: absolute; - top: 42px; - clear: both; - left: 0; - right: 0; - z-index: 10000; - font-size: 100%; - vertical-align: middle; - background-color: #fff; - border-bottom: 1px solid #bbb; -} -div.related ul { - padding: 0; - margin: 0; -} - - -/* Footer --------------------------------------------------------------------*/ - -footer { - display: block; - margin: 10px 10px 0px; - padding: 10px 0 0 0; - border-top: 1px solid #bbb; -} -.pull-right { - float: right; - width: 30em; - text-align: right; -} - - -/* Sphinx sidebar ------------------------------------------------------------*/ - -div.sphinxsidebar { - font-size: inherit; - border-radius: 3px; - background-color: #eee; - border: 1px solid #bbb; -} - -div.sphinxsidebarwrapper { - padding: 0px 0px 0px 5px; -} - -div.sphinxsidebar h3 { - font-family: 'Trebuchet MS', sans-serif; - font-size: 1.4em; - font-weight: normal; - margin: 5px 0px 0px 5px; - padding: 0; - line-height: 1.6em; -} -div.sphinxsidebar h4 { - font-family: 'Trebuchet MS', sans-serif; - font-size: 1.3em; - font-weight: normal; - margin: 5px 0 0 0; - padding: 0; -} -div.sphinxsidebar p { -} -div.sphinxsidebar p.topless { - margin: 5px 10px 10px 10px; -} -div.sphinxsidebar ul { - margin: 0px 0px 0px 5px; - padding: 0; -} - -div.sphinxsidebar ul ul { - margin-left: 15px; - list-style-type: disc; -} - -/* If showing the global TOC (toctree), - color the current page differently */ -div.sphinxsidebar a.current { - color: #404040; -} -div.sphinxsidebar a.current:hover { - color: #404040; -} - - -/* document, documentwrapper, body, bodywrapper ----------------------------- */ - -div.document { - margin-top: 72px; - margin-left: 10px; - margin-right: 10px; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.body { - background-color: #ffffff; - padding: 0 0 0px 20px; -} - -div.bodywrapper { - margin: 0 0 0 230px; - max-width: 55em; -} - - -/* Header links ------------------------------------------------------------- */ - -a.headerlink { - font-size: 0.8em; - padding: 0 4px 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - background-color: #0069d6; - color: white; - text-docoration: none; -} - - -/* Admonitions and warnings ------------------------------------------------- */ - -/* Shared by admonitions and warnings */ -div.admonition, -div.warning { - padding: 0px; - border-radius: 3px; - -moz-border-radius: 3px; - -webkit-border-radius: 3px; -} -div.admonition p, -div.warning p { - margin: 0.5em 1em 0.5em 1em; - padding: 0; -} -div.admonition pre, -div.warning pre { - margin: 0.4em 1em 0.4em 1em; -} -div.admonition p.admonition-title, -div.warning p.admonition-title { - margin: 0; - padding: 0.1em 0 0.1em 0.5em; - color: white; - font-weight: bold; - font-size: 1.1em; -} -div.admonition ul, div.admonition ol, -div.warning ul, div.warning ol { - margin: 0.1em 0.5em 0.5em 3em; - padding: 0; -} - -/* Admonitions only */ -div.admonition { - border: 1px solid #609060; - background-color: #e9ffe9; -} -div.admonition p.admonition-title { - background-color: #70A070; -} - -/* Warnings only */ -div.warning { - border: 1px solid #900000; - background-color: #ffe9e9; -} -div.warning p.admonition-title { - background-color: #b04040; -} - - -/* Figures ------------------------------------------------------------------ */ - -.figure.align-center { - clear: none; -} - -/* This is a div for containing multiple figures side-by-side, for use with - * .. container:: figures */ -div.figures { - border: 1px solid #CCCCCC; - background-color: #F8F8F8; - margin: 1em; - text-align: center; -} - -div.figures .figure { - clear: none; - float: none; - display: inline-block; - border: none; - margin-left: 0.5em; - margin-right: 0.5em; -} - -.field-list th { - white-space: nowrap; -} diff --git a/pyoptsparse/doc/themes/mdolab_theme/static/sidebar.js b/pyoptsparse/doc/themes/mdolab_theme/static/sidebar.js deleted file mode 100644 index 15d87f3ac..000000000 --- a/pyoptsparse/doc/themes/mdolab_theme/static/sidebar.js +++ /dev/null @@ -1,160 +0,0 @@ -/* - * sidebar.js - * ~~~~~~~~~~ - * - * This script makes the Sphinx sidebar collapsible. - * - * .sphinxsidebar contains .sphinxsidebarwrapper. This script adds - * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton - * used to collapse and expand the sidebar. - * - * When the sidebar is collapsed the .sphinxsidebarwrapper is hidden - * and the width of the sidebar and the margin-left of the document - * are decreased. When the sidebar is expanded the opposite happens. - * This script saves a per-browser/per-session cookie used to - * remember the position of the sidebar among the pages. - * Once the browser is closed the cookie is deleted and the position - * reset to the default (expanded). - * - * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -$(function() { - // global elements used by the functions. - // the 'sidebarbutton' element is defined as global after its - // creation, in the add_sidebar_button function - var bodywrapper = $('.bodywrapper'); - var sidebar = $('.sphinxsidebar'); - var sidebarwrapper = $('.sphinxsidebarwrapper'); - - // for some reason, the document has no sidebar; do not run into errors - if (!sidebar.length) return; - - // original margin-left of the bodywrapper and width of the sidebar - // with the sidebar expanded - var bw_margin_expanded = bodywrapper.css('margin-left'); - var ssb_width_expanded = sidebar.width(); - - // margin-left of the bodywrapper and width of the sidebar - // with the sidebar collapsed - var bw_margin_collapsed = 12; - var ssb_width_collapsed = 12; - - // custom colors - var dark_color = '#404040'; - var light_color = '#505050'; - - function sidebar_is_collapsed() { - return sidebarwrapper.is(':not(:visible)'); - } - - function toggle_sidebar() { - if (sidebar_is_collapsed()) - expand_sidebar(); - else - collapse_sidebar(); - } - - function collapse_sidebar() { - sidebarwrapper.hide(); - sidebar.css('width', ssb_width_collapsed); - bodywrapper.css('margin-left', bw_margin_collapsed); - sidebarbutton.css({ - 'margin-left': '-1px', - 'height': bodywrapper.height(), - 'border-radius': '3px' - }); - sidebarbutton.find('span').text('»'); - sidebarbutton.attr('title', _('Expand sidebar')); - document.cookie = 'sidebar=collapsed'; - } - - function expand_sidebar() { - bodywrapper.css('margin-left', bw_margin_expanded); - sidebar.css('width', ssb_width_expanded); - sidebarwrapper.show(); - sidebarbutton.css({ - 'margin-left': ssb_width_expanded - 12, - 'height': bodywrapper.height(), - 'border-radius': '0px 3px 3px 0px' - }); - sidebarbutton.find('span').text('«'); - sidebarbutton.attr('title', _('Collapse sidebar')); - document.cookie = 'sidebar=expanded'; - } - - function add_sidebar_button() { - sidebarwrapper.css({ - 'float': 'left', - 'margin-right': '0', - 'width': ssb_width_expanded - 18 - }); - // create the button - sidebar.append('
«
'); - var sidebarbutton = $('#sidebarbutton'); - - // find the height of the viewport to center the '<<' in the page - var viewport_height; - if (window.innerHeight) - viewport_height = window.innerHeight; - else - viewport_height = $(window).height(); - var sidebar_offset = sidebar.offset().top; - var sidebar_height = Math.max(bodywrapper.height(), sidebar.height()); - sidebarbutton.find('span').css({ - 'font-family': '"Lucida Grande",Arial,sans-serif', - 'display': 'block', - 'top': Math.min(viewport_height/2, sidebar_height/2 + sidebar_offset) - 10, - 'width': 12, - 'position': 'fixed', - 'text-align': 'center' - }); - - sidebarbutton.click(toggle_sidebar); - sidebarbutton.attr('title', _('Collapse sidebar')); - sidebarbutton.css({ - 'color': '#FFFFFF', - 'background-color': light_color, - 'border': '1px solid ' + light_color, - 'border-radius': '0px 3px 3px 0px', - 'font-size': '1.2em', - 'cursor': 'pointer', - 'height': sidebar_height, - 'padding-top': '1px', - 'margin': '-1px', - 'margin-left': ssb_width_expanded - 12 - }); - - sidebarbutton.hover( - function () { - $(this).css('background-color', dark_color); - }, - function () { - $(this).css('background-color', light_color); - } - ); - } - - function set_position_from_cookie() { - if (!document.cookie) - return; - var items = document.cookie.split(';'); - for(var k=0; k>> import pyoptsparse - -Next we define the objective function that takes in the design -variable *dictionary* and returns a *dictionary* containing the -constraints and objective, as well as a (boolean) flag indicating if -the objective function evaluation was successful. For the TP37, the -objective function is a simple analytic function:: - - def objfunc(xdict): - x = xdict['xvars'] - funcs = {} - funcs['obj'] = -x[0]*x[1]*x[2] - conval = [0]*2 - conval[0] = x[0] + 2.*x[1] + 2.*x[2] - 72.0 - conval[1] = -x[0] - 2.*x[1] - 2.*x[2] - funcs['con'] = conval - fail = False - - return funcs, fail - -Notes: - - 1. The ``xdict`` variable is a dictionary whose keys are the names - from each ``addVar()`` and ``addVarGroup()`` call. The line:: - - x = xdict['xvars'] - - retrieves an array of length 3 which are all the variables for - this optimization. - - 2. The line:: - - conval = [0]*2 - - creates a list of length 2, which stores the numerical values of - the two constraints. The ``funcs`` dictionary return must contain - keys that match the constraint names from ``addCon`` and - ``addConGroup`` as well as the objectives from ``addObj`` calls. This - is done in the following calls:: - - funcs['obj'] = -x[0]*x[1]*x[2] - funcs['con'] = conval - -Now the optimization problem can be initialized:: - - >>> optProb = Optimization('TP037', objfunc) - -This creates an instance of the optimization class with a name and a -reference to the objective function. To complete the setup of the -optimization problem, the design variables and constraints need to be defined. - -Design variables and constraints can be added either one-by-one or as -a group. Adding variables by group is generally recommended for -related variables:: - - >>> optProb.addVarGroup('xvars', 3, 'c', lower=[0,0,0], upper=[42,42,42], value=10) - -This calls adds a group of 3 variables with name 'xvars'. The variable -bounds (side constraints) are 0 for the lower bounds, 42 for the upper -bounds. The inital values for each variable is 10.0 - -Now, we must add the constraints. Like design variables, these may be -added individually or by group. It is recommended that related -constraints are added by group where possible:: - - >>> optProb.addConGroup('con',2, lower=None, upper=0.0) - -This call adds two variables with name 'con'. There is no lower bound -for the variables and the upper bound is 0.0. - -We must also assign the the key value for the objective using the -``addObj()`` call:: - - >>> optProb.addObj('obj') - -The optimization problem can be printed to verify that it is setup correctly:: - - >>> print optProb - -To solve an optimization problem with ``pyOptSparse`` an optimizer -must be initialized. The initialization of one or more optimizers is -independent of the initialization of any number of optimization -problems. To initialize ``SLSQP``, which is an open-source, sequential -least squares programming algorithm that comes as part of the -pyOptSparse package, use:: - - >>> opt = pyoptsparse.SLSQP() - -This initializes an instance of ``SLSQP`` with the default options. The -setOption() method can be used to change any optimizer specific option, -for example the internal output flag of ``SLSQP``:: - - >>> opt.setOption('IPRINT', -1) - -Now TP37 can be solved using ``SLSQP`` and for example, ``pyOptSparse``’s automatic -finite difference for the gradients:: - - >>> sol = opt(optProb, sensType='FD') - -We can print the solution objection to view the result of the optimization:: - - >>> print sol - - TP037 - ================================================================================ - - Objective Function: objfunc - - Solution: - -------------------------------------------------------------------------------- - Total Time: 0.0256 - User Objective Time : 0.0003 - User Sensitivity Time : 0.0021 - Interface Time : 0.0226 - Opt Solver Time: 0.0007 - Calls to Objective Function : 23 - Calls to Sens Function : 9 - - Objectives: - Name Value Optimum - f 0 0 - - Variables (c - continuous, i - integer, d - discrete): - Name Type Value Lower Bound Upper Bound - xvars_0 c 24.000000 0.00e+00 4.20e+01 - xvars_1 c 12.000000 0.00e+00 4.20e+01 - xvars_2 c 12.000000 0.00e+00 4.20e+01 - - Constraints (i - inequality, e - equality): - Name Type Bounds - con i 1.00e-20 <= 0.000000 <= 0.00e+00 - con i 1.00e-20 <= 0.000000 <= 0.00e+00 - - -------------------------------------------------------------------------------- diff --git a/pyoptsparse/examples/hs015.py b/pyoptsparse/examples/hs015.py deleted file mode 100644 index 40b8bb0c1..000000000 --- a/pyoptsparse/examples/hs015.py +++ /dev/null @@ -1,79 +0,0 @@ - ## Solve test problem HS15 from the Hock & Schittkowski collection. - # - # min 100 (x2 - x1^2)^2 + (1 - x1)^2 - # s.t. x1 x2 >= 1 - # x1 + x2^2 >= 0 - # x1 <= 0.5 - # - # The standard start point (-2, 1) usually converges to the standard - # minimum at (0.5, 2.0), with final objective = 306.5. - # Sometimes the solver converges to another local minimum - # at (-0.79212, -1.26243), with final objective = 360.4. - ## -from __future__ import print_function - -import numpy -import argparse -from pyoptsparse import Optimization, OPT -parser = argparse.ArgumentParser() -parser.add_argument("--opt", help="optimizer", type=str, default='SLSQP') -parser.add_argument("--storeHistory", help="option to store history",type=int, default=0) -args = parser.parse_args() -optOptions = {} - -def objfunc(xdict): - x = xdict['xvars'] - funcs = {} - funcs['obj'] = [100*(x[1] - x[0]**2)**2 + (1-x[0])**2] - conval = numpy.zeros(2, 'D') - conval[0] = x[0]*x[1] - conval[1] = x[0] + x[1]**2 - funcs['con'] = conval - fail = False - - return funcs, fail - -def sens(xdict, funcs): - x = xdict['xvars'] - funcsSens = {} - funcsSens['obj', 'xvars'] = [2*100*(x[1]-x[0]**2)*(-2*x[0]) - 2*(1-x[0]), - 2*100*(x[1]-x[0]**2)] - funcsSens['con', 'xvars'] = [[x[1], x[0]], [1, 2*x[1]]] - - fail = False - - return funcsSens, fail - -# Optimization Object -optProb = Optimization('HS15 Constraint Problem', objfunc) - -# Design Variables -lower = [-5, -5] -upper = [0.5, 5] -value = [-2, 1] -optProb.addVarGroup('xvars', 2, lower=lower, upper=upper, value=value) - -# Constraints -lower = [1, 0] -upper = [None, None] -optProb.addConGroup('con', 2, lower=lower, upper=upper) - -# Objective -optProb.addObj('obj') - -# Check optimization problem: -print(optProb) - -# Optimizer -opt = OPT(args.opt, options=optOptions) - -# Solution -if args.storeHistory: - histFileName = '%s_hs015_Hist.hst'%(args.opt.lower()) -else: - histFileName = None -# end -sol = opt(optProb, sens=sens,storeHistory=histFileName) - -# Check Solution -print(sol) diff --git a/pyoptsparse/examples/hs015VarPlot.py b/pyoptsparse/examples/hs015VarPlot.py deleted file mode 100644 index 657c65dc9..000000000 --- a/pyoptsparse/examples/hs015VarPlot.py +++ /dev/null @@ -1,73 +0,0 @@ -import sys -import numpy as np -import matplotlib.pyplot as plt -from pyoptsparse.pyoptsparse.sqlitedict.sqlitedict import SqliteDict - -db = SqliteDict() -opts = ['ipopt', 'slsqp', 'snopt', 'fsqp', 'conmin', 'nlpqlp', 'psqp'] -for opt in opts: - fileName = '%s_hs015_Hist.hst'%opt - try: - db[opt] = SqliteDict(fileName) - except: - pass - -obj = {} -x1 = {} -x2 = {} - -for opt in db.keys(): - n = int(db[opt]['last']) - - obj[opt] = [] - x1[opt] = [] - x2[opt] = [] - for i in xrange(n): - try: - obj[opt].append(db[opt]['%d'%i]['funcs']['obj']) - x1[opt].append(db[opt]['%d'%i]['xuser']['xvars'][0]) - x2[opt].append(db[opt]['%d'%i]['xuser']['xvars'][1]) - except: - pass - -# Generate the Rosenbrock contours -delta = 0.25 -x = np.arange(-2.5, 1.5, delta) -y = np.arange(-6.5, 3.0, delta) -X, Y = np.meshgrid(x, y) - -Z = 100*(Y - X**2)**2 + (1-X)**2 -# and the constraint contours -A = X*Y -B = X + Y**2 - -# plot the contours and constraints -plt.figure(figsize=(11, 8.5)) -levels = [6000,3000,2000,1000,500,250] -CS = plt.contour(X, Y, Z,levels,colors='k') -levels = np.arange(1.0, 1.01) -CS1 = plt.contour(X,Y,A, levels,colors='g') -levels = np.arange(0.0, 0.01) -CS2 = plt.contour(X,Y,B, levels,colors='b') -plt.clabel(CS, inline=1, fontsize=10) -plt.clabel(CS1, inline=1, fontsize=10) -plt.clabel(CS2, inline=1, fontsize=10) - -# set the one sided variable -xupper=[0.5,0.5] -yupper = [-7,3.0] - -# Now plot the optimizer output -styleList=['ko-','ro-','bo-','go-','mo-','co-','ks--'] -counter=0 -for opt in db.keys(): - plt.plot(x1[opt],x2[opt],styleList[counter],label='%s'%(opt)) - counter+=1 - -# end -plt.plot(xupper,yupper,'k') -plt.legend(loc=3) -plt.xlabel('x1') -plt.ylabel('x2') -plt.title('Simple optimizer comparison') -plt.show() diff --git a/pyoptsparse/examples/hs071.py b/pyoptsparse/examples/hs071.py deleted file mode 100644 index ff59c9ede..000000000 --- a/pyoptsparse/examples/hs071.py +++ /dev/null @@ -1,63 +0,0 @@ -from __future__ import print_function - -import numpy -import argparse -from pyoptsparse import Optimization, OPT - -parser = argparse.ArgumentParser() -parser.add_argument("--opt",help="optimizer",type=str, default='SLSQP') -args = parser.parse_args() -optOptions = {} - -def objfunc(xdict): - x = xdict['xvars'] - funcs = {} - funcs['obj'] = x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2] - funcs['con1'] = x[0] * x[1] * x[2] * x[3] - funcs['con2'] = x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3] - fail = False - return funcs, fail - -def sens(xdict, funcs): - x = xdict['xvars'] - funcsSens = {} - funcsSens['obj'] = {'xvars': numpy.array( - [x[0] * x[3] + x[3] * (x[0] + x[1] + x[2]) , - x[0] * x[3], - x[0] * x[3] + 1.0, - x[0] * (x[0] + x[1] + x[2]) - ])} - jac = [[x[1]*x[2]*x[3], x[0]*x[2]*x[3], x[0]*x[1]*x[3], x[0]*x[1]*x[2]]] - funcsSens['con1'] = {'xvars': jac} - jac = [[2.0*x[0], 2.0*x[1], 2.0*x[2], 2.0*x[3]]] - funcsSens['con2'] = {'xvars': jac} - fail = False - return funcsSens, fail - -# Optimization Object -optProb = Optimization('HS071 Constraint Problem', objfunc) - -# Design Variables -x0 = [1.0, 5.0, 5.0, 1.0] -optProb.addVarGroup('xvars', 4, lower=1, upper=5, value=x0) - -# Constraints -# optProb.addCon('con1', lower=25, upper=1e19) -optProb.addCon('con1', lower=25) -# optProb.addCon('con2', lower=40, upper=40) -optProb.addCon('con2', lower=40, upper=40) - -# Objective -optProb.addObj('obj') - -# Check optimization problem: -print(optProb) - -# Optimizer -opt = OPT(args.opt, options=optOptions) - -# Solution -sol = opt(optProb, sens=sens) - -# Check Solution -print(sol) diff --git a/pyoptsparse/examples/hs071_zero_return.py b/pyoptsparse/examples/hs071_zero_return.py deleted file mode 100644 index daf93fcdf..000000000 --- a/pyoptsparse/examples/hs071_zero_return.py +++ /dev/null @@ -1,82 +0,0 @@ -from __future__ import print_function - -import numpy -import argparse -from pyoptsparse import Optimization, OPT - -parser = argparse.ArgumentParser() -parser.add_argument("--opt",help="optimizer",type=str, default='SLSQP') -args = parser.parse_args() -optOptions = {} - -def objfunc(xdict): - x0 = xdict['x0'][0] - x1 = xdict['x1'][0] - x2 = xdict['x2'][0] - x3 = xdict['x3'][0] - - funcs = {} - funcs['obj'] = x0 * x3 * (x0 + x1 + x2) + x2 - funcs['con1'] = [x0 * x1 * x2 * x3] - funcs['con2'] = [x0*x0 + x1*x1 + x2*x2 + x3*x3] - fail = False - return funcs, fail - -def sens(xdict, funcs): - - x0 = xdict['x0'][0] - x1 = xdict['x1'][0] - x2 = xdict['x2'][0] - x3 = xdict['x3'][0] - - funcsSens = {} - funcsSens['obj'] = {'x0': numpy.array([x0 * x3 + x3 * (x0 + x1 + x2)]), - 'x1': numpy.array([x0 * x3]), - 'x2': numpy.array([x0 * x3 + 1.0, 0]), - 'x3': numpy.array([x0 * (x0 + x1 + x2)])} - - funcsSens['con1'] = {'x0': numpy.array([[x1*x2*x3]]), - 'x1': numpy.array([[x0*x2*x3]]), -# 'x2': numpy.array([[x0*x1*x3, 0]]), - 'x3': numpy.array([[x0*x1*x2]])} -# ^ -# | -# If we don't return any one of the constraint jacobian blocks, -# pyoptsparse will assume it to be zero. - - funcsSens['con2'] = {'x0': numpy.array([[2.0*x0]]), - 'x1': numpy.array([[2.0*x1]]), - 'x2': numpy.array([[2.0*x2, 0]]), - 'x3': numpy.array([[2.0*x3]])} - - fail = False - return funcsSens, fail - -# Optimization Object -optProb = Optimization('HS071 Constraint Problem', objfunc) - -# Design Variables -x0 = [1.0, 5.0, 5.0, 1.0] -optProb.addVarGroup('x0', 1, lower=1, upper=5, value=x0[0]) -optProb.addVarGroup('x1', 1, lower=1, upper=5, value=x0[1]) -optProb.addVarGroup('x2', 2, lower=1, upper=5, value=x0[2]) -optProb.addVarGroup('x3', 1, lower=1, upper=5, value=x0[3]) - -# Constraints -optProb.addConGroup('con1', 1, lower=[25], upper=[1e19]) -optProb.addConGroup('con2', 1, lower=[40], upper=[40]) - -# Objective -optProb.addObj('obj') - -# Check optimization problem: -print(optProb) - -# Optimizer -opt = OPT(args.opt, options=optOptions) - -# Solution -sol = opt(optProb, sens=sens) - -# Check Solution -print(sol) diff --git a/pyoptsparse/examples/large_sparse.py b/pyoptsparse/examples/large_sparse.py deleted file mode 100644 index 93c53ebfe..000000000 --- a/pyoptsparse/examples/large_sparse.py +++ /dev/null @@ -1,76 +0,0 @@ -# This example is taken from the OpenOpt Examples website. -# http://trac.openopt.org/openopt/browser/PythonPackages/FuncDesigner/FuncDesigner/examples/nlpSparse.py -from __future__ import print_function - -import numpy -from numpy import arange -from scipy import sparse -import argparse -from pyoptsparse import Optimization, OPT - -N = 50000 - -def objfunc(xdict): - x = xdict['x']; y = xdict['y']; z = xdict['z'] - funcs = {} - funcs['obj'] = x**2 + 2*numpy.sum(y**2) + 3*numpy.sum(z) - funcs['con1'] = x + 1e-3*abs(x)**2.05 - funcs['con2'] = x**4 + numpy.sum(y) + numpy.sum(z**2) - funcs['con3'] = x + numpy.sum(z) - - return funcs, False - -def sens(xdict, funcs): - x = xdict['x']; y = xdict['y']; z = xdict['z'] - funcsSens = {} - funcsSens = {('obj', 'x') : [2*x], - ('obj', 'y') : 4*y, - ('obj', 'z') : 3*numpy.ones(2*N), - ('con1', 'x') : 2.05*x*(x*x)**0.025, - ('con2', 'x') : 4*x**3, - ('con2', 'y') : numpy.ones(N), - ('con2', 'z') : 2*z, - ('con3', 'x') : 1.0, - ('con3', 'z') : numpy.ones(2*N)} - - return funcsSens, False - -def large_sparse(optimizer='SNOPT', optOptions=None): - opt_options = {} if optOptions is None else optOptions - - # Optimization Object - optProb = Optimization('large and sparse', objfunc) - - # Design Variables - optProb.addVar('x', lower=-100, upper=150, value=0) - optProb.addVarGroup('y', N, lower=-10-arange(N), upper=arange(N), value=0) - optProb.addVarGroup('z', 2*N, upper=arange(2*N), lower=-100-arange(2*N), value=0) - # Constraints - optProb.addCon('con1', upper=100, wrt=['x']) - optProb.addCon('con2', upper=100) - optProb.addCon('con3', lower=4, wrt=['x','z']) - optProb.addConGroup('lincon', N, lower=2-3*arange(N), linear=True, - wrt=['x','y'], - jac={'x': numpy.ones((N,1)), - 'y':sparse.spdiags(numpy.ones(N), 0, N, N)}) - optProb.addObj('obj') - # Optimizer - opt = OPT(optimizer, options=opt_options) - optProb.printSparsity() - - return opt, optProb - - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument("--opt",help="optimizer",type=str, default='SNOPT') - parser.add_argument('--optOptions', type=str, help='Options for the optimizer', default="{}") - args = parser.parse_args() - exec('optOptions=%s'% args.optOptions) - - opt, optProb = large_sparse(args.opt, optOptions) - - # Solution - sol = opt(optProb, sens=sens) - print(sol) \ No newline at end of file diff --git a/pyoptsparse/examples/nsga2_multi_objective.py b/pyoptsparse/examples/nsga2_multi_objective.py deleted file mode 100644 index e9cd488ef..000000000 --- a/pyoptsparse/examples/nsga2_multi_objective.py +++ /dev/null @@ -1,30 +0,0 @@ -from pyoptsparse import Optimization, NSGA2 - -def objfunc(xdict): - x = xdict['x'] - y = xdict['y'] - - funcs = {} - funcs['obj1'] = (x - 0.0)**2 + (y - 0.0)**2 - funcs['obj2'] = (x - 1.0)**2 + (y - 1.0)**2 - - fail = False - - return funcs, fail - -# Instantiate Optimization Problem -optProb = Optimization('Rosenbrock function', objfunc) -optProb.addVar('x', 'c', value=0, lower=-600, upper=600) -optProb.addVar('y', 'c', value=0, lower=-600, upper=600) - -optProb.addObj('obj1') -optProb.addObj('obj2') - -#300 generations will find x=(0,0), 200 or less will find x=(1,1) -options = { - 'maxGen':200 -} -opt = NSGA2(options=options) -sol = opt(optProb) - -print sol diff --git a/pyoptsparse/examples/rosenbrock.py b/pyoptsparse/examples/rosenbrock.py deleted file mode 100644 index 7309439ce..000000000 --- a/pyoptsparse/examples/rosenbrock.py +++ /dev/null @@ -1,130 +0,0 @@ -from __future__ import print_function -#!/usr/bin/env python -import time, sys -from pyoptsparse import Optimization, OPT -import os, argparse -import numpy -import sys -import pdb -# import cProfile - -parser = argparse.ArgumentParser() -parser.add_argument("--sens",help="sensitivity mode",type=str, default='FD') -parser.add_argument("--constrained",help="constrained or not",type=int,default=0) -parser.add_argument("--testHist",help="test history",type=str,default="no") -parser.add_argument("--groups",help="use groups",type=int, default=0) -parser.add_argument("--sensMode",help="gradient mode",type=str, default='') -parser.add_argument("--opt",help="optimizer",type=str, default='SLSQP') -parser.add_argument('--pythonProf',help="profile in Python",type=int,default=0) -args = parser.parse_args() -sens = args.sens -constrained = args.constrained -testHist = args.testHist -groups = args.groups -sensMode = args.sensMode -pythonProf = args.pythonProf -optOptions = {} - -def objfunc(xdict): - x = xdict['xvars'] # Extract array - funcs = {} - funcs['obj'] = 100*(x[1]-x[0]**2)**2+(1-x[0])**2 - funcs['con'] = 0.1-(x[0]-1)**3 - (x[1]-1) - fail = False - - return funcs, fail - -def sensfunc(xdict, funcsDict): - x = xdict['xvars'] # Extract array - funcsSens = {} - funcsSens['obj'] = {'xvars': [2*100*(x[1]-x[0]**2)*(-2*x[0]) - 2*(1-x[0]), - 2*100*(x[1]-x[0]**2)]} - funcsSens['con'] = {'xvars':[-3*(x[0]-1)**2, -1]} - fail = False - return funcsSens, fail - -# Matrix-free algorithm return functions -def objgrad(xdict): - x = xdict['xvars'] - - objsens = {} - objsens['obj'] = {'xvars': numpy.array([2*100*(x[1]-x[0]**2)*(-2*x[0]) - 2*(1-x[0]), - 2*100*(x[1]-x[0]**2)])} - fail = False - - return objsens, fail - -def jprod(xdict, pdict, sparse_only): - x = xdict['xvars'] - p = pdict['xvars'] - qdict = {} - - if constrained: - gcon = numpy.array([-3*(x[0]-1)**2, -1]) - qdict['con'] = numpy.array([numpy.dot(gcon,p)]) - else: - q = numpy.zeros(0) - fail = False - - return qdict, fail - -def jtprod(xdict,qdict,sparse_only): - x = xdict['xvars'] - - pdict = {} - if constrained: - q = qdict['con'] - gcon = numpy.array([-3*(x[0]-1)**2, -1]) - pdict['xvars'] = q*gcon - else: - pdict['xvars'] = numpy.zeros(len(x)) - fail = False - - return pdict, fail - -if sens == 'none': - sens = None -if sens == 'user': - sens = sensfunc -if sens == 'matrix-free': - sens = [objgrad, jprod, jtprod] - -# Instantiate Optimization Problem -optProb = Optimization('Rosenbrock function', objfunc) -optProb.addVarGroup('xvars', 2, 'c', value=[3, -3], lower=-5.12, upper=5.12, - scale=[1.0, 1.0]) -optProb.finalizeDesignVariables() -if constrained: - optProb.addCon('con',upper=0, scale=1.0) -optProb.addObj('obj') - -# Create optimizer -opt = OPT(args.opt, options=optOptions) -if testHist == 'no': - # Just run a normal run - sol = opt(optProb, sens=sens, sensMode=sensMode) - # print(sol.fStar) - print(sol) -else: - # First call just does 10 iterations - if args.opt.lower() == 'snopt': - opt.setOption('Major iterations limit',10) - solSnopt1 = opt(optProb, sens=sens, sensMode='pgc', storeHistory='opt_hist') - - # Now we are allowed to do 50 - opt.setOption('Major iterations limit',50) - if testHist == 'hot': - solSnopt2 = opt(optProb, sens=sens, sensMode=sensMode, - hotStart='opt_hist', storeHistory='opt_hist') - else: - solSnopt2 = opt(optProb, sens=sens, sensMode=sensMode, - coldStart='opt_hist', storeHistory='opt_hist') - - print(solSnopt2.fStar) - - else: - # Quick test that history prints ok - # if pythonProf: - # cProfile.run('sol = opt(optProb, sens=sens, sensMode=sensMode, storeHistory=\'opt_hist.bin\')',args.opt.lower()+'_profile.profile') - # else: - sol = opt(optProb, sens=sens, sensMode=sensMode, storeHistory='opt_hist.bin') diff --git a/pyoptsparse/examples/runtests.sh b/pyoptsparse/examples/runtests.sh deleted file mode 100644 index 0633630e6..000000000 --- a/pyoptsparse/examples/runtests.sh +++ /dev/null @@ -1,7 +0,0 @@ -python hs015.py --opt=snopt --storeHistory=1 -python hs015.py --opt=slsqp --storeHistory=1 -python hs015.py --opt=nlpqlp --storeHistory=1 -python hs015.py --opt=fsqp --storeHistory=1 -python hs015.py --opt=ipopt --storeHistory=1 -python hs015.py --opt=conmin --storeHistory=1 -python hs015.py --opt=psqp --storeHistory=1 diff --git a/pyoptsparse/examples/snopt_bugfix.py b/pyoptsparse/examples/snopt_bugfix.py deleted file mode 100644 index fdcd38b96..000000000 --- a/pyoptsparse/examples/snopt_bugfix.py +++ /dev/null @@ -1,69 +0,0 @@ -# This example shows a bug where pySNOPT wouldn't optimize a model that has -# only equality constraints because it thought the problem was trivial. The -# problem is a simple paraboloid. The minimum should be at (7.166667, -# -7.833334), but with the bug, x and y stay at zero. - -from __future__ import print_function -import numpy as np - -from pyoptsparse import Optimization, SNOPT - - -def objfunc(xdict): - """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 """ - x = xdict['x'] - y = xdict['y'] - funcs = {} - - funcs['obj'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0 - conval = -x + y - funcs['con'] = conval - - fail = False - return funcs, fail - -def sens(xdict, funcs): - """f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 - """ - x = xdict['x'] - y = xdict['y'] - funcsSens = {} - - funcsSens['obj', 'x'] = 2.0*x - 6.0 + y - funcsSens['obj', 'y'] = 2.0*y + 8.0 + x - #funcsSens['con', 'x'] = -1.0 - #funcsSens['con', 'y'] = 1.0 - - fail = False - return funcsSens, fail - - -con_jac = {} -con_jac['x'] = np.array(-1.0) -con_jac['y'] = np.array(1.0) - - -# Optimization Object -optProb = Optimization('Paraboloid', objfunc) - -# Design Variables -optProb.addVarGroup('x', 1, type='c', lower=-50.0, upper=50.0, value=0.0) -optProb.addVarGroup('y', 1, type='c', lower=-50.0, upper=50.0, value=0.0) -optProb.finalizeDesignVariables() - -# Objective -optProb.addObj('obj') - -# Equality Constraint -optProb.addConGroup('con', 1, lower=-15.0, upper=-15.0, wrt=['x', 'y'], linear=True, jac=con_jac) - -# Check optimization problem: -print(optProb) - -# Optimizer -opt = SNOPT(optOptions = {'Major feasibility tolerance' : 1e-1}) -sol = opt(optProb, sens=sens) - -# Check Solution -print(sol) -print('Solution shoud be (x, y) = (7.166667, -7.833334)\n') \ No newline at end of file diff --git a/pyoptsparse/examples/tp037.py b/pyoptsparse/examples/tp037.py deleted file mode 100644 index 9f7524381..000000000 --- a/pyoptsparse/examples/tp037.py +++ /dev/null @@ -1,46 +0,0 @@ -from __future__ import print_function - -import numpy -import argparse -from pyoptsparse import Optimization, OPT - -parser = argparse.ArgumentParser() -parser.add_argument("--opt",help="optimizer",type=str, default='SLSQP') -args = parser.parse_args() -optOptions = {} - -def objfunc(xx): - x = xx['xvars'] - funcs = {} - funcs['obj'] = -x[0]*x[1]*x[2] - conval = [0]*2 - conval[0] = x[0] + 2.*x[1] + 2.*x[2] - 72.0 - conval[1] = -x[0] - 2.*x[1] - 2.*x[2] - funcs['con'] = conval - fail = False - - return funcs, fail - -# Optimization Object -optProb = Optimization('TP037 Constraint Problem', objfunc) - -# Design Variables -optProb.addVarGroup('xvars', 3, 'c',lower=[0,0,0], upper=[42,42,42], value=10) - -# Constraints -optProb.addConGroup('con', 2, lower=None, upper=0.0) - -# Objective -optProb.addObj('obj') - -# Check optimization problem: -print(optProb) - -# Optimizer -opt = OPT(args.opt, options=optOptions) - -# Solution -sol = opt(optProb, sens='CS') - -# Check Solution -print(sol) diff --git a/pyoptsparse/examples/tp109.py b/pyoptsparse/examples/tp109.py deleted file mode 100644 index c53073179..000000000 --- a/pyoptsparse/examples/tp109.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -""" -Solves Schittkowski's TP109 constraint problem. - - min 3.0*x1+1.*10**(-6)*x1**3+0.522074*10**(-6)*x2**3+2.0*x2 - s.t. -(x4-x3+0.550) <= 0 - -(x3-x4+0.550) <= 0 - -(2.25*10**(+6)-x1**2-x8**2) <= 0 - -(2.25*10**(+6)-x2**2-x9**2) <= 0 - -(x5*x6*sin(-x3-0.250) + +x5*x7*sin(-x4-0.250)+2.0*x5**2*b)*ra+400.0-x1 = 0 - -((x5*x6*sin(x3-0.250)+x6*x7*sin(x3-x4-0.250)+2.0*x6**2*b)*ra+400.0-x2) = 0 - -((x5*x7*sin(x4-0.250)+x6*x7*sin(x4-x3-0.250)+2.0*x7**2*b)*ra+881.7790) = 0 - -(x8+(x5*x6*cos(-x3-0.250)+x5*x7*cos(-x4-0.250)-2.0*x5**2*c)*ra+0.7533*10**(-3)*x5**2-200.00) = 0 - -(x9+(x5*x6*cos(x3-0.250)+x7*x6*cos(x3-x4-0.250)-2.0*x6**2*c)*ra+0.7533*10**(-3)*x(6)**2-200.00) = 0 - -((x5*x7*cos(x4-0.250)+x6*x7*cos(x4-x3-0.250)-2.0*x7**2*c)*ra+0.7533*10**(-3)*x7**2-22.9380) = 0 - 0 <= xi, i = 1,2 - -0.55 <= xi <= 0.55, i = 3,4 - 196.0 <= xi <= 252.0, i = 5,6,7 - -400.0 <= xi <= 800.0, i = 8,9 - where a = 50.176 - b = sin(0.25) - c = cos(0.25) - ra = 1.0/50.176 - - - f*1 = 0.536206927538e+04 - x*1 = [0.674888100445e+03, 0.113417039470e+04, 0.133569060261e+00, -0.371152592466e+00, 0.252e+03, 0.252e+03, 0.201464535316e+03, 0.426660777226e+03, 0.368494083867e+03] -""" -from __future__ import print_function - -import numpy -import argparse -from numpy import sin, cos -from pyoptsparse import Optimization, OPT - -parser = argparse.ArgumentParser() -parser.add_argument("--opt",help="optimizer",type=str, default='SLSQP') -parser.add_argument('--optOptions', type=str, help='Options for the optimizer', default="{}") -args = parser.parse_args() -exec('optOptions=%s'% args.optOptions) -USE_LINEAR = True - -def objfunc(xdict): - x = xdict['xvars'] - - a = 50.1760 - b = sin(0.250) - c = cos(0.250) - funcs = {} - funcs['obj'] = 3.0*x[0] + (1e-6)*x[0]**3 + 0.522074e-6*x[1]**3 + 2*x[1] - fcon = numpy.zeros(10,'D') - fcon[0] = 2250000 - x[0]**2 - x[7]**2 - fcon[1] = 2250000 - x[1]**2 - x[8]**2 - fcon[2] = x[4]*x[5]*sin(-x[2]-0.25) + x[4]*x[6]*sin(-x[3] - 0.25) + 2*b*x[4]**2 - a*x[0] + 400*a - fcon[3] = x[4]*x[5]*sin(x[2] - 0.25) + x[5]*x[6]*sin(x[2] - x[3] - 0.25) + 2*b*x[5]**2 - a*x[1] + 400*a - fcon[4] = x[4]*x[6]*sin(x[3] - 0.25) + x[5]*x[6]*sin(x[3] - x[2] - 0.25) + 2*b*x[6]**2 + 881.779*a - fcon[5] = a*x[7] + x[4]*x[5]*cos(-x[2] - 0.25) + x[4]*x[6]*cos(-x[3] - 0.25) - 200*a - 2*c*x[4]**2 + 0.7533e-3*a*x[4]**2 - fcon[6] = a*x[8] + x[4]*x[5]*cos(x[2]-0.25) + x[5]*x[6]*cos(x[2] - x[3] - 0.25) - 2*c*x[5]**2 + 0.7533e-3*a*x[5]**2 - 200*a - fcon[7] = x[4]*x[6]*cos(x[3] - 0.25) + x[5]*x[6]*cos(x[3] - x[2] - 0.25) - 2*c*x[6]**2 - 22.938*a + 0.7533e-3*a*x[6]**2 - fcon[8] = x[3] - x[2] + 0.55 - fcon[9] = x[2] - x[3] + 0.55 - - if USE_LINEAR: - funcs['con'] = fcon[0:8] - else: - funcs['con'] = fcon[0:10] - fail = False - - return funcs, fail - -# Optimization Object -optProb = Optimization('TP109 Constraint Problem', objfunc) - -# Design Variables -lower = [0.0, 0.0, -0.55, -0.55, 196, 196, 196, -400, -400] -upper = [None, None, 0.55, 0.55, 252, 252, 252, 800, 800] -value = [0, 0, 0, 0, 0, 0, 0, 0, 0] -optProb.addVarGroup('xvars', 9, lower=lower, upper=upper, value=value) - -# Constraints -lower = [0, 0, 0, 0, 0, 0, 0, 0] -upper = [None, None, 0, 0, 0, 0, 0, 0] -if not USE_LINEAR: - lower.extend([0, 0]) - upper.extend([None, None]) - -optProb.addConGroup('con', len(lower), lower=lower, upper=upper) - -# And the 2 linear constriants -if USE_LINEAR: - jac = numpy.zeros((1, 9)) - jac[0, 3] = 1.0 - jac[0, 2] = -1.0 - optProb.addConGroup('lin_con', 1, lower=-.55, upper=0.55, - wrt=['xvars'], jac={'xvars':jac}, linear=True) - -# Objective -optProb.addObj('obj') - -# Check optimization problem: -print(optProb) -optProb.printSparsity() - -# Optimizer -opt = OPT(args.opt, options=optOptions) - -# Solution -sol = opt(optProb, sens='CS') - -# Check Solution -print(sol) diff --git a/pyoptsparse/examples/tp109_autorefine.py b/pyoptsparse/examples/tp109_autorefine.py deleted file mode 100644 index 1b94dc241..000000000 --- a/pyoptsparse/examples/tp109_autorefine.py +++ /dev/null @@ -1,56 +0,0 @@ -# Example of auto-refinement -- runs ALPSO followed by SNOPT. -# See TP109.py for more information. -from __future__ import print_function - -import numpy -import argparse -from numpy import sin, cos -from pyoptsparse import Optimization, SNOPT, ALPSO -USE_LINEAR=True -from tp109 import objfunc # Import objective from the other file - -# Optimization Object -optProb = Optimization('TP109 Constraint Problem',objfunc) - -# Design Variables (Removed infinite bounds for ALPSO) -lower = [0.0, 0.0, -0.55, -0.55, 196, 196, 196, -400, -400] -upper = [2000, 2000, 0.55, 0.55, 252, 252, 252, 800, 800] -value = [0,0,0,0,0,0,0,0,0] -optProb.addVarGroup('xvars', 9, lower=lower, upper=upper, value=value) - -# Constraints -lower = [0, 0 , 0, 0, 0, 0, 0, 0] -upper = [None, None, 0, 0, 0, 0, 0, 0] -if not USE_LINEAR: - lower.extend([0,0]) - upper.extend([None, None]) - -optProb.addConGroup('con', len(lower), lower=lower, upper=upper) - -# And the 2 linear constriants -if USE_LINEAR: - jac = numpy.zeros((1, 9)) - jac[0, 3] = 1.0; jac[0, 2] = -1.0 - optProb.addConGroup('lin_con',1, lower=-.55, upper=0.55, - wrt=['xvars'], jac ={'xvars':jac}, linear=True) - -# Objective -optProb.addObj('obj') - -# Check optimization problem: -print(optProb) -optProb.printSparsity() - -# Global Optimizer: ALPSO -opt1 = ALPSO() - -# Get first Solution -sol1 = opt1(optProb) -print(sol1) - -# Now run the previous solution with SNOPT -opt2 = SNOPT() -sol2 = opt2(sol1) - -# Check Solution -print(sol2) diff --git a/pyoptsparse/postprocessing/OptView.py b/pyoptsparse/postprocessing/OptView.py deleted file mode 100644 index ee5266033..000000000 --- a/pyoptsparse/postprocessing/OptView.py +++ /dev/null @@ -1,1636 +0,0 @@ -""" - -Provides interactive visualization of optimization results created by -pyOptSparse. Figures produced here can be saved as images or pickled -for future customization. - -John Jasa 2015-2017 - -""" - -# ====================================================================== -# Standard Python modules -# ====================================================================== -from __future__ import print_function -import os -import argparse -import shelve - -import sys -major_python_version = sys.version_info[0] - -if major_python_version == 2: - import tkFont - import Tkinter as Tk -else: - import tkinter as Tk - from tkinter import font as tkFont - -import re -import warnings - -# ====================================================================== -# External Python modules -# ====================================================================== -import matplotlib -matplotlib.use('TkAgg') -from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,\ - NavigationToolbar2Tk -import matplotlib.pyplot as plt -from mpl_toolkits.axes_grid1 import host_subplot -import mpl_toolkits.axisartist as AA -try: - warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) - warnings.filterwarnings("ignore",category=UserWarning) -except: - pass -import numpy as np -try: - from sqlitedict import SqliteDict -except: - from pyoptsparse import SqliteDict -import traceback - -class Display(object): - - """ - Container for display parameters, properties, and objects. - This includes a canvas for MPL plots and a bottom area with widgets. - """ - - def __init__(self, histList, outputDir, figsize): - - # Initialize the Tkinter object, which will contain all graphical - # elements. - self.root = Tk.Tk() - self.root.wm_title("OptView") - - # Load the OptView icon - try: - icon_dir = os.path.dirname(os.path.abspath(__file__)) - icon_name = 'OptViewIcon.gif' - icon_dir_full = os.path.join(icon_dir, icon_name) - img = Tk.PhotoImage(file=icon_dir_full) - self.root.tk.call('wm', 'iconphoto', self.root._w, img) - except: # bare except because error is not in standard Python - pass - - figsize = (figsize, figsize) - - # Instantiate the MPL figure - self.f = plt.figure(figsize=figsize, dpi=100, facecolor='white') - - # Link the MPL figure onto the TK canvas and pack it - self.canvas = FigureCanvasTkAgg(self.f, master=self.root) - self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) - - # Add a toolbar to explore the figure like normal MPL behavior - toolbar = NavigationToolbar2Tk(self.canvas, self.root) - toolbar.update() - self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) - - # Increase the font size - matplotlib.rcParams.update({'font.size': 16}) - - # Initialize lists, dicts, and save inputs from user - self.arr_active = 0 - self.plots = [] - self.annotate = None - self.histList = histList - self.outputDir = outputDir - self.bounds = {} - self.scaling = {} - self.color_bounds = [0., 0.] - - # Actually setup and run the GUI - self.OptimizationHistory() - - def OptimizationHistory(self): - """ - Reads in database history file and stores contents. - Function information is stored as a dict in func_data, - variable information is stored as a dict in var_data, - and bounds information is stored as a dict in bounds. - """ - - # Initialize dictionaries for design variables and unknowns. - # The data is saved redundantly in dicts for all iterations and then - # for major iterations as well. - self.func_data_all = {} - self.func_data_major = {} - self.var_data_all = {} - self.var_data_major = {} - db = {} - self.num_iter = 0 - - # Loop over each history file name provided by the user. - for histIndex, histFileName in enumerate(self.histList): - - # If they only have one history file, we don't change the keys' names - if len(self.histList) == 1: - histIndex = '' - else: # If multiple history files, append letters to the keys, - # such that 'key' becomes 'key_A', 'key_B', etc - histIndex = '_' + chr(histIndex + ord('A')) - self.histIndex = histIndex - - try: # This is the classic method of storing history files - db = shelve.open(histFileName, 'r') - OpenMDAO = False - except: # Bare except because error is not in standard Python. - # If the db has the 'iterations' tag, it's an OpenMDAO db. - db = SqliteDict(histFileName, 'iterations') - OpenMDAO = True - - # Need to do this since in py3 db.keys() is a generator object - keys = [i for i in db.keys()] - - # If it has no 'iterations' tag, it's a pyOptSparse db. - if keys == []: - OpenMDAO = False - db = SqliteDict(histFileName) - - # Specific instructions for OpenMDAO databases - if OpenMDAO: - - # Get the number of iterations by looking at the largest number - # in the split string names for each entry in the db - if major_python_version == 3: - for string in db.keys(): - string = string.split('|') - else: - string = db.keys()[-1].split('|') - - nkey = int(string[-1]) - self.solver_name = string[0] - - # Initalize a list detailing if the iterations are major or minor - self.iter_type = np.zeros(nkey) - - # Get the keys of the database where derivatives were evaluated. - # These correspond to major iterations, while no derivative - # info is calculated for gradient-free linesearches. - deriv_keys = SqliteDict(histFileName, 'derivs').keys() - self.deriv_keys = [int(key.split('|')[-1]) for key in deriv_keys] - - # Save information from the history file for the funcs. - self.DetermineMajorIterations(db, OpenMDAO=OpenMDAO) - - # Save information from the history file for the unknowns. - self.SaveDBData(db, self.func_data_all, self.func_data_major, OpenMDAO=OpenMDAO, data_str='Unknowns') - - # Save information from the history file for the design variables. - self.SaveDBData(db, self.var_data_all, self.var_data_major, OpenMDAO=OpenMDAO, data_str='Parameters') - - # Add labels to OpenMDAO variables. - # Corresponds to constraints, design variables, and objective. - try: - db = SqliteDict(histFileName, 'metadata') - self.SaveOpenMDAOData(db) - - except KeyError: # Skip metadata info if not included in OpenMDAO hist file - pass - - else: - - # Get the number of iterations - nkey = int(db['last']) + 1 - self.nkey = nkey - - # Initalize a list detailing if the iterations are major or minor - self.iter_type = np.zeros(nkey) - - # Check to see if there is bounds information in the db file. - # If so, add them to self.bounds to plot later. - try: - info_dict = db['varInfo'].copy() - info_dict.update(db['conInfo']) - # Got to be a little tricky here since we're modifying - # info_dict; if we simply loop over it with the generator - # from Python3, it will contain the new keys and then the - # names will be mangled incorrectly. - bounds_dict = {} - scaling_dict = {} - for key in info_dict.keys(): - bounds_dict[key + histIndex] = { - 'lower': info_dict[key]['lower'], - 'upper': info_dict[key]['upper'] - } - scaling_dict[key + histIndex] = info_dict[key]['scale'] - self.bounds.update(bounds_dict) - self.scaling.update(scaling_dict) - except KeyError: - pass - - # Check to see if there is proper saved info about iter type - if 'iu0' in db['0'].keys(): - if db[db['last']]['iu0'] > 0: - self.storedIters = True - else: - self.storedIters = False - else: - self.storedIters = False - - # Save information from the history file for the funcs. - self.DetermineMajorIterations(db, OpenMDAO=OpenMDAO) - - # Save information from the history file for the funcs. - self.SaveDBData(db, self.func_data_all, self.func_data_major, OpenMDAO=OpenMDAO, data_str='funcs') - - # Save information from the history file for the design variables. - self.SaveDBData(db, self.var_data_all, self.var_data_major, OpenMDAO=OpenMDAO, data_str='xuser') - - # Set the initial dictionaries to reference all iterations. - # Later this can be set to reference only the major iterations. - self.func_data = self.func_data_all - self.var_data = self.var_data_all - - # Find the maximum length of any variable in the dictionaries and - # save this as the number of iterations. - for data_dict in [self.func_data, self.var_data]: - for key in data_dict.keys(): - length = len(data_dict[key]) - if length > self.num_iter: - self.num_iter = length - - def DetermineMajorIterations(self, db, OpenMDAO): - - if not OpenMDAO: - self.obj_key = db['0']['objKey'] - - prev_key = 0 - # Loop over each optimization iteration - for i, iter_type in enumerate(self.iter_type): - - # If this is an OpenMDAO file, the keys are of the format - # 'rank0:SNOPT|1', etc - key = '%d' % i - - # Only actual optimization iterations have 'funcs' in them. - # pyOptSparse saves info for two iterations for every - # actual major iteration. In particular, one has funcs - # and the next has funcsSens, but they're both part of the - # same major iteration. - if any('funcs' == s for s in db[key].keys()): - - # If this iteration has 'funcs' within it, but it's not - # flagged as major, then it's a minor iteration. - if i == 0: - self.iter_type[i] = 1 - else: - self.iter_type[i] = 2 - - if not self.storedIters: # Otherwise, use a spotty heuristic to see if the - # iteration is major or not. NOTE: this is often - # inaccurate, especially if the optimization used - # gradient-enhanced line searches. - try: - keyp1 = '%d' % (i + 1) - db[keyp1]['funcsSens'] - self.iter_type[i] = 1 # for 'major' iterations - except KeyError: - self.iter_type[i] = 2 # for 'minor' iterations - - else: - self.iter_type[i] = 0 # this is not a real iteration, - # just the sensitivity evaluation - - min_list = [] - # Loop over each optimization iteration - for i, iter_type in enumerate(self.iter_type): - - if iter_type == 0: - continue - - key = '%d' % i - - # # If the proper history is stored coming out of - # # pyoptsparse, use that for filtering major iterations. - # if self.storedIters: - # if db[key]['iu0'] != db[prev_key]['iu0']: - # min_array = np.array(min_list) - # argmin = np.argmin(min_array[:, 1]) - # major_key = min_array[argmin, 0] - # self.iter_type[int(major_key)] = 1 - # min_list = [] - # min_list.append([int(key), db[key]['funcs'][self.obj_key]]) - # prev_key = i - - else: # this is if it's OpenMDAO - for i, iter_type in enumerate(self.iter_type): - key = '{}|{}'.format(self.solver_name, i+1) # OpenMDAO uses 1-indexing - if i in self.deriv_keys: - self.iter_type[i] = 1. - - # If no derivative info is saved, we don't know which iterations are major. - # Treat all iterations as major. - if len(self.deriv_keys) < 1: - self.iter_type[:] = 1. - - - def SaveDBData(self, db, data_all, data_major, OpenMDAO, data_str): - """ Method to save the information within the database corresponding - to a certain key to the relevant dictionaries within the Display - object. This method is called twice, once for the design variables - and the other for the outputs. """ - - # Loop over each optimization iteration - for i, iter_type in enumerate(self.iter_type): - - # If this is an OpenMDAO file, the keys are of the format - # 'rank0:SNOPT|1', etc - if OpenMDAO: - key = '{}|{}'.format(self.solver_name, i+1) # OpenMDAO uses 1-indexing - else: # Otherwise the keys are simply a number - key = '%d' % i - - # Do this for both major and minor iterations - if self.iter_type[i]: - - # Get just the info in the dict for this iteration - iter_data = db[key][data_str] - iter_key = key - - # Loop through each key within this iteration - for key in sorted(iter_data): - - # Format a new_key string where we append a modifier - # if we have multiple history files - new_key = key + '{}'.format(self.histIndex) - - # If this key is not in the data dictionaries, add it - if new_key not in data_all: - data_all[new_key] = [] - data_major[new_key] = [] - - # Process the data from the key. Convert it to a numpy - # array, keep only the real part, squeeze any 1-dim - # axes out of it, then flatten it. - data = np.squeeze(np.array(iter_data[key]).real).flatten() - - # Append the data to the entries within the dictionaries. - data_all[new_key].append(data) - if self.iter_type[i] == 1: - data_major[new_key].append(data) - - - def SaveOpenMDAOData(self, db): - """ Examine the OpenMDAO dict and save tags if the variables are - objectives (o), constraints (c), or design variables (dv). """ - - # Loop over each key in the metadata db - for tag in db: - - # Only look at variables and unknowns - if tag in ['Unknowns', 'Parameters']: - for old_item in db[tag]: - - # We'll rename each item, so we need to get the old item - # name and modify it - item = old_item + '{}'.format(self.histIndex) - - # Here we just have an open parenthesis, and then we will - # add o, c, or dv. Note that we could add multiple flags - # to a single item. That's why we have a sort of convoluted - # process of adding the tags. - new_key = item + ' (' - flag_list = [] - - # Check each flag and see if they have the relevant entries - # within the dict; if so, tag them. - for flag in db[tag][old_item]: - if 'is_objective' in flag: - flag_list.append('o') - if 'is_desvar' in flag: - flag_list.append('dv') - if 'is_constraint' in flag: - flag_list.append('c') - - # Create the new_key based on the flags for each variable - for flag in flag_list: - if flag == flag_list[-1]: - new_key += flag + ')' - else: - new_key += flag + ', ' - - # If there are actually flags to add, pop out the old items - # in the dict and re-add them with the new name. - if flag_list: - try: - if 'dv' in flag_list: - self.var_data_all[new_key] = self.func_data_all.pop(item) - self.var_data_major[new_key] = self.func_data_major.pop(item) - - else: - self.func_data_all[new_key] = self.func_data_all.pop(item) - self.func_data_major[new_key] = self.func_data_major.pop(item) - - except KeyError: - pass - - def quit(self): - """ - Destroy GUI window cleanly if quit button pressed. - """ - self.root.quit() - self.root.destroy() - - def error_display(self, string="That option not supported"): - """ - Display error string on canvas when invalid options selected. - """ - self.f.clf() - a = self.f.add_subplot(111) - a.text(0.05, .9, - "Error: " + string, - fontsize=20, - transform=a.transAxes) - self.canvas.draw() - - def warning_display(self, string="That option not supported"): - """ - Display warning message on canvas as necessary. - """ - a = plt.gca() - a.text(0.05, 1.04, - "Warning: " + string, - fontsize=20, - transform=a.transAxes) - self.canvas.draw() - - def note_display(self, string=""): - """ - Display warning message on canvas as necessary. - """ - a = plt.gca() - a.text(0.05, 1.04, - string, - fontsize=20, - transform=a.transAxes) - self.canvas.draw() - - def plot_bounds(self, val, a, color): - """ - Plot the bounds if selected. - """ - - if val not in self.bounds: - for ii, char in enumerate(reversed(val)): - if char == '_': - split_loc = len(val) - ii - break - val_name = val[:split_loc - 1] - val_num = int(val[split_loc:]) - lower = [self.bounds[val_name]['lower'][val_num]] - upper = [self.bounds[val_name]['upper'][val_num]] - else: - lower = self.bounds[val]['lower'] - upper = self.bounds[val]['upper'] - - lower = list(lower) - upper = list(upper) - - a.margins(None, .02) - a.set_prop_cycle('color', color) - for lower_bound in lower: - if lower_bound is not None and abs(lower_bound) < 1e18: - a.plot( - [0, self.num_iter - 1], [ - lower_bound, lower_bound], - "--", linewidth=2, clip_on=False - ) - - a.set_prop_cycle('color', color) - for upper_bound in upper: - if upper_bound is not None and abs(upper_bound) < 1e18: - a.plot( - [0, self.num_iter - 1], [ - upper_bound, upper_bound], - "--", label=val + ' bounds', linewidth=2, clip_on=False) - - def orig_plot(self, dat, val, values, a, i=0): - """ - Plots the original data values from the history file. - """ - cc = plt.rcParams['axes.prop_cycle'].by_key()['color'] * 10 - color = cc[i] - - try: - array_size = len(dat[val][0]) - if self.var_minmax.get(): - a.set_prop_cycle('color', color) - minmax_list = [] - for minmax in dat[val]: - minmax_list.append( - [np.min(minmax), np.max(minmax)]) - plots = a.plot(minmax_list, "o-", label=val, - markeredgecolor='none', clip_on=False) - - elif array_size < 20 or self.var_showall.get(): - if i > 0: - a.set_prop_cycle('color', color) - plots = a.plot(dat[val], "o-", label=val, - markeredgecolor='none', clip_on=False) - - a.set_ylabel(val) - self.color_error_flag = 1 - else: - self.error_display("Too many values to display") - - except TypeError: - a.set_prop_cycle('color', color) - if self.var.get() == 0: - pass - else: - a.set_ylabel(val) - plots = a.plot(dat[val], "o-", label=val, - markeredgecolor='none', clip_on=False) - - except (KeyError, IndexError): - self.warning_display("No 'major' iterations") - try: - if len(plots) > 1: - for i, plot in enumerate(plots): - self.plots.append([plot, i]) - else: - self.plots.append([plots[0], -1]) - except UnboundLocalError: - self.error_display("Too many values to display") - try: - if self.var_bounds.get(): - self.plot_bounds(val, a, color) - - except (UnboundLocalError, ValueError): - if len(values) > 1: - pass - else: - self.error_display("No bounds information") - - def color_plot(self, dat, labels, a): - - # If the user wants the non-constraint colormap, use viridis - if self.var_color.get(): - cmap = plt.get_cmap('viridis') - - # Otherwise, use a custom red-green colormap that has white in the middle - # to showcase which constraints are active or not - else: - cdict1 = {'red': ((0.0, 0.06, 0.06), - (0.3, .11, .11), - (0.5, 1.0, 1.0), - (0.8, 0.8, 0.8), - (1.0, 0.6, 0.6)), - - 'green': ((0.0, 0.3, 0.3), - (0.3, 0.6, 0.6), - (0.5, 1.0, 1.0), - (0.8, 0.0, 0.0), - (1.0, 0.0, 0.0)), - - 'blue': ((0.0, .15, .15), - (0.3, .25, .25), - (0.5, 1.0, 1.0), - (0.8, 0.0, 0.0), - (1.0, 0.0, 0.0)) - } - - from matplotlib.colors import LinearSegmentedColormap - cmap = LinearSegmentedColormap('RedGreen', cdict1) - - # Get the numbmer of iterations and set up some lists - iter_len = len(dat[labels[0]]) - full_array = np.zeros((0, iter_len)) - tick_labels = [] - - # Loop through the data sets selected by the user - for label in labels: - - # Get the subarray for this particular data set and record its size - subarray = np.array(dat[label]).T - sub_size = subarray.shape[0] - - # Add the subarray to the total array to view later - full_array = np.vstack((full_array, subarray)) - - # Set the labels for the ticks. - # If it's a scalar, simply have the data label. - if sub_size == 1: - tick_labels.append(label) - - # Otherwise, have the data label and append a number to it. - else: - tick_labels.append(label + ' 0') - - # However, if there are a large number of data points, - # only label 12 of them to space out the labels. - n = max(sub_size // 12, 1) - for i in range(1, sub_size): - if not i % n: - tick_labels.append(str(i)) - else: - tick_labels.append('') - - if len(self.min_bound.get()) or len(self.max_bound.get()): - bounds = self.color_bounds - - # If the user wants the color set by the bounds, try to get the bounds - # information from the bounds dictionary. - elif self.var_color_bounds.get(): - bounds = [0., 0.] - - # Loop through the labels and extract the smallest lower bound - # and the largest upper bound. - for label in labels: - try: - bounds[0] = min(bounds[0], self.bounds[label]['lower'][0]) - bounds[1] = max(bounds[1], self.bounds[label]['upper'][0]) - except: - pass - - # If we found no bounds data, simply use the smallest and largest - # values from the arrays. - if bounds[0] == 0. and bounds[1] == 0.: - self.warning_display("No bounds information, using min/max array values instead") - largest_mag_val = np.max(np.abs(full_array)) - bounds = [-largest_mag_val, largest_mag_val] - - # Otherwise, simply use the smallest and largest values from the arrays - else: - largest_mag_val = np.max(np.abs(full_array)) - bounds = [-largest_mag_val, largest_mag_val] - - # Set up a colorbar and add it to the figure - cax = a.imshow(full_array, cmap=cmap, aspect='auto', - vmin=bounds[0], vmax=bounds[1]) - fig = plt.gcf() - cbar = fig.colorbar(cax) - - # Some dirty hardcoding in an attempt to get the labels to appear nicely - # for different widths of OptView windows. - # This is challenging to do correctly because of non-uniform text widths. - size = fig.get_size_inches() * fig.dpi - width, height = size - - # More dirty harcoding to try to produce a nice layout. - max_label_length = np.max([len(label) for label in labels]) - plt.subplots_adjust(left=(.006 * max_label_length + .02) * (6000 - width) / 4000) - - # Set the y-tick labels for the plot based on the previously saved info - plt.yticks(range(full_array.shape[0]), tick_labels) - - def plot_selected(self, values, dat): - """ - Plot data based on selected keys within listboxes. - """ - fail = 0 - self.color_error_flag = 0 - self.f.clf() - self.plots = [] - - # Grid the checkbox options that should exist - self.c12.grid_forget() - self.c13.grid_forget() - self.min_label.grid_forget() - self.min.grid_forget() - self.max_label.grid_forget() - self.max.grid_forget() - self.c4.grid(row=0, column=1, sticky=Tk.W) - self.c5.grid(row=1, column=1, sticky=Tk.W) - self.c6.grid(row=2, column=1, sticky=Tk.W) - self.c7.grid(row=3, column=1, sticky=Tk.W) - self.c8.grid(row=4, column=1, sticky=Tk.W) - self.c9.grid(row=5, column=1, sticky=Tk.W) - - plt.subplots_adjust(left=.1) - - try: - if self.var_bounds.get(): - try: - self.bounds - except AttributeError: - self.error_display("No bounds information in history file") - fail = 1 - - # Plot on shared axes - if self.var.get() == 0 and not fail: - a = self.f.add_subplot(111) - - # Calculate and plot the delta values if selected - if self.var_del.get(): - for idx, val in enumerate(values): - newdat = [] - if self.var_scale.get(): - if val not in self.scaling: - for ii, char in enumerate(reversed(val)): - if char == '_': - split_loc = len(val) - ii - break - val_name = val[:split_loc - 1] - val_num = int(val[split_loc:]) - scale = [self.scaling[val_name][val_num]] - else: - scale = self.scaling[val] - else: - scale = 1.0 - for i, value in enumerate(dat[val], start=1): - newdat.append(abs(value - dat[val][i - 2])*scale) - plots = a.plot( - range(1, self.num_iter), - newdat[1:], - "o-", - label=val, - markeredgecolor='none', clip_on=False) - if len(plots) > 1: - for i, plot in enumerate(plots): - self.plots.append([plot, i]) - else: - self.plots.append([plots[0], -1]) - - elif self.var_scale.get(): - for idx, val in enumerate(values): - newdat = [] - if val not in self.scaling: - for ii, char in enumerate(reversed(val)): - if char == '_': - split_loc = len(val) - ii - break - val_name = val[:split_loc - 1] - val_num = int(val[split_loc:]) - scale = [self.scaling[val_name][val_num]] - else: - scale = self.scaling[val] - for i, value in enumerate(dat[val]): - newdat.append(value * scale) - plots = a.plot( - range(0, self.num_iter), - newdat, - "o-", - label=val, - markeredgecolor='none', clip_on=False) - if len(plots) > 1: - for i, plot in enumerate(plots): - self.plots.append([plot, i]) - else: - self.plots.append([plots[0], -1]) - - # Otherwise plot original data - else: - for i, val in enumerate(values): - self.orig_plot(dat, val, values, a, i) - - if self.color_error_flag and self.var_bounds.get(): - self.warning_display( - "Line color for bounds may not match data color") - - # Plot using log scale if selected - if self.var_log.get(): - a.set_yscale('log') - - if self.var_legend.get(): - a.legend(loc='best') - - plt.subplots_adjust(right=.95) - a.set_xlabel('iteration') - a.set_xlim(0, self.num_iter - 1) - self.canvas.draw() - - # Plot on individual vertical axes - elif self.var.get() == 1 and not fail: - - # Set window sizing parameters for when additional axes are - # added - n = len(values) - plt.figure(self.f.number) - par_list = [[] for i in range(n)] # make into array - par_list[0] = host_subplot(111, axes_class=AA.Axes) - size_list = [.95, .95, .93, .83, .73, .63, .53, .43, .33] - plt.subplots_adjust(right=size_list[n]) - - for i in range(1, n): - par_list[i] = par_list[0].twinx() - - offset = 60 - for i in range(2, n): - new_fixed_axis = par_list[ - i].get_grid_helper().new_fixed_axis - par_list[i].axis["right"] = new_fixed_axis( - loc="right", axes=par_list[i], offset=(offset * i ** 1.15, 0)) - par_list[i].axis["right"].toggle(all=True) - - p_list = [[] for i in range(n)] - - # Compute and plot delta values if selected - if self.var_del.get(): - for i, val in enumerate(values): - newdat = [] - for idx, value in enumerate(dat[val], start=1): - newdat.append(abs(value - dat[val][idx - 2])) - p_list[i], = par_list[i].plot(range(1, self.num_iter), - newdat[1:], "o-", label=val, - markeredgecolor='none', clip_on=False) - par_list[i].set_ylabel(val) - # Otherwise plot original data - else: - for i, val in enumerate(values): - cc = plt.rcParams['axes.prop_cycle'].by_key()['color'] * 10 - par_list[i].set_prop_cycle('color', cc[i]) - p_list[i], = par_list[i].plot( - dat[val], "o-", label=val, markeredgecolor='none', clip_on=False) - par_list[i].set_ylabel(val) - - try: - if self.var_bounds.get(): - self.plot_bounds(val, par_list[i], cc[i]) - except (ValueError, UnboundLocalError): - if len(values) > 1: - pass - else: - self.error_display("No bounds information") - - # Plot using log scale if selected - if self.var_log.get(): - for ax in par_list: - ax.set_yscale('log') - - par_list[0].set_xlim(0, self.num_iter - 1) - par_list[0].set_xlabel('iteration') - if self.var_legend.get(): - par_list[0].legend(loc='best') - for i, plot in enumerate(p_list): - self.plots.append([plot, i]) - - self.canvas.draw() - - # Plot on stacked axes with shared x-axis - elif self.var.get() == 2 and not fail: - n = len(values) - - # Compute and plot delta values if selected - if self.var_del.get(): - a = [] - for i, val in enumerate(values): - newdat = [] - for idx, value in enumerate(dat[val], start=1): - newdat.append(abs(value - dat[val][idx - 2])) - a.append(self.f.add_subplot(n, 1, i + 1)) - plots = a[i].plot(range(1, self.num_iter), newdat[1:], - "o-", label=val, markeredgecolor='none', clip_on=False) - a[i].set_ylabel('delta ' + val) - self.plots.append([plots[0], -1]) - - # Otherwise plot original data - else: - a = [] - for i, val in enumerate(values): - a.append(self.f.add_subplot(n, 1, i + 1)) - self.orig_plot(dat, val, values, a[i]) - - # Plot using log scale if selected - if self.var_log.get(): - for ax in a: - ax.set_yscale('log') - - # Turn off horiztonal axes above the bottom plot - a[-1].set_xlabel('iteration') - for ax in a: - if ax != a[-1]: - ax.spines['bottom'].set_visible(False) - ax.set_xticklabels([]) - ax.xaxis.set_major_locator(plt.NullLocator()) - ax.spines['top'].set_visible(False) - for tic in ax.xaxis.get_major_ticks(): - tic.tick2On = False - ax.tick_params( - axis='y', - which='both', - labelleft='off', - labelright='on') - ax.set_xlim(0, self.num_iter - 1) - - plt.subplots_adjust(right=.95) - self.canvas.draw() - - # Plot color plots of rectangular pixels showing values, - # especially useful for constraints - elif self.var.get() == 3 and not fail: - - # Remove options that aren't relevant - self.c4.grid_forget() - self.c5.grid_forget() - self.c6.grid_forget() - self.c7.grid_forget() - self.c8.grid_forget() - self.c9.grid_forget() - - # Add option to change colormap - self.c12.grid(row=0, column=1, sticky=Tk.W) - self.c13.grid(row=1, column=1, sticky=Tk.W) - - # Add bounds textboxes - self.min_label.grid(row=4, column=0, pady=10, sticky=Tk.W) - self.min.grid(row=4, column=1, pady=10, sticky=Tk.W) - self.max_label.grid(row=5, column=0, pady=10, sticky=Tk.W) - self.max.grid(row=5, column=1, pady=10, sticky=Tk.W) - - a = self.f.add_subplot(111) - - self.color_plot(dat, values, a) - - plt.subplots_adjust(right=.95) - a.set_xlabel('iteration') - a.set_xlim(0, self.num_iter - 1) - self.canvas.draw() - - except ValueError: - self.error_display() - - def onselect(self, evt, data_name): - """ - Update current plot with selected data from listboxes. - Also checks if the data is array-type and provides an - additional listbox to select data within that array. - """ - w = evt.widget - values = [w.get(int(i)) for i in w.curselection()] - self.update_graph() - if len(values) == 1: - try: - data = data_name[values[0]] - data[0][0] - self.v.set(values[0]) - self.lb_arr.delete(0, Tk.END) - for i, val in enumerate(data[0]): - self.lb_arr.insert(Tk.END, values[0] + '_' + str(i)) - self.arr_title.pack(side=Tk.TOP) - self.scrollbar_arr.pack(side=Tk.RIGHT, fill=Tk.Y) - self.lb_arr.pack(side=Tk.RIGHT) - self.arr_active = 1 - except (IndexError, TypeError): - self.lb_arr.pack_forget() - self.scrollbar_arr.pack_forget() - self.arr_title.pack_forget() - self.arr_active = 0 - except KeyError: - self.warning_display("No 'major' iterations") - - def onselect_arr(self, evt): - """ - Obtain the selected plotting values from the array-based variable listbox. - """ - w = evt.widget - values = [int(i) for i in w.curselection()] - - # Get the currently selected functions/variables - func_sel = self.lb_func.curselection() - var_sel = self.lb_var.curselection() - if len(func_sel): - values_orig = [self.lb_func.get(i) for i in func_sel] - dat = self.func_data[values_orig[0]] - elif len(var_sel): - values_orig = [self.lb_var.get(i) for i in var_sel] - dat = self.var_data[values_orig[0]] - - # Add the array-based information to the listbox for selection - self.arr_data = {} - self.val_names = [] - for i, val in enumerate(values): - self.val_names.append(values_orig[0] + '_{0}'.format(val)) - self.arr_data[self.val_names[i]] = [] - for ind_dat in dat: - self.arr_data[self.val_names[i]].append(ind_dat[val]) - self.plot_selected(self.val_names, self.arr_data) - - def update_graph(self): - """ - Produce an updated graph based on user options. - """ - - if self.var_minmax.get() and self.var_showall.get(): - self.error_display("Cannot show all and min/max at same time") - - else: - func_sel = self.lb_func.curselection() - var_sel = self.lb_var.curselection() - arr_sel = self.lb_arr.curselection() - values = [] - dat = {} - - if len(arr_sel) and self.arr_active: - self.plot_selected(self.val_names, self.arr_data) - - elif len(func_sel) or len(var_sel): - values.extend([self.lb_func.get(i) for i in func_sel]) - dat = self.func_data.copy() - values.extend([self.lb_var.get(i) for i in var_sel]) - dat.update(self.var_data) - self.plot_selected(values, dat) - - def set_mask(self): - - if self.var_mask.get(): - self.func_data = self.func_data_major - self.var_data = self.var_data_major - else: - self.func_data = self.func_data_all - self.var_data = self.var_data_all - - self.num_iter = 0 - - for key in self.func_data.keys(): - length = len(self.func_data[key]) - if length > self.num_iter: - self.num_iter = length - - self.update_graph() - - def save_figure(self): - """ - Save the current figure using the selected variables as the filename. - """ - func_sel = self.lb_func.curselection() - var_sel = self.lb_var.curselection() - arr_sel = self.lb_arr.curselection() - values = [] - if len(arr_sel) and self.arr_active: - values = self.val_names - elif len(func_sel): - values = [self.lb_func.get(i) for i in func_sel] - elif len(var_sel): - values = [self.lb_var.get(i) for i in var_sel] - groups = '' - for string in values: - groups += string + '_' - fname = groups + '.png' - fpathname = os.path.join(self.outputDir, fname) - plt.savefig(fpathname) - fname = 'saved_figure.pickle' - fpathname = os.path.join(self.outputDir, fname) - try: - import dill - dill.dump(self.f, file(fpathname, 'wb')) - except ImportError: - pass - - def save_all_figues(self): - """ - Batch save all individual figures from functions and variables. - """ - for data_name in [self.func_data, self.var_data]: - for key in data_name: - fig = plt.figure() - plt.plot(data_name[key], 'ko-') - plt.title(key) - fname = key + '.png' - fpathname = os.path.join(self.outputDir, fname) - plt.savefig(fpathname) - plt.clf() - - def save_tec(self): - """ - Output selected data to tec file. - """ - func_sel = self.lb_func.curselection() - var_sel = self.lb_var.curselection() - arr_sel = self.lb_arr.curselection() - dat = {} - if len(arr_sel) and self.arr_active: - for name in self.val_names: - dat[name] = self.arr_data[name] - if len(func_sel): - values = [self.lb_func.get(i) for i in func_sel] - for name in values: - dat[name] = self.func_data[name] - if len(var_sel): - values = [self.lb_var.get(i) for i in var_sel] - for name in values: - dat[name] = self.var_data[name] - - keys = dat.keys() - - num_vars = len(keys) - num_iters = len(dat[keys[0]]) - full_data = np.arange(num_iters, dtype=np.float_).reshape(num_iters, 1) - var_names = ['Iteration'] - for key in keys: - small_data = np.asarray(dat[key]) - - if len(small_data.shape) == 1: - full_data = np.c_[full_data, small_data] - var_names.append(key) - - else: - m = small_data.shape[0] - n = small_data.shape[1] - indiv_data = np.empty((m, 1)) - for i in range(n): - for j in range(m): - indiv_data[j] = small_data[j][i] - full_data = np.c_[full_data, indiv_data] - var_names.append(key + '_{}'.format(i)) - - filename = 'OptView_tec.dat' - self._file = open(filename, 'w') - self._file.write('Title = \"OptView data output\"" \n') - self._file.write('Variables = ') - for name in var_names: - self._file.write('\"' + name + '\" ') - self._file.write('\n') - - self._file.write('Zone T= \"OptView_tec_data\", ' + \ - 'I={}, '.format(num_iters) + 'F=POINT\n') - np.savetxt(self._file, full_data) - self._file.close() - - def var_search(self, _): - """ - Remove listbox entries that do not contain user-inputted string, - used to search through outputted data. - """ - self.lb_func.delete(0, Tk.END) - self.lb_var.delete(0, Tk.END) - for key in sorted(self.func_data): - self.lb_func.insert(Tk.END, key) - for key in sorted(self.var_data): - self.lb_var.insert(Tk.END, key) - - search_entry = self.entry_search.get() - func_range = range(len(self.func_data)) - for i in func_range[::-1]: - if not re.search(search_entry.lower(), self.lb_func.get(i).lower()): - self.lb_func.delete(i) - - var_range = range(len(self.var_data)) - for i in var_range[::-1]: - if not re.search(search_entry.lower(), self.lb_var.get(i).lower()): - self.lb_var.delete(i) - - if not self.lb_var.get(1) and not self.lb_func.get(1): - if self.lb_var.get(0): - self.lb_var.select_set(0) - if self.lb_func.get(0): - self.lb_func.select_set(0) - self.update_graph() - - def update_font(self, val): - """ - Set the font for matplotlib based on slider. - """ - matplotlib.rcParams.update({'font.size': int(val)}) - self.update_graph() - - def refresh_history(self): - """ - Refresh opt_his data if the history file has been updated. - """ - old_funcs = [] - for key in self.func_data: - old_funcs.append(key) - old_vars = [] - for key in self.var_data: - old_vars.append(key) - - self.OptimizationHistory() - - new_funcs = [] - for key in self.func_data: - new_funcs.append(key) - new_vars = [] - for key in self.var_data: - new_vars.append(key) - - if not (old_funcs == new_funcs and old_vars == new_vars): - self.var_search('dummy') - - def refresh_history_init(self): - self.refresh_history() - self.set_mask() - - def auto_ref(self): - """ - Automatically refreshes the history file, which is - useful if examining a running optimization. - """ - if self.var_ref.get(): - self.root.after(1000, self.auto_ref) - self.refresh_history() - self.set_mask() - - def clear_selections(self): - """ - Deselects all currently-selected variables, functions, and array options - """ - self.lb_func.selection_clear(0, Tk.END) - self.lb_var.selection_clear(0, Tk.END) - self.lb_arr.selection_clear(0, Tk.END) - - def on_move(self, event): - """ - Checks to see if the cursor is over a plot and provides a - hovering label if necessary. - """ - try: - self.annotation.remove() - except (AttributeError, ValueError): - pass - if event.xdata: - visibility_changed = False - point_selected = None - for point in self.plots: - if point[0].contains(event)[0]: - point_selected = point - - # Prevent error message if we move out of bounds while hovering - # over a point on a line - if point_selected: - visibility_changed = True - ax = point_selected[0].axes - label = point_selected[0].get_label() - if point_selected[1] >= 0: - label = label + '_' + str(point_selected[1]) - - xdat = point_selected[0].get_xdata() - ydat = point_selected[0].get_ydata() - - iter_count = np.round(event.xdata, 0) - ind = np.where(xdat == iter_count)[0][0] - - label = label + '\niter: {0:d}\nvalue: {1}'.format(int(iter_count), ydat[ind]) - - # Get the width of the window so we can scale the label placement - size = self.f.get_size_inches() * self.f.dpi - width, height = size - - xlim = ax.get_xlim() - ylim = ax.get_ylim() - - x_coord = (event.xdata - xlim[0]) / (xlim[1] - xlim[0]) - y_coord = (event.ydata - ylim[0]) / (ylim[1] - ylim[0]) - - # Scale and position the label based on the iteration number. - x_coord -= event.xdata/(xlim[1]-xlim[0]) * len(label) * 10 / width - - self.annotation = ax.annotate(label, - xy=(x_coord, y_coord), xycoords='axes fraction', - xytext=(x_coord, y_coord), textcoords='axes fraction', - horizontalalignment="left", - bbox=dict( - boxstyle="round", facecolor="w", - edgecolor="0.5", alpha=0.8), - ) - else: - try: - self.annotation.remove() - except (AttributeError, ValueError): - pass - - self.canvas.draw() - - def set_bounds(self, bound): - try: - if self.min_bound == bound: - self.color_bounds[0] = float(bound.get()) - else: - self.color_bounds[1] = float(bound.get()) - except ValueError: - pass - self.update_graph() - - def draw_GUI(self): - """ - Create the frames and widgets in the bottom section of the canvas. - """ - font = tkFont.Font(family="Helvetica", size=10) - - sel_frame = Tk.Frame(self.root) - sel_frame.pack(side=Tk.LEFT) - - # Produce a frame and listbox to contain function information - func_frame = Tk.Frame(sel_frame) - func_frame.pack(side=Tk.LEFT, fill=Tk.Y, padx=20) - func_title = Tk.Label(func_frame, text="Functions", font=font) - func_title.pack(side=Tk.TOP) - self.lb_func = Tk.Listbox( - func_frame, - name='lb_func', - selectmode=Tk.EXTENDED, - font=font, - width=30, - exportselection=0) - self.lb_func.pack(side=Tk.LEFT) - for key in sorted(self.func_data): - self.lb_func.insert(Tk.END, key) - scrollbar_func = Tk.Scrollbar(func_frame) - scrollbar_func.pack(side=Tk.RIGHT, fill=Tk.Y) - self.lb_func.config(yscrollcommand=scrollbar_func.set) - scrollbar_func.config(command=self.lb_func.yview) - self.lb_func.bind( - '<>', - lambda event: self.onselect( - event, - self.func_data)) - - # Produce a frame and listbox to contain variable information - var_frame = Tk.Frame(sel_frame) - var_frame.pack(side=Tk.RIGHT, fill=Tk.Y, padx=20) - var_title = Tk.Label(var_frame, text="Design Variables", font=font) - var_title.pack(side=Tk.TOP) - scrollbar_var = Tk.Scrollbar(var_frame) - scrollbar_var.pack(side=Tk.RIGHT, fill=Tk.Y) - self.lb_var = Tk.Listbox( - var_frame, - name='lb_var', - selectmode=Tk.EXTENDED, - font=font, - width=30, - exportselection=0) - self.lb_var.pack(side=Tk.RIGHT) - for key in sorted(self.var_data): - self.lb_var.insert(Tk.END, key) - self.lb_var.config(yscrollcommand=scrollbar_var.set) - scrollbar_var.config(command=self.lb_var.yview) - self.lb_var.bind( - '<>', - lambda event: self.onselect( - event, - self.var_data)) - - # Produce a frame and listbox to contain array-based variable - # information - arr_frame = Tk.Frame(self.root) - arr_frame.pack(side=Tk.RIGHT, fill=Tk.Y, padx=20) - self.v = Tk.StringVar() - self.arr_title = Tk.Label( - arr_frame, - text="Array variables", - font=font, - textvariable=self.v) - self.scrollbar_arr = Tk.Scrollbar(arr_frame) - self.lb_arr = Tk.Listbox( - arr_frame, - name='lb_arr', - selectmode=Tk.EXTENDED, - font=font, - width=30, - exportselection=0) - self.lb_arr.config(yscrollcommand=self.scrollbar_arr.set) - self.scrollbar_arr.config(command=self.lb_arr.yview) - self.lb_arr.bind('<>', self.onselect_arr) - - # Create options frame with buttons and checkboxes for user - options_frame = Tk.Frame(self.root) - options_frame.pack(side=Tk.LEFT, fill=Tk.Y, pady=10) - - button0 = Tk.Button( - options_frame, - text='Clear selections', - command=self.clear_selections, - font=font) - button0.grid(row=0, column=2, padx=5, sticky=Tk.W) - - button1 = Tk.Button( - options_frame, - text='Refresh history', - command=self.refresh_history_init, - font=font) - button1.grid(row=1, column=2, padx=5, sticky=Tk.W) - - button2 = Tk.Button( - options_frame, - text='Save all figures', - command=self.save_all_figues, - font=font) - button2.grid(row=2, column=2, padx=5, sticky=Tk.W) - - button3 = Tk.Button( - options_frame, - text='Save figure', - command=self.save_figure, - font=font) - button3.grid(row=3, column=2, padx=5, sticky=Tk.W) - - button4 = Tk.Button( - options_frame, - text='Save tec file', - command=self.save_tec, - font=font) - button4.grid(row=4, column=2, padx=5, sticky=Tk.W) - - button5 = Tk.Button( - options_frame, - text='Quit', - command=self.quit, - font=font) - button5.grid(row=5, column=2, padx=5, sticky=Tk.W) - - self.min_label = Tk.Label( - options_frame, - text="Min bound for colorbar:", - font=font) - - # Input box to select the min bounds for the colorbar when using color plots - self.min_bound = Tk.StringVar() - self.min_bound.trace("w", lambda name, index, mode, min_bound=self.min_bound: self.set_bounds(self.min_bound)) - self.min = Tk.Entry( - options_frame, text="Search", textvariable=self.min_bound, - font=font) - - self.max_label = Tk.Label( - options_frame, - text="Max bound for colorbar:", - font=font) - - # Input box to select the max bounds for the colorbar when using color plots - self.max_bound = Tk.StringVar() - self.max_bound.trace("w", lambda name, index, mode, max_bound=self.max_bound: self.set_bounds(self.max_bound)) - self.max = Tk.Entry( - options_frame, text="Search", textvariable=self.max_bound, - font=font) - - # Plot options - self.var = Tk.IntVar() - c1 = Tk.Radiobutton( - options_frame, text="Shared axes", variable=self.var, - command=self.update_graph, font=font, value=0) - c1.grid(row=0, column=0, sticky=Tk.W) - - c2 = Tk.Radiobutton( - options_frame, text="Multiple axes", variable=self.var, - command=self.update_graph, font=font, value=1) - c2.grid(row=1, column=0, sticky=Tk.W) - - c3 = Tk.Radiobutton( - options_frame, text="Stacked plots", variable=self.var, - command=self.update_graph, font=font, value=2) - c3.grid(row=2, column=0, sticky=Tk.W) - - c12 = Tk.Radiobutton( - options_frame, text="Color plots", variable=self.var, - command=self.update_graph, font=font, value=3) - c12.grid(row=3, column=0, sticky=Tk.W) - - self.var_del = Tk.IntVar() - self.c4 = Tk.Checkbutton( - options_frame, - text="Absolute delta values", - variable=self.var_del, - command=self.update_graph, - font=font) - self.c4.grid(row=0, column=1, sticky=Tk.W) - - self.var_log = Tk.IntVar() - self.c5 = Tk.Checkbutton( - options_frame, - text="Log scale", - variable=self.var_log, - command=self.update_graph, - font=font) - self.c5.grid(row=1, column=1, sticky=Tk.W) - - # Option to only show the min and max of array-type variables - self.var_minmax = Tk.IntVar() - self.c6 = Tk.Checkbutton( - options_frame, - text="Min/max for arrays", - variable=self.var_minmax, - command=self.update_graph, - font=font) - self.c6.grid(row=2, column=1, sticky=Tk.W) - - # Option to show all values for array-type variables - self.var_showall = Tk.IntVar() - self.c7 = Tk.Checkbutton( - options_frame, - text="Show all for arrays", - variable=self.var_showall, - command=self.update_graph, - font=font) - self.c7.grid(row=3, column=1, sticky=Tk.W) - - # Option to show legend - self.var_legend = Tk.IntVar() - self.c8 = Tk.Checkbutton( - options_frame, - text="Show legend", - variable=self.var_legend, - command=self.update_graph, - font=font) - self.var_legend.set(1) - self.c8.grid(row=4, column=1, sticky=Tk.W) - - # Option to show bounds - self.var_bounds = Tk.IntVar() - self.c9 = Tk.Checkbutton( - options_frame, - text="Show bounds", - variable=self.var_bounds, - command=self.update_graph, - font=font) - self.c9.grid(row=5, column=1, sticky=Tk.W) - - # Option to only show major iterations - self.var_mask = Tk.IntVar() - self.c10 = Tk.Checkbutton( - options_frame, - text="Show major iterations", - variable=self.var_mask, - command=self.set_mask, - font=font) - self.c10.grid(row=6, column=1, sticky=Tk.W, pady=6) - - # Option to automatically refresh history file - # especially useful for running optimizations - self.var_ref = Tk.IntVar() - self.c11 = Tk.Checkbutton( - options_frame, - text="Automatically refresh", - variable=self.var_ref, - command=self.auto_ref, - font=font) - self.c11.grid(row=7, column=1, sticky=Tk.W, pady=6) - - # Option to choose colormap for color plots - self.var_color = Tk.IntVar() - self.c12 = Tk.Checkbutton( - options_frame, - text="Viridis colormap", - variable=self.var_color, - command=self.update_graph, - font=font) - - # Option to choose limits of colorbar axes - self.var_color_bounds = Tk.IntVar() - self.c13 = Tk.Checkbutton( - options_frame, - text="Colorbar set by bounds", - variable=self.var_color_bounds, - command=self.update_graph, - font=font) - - # Option to scale variables or constraints to how - # the optimizer sees them - self.var_scale = Tk.IntVar() - self.c14 = Tk.Checkbutton( - options_frame, - text="Apply scaling factor", - variable=self.var_scale, - command=self.update_graph, - font=font) - self.c14.grid(row=8, column=1, sticky=Tk.W, pady=6) - - lab = Tk.Label( - options_frame, - text="Search for a function/variable:", - font=font) - lab.grid(row=9, column=0, columnspan=2, pady=10, sticky=Tk.W) - - # Search box to filter displayed functions/variables - vs = Tk.StringVar() - vs.trace("w", lambda name, index, mode, vs=vs: self.var_search(vs)) - self.entry_search = Tk.Entry( - options_frame, text="Search", textvariable=vs, - font=font) - self.entry_search.grid(row=9, column=2, pady=10, sticky=Tk.W) - - lab_font = Tk.Label( - options_frame, - text="Font size for plots:", - font=font) - lab_font.grid(row=10, column=0, sticky=Tk.S) - - w = Tk.Scale(options_frame, from_=6, to=24, orient=Tk.HORIZONTAL, - resolution=2, command=self.update_font, font=font) - w.set(16) - w.grid(row=10, column=1) - -if __name__ == '__main__': - # Called only if this script is run as main. - - # ====================================================================== - # Input Information - # ====================================================================== - parser = argparse.ArgumentParser() - parser.add_argument( - 'histFile', nargs='*', type=str, default='opt_hist.hst', - help="Specify the history file to be plotted") - parser.add_argument('--output', nargs='?', type=str, default='./', - help="Specify the output directory") - parser.add_argument('--figsize', nargs='?', type=float, default='4', - help="Specify the desired minimum figure canvas size") - - args = parser.parse_args() - histList = args.histFile - outputDir = args.output - figsize = args.figsize - - histFileName = histList[0] - - # Check that the output directory is available. Create it if not - if not os.path.isdir(outputDir): - os.makedirs(outputDir) - # Initialize display parameters, obtain history, and draw GUI - disp = Display(histList, outputDir, figsize) - disp.draw_GUI() - disp.root.protocol("WM_DELETE_WINDOW", disp.quit) - on_move_id = disp.f.canvas.mpl_connect('motion_notify_event', disp.on_move) - disp.note_display('Select functions or design variables from the listboxes \nbelow to view the optimization history.') - Tk.mainloop() diff --git a/pyoptsparse/postprocessing/OptViewIcon.gif b/pyoptsparse/postprocessing/OptViewIcon.gif deleted file mode 100644 index 3001627c0..000000000 Binary files a/pyoptsparse/postprocessing/OptViewIcon.gif and /dev/null differ diff --git a/pyoptsparse/postprocessing/OptView_dash.py b/pyoptsparse/postprocessing/OptView_dash.py deleted file mode 100644 index 4c514832a..000000000 --- a/pyoptsparse/postprocessing/OptView_dash.py +++ /dev/null @@ -1,615 +0,0 @@ -#!/usr/bin/python -import dash -import dash_core_components as dcc -import dash_html_components as html -import plotly.graph_objs as go -from plotly import tools -import numpy as np -import argparse -from sqlitedict import SqliteDict -import shelve -import sys - -major_python_version = sys.version_info[0] -parser = argparse.ArgumentParser() -parser.add_argument( - 'histFile', nargs='*', type=str, default='opt_hist.hst', - help="Specify the history file to be plotted") - -args = parser.parse_args() -histList = args.histFile - - -class ReadOptHist(object): - """ - Container for display parameters, properties, and objects. - This includes a canvas for MPL plots and a bottom area with widgets. - """ - - def __init__(self, histList): - - # Initialize lists, dicts, and save inputs from user - self.arr_active = 0 - self.plots = [] - self.annotate = None - self.histList = histList - self.bounds = {} - self.scaling = {} - self.color_bounds = [0., 0.] - - # Actually setup and run the GUI - self.OptimizationHistory() - - def OptimizationHistory(self): - """ - Reads in database history file and stores contents. - Function information is stored as a dict in func_data, - variable information is stored as a dict in var_data, - and bounds information is stored as a dict in bounds. - """ - - # Initialize dictionaries for design variables and unknowns. - # The data is saved redundantly in dicts for all iterations and then - # for major iterations as well. - self.func_data_all = {} - self.func_data_major = {} - self.var_data_all = {} - self.var_data_major = {} - db = {} - self.num_iter = 0 - - # Loop over each history file name provided by the user. - for histIndex, histFileName in enumerate(self.histList): - - # If they only have one history file, we don't change the keys' names - if len(self.histList) == 1: - histIndex = '' - else: # If multiple history files, append letters to the keys, - # such that 'key' becomes 'key_A', 'key_B', etc - histIndex = '_' + chr(histIndex + ord('A')) - self.histIndex = histIndex - - try: # This is the classic method of storing history files - db = shelve.open(histFileName, 'r') - OpenMDAO = False - except: # Bare except because error is not in standard Python. - # If the db has the 'iterations' tag, it's an OpenMDAO db. - db = SqliteDict(histFileName, 'iterations') - OpenMDAO = True - - # Need to do this since in py3 db.keys() is a generator object - keys = [i for i in db.keys()] - - # If it has no 'iterations' tag, it's a pyOptSparse db. - if keys == []: - OpenMDAO = False - db = SqliteDict(histFileName) - - # Specific instructions for OpenMDAO databases - if OpenMDAO: - - # Get the number of iterations by looking at the largest number - # in the split string names for each entry in the db - if major_python_version == 3: - for string in db.keys(): - string = string.split('|') - else: - string = db.keys()[-1].split('|') - - nkey = int(string[-1]) - self.solver_name = string[0] - - # Initalize a list detailing if the iterations are major or minor - self.iter_type = np.zeros(nkey) - - # Get the keys of the database where derivatives were evaluated. - # These correspond to major iterations, while no derivative - # info is calculated for gradient-free linesearches. - deriv_keys = SqliteDict(histFileName, 'derivs').keys() - self.deriv_keys = [int(key.split('|')[-1]) for key in deriv_keys] - - # Save information from the history file for the funcs. - self.DetermineMajorIterations(db, OpenMDAO=OpenMDAO) - - # Save information from the history file for the unknowns. - self.SaveDBData(db, self.func_data_all, self.func_data_major, OpenMDAO=OpenMDAO, data_str='Unknowns') - - # Save information from the history file for the design variables. - self.SaveDBData(db, self.var_data_all, self.var_data_major, OpenMDAO=OpenMDAO, data_str='Parameters') - - # Add labels to OpenMDAO variables. - # Corresponds to constraints, design variables, and objective. - try: - db = SqliteDict(histFileName, 'metadata') - self.SaveOpenMDAOData(db) - - except KeyError: # Skip metadata info if not included in OpenMDAO hist file - pass - - else: - - # Get the number of iterations - nkey = int(db['last']) + 1 - self.nkey = nkey - - # Initalize a list detailing if the iterations are major or minor - self.iter_type = np.zeros(nkey) - - # Check to see if there is bounds information in the db file. - # If so, add them to self.bounds to plot later. - try: - info_dict = db['varInfo'].copy() - info_dict.update(db['conInfo']) - # Got to be a little tricky here since we're modifying - # info_dict; if we simply loop over it with the generator - # from Python3, it will contain the new keys and then the - # names will be mangled incorrectly. - bounds_dict = {} - scaling_dict = {} - for key in info_dict.keys(): - bounds_dict[key + histIndex] = { - 'lower': info_dict[key]['lower'], - 'upper': info_dict[key]['upper'] - } - scaling_dict[key + histIndex] = info_dict[key]['scale'] - self.bounds.update(bounds_dict) - self.scaling.update(scaling_dict) - except KeyError: - pass - - # Check to see if there is proper saved info about iter type - if 'iu0' in db['0'].keys(): - if db[db['last']]['iu0'] > 0: - self.storedIters = True - else: - self.storedIters = False - else: - self.storedIters = False - - # Save information from the history file for the funcs. - self.DetermineMajorIterations(db, OpenMDAO=OpenMDAO) - - # Save information from the history file for the funcs. - self.SaveDBData(db, self.func_data_all, self.func_data_major, OpenMDAO=OpenMDAO, data_str='funcs') - - # Save information from the history file for the design variables. - self.SaveDBData(db, self.var_data_all, self.var_data_major, OpenMDAO=OpenMDAO, data_str='xuser') - - # Set the initial dictionaries to reference all iterations. - # Later this can be set to reference only the major iterations. - self.func_data = self.func_data_all - self.var_data = self.var_data_all - - # Find the maximum length of any variable in the dictionaries and - # save this as the number of iterations. - for data_dict in [self.func_data, self.var_data]: - for key in data_dict.keys(): - length = len(data_dict[key]) - if length > self.num_iter: - self.num_iter = length - - def DetermineMajorIterations(self, db, OpenMDAO): - - if not OpenMDAO: - self.obj_key = db['0']['objKey'] - - prev_key = 0 - # Loop over each optimization iteration - for i, iter_type in enumerate(self.iter_type): - - # If this is an OpenMDAO file, the keys are of the format - # 'rank0:SNOPT|1', etc - key = '%d' % i - - # Only actual optimization iterations have 'funcs' in them. - # pyOptSparse saves info for two iterations for every - # actual major iteration. In particular, one has funcs - # and the next has funcsSens, but they're both part of the - # same major iteration. - if any('funcs' == s for s in db[key].keys()): - - # If this iteration has 'funcs' within it, but it's not - # flagged as major, then it's a minor iteration. - if i == 0: - self.iter_type[i] = 1 - else: - self.iter_type[i] = 2 - - if not self.storedIters: # Otherwise, use a spotty heuristic to see if the - # iteration is major or not. NOTE: this is often - # inaccurate, especially if the optimization used - # gradient-enhanced line searches. - try: - keyp1 = '%d' % (i + 1) - db[keyp1]['funcsSens'] - self.iter_type[i] = 1 # for 'major' iterations - except KeyError: - self.iter_type[i] = 2 # for 'minor' iterations - - else: - self.iter_type[i] = 0 # this is not a real iteration, - # just the sensitivity evaluation - - min_list = [] - # Loop over each optimization iteration - for i, iter_type in enumerate(self.iter_type): - - if iter_type == 0: - continue - - key = '%d' % i - - # # If the proper history is stored coming out of - # # pyoptsparse, use that for filtering major iterations. - # if self.storedIters: - # if db[key]['iu0'] != db[prev_key]['iu0']: - # min_array = np.array(min_list) - # argmin = np.argmin(min_array[:, 1]) - # major_key = min_array[argmin, 0] - # self.iter_type[int(major_key)] = 1 - # min_list = [] - # min_list.append([int(key), db[key]['funcs'][self.obj_key]]) - # prev_key = i - - else: # this is if it's OpenMDAO - for i, iter_type in enumerate(self.iter_type): - key = '{}|{}'.format(self.solver_name, i + 1) # OpenMDAO uses 1-indexing - if i in self.deriv_keys: - self.iter_type[i] = 1. - - # If no derivative info is saved, we don't know which iterations are major. - # Treat all iterations as major. - if len(self.deriv_keys) < 1: - self.iter_type[:] = 1. - - def refresh_history(self): - """ - Refresh opt_his data if the history file has been updated. - """ - # old_funcs = [] - # for key in self.func_data: - # old_funcs.append(key) - # old_vars = [] - # for key in self.var_data: - # old_vars.append(key) - - self.OptimizationHistory() - - # new_funcs = [] - # for key in self.func_data: - # new_funcs.append(key) - # new_vars = [] - # for key in self.var_data: - # new_vars.append(key) - # - # if not (old_funcs == new_funcs and old_vars == new_vars): - # self.var_search('dummy') - - def SaveDBData(self, db, data_all, data_major, OpenMDAO, data_str): - """ Method to save the information within the database corresponding - to a certain key to the relevant dictionaries within the Display - object. This method is called twice, once for the design variables - and the other for the outputs. """ - - # Loop over each optimization iteration - for i, iter_type in enumerate(self.iter_type): - - # If this is an OpenMDAO file, the keys are of the format - # 'rank0:SNOPT|1', etc - if OpenMDAO: - key = '{}|{}'.format(self.solver_name, i + 1) # OpenMDAO uses 1-indexing - else: # Otherwise the keys are simply a number - key = '%d' % i - - # Do this for both major and minor iterations - if self.iter_type[i]: - - # Get just the info in the dict for this iteration - iter_data = db[key][data_str] - iter_key = key - - # Loop through each key within this iteration - for key in sorted(iter_data): - - # Format a new_key string where we append a modifier - # if we have multiple history files - new_key = key + '{}'.format(self.histIndex) - - # If this key is not in the data dictionaries, add it - if new_key not in data_all: - data_all[new_key] = [] - data_major[new_key] = [] - - # Process the data from the key. Convert it to a numpy - # array, keep only the real part, squeeze any 1-dim - # axes out of it, then flatten it. - data = np.squeeze(np.array(iter_data[key]).real).flatten() - - # Append the data to the entries within the dictionaries. - data_all[new_key].append(data) - if self.iter_type[i] == 1: - data_major[new_key].append(data) - - def SaveOpenMDAOData(self, db): - """ Examine the OpenMDAO dict and save tags if the variables are - objectives (o), constraints (c), or design variables (dv). """ - - # Loop over each key in the metadata db - for tag in db: - - # Only look at variables and unknowns - if tag in ['Unknowns', 'Parameters']: - for old_item in db[tag]: - - # We'll rename each item, so we need to get the old item - # name and modify it - item = old_item + '{}'.format(self.histIndex) - - # Here we just have an open parenthesis, and then we will - # add o, c, or dv. Note that we could add multiple flags - # to a single item. That's why we have a sort of convoluted - # process of adding the tags. - new_key = item + ' (' - flag_list = [] - - # Check each flag and see if they have the relevant entries - # within the dict; if so, tag them. - for flag in db[tag][old_item]: - if 'is_objective' in flag: - flag_list.append('o') - if 'is_desvar' in flag: - flag_list.append('dv') - if 'is_constraint' in flag: - flag_list.append('c') - - # Create the new_key based on the flags for each variable - for flag in flag_list: - if flag == flag_list[-1]: - new_key += flag + ')' - else: - new_key += flag + ', ' - - # If there are actually flags to add, pop out the old items - # in the dict and re-add them with the new name. - if flag_list: - try: - if 'dv' in flag_list: - self.var_data_all[new_key] = self.func_data_all.pop(item) - self.var_data_major[new_key] = self.func_data_major.pop(item) - - else: - self.func_data_all[new_key] = self.func_data_all.pop(item) - self.func_data_major[new_key] = self.func_data_major.pop(item) - - except KeyError: - pass - - -Opt = ReadOptHist(histList) -app = dash.Dash(__name__) -app.layout = \ - html.Div([ - html.Div(className="banner", children=[ - # Change App Name here - html.Div(className='container scalable', children=[ - # Change App Name here - html.H2(html.A( - 'MACH Dashboard', - style={ - 'text-decoration': 'none', - 'color': 'inherit' - } - )), - ]), - ]), - html.Div(id='body', className='container scalable', children=[ - html.Div(className='row', children=[ - html.Div( - className='ten columns', - style={ - 'min-width': '24.5%', - 'height': 'calc(100vh - 120px)', - 'margin-top': '5px', - - # Remove possibility to select the text for better UX - 'user-select': 'none', - '-moz-user-select': 'none', - '-webkit-user-select': 'none', - '-ms-user-select': 'none' - }, - children=[ - html.Div([ - dcc.Dropdown( - id='dvar', - options=[{'label': i, 'value': i} for i in Opt.var_data_all.keys()], - multi=True, - placeholder="Choose design group" - ), - ], style={'width': '50%', 'display': 'inline-block'}), - html.Div([ - dcc.Dropdown( - id='func', - options=[{'label': i, 'value': i} for i in Opt.func_data_all.keys()], - multi=True, - placeholder="Choose func group" - ), - ], style={'width': '50%', 'display': 'inline-block'}), - html.Div([ - dcc.Dropdown( - id='dvar-child', - multi=True, - placeholder="Choose design var" - ) - ], style={'width': '50%', 'display': 'inline-block'}), - html.Div( - dcc.Dropdown( - id='func-child', - multi=True, - placeholder="Choose func var" - ) - , style={'width': '50%', 'display': 'inline-block'}), - html.Div( - dcc.RadioItems( - id='axis_scale', - options=[ - {'label': 'linear', 'value': 'linear'}, - {'label': 'log', 'value': 'log'} - ], - value='linear', - labelStyle={'display': 'inline-block'} - ), style={'width': '50%', 'display': 'inline-block'} - ), - html.Div( - dcc.RadioItems( - id='scale_type', - options=[ - {'label': 'shared axes', 'value': 'shared'}, - {'label': 'multiple axes', 'value': 'multi'} - ], - value='shared', - labelStyle={'display': 'inline-block'} - ), style={'width': '50%', 'display': 'inline-block'} - ), - dcc.Graph( - id='2Dscatter' - ), - dcc.Interval( - id='interval-component', - interval=1 * 1000, # in milliseconds - n_intervals=0 - ), - html.Div(id="hidden-div", style={"display":"none"}) - ]) - ]) - ]) - ]) - -external_css = [ - # Normalize the CSS - "https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css", - # Fonts - "https://fonts.googleapis.com/css?family=Open+Sans|Roboto", - "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" -] - -for css in external_css: - app.css.append_css({"external_url": css}) - -app.config.supress_callback_exceptions = True - - -@app.callback( - dash.dependencies.Output('2Dscatter', 'figure'), - [dash.dependencies.Input('dvar-child', 'value'), - dash.dependencies.Input('func-child', 'value'), - dash.dependencies.Input('axis_scale', 'value'), - dash.dependencies.Input('scale_type', 'value'), - dash.dependencies.Input('hidden-div', 'value')] - ) -def update_2d_scatter(dvar, func, axisscale, type, n): - trace = [] - i = 0 - if dvar: - for var in dvar: - index = var.split('_')[-1] - varname = var[::-1].replace(index+'_', '',1)[::-1] - trace.append(go.Scatter( - x=range(Opt.num_iter), - y=[data[int(index)] for data in Opt.var_data[varname]], - name=var, - mode='lines+markers' - )) - i+=1 - - if func: - for var in func: - index = var.split('_')[-1] - varname = var[::-1].replace(index+'_', '', 1)[::-1] - trace.append(go.Scatter( - x=range(Opt.num_iter), - y=[data[int(index)] for data in Opt.func_data_all[varname]], - name=var, - mode='lines+markers', - )) - i+=1 - - fig={} - fig['layout'] = {} - if dvar or func: - if type=='multi': - fig = tools.make_subplots(rows=i,cols=1) - for k in range(i): - fig.append_trace(trace[k],k+1,1) - else: - fig['data'] = trace - - - fig['layout'].update( - xaxis={ - 'title': {'text': 'iterations', - 'font': { - 'family': 'Courier New, monospace', - 'size': 24, - 'color': '#7f7f7f' - }}, - 'type': axisscale, - }, - yaxis={ - 'title': {'text': 'Data', - 'font': { - 'family': 'Courier New, monospace', - 'size': 24, - 'color': '#7f7f7f' - }}, - 'type': axisscale, - }, - height=900, - showlegend=True - ) - - return (fig) - - -@app.callback( - dash.dependencies.Output('dvar-child', 'options'), - [dash.dependencies.Input('dvar', 'value')] -) -def update_dvar_child(dvar): - strlist = [] - if dvar: - for var in dvar: - num = len(Opt.var_data[var][0]) - strlist += [var + '_' + str(i) for i in range(num)] - return ( - [{'label': i, 'value': i} for i in strlist] - - ) - - -@app.callback( - dash.dependencies.Output('func-child', 'options'), - [dash.dependencies.Input('func', 'value')] -) -def update_func_child(func): - strlist = [] - if func: - for var in func: - num = len(Opt.func_data_all[var][0]) - strlist += [var + '_' + str(i) for i in range(num)] - - return ( - [{'label': i, 'value': i} for i in strlist] - - ) - -@app.callback( - dash.dependencies.Output('hidden-div', 'value'), - [dash.dependencies.Input('interval-component', 'n_intervals')] -) -def update_opt_history(n): - Opt.refresh_history() - return n - - -if __name__ == '__main__': - app.run_server(debug=True, port=50002, host='0.0.0.0') diff --git a/pyoptsparse/postprocessing/SNOPT_parse.py b/pyoptsparse/postprocessing/SNOPT_parse.py deleted file mode 100644 index b267f658f..000000000 --- a/pyoptsparse/postprocessing/SNOPT_parse.py +++ /dev/null @@ -1,62 +0,0 @@ -''' -This script parses the output of SNOPT Printout files. It extracts the optimality, feasibility and merit function for each major iteration, and writes a tecplot file that can be used for the generation of plots. - -Usage: run it as -python SNOPT_parse.py path_to_file - -If no filename is given, the default 'SNOPT_print.out' will be assumed. -''' - -import sys -import numpy as np - -if len(sys.argv) > 1: - file_name = sys.argv[1] -else: - file_name = 'SNOPT_print.out' - -# Values we want to extract -merit = [] -optimality = [] -feasibility = [] - -# Open file -f = open(file_name,'r') - -QP_line = " Itn QPmult QPstep nInf SumInf rgNorm QPobjective +SBS -SBS -BS Pivot L+U ncp nS condHz" -LP_line = " Itn LPmult LPstep nInf SumInf LPobjective +SBS -SBS -BS Pivot L+U ncp nS" -NP_line = " Itns Major Minors Step nCon Feasible Optimal MeritFunction L+U BSwap nS condHz Penalty" -EXIT_line = "SNOPTC EXIT" - -# Read all lines -read_next_line = False -for line in f: - - if EXIT_line in line: - break - - if QP_line in line or LP_line in line: - read_next_line = False - - if NP_line in line: - read_next_line = True - continue - - if read_next_line and len(line) > 100: - merit.append(float(line[55:68])) - optimality.append(float(line[46:53])) - feasibility.append(float(line[37:44])) - -# Close print file -f.close() - -# Now dump out the data into a tecplot file: -f = open("SNOPT.dat",'w') -iterations = np.arange(len(merit)) -f.write ('VARIABLES = "Iteration","Merit Function","Optimality","Feasibility",\n') -f.write('Zone T="SNOPT Data" I=%d\n'%(len(merit))) -f.write('DATAPACKING=POINT\n') -for i in range(len(merit)): - fea = max(feasibility[i],1e-6) - f.write('%f %f %f %f\n'%(iterations[i],merit[i],optimality[i],fea)) -f.close() \ No newline at end of file diff --git a/pyoptsparse/postprocessing/assets/base-styles.css b/pyoptsparse/postprocessing/assets/base-styles.css deleted file mode 100644 index 683afc327..000000000 --- a/pyoptsparse/postprocessing/assets/base-styles.css +++ /dev/null @@ -1,393 +0,0 @@ -/* Table of contents -–––––––––––––––––––––––––––––––––––––––––––––––––– -- Grid -- Base Styles -- Typography -- Links -- Buttons -- Forms -- Lists -- Code -- Tables -- Spacing -- Utilities -- Clearing -- Media Queries -*/ - - -/* Grid -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -.container { - position: relative; - width: 100%; - max-width: 960px; - margin: 0 auto; - padding: 0 20px; - box-sizing: border-box; } -.column, -.columns { - width: 100%; - float: left; - box-sizing: border-box; } - -/* For devices larger than 400px */ -@media (min-width: 400px) { - .container { - width: 85%; - padding: 0; } -} - -/* For devices larger than 550px */ -@media (min-width: 550px) { - .container { - width: 80%; } - .column, - .columns { - margin-left: 0.5%; } - .column:first-child, - .columns:first-child { - margin-left: 0; } - - .one.column, - .one.columns { width: 8%; } - .two.columns { width: 16.25%; } - .three.columns { width: 22%; } - .four.columns { width: 33%; } - .five.columns { width: 39.3333333333%; } - .six.columns { width: 49.75%; } - .seven.columns { width: 56.6666666667%; } - .eight.columns { width: 66.5%; } - .nine.columns { width: 74.0%; } - .ten.columns { width: 82.6666666667%; } - .eleven.columns { width: 91.5%; } - .twelve.columns { width: 100%; margin-left: 0; } - - .one-third.column { width: 30.6666666667%; } - .two-thirds.column { width: 65.3333333333%; } - - .one-half.column { width: 48%; } - - /* Offsets */ - .offset-by-one.column, - .offset-by-one.columns { margin-left: 8.66666666667%; } - .offset-by-two.column, - .offset-by-two.columns { margin-left: 17.3333333333%; } - .offset-by-three.column, - .offset-by-three.columns { margin-left: 26%; } - .offset-by-four.column, - .offset-by-four.columns { margin-left: 34.6666666667%; } - .offset-by-five.column, - .offset-by-five.columns { margin-left: 43.3333333333%; } - .offset-by-six.column, - .offset-by-six.columns { margin-left: 52%; } - .offset-by-seven.column, - .offset-by-seven.columns { margin-left: 60.6666666667%; } - .offset-by-eight.column, - .offset-by-eight.columns { margin-left: 69.3333333333%; } - .offset-by-nine.column, - .offset-by-nine.columns { margin-left: 78.0%; } - .offset-by-ten.column, - .offset-by-ten.columns { margin-left: 86.6666666667%; } - .offset-by-eleven.column, - .offset-by-eleven.columns { margin-left: 95.3333333333%; } - - .offset-by-one-third.column, - .offset-by-one-third.columns { margin-left: 34.6666666667%; } - .offset-by-two-thirds.column, - .offset-by-two-thirds.columns { margin-left: 69.3333333333%; } - - .offset-by-one-half.column, - .offset-by-one-half.columns { margin-left: 52%; } - -} - - -/* Base Styles -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -/* NOTE -html is set to 62.5% so that all the REM measurements throughout Skeleton -are based on 10px sizing. So basically 1.5rem = 15px :) */ -html { - font-size: 62.5%; } -body { - font-size: 1.5em; /* currently ems cause chrome bug misinterpreting rems on body element */ - line-height: 1.6; - font-weight: 400; - font-family: "Open Sans", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif; - color: rgb(50, 50, 50); } - - -/* Typography -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -h1, h2, h3, h4, h5, h6 { - margin-top: 0; - margin-bottom: 0; - font-weight: 300; } -h1 { font-size: 4.5rem; line-height: 1.2; letter-spacing: -.1rem; margin-bottom: 2rem; } -h2 { font-size: 3.6rem; line-height: 1.25; letter-spacing: -.1rem; margin-bottom: 1.8rem; margin-top: 1.8rem;} -h3 { font-size: 3.0rem; line-height: 1.3; letter-spacing: -.1rem; margin-bottom: 1.5rem; margin-top: 1.5rem;} -h4 { font-size: 2.6rem; line-height: 1.35; letter-spacing: -.08rem; margin-bottom: 1.2rem; margin-top: 1.2rem;} -h5 { font-size: 2.2rem; line-height: 1.5; letter-spacing: -.05rem; margin-bottom: 0.6rem; margin-top: 0.6rem;} -h6 { font-size: 2.0rem; line-height: 1.6; letter-spacing: 0; margin-bottom: 0.75rem; margin-top: 0.75rem;} - -p { - margin-top: 0; } - - -/* Blockquotes -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -blockquote { - border-left: 4px lightgrey solid; - padding-left: 1rem; - margin-top: 2rem; - margin-bottom: 2rem; - margin-left: 0rem; -} - - -/* Links -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -a { - color: #1EAEDB; } -a:hover { - color: #0FA0CE; } - - -/* Buttons -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -.button, -button, -input[type="submit"], -input[type="reset"], -input[type="button"] { - display: inline-block; - height: 38px; - padding: 0 30px; - color: #555; - text-align: center; - font-size: 11px; - font-weight: 600; - line-height: 38px; - letter-spacing: .1rem; - text-transform: uppercase; - text-decoration: none; - white-space: nowrap; - background-color: transparent; - border-radius: 4px; - border: 1px solid #bbb; - cursor: pointer; - box-sizing: border-box; } -.button:hover, -button:hover, -input[type="submit"]:hover, -input[type="reset"]:hover, -input[type="button"]:hover, -.button:focus, -button:focus, -input[type="submit"]:focus, -input[type="reset"]:focus, -input[type="button"]:focus { - color: #333; - border-color: #888; - outline: 0; } -.button.button-primary, -button.button-primary, -input[type="submit"].button-primary, -input[type="reset"].button-primary, -input[type="button"].button-primary { - color: #FFF; - background-color: #33C3F0; - border-color: #33C3F0; } -.button.button-primary:hover, -button.button-primary:hover, -input[type="submit"].button-primary:hover, -input[type="reset"].button-primary:hover, -input[type="button"].button-primary:hover, -.button.button-primary:focus, -button.button-primary:focus, -input[type="submit"].button-primary:focus, -input[type="reset"].button-primary:focus, -input[type="button"].button-primary:focus { - color: #FFF; - background-color: #1EAEDB; - border-color: #1EAEDB; } - - -/* Forms -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -input[type="email"], -input[type="number"], -input[type="search"], -input[type="text"], -input[type="tel"], -input[type="url"], -input[type="password"], -textarea, -select { - height: 38px; - padding: 6px 10px; /* The 6px vertically centers text on FF, ignored by Webkit */ - background-color: #fff; - border: 1px solid #D1D1D1; - border-radius: 4px; - box-shadow: none; - box-sizing: border-box; - font-family: inherit; - font-size: inherit; /*https://stackoverflow.com/questions/6080413/why-doesnt-input-inherit-the-font-from-body*/} -/* Removes awkward default styles on some inputs for iOS */ -input[type="email"], -input[type="number"], -input[type="search"], -input[type="text"], -input[type="tel"], -input[type="url"], -input[type="password"], -textarea { - -webkit-appearance: none; - -moz-appearance: none; - appearance: none; } -textarea { - min-height: 65px; - padding-top: 6px; - padding-bottom: 6px; } -input[type="email"]:focus, -input[type="number"]:focus, -input[type="search"]:focus, -input[type="text"]:focus, -input[type="tel"]:focus, -input[type="url"]:focus, -input[type="password"]:focus, -textarea:focus, -select:focus { - border: 1px solid #33C3F0; - outline: 0; } -label, -legend { - display: block; - margin-bottom: 0px; } -fieldset { - padding: 0; - border-width: 0; } -input[type="checkbox"], -input[type="radio"] { - display: inline; } -label > .label-body { - display: inline-block; - margin-left: .5rem; - font-weight: normal; } - - -/* Lists -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -ul { - list-style: circle inside; } -ol { - list-style: decimal inside; } -ol, ul { - padding-left: 0; - margin-top: 0; } -ul ul, -ul ol, -ol ol, -ol ul { - margin: 1.5rem 0 1.5rem 3rem; - font-size: 90%; } -li { - margin-bottom: 1rem; } - - -/* Tables -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -th, -td { - padding: 12px 15px; - text-align: left; - border-bottom: 1px solid #E1E1E1; } -th:first-child, -td:first-child { - padding-left: 0; } -th:last-child, -td:last-child { - padding-right: 0; } - - -/* Spacing -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -button, -.button { - margin-bottom: 0rem; } -input, -textarea, -select, -fieldset { - margin-bottom: 0rem; } -pre, -dl, -figure, -table, -form { - margin-bottom: 0rem; } -p, -ul, -ol { - margin-bottom: 0.75rem; } - -/* Utilities -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -.u-full-width { - width: 100%; - box-sizing: border-box; } -.u-max-full-width { - max-width: 100%; - box-sizing: border-box; } -.u-pull-right { - float: right; } -.u-pull-left { - float: left; } - - -/* Misc -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -hr { - margin-top: 3rem; - margin-bottom: 3.5rem; - border-width: 0; - border-top: 1px solid #E1E1E1; } - - -/* Clearing -–––––––––––––––––––––––––––––––––––––––––––––––––– */ - -/* Self Clearing Goodness */ -.container:after, -.row:after, -.u-cf { - content: ""; - display: table; - clear: both; } - - -/* Media Queries -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -/* -Note: The best way to structure the use of media queries is to create the queries -near the relevant code. For example, if you wanted to change the styles for buttons -on small devices, paste the mobile query code up in the buttons section and style it -there. -*/ - - -/* Larger than mobile */ -@media (min-width: 400px) {} - -/* Larger than phablet (also point when grid becomes active) */ -@media (min-width: 550px) {} - -/* Larger than tablet */ -@media (min-width: 750px) {} - -/* Larger than desktop */ -@media (min-width: 1000px) {} - -/* Larger than Desktop HD */ -@media (min-width: 1200px) {} \ No newline at end of file diff --git a/pyoptsparse/postprocessing/assets/custom-styles.css b/pyoptsparse/postprocessing/assets/custom-styles.css deleted file mode 100644 index 6d44ed720..000000000 --- a/pyoptsparse/postprocessing/assets/custom-styles.css +++ /dev/null @@ -1,45 +0,0 @@ -/* Table of contents -–––––––––––––––––––––––––––––––––––––––––––––––––– -- Banner -- Scalable Container -- Remove Undo - - -/* Banner -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -.banner { - height: 75px; - background-color: #BC2C2E; - padding-top: 0px; - padding-left: 0px; - padding-right: 0px; - width: 100%; - margin-bottom: 10px; -} - -.banner h2 { - color: white; - display: inline-block; - font-family: 'Open Sans', sans-serif; - font-size:4rem; - line-height:1; -} - -.banner Img { - position: relative; - float: right; - height: 75px; -} - -/* Scalable Container -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -.container.scalable { - width: 90%; - max-width: none; -} - -/* Remove Undo -–––––––––––––––––––––––––––––––––––––––––––––––––– */ -._dash-undo-redo { - display: none; -} diff --git a/pyoptsparse/postprocessing/opt_hist.hst b/pyoptsparse/postprocessing/opt_hist.hst deleted file mode 100644 index 0b43b34a7..000000000 Binary files a/pyoptsparse/postprocessing/opt_hist.hst and /dev/null differ diff --git a/pyoptsparse/postprocessing/view_saved_figure.py b/pyoptsparse/postprocessing/view_saved_figure.py deleted file mode 100644 index e533ac13c..000000000 --- a/pyoptsparse/postprocessing/view_saved_figure.py +++ /dev/null @@ -1,34 +0,0 @@ -import matplotlib -matplotlib.use('TkAgg') -from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg -import Tkinter as Tk -import matplotlib.pyplot as plt -import dill - -root = Tk.Tk() - -# Load figure from disk and display -fig = dill.load(open('saved_figure.pickle','rb')) - -''' -The above code loads in the figure that was saved in OptView. -fig is a matplotlib object that can be altered and saved like any -regular figure. -The code at the bottom renders the image for immediate display. -Add your specific plot formatting code as necessary below this comment -string but before the bottom code. -''' - -# Add customization code below -ax = fig.axes[0] -ax.set_title('Example title') -ax.set_ylabel('Example y-axis') - - -# Display the altered figure -canvas = FigureCanvasTkAgg(fig, master=root) -canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) -toolbar = NavigationToolbar2TkAgg(canvas, root) -toolbar.update() -canvas.show() -Tk.mainloop() diff --git a/pyoptsparse/pyoptsparse/__init__.py b/pyoptsparse/pyoptsparse/__init__.py deleted file mode 100644 index edd747009..000000000 --- a/pyoptsparse/pyoptsparse/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env python -from __future__ import absolute_import -from .sqlitedict.sqlitedict import SqliteDict -from .pyOpt_history import History -from .pyOpt_variable import Variable -from .pyOpt_gradient import Gradient -from .pyOpt_constraint import Constraint -from .pyOpt_objective import Objective -from .pyOpt_optimization import Optimization -from .pyOpt_optimizer import Optimizer -from .pyOpt_optimizer import OPT - -# Now import all the individual optimizers -from .pySNOPT.pySNOPT import SNOPT -from .pyIPOPT.pyIPOPT import IPOPT -from .pySLSQP.pySLSQP import SLSQP -from .pyCONMIN.pyCONMIN import CONMIN -#from .pyFSQP.pyFSQP import FSQP -from .pyPSQP.pyPSQP import PSQP -from .pyNLPQLP.pyNLPQLP import NLPQLP -from .pyNSGA2.pyNSGA2 import NSGA2 -from .pyNLPY_AUGLAG.pyNLPY_AUGLAG import NLPY_AUGLAG -from .pyALPSO.pyALPSO import ALPSO -# from .pyNOMAD.pyNOMAD import NOMAD -from .sqlitedict.sqlitedict import SqliteDict diff --git a/pyoptsparse/pyoptsparse/pyALPSO/LICENSE b/pyoptsparse/pyoptsparse/pyALPSO/LICENSE deleted file mode 100644 index f87e922fe..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/LICENSE +++ /dev/null @@ -1,708 +0,0 @@ -ALPSO - Augmented Lagrangian Particle Swarm Optimizer -Copyright (c) 2011, Dr. Ruben E. Perez (Ruben.Perez@rmc.ca) - and Peter W. Jansen (Peter.Jansen@rmc.ca) - -ALPSO is free software: you can redistribute it and/or modify it -under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - -Non-free versions of ALPSO are available under terms different -from those of the General Public License. For more information -related to such a license, future developments and/or technical -support, contact Dr. Ruben E. Perez (Ruben.Perez@rmc.ca) or -Peter W. Jansen (Peter.Jansen@rmc.ca). - -In addition, we kindly ask you to acknowledge the code authors in -any program, application or publication in which you use it. For -published works that use ALPSO we suggest referencing: - -P. Jansen and R. Perez, "Constrained Structural Design Optimization -via a Parallel Augmented Lagrangian Particle Swarm Optimization -Approach", International Journal of Computers and Structures, -Vol. 89, No. 13-14, pp. 1352–1366, 2011. - ----------------------------------------------------------------------- - - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/pyoptsparse/pyoptsparse/pyALPSO/README b/pyoptsparse/pyoptsparse/pyALPSO/README deleted file mode 100644 index 380907726..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/README +++ /dev/null @@ -1 +0,0 @@ -This directory contains the alpso class definition and source. diff --git a/pyoptsparse/pyoptsparse/pyALPSO/__init__.py b/pyoptsparse/pyoptsparse/pyALPSO/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyALPSO/alpso.py b/pyoptsparse/pyoptsparse/pyALPSO/alpso.py deleted file mode 100644 index 58a3dde6d..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/alpso.py +++ /dev/null @@ -1,1136 +0,0 @@ -#!/usr/bin/env python -""" -alpso - Python Version of the Augmented Lagrangian Particle Swarm Optimizer - -alpso if a global optimizer which solves problems of the form: - - min F(x) - - subject to: Gi(x) = 0, i = 1(1)ME - Gj(x) <= 0, j = ME+1(1)M - xLB <= x <= xUB - -Copyright (c) 2006-2011 by Dr. Ruben E. Perez and Mr. Peter Jansen -All rights reserved. Not to be used for commercial purposes. -Revision: 1.7 $Date: 04/03/2010 21:00$ - - -Developers: ------------ -- Dr. Ruben E. Perez (RP) -- Mr. Peter W. Jansen (PJ) - -History -------- - v. 1.2 - Initial Code Development in C (RP, 2006) - v. 1.3 - Initial Migration from C to Python (RP,PJ 2008) - v. 1.4 - Migration Bug Fixes (PJ, 2008) - v. 1.5 - Migration Running Version (PJ, 2008) - v. 1.6 - Migration Scaling Option (PJ, 2008) - - Removed lambda convergence citeria (PJ, 2009) - - Added Multiple x0s Input Functionality (PJ, 2010) - v. 1.7 - Added Neighbourhood option (PJ, 2010) -""" - -__version__ = '$Revision: $' - -''' -To Do: - - Migrate Inner Loop Printing Option - - Add Other Inertia and Velocity Updates to Inner Loop - - Fix Neighbourhood best from Lagrangian value -''' - -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os, sys, random, time -import pdb -from math import floor - -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy - -# ============================================================================= -# Extension modules -# ============================================================================= - - -# ============================================================================= -# Misc Definitions -# ============================================================================= -inf = 10.E+20 # define a value for infinity -# ============================================================================= -eps = 1.0 # define a value for machine precision -while (eps / 2.0 + 1.0) > 1.0: - eps /= 2.0 - -eps *= 2.0 - - -# eps = math.ldexp(1,-52) - - -# ============================================================================== -# alpso function -# ============================================================================== -def alpso(dimensions, constraints, neqcons, xtype, x0, xmin, xmax, swarmsize, nhn, - nhm, maxOutIter, maxInnIter, minInnIter, stopCriteria, stopIters, etol, - itol, rtol, atol, dtol, prtOutIter, prtInnIter, r0, vinit, vmax, c1, c2, w1, w2, - ns, nf, vcrazy, fileout, filename, logfile, hstfile, rseed, scale, nhs, objfunc): - """ - Python Version of the Augmented Lagrangian Particle Swarm Optimizer - - Documentation last updated: April. 29, 2008 - Ruben E. Perez - """ - - # - if x0 != []: - if isinstance(x0, list): - x0 = numpy.array(x0) - elif not isinstance(x0, numpy.ndarray): - print("""Warning: Initial x must be either list or numpy.array, - all initial positions randomly generated""") - - # - if hstfile is not None: - h_start = True - else: - h_start = False - - if logfile is not None: - sto_hst = True - else: - sto_hst = False - - # Set random number seed - rand = random.Random() - if rseed == {}: - rseed = time.time() - - rand.seed(rseed) - - # - if filename == '': - filename = 'ALPSO.out' - - ofname = '' - sfname = '' - fntmp = filename.split('.') - if len(fntmp) == 1: - ofname += fntmp[0] + '_print.out' - sfname += fntmp[0] + '_summary.out' - else: - if '/' not in fntmp[-1] and '\\' not in fntmp[-1]: - ofname += filename[:filename.rfind('.')] + '_print.' + fntmp[-1] - sfname += filename[:filename.rfind('.')] + '_summary.' + fntmp[-1] - else: - ofname += filename + '_print.out' - sfname += filename + '_summary.out' - - header = '' - header += ' ' * 37 + '======================\n' - header += ' ' * 39 + ' ALPSO 1.1 (Serial)\n' - header += ' ' * 37 + '======================\n\n' - header += 'Parameters:\n' - header += '-' * 97 + '\n' - if maxInnIter != minInnIter: - diI = 1 - else: - diI = 0 - - if x0 != []: - if len(x0.shape) == 1: - nxi = 1 - else: - nxi = x0.shape[0] - - else: - nxi = 0 - - header += 'Swarmsize :%9d' % swarmsize + ' MaxOuterIters :%9d' % maxOutIter + ' Seed:%26.8f\n' % rseed - header += 'Cognitive Parameter :%9.3f' % c1 + ' MaxInnerIters :%9d' % maxInnIter + ' Scaling :%11d\n' % scale - header += 'Social Parameter :%9.3f' % c2 + ' MinInnerIters :%9d' % minInnIter + ' Stopping Criteria :%11d\n' % stopCriteria - header += 'Initial Weight :%9.3f' % w1 + ' DynInnerIters :%9d' % diI + ' Number of Failures :%11d\n' % ns - header += 'Final Weight :%9.3f' % w2 + ' StoppingIters :%9d' % stopIters + ' Number of Successes:%11d\n\n' % nf - - header += 'Absolute Tolerance : %1.2e' % atol + ' Number Initial Pos:%9d' % nxi + ' Neighbourhood Model:%11s\n' % nhm - header += 'Relative Tolerance : %1.2e' % rtol + ' Initial Velocity :%9d' % vinit + ' Neighbourhood Size :%11d\n' % nhn - header += 'Inequality Tolerance: %1.2e' % itol + ' Maximum Velocity :%9d' % vmax + ' Selfless :%11d\n' % nhs - header += 'Equality Tolerance : %1.2e' % etol + ' Craziness Velocity: %1.2e' % vcrazy + ' Fileout :%11d\n' % fileout - header += 'Global Distance : %1.2e' % dtol + ' Initial Penalty :%9.2f' % r0 + ' File Name :%11s\n' % filename - header += '-' * 97 + '\n\n' - - if (fileout == 1) or (fileout == 3): - if os.path.isfile(ofname): - os.remove(ofname) - - ofile = open(ofname, 'w') - ofile.write(header) - - if (fileout == 2) or (fileout == 3): - if os.path.isfile(sfname): - os.remove(sfname) - - sfile = open(sfname, 'w') - sfile.write(header) - - # - dt = 1.0 - vlimit = vmax - vmax = numpy.ones(dimensions, float) * vmax - if scale == 1: - space_centre = numpy.zeros(dimensions, float) - space_halflen = numpy.zeros(dimensions, float) - for j in range(dimensions): - space_centre[j] = (xmin[j] + xmax[j]) / 2.0 - space_halflen[j] = ((xmax[j] - xmin[j]) / 2.0) - - xmin = -numpy.ones(dimensions, float) - xmax = numpy.ones(dimensions, float) - else: - for j in range(dimensions): - vmax[j] = ((xmax[j] - xmin[j]) / 2.0) * vlimit - - # Initialize the positions and velocities for entire population - x_k = numpy.zeros((swarmsize, dimensions), float) - v_k = numpy.zeros((swarmsize, dimensions), float) - discrete_i = [] - for i in range(swarmsize): - for j in range(dimensions): - x_k[i, j] = xmin[j] + rand.random() * (xmax[j] - xmin[j]) - if xtype[j] == 1: - discrete_i.append(j) - - v_k[i, j] = (xmin[j] + rand.random() * (xmax[j] - xmin[j])) / dt - - if x0 != []: - if len(x0.shape) == 1: - if scale == 1: - x_k[0, :] = (x0[:] - space_centre) / space_halflen - else: - x_k[0, :] = x0[:] - - else: - if x0.shape[0] > swarmsize: - print('Warning: %d initial positions specified for %d particles, last %d positions ignored' - % (x0.shape[0], swarmsize, x0.shape[0] - swarmsize)) - x0 = x0[0:swarmsize, :] - - for i in range(x0.shape[0]): - if scale == 1: - x_k[i, :] = (x0[i, :] - space_centre) / space_halflen - else: - x_k[i, :] = x0[i, :] - - # Initialize Augmented Lagrange - f = numpy.zeros(swarmsize, float) - L = numpy.zeros(swarmsize, float) - g = numpy.zeros([swarmsize, constraints], float) - g_old = numpy.zeros([swarmsize, constraints], float) - rp = numpy.ones(constraints, float) * r0 - lambda_val = numpy.zeros(constraints, float) - lambda_old = numpy.zeros(constraints, float) - tau = numpy.zeros([swarmsize, constraints], float) - tau_new = numpy.zeros(constraints, float) - tau_old = numpy.zeros(constraints, float) - nfevals = 0 - - if h_start: - [vals, hist_end] = hstfile.read([], ident=['obj', 'con']) - f = vals['obj'][0] - g = vals['con'][0].reshape(g.shape) - else: - for i in range(swarmsize): - - # Evaluate Ojective Function - if scale == 1: - xtmp = (x_k[i, :] * space_halflen) + space_centre - else: - xtmp = x_k[i, :] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - [f[i], g[i, :]] = objfunc(xtmp) - nfevals += 1 - - for i in range(swarmsize): - - # Augmented Lagrangian Value - L[i] = f[i] - if constraints > 0: - - # Equality Constraints - for l in range(neqcons): - tau[i, l] = g[i, l] - - # Inequality Constraints - for l in range(neqcons, constraints): - if rp[l] != 0: - if g[i, l] > -lambda_val[l] / (2 * rp[l]): - tau[i, l] = g[i, l] - else: - tau[i, l] = -lambda_val[l] / (2 * rp[l]) - - else: - tau[i, l] = g[i, l] - - # - for l in range(constraints): - L[i] += lambda_val[l] * tau[i, l] + rp[l] * tau[i, l] ** 2 - - # Initialize Particles Best - best_x = numpy.zeros((swarmsize, dimensions)) - best_L = numpy.zeros(swarmsize, float) - best_f = numpy.zeros(swarmsize, float) - best_g = numpy.zeros([swarmsize, constraints], float) - for i in range(swarmsize): - for j in range(dimensions): - best_x[i, j] = x_k[i, j] - - best_L[i] = L[i] - best_f[i] = f[i] - for l in range(constraints): - best_g[i, l] = g[i, l] - - # Initialize Swarm Best - swarm_i = L.argmin() - swarm_i_old = 0 - swarm_x = numpy.zeros(dimensions, float) - for j in range(dimensions): - swarm_x[j] = x_k[swarm_i, j] - - swarm_L = L[swarm_i] - swarm_L_old = L[0] - swarm_f = f[swarm_i] - swarm_f_old = f[0] - swarm_g = numpy.zeros(constraints, float) - swarm_g_old = numpy.zeros(constraints, float) - for l in range(constraints): - swarm_g[l] = g[swarm_i, l] - swarm_g_old[l] = g[0, l] - - # Initialize Neighbourhood - if (nhm == 'dlring') or (nhm == 'slring') or (nhm == 'wheel') or (nhm == 'spatial') or (nhm == 'sfrac'): - - nhps = [] - nhbest_L = numpy.ones(swarmsize) * inf - nhbest_f = numpy.zeros(swarmsize) - nhbest_x = numpy.zeros((swarmsize, dimensions)) - nhbest_i = numpy.zeros(swarmsize) - - if nhm == 'dlring': - for i in range(swarmsize): - nhps.append([]) - if nhs == 0: - nhps[i].append(i) - - for nb in range(1, (nhn / 2) + 1): - if i + nb >= swarmsize: - nhps[i].append(-1 + nb) - else: - nhps[i].append(i + nb) - - if i - nb < 0: - nhps[i].append(swarmsize + i - nb) - else: - nhps[i].append(i - nb) - - elif nhm == 'slring': - for i in range(swarmsize): - nhps.append([]) - if nhs == 0: - nhps[i].append(i) - - for nb in range(1, (nhn / 2) + 1): - if i + nb >= swarmsize: - nhps[i].append(-1 + nb) - else: - nhps[i].append(i + nb) - - if i - (nb * 2) < 0: - nhps[i].append(swarmsize + i - (nb * 2)) - else: - nhps[i].append(i - (nb * 2)) - - elif nhm == 'wheel': - nhps.append([]) - nhps[0].append(0) - for i in range(1, swarmsize): - nhps.append([]) - nhps[i].append(i) - nhps[i].append(0) - nhps[0].append(i) - - elif nhm == 'spatial': - pdist = numpy.ones((swarmsize, swarmsize)) * inf - for i in range(swarmsize): - for i2 in range(i + 1, swarmsize): - pdist[i, i2] = numpy.linalg.norm(x_k[i2, :] - x_k[i, :]) - - for i2 in range(i): - pdist[i, i2] = pdist[i2, i] - - for i in range(swarmsize): - nhps.append([]) - for nb in range(nhn): - nhps[i].append(pdist[i, :].argmin()) - pdist[i, nhps[i][nb]] = inf - - if nhs == 0: - nhps[i].append(i) - - elif nhm == 'sfrac': - pdist = numpy.zeros((swarmsize, swarmsize)) - d_max = numpy.zeros(swarmsize) - frac = 0.6 - for i in range(swarmsize): - for i2 in range(i + 1, swarmsize): - pdist[i, i2] = numpy.linalg.norm(x_k[i2, :] - x_k[i, :]) - - for i2 in range(i): - pdist[i, i2] = pdist[i2, i] - - for i in range(swarmsize): - nhps.append([]) - d_max[i] = pdist[i, :].max() - for i2 in range(swarmsize): - if i == i2: - if nhs == 1: - pass - else: - nhps[i].append(i) - - else: - if pdist[i, i2] / d_max[i] < frac: - nhps[i].append(i2) - - # Inizialize Neighbourhood Best - for i in range(swarmsize): - for nbp in nhps[i]: - if L[nbp] < nhbest_L[i]: - nhbest_L[i] = L[nbp] - nhbest_f[i] = f[nbp] - nhbest_x[i, :] = x_k[nbp, :] - nhbest_i[i] = nbp - - # Initialize stopping criteria distances - global_dist = 0 - for i in range(swarmsize): - dist = 0 - for j in range(dimensions): - dist += (x_k[i, j] - swarm_x[j]) ** 2 - - global_dist += dist ** 0.5 - - global_distance_reference = global_dist / swarmsize # relative extent of the swarm - - global_distance = numpy.zeros(stopIters, float) - global_L = numpy.zeros(stopIters, float) - for k in range(stopIters): - global_distance[k] = global_distance_reference - global_L[k] = swarm_L - - # Store History - if sto_hst: - logfile.write(rseed, 'seed') - if scale == 1: - x_uns = numpy.zeros(x_k.shape) - for i in range(swarmsize): - x_uns[i, :] = (x_k[i, :] * space_halflen) + space_centre - - else: - x_uns = x_k - - if discrete_i: - for i in range(swarmsize): - for m in discrete_i: - x_uns[i, m] = floor(x_uns[i, m] + 0.5) - - logfile.write(x_uns, 'x') - logfile.write(f, 'obj') - logfile.write(g, 'con') - logfile.write(swarm_x, 'gbest_x') - logfile.write(swarm_f, 'gbest_f') - logfile.write(swarm_g, 'gbest_g') - - # Output to Summary File - if (fileout == 2) or (fileout == 3): - stext = '' - stext += 'Global Best Particle:\n' - stext += '-' * 97 + '\n' - stext += ' Major Minor nFCon Violation(L2) Objective Lagrangian Rel Lagrangian Global Dist\n' - stext += '-' * 97 + '\n' - sfile.write(stext) - sfile.flush() - - # Outer optimization loop - k_out = 0 - stop_main_flag = 0 - no_successes = 0 - no_failures = 0 - rho = 1.0 - vcr = 0.0 - while (k_out < maxOutIter) and (stop_main_flag == 0): - - k_out += 1 - - # Update g_old Major Iteration - for i in range(swarmsize): - g_old[i, :] = g[i, :] - - # Inner optimization loop - core ALPSO algorithm applied to the lagrangian function - k_inn = 0 - stop_inner = 0 - while (k_inn < maxInnIter) and (stop_inner == 0): - - k_inn += 1 - - # calculating new search radius for the best particle ("Guaranteed Convergence" method) - if (swarm_i == swarm_i_old) and (swarm_L >= swarm_L_old): - no_failures += 1 - no_successes = 0 - elif (swarm_i == swarm_i_old) and (swarm_L < swarm_L_old): - no_successes += 1 - no_failures = 0 - else: - no_successes = 0 - no_failures = 0 - - if no_successes > ns: - rho *= 2.0 - no_successes = 0 - elif no_failures > nf: - rho *= 0.5 - no_failures = 0 - - if rho < 10e-5: - rho = 10e-5 - elif rho > 1.0: - rho = 1.0 - - # memorization for next outer iteration - if k_inn == 1: - swarm_i_old = swarm_i - swarm_L_old = swarm_L - swarm_f_old = swarm_f - swarm_g_old[:] = swarm_g[:] - - # stopping criteria distances - global_dist = 0 - for i in range(swarmsize): - dist = 0 - for j in range(dimensions): - dist += (x_k[i, j] - swarm_x[j]) ** 2 - - global_dist += dist ** 0.5 - - global_distance[0] = global_dist / swarmsize # relative extent of the swarm - - # Update inertia weight - w = w2 + ((w2 - w1) / global_distance_reference) * global_distance[1] - if w > w1: - w = w1 - elif w < w2: - w = w2 - - # Swarm Update - for i in range(swarmsize): - - # Update velocity vector - if (nhm == 'dlring') or (nhm == 'slring') or (nhm == 'wheel') or (nhm == 'spatial') or (nhm == 'sfrac'): - lbest_x = nhbest_x[i, :] - else: - lbest_x = swarm_x[:] - - for j in range(dimensions): - if i == swarm_i: - rr = rand.random() - v_k[i, j] = w * v_k[i, j] + -x_k[i, j] + swarm_x[j] + rho * (1.0 - 2.0 * rr) - else: - r1 = rand.random() - r2 = rand.random() - rc = rand.random() - - v_k[i, j] = w * v_k[i, j] + c1 * r1 * (best_x[i, j] - x_k[i, j]) / dt + c2 * r2 * ( - lbest_x[j] - x_k[i, j]) / dt + vcr * (1.0 - 2.0 * rc) - - # Check for velocity vector out of range - if v_k[i, j] > vmax[j]: - v_k[i, j] = vmax[j] - elif v_k[i, j] < -vmax[j]: - v_k[i, j] = -vmax[j] - - # positions update - x_k[i, j] += v_k[i, j] * dt - - # Check for positions out of range - if x_k[i, j] > xmax[j]: - x_k[i, j] = xmax[j] - elif x_k[i, j] < xmin[j]: - x_k[i, j] = xmin[j] - - # Augmented Lagrange - if h_start: - [vals, hist_end] = hstfile.read([], ident=['obj', 'con']) - if not hist_end: - f = vals['obj'][0] - g = vals['con'][0].reshape(g.shape) - else: - h_start = False - hstfile.close() - - if not h_start: - for i in range(swarmsize): - - # Evaluate Ojective Function - if scale == 1: - xtmp = (x_k[i, :] * space_halflen) + space_centre - else: - xtmp = x_k[i, :] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - [f[i], g[i, :]] = objfunc(xtmp) - nfevals += 1 - - # Store History - if sto_hst: - if scale == 1: - x_uns = numpy.zeros(x_k.shape) - for i in range(swarmsize): - x_uns[i, :] = (x_k[i, :] * space_halflen) + space_centre - - else: - x_uns = x_k - - if discrete_i: - for i in range(swarmsize): - for m in discrete_i: - x_uns[i, m] = floor(x_uns[i, m] + 0.5) - - logfile.write(x_uns, 'x') - logfile.write(f, 'obj') - logfile.write(g, 'con') - - for i in range(swarmsize): - - # Lagrangian Value - L[i] = f[i] - if constraints > 0: - - # Equality Constraints - for l in range(neqcons): - tau[i, l] = g[i, l] - - # Inequality Constraints - for l in range(neqcons, constraints): - if rp[l] != 0: - if g[i, l] > -lambda_val[l] / (2 * rp[l]): - tau[i, l] = g[i, l] - else: - tau[i, l] = -lambda_val[l] / (2 * rp[l]) - - else: - tau[i, l] = g[i, l] - - # - for l in range(constraints): - L[i] += lambda_val[l] * tau[i, l] + rp[l] * tau[i, l] ** 2 - - # If there is no new better solution for gbest keep the old best position - # if (L[swarm_i] > swarm_L): - # x_k[swarm_i,:] = swarm_x[:] - # f[swarm_i] = swarm_f - # g[swarm_i,:] = swarm_g[:] - # L[swarm_i] = swarm_L - - # Particle Best Update - for i in range(swarmsize): - if L[i] < best_L[i]: - best_L[i] = L[i] - best_f[i] = f[i] - best_g[i, :] = g[i, :] - best_x[i, :] = x_k[i, :] - - # Swarm Best Update - for i in range(swarmsize): - if L[i] < swarm_L: - # update of the best particle and best position - swarm_i = i - swarm_x[:] = x_k[i, :] - - # update of the best objective function value found - swarm_f = f[i] - - # update of the best constraints values found - swarm_g[:] = g[i, :] - - # update of the swarm best L - swarm_L = L[i] - - # Spatial Neighbourhood Update - if (nhm == 'spatial') or (nhm == 'sfrac'): - for i in range(swarmsize): - for i2 in range(i + 1, swarmsize): - pdist[i, i2] = numpy.linalg.norm(x_k[i2, :] - x_k[i, :]) - - for i2 in range(i): - pdist[i, i2] = pdist[i2, i] - - if nhm == 'spatial': - for i in range(swarmsize): - nhps[i] = [] - for nb in range(nhn): - nhps[i].append(pdist[i, :].argmin()) - pdist[i, nhps[i][nb]] = inf - - if nhs == 0: - nhps[i].append(i) - - else: - frac = ((3 * k_out) + 0.6 * maxOutIter) / maxOutIter - if frac >= 1.0: - nhm = 'gbest' - else: - for i in range(swarmsize): - nhps[i] = [] - d_max[i] = pdist[i, :].max() - for i2 in range(swarmsize): - if i == i2: - if nhs == 1: - pass - else: - nhps[i].append(i) - - else: - if pdist[i, i2] / d_max[i] < frac: - nhps[i].append(i2) - - # Neighbourhood Best Update - if (nhm == 'dlring') or (nhm == 'slring') or (nhm == 'wheel') or (nhm == 'spatial') or (nhm == 'sfrac'): - for i in range(swarmsize): - for nbp in nhps[i]: - if L[nbp] < nhbest_L[i]: - nhbest_L[i] = L[nbp] - nhbest_f[i] = f[nbp] - nhbest_x[i, :] = x_k[nbp, :] - nhbest_i[i] = nbp - - # Print Inner - if prtInnIter != 0 and numpy.mod(k_inn, prtInnIter) == 0: - # output to screen - print('Outer Iteration: %d [%d. Inner Iteration]' % (k_out, k_inn)) - - if (fileout == 1) or (fileout == 3): - # output to filename - pass - - # Inner Loop Convergence - if k_inn >= minInnIter: - if swarm_L < swarm_L_old: - stop_inner = 1 - - # Store History - if sto_hst: - logfile.write(swarm_x, 'gbest_x') - logfile.write(swarm_f, 'gbest_f') - logfile.write(swarm_g, 'gbest_g') - - # Print Outer - if prtOutIter != 0 and numpy.mod(k_out, prtOutIter) == 0: - # Output to screen - print("=" * 80 + "\n") - print("NUMBER OF ITERATIONS: %d\n" % k_out) - print("NUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - print("OBJECTIVE FUNCTION VALUE:") - print("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - print("EQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons): - print("\tH(%d) = %g" % (l, swarm_g[l])) - - # Inequality Constraints - print("\nINEQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons, constraints): - print("\tG(%d) = %g" % (l, swarm_g[l])) - - print("\nLAGRANGIAN MULTIPLIERS VALUES:") - for l in range(constraints): - print("\tL(%d) = %g" % (l, lambda_val[l])) - - print("\nBEST POSITION:") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - print(text) - print("=" * 80 + "\n") - - if (fileout == 1) or (fileout == 3): - # Output to Print File - ofile.write("\n" + "=" * 80 + "\n") - ofile.write("\nNUMBER OF ITERATIONS: %d\n" % k_out) - ofile.write("\nNUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - ofile.write("\nOBJECTIVE FUNCTION VALUE:\n") - ofile.write("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - ofile.write("\nEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons): - ofile.write("\tH(%d) = %.16g\n" % (l, swarm_g[l])) - - # Inequality Constraints - ofile.write("\nINEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons, constraints): - ofile.write("\tG(%d) = %.16g\n" % (l, swarm_g[l])) - - ofile.write("\nLAGRANGIAN MULTIPLIERS VALUES:\n") - for l in range(constraints): - ofile.write("\tL(%d) = %.16g\n" % (l, lambda_val[l])) - - ofile.write("\nPENALTY FACTOR:\n") - for l in range(constraints): - ofile.write("\trp(%d) = %.16g\n" % (l, rp[l])) - - ofile.write("\nBEST POSITION:\n") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - ofile.write(text) - ofile.write("\n" + "=" * 80 + "\n") - ofile.flush() - - # Store History - if sto_hst and (minInnIter != maxInnIter): - logfile.write(k_inn, 'ninner') - - # Test Constraint convergence - stop_con_num = 0 - infeas_con = [] - if constraints == 0: - stop_constraints_flag = 1 - else: - for l in range(neqcons): - if abs(swarm_g[l]) <= etol: - stop_con_num += 1 - else: - infeas_con.append(l) - - for l in range(neqcons, constraints): - if swarm_g[l] < itol: - stop_con_num += 1 - else: - infeas_con.append(l) - - if stop_con_num == constraints: - stop_constraints_flag = 1 - else: - stop_constraints_flag = 0 - - # # Test Lagrange multiplier convergence - # stop_lambda_flag = 0 - # if (constraints == 0): - # stop_lambda_flag = 1 - # else: - # for l in range(constraints): - # if (abs(lambda_val[l]-lambda_old[l]) <= ltol): - # stop_lambda_flag += 1 - # - # - # if (stop_lambda_flag==constraints): - # stop_lambda_flag = 1 - # else: - # stop_lambda_flag = 0 - # - # - # - - # Test Position and Function convergence - stop_criteria_flag = 0 - if stopCriteria == 1: - - # setting up the stopping criteria based on distance and tolerance - for k in range(stopIters - 1, 0, -1): - global_distance[k] = global_distance[k - 1] - global_L[k] = global_L[k - 1] - - # - global_dist = 0 - for i in range(swarmsize): - dist = 0 - for j in range(dimensions): - dist += (x_k[i, j] - swarm_x[j]) ** 2 - - global_dist += dist ** 0.5 - - global_distance[0] = global_dist / swarmsize # relative extent of the swarm - - # - global_L[0] = swarm_L - - # - if (abs(global_distance[0] - global_distance[stopIters - 1]) <= - dtol * abs(global_distance[stopIters - 1]) and - abs(global_L[0] - global_L[stopIters - 1]) <= rtol * abs(global_L[stopIters - 1]) or - abs(global_L[0] - global_L[stopIters - 1]) <= atol): - stop_criteria_flag = 1 - else: - stop_criteria_flag = 0 - - # Test Convergence - if stop_constraints_flag == 1 and stop_criteria_flag == 1: # and stop_lambda_flag == 1 - stop_main_flag = 1 - else: - stop_main_flag = 0 - - # Output to Summary File - if (fileout == 2) or (fileout == 3): - cvss = 0.0 - for l in infeas_con: - cvss += swarm_g[l] ** 2 - - cvL2 = cvss ** 0.5 - if stopCriteria == 1: - relL = abs(global_L[0] - global_L[stopIters - 1]) / abs(global_L[stopIters - 1]) - stext = '%9d%8d%8d%15.4e%15f%13.4e%16.4e%14.4e\n' % ( - k_out, k_inn, stop_con_num, cvL2, swarm_f, swarm_L, relL, global_distance[0]) - else: - stext = '%9d%8d%8d%15.4e%15f%13.4e%16s%14s\n' % ( - k_out, k_inn, stop_con_num, cvL2, swarm_f, swarm_L, 'NA', 'NA') - - sfile.write(stext) - sfile.flush() - - # Update Augmented Lagrangian Terms - if stop_main_flag == 0: - - if constraints > 0: - # Update new Tau - for l in range(neqcons): - tau_new[l] = swarm_g[l] - - for l in range(neqcons, constraints): - if swarm_g[l] > -lambda_val[l] / (2 * rp[l]): - tau_new[l] = swarm_g[l] - else: - tau_new[l] = -lambda_val[l] / (2 * rp[l]) - - # Update Lagrange Multiplier - for l in range(constraints): - lambda_old[l] = lambda_val[l] - lambda_val[l] += 2 * rp[l] * tau_new[l] - if abs(lambda_val[l]) < eps: - lambda_val[l] = 0.0 - - # Update Penalty Factor - for l in range(neqcons): - if abs(swarm_g[l]) > abs(swarm_g_old[l]) and abs(swarm_g[l]) > etol: - rp[l] *= 2.0 - elif abs(swarm_g[l]) <= etol: - rp[l] *= 0.5 - - for l in range(neqcons, constraints): - if swarm_g[l] > swarm_g_old[l] and swarm_g[l] > itol: - rp[l] *= 2.0 - elif swarm_g[l] <= itol: - rp[l] *= 0.5 - - # Apply Lower Bounds on rp - for l in range(neqcons): - if rp[l] < 0.5 * (abs(lambda_val[l]) / etol) ** 0.5: - rp[l] = 0.5 * (abs(lambda_val[l]) / etol) ** 0.5 - - for l in range(neqcons, constraints): - if rp[l] < 0.5 * (abs(lambda_val[l]) / itol) ** 0.5: - rp[l] = 0.5 * (abs(lambda_val[l]) / itol) ** 0.5 - - for l in range(constraints): - if rp[l] < 1: - rp[l] = 1 - - for i in range(swarmsize): - if constraints > 0: - # Update Tau - for l in range(neqcons): - tau[i, l] = g[i, l] - - for l in range(neqcons, constraints): - if g[i, l] > -lambda_val[l] / (2 * rp[l]): - tau[i, l] = g[i, l] - else: - tau[i, l] = -lambda_val[l] / (2 * rp[l]) - - # set craziness velocity for next inner loop run - vcr = (1 - k_out / maxOutIter) * vcrazy - - # update swarm with new Lagrangian function for next inner run - for i in range(swarmsize): - L[i] = f[i] - if constraints > 0: - for l in range(constraints): - L[i] += lambda_val[l] * tau[i, l] + rp[l] * tau[i, l] ** 2 - - swarm_L = L[swarm_i] - - swarm_L_old = swarm_f_old - if constraints > 0: - - # Equality Constraints - for l in range(neqcons): - tau_old[l] = swarm_g_old[l] - - # Inequality Constraints - for l in range(neqcons, constraints): - if rp[l] != 0: - if swarm_g_old[l] > -lambda_val[l] / (2 * rp[l]): - tau_old[l] = swarm_g_old[l] - else: - tau_old[l] = -lambda_val[l] / (2 * rp[l]) - - else: - tau_old[l] = swarm_g_old[l] - - # - for l in range(constraints): - swarm_L_old += lambda_val[l] * tau_old[l] + rp[l] * tau_old[l] ** 2 - - # reset swarm memory for next inner run - for i in range(swarmsize): - best_L[i] = L[i] - best_f[i] = f[i] - best_g[i, :] = g[i, :] - best_x[i, :] = x_k[i, :] - - # Print Results - if prtOutIter != 0: - # Output to screen - print("=" * 80 + "\n") - print("RANDOM SEED VALUE: %.8f\n" % rseed) - print("NUMBER OF ITERATIONS: %d\n" % k_out) - print("NUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - print("OBJECTIVE FUNCTION VALUE:") - print("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - print("EQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons): - print("\tH(%d) = %g" % (l, swarm_g[l])) - - # Inequality Constraints - print("\nINEQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons, constraints): - print("\tG(%d) = %g" % (l, swarm_g[l])) - - print("\nLAGRANGIAN MULTIPLIERS VALUES:") - for l in range(constraints): - print("\tL(%d) = %g" % (l, float(lambda_val[l]))) - - print("\nBEST POSITION:") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - print(text) - print("=" * 80 + "\n") - - if (fileout == 1) or (fileout == 3): - ofile.close() - - if (fileout == 2) or (fileout == 3): - # Output to Summary - sfile.write("\n\nSolution:") - sfile.write("\n" + "=" * 94 + "\n") - sfile.write("\nNUMBER OF ITERATIONS: %d\n" % k_out) - sfile.write("\nNUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - sfile.write("\nOBJECTIVE FUNCTION VALUE:\n") - sfile.write("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - sfile.write("\nEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons): - sfile.write("\tH(%d) = %.16g\n" % (l, swarm_g[l])) - - # Inequality Constraints - sfile.write("\nINEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons, constraints): - sfile.write("\tG(%d) = %.16g\n" % (l, swarm_g[l])) - - sfile.write("\nLAGRANGIAN MULTIPLIERS VALUES:\n") - for l in range(constraints): - sfile.write("\tL(%d) = %.16g\n" % (l, float(lambda_val[l]))) - - sfile.write("\nPENALTY FACTOR:\n") - for l in range(constraints): - sfile.write("\trp(%d) = %.16g\n" % (l, rp[l])) - - sfile.write("\nBEST POSITION:\n") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - sfile.write(text) - sfile.write("\n" + "=" * 94 + "\n") - sfile.flush() - sfile.close() - - # Results - if scale == 1: - opt_x = (swarm_x * space_halflen) + space_centre - else: - opt_x = swarm_x - - for m in discrete_i: - opt_x[m] = int(floor(opt_x[m] + 0.5)) - - opt_f = swarm_f - opt_g = swarm_g - opt_lambda = lambda_val[:] - - return opt_x, opt_f, opt_g, opt_lambda, nfevals, '%.8f' % rseed diff --git a/pyoptsparse/pyoptsparse/pyALPSO/alpso_ext.py b/pyoptsparse/pyoptsparse/pyALPSO/alpso_ext.py deleted file mode 100644 index 36c23ce69..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/alpso_ext.py +++ /dev/null @@ -1,1132 +0,0 @@ -#!/usr/bin/env python -""" -alpso - Python Version of the Augmented Lagrangian Particle Swarm Optimizer - -alpso if a global optimizer which solves problems of the form: - - min F(x) - - subject to: Gi(x) = 0, i = 1(1)ME - Gj(x) <= 0, j = ME+1(1)M - xLB <= x <= xUB - -Copyright (c) 2006-2011 by Dr. Ruben E. Perez and Mr. Peter Jansen -All rights reserved. Not to be used for commercial purposes. -Revision: 1.7 $Date: 04/03/2010 21:00$ - - -Developers: ------------ -- Dr. Ruben E. Perez (RP) -- Mr. Peter W. Jansen (PJ) - -History -------- - v. 1.2 - Initial Code Development in C (RP, 2006) - v. 1.3 - Initial Migration from C to Python (RP,PJ 2008) - v. 1.4 - Migration Bug Fixes (PJ, 2008) - v. 1.5 - Migration Running Version (PJ, 2008) - v. 1.6 - Migration Scaling Option (PJ, 2008) - - Removed lambda convergence citeria (PJ, 2009) - - Added Multiple x0s Input Functionality (PJ, 2010) - v. 1.7 - Added Neighbourhood option (PJ, 2010) -""" - -__version__ = '$Revision: $' - -''' -To Do: - - Migrate Inner Loop Printing Option - - Add Other Inertia and Velocity Updates to Inner Loop - - Fix Neighbourhood best from Lagrangian value -''' - -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os, sys, random, time -import pdb -from math import floor - -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy - -# ============================================================================= -# Extension modules -# ============================================================================= - - -# ============================================================================= -# Misc Definitions -# ============================================================================= -inf = 10.E+20 # define a value for infinity -# ============================================================================= -eps = 1.0 # define a value for machine precision -while (eps / 2.0 + 1.0) > 1.0: - eps /= 2.0 - -eps *= 2.0 - - -# eps = math.ldexp(1,-52) - - -# ============================================================================== -# alpso function -# ============================================================================== -def alpso(dimensions, constraints, neqcons, xtype, x0, xmin, xmax, swarmsize, nhn, - nhm, maxOutIter, maxInnIter, minInnIter, stopCriteria, stopIters, etol, - itol, rtol, atol, dtol, prtOutIter, prtInnIter, r0, vinit, vmax, c1, c2, w1, w2, - ns, nf, vcrazy, fileout, filename, logfile, hstfile, rseed, scale, nhs, objfunc): - """ - Python Version of the Augmented Lagrangian Particle Swarm Optimizer - - Documentation last updated: April. 29, 2008 - Ruben E. Perez - """ - - # - if x0 != []: - if isinstance(x0, list): - x0 = numpy.array(x0) - elif not isinstance(x0, numpy.ndarray): - print("""Warning: Initial x must be either list or numpy.array, - all initial positions randomly generated""") - - # - if hstfile is not None: - h_start = True - else: - h_start = False - - if logfile is not None: - sto_hst = True - else: - sto_hst = False - - # Set random number seed - rand = random.Random() - if rseed == {}: - rseed = time.time() - - rand.seed(rseed) - - # - if filename == '': - filename = 'ALPSO.out' - - ofname = '' - sfname = '' - fntmp = filename.split('.') - if len(fntmp) == 1: - ofname += fntmp[0] + '_print.out' - sfname += fntmp[0] + '_summary.out' - else: - if '/' not in fntmp[-1] and '\\' not in fntmp[-1]: - ofname += filename[:filename.rfind('.')] + '_print.' + fntmp[-1] - sfname += filename[:filename.rfind('.')] + '_summary.' + fntmp[-1] - else: - ofname += filename + '_print.out' - sfname += filename + '_summary.out' - - header = '' - header += ' ' * 37 + '======================\n' - header += ' ' * 39 + ' ALPSO 1.1 (Bulk)\n' - header += ' ' * 37 + '======================\n\n' - header += 'Parameters:\n' - header += '-' * 97 + '\n' - if maxInnIter != minInnIter: - diI = 1 - else: - diI = 0 - - if x0 != []: - if len(x0.shape) == 1: - nxi = 1 - else: - nxi = x0.shape[0] - - else: - nxi = 0 - - header += 'Swarmsize :%9d' % swarmsize + ' MaxOuterIters :%9d' % maxOutIter + ' Seed:%26.8f\n' % rseed - header += 'Cognitive Parameter :%9.3f' % c1 + ' MaxInnerIters :%9d' % maxInnIter + ' Scaling :%11d\n' % scale - header += 'Social Parameter :%9.3f' % c2 + ' MinInnerIters :%9d' % minInnIter + ' Stopping Criteria :%11d\n' % stopCriteria - header += 'Initial Weight :%9.3f' % w1 + ' DynInnerIters :%9d' % diI + ' Number of Failures :%11d\n' % ns - header += 'Final Weight :%9.3f' % w2 + ' StoppingIters :%9d' % stopIters + ' Number of Successes:%11d\n\n' % nf - - header += 'Absolute Tolerance : %1.2e' % atol + ' Number Initial Pos:%9d' % nxi + ' Neighbourhood Model:%11s\n' % nhm - header += 'Relative Tolerance : %1.2e' % rtol + ' Initial Velocity :%9d' % vinit + ' Neighbourhood Size :%11d\n' % nhn - header += 'Inequality Tolerance: %1.2e' % itol + ' Maximum Velocity :%9d' % vmax + ' Selfless :%11d\n' % nhs - header += 'Equality Tolerance : %1.2e' % etol + ' Craziness Velocity: %1.2e' % vcrazy + ' Fileout :%11d\n' % fileout - header += 'Global Distance : %1.2e' % dtol + ' Initial Penalty :%9.2f' % r0 + ' File Name :%11s\n' % filename - header += '-' * 97 + '\n\n' - - if (fileout == 1) or (fileout == 3): - if os.path.isfile(ofname): - os.remove(ofname) - - ofile = open(ofname, 'w') - ofile.write(header) - - if (fileout == 2) or (fileout == 3): - if os.path.isfile(sfname): - os.remove(sfname) - - sfile = open(sfname, 'w') - sfile.write(header) - - # - dt = 1.0 - vlimit = vmax - vmax = numpy.ones(dimensions, float) * vmax - if scale == 1: - space_centre = numpy.zeros(dimensions, float) - space_halflen = numpy.zeros(dimensions, float) - for j in range(dimensions): - space_centre[j] = (xmin[j] + xmax[j]) / 2.0 - space_halflen[j] = ((xmax[j] - xmin[j]) / 2.0) - - xmin = -numpy.ones(dimensions, float) - xmax = numpy.ones(dimensions, float) - else: - for j in range(dimensions): - vmax[j] = ((xmax[j] - xmin[j]) / 2.0) * vlimit - - # Initialize the positions and velocities for entire population - x_k = numpy.zeros((swarmsize, dimensions), float) - v_k = numpy.zeros((swarmsize, dimensions), float) - discrete_i = [] - for i in range(swarmsize): - for j in range(dimensions): - x_k[i, j] = xmin[j] + rand.random() * (xmax[j] - xmin[j]) - if xtype[j] == 1: - discrete_i.append(j) - - v_k[i, j] = (xmin[j] + rand.random() * (xmax[j] - xmin[j])) / dt - - if x0 != []: - if len(x0.shape) == 1: - if scale == 1: - x_k[0, :] = (x0[:] - space_centre) / space_halflen - else: - x_k[0, :] = x0[:] - - else: - if x0.shape[0] > swarmsize: - print('Warning: %d initial positions specified for %d particles, last %d positions ignored' - % (x0.shape[0], swarmsize, x0.shape[0] - swarmsize)) - x0 = x0[0:swarmsize, :] - - for i in range(x0.shape[0]): - if scale == 1: - x_k[i, :] = (x0[i, :] - space_centre) / space_halflen - else: - x_k[i, :] = x0[i, :] - - # Initialize Augmented Lagrange - f = numpy.zeros(swarmsize, float) - L = numpy.zeros(swarmsize, float) - g = numpy.zeros([swarmsize, constraints], float) - g_old = numpy.zeros([swarmsize, constraints], float) - rp = numpy.ones(constraints, float) * r0 - lambda_val = numpy.zeros(constraints, float) - lambda_old = numpy.zeros(constraints, float) - tau = numpy.zeros([swarmsize, constraints], float) - tau_new = numpy.zeros(constraints, float) - tau_old = numpy.zeros(constraints, float) - nfevals = 0 - - if h_start: - [vals, hist_end] = hstfile.read([], ident=['obj', 'con']) - f = vals['obj'][0] - g = vals['con'][0].reshape(g.shape) - else: - # Evaluate Objective Function - if scale == 1: - xtmp = (x_k * space_halflen) + space_centre - else: - xtmp = x_k - - for m in discrete_i: - xtmp[:, m] = floor(xtmp[:, m] + .5) - - f, g = objfunc(xtmp) - nfevals += swarmsize - - for i in range(swarmsize): - - # Augmented Lagrangian Value - L[i] = f[i] - if constraints > 0: - - # Equality Constraints - for l in range(neqcons): - tau[i, l] = g[i, l] - - # Inequality Constraints - for l in range(neqcons, constraints): - if rp[l] != 0: - if g[i, l] > -lambda_val[l] / (2 * rp[l]): - tau[i, l] = g[i, l] - else: - tau[i, l] = -lambda_val[l] / (2 * rp[l]) - - else: - tau[i, l] = g[i, l] - - # - for l in range(constraints): - L[i] += lambda_val[l] * tau[i, l] + rp[l] * tau[i, l] ** 2 - - # Initialize Particles Best - best_x = numpy.zeros((swarmsize, dimensions)) - best_L = numpy.zeros(swarmsize, float) - best_f = numpy.zeros(swarmsize, float) - best_g = numpy.zeros([swarmsize, constraints], float) - for i in range(swarmsize): - for j in range(dimensions): - best_x[i, j] = x_k[i, j] - - best_L[i] = L[i] - best_f[i] = f[i] - for l in range(constraints): - best_g[i, l] = g[i, l] - - # Initialize Swarm Best - swarm_i = L.argmin() - swarm_i_old = 0 - swarm_x = numpy.zeros(dimensions, float) - for j in range(dimensions): - swarm_x[j] = x_k[swarm_i, j] - - swarm_L = L[swarm_i] - swarm_L_old = L[0] - swarm_f = f[swarm_i] - swarm_f_old = f[0] - swarm_g = numpy.zeros(constraints, float) - swarm_g_old = numpy.zeros(constraints, float) - for l in range(constraints): - swarm_g[l] = g[swarm_i, l] - swarm_g_old[l] = g[0, l] - - # Initialize Neighbourhood - if (nhm == 'dlring') or (nhm == 'slring') or (nhm == 'wheel') or (nhm == 'spatial') or (nhm == 'sfrac'): - - nhps = [] - nhbest_L = numpy.ones(swarmsize) * inf - nhbest_f = numpy.zeros(swarmsize) - nhbest_x = numpy.zeros((swarmsize, dimensions)) - nhbest_i = numpy.zeros(swarmsize) - - if nhm == 'dlring': - for i in range(swarmsize): - nhps.append([]) - if nhs == 0: - nhps[i].append(i) - - for nb in range(1, (nhn / 2) + 1): - if i + nb >= swarmsize: - nhps[i].append(-1 + nb) - else: - nhps[i].append(i + nb) - - if i - nb < 0: - nhps[i].append(swarmsize + i - nb) - else: - nhps[i].append(i - nb) - - elif nhm == 'slring': - for i in range(swarmsize): - nhps.append([]) - if nhs == 0: - nhps[i].append(i) - - for nb in range(1, (nhn / 2) + 1): - if i + nb >= swarmsize: - nhps[i].append(-1 + nb) - else: - nhps[i].append(i + nb) - - if i - (nb * 2) < 0: - nhps[i].append(swarmsize + i - (nb * 2)) - else: - nhps[i].append(i - (nb * 2)) - - elif nhm == 'wheel': - nhps.append([]) - nhps[0].append(0) - for i in range(1, swarmsize): - nhps.append([]) - nhps[i].append(i) - nhps[i].append(0) - nhps[0].append(i) - - elif nhm == 'spatial': - pdist = numpy.ones((swarmsize, swarmsize)) * inf - for i in range(swarmsize): - for i2 in range(i + 1, swarmsize): - pdist[i, i2] = numpy.linalg.norm(x_k[i2, :] - x_k[i, :]) - - for i2 in range(i): - pdist[i, i2] = pdist[i2, i] - - for i in range(swarmsize): - nhps.append([]) - for nb in range(nhn): - nhps[i].append(pdist[i, :].argmin()) - pdist[i, nhps[i][nb]] = inf - - if nhs == 0: - nhps[i].append(i) - - elif nhm == 'sfrac': - pdist = numpy.zeros((swarmsize, swarmsize)) - d_max = numpy.zeros(swarmsize) - frac = 0.6 - for i in range(swarmsize): - for i2 in range(i + 1, swarmsize): - pdist[i, i2] = numpy.linalg.norm(x_k[i2, :] - x_k[i, :]) - - for i2 in range(i): - pdist[i, i2] = pdist[i2, i] - - for i in range(swarmsize): - nhps.append([]) - d_max[i] = pdist[i, :].max() - for i2 in range(swarmsize): - if i == i2: - if nhs == 1: - pass - else: - nhps[i].append(i) - - else: - if pdist[i, i2] / d_max[i] < frac: - nhps[i].append(i2) - - # Inizialize Neighbourhood Best - for i in range(swarmsize): - for nbp in nhps[i]: - if L[nbp] < nhbest_L[i]: - nhbest_L[i] = L[nbp] - nhbest_f[i] = f[nbp] - nhbest_x[i, :] = x_k[nbp, :] - nhbest_i[i] = nbp - - # Initialize stopping criteria distances - global_dist = 0 - for i in range(swarmsize): - dist = 0 - for j in range(dimensions): - dist += (x_k[i, j] - swarm_x[j]) ** 2 - - global_dist += dist ** 0.5 - - global_distance_reference = global_dist / swarmsize # relative extent of the swarm - - global_distance = numpy.zeros(stopIters, float) - global_L = numpy.zeros(stopIters, float) - for k in range(stopIters): - global_distance[k] = global_distance_reference - global_L[k] = swarm_L - - # Store History - if sto_hst: - logfile.write(rseed, 'seed') - if scale == 1: - x_uns = numpy.zeros(x_k.shape) - for i in range(swarmsize): - x_uns[i, :] = (x_k[i, :] * space_halflen) + space_centre - - else: - x_uns = x_k - - if discrete_i: - for i in range(swarmsize): - for m in discrete_i: - x_uns[i, m] = floor(x_uns[i, m] + 0.5) - - logfile.write(x_uns, 'x') - logfile.write(f, 'obj') - logfile.write(g, 'con') - logfile.write(swarm_x, 'gbest_x') - logfile.write(swarm_f, 'gbest_f') - logfile.write(swarm_g, 'gbest_g') - - # Output to Summary File - if (fileout == 2) or (fileout == 3): - stext = '' - stext += 'Global Best Particle:\n' - stext += '-' * 97 + '\n' - stext += ' Major Minor nFCon Violation(L2) Objective Lagrangian Rel Lagrangian Global Dist\n' - stext += '-' * 97 + '\n' - sfile.write(stext) - sfile.flush() - - # Outer optimization loop - k_out = 0 - stop_main_flag = 0 - no_successes = 0 - no_failures = 0 - rho = 1.0 - vcr = 0.0 - while (k_out < maxOutIter) and (stop_main_flag == 0): - - k_out += 1 - - # Update g_old Major Iteration - for i in range(swarmsize): - g_old[i, :] = g[i, :] - - # Inner optimization loop - core ALPSO algorithm applied to the lagrangian function - k_inn = 0 - stop_inner = 0 - while (k_inn < maxInnIter) and (stop_inner == 0): - - k_inn += 1 - - # calculating new search radius for the best particle ("Guaranteed Convergence" method) - if (swarm_i == swarm_i_old) and (swarm_L >= swarm_L_old): - no_failures += 1 - no_successes = 0 - elif (swarm_i == swarm_i_old) and (swarm_L < swarm_L_old): - no_successes += 1 - no_failures = 0 - else: - no_successes = 0 - no_failures = 0 - - if no_successes > ns: - rho *= 2.0 - no_successes = 0 - elif no_failures > nf: - rho *= 0.5 - no_failures = 0 - - if rho < 10e-5: - rho = 10e-5 - elif rho > 1.0: - rho = 1.0 - - # memorization for next outer iteration - if k_inn == 1: - swarm_i_old = swarm_i - swarm_L_old = swarm_L - swarm_f_old = swarm_f - swarm_g_old[:] = swarm_g[:] - - # stopping criteria distances - global_dist = 0 - for i in range(swarmsize): - dist = 0 - for j in range(dimensions): - dist += (x_k[i, j] - swarm_x[j]) ** 2 - - global_dist += dist ** 0.5 - - global_distance[0] = global_dist / swarmsize # relative extent of the swarm - - # Update inertia weight - w = w2 + ((w2 - w1) / global_distance_reference) * global_distance[1] - if w > w1: - w = w1 - elif w < w2: - w = w2 - - # Swarm Update - for i in range(swarmsize): - - # Update velocity vector - if (nhm == 'dlring') or (nhm == 'slring') or (nhm == 'wheel') or (nhm == 'spatial') or (nhm == 'sfrac'): - lbest_x = nhbest_x[i, :] - else: - lbest_x = swarm_x[:] - - for j in range(dimensions): - if i == swarm_i: - rr = rand.random() - v_k[i, j] = w * v_k[i, j] + -x_k[i, j] + swarm_x[j] + rho * (1.0 - 2.0 * rr) - else: - r1 = rand.random() - r2 = rand.random() - rc = rand.random() - - v_k[i, j] = w * v_k[i, j] + c1 * r1 * (best_x[i, j] - x_k[i, j]) / dt + c2 * r2 * ( - lbest_x[j] - x_k[i, j]) / dt + vcr * (1.0 - 2.0 * rc) - - # Check for velocity vector out of range - if v_k[i, j] > vmax[j]: - v_k[i, j] = vmax[j] - elif v_k[i, j] < -vmax[j]: - v_k[i, j] = -vmax[j] - - # positions update - x_k[i, j] += v_k[i, j] * dt - - # Check for positions out of range - if x_k[i, j] > xmax[j]: - x_k[i, j] = xmax[j] - elif x_k[i, j] < xmin[j]: - x_k[i, j] = xmin[j] - - # Augmented Lagrange - if h_start: - [vals, hist_end] = hstfile.read([], ident=['obj', 'con']) - if not hist_end: - f = vals['obj'][0] - g = vals['con'][0].reshape(g.shape) - else: - h_start = False - hstfile.close() - - if not h_start: - # Evaluate Objective Function - if scale == 1: - xtmp = (x_k * space_halflen) + space_centre - else: - xtmp = x_k - - for m in discrete_i: - xtmp[:, m] = floor(xtmp[:, m] + .5) - - f, g = objfunc(xtmp) - nfevals += swarmsize - - # Store History - if sto_hst: - if scale == 1: - x_uns = numpy.zeros(x_k.shape) - for i in range(swarmsize): - x_uns[i, :] = (x_k[i, :] * space_halflen) + space_centre - - else: - x_uns = x_k - - if discrete_i: - for i in range(swarmsize): - for m in discrete_i: - x_uns[i, m] = floor(x_uns[i, m] + 0.5) - - logfile.write(x_uns, 'x') - logfile.write(f, 'obj') - logfile.write(g, 'con') - - for i in range(swarmsize): - - # Lagrangian Value - L[i] = f[i] - if constraints > 0: - - # Equality Constraints - for l in range(neqcons): - tau[i, l] = g[i, l] - - # Inequality Constraints - for l in range(neqcons, constraints): - if rp[l] != 0: - if g[i, l] > -lambda_val[l] / (2 * rp[l]): - tau[i, l] = g[i, l] - else: - tau[i, l] = -lambda_val[l] / (2 * rp[l]) - - else: - tau[i, l] = g[i, l] - - # - for l in range(constraints): - L[i] += lambda_val[l] * tau[i, l] + rp[l] * tau[i, l] ** 2 - - # If there is no new better solution for gbest keep the old best position - # if (L[swarm_i] > swarm_L): - # x_k[swarm_i,:] = swarm_x[:] - # f[swarm_i] = swarm_f - # g[swarm_i,:] = swarm_g[:] - # L[swarm_i] = swarm_L - - # Particle Best Update - for i in range(swarmsize): - if L[i] < best_L[i]: - best_L[i] = L[i] - best_f[i] = f[i] - best_g[i, :] = g[i, :] - best_x[i, :] = x_k[i, :] - - # Swarm Best Update - for i in range(swarmsize): - if L[i] < swarm_L: - # update of the best particle and best position - swarm_i = i - swarm_x[:] = x_k[i, :] - - # update of the best objective function value found - swarm_f = f[i] - - # update of the best constraints values found - swarm_g[:] = g[i, :] - - # update of the swarm best L - swarm_L = L[i] - - # Spatial Neighbourhood Update - if (nhm == 'spatial') or (nhm == 'sfrac'): - for i in range(swarmsize): - for i2 in range(i + 1, swarmsize): - pdist[i, i2] = numpy.linalg.norm(x_k[i2, :] - x_k[i, :]) - - for i2 in range(i): - pdist[i, i2] = pdist[i2, i] - - if nhm == 'spatial': - for i in range(swarmsize): - nhps[i] = [] - for nb in range(nhn): - nhps[i].append(pdist[i, :].argmin()) - pdist[i, nhps[i][nb]] = inf - - if nhs == 0: - nhps[i].append(i) - - else: - frac = ((3 * k_out) + 0.6 * maxOutIter) / maxOutIter - if frac >= 1.0: - nhm = 'gbest' - else: - for i in range(swarmsize): - nhps[i] = [] - d_max[i] = pdist[i, :].max() - for i2 in range(swarmsize): - if i == i2: - if nhs == 1: - pass - else: - nhps[i].append(i) - - else: - if pdist[i, i2] / d_max[i] < frac: - nhps[i].append(i2) - - # Neighbourhood Best Update - if (nhm == 'dlring') or (nhm == 'slring') or (nhm == 'wheel') or (nhm == 'spatial') or (nhm == 'sfrac'): - for i in range(swarmsize): - for nbp in nhps[i]: - if L[nbp] < nhbest_L[i]: - nhbest_L[i] = L[nbp] - nhbest_f[i] = f[nbp] - nhbest_x[i, :] = x_k[nbp, :] - nhbest_i[i] = nbp - - # Print Inner - if prtInnIter != 0 and numpy.mod(k_inn, prtInnIter) == 0: - # output to screen - print('Outer Iteration: %d [%d. Inner Iteration]' % (k_out, k_inn)) - - if (fileout == 1) or (fileout == 3): - # output to filename - pass - - # Inner Loop Convergence - if k_inn >= minInnIter: - if swarm_L < swarm_L_old: - stop_inner = 1 - - # Store History - if sto_hst: - logfile.write(swarm_x, 'gbest_x') - logfile.write(swarm_f, 'gbest_f') - logfile.write(swarm_g, 'gbest_g') - - # Print Outer - if prtOutIter != 0 and numpy.mod(k_out, prtOutIter) == 0: - # Output to screen - print("=" * 80 + "\n") - print("NUMBER OF ITERATIONS: %d\n" % k_out) - print("NUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - print("OBJECTIVE FUNCTION VALUE:") - print("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - print("EQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons): - print("\tH(%d) = %g" % (l, swarm_g[l])) - - # Inequality Constraints - print("\nINEQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons, constraints): - print("\tG(%d) = %g" % (l, swarm_g[l])) - - print("\nLAGRANGIAN MULTIPLIERS VALUES:") - for l in range(constraints): - print("\tL(%d) = %g" % (l, lambda_val[l])) - - print("\nBEST POSITION:") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - print(text) - print("=" * 80 + "\n") - - if (fileout == 1) or (fileout == 3): - # Output to Print File - ofile.write("\n" + "=" * 80 + "\n") - ofile.write("\nNUMBER OF ITERATIONS: %d\n" % k_out) - ofile.write("\nNUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - ofile.write("\nOBJECTIVE FUNCTION VALUE:\n") - ofile.write("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - ofile.write("\nEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons): - ofile.write("\tH(%d) = %.16g\n" % (l, swarm_g[l])) - - # Inequality Constraints - ofile.write("\nINEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons, constraints): - ofile.write("\tG(%d) = %.16g\n" % (l, swarm_g[l])) - - ofile.write("\nLAGRANGIAN MULTIPLIERS VALUES:\n") - for l in range(constraints): - ofile.write("\tL(%d) = %.16g\n" % (l, lambda_val[l])) - - ofile.write("\nPENALTY FACTOR:\n") - for l in range(constraints): - ofile.write("\trp(%d) = %.16g\n" % (l, rp[l])) - - ofile.write("\nBEST POSITION:\n") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - ofile.write(text) - ofile.write("\n" + "=" * 80 + "\n") - ofile.flush() - - # Store History - if sto_hst and (minInnIter != maxInnIter): - logfile.write(k_inn, 'ninner') - - # Test Constraint convergence - stop_con_num = 0 - infeas_con = [] - if constraints == 0: - stop_constraints_flag = 1 - else: - for l in range(neqcons): - if abs(swarm_g[l]) <= etol: - stop_con_num += 1 - else: - infeas_con.append(l) - - for l in range(neqcons, constraints): - if swarm_g[l] < itol: - stop_con_num += 1 - else: - infeas_con.append(l) - - if stop_con_num == constraints: - stop_constraints_flag = 1 - else: - stop_constraints_flag = 0 - - # # Test Lagrange multiplier convergence - # stop_lambda_flag = 0 - # if (constraints == 0): - # stop_lambda_flag = 1 - # else: - # for l in range(constraints): - # if (abs(lambda_val[l]-lambda_old[l]) <= ltol): - # stop_lambda_flag += 1 - # - # - # if (stop_lambda_flag==constraints): - # stop_lambda_flag = 1 - # else: - # stop_lambda_flag = 0 - # - # - # - - # Test Position and Function convergence - stop_criteria_flag = 0 - if stopCriteria == 1: - - # setting up the stopping criteria based on distance and tolerance - for k in range(stopIters - 1, 0, -1): - global_distance[k] = global_distance[k - 1] - global_L[k] = global_L[k - 1] - - # - global_dist = 0 - for i in range(swarmsize): - dist = 0 - for j in range(dimensions): - dist += (x_k[i, j] - swarm_x[j]) ** 2 - - global_dist += dist ** 0.5 - - global_distance[0] = global_dist / swarmsize # relative extent of the swarm - - # - global_L[0] = swarm_L - - # - if (abs(global_distance[0] - global_distance[stopIters - 1]) <= - dtol * abs(global_distance[stopIters - 1]) and - abs(global_L[0] - global_L[stopIters - 1]) <= rtol * abs(global_L[stopIters - 1]) or - abs(global_L[0] - global_L[stopIters - 1]) <= atol): - stop_criteria_flag = 1 - else: - stop_criteria_flag = 0 - - # Test Convergence - if stop_constraints_flag == 1 and stop_criteria_flag == 1: # and stop_lambda_flag == 1 - stop_main_flag = 1 - else: - stop_main_flag = 0 - - # Output to Summary File - if (fileout == 2) or (fileout == 3): - cvss = 0.0 - for l in infeas_con: - cvss += swarm_g[l] ** 2 - - cvL2 = cvss ** 0.5 - if stopCriteria == 1: - relL = abs(global_L[0] - global_L[stopIters - 1]) / abs(global_L[stopIters - 1]) - stext = '%9d%8d%8d%15.4e%15f%13.4e%16.4e%14.4e\n' % ( - k_out, k_inn, stop_con_num, cvL2, swarm_f, swarm_L, relL, global_distance[0]) - else: - stext = '%9d%8d%8d%15.4e%15f%13.4e%16s%14s\n' % ( - k_out, k_inn, stop_con_num, cvL2, swarm_f, swarm_L, 'NA', 'NA') - - sfile.write(stext) - sfile.flush() - - # Update Augmented Lagrangian Terms - if stop_main_flag == 0: - - if constraints > 0: - # Update new Tau - for l in range(neqcons): - tau_new[l] = swarm_g[l] - - for l in range(neqcons, constraints): - if swarm_g[l] > -lambda_val[l] / (2 * rp[l]): - tau_new[l] = swarm_g[l] - else: - tau_new[l] = -lambda_val[l] / (2 * rp[l]) - - # Update Lagrange Multiplier - for l in range(constraints): - lambda_old[l] = lambda_val[l] - lambda_val[l] += 2 * rp[l] * tau_new[l] - if abs(lambda_val[l]) < eps: - lambda_val[l] = 0.0 - - # Update Penalty Factor - for l in range(neqcons): - if abs(swarm_g[l]) > abs(swarm_g_old[l]) and abs(swarm_g[l]) > etol: - rp[l] *= 2.0 - elif abs(swarm_g[l]) <= etol: - rp[l] *= 0.5 - - for l in range(neqcons, constraints): - if swarm_g[l] > swarm_g_old[l] and swarm_g[l] > itol: - rp[l] *= 2.0 - elif swarm_g[l] <= itol: - rp[l] *= 0.5 - - # Apply Lower Bounds on rp - for l in range(neqcons): - if rp[l] < 0.5 * (abs(lambda_val[l]) / etol) ** 0.5: - rp[l] = 0.5 * (abs(lambda_val[l]) / etol) ** 0.5 - - for l in range(neqcons, constraints): - if rp[l] < 0.5 * (abs(lambda_val[l]) / itol) ** 0.5: - rp[l] = 0.5 * (abs(lambda_val[l]) / itol) ** 0.5 - - for l in range(constraints): - if rp[l] < 1: - rp[l] = 1 - - for i in range(swarmsize): - if constraints > 0: - # Update Tau - for l in range(neqcons): - tau[i, l] = g[i, l] - - for l in range(neqcons, constraints): - if g[i, l] > -lambda_val[l] / (2 * rp[l]): - tau[i, l] = g[i, l] - else: - tau[i, l] = -lambda_val[l] / (2 * rp[l]) - - # set craziness velocity for next inner loop run - vcr = (1 - k_out / maxOutIter) * vcrazy - - # update swarm with new Lagrangian function for next inner run - for i in range(swarmsize): - L[i] = f[i] - if constraints > 0: - for l in range(constraints): - L[i] += lambda_val[l] * tau[i, l] + rp[l] * tau[i, l] ** 2 - - swarm_L = L[swarm_i] - - swarm_L_old = swarm_f_old - if constraints > 0: - - # Equality Constraints - for l in range(neqcons): - tau_old[l] = swarm_g_old[l] - - # Inequality Constraints - for l in range(neqcons, constraints): - if rp[l] != 0: - if swarm_g_old[l] > -lambda_val[l] / (2 * rp[l]): - tau_old[l] = swarm_g_old[l] - else: - tau_old[l] = -lambda_val[l] / (2 * rp[l]) - - else: - tau_old[l] = swarm_g_old[l] - - # - for l in range(constraints): - swarm_L_old += lambda_val[l] * tau_old[l] + rp[l] * tau_old[l] ** 2 - - # reset swarm memory for next inner run - for i in range(swarmsize): - best_L[i] = L[i] - best_f[i] = f[i] - best_g[i, :] = g[i, :] - best_x[i, :] = x_k[i, :] - - # Print Results - if prtOutIter != 0: - # Output to screen - print("=" * 80 + "\n") - print("RANDOM SEED VALUE: %.8f\n" % rseed) - print("NUMBER OF ITERATIONS: %d\n" % k_out) - print("NUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - print("OBJECTIVE FUNCTION VALUE:") - print("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - print("EQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons): - print("\tH(%d) = %g" % (l, swarm_g[l])) - - # Inequality Constraints - print("\nINEQUALITY CONSTRAINTS VALUES:") - for l in range(neqcons, constraints): - print("\tG(%d) = %g" % (l, swarm_g[l])) - - print("\nLAGRANGIAN MULTIPLIERS VALUES:") - for l in range(constraints): - print("\tL(%d) = %g" % (l, float(lambda_val[l]))) - - print("\nBEST POSITION:") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - print(text) - print("=" * 80 + "\n") - - if (fileout == 1) or (fileout == 3): - ofile.close() - - if (fileout == 2) or (fileout == 3): - # Output to Summary - sfile.write("\n\nSolution:") - sfile.write("\n" + "=" * 94 + "\n") - sfile.write("\nNUMBER OF ITERATIONS: %d\n" % k_out) - sfile.write("\nNUMBER OF OBJECTIVE FUNCTION EVALUATIONS: %d\n" % nfevals) - sfile.write("\nOBJECTIVE FUNCTION VALUE:\n") - sfile.write("\tF = %.16g\n" % (float(swarm_f))) - if constraints > 0: - # Equality Constraints - sfile.write("\nEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons): - sfile.write("\tH(%d) = %.16g\n" % (l, swarm_g[l])) - - # Inequality Constraints - sfile.write("\nINEQUALITY CONSTRAINTS VALUES:\n") - for l in range(neqcons, constraints): - sfile.write("\tG(%d) = %.16g\n" % (l, swarm_g[l])) - - sfile.write("\nLAGRANGIAN MULTIPLIERS VALUES:\n") - for l in range(constraints): - sfile.write("\tL(%d) = %.16g\n" % (l, float(lambda_val[l]))) - - sfile.write("\nPENALTY FACTOR:\n") - for l in range(constraints): - sfile.write("\trp(%d) = %.16g\n" % (l, rp[l])) - - sfile.write("\nBEST POSITION:\n") - if scale == 1: - xtmp = (swarm_x[:] * space_halflen) + space_centre - else: - xtmp = swarm_x[:] - - for m in discrete_i: - xtmp[m] = floor(xtmp[m] + 0.5) - - text = '' - for j in range(dimensions): - text += ("\tP(%d) = %.16g\t" % (j, xtmp[j])) - if numpy.mod(j + 1, 3) == 0: - text += "\n" - - sfile.write(text) - sfile.write("\n" + "=" * 94 + "\n") - sfile.flush() - sfile.close() - - # Results - if scale == 1: - opt_x = (swarm_x * space_halflen) + space_centre - else: - opt_x = swarm_x - - for m in discrete_i: - opt_x[m] = int(floor(opt_x[m] + 0.5)) - - opt_f = swarm_f - opt_g = swarm_g - opt_lambda = lambda_val[:] - - return opt_x, opt_f, opt_g, opt_lambda, nfevals, '%.8f' % rseed diff --git a/pyoptsparse/pyoptsparse/pyALPSO/pyALPSO.py b/pyoptsparse/pyoptsparse/pyALPSO/pyALPSO.py deleted file mode 100644 index 032493a30..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/pyALPSO.py +++ /dev/null @@ -1,239 +0,0 @@ -# /bin/env python -""" -pyALPSO - A pyOptSparse interface to ALPSO -work with sparse optimization problems. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# Standard Python modules -# ============================================================================= -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error - - -# ============================================================================= -# ALPSO Optimizer Class -# ============================================================================= -class ALPSO(Optimizer): - """ - ALPSO Optimizer Class - Inherited from Optimizer Abstract Class - - *Keyword arguments:** - - - pll_type -> STR: ALPSO Parallel Implementation (None, SPM- Static, DPM- Dynamic, POA-Parallel Analysis), *Default* = None - """ - - def __init__(self, *args, **kwargs): - - from . import alpso - self.alpso = alpso - - category = 'Global Optimizer' - defOpts = { - 'SwarmSize': [int, 40], # Number of Particles (Depends on Problem dimensions) - 'maxOuterIter': [int, 200], # Maximum Number of Outer Loop Iterations (Major Iterations) - 'maxInnerIter': [int, 6], # Maximum Number of Inner Loop Iterations (Minor Iterations) - 'minInnerIter': [int, 6], # Minimum Number of Inner Loop Iterations (Dynamic Inner Iterations) - 'dynInnerIter': [int, 0], # Dynamic Number of Inner Iterations Flag - 'stopCriteria': [int, 1], # Stopping Criteria Flag (0 - maxIters, 1 - convergence) - 'stopIters': [int, 5], # Consecutive Number of Iterations for which the Stopping Criteria must be Satisfied - 'etol': [float, 1e-3], # Absolute Tolerance for Equality constraints - 'itol': [float, 1e-3], # Absolute Tolerance for Inequality constraints - # 'ltol':[float, 1e-2], # Absolute Tolerance for Lagrange Multipliers - 'rtol': [float, 1e-2], # Relative Tolerance for Lagrange Multipliers - 'atol': [float, 1e-2], # Absolute Tolerance for Lagrange Function - 'dtol': [float, 1e-1], # Relative Tolerance in Distance of All Particles to Terminate (GCPSO) - 'printOuterIters': [int, 0], # Number of Iterations Before Print Outer Loop Information - 'printInnerIters': [int, 0], # Number of Iterations Before Print Inner Loop Information - 'rinit': [float, 1.0], # Initial Penalty Factor - 'xinit': [int, 0], # Initial Position Flag (0 - no position, 1 - position given) - 'vinit': [float, 1.0], # Initial Velocity of Particles in Normalized [-1, 1] Design Space - 'vmax': [float, 2.0], # Maximum Velocity of Particles in Normalized [-1, 1] Design Space - 'c1': [float, 2.0], # Cognitive Parameter - 'c2': [float, 1.0], # Social Parameter - 'w1': [float, 0.99], # Initial Inertia Weight - 'w2': [float, 0.55], # Final Inertia Weight - 'ns': [int, 15], # Number of Consecutive Successes in Finding New Best Position of Best Particle Before Search Radius will be Increased (GCPSO) - 'nf': [int, 5], # Number of Consecutive Failures in Finding New Best Position of Best Particle Before Search Radius will be Increased (GCPSO) - 'dt': [float, 1.0], # Time step - 'vcrazy': [float, 1e-4], # Craziness Velocity (Added to Particle Velocity After Updating the Penalty Factors and Langangian Multipliers) - 'fileout': [int, 1], # Flag to Turn On Output to filename - 'filename': [str, 'ALPSO.out'], # We could probably remove fileout flag if filename or fileinstance is given - 'seed': [float, 0], # Random Number Seed (0 - Auto-Seed based on time clock) - 'HoodSize': [int, 40], # Number of Neighbours of Each Particle - 'HoodModel': [str, 'gbest'], # Neighbourhood Model (dl/slring - Double/Single Link Ring, wheel - Wheel, Spatial - based on spatial distance, sfrac - Spatial Fraction) - 'HoodSelf': [int, 1], # Selfless Neighbourhood Model (0 - Include Particle i in NH i, 1 - Don't Include Particle i) - 'Scaling': [int, 1], # Design Variables Scaling Flag (0 - no scaling, 1 - scaling between [-1, 1]) - 'parallelType': [str, ''], # Type of parallelization ('' or 'EXT') - } - informs = {} - Optimizer.__init__(self, 'ALPSO', category, defOpts, informs, *args, **kwargs) - - def __call__(self, optProb, storeHistory=None, **kwargs): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - Notes - ----- - The kwargs are there such that the sens= argument can be - supplied (but ignored here in alpso) - """ - # ====================================================================== - # ALPSO - Objective/Constraint Values Function - # ====================================================================== - def objconfunc(x): - fobj, fcon, fail = self._masterFunc(x, ['fobj', 'fcon']) - return fobj, fcon - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - - if len(optProb.constraints) == 0: - self.unconstrained = True - - xl, xu, xs = self._assembleContinuousVariables() - xs = numpy.maximum(xs, xl) - xs = numpy.minimum(xs, xu) - n = len(xs) - ff = self._assembleObjective() - types = [0] * len(xs) - oneSided = True - if self.unconstrained: - m = 0 - me = 0 - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'le', 'ni', 'li'], oneSided=oneSided, noEquality=False) - m = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - indices, __, __, __ = self.optProb.getOrdering( - ['ne', 'le'], oneSided=oneSided, noEquality=False) - me = len(indices) - - nobj = 1 - - - if self.optProb.comm.rank == 0: - # Set history/hotstart/coldstart - self._setHistory(storeHistory, None) - - # Setup argument list values - opt = self.getOption - - dyniI = self.getOption('dynInnerIter') - if dyniI == 0: - self.setOption('minInnerIter', opt('maxInnerIter')) - - if not opt('stopCriteria') in [0, 1]: - raise Error('Incorrect Stopping Criteria Setting') - - if opt('fileout') not in [0, 1, 2, 3]: - raise Error('Incorrect fileout Setting') - - if opt('seed') == 0: - self.setOption('seed', time.time()) - - # As far as I can tell, there is no need for this bulk attribute. - # ALPSO calls the objconfunc iteratively for each particle in the - # swarm, so we can deal with them one at a time, just as the other - # optimizers. - # self.optProb.bulk = opt('SwarmSize') - - # Run ALPSO - t0 = time.time() - opt_x, opt_f, opt_g, opt_lambda, nfevals, rseed = self.alpso.alpso( - n, m, me, types, xs, xl, xu, opt('SwarmSize'), opt('HoodSize'), - opt('HoodModel'), opt('maxOuterIter'), opt('maxInnerIter'), - opt('minInnerIter'), opt('stopCriteria'), opt('stopIters'), - opt('etol'), opt('itol'), opt('rtol'), opt('atol'), opt('dtol'), - opt('printOuterIters'), opt('printInnerIters'), opt('rinit'), - opt('vinit'), opt('vmax'), opt('c1'), opt('c2'), opt('w1'), - opt('w2'), opt('ns'), opt('nf'), opt('vcrazy'), opt('fileout'), - opt('filename'), None, None, opt('seed'), - opt('Scaling'), opt('HoodSelf'), objconfunc) - optTime = time.time() - t0 - - # Broadcast a -1 to indcate NSGA2 has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - # sol_inform['value'] = inform - # sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, opt_f, opt_x) - for key in sol.objectives.keys(): - sol.objectives[key].value = opt_f - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - if name == 'parallelType': - value = value.upper() - if value == 'EXT': - try: - from . import alpso_ext - self.alpso = alpso_ext - except ImportError: - raise ImportError('pyALPSO: ALPSO EXT shared library failed to import.') - - else: - raise ValueError("parallel_type must be either '' or 'EXT'.") - - def _on_getOption(self, name, value): - pass - - def _communicateSolution(self, sol): - if sol is not None: - sol.userObjCalls = self.optProb.comm.allreduce(sol.userObjCalls) - sol.comm = None - sol = self.optProb.comm.bcast(sol) - sol.objFun = self.optProb.objFun - sol.comm = self.optProb.comm - - return sol diff --git a/pyoptsparse/pyoptsparse/pyALPSO/setup.py b/pyoptsparse/pyoptsparse/pyALPSO/setup.py deleted file mode 100644 index 36cdb82da..000000000 --- a/pyoptsparse/pyoptsparse/pyALPSO/setup.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyALPSO',parent_package,top_path) - - config.add_data_files('LICENSE','README') - - return config - diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/LICENSE b/pyoptsparse/pyoptsparse/pyCONMIN/LICENSE deleted file mode 100644 index d7f6886be..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/LICENSE +++ /dev/null @@ -1,360 +0,0 @@ -CONMIN - CONstrained function MINimization -Copyright (c) 1972, Gary N. Vanderplaats -Modified for pyOpt - 2008, Ruben E. Perez (Ruben.Perez@rmc.ca) - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, -MA 02111-1307 USA. - ----------------------------------------------------------------------- - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/README b/pyoptsparse/pyoptsparse/pyCONMIN/README deleted file mode 100644 index 4cac22853..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the conmin class definition -and the conmin shared library, conmin.so or conmin.pyd. diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/__init__.py b/pyoptsparse/pyoptsparse/pyCONMIN/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/pyCONMIN.py b/pyoptsparse/pyoptsparse/pyCONMIN/pyCONMIN.py deleted file mode 100644 index 933903fd7..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/pyCONMIN.py +++ /dev/null @@ -1,269 +0,0 @@ -#/bin/env python -""" -pyCONMIN - A variation of the pyCONMIN wrapper specificially designed to -work with sparse optimization problems. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# CONMIN Library -# ============================================================================= -try: - from . import conmin -except ImportError: - conmin = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -# ============================================================================= -# CONMIN Optimizer Class -# ============================================================================= -class CONMIN(Optimizer): - """ - CONMIN Optimizer Class - Inherited from Optimizer Abstract Class - """ - def __init__(self, *args, **kwargs): - name = 'CONMIN' - category = 'Local Optimizer' - defOpts = { - 'ITMAX':[int, 1e4], # Maximum Number of Iterations - 'DELFUN':[float, 1e-6], # Objective Relative Tolerance - 'DABFUN':[float, 1e-6], # Objective Absolute Tolerance - 'ITRM':[int, 5], - 'NFEASCT':[int, 20], - 'IPRINT':[int, 4], # Print Control (0 - None, 1 - Final, 2,3,4 - Debug) - 'IOUT':[int, 6], # Output Unit Number - 'IFILE':[str, 'CONMIN.out'], # Output File Name - } - informs = {} - if conmin is None: - raise Error('There was an error importing the compiled \ - conmin module') - - self.set_options = [] - Optimizer.__init__(self, name, category, defOpts, informs, *args, - **kwargs) - - # CONMIN needs jacobians in dense format - self.jacType = 'dense2d' - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. To - explictly use pyOptSparse gradient class to do the - derivatives with finite differenes use 'FD'. 'sens' - may also be 'CS' which will cause pyOptSpare to compute - the derivatives using the complex step method. Finally, - 'sens' may be a python function handle which is expected - to compute the sensitivities directly. For expensive - function evaluations and/or problems with large numbers of - design variables this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is 'FD' and 1e-40j when sens is 'CS'. - - sensMode : str - Use 'pgc' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from CONMIN does not match the history, function and - gradient evaluations revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if len(optProb.constraints) == 0: - # If the user *actually* has an unconstrained problem, - # slsqp sort of chokes with that....it has to have at - # least one constraint. So we will add one - # automatically here: - self.unconstrained = True - optProb.dummyConstraint = False - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - self._setSens(sens, sensStep, sensMode) - blx, bux, xs = self._assembleContinuousVariables() - xs = numpy.maximum(xs, blx) - xs = numpy.minimum(xs, bux) - n = len(xs) - ff = self._assembleObjective() - - oneSided = True - noEquality = True - if self.unconstrained: - m = 0 - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'le', 'ni', 'li'], oneSided=oneSided, - noEquality=noEquality) - m = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - if self.optProb.comm.rank == 0: - # Set history/hotstart/coldstart - self._setHistory(storeHistory, hotStart) - - #================================================================= - # CONMIN - Objective/Constraint Values Function - #================================================================= - def cnmnfun(n1, n2, x, f, g): - fobj, fcon, fail = self._masterFunc(x[0:ndv], ['fobj', 'fcon']) - f = fobj - g[0:ncn] = fcon - - return f, g - - #================================================================= - # CONMIN - Objective/Constraint Gradients Function - #================================================================= - def cnmngrad(n1, n2, x, f, g, ct, df, a, ic, nac): - - gobj, gcon, fail = self._masterFunc(x[0:ndv], ['gobj', 'gcon']) - df[0:ndv] = gobj.copy() - - # Only assign the gradients for constraints that are - # actually active: - nac = 0 - for j in range(ncn): - if g[j] >= ct: - a[0:ndv, nac] = gcon[j, :] - ic[nac] = j + 1 - nac += 1 - return df, a, ic, nac - - # Setup argument list values - ndv = len(xs) - ncn = m - nn1 = ndv + 2 - nn2 = ncn + 2*ndv - nn3 = max(nn2, ndv) - nn4 = max(nn2, ndv) - nn5 = 2*nn4 - gg = numpy.zeros(ncn, numpy.float) - if self.getOption('IPRINT') >= 0 and self.getOption('IPRINT') <= 4: - iprint = self.getOption('IPRINT') - else: - raise Error('IPRINT option must be >= 0 and <= 4') - - iout = self.getOption('IOUT') - ifile = self.getOption('IFILE') - - # Check if file exists and remove if necessary - if iprint > 0: - if os.path.isfile(ifile): - os.remove(ifile) - - itmax = self.getOption('ITMAX') - delfun = self.getOption('DELFUN') - - #finit, ginit = cnmnfun([],[],xx,ff,gg) - dabfun = self.getOption('DABFUN') - - itrm = self.getOption('ITRM') - nfeasct = self.getOption('ITRM') - nfdg = 1 # User will supply all gradients - - # Counters for functions and gradients - nfun = 0 - ngrd = 0 - - # Run CONMIN - t0 = time.time() - conmin.conmin(ndv, ncn, xs, blx, bux, ff, gg, - nn1, nn2, nn3, nn4, nn5, - iprint, iout, ifile, itmax, delfun, dabfun, itrm, - nfeasct, nfdg, nfun, ngrd, cnmnfun, cnmngrad) - optTime = time.time() - t0 - - if iprint > 0: - conmin.closeunit(self.getOption('IOUT')) - - # Broadcast a -1 to indcate SLSQP has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - #sol_inform['value'] = inform - #sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name, value): - pass - diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/setup.py b/pyoptsparse/pyoptsparse/pyCONMIN/setup.py deleted file mode 100644 index b6e080e87..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyCONMIN',parent_package,top_path) - - config.add_library('conmin', - sources=[os.path.join('source', '*.f')]) - config.add_extension('conmin', - sources=['source/f2py/conmin.pyf'], - libraries=['conmin']) - config.add_data_files('LICENSE','README') - - return config - diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/README b/pyoptsparse/pyoptsparse/pyCONMIN/source/README deleted file mode 100644 index cbdad0c4e..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/README +++ /dev/null @@ -1,4 +0,0 @@ -This directory contains the Fortran 77 source for CONMIN -modified for pyOpt interfacing by Dr. Ruben E. Perez, -plus two helper files called openunit.f and closeunit.f -to manipulate Fortran units from Python. diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/closeunit.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/closeunit.f deleted file mode 100644 index f1d9f8377..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/closeunit.f +++ /dev/null @@ -1,10 +0,0 @@ -C Helper subroutine to close files in the Fortran world - subroutine closeunit(unitnum) - - integer unitnum -Cf2py intent(in) unitnum - - close(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn00.bak b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn00.bak deleted file mode 100644 index 7e55e9ed1..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn00.bak +++ /dev/null @@ -1,903 +0,0 @@ - SUBROUTINE CNMN00 (X,VLB,VUB,G,SCAL,DF,A,S,G1,G2,B,C,ISC,IC,MS1,N1 - 1,N2,N3,N4,N5) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT -C -C NFEASCT ADDED TO COMMON BLOCK BY KCYOUNG ON 4/14/92 TO ALLOW MORE -C THAN 10 ITERATION ATTEMPTS. NFEASCT BECOMES AN INPUT VALUE -C - DIMENSION X(N1), VLB(N1), VUB(N1), G(N2), SCAL(N1), DF(N1), A(N1,N - 13), S(N1), G1(N2), G2(N2), B(N3,N3), C(N4), ISC(N2), IC(N3), MS1(N - 25) - COMMON /CONSAV/ DM1,DM2,DM3,DM4,DM5,DM6,DM7,DM8,DM9,DM10,DM11,DM12 - 1,DCT,DCTL,PHI,ABOBJ,CTA,CTAM,CTBM,OBJ1,SLOPE,DX,DX1,FI,XI,DFTDF1,A - 2LP,FFF,A1,A2,A3,A4,F1,F2,F3,F4,CV1,CV2,CV3,CV4,APP,ALPCA,ALPFES,AL - 3PLN,ALPMIN,ALPNC,ALPSAV,ALPSID,ALPTOT,RSPACE,IDM1,IDM2,IDM3,JDIR,I - 4OBJ,KOBJ,KCOUNT,NCAL(2),NFEAS,MSCAL,NCOBJ,NVC,KOUNT,ICOUNT,IGOOD1, - 5IGOOD2,IGOOD3,IGOOD4,IBEST,III,NLNC,JGOTO,ISPACE(2) -C ROUTINE TO SOLVE CONSTRAINED OR UNCONSTRAINED FUNCTION -C MINIMIZATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C * * * * * * * * * * * JUNE, 1979 VERSION * * * * * * * * * * * -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C REFERENCE; CONMIN - A FORTRAN PROGRAM FOR CONSTRAINED FUNCTION -C MINIMIZATION: USER'S MANUAL, BY G. N. VANDERPLAATS, -C NASA TM X-62,282, AUGUST, 1973. -C STORAGE REQUIREMENTS: -C PROGRAM - 7000 DECIMAL WORDS (CDC COMPUTER) -C ARRAYS - APPROX. 2*(NDV**2)+26*NDV+4*NCON, -C WHERE N3 = NDV+2. -C RE-SCALE VARIABLES IF REQUIRED. - IF (NSCAL.EQ.0.OR.IGOTO.EQ.0) GO TO 20 - DO 10 I=1,NDV -10 X(I)=C(I) -20 CONTINUE -C CONSTANTS. - NDV1=NDV+1 - NDV2=NDV+2 - IF (IGOTO.EQ.0) GO TO 40 -C ------------------------------------------------------------------ -C CHECK FOR UNBOUNDED SOLUTION -C ------------------------------------------------------------------ -C STOP IF OBJ IS LESS THAN -1.0E+40 - IF (OBJ.GT.-1.0E+40) GO TO 30 - WRITE (6,980) - GO TO 810 -30 CONTINUE - GO TO (160,390,380,670,690),IGOTO -C ------------------------------------------------------------------ -C SAVE INPUT CONTROL PARAMETERS -C ------------------------------------------------------------------ -40 CONTINUE - IF (IPRINT.GT.0) WRITE (6,1220) - IF (LINOBJ.EQ.0.OR.(NCON.GT.0.OR.NSIDE.GT.0)) GO TO 50 -C TOTALLY UNCONSTRAINED FUNCTION WITH LINEAR OBJECTIVE. -C SOLUTION IS UNBOUNDED. - WRITE (6,970) LINOBJ,NCON,NSIDE - RETURN -50 CONTINUE - IDM1=ITRM - IDM2=ITMAX - IDM3=ICNDIR - DM1=DELFUN - DM2=DABFUN - DM3=CT - DM4=CTMIN - DM5=CTL - DM6=CTLMIN - DM7=THETA - DM8=PHI - DM9=FDCH - DM10=FDCHM - DM11=ABOBJ1 - DM12=ALPHAX -C ------------------------------------------------------------------ -C DEFAULTS -C ------------------------------------------------------------------ - IF (ITRM.LE.0) ITRM=3 - IF (ITMAX.LE.0) ITMAX=20 - NDV1=NDV+1 - IF (ICNDIR.EQ.0) ICNDIR=NDV1 - IF (DELFUN.LE.0.) DELFUN=.0001 - CT=-ABS(CT) - IF (CT.GE.0.) CT=-.1 - CTMIN=ABS(CTMIN) - IF (CTMIN.LE.0.) CTMIN=.004 - CTL=-ABS(CTL) - IF (CTL.GE.0.) CTL=-0.01 - CTLMIN=ABS(CTLMIN) - IF (CTLMIN.LE.0.) CTLMIN=.001 - IF (THETA.LE.0.) THETA=1. - IF (ABOBJ1.LE.0.) ABOBJ1=.1 - IF (ALPHAX.LE.0.) ALPHAX=.1 - IF (FDCH.LE.0.) FDCH=.01 - IF (FDCHM.LE.0.) FDCHM=.01 -C ------------------------------------------------------------------ -C INITIALIZE INTERNAL PARAMETERS -C ------------------------------------------------------------------ - INFOG=0 - ITER=0 - JDIR=0 - IOBJ=0 - KOBJ=0 - NDV2=NDV+2 - KCOUNT=0 - NCAL(1)=0 - NCAL(2)=0 - NAC=0 - NFEAS=0 - MSCAL=NSCAL - CT1=ITRM - CT1=1./CT1 - DCT=(CTMIN/ABS(CT))**CT1 - DCTL=(CTLMIN/ABS(CTL))**CT1 - PHI=5. - ABOBJ=ABOBJ1 - NCOBJ=0 - CTAM=ABS(CTMIN) - CTBM=ABS(CTLMIN) -C CALCULATE NUMBER OF LINEAR CONSTRAINTS, NLNC. - NLNC=0 - IF (NCON.EQ.0) GO TO 70 - DO 60 I=1,NCON - IF (ISC(I).GT.0) NLNC=NLNC+1 -60 CONTINUE -70 CONTINUE -C ------------------------------------------------------------------ -C CHECK TO BE SURE THAT SIDE CONSTRAINTS ARE SATISFIED -C ------------------------------------------------------------------ - IF (NSIDE.EQ.0) GO TO 110 - DO 100 I=1,NDV - IF (VLB(I).LE.VUB(I)) GO TO 80 - XX=.5*(VLB(I)+VUB(I)) - X(I)=XX - VLB(I)=XX - VUB(I)=XX - WRITE (6,1120) I -80 CONTINUE - XX=X(I)-VLB(I) - IF (XX.GE.0.) GO TO 90 -C LOWER BOUND VIOLATED. - WRITE (6,1130) X(I),VLB(I),I - X(I)=VLB(I) - GO TO 100 -90 CONTINUE - XX=VUB(I)-X(I) - IF (XX.GE.0.) GO TO 100 - WRITE (6,1140) X(I),VUB(I),I - X(I)=VUB(I) -100 CONTINUE -110 CONTINUE -C ------------------------------------------------------------------ -C INITIALIZE SCALING VECTOR, SCAL -C ------------------------------------------------------------------ - IF (NSCAL.EQ.0) GO TO 150 - IF (NSCAL.LT.0) GO TO 130 - DO 120 I=1,NDV -120 SCAL(I)=1. - GO TO 150 -130 CONTINUE - DO 140 I=1,NDV - SI=ABS(SCAL(I)) - IF (SI.LT.1.0E-20) SI=1.0E-5 - SCAL(I)=SI - SI=1./SI - X(I)=X(I)*SI - IF (NSIDE.EQ.0) GO TO 140 - VLB(I)=VLB(I)*SI - VUB(I)=VUB(I)*SI -140 CONTINUE -150 CONTINUE -C ------------------------------------------------------------------ -C ***** CALCULATE INITIAL FUNCTION AND CONSTRAINT VALUES ***** -C ------------------------------------------------------------------ - INFO=1 - NCAL(1)=1 - IGOTO=1 - GO TO 950 -160 CONTINUE - OBJ1=OBJ - IF (DABFUN.LE.0.) DABFUN=.001*ABS(OBJ) - IF (DABFUN.LT.1.0E-10) DABFUN=1.0E-10 - IF (IPRINT.LE.0) GO TO 270 -C ------------------------------------------------------------------ -C PRINT INITIAL DESIGN INFORMATION -C ------------------------------------------------------------------ - IF (IPRINT.LE.1) GO TO 230 - IF (NSIDE.EQ.0.AND.NCON.EQ.0) WRITE (6,1290) - IF (NSIDE.NE.0.OR.NCON.GT.0) WRITE (6,1230) - WRITE (6,1240) IPRINT,NDV,ITMAX,NCON,NSIDE,ICNDIR,NSCAL,NFDG - 1,LINOBJ,ITRM,N1,N2,N3,N4,N5 - WRITE (6,1260) CT,CTMIN,CTL,CTLMIN,THETA,PHI,DELFUN,DABFUN - WRITE (6,1250) FDCH,FDCHM,ALPHAX,ABOBJ1 - IF (NSIDE.EQ.0) GO TO 190 - WRITE (6,1270) - DO 170 I=1,NDV,6 - M1=MIN0(NDV,I+5) -170 WRITE (6,1010) I,(VLB(J),J=I,M1) - WRITE (6,1280) - DO 180 I=1,NDV,6 - M1=MIN0(NDV,I+5) -180 WRITE (6,1010) I,(VUB(J),J=I,M1) -190 CONTINUE - IF (NSCAL.GE.0) GO TO 200 - WRITE (6,1300) - WRITE (6,1460) (SCAL(I),I=1,NDV) -200 CONTINUE - IF (NCON.EQ.0) GO TO 230 - IF (NLNC.EQ.0.OR.NLNC.EQ.NCON) GO TO 220 - WRITE (6,1020) - DO 210 I=1,NCON,15 - M1=MIN0(NCON,I+14) -210 WRITE (6,1030) I,(ISC(J),J=I,M1) - GO TO 230 -220 IF (NLNC.EQ.NCON) WRITE (6,1040) - IF (NLNC.EQ.0) WRITE (6,1050) -230 CONTINUE - WRITE (6,1440) OBJ - WRITE (6,1450) - DO 240 I=1,NDV - X1=1. - IF (NSCAL.NE.0) X1=SCAL(I) -240 G1(I)=X(I)*X1 - DO 250 I=1,NDV,6 - M1=MIN0(NDV,I+5) -250 WRITE (6,1010) I,(G1(J),J=I,M1) - IF (NCON.EQ.0) GO TO 270 - WRITE (6,1470) - DO 260 I=1,NCON,6 - M1=MIN0(NCON,I+5) -260 WRITE (6,1010) I,(G(J),J=I,M1) -270 CONTINUE - IF (IPRINT.GT.1) WRITE (6,1360) -C ------------------------------------------------------------------ -C ******************** BEGIN MINIMIZATION ************************ -C ------------------------------------------------------------------ -280 CONTINUE - ITER=ITER+1 - IF (ABOBJ1.LT..0001) ABOBJ1=.0001 - IF (ABOBJ1.GT..2) ABOBJ1=.2 - IF (ALPHAX.GT.1.) ALPHAX=1. - IF (ALPHAX.LT..001) ALPHAX=.001 -C -C THE FOLLOWING TWO LINES OF CODE WERE COMMENTED OUT ON 3/5/81 -C -C NFEAS=NFEAS+1 -C IF (NFEAS.GT.10) GO TO 810 - IF (IPRINT.GT.2) WRITE (6,1310) ITER - IF (IPRINT.GT.3.AND.NCON.GT.0) WRITE (6,1320) CT,CTL,PHI - CTA=ABS(CT) - IF (NCOBJ.EQ.0) GO TO 340 -C ------------------------------------------------------------------ -C NO MOVE ON LAST ITERATION. DELETE CONSTRAINTS THAT ARE NO -C LONGER ACTIVE. -C ------------------------------------------------------------------ - NNAC=NAC - DO 290 I=1,NNAC - IF (IC(I).GT.NCON) NAC=NAC-1 -290 CONTINUE - IF (NAC.LE.0) GO TO 420 - NNAC=NAC - DO 330 I=1,NNAC -300 NIC=IC(I) - CT1=CT - IF (ISC(NIC).GT.0) CT1=CTL - IF (G(NIC).GT.CT1) GO TO 330 - NAC=NAC-1 - IF (I.GT.NAC) GO TO 420 - DO 320 K=I,NAC - II=K+1 - DO 310 J=1,NDV2 -310 A(J,K)=A(J,II) -320 IC(K)=IC(II) - GO TO 300 -330 CONTINUE - GO TO 420 -340 CONTINUE - IF (MSCAL.LT.NSCAL.OR.NSCAL.EQ.0) GO TO 360 - IF (NSCAL.LT.0.AND.KCOUNT.LT.ICNDIR) GO TO 360 - MSCAL=0 - KCOUNT=0 -C ------------------------------------------------------------------ -C SCALE VARIABLES -C ------------------------------------------------------------------ - DO 350 I=1,NDV - SI=SCAL(I) - XI=SI*X(I) - SIB=SI - IF (NSCAL.GT.0) SI=ABS(XI) - IF (SI.LT.1.0E-10) GO TO 350 - SCAL(I)=SI - SI=1./SI - X(I)=XI*SI - IF (NSIDE.EQ.0) GO TO 350 - VLB(I)=SIB*SI*VLB(I) - VUB(I)=SIB*SI*VUB(I) -350 CONTINUE - IF (IPRINT.LT.4.OR.(NSCAL.LT.0.AND.ITER.GT.1)) GO TO 360 - WRITE (6,1330) - WRITE (6,1460) (SCAL(I),I=1,NDV) -360 CONTINUE - MSCAL=MSCAL+1 - NAC=0 -C ------------------------------------------------------------------ -C OBTAIN GRADIENTS OF OBJECTIVE AND ACTIVE CONSTRAINTS -C ------------------------------------------------------------------ - INFO=2 - NCAL(2)=NCAL(2)+1 - IF (NFDG.NE.1) GO TO 370 - IGOTO=2 - GO TO 950 -370 CONTINUE - JGOTO=0 -380 CONTINUE - CALL CNMN01 (JGOTO,X,DF,G,ISC,IC,A,G1,VLB,VUB,SCAL,C,NCAL,DX,DX1 - 1,FI,XI,III,N1,N2,N3,N4) - IGOTO=3 - IF (JGOTO.GT.0) GO TO 950 -390 CONTINUE - INFO=1 - IF (NAC.GE.N3) GO TO 810 - IF (NSCAL.EQ.0.OR.NFDG.EQ.0) GO TO 420 -C ------------------------------------------------------------------ -C SCALE GRADIENTS -C ------------------------------------------------------------------ -C SCALE GRADIENT OF OBJECTIVE FUNCTION. - DO 400 I=1,NDV -400 DF(I)=DF(I)*SCAL(I) - IF (NFDG.EQ.2.OR.NAC.EQ.0) GO TO 420 -C SCALE GRADIENTS OF ACTIVE CONSTRAINTS. - DO 410 J=1,NDV - SCJ=SCAL(J) - DO 410 I=1,NAC -410 A(J,I)=A(J,I)*SCJ -420 CONTINUE - IF (IPRINT.LT.3.OR.NCON.EQ.0) GO TO 470 -C ------------------------------------------------------------------ -C PRINT -C ------------------------------------------------------------------ -C PRINT ACTIVE AND VIOLATED CONSTRAINT NUMBERS. - M1=0 - M2=N3 - IF (NAC.EQ.0) GO TO 450 - DO 440 I=1,NAC - J=IC(I) - IF (J.GT.NCON) GO TO 440 - GI=G(J) - C1=CTAM - IF (ISC(J).GT.0) C1=CTBM - GI=GI-C1 - IF (GI.GT.0.) GO TO 430 -C ACTIVE CONSTRAINT. - M1=M1+1 - MS1(M1)=J - GO TO 440 -430 M2=M2+1 -C VIOLATED CONSTRAINT. - MS1(M2)=J -440 CONTINUE -450 M3=M2-N3 - WRITE (6,1060) M1 - IF (M1.EQ.0) GO TO 460 - WRITE (6,1070) - WRITE (6,1480) (MS1(I),I=1,M1) -460 WRITE (6,1080) M3 - IF (M3.EQ.0) GO TO 470 - WRITE (6,1070) - M3=N3+1 - WRITE (6,1480) (MS1(I),I=M3,M2) -470 CONTINUE -C ------------------------------------------------------------------ -C CALCULATE GRADIENTS OF ACTIVE SIDE CONSTRAINTS -C ------------------------------------------------------------------ - IF (NSIDE.EQ.0) GO TO 530 - MCN1=NCON - M1=0 - DO 510 I=1,NDV -C LOWER BOUND. - XI=X(I) - XID=VLB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XID-XI)/X12 - IF (GI.LT.-1.0E-6) GO TO 490 - M1=M1+1 - MS1(M1)=-I - NAC=NAC+1 - IF (NAC.GE.N3) GO TO 810 - MCN1=MCN1+1 - DO 480 J=1,NDV -480 A(J,NAC)=0. - A(I,NAC)=-1. - IC(NAC)=MCN1 - G(MCN1)=GI - ISC(MCN1)=1 -C UPPER BOUND. -490 XID=VUB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XI-XID)/X12 - IF (GI.LT.-1.0E-6) GO TO 510 - M1=M1+1 - MS1(M1)=I - NAC=NAC+1 - IF (NAC.GE.N3) GO TO 810 - MCN1=MCN1+1 - DO 500 J=1,NDV -500 A(J,NAC)=0. - A(I,NAC)=1. - IC(NAC)=MCN1 - G(MCN1)=GI - ISC(MCN1)=1 -510 CONTINUE -C ------------------------------------------------------------------ -C PRINT -C ------------------------------------------------------------------ -C PRINT ACTIVE SIDE CONSTRAINT NUMBERS. - IF (IPRINT.LT.3) GO TO 530 - WRITE (6,1090) M1 - IF (M1.EQ.0) GO TO 530 - WRITE (6,1100) - WRITE(6,1480) (MS1(J),J=1,M1) -530 CONTINUE -C PRINT GRADIENTS OF ACTIVE AND VIOLATED CONSTRAINTS. - IF (IPRINT.LT.4) GO TO 570 - WRITE (6,1340) - DO 540 I=1,NDV,6 - M1=MIN0(NDV,I+5) -540 WRITE (6,1010) I,(DF(J),J=I,M1) - IF (NAC.EQ.0) GO TO 570 - WRITE (6,1350) - DO 560 I=1,NAC - M1=IC(I) - M2=M1-NCON - M3=0 - IF (M2.GT.0) M3=IABS(MS1(M2)) - IF (M2.LE.0) WRITE (6,990) M1 - IF (M2.GT.0) WRITE (6,1000) M3 - DO 550 K=1,NDV,6 - M1=MIN0(NDV,K+5) -550 WRITE (6,1010) K,(A(J,I),J=K,M1) -560 WRITE (6,1360) -570 CONTINUE -C ------------------------------------------------------------------ -C ****************** DETERMINE SEARCH DIRECTION ******************* -C ------------------------------------------------------------------ - ALP=1.0E+20 - IF (NAC.GT.0) GO TO 580 -C ------------------------------------------------------------------ -C UNCONSTRAINED FUNCTION -C ------------------------------------------------------------------ -C FIND DIRECTION OF STEEPEST DESCENT OR CONJUGATE DIRECTION. -C -C S. N. 575 ADDED ON 2/25/81 -C - 575 NVC=0 - NFEAS=0 - KCOUNT=KCOUNT+1 -C IF KCOUNT.GT.ICNDIR RESTART CONJUGATE DIRECTION ALGORITHM. - IF (KCOUNT.GT.ICNDIR.OR.IOBJ.EQ.2) KCOUNT=1 - IF (KCOUNT.EQ.1) JDIR=0 -C IF JDIR = 0 FIND DIRECTION OF STEEPEST DESCENT. - CALL CNMN02 (JDIR,SLOPE,DFTDF1,DF,S,N1) - GO TO 630 -580 CONTINUE -C ------------------------------------------------------------------ -C CONSTRAINED FUNCTION -C ------------------------------------------------------------------ -C FIND USABLE-FEASIBLE DIRECTION. - KCOUNT=0 - JDIR=0 - PHI=10.*PHI - IF (PHI.GT.1000.) PHI=1000. -C -C THE FOLLOWING LINE OF CODE WAS COMMENTED OUT ON 3/5/81 -C -C IF (NFEAS.EQ.1) PHI=5. -C CALCULATE DIRECTION, S. - CALL CNMN05 (G,DF,A,S,B,C,SLOPE,PHI,ISC,IC,MS1,NVC,N1,N2,N3,N4,N5) -C -C THE FOLLOWING LINE WAS ADDED ON 2/25/81 -C - IF(NAC.EQ.0) GO TO 575 -C -C THE FOLLOWING FIVE LINES WERE COMMENTED OUT ON 3/5/81 -C REASON : THEY WERE NOT IN G. VANDERPLAATS LISTING -C -C IF THIS DESIGN IS FEASIBLE AND LAST ITERATION WAS INFEASIBLE, -C SET ABOBJ1=.05 (5 PERCENT). -C IF (NVC.EQ.0.AND.NFEAS.GT.1) ABOBJ1=.05 -C IF (NVC.EQ.0) NFEAS=0 - IF (IPRINT.LT.3) GO TO 600 - WRITE (6,1370) - DO 590 I=1,NAC,6 - M1=MIN0(NAC,I+5) -590 WRITE (6,1010) I,(A(NDV1,J),J=I,M1) - WRITE (6,1210) S(NDV1) -600 CONTINUE -C ------------------------------------------------------------------ -C ****************** ONE-DIMENSIONAL SEARCH ************************ -C ------------------------------------------------------------------ - IF (S(NDV1).LT.1.0E-6.AND.NVC.EQ.0) GO TO 710 -C ------------------------------------------------------------------ -C FIND ALPHA TO OBTAIN A FEASIBLE DESIGN -C ------------------------------------------------------------------ - IF (NVC.EQ.0) GO TO 630 - ALP=-1. - DO 620 I=1,NAC - NCI=IC(I) - C1=G(NCI) - CTC=CTAM - IF (ISC(NCI).GT.0) CTC=CTBM - IF (C1.LE.CTC) GO TO 620 - ALP1=0. - DO 610 J=1,NDV -610 ALP1=ALP1+S(J)*A(J,I) - ALP1=ALP1*A(NDV2,I) - IF (ABS(ALP1).LT.1.0E-20) GO TO 620 - ALP1=-C1/ALP1 - IF (ALP1.GT.ALP) ALP=ALP1 -620 CONTINUE -630 CONTINUE -C ------------------------------------------------------------------ -C LIMIT CHANCE TO ABOBJ1*OBJ -C ------------------------------------------------------------------ - ALP1=1.0E+20 - SI=ABS(OBJ) - IF (SI.LT..01) SI=.01 - IF (ABS(SLOPE).GT.1.0E-20) ALP1=ABOBJ1*SI/SLOPE - ALP1=ABS(ALP1) - IF (NVC.GT.0) ALP1=10.*ALP1 - IF (ALP1.LT.ALP) ALP=ALP1 -C ------------------------------------------------------------------ -C LIMIT CHANGE IN VARIABLE TO ALPHAX -C ------------------------------------------------------------------ - ALP11=1.0E+20 - DO 640 I=1,NDV - SI=ABS(S(I)) - XI=ABS(X(I)) - IF (SI.LT.1.0E-10.OR.XI.LT.0.1) GO TO 640 - ALP1=ALPHAX*XI/SI - IF (ALP1.LT.ALP11) ALP11=ALP1 -640 CONTINUE - IF (NVC.GT.0) ALP11=10.*ALP11 - IF (ALP11.LT.ALP) ALP=ALP11 - IF (ALP.GT.1.0E+20) ALP=1.0E+20 - IF (ALP.LE.1.0E-20) ALP=1.0E-20 - IF (IPRINT.LT.3) GO TO 660 - WRITE (6,1380) - DO 650 I=1,NDV,6 - M1=MIN0(NDV,I+5) -650 WRITE (6,1010) I,(S(J),J=I,M1) - WRITE (6,1110) SLOPE,ALP -660 CONTINUE - IF (NCON.GT.0.OR.NSIDE.GT.0) GO TO 680 -C ------------------------------------------------------------------ -C DO ONE-DIMENSIONAL SEARCH FOR UNCONSTRAINED FUNCTION -C ------------------------------------------------------------------ - JGOTO=0 -670 CONTINUE - CALL CNMN03 (X,S,SLOPE,ALP,FFF,A1,A2,A3,A4,F1,F2,F3,F4,APP,N1 - 1,NCAL,KOUNT,JGOTO) - IGOTO=4 - IF (JGOTO.GT.0) GO TO 950 - JDIR=1 -C PROCEED TO CONVERGENCE CHECK. - GO TO 700 -C ------------------------------------------------------------------ -C SOLVE ONE-DIMENSIONAL SEARCH PROBLEM FOR CONSTRAINED FUNCTION -C ------------------------------------------------------------------ -680 CONTINUE - JGOTO=0 -690 CONTINUE - CALL CNMN06 (X,VLB,VUB,G,SCAL,DF,S,G1,G2,CTAM,CTBM,SLOPE,ALP,A2,A3 - 1,A4,F1,F2,F3,CV1,CV2,CV3,CV4,ALPCA,ALPFES,ALPLN,ALPMIN,ALPNC,ALPSA - 2V,ALPSID,ALPTOT,ISC,N1,N2,NCAL,NVC,ICOUNT,IGOOD1,IGOOD2,IGOOD3,IGO - 3OD4,IBEST,III,NLNC,JGOTO) - IGOTO=5 - IF (JGOTO.GT.0) GO TO 950 - IF (NAC.EQ.0) JDIR=1 -C ------------------------------------------------------------------ -C ******************* UPDATE ALPHAX ************************** -C ------------------------------------------------------------------ -700 CONTINUE -710 CONTINUE - IF (ALP.GT.1.0E+19) ALP=0. -C UPDATE ALPHAX TO BE AVERAGE OF MAXIMUM CHANGE IN X(I) -C AND ALHPAX. - ALP11=0. - DO 720 I=1,NDV - SI=ABS(S(I)) - XI=ABS(X(I)) - IF (XI.LT.1.0E-10) GO TO 720 - ALP1=ALP*SI/XI - IF (ALP1.GT.ALP11) ALP11=ALP1 -720 CONTINUE - ALP11=.5*(ALP11+ALPHAX) - ALP12=5.*ALPHAX - IF (ALP11.GT.ALP12) ALP11=ALP12 - ALPHAX=ALP11 - NCOBJ=NCOBJ+1 -C ABSOLUTE CHANGE IN OBJECTIVE. - OBJD=OBJ1-OBJ - OBJB=ABS(OBJD) - IF (OBJB.LT.1.0E-10) OBJB=0. - IF (NAC.EQ.0.OR.OBJB.GT.0.) NCOBJ=0 - IF (NCOBJ.GT.1) NCOBJ=0 -C ------------------------------------------------------------------ -C PRINT -C ------------------------------------------------------------------ -C PRINT MOVE PARAMETER, NEW X-VECTOR AND CONSTRAINTS. - IF (IPRINT.LT.3) GO TO 730 - WRITE (6,1390) ALP -730 IF (IPRINT.LT.2) GO TO 800 - IF (OBJB.GT.0.) GO TO 740 - IF (IPRINT.EQ.2) WRITE (6,1400) ITER,OBJ - IF (IPRINT.GT.2) WRITE (6,1410) OBJ - GO TO 760 -740 IF (IPRINT.EQ.2) GO TO 750 - WRITE (6,1420) OBJ - GO TO 760 -750 WRITE (6,1430) ITER,OBJ -760 WRITE (6,1450) - DO 770 I=1,NDV - FF1=1. - IF (NSCAL.NE.0) FF1=SCAL(I) -770 G1(I)=FF1*X(I) - DO 780 I=1,NDV,6 - M1=MIN0(NDV,I+5) -780 WRITE (6,1010) I,(G1(J),J=I,M1) - IF (NCON.EQ.0) GO TO 800 - WRITE (6,1470) - DO 790 I=1,NCON,6 - M1=MIN0(NCON,I+5) -790 WRITE (6,1010) I,(G(J),J=I,M1) -800 CONTINUE -C -C THE FOLLOWING CODE WAS ADDED ON 3/5/81 -C -C IT HAD NOT BEEN REPORTED AS A FIX TO MAOB -C BUT WAS SENT TO JEFF STROUD A YEAR AGO -C SEE OTHER COMMENTS IN CONMIN SUBROUTINE FOR DELETIONS OF CODE -C ON 3/5/81 PERTAINING TO THIS FIX -C -C -C CHECK FEASIBILITY -C - IF(NCON.LE.0) GO TO 808 - NFEASCT=10 - DO 804 I=1,NCON - C1=CTAM - IF(ISC(I).GT.0) C1=CTBM - IF(G(I).LE.C1) GO TO 804 - NFEAS=NFEAS+1 - GO TO 806 - 804 CONTINUE - IF(NFEAS.GT.0) ABOBJ1=.05 - NFEAS=0 - PHI=5. - 806 IF(NFEAS.GE.NFEASCT) GO TO 810 - 808 CONTINUE -C -C END OF INSERTED FIX -C -C ------------------------------------------------------------------ -C CHECK CONVERGENCE -C ------------------------------------------------------------------ -C STOP IF ITER EQUALS ITMAX. - IF (ITER.GE.ITMAX) GO TO 810 -C ------------------------------------------------------------------ -C ABSOLUTE CHANGE IN OBJECTIVE -C ------------------------------------------------------------------ - OBJB=ABS(OBJD) - KOBJ=KOBJ+1 - IF (OBJB.GE.DABFUN.OR.NFEAS.GT.0) KOBJ=0 -C ------------------------------------------------------------------ -C RELATIVE CHANGE IN OBJECTIVE -C ------------------------------------------------------------------ - IF (ABS(OBJ1).GT.1.0E-10) OBJD=OBJD/ABS(OBJ1) - ABOBJ1=.5*(ABS(ABOBJ)+ABS(OBJD)) - ABOBJ=ABS(OBJD) - IOBJ=IOBJ+1 - IF (NVC.GT.0.OR.OBJD.GE.DELFUN) IOBJ=0 - IF (IOBJ.GE.ITRM.OR.KOBJ.GE.ITRM) GO TO 810 - OBJ1=OBJ -C ------------------------------------------------------------------ -C REDUCE CT IF OBJECTIVE FUNCTION IS CHANGING SLOWLY -C ------------------------------------------------------------------ - IF (IOBJ.LT.1.OR.NAC.EQ.0) GO TO 280 - CT=DCT*CT - CTL=CTL*DCTL - IF (ABS(CT).LT.CTMIN) CT=-CTMIN - IF (ABS(CTL).LT.CTLMIN) CTL=-CTLMIN - GO TO 280 -810 CONTINUE - IF (NAC.GE.N3) WRITE (6,1490) -C ------------------------------------------------------------------ -C **************** FINAL FUNCTION INFORMATION ******************** -C ------------------------------------------------------------------ - IF (NSCAL.EQ.0) GO TO 830 -C UN-SCALE THE DESIGN VARIABLES. - DO 820 I=1,NDV - XI=SCAL(I) - IF (NSIDE.EQ.0) GO TO 820 - VLB(I)=XI*VLB(I) - VUB(I)=XI*VUB(I) -820 X(I)=XI*X(I) -C ------------------------------------------------------------------ -C PRINT FINAL RESULTS -C ------------------------------------------------------------------ -830 IF (IPRINT.EQ.0.OR.NAC.GE.N3) GO TO 940 - WRITE (6,1500) - WRITE (6,1420) OBJ - WRITE (6,1450) - DO 840 I=1,NDV,6 - M1=MIN0(NDV,I+5) -840 WRITE (6,1010) I,(X(J),J=I,M1) - IF (NCON.EQ.0) GO TO 900 - WRITE (6,1470) - DO 850 I=1,NCON,6 - M1=MIN0(NCON,I+5) -850 WRITE (6,1010) I,(G(J),J=I,M1) -C DETERMINE WHICH CONSTRAINTS ARE ACTIVE AND PRINT. - NAC=0 - NVC=0 - DO 870 I=1,NCON - CTA=CTAM - IF (ISC(I).GT.0) CTA=CTBM - GI=G(I) - IF (GI.GT.CTA) GO TO 860 - IF (GI.LT.CT.AND.ISC(I).EQ.0) GO TO 870 - IF (GI.LT.CTL.AND.ISC(I).GT.0) GO TO 870 - NAC=NAC+1 - IC(NAC)=I - GO TO 870 -860 NVC=NVC+1 - MS1(NVC)=I -870 CONTINUE - WRITE (6,1060) NAC - IF (NAC.EQ.0) GO TO 880 - WRITE (6,1070) - WRITE (6,1480) (IC(J),J=1,NAC) -880 WRITE (6,1080) NVC - IF (NVC.EQ.0) GO TO 890 - WRITE (6,1070) - WRITE (6,1480) (MS1(J),J=1,NVC) -890 CONTINUE -900 CONTINUE - IF (NSIDE.EQ.0) GO TO 930 -C DETERMINE WHICH SIDE CONSTRAINTS ARE ACTIVE AND PRINT. - NAC=0 - DO 920 I=1,NDV - XI=X(I) - XID=VLB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XID-XI)/X12 - IF (GI.LT.-1.0E-6) GO TO 910 - NAC=NAC+1 - MS1(NAC)=-I -910 XID=VUB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XI-XID)/X12 - IF (GI.LT.-1.0E-6) GO TO 920 - NAC=NAC+1 - MS1(NAC)=I -920 CONTINUE - WRITE (6,1090) NAC - IF (NAC.EQ.0) GO TO 930 - WRITE (6,1100) - WRITE (6,1480) (MS1(J),J=1,NAC) -930 CONTINUE - WRITE (6,1150) - IF (ITER.GE.ITMAX) WRITE (6,1160) - IF (NFEAS.GE.NFEASCT) WRITE (6,1170) - IF (IOBJ.GE.ITRM) WRITE (6,1180) ITRM - IF (KOBJ.GE.ITRM) WRITE (6,1190) ITRM - WRITE (6,1200) ITER - WRITE (6,1510) NCAL(1) - IF (NCON.GT.0) WRITE (6,1520) NCAL(1) - IF (NFDG.NE.0) WRITE (6,1530) NCAL(2) - IF (NCON.GT.0.AND.NFDG.EQ.1) WRITE (6,1540) NCAL(2) -C ------------------------------------------------------------------ -C RE-SET BASIC PARAMETERS TO INPUT VALUES -C ------------------------------------------------------------------ -940 ITRM=IDM1 - ITMAX=IDM2 - ICNDIR=IDM3 - DELFUN=DM1 - DABFUN=DM2 - CT=DM3 - CTMIN=DM4 - CTL=DM5 - CTLMIN=DM6 - THETA=DM7 - PHI=DM8 - FDCH=DM9 - FDCHM=DM10 - ABOBJ1=DM11 - ALPHAX=DM12 - IGOTO=0 -950 CONTINUE - IF (NSCAL.EQ.0.OR.IGOTO.EQ.0) RETURN -C UN-SCALE VARIABLES. - DO 960 I=1,NDV - C(I)=X(I) -960 X(I)=X(I)*SCAL(I) - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -970 FORMAT (///5X,72HA COMPLETELY UNCONSTRAINED FUNCTION WITH A LINEAR - 1 OBJECTIVE IS SPECIFIED//10X,8HLINOBJ =,I5/10X,8HNCON =,I5/10X,8 - 2HNSIDE =,I5//5X,35HCONTROL RETURNED TO CALLING PROGRAM) -980 FORMAT (///5X,56HCONMIN HAS ACHIEVED A SOLUTION OF OBJ LESS THAN - - 11.0E+40/5X,32HSOLUTION APPEARS TO BE UNBOUNDED/5X,26HOPTIMIZATION - 2IS TERMINATED) -990 FORMAT (5X,17HCONSTRAINT NUMBER,I5) -1000 FORMAT (5X,27HSIDE CONSTRAINT ON VARIABLE,I5) -1010 FORMAT (3X,I5,1H),2X,6E13.5) -1020 FORMAT (/5X,35HLINEAR CONSTRAINT IDENTIFIERS (ISC)/5X,36HNON-ZERO - 1INDICATES LINEAR CONSTRAINT) -1030 FORMAT (3X,I5,1H),2X,15I5) -1040 FORMAT (/5X,26HALL CONSTRAINTS ARE LINEAR) -1050 FORMAT (/5X,30HALL CONSTRAINTS ARE NON-LINEAR) -1060 FORMAT (/5X,9HTHERE ARE,I5,19H ACTIVE CONSTRAINTS) -1070 FORMAT (5X,22HCONSTRAINT NUMBERS ARE) -1080 FORMAT (/5X,9HTHERE ARE,I5,21H VIOLATED CONSTRAINTS) -1090 FORMAT (/5X,9HTHERE ARE,I5,24H ACTIVE SIDE CONSTRAINTS) -1100 FORMAT (5X,43HDECISION VARIABLES AT LOWER OR UPPER BOUNDS,30H (MIN - 1US INDICATES LOWER BOUND)) -1110 FORMAT (/5X,22HONE-DIMENSIONAL SEARCH/5X,15HINITIAL SLOPE =,E12.4, - 12X,16HPROPOSED ALPHA =,E12.4) -1120 FORMAT (///5X,35H* * CONMIN DETECTS VLB(I).GT.VUB(I)/5X,57HFIX IS - 1SET X(I)=VLB(I)=VUB(I) = .5*(VLB(I)+VUB(I) FOR I =,I5) -1130 FORMAT (///5X,41H* * CONMIN DETECTS INITIAL X(I).LT.VLB(I)/5X,6HX( - 1I) =,E12.4,2X,8HVLB(I) =,E12.4/5X,35HX(I) IS SET EQUAL TO VLB(I) F - 2OR I =,I5) -1140 FORMAT (///5X,41H* * CONMIN DETECTS INITIAL X(I).GT.VUB(I)/5X,6HX( - 1I) =,E12.4,2X,8HVUB(I) =,E12.4/5X,35HX(I) IS SET EQUAL TO VUB(I) F - 2OR I =,I5) -1150 FORMAT (/5X,21HTERMINATION CRITERION) -1160 FORMAT (10X,17HITER EQUALS ITMAX) -1170 FORMAT (10X,'NFEASCT CONSECUTIVE ITERATIONS FAILED TO PRODUCE A - 1FEASIBLE DESIGN') -1180 FORMAT (10X,43HABS(1-OBJ(I-1)/OBJ(I)) LESS THAN DELFUN FOR,I3,11H - 1ITERATIONS) -1190 FORMAT (10X,43HABS(OBJ(I)-OBJ(I-1)) LESS THAN DABFUN FOR,I3,11H - 1ITERATIONS) -1200 FORMAT (/5X,22HNUMBER OF ITERATIONS =,I5) -1210 FORMAT (/5X,28HCONSTRAINT PARAMETER, BETA =,E14.5) -1220 FORMAT (1H1,////12X,27(2H* )/12X,1H*,51X,1H*/12X,1H*,20X,11HC O N - 1M I N,20X,1H*/12X,1H*,51X,1H*/12X,1H*,15X,21H FORTRAN PROGRAM FOR - 2,15X,1H*/12X,1H*,51X,1H*/12X,1H*,9X,33HCONSTRAINED FUNCTION MINIMI - 3ZATION,9X,1H*/12X,1H*,51X,1H*/12X,27(2H* )) -1230 FORMAT (////5X,33HCONSTRAINED FUNCTION MINIMIZATION//5X,18HCONTROL - 1 PARAMETERS) -1240 FORMAT (/5X,60HIPRINT NDV ITMAX NCON NSIDE ICNDIR NSC - 1AL NFDG/8I8//5X,12HLINOBJ ITRM,5X,2HN1,6X,2HN2,6X,2HN3,6X,2HN4, - 26X,2HN5/8I8) -1250 FORMAT (/9X,4HFDCH,12X,5HFDCHM,11X,6HALPHAX,10X,6HABOBJ1/1X,4(2X,E - 114.5)) -1260 FORMAT (/9X,2HCT,14X,5HCTMIN,11X,3HCTL,13X,6HCTLMIN/1X,4(2X,E14.5) - 1//9X,5HTHETA,11X,3HPHI,13X,6HDELFUN,10X,6HDABFUN/1X,4(2X,E14.5)) -1270 FORMAT (/5X,40HLOWER BOUNDS ON DECISION VARIABLES (VLB)) -1280 FORMAT (/5X,40HUPPER BOUNDS ON DECISION VARIABLES (VUB)) -1290 FORMAT (////5X,35HUNCONSTRAINED FUNCTION MINIMIZATION//5X,18HCONTR - 1OL PARAMETERS) -1300 FORMAT (/5X,21HSCALING VECTOR (SCAL)) -1310 FORMAT (////5X,22HBEGIN ITERATION NUMBER,I5) -1320 FORMAT (/5X,4HCT =,E14.5,5X,5HCTL =,E14.5,5X,5HPHI =,E14.5) -1330 FORMAT (/5X,25HNEW SCALING VECTOR (SCAL)) -1340 FORMAT (/5X,15HGRADIENT OF OBJ) -1350 FORMAT (/5X,44HGRADIENTS OF ACTIVE AND VIOLATED CONSTRAINTS) -1360 FORMAT (1H ) -1370 FORMAT (/5X,37HPUSH-OFF FACTORS, (THETA(I), I=1,NAC)) -1380 FORMAT (/5X,27HSEARCH DIRECTION (S-VECTOR)) -1390 FORMAT (/5X,18HCALCULATED ALPHA =,E14.5) -1400 FORMAT (////5X,6HITER =,I5,5X,5HOBJ =,E14.5,5X,16HNO CHANGE IN OBJ - 1) -1410 FORMAT (/5X,5HOBJ =,E15.6,5X,16HNO CHANGE ON OBJ) -1420 FORMAT (/5X,5HOBJ =,E15.6) -1430 FORMAT (////5X,6HITER =,I5,5X,5HOBJ =,E14.5) -1440 FORMAT (//5X,28HINITIAL FUNCTION INFORMATION//5X,5HOBJ =,E15.6) -1450 FORMAT (/5X,29HDECISION VARIABLES (X-VECTOR)) -1460 FORMAT (3X,7E13.4) -1470 FORMAT (/5X,28HCONSTRAINT VALUES (G-VECTOR)) -1480 FORMAT (5X,15I5) -1490 FORMAT (/5X,59HTHE NUMBER OF ACTIVE AND VIOLATED CONSTRAINTS EXCEE - 1DS N3-1./5X,66HDIMENSIONED SIZE OF MATRICES A AND B AND VECTOR IC - 2IS INSUFFICIENT/5X,61HOPTIMIZATION TERMINATED AND CONTROL RETURNED - 3 TO MAIN PROGRAM.) -1500 FORMAT (1H1,////4X,30HFINAL OPTIMIZATION INFORMATION) -1510 FORMAT (/5X,32HOBJECTIVE FUNCTION WAS EVALUATED,8X,I5,2X,5HTIMES) -1520 FORMAT (/5X,35HCONSTRAINT FUNCTIONS WERE EVALUATED,I10,2X,5HTIMES) -1530 FORMAT (/5X,36HGRADIENT OF OBJECTIVE WAS CALCULATED,I9,2X,5HTIMES) -1540 FORMAT (/5X,40HGRADIENTS OF CONSTRAINTS WERE CALCULATED,I5,2X,5HTI - 1MES) - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn00.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn00.f deleted file mode 100644 index b20377f3d..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn00.f +++ /dev/null @@ -1,904 +0,0 @@ - SUBROUTINE CNMN00 (X,VLB,VUB,G,SCAL,DF,A,S,G1,G2,B,C,ISC,IC,MS1,N1 - 1,N2,N3,N4,N5) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - COMMON /OUTPUT/ IOUT -C -C NFEASCT ADDED TO COMMON BLOCK BY KCYOUNG ON 4/14/92 TO ALLOW MORE -C THAN 10 ITERATION ATTEMPTS. NFEASCT BECOMES AN INPUT VALUE -C - DIMENSION X(N1), VLB(N1), VUB(N1), G(N2), SCAL(N1), DF(N1), A(N1,N - 13), S(N1), G1(N2), G2(N2), B(N3,N3), C(N4), ISC(N2), IC(N3), MS1(N - 25) - COMMON /CONSAV/ DM1,DM2,DM3,DM4,DM5,DM6,DM7,DM8,DM9,DM10,DM11,DM12 - 1,DCT,DCTL,PHI,ABOBJ,CTA,CTAM,CTBM,OBJ1,SLOPE,DX,DX1,FI,XI,DFTDF1,A - 2LP,FFF,A1,A2,A3,A4,F1,F2,F3,F4,CV1,CV2,CV3,CV4,APP,ALPCA,ALPFES,AL - 3PLN,ALPMIN,ALPNC,ALPSAV,ALPSID,ALPTOT,RSPACE,IDM1,IDM2,IDM3,JDIR,I - 4OBJ,KOBJ,KCOUNT,NCAL(2),NFEAS,MSCAL,NCOBJ,NVC,KOUNT,ICOUNT,IGOOD1, - 5IGOOD2,IGOOD3,IGOOD4,IBEST,III,NLNC,JGOTO,ISPACE(2) -C ROUTINE TO SOLVE CONSTRAINED OR UNCONSTRAINED FUNCTION -C MINIMIZATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C * * * * * * * * * * * JUNE, 1979 VERSION * * * * * * * * * * * -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C REFERENCE; CONMIN - A FORTRAN PROGRAM FOR CONSTRAINED FUNCTION -C MINIMIZATION: USER'S MANUAL, BY G. N. VANDERPLAATS, -C NASA TM X-62,282, AUGUST, 1973. -C STORAGE REQUIREMENTS: -C PROGRAM - 7000 DECIMAL WORDS (CDC COMPUTER) -C ARRAYS - APPROX. 2*(NDV**2)+26*NDV+4*NCON, -C WHERE N3 = NDV+2. -C RE-SCALE VARIABLES IF REQUIRED. - IF (NSCAL.EQ.0.OR.IGOTO.EQ.0) GO TO 20 - DO 10 I=1,NDV -10 X(I)=C(I) -20 CONTINUE -C CONSTANTS. - NDV1=NDV+1 - NDV2=NDV+2 - IF (IGOTO.EQ.0) GO TO 40 -C ------------------------------------------------------------------ -C CHECK FOR UNBOUNDED SOLUTION -C ------------------------------------------------------------------ -C STOP IF OBJ IS LESS THAN -1.0E+20 - IF (OBJ.GT.-1.0E+20) GO TO 30 - WRITE (IOUT,980) - GO TO 810 -30 CONTINUE - GO TO (160,390,380,670,690),IGOTO -C ------------------------------------------------------------------ -C SAVE INPUT CONTROL PARAMETERS -C ------------------------------------------------------------------ -40 CONTINUE - IF (IPRINT.GT.0) WRITE (IOUT,1220) - IF (LINOBJ.EQ.0.OR.(NCON.GT.0.OR.NSIDE.GT.0)) GO TO 50 -C TOTALLY UNCONSTRAINED FUNCTION WITH LINEAR OBJECTIVE. -C SOLUTION IS UNBOUNDED. - WRITE (IOUT,970) LINOBJ,NCON,NSIDE - RETURN -50 CONTINUE - IDM1=ITRM - IDM2=ITMAX - IDM3=ICNDIR - DM1=DELFUN - DM2=DABFUN - DM3=CT - DM4=CTMIN - DM5=CTL - DM6=CTLMIN - DM7=THETA - DM8=PHI - DM9=FDCH - DM10=FDCHM - DM11=ABOBJ1 - DM12=ALPHAX -C ------------------------------------------------------------------ -C DEFAULTS -C ------------------------------------------------------------------ - IF (ITRM.LE.0) ITRM=3 - IF (ITMAX.LE.0) ITMAX=20 - NDV1=NDV+1 - IF (ICNDIR.EQ.0) ICNDIR=NDV1 - IF (DELFUN.LE.0.) DELFUN=.0001 - CT=-ABS(CT) - IF (CT.GE.0.) CT=-.1 - CTMIN=ABS(CTMIN) - IF (CTMIN.LE.0.) CTMIN=.004 - CTL=-ABS(CTL) - IF (CTL.GE.0.) CTL=-0.01 - CTLMIN=ABS(CTLMIN) - IF (CTLMIN.LE.0.) CTLMIN=.001 - IF (THETA.LE.0.) THETA=1. - IF (ABOBJ1.LE.0.) ABOBJ1=.1 - IF (ALPHAX.LE.0.) ALPHAX=.1 - IF (FDCH.LE.0.) FDCH=.01 - IF (FDCHM.LE.0.) FDCHM=.01 -C ------------------------------------------------------------------ -C INITIALIZE INTERNAL PARAMETERS -C ------------------------------------------------------------------ - INFOG=0 - ITER=0 - JDIR=0 - IOBJ=0 - KOBJ=0 - NDV2=NDV+2 - KCOUNT=0 - NCAL(1)=0 - NCAL(2)=0 - NAC=0 - NFEAS=0 - MSCAL=NSCAL - CT1=ITRM - CT1=1./CT1 - DCT=(CTMIN/ABS(CT))**CT1 - DCTL=(CTLMIN/ABS(CTL))**CT1 - PHI=5. - ABOBJ=ABOBJ1 - NCOBJ=0 - CTAM=ABS(CTMIN) - CTBM=ABS(CTLMIN) -C CALCULATE NUMBER OF LINEAR CONSTRAINTS, NLNC. - NLNC=0 - IF (NCON.EQ.0) GO TO 70 - DO 60 I=1,NCON - IF (ISC(I).GT.0) NLNC=NLNC+1 -60 CONTINUE -70 CONTINUE -C ------------------------------------------------------------------ -C CHECK TO BE SURE THAT SIDE CONSTRAINTS ARE SATISFIED -C ------------------------------------------------------------------ - IF (NSIDE.EQ.0) GO TO 110 - DO 100 I=1,NDV - IF (VLB(I).LE.VUB(I)) GO TO 80 - XX=.5*(VLB(I)+VUB(I)) - X(I)=XX - VLB(I)=XX - VUB(I)=XX - WRITE (IOUT,1120) I -80 CONTINUE - XX=X(I)-VLB(I) - IF (XX.GE.0.) GO TO 90 -C LOWER BOUND VIOLATED. - WRITE (IOUT,1130) X(I),VLB(I),I - X(I)=VLB(I) - GO TO 100 -90 CONTINUE - XX=VUB(I)-X(I) - IF (XX.GE.0.) GO TO 100 - WRITE (IOUT,1140) X(I),VUB(I),I - X(I)=VUB(I) -100 CONTINUE -110 CONTINUE -C ------------------------------------------------------------------ -C INITIALIZE SCALING VECTOR, SCAL -C ------------------------------------------------------------------ - IF (NSCAL.EQ.0) GO TO 150 - IF (NSCAL.LT.0) GO TO 130 - DO 120 I=1,NDV -120 SCAL(I)=1. - GO TO 150 -130 CONTINUE - DO 140 I=1,NDV - SI=ABS(SCAL(I)) - IF (SI.LT.1.0E-20) SI=1.0E-5 - SCAL(I)=SI - SI=1./SI - X(I)=X(I)*SI - IF (NSIDE.EQ.0) GO TO 140 - VLB(I)=VLB(I)*SI - VUB(I)=VUB(I)*SI -140 CONTINUE -150 CONTINUE -C ------------------------------------------------------------------ -C ***** CALCULATE INITIAL FUNCTION AND CONSTRAINT VALUES ***** -C ------------------------------------------------------------------ - INFO=1 - NCAL(1)=1 - IGOTO=1 - GO TO 950 -160 CONTINUE - OBJ1=OBJ - IF (DABFUN.LE.0.) DABFUN=.001*ABS(OBJ) - IF (DABFUN.LT.1.0E-10) DABFUN=1.0E-10 - IF (IPRINT.LE.0) GO TO 270 -C ------------------------------------------------------------------ -C PRINT INITIAL DESIGN INFORMATION -C ------------------------------------------------------------------ - IF (IPRINT.LE.1) GO TO 230 - IF (NSIDE.EQ.0.AND.NCON.EQ.0) WRITE (IOUT,1290) - IF (NSIDE.NE.0.OR.NCON.GT.0) WRITE (IOUT,1230) - WRITE (IOUT,1240) IPRINT,NDV,ITMAX,NCON,NSIDE,ICNDIR,NSCAL,NFDG - 1,LINOBJ,ITRM,N1,N2,N3,N4,N5 - WRITE (IOUT,1260) CT,CTMIN,CTL,CTLMIN,THETA,PHI,DELFUN,DABFUN - WRITE (IOUT,1250) FDCH,FDCHM,ALPHAX,ABOBJ1 - IF (NSIDE.EQ.0) GO TO 190 - WRITE (IOUT,1270) - DO 170 I=1,NDV,6 - M1=MIN0(NDV,I+5) -170 WRITE (IOUT,1010) I,(VLB(J),J=I,M1) - WRITE (IOUT,1280) - DO 180 I=1,NDV,6 - M1=MIN0(NDV,I+5) -180 WRITE (IOUT,1010) I,(VUB(J),J=I,M1) -190 CONTINUE - IF (NSCAL.GE.0) GO TO 200 - WRITE (IOUT,1300) - WRITE (IOUT,1460) (SCAL(I),I=1,NDV) -200 CONTINUE - IF (NCON.EQ.0) GO TO 230 - IF (NLNC.EQ.0.OR.NLNC.EQ.NCON) GO TO 220 - WRITE (IOUT,1020) - DO 210 I=1,NCON,15 - M1=MIN0(NCON,I+14) -210 WRITE (IOUT,1030) I,(ISC(J),J=I,M1) - GO TO 230 -220 IF (NLNC.EQ.NCON) WRITE (IOUT,1040) - IF (NLNC.EQ.0) WRITE (IOUT,1050) -230 CONTINUE - WRITE (IOUT,1440) OBJ - WRITE (IOUT,1450) - DO 240 I=1,NDV - X1=1. - IF (NSCAL.NE.0) X1=SCAL(I) -240 G1(I)=X(I)*X1 - DO 250 I=1,NDV,6 - M1=MIN0(NDV,I+5) -250 WRITE (IOUT,1010) I,(G1(J),J=I,M1) - IF (NCON.EQ.0) GO TO 270 - WRITE (IOUT,1470) - DO 260 I=1,NCON,6 - M1=MIN0(NCON,I+5) -260 WRITE (IOUT,1010) I,(G(J),J=I,M1) -270 CONTINUE - IF (IPRINT.GT.1) WRITE (IOUT,1360) -C ------------------------------------------------------------------ -C ******************** BEGIN MINIMIZATION ************************ -C ------------------------------------------------------------------ -280 CONTINUE - ITER=ITER+1 - IF (ABOBJ1.LT..0001) ABOBJ1=.0001 - IF (ABOBJ1.GT..2) ABOBJ1=.2 - IF (ALPHAX.GT.1.) ALPHAX=1. - IF (ALPHAX.LT..001) ALPHAX=.001 -C -C THE FOLLOWING TWO LINES OF CODE WERE COMMENTED OUT ON 3/5/81 -C -C NFEAS=NFEAS+1 -C IF (NFEAS.GT.10) GO TO 810 - IF (IPRINT.GT.2) WRITE (IOUT,1310) ITER - IF (IPRINT.GT.3.AND.NCON.GT.0) WRITE (IOUT,1320) CT,CTL,PHI - CTA=ABS(CT) - IF (NCOBJ.EQ.0) GO TO 340 -C ------------------------------------------------------------------ -C NO MOVE ON LAST ITERATION. DELETE CONSTRAINTS THAT ARE NO -C LONGER ACTIVE. -C ------------------------------------------------------------------ - NNAC=NAC - DO 290 I=1,NNAC - IF (IC(I).GT.NCON) NAC=NAC-1 -290 CONTINUE - IF (NAC.LE.0) GO TO 420 - NNAC=NAC - DO 330 I=1,NNAC -300 NIC=IC(I) - CT1=CT - IF (ISC(NIC).GT.0) CT1=CTL - IF (G(NIC).GT.CT1) GO TO 330 - NAC=NAC-1 - IF (I.GT.NAC) GO TO 420 - DO 320 K=I,NAC - II=K+1 - DO 310 J=1,NDV2 -310 A(J,K)=A(J,II) -320 IC(K)=IC(II) - GO TO 300 -330 CONTINUE - GO TO 420 -340 CONTINUE - IF (MSCAL.LT.NSCAL.OR.NSCAL.EQ.0) GO TO 360 - IF (NSCAL.LT.0.AND.KCOUNT.LT.ICNDIR) GO TO 360 - MSCAL=0 - KCOUNT=0 -C ------------------------------------------------------------------ -C SCALE VARIABLES -C ------------------------------------------------------------------ - DO 350 I=1,NDV - SI=SCAL(I) - XI=SI*X(I) - SIB=SI - IF (NSCAL.GT.0) SI=ABS(XI) - IF (SI.LT.1.0E-10) GO TO 350 - SCAL(I)=SI - SI=1./SI - X(I)=XI*SI - IF (NSIDE.EQ.0) GO TO 350 - VLB(I)=SIB*SI*VLB(I) - VUB(I)=SIB*SI*VUB(I) -350 CONTINUE - IF (IPRINT.LT.4.OR.(NSCAL.LT.0.AND.ITER.GT.1)) GO TO 360 - WRITE (IOUT,1330) - WRITE (IOUT,1460) (SCAL(I),I=1,NDV) -360 CONTINUE - MSCAL=MSCAL+1 - NAC=0 -C ------------------------------------------------------------------ -C OBTAIN GRADIENTS OF OBJECTIVE AND ACTIVE CONSTRAINTS -C ------------------------------------------------------------------ - INFO=2 - NCAL(2)=NCAL(2)+1 - IF (NFDG.NE.1) GO TO 370 - IGOTO=2 - GO TO 950 -370 CONTINUE - JGOTO=0 -380 CONTINUE - CALL CNMN01 (JGOTO,X,DF,G,ISC,IC,A,G1,VLB,VUB,SCAL,C,NCAL,DX,DX1 - 1,FI,XI,III,N1,N2,N3,N4) - IGOTO=3 - IF (JGOTO.GT.0) GO TO 950 -390 CONTINUE - INFO=1 - IF (NAC.GE.N3) GO TO 810 - IF (NSCAL.EQ.0.OR.NFDG.EQ.0) GO TO 420 -C ------------------------------------------------------------------ -C SCALE GRADIENTS -C ------------------------------------------------------------------ -C SCALE GRADIENT OF OBJECTIVE FUNCTION. - DO 400 I=1,NDV -400 DF(I)=DF(I)*SCAL(I) - IF (NFDG.EQ.2.OR.NAC.EQ.0) GO TO 420 -C SCALE GRADIENTS OF ACTIVE CONSTRAINTS. - DO 410 J=1,NDV - SCJ=SCAL(J) - DO 410 I=1,NAC -410 A(J,I)=A(J,I)*SCJ -420 CONTINUE - IF (IPRINT.LT.3.OR.NCON.EQ.0) GO TO 470 -C ------------------------------------------------------------------ -C PRINT -C ------------------------------------------------------------------ -C PRINT ACTIVE AND VIOLATED CONSTRAINT NUMBERS. - M1=0 - M2=N3 - IF (NAC.EQ.0) GO TO 450 - DO 440 I=1,NAC - J=IC(I) - IF (J.GT.NCON) GO TO 440 - GI=G(J) - C1=CTAM - IF (ISC(J).GT.0) C1=CTBM - GI=GI-C1 - IF (GI.GT.0.) GO TO 430 -C ACTIVE CONSTRAINT. - M1=M1+1 - MS1(M1)=J - GO TO 440 -430 M2=M2+1 -C VIOLATED CONSTRAINT. - MS1(M2)=J -440 CONTINUE -450 M3=M2-N3 - WRITE (IOUT,1060) M1 - IF (M1.EQ.0) GO TO 460 - WRITE (IOUT,1070) - WRITE (IOUT,1480) (MS1(I),I=1,M1) -460 WRITE (IOUT,1080) M3 - IF (M3.EQ.0) GO TO 470 - WRITE (IOUT,1070) - M3=N3+1 - WRITE (IOUT,1480) (MS1(I),I=M3,M2) -470 CONTINUE -C ------------------------------------------------------------------ -C CALCULATE GRADIENTS OF ACTIVE SIDE CONSTRAINTS -C ------------------------------------------------------------------ - IF (NSIDE.EQ.0) GO TO 530 - MCN1=NCON - M1=0 - DO 510 I=1,NDV -C LOWER BOUND. - XI=X(I) - XID=VLB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XID-XI)/X12 - IF (GI.LT.-1.0E-6) GO TO 490 - M1=M1+1 - MS1(M1)=-I - NAC=NAC+1 - IF (NAC.GE.N3) GO TO 810 - MCN1=MCN1+1 - DO 480 J=1,NDV -480 A(J,NAC)=0. - A(I,NAC)=-1. - IC(NAC)=MCN1 - G(MCN1)=GI - ISC(MCN1)=1 -C UPPER BOUND. -490 XID=VUB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XI-XID)/X12 - IF (GI.LT.-1.0E-6) GO TO 510 - M1=M1+1 - MS1(M1)=I - NAC=NAC+1 - IF (NAC.GE.N3) GO TO 810 - MCN1=MCN1+1 - DO 500 J=1,NDV -500 A(J,NAC)=0. - A(I,NAC)=1. - IC(NAC)=MCN1 - G(MCN1)=GI - ISC(MCN1)=1 -510 CONTINUE -C ------------------------------------------------------------------ -C PRINT -C ------------------------------------------------------------------ -C PRINT ACTIVE SIDE CONSTRAINT NUMBERS. - IF (IPRINT.LT.3) GO TO 530 - WRITE (IOUT,1090) M1 - IF (M1.EQ.0) GO TO 530 - WRITE (IOUT,1100) - WRITE(6,1480) (MS1(J),J=1,M1) -530 CONTINUE -C PRINT GRADIENTS OF ACTIVE AND VIOLATED CONSTRAINTS. - IF (IPRINT.LT.4) GO TO 570 - WRITE (IOUT,1340) - DO 540 I=1,NDV,6 - M1=MIN0(NDV,I+5) -540 WRITE (IOUT,1010) I,(DF(J),J=I,M1) - IF (NAC.EQ.0) GO TO 570 - WRITE (IOUT,1350) - DO 560 I=1,NAC - M1=IC(I) - M2=M1-NCON - M3=0 - IF (M2.GT.0) M3=IABS(MS1(M2)) - IF (M2.LE.0) WRITE (IOUT,990) M1 - IF (M2.GT.0) WRITE (IOUT,1000) M3 - DO 550 K=1,NDV,6 - M1=MIN0(NDV,K+5) -550 WRITE (IOUT,1010) K,(A(J,I),J=K,M1) -560 WRITE (IOUT,1360) -570 CONTINUE -C ------------------------------------------------------------------ -C ****************** DETERMINE SEARCH DIRECTION ******************* -C ------------------------------------------------------------------ - ALP=1.0E+20 - IF (NAC.GT.0) GO TO 580 -C ------------------------------------------------------------------ -C UNCONSTRAINED FUNCTION -C ------------------------------------------------------------------ -C FIND DIRECTION OF STEEPEST DESCENT OR CONJUGATE DIRECTION. -C -C S. N. 575 ADDED ON 2/25/81 -C - 575 NVC=0 - NFEAS=0 - KCOUNT=KCOUNT+1 -C IF KCOUNT.GT.ICNDIR RESTART CONJUGATE DIRECTION ALGORITHM. - IF (KCOUNT.GT.ICNDIR.OR.IOBJ.EQ.2) KCOUNT=1 - IF (KCOUNT.EQ.1) JDIR=0 -C IF JDIR = 0 FIND DIRECTION OF STEEPEST DESCENT. - CALL CNMN02 (JDIR,SLOPE,DFTDF1,DF,S,N1) - GO TO 630 -580 CONTINUE -C ------------------------------------------------------------------ -C CONSTRAINED FUNCTION -C ------------------------------------------------------------------ -C FIND USABLE-FEASIBLE DIRECTION. - KCOUNT=0 - JDIR=0 - PHI=10.*PHI - IF (PHI.GT.1000.) PHI=1000. -C -C THE FOLLOWING LINE OF CODE WAS COMMENTED OUT ON 3/5/81 -C -C IF (NFEAS.EQ.1) PHI=5. -C CALCULATE DIRECTION, S. - CALL CNMN05 (G,DF,A,S,B,C,SLOPE,PHI,ISC,IC,MS1,NVC,N1,N2,N3,N4,N5) -C -C THE FOLLOWING LINE WAS ADDED ON 2/25/81 -C - IF(NAC.EQ.0) GO TO 575 -C -C THE FOLLOWING FIVE LINES WERE COMMENTED OUT ON 3/5/81 -C REASON : THEY WERE NOT IN G. VANDERPLAATS LISTING -C -C IF THIS DESIGN IS FEASIBLE AND LAST ITERATION WAS INFEASIBLE, -C SET ABOBJ1=.05 (5 PERCENT). -C IF (NVC.EQ.0.AND.NFEAS.GT.1) ABOBJ1=.05 -C IF (NVC.EQ.0) NFEAS=0 - IF (IPRINT.LT.3) GO TO 600 - WRITE (IOUT,1370) - DO 590 I=1,NAC,6 - M1=MIN0(NAC,I+5) -590 WRITE (IOUT,1010) I,(A(NDV1,J),J=I,M1) - WRITE (IOUT,1210) S(NDV1) -600 CONTINUE -C ------------------------------------------------------------------ -C ****************** ONE-DIMENSIONAL SEARCH ************************ -C ------------------------------------------------------------------ - IF (S(NDV1).LT.1.0E-6.AND.NVC.EQ.0) GO TO 710 -C ------------------------------------------------------------------ -C FIND ALPHA TO OBTAIN A FEASIBLE DESIGN -C ------------------------------------------------------------------ - IF (NVC.EQ.0) GO TO 630 - ALP=-1. - DO 620 I=1,NAC - NCI=IC(I) - C1=G(NCI) - CTC=CTAM - IF (ISC(NCI).GT.0) CTC=CTBM - IF (C1.LE.CTC) GO TO 620 - ALP1=0. - DO 610 J=1,NDV -610 ALP1=ALP1+S(J)*A(J,I) - ALP1=ALP1*A(NDV2,I) - IF (ABS(ALP1).LT.1.0E-20) GO TO 620 - ALP1=-C1/ALP1 - IF (ALP1.GT.ALP) ALP=ALP1 -620 CONTINUE -630 CONTINUE -C ------------------------------------------------------------------ -C LIMIT CHANCE TO ABOBJ1*OBJ -C ------------------------------------------------------------------ - ALP1=1.0E+20 - SI=ABS(OBJ) - IF (SI.LT..01) SI=.01 - IF (ABS(SLOPE).GT.1.0E-20) ALP1=ABOBJ1*SI/SLOPE - ALP1=ABS(ALP1) - IF (NVC.GT.0) ALP1=10.*ALP1 - IF (ALP1.LT.ALP) ALP=ALP1 -C ------------------------------------------------------------------ -C LIMIT CHANGE IN VARIABLE TO ALPHAX -C ------------------------------------------------------------------ - ALP11=1.0E+20 - DO 640 I=1,NDV - SI=ABS(S(I)) - XI=ABS(X(I)) - IF (SI.LT.1.0E-10.OR.XI.LT.0.1) GO TO 640 - ALP1=ALPHAX*XI/SI - IF (ALP1.LT.ALP11) ALP11=ALP1 -640 CONTINUE - IF (NVC.GT.0) ALP11=10.*ALP11 - IF (ALP11.LT.ALP) ALP=ALP11 - IF (ALP.GT.1.0E+20) ALP=1.0E+20 - IF (ALP.LE.1.0E-20) ALP=1.0E-20 - IF (IPRINT.LT.3) GO TO 660 - WRITE (IOUT,1380) - DO 650 I=1,NDV,6 - M1=MIN0(NDV,I+5) -650 WRITE (IOUT,1010) I,(S(J),J=I,M1) - WRITE (IOUT,1110) SLOPE,ALP -660 CONTINUE - IF (NCON.GT.0.OR.NSIDE.GT.0) GO TO 680 -C ------------------------------------------------------------------ -C DO ONE-DIMENSIONAL SEARCH FOR UNCONSTRAINED FUNCTION -C ------------------------------------------------------------------ - JGOTO=0 -670 CONTINUE - CALL CNMN03 (X,S,SLOPE,ALP,FFF,A1,A2,A3,A4,F1,F2,F3,F4,APP,N1 - 1,NCAL,KOUNT,JGOTO) - IGOTO=4 - IF (JGOTO.GT.0) GO TO 950 - JDIR=1 -C PROCEED TO CONVERGENCE CHECK. - GO TO 700 -C ------------------------------------------------------------------ -C SOLVE ONE-DIMENSIONAL SEARCH PROBLEM FOR CONSTRAINED FUNCTION -C ------------------------------------------------------------------ -680 CONTINUE - JGOTO=0 -690 CONTINUE - CALL CNMN06 (X,VLB,VUB,G,SCAL,DF,S,G1,G2,CTAM,CTBM,SLOPE,ALP,A2,A3 - 1,A4,F1,F2,F3,CV1,CV2,CV3,CV4,ALPCA,ALPFES,ALPLN,ALPMIN,ALPNC,ALPSA - 2V,ALPSID,ALPTOT,ISC,N1,N2,NCAL,NVC,ICOUNT,IGOOD1,IGOOD2,IGOOD3,IGO - 3OD4,IBEST,III,NLNC,JGOTO) - IGOTO=5 - IF (JGOTO.GT.0) GO TO 950 - IF (NAC.EQ.0) JDIR=1 -C ------------------------------------------------------------------ -C ******************* UPDATE ALPHAX ************************** -C ------------------------------------------------------------------ -700 CONTINUE -710 CONTINUE - IF (ALP.GT.1.0E+19) ALP=0. -C UPDATE ALPHAX TO BE AVERAGE OF MAXIMUM CHANGE IN X(I) -C AND ALHPAX. - ALP11=0. - DO 720 I=1,NDV - SI=ABS(S(I)) - XI=ABS(X(I)) - IF (XI.LT.1.0E-10) GO TO 720 - ALP1=ALP*SI/XI - IF (ALP1.GT.ALP11) ALP11=ALP1 -720 CONTINUE - ALP11=.5*(ALP11+ALPHAX) - ALP12=5.*ALPHAX - IF (ALP11.GT.ALP12) ALP11=ALP12 - ALPHAX=ALP11 - NCOBJ=NCOBJ+1 -C ABSOLUTE CHANGE IN OBJECTIVE. - OBJD=OBJ1-OBJ - OBJB=ABS(OBJD) - IF (OBJB.LT.1.0E-10) OBJB=0. - IF (NAC.EQ.0.OR.OBJB.GT.0.) NCOBJ=0 - IF (NCOBJ.GT.1) NCOBJ=0 -C ------------------------------------------------------------------ -C PRINT -C ------------------------------------------------------------------ -C PRINT MOVE PARAMETER, NEW X-VECTOR AND CONSTRAINTS. - IF (IPRINT.LT.3) GO TO 730 - WRITE (IOUT,1390) ALP -730 IF (IPRINT.LT.2) GO TO 800 - IF (OBJB.GT.0.) GO TO 740 - IF (IPRINT.EQ.2) WRITE (IOUT,1400) ITER,OBJ - IF (IPRINT.GT.2) WRITE (IOUT,1410) OBJ - GO TO 760 -740 IF (IPRINT.EQ.2) GO TO 750 - WRITE (IOUT,1420) OBJ - GO TO 760 -750 WRITE (IOUT,1430) ITER,OBJ -760 WRITE (IOUT,1450) - DO 770 I=1,NDV - FF1=1. - IF (NSCAL.NE.0) FF1=SCAL(I) -770 G1(I)=FF1*X(I) - DO 780 I=1,NDV,6 - M1=MIN0(NDV,I+5) -780 WRITE (IOUT,1010) I,(G1(J),J=I,M1) - IF (NCON.EQ.0) GO TO 800 - WRITE (IOUT,1470) - DO 790 I=1,NCON,6 - M1=MIN0(NCON,I+5) -790 WRITE (IOUT,1010) I,(G(J),J=I,M1) -800 CONTINUE -C -C THE FOLLOWING CODE WAS ADDED ON 3/5/81 -C -C IT HAD NOT BEEN REPORTED AS A FIX TO MAOB -C BUT WAS SENT TO JEFF STROUD A YEAR AGO -C SEE OTHER COMMENTS IN CONMIN SUBROUTINE FOR DELETIONS OF CODE -C ON 3/5/81 PERTAINING TO THIS FIX -C -C -C CHECK FEASIBILITY -C - IF(NCON.LE.0) GO TO 808 - NFEASCT=10 - DO 804 I=1,NCON - C1=CTAM - IF(ISC(I).GT.0) C1=CTBM - IF(G(I).LE.C1) GO TO 804 - NFEAS=NFEAS+1 - GO TO 806 - 804 CONTINUE - IF(NFEAS.GT.0) ABOBJ1=.05 - NFEAS=0 - PHI=5. - 806 IF(NFEAS.GE.NFEASCT) GO TO 810 - 808 CONTINUE -C -C END OF INSERTED FIX -C -C ------------------------------------------------------------------ -C CHECK CONVERGENCE -C ------------------------------------------------------------------ -C STOP IF ITER EQUALS ITMAX. - IF (ITER.GE.ITMAX) GO TO 810 -C ------------------------------------------------------------------ -C ABSOLUTE CHANGE IN OBJECTIVE -C ------------------------------------------------------------------ - OBJB=ABS(OBJD) - KOBJ=KOBJ+1 - IF (OBJB.GE.DABFUN.OR.NFEAS.GT.0) KOBJ=0 -C ------------------------------------------------------------------ -C RELATIVE CHANGE IN OBJECTIVE -C ------------------------------------------------------------------ - IF (ABS(OBJ1).GT.1.0E-10) OBJD=OBJD/ABS(OBJ1) - ABOBJ1=.5*(ABS(ABOBJ)+ABS(OBJD)) - ABOBJ=ABS(OBJD) - IOBJ=IOBJ+1 - IF (NVC.GT.0.OR.OBJD.GE.DELFUN) IOBJ=0 - IF (IOBJ.GE.ITRM.OR.KOBJ.GE.ITRM) GO TO 810 - OBJ1=OBJ -C ------------------------------------------------------------------ -C REDUCE CT IF OBJECTIVE FUNCTION IS CHANGING SLOWLY -C ------------------------------------------------------------------ - IF (IOBJ.LT.1.OR.NAC.EQ.0) GO TO 280 - CT=DCT*CT - CTL=CTL*DCTL - IF (ABS(CT).LT.CTMIN) CT=-CTMIN - IF (ABS(CTL).LT.CTLMIN) CTL=-CTLMIN - GO TO 280 -810 CONTINUE - IF (NAC.GE.N3) WRITE (IOUT,1490) -C ------------------------------------------------------------------ -C **************** FINAL FUNCTION INFORMATION ******************** -C ------------------------------------------------------------------ - IF (NSCAL.EQ.0) GO TO 830 -C UN-SCALE THE DESIGN VARIABLES. - DO 820 I=1,NDV - XI=SCAL(I) - IF (NSIDE.EQ.0) GO TO 820 - VLB(I)=XI*VLB(I) - VUB(I)=XI*VUB(I) -820 X(I)=XI*X(I) -C ------------------------------------------------------------------ -C PRINT FINAL RESULTS -C ------------------------------------------------------------------ -830 IF (IPRINT.EQ.0.OR.NAC.GE.N3) GO TO 940 - WRITE (IOUT,1500) - WRITE (IOUT,1420) OBJ - WRITE (IOUT,1450) - DO 840 I=1,NDV,6 - M1=MIN0(NDV,I+5) -840 WRITE (IOUT,1010) I,(X(J),J=I,M1) - IF (NCON.EQ.0) GO TO 900 - WRITE (IOUT,1470) - DO 850 I=1,NCON,6 - M1=MIN0(NCON,I+5) -850 WRITE (IOUT,1010) I,(G(J),J=I,M1) -C DETERMINE WHICH CONSTRAINTS ARE ACTIVE AND PRINT. - NAC=0 - NVC=0 - DO 870 I=1,NCON - CTA=CTAM - IF (ISC(I).GT.0) CTA=CTBM - GI=G(I) - IF (GI.GT.CTA) GO TO 860 - IF (GI.LT.CT.AND.ISC(I).EQ.0) GO TO 870 - IF (GI.LT.CTL.AND.ISC(I).GT.0) GO TO 870 - NAC=NAC+1 - IC(NAC)=I - GO TO 870 -860 NVC=NVC+1 - MS1(NVC)=I -870 CONTINUE - WRITE (IOUT,1060) NAC - IF (NAC.EQ.0) GO TO 880 - WRITE (IOUT,1070) - WRITE (IOUT,1480) (IC(J),J=1,NAC) -880 WRITE (IOUT,1080) NVC - IF (NVC.EQ.0) GO TO 890 - WRITE (IOUT,1070) - WRITE (IOUT,1480) (MS1(J),J=1,NVC) -890 CONTINUE -900 CONTINUE - IF (NSIDE.EQ.0) GO TO 930 -C DETERMINE WHICH SIDE CONSTRAINTS ARE ACTIVE AND PRINT. - NAC=0 - DO 920 I=1,NDV - XI=X(I) - XID=VLB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XID-XI)/X12 - IF (GI.LT.-1.0E-6) GO TO 910 - NAC=NAC+1 - MS1(NAC)=-I -910 XID=VUB(I) - X12=ABS(XID) - IF (X12.LT.1.) X12=1. - GI=(XI-XID)/X12 - IF (GI.LT.-1.0E-6) GO TO 920 - NAC=NAC+1 - MS1(NAC)=I -920 CONTINUE - WRITE (IOUT,1090) NAC - IF (NAC.EQ.0) GO TO 930 - WRITE (IOUT,1100) - WRITE (IOUT,1480) (MS1(J),J=1,NAC) -930 CONTINUE - WRITE (IOUT,1150) - IF (ITER.GE.ITMAX) WRITE (IOUT,1160) - IF (NFEAS.GE.NFEASCT) WRITE (IOUT,1170) - IF (IOBJ.GE.ITRM) WRITE (IOUT,1180) ITRM - IF (KOBJ.GE.ITRM) WRITE (IOUT,1190) ITRM - WRITE (IOUT,1200) ITER - WRITE (IOUT,1510) NCAL(1) - IF (NCON.GT.0) WRITE (IOUT,1520) NCAL(1) - IF (NFDG.NE.0) WRITE (IOUT,1530) NCAL(2) - IF (NCON.GT.0.AND.NFDG.EQ.1) WRITE (IOUT,1540) NCAL(2) -C ------------------------------------------------------------------ -C RE-SET BASIC PARAMETERS TO INPUT VALUES -C ------------------------------------------------------------------ -940 ITRM=IDM1 - ITMAX=IDM2 - ICNDIR=IDM3 - DELFUN=DM1 - DABFUN=DM2 - CT=DM3 - CTMIN=DM4 - CTL=DM5 - CTLMIN=DM6 - THETA=DM7 - PHI=DM8 - FDCH=DM9 - FDCHM=DM10 - ABOBJ1=DM11 - ALPHAX=DM12 - IGOTO=0 -950 CONTINUE - IF (NSCAL.EQ.0.OR.IGOTO.EQ.0) RETURN -C UN-SCALE VARIABLES. - DO 960 I=1,NDV - C(I)=X(I) -960 X(I)=X(I)*SCAL(I) - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -970 FORMAT (///5X,72HA COMPLETELY UNCONSTRAINED FUNCTION WITH A LINEAR - 1 OBJECTIVE IS SPECIFIED//10X,8HLINOBJ =,I5/10X,8HNCON =,I5/10X,8 - 2HNSIDE =,I5//5X,35HCONTROL RETURNED TO CALLING PROGRAM) -980 FORMAT (///5X,56HCONMIN HAS ACHIEVED A SOLUTION OF OBJ LESS THAN - - 11.0E+40/5X,32HSOLUTION APPEARS TO BE UNBOUNDED/5X,26HOPTIMIZATION - 2IS TERMINATED) -990 FORMAT (5X,17HCONSTRAINT NUMBER,I5) -1000 FORMAT (5X,27HSIDE CONSTRAINT ON VARIABLE,I5) -1010 FORMAT (3X,I5,1H),2X,6E13.5) -1020 FORMAT (/5X,35HLINEAR CONSTRAINT IDENTIFIERS (ISC)/5X,36HNON-ZERO - 1INDICATES LINEAR CONSTRAINT) -1030 FORMAT (3X,I5,1H),2X,15I5) -1040 FORMAT (/5X,26HALL CONSTRAINTS ARE LINEAR) -1050 FORMAT (/5X,30HALL CONSTRAINTS ARE NON-LINEAR) -1060 FORMAT (/5X,9HTHERE ARE,I5,19H ACTIVE CONSTRAINTS) -1070 FORMAT (5X,22HCONSTRAINT NUMBERS ARE) -1080 FORMAT (/5X,9HTHERE ARE,I5,21H VIOLATED CONSTRAINTS) -1090 FORMAT (/5X,9HTHERE ARE,I5,24H ACTIVE SIDE CONSTRAINTS) -1100 FORMAT (5X,43HDECISION VARIABLES AT LOWER OR UPPER BOUNDS,30H (MIN - 1US INDICATES LOWER BOUND)) -1110 FORMAT (/5X,22HONE-DIMENSIONAL SEARCH/5X,15HINITIAL SLOPE =,E12.4, - 12X,16HPROPOSED ALPHA =,E12.4) -1120 FORMAT (///5X,35H* * CONMIN DETECTS VLB(I).GT.VUB(I)/5X,57HFIX IS - 1SET X(I)=VLB(I)=VUB(I) = .5*(VLB(I)+VUB(I) FOR I =,I5) -1130 FORMAT (///5X,41H* * CONMIN DETECTS INITIAL X(I).LT.VLB(I)/5X,6HX( - 1I) =,E12.4,2X,8HVLB(I) =,E12.4/5X,35HX(I) IS SET EQUAL TO VLB(I) F - 2OR I =,I5) -1140 FORMAT (///5X,41H* * CONMIN DETECTS INITIAL X(I).GT.VUB(I)/5X,6HX( - 1I) =,E12.4,2X,8HVUB(I) =,E12.4/5X,35HX(I) IS SET EQUAL TO VUB(I) F - 2OR I =,I5) -1150 FORMAT (/5X,21HTERMINATION CRITERION) -1160 FORMAT (10X,17HITER EQUALS ITMAX) -1170 FORMAT (10X,'NFEASCT CONSECUTIVE ITERATIONS FAILED TO PRODUCE A - 1FEASIBLE DESIGN') -1180 FORMAT (10X,43HABS(1-OBJ(I-1)/OBJ(I)) LESS THAN DELFUN FOR,I3,11H - 1ITERATIONS) -1190 FORMAT (10X,43HABS(OBJ(I)-OBJ(I-1)) LESS THAN DABFUN FOR,I3,11H - 1ITERATIONS) -1200 FORMAT (/5X,22HNUMBER OF ITERATIONS =,I5) -1210 FORMAT (/5X,28HCONSTRAINT PARAMETER, BETA =,E14.5) -1220 FORMAT (1H1,////12X,27(2H* )/12X,1H*,51X,1H*/12X,1H*,20X,11HC O N - 1M I N,20X,1H*/12X,1H*,51X,1H*/12X,1H*,15X,21H FORTRAN PROGRAM FOR - 2,15X,1H*/12X,1H*,51X,1H*/12X,1H*,9X,33HCONSTRAINED FUNCTION MINIMI - 3ZATION,9X,1H*/12X,1H*,51X,1H*/12X,27(2H* )) -1230 FORMAT (////5X,33HCONSTRAINED FUNCTION MINIMIZATION//5X,18HCONTROL - 1 PARAMETERS) -1240 FORMAT (/5X,60HIPRINT NDV ITMAX NCON NSIDE ICNDIR NSC - 1AL NFDG/8I8//5X,12HLINOBJ ITRM,5X,2HN1,6X,2HN2,6X,2HN3,6X,2HN4, - 26X,2HN5/8I8) -1250 FORMAT (/9X,4HFDCH,12X,5HFDCHM,11X,6HALPHAX,10X,6HABOBJ1/1X,4(2X,E - 114.5)) -1260 FORMAT (/9X,2HCT,14X,5HCTMIN,11X,3HCTL,13X,6HCTLMIN/1X,4(2X,E14.5) - 1//9X,5HTHETA,11X,3HPHI,13X,6HDELFUN,10X,6HDABFUN/1X,4(2X,E14.5)) -1270 FORMAT (/5X,40HLOWER BOUNDS ON DECISION VARIABLES (VLB)) -1280 FORMAT (/5X,40HUPPER BOUNDS ON DECISION VARIABLES (VUB)) -1290 FORMAT (////5X,35HUNCONSTRAINED FUNCTION MINIMIZATION//5X,18HCONTR - 1OL PARAMETERS) -1300 FORMAT (/5X,21HSCALING VECTOR (SCAL)) -1310 FORMAT (////5X,22HBEGIN ITERATION NUMBER,I5) -1320 FORMAT (/5X,4HCT =,E14.5,5X,5HCTL =,E14.5,5X,5HPHI =,E14.5) -1330 FORMAT (/5X,25HNEW SCALING VECTOR (SCAL)) -1340 FORMAT (/5X,15HGRADIENT OF OBJ) -1350 FORMAT (/5X,44HGRADIENTS OF ACTIVE AND VIOLATED CONSTRAINTS) -1360 FORMAT (1H ) -1370 FORMAT (/5X,37HPUSH-OFF FACTORS, (THETA(I), I=1,NAC)) -1380 FORMAT (/5X,27HSEARCH DIRECTION (S-VECTOR)) -1390 FORMAT (/5X,18HCALCULATED ALPHA =,E14.5) -1400 FORMAT (////5X,6HITER =,I5,5X,5HOBJ =,E14.5,5X,16HNO CHANGE IN OBJ - 1) -1410 FORMAT (/5X,5HOBJ =,E15.6,5X,16HNO CHANGE ON OBJ) -1420 FORMAT (/5X,5HOBJ =,E15.6) -1430 FORMAT (////5X,6HITER =,I5,5X,5HOBJ =,E14.5) -1440 FORMAT (//5X,28HINITIAL FUNCTION INFORMATION//5X,5HOBJ =,E15.6) -1450 FORMAT (/5X,29HDECISION VARIABLES (X-VECTOR)) -1460 FORMAT (3X,7E13.4) -1470 FORMAT (/5X,28HCONSTRAINT VALUES (G-VECTOR)) -1480 FORMAT (5X,15I5) -1490 FORMAT (/5X,59HTHE NUMBER OF ACTIVE AND VIOLATED CONSTRAINTS EXCEE - 1DS N3-1./5X,66HDIMENSIONED SIZE OF MATRICES A AND B AND VECTOR IC - 2IS INSUFFICIENT/5X,61HOPTIMIZATION TERMINATED AND CONTROL RETURNED - 3 TO MAIN PROGRAM.) -1500 FORMAT (1H1,////4X,30HFINAL OPTIMIZATION INFORMATION) -1510 FORMAT (/5X,32HOBJECTIVE FUNCTION WAS EVALUATED,8X,I5,2X,5HTIMES) -1520 FORMAT (/5X,35HCONSTRAINT FUNCTIONS WERE EVALUATED,I10,2X,5HTIMES) -1530 FORMAT (/5X,36HGRADIENT OF OBJECTIVE WAS CALCULATED,I9,2X,5HTIMES) -1540 FORMAT (/5X,40HGRADIENTS OF CONSTRAINTS WERE CALCULATED,I5,2X,5HTI - 1MES) - END diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn01.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn01.f deleted file mode 100644 index 694c7359c..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn01.f +++ /dev/null @@ -1,95 +0,0 @@ - SUBROUTINE CNMN01 (JGOTO,X,DF,G,ISC,IC,A,G1,VLB,VUB,SCAL,C,NCAL,DX - 1,DX1,FI,XI,III,N1,N2,N3,N4) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - DIMENSION X(N1), DF(N1), G(N2), ISC(N2), IC(N3), A(N1,N3), G1(N2), - 1 VLB(N1), VUB(N1), SCAL(N1), NCAL(2), C(N4) -C ROUTINE TO CALCULATE GRADIENT INFORMATION BY FINITE DIFFERENCE. -C BY G. N. VANDERPLAATS JUNE, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. - IF (JGOTO.EQ.1) GO TO 10 - IF (JGOTO.EQ.2) GO TO 70 - INFOG=0 - INF=INFO - NAC=0 - IF (LINOBJ.NE.0.AND.ITER.GT.1) GO TO 10 -C ------------------------------------------------------------------ -C GRADIENT OF LINEAR OBJECTIVE -C ------------------------------------------------------------------ - IF (NFDG.EQ.2) JGOTO=1 - IF (NFDG.EQ.2) RETURN -10 CONTINUE - JGOTO=0 - IF (NFDG.EQ.2.AND.NCON.EQ.0) RETURN - IF (NCON.EQ.0) GO TO 40 -C ------------------------------------------------------------------ -C * * * DETERMINE WHICH CONSTRAINTS ARE ACTIVE OR VIOLATED * * * -C ------------------------------------------------------------------ - DO 20 I=1,NCON - IF (G(I).LT.CT) GO TO 20 - IF (ISC(I).GT.0.AND.G(I).LT.CTL) GO TO 20 - NAC=NAC+1 - IF (NAC.GE.N3) RETURN - IC(NAC)=I -20 CONTINUE - IF (NFDG.EQ.2.AND.NAC.EQ.0) RETURN - IF ((LINOBJ.GT.0.AND.ITER.GT.1).AND.NAC.EQ.0) RETURN -C ------------------------------------------------------------------ -C STORE VALUES OF CONSTRAINTS IN G1 -C ------------------------------------------------------------------ - DO 30 I=1,NCON -30 G1(I)=G(I) -40 CONTINUE - JGOTO=0 - IF (NAC.EQ.0.AND.NFDG.EQ.2) RETURN -C ------------------------------------------------------------------ -C CALCULATE GRADIENTS -C ------------------------------------------------------------------ - INFOG=1 - INFO=1 - FI=OBJ - III=0 -50 III=III+1 - XI=X(III) - DX=FDCH*XI - DX=ABS(DX) - FDCH1=FDCHM - IF (NSCAL.NE.0) FDCH1=FDCHM/SCAL(III) - IF (DX.LT.FDCH1) DX=FDCH1 - X1=XI+DX - IF (NSIDE.EQ.0) GO TO 60 - IF (X1.GT.VUB(III)) DX=-DX -60 DX1=1./DX - X(III)=XI+DX - NCAL(1)=NCAL(1)+1 -C ------------------------------------------------------------------ -C FUNCTION EVALUATION -C ------------------------------------------------------------------ - JGOTO=2 - RETURN -70 CONTINUE - X(III)=XI - IF (NFDG.EQ.0) DF(III)=DX1*(OBJ-FI) - IF (NAC.EQ.0) GO TO 90 -C ------------------------------------------------------------------ -C DETERMINE GRADIENT COMPONENTS OF ACTIVE CONSTRAINTS -C ------------------------------------------------------------------ - DO 80 J=1,NAC - I1=IC(J) -80 A(III,J)=DX1*(G(I1)-G1(I1)) -90 CONTINUE - IF (III.LT.NDV) GO TO 50 - INFOG=0 - INFO=INF - JGOTO=0 - OBJ=FI - IF (NCON.EQ.0) RETURN -C ------------------------------------------------------------------ -C STORE CURRENT CONSTRAINT VALUES BACK IN G-VECTOR -C ------------------------------------------------------------------ - DO 100 I=1,NCON -100 G(I)=G1(I) - RETURN - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn02.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn02.f deleted file mode 100644 index 8dd1fab41..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn02.f +++ /dev/null @@ -1,62 +0,0 @@ - SUBROUTINE CNMN02 (NCALC,SLOPE,DFTDF1,DF,S,N1) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - DIMENSION DF(N1), S(N1) -C ROUTINE TO DETERMINE CONJUGATE DIRECTION VECTOR OR DIRECTION -C OF STEEPEST DESCENT FOR UNCONSTRAINED FUNCTION MINIMIZATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C NCALC = CALCULATION CONTROL. -C NCALC = 0, S = STEEPEST DESCENT. -C NCALC = 1, S = CONJUGATE DIRECTION. -C CONJUGATE DIRECTION IS FOUND BY FLETCHER-REEVES ALGORITHM. -C ------------------------------------------------------------------ -C CALCULATE NORM OF GRADIENT VECTOR -C ------------------------------------------------------------------ - DFTDF=0. - DO 10 I=1,NDV - DFI=DF(I) -10 DFTDF=DFTDF+DFI*DFI -C ------------------------------------------------------------------ -C ********** FIND DIRECTION S ********** -C ------------------------------------------------------------------ - IF (NCALC.NE.1) GO TO 30 - IF (DFTDF1.LT.1.0E-20) GO TO 30 -C ------------------------------------------------------------------ -C FIND FLETCHER-REEVES CONJUGATE DIRECTION -C ------------------------------------------------------------------ - BETA=DFTDF/DFTDF1 - SLOPE=0. - DO 20 I=1,NDV - DFI=DF(I) - SI=BETA*S(I)-DFI - SLOPE=SLOPE+SI*DFI -20 S(I)=SI - GO TO 50 -30 CONTINUE - NCALC=0 -C ------------------------------------------------------------------ -C CALCULATE DIRECTION OF STEEPEST DESCENT -C ------------------------------------------------------------------ - DO 40 I=1,NDV -40 S(I)=-DF(I) - SLOPE=-DFTDF -50 CONTINUE -C ------------------------------------------------------------------ -C NORMALIZE S TO MAX ABS VALUE OF UNITY -C ------------------------------------------------------------------ - S1=0. - DO 60 I=1,NDV - S2=ABS(S(I)) - IF (S2.GT.S1) S1=S2 -60 CONTINUE - IF (S1.LT.1.0E-20) S1=1.0E-20 - S1=1./S1 - DFTDF1=DFTDF*S1 - DO 70 I=1,NDV -70 S(I)=S1*S(I) - SLOPE=S1*SLOPE - RETURN - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn03.bak b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn03.bak deleted file mode 100644 index 57dbef285..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn03.bak +++ /dev/null @@ -1,274 +0,0 @@ - SUBROUTINE CNMN03 (X,S,SLOPE,ALP,FFF,A1,A2,A3,A4,F1,F2,F3,F4,APP,N - 11,NCAL,KOUNT,JGOTO) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - DIMENSION X(N1), S(N1), NCAL(2) -C ROUTINE TO SOLVE ONE-DIMENSIONAL SEARCH IN UNCONSTRAINED -C MINIMIZATION USING 2-POINT QUADRATIC INTERPOLATION, 3-POINT -C CUBIC INTERPOLATION AND 4-POINT CUBIC INTERPOLATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C ALP = PROPOSED MOVE PARAMETER. -C SLOPE = INITIAL FUNCTION SLOPE = S-TRANSPOSE TIMES DF. -C SLOPE MUST BE NEGATIVE. -C OBJ = INITIAL FUNCTION VALUE. - ZRO=0. - IF (JGOTO.EQ.0) GO TO 10 - GO TO (50,80,110,140,180,220,270),JGOTO -C ------------------------------------------------------------------ -C INITIAL INFORMATION (ALPHA=0) -C ------------------------------------------------------------------ -10 IF (SLOPE.LT.0.) GO TO 20 - ALP=0. - RETURN -20 CONTINUE - IF (IPRINT.GT.4) WRITE (6,360) - FFF=OBJ - AP1=0. - A1=0. - F1=OBJ - A2=ALP - A3=0. - F3=0. - AP=A2 - KOUNT=0 -C ------------------------------------------------------------------ -C MOVE A DISTANCE AP*S AND UPDATE FUNCTION VALUE -C ------------------------------------------------------------------ -30 CONTINUE - KOUNT=KOUNT+1 - DO 40 I=1,NDV -40 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) AP - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=1 - RETURN -50 CONTINUE - F2=OBJ - IF (IPRINT.GT.4) WRITE (6,390) F2 - IF (F2.LT.F1) GO TO 120 -C ------------------------------------------------------------------ -C CHECK FOR ILL-CONDITIONING -C ------------------------------------------------------------------ - IF (KOUNT.GT.5) GO TO 60 - FF=2.*ABS(F1) - IF (F2.LT.FF) GO TO 90 - FF=5.*ABS(F1) - IF (F2.LT.FF) GO TO 60 - A2=.5*A2 - AP=-A2 - ALP=A2 - GO TO 30 -60 F3=F2 - A3=A2 - A2=.5*A2 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=A2-ALP - ALP=A2 - DO 70 I=1,NDV -70 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) A2 - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=2 - RETURN -80 CONTINUE - F2=OBJ - IF (IPRINT.GT.4) WRITE (6,390) F2 -C PROCEED TO CUBIC INTERPOLATION. - GO TO 160 -90 CONTINUE -C ------------------------------------------------------------------ -C ********** 2-POINT QUADRATIC INTERPOLATION ********** -C ------------------------------------------------------------------ - JJ=1 - II=1 - CALL CNMN04 (II,APP,ZRO,A1,F1,SLOPE,A2,F2,ZRO,ZRO,ZRO,ZRO) - IF (APP.LT.ZRO.OR.APP.GT.A2) GO TO 120 - F3=F2 - A3=A2 - A2=APP - JJ=0 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=A2-ALP - ALP=A2 - DO 100 I=1,NDV -100 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) A2 - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=3 - RETURN -110 CONTINUE - F2=OBJ - IF (IPRINT.GT.4) WRITE (6,390) F2 - GO TO 150 -120 A3=2.*A2 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=A3-ALP - ALP=A3 - DO 130 I=1,NDV -130 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) A3 - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=4 - RETURN -140 CONTINUE - F3=OBJ - IF (IPRINT.GT.4) WRITE (6,390) F3 -150 CONTINUE - IF (F3.LT.F2) GO TO 190 -160 CONTINUE -C ------------------------------------------------------------------ -C ********** 3-POINT CUBIC INTERPOLATION ********** -C ------------------------------------------------------------------ - II=3 - CALL CNMN04 (II,APP,ZRO,A1,F1,SLOPE,A2,F2,A3,F3,ZRO,ZRO) - IF (APP.LT.ZRO.OR.APP.GT.A3) GO TO 190 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE. -C ------------------------------------------------------------------ - AP1=APP - AP=APP-ALP - ALP=APP - DO 170 I=1,NDV -170 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) ALP - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=5 - RETURN -180 CONTINUE - IF (IPRINT.GT.4) WRITE (6,390) OBJ -C ------------------------------------------------------------------ -C CHECK CONVERGENCE -C ------------------------------------------------------------------ - AA=1.-APP/A2 - AB2=ABS(F2) - AB3=ABS(OBJ) - AB=AB2 - IF (AB3.GT.AB) AB=AB3 - IF (AB.LT.1.0E-15) AB=1.0E-15 - AB=(AB2-AB3)/AB - IF (ABS(AB).LT.1.0E-15.AND.ABS(AA).LT..001) GO TO 330 - A4=A3 - F4=F3 - A3=APP - F3=OBJ - IF (A3.GT.A2) GO TO 230 - A3=A2 - F3=F2 - A2=APP - F2=OBJ - GO TO 230 -190 CONTINUE -C ------------------------------------------------------------------ -C ********** 4-POINT CUBIC INTERPOLATION ********** -C ------------------------------------------------------------------ -200 CONTINUE - A4=2.*A3 -C UPDATE DESIGN VECTOR AND FUNCTION VALUE. - AP=A4-ALP - ALP=A4 - DO 210 I=1,NDV -210 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) ALP - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=6 - RETURN -220 CONTINUE - F4=OBJ - IF (IPRINT.GT.4) WRITE (6,390) F4 - IF (F4.GT.F3) GO TO 230 - A1=A2 - F1=F2 - A2=A3 - F2=F3 - A3=A4 - F3=F4 - GO TO 200 -230 CONTINUE - II=4 - CALL CNMN04 (II,APP,A1,A1,F1,SLOPE,A2,F2,A3,F3,A4,F4) - IF (APP.GT.A1) GO TO 250 - AP=A1-ALP - ALP=A1 - OBJ=F1 - DO 240 I=1,NDV -240 X(I)=X(I)+AP*S(I) - GO TO 280 -250 CONTINUE -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=APP-ALP - ALP=APP - DO 260 I=1,NDV -260 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (6,370) ALP - IF (IPRINT.GT.4) WRITE (6,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=7 - RETURN -270 CONTINUE - IF (IPRINT.GT.4) WRITE (6,390) OBJ -280 CONTINUE -C ------------------------------------------------------------------ -C CHECK FOR ILL-CONDITIONING -C ------------------------------------------------------------------ - IF (OBJ.GT.F2.OR.OBJ.GT.F3) GO TO 290 - IF (OBJ.LE.F1) GO TO 330 - AP=A1-ALP - ALP=A1 - OBJ=F1 - GO TO 310 -290 CONTINUE - IF (F2.LT.F3) GO TO 300 - OBJ=F3 - AP=A3-ALP - ALP=A3 - GO TO 310 -300 OBJ=F2 - AP=A2-ALP - ALP=A2 -310 CONTINUE -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR -C ------------------------------------------------------------------ - DO 320 I=1,NDV -320 X(I)=X(I)+AP*S(I) -330 CONTINUE -C ------------------------------------------------------------------ -C CHECK FOR MULTIPLE MINIMA -C ------------------------------------------------------------------ - IF (OBJ.LE.FFF) GO TO 350 -C INITIAL FUNCTION IS MINIMUM. - DO 340 I=1,NDV -340 X(I)=X(I)-ALP*S(I) - ALP=0. - OBJ=FFF -350 CONTINUE - JGOTO=0 - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -360 FORMAT (/////5X,60H* * * UNCONSTRAINED ONE-DIMENSIONAL SEARCH INFO - 1RMATION * * *) -370 FORMAT (/5X,7HALPHA =,E14.5/5X,8HX-VECTOR) -380 FORMAT (5X,6E13.5) -390 FORMAT (/5X,5HOBJ =,E14.5) - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn03.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn03.f deleted file mode 100644 index 9693a5867..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn03.f +++ /dev/null @@ -1,275 +0,0 @@ - SUBROUTINE CNMN03 (X,S,SLOPE,ALP,FFF,A1,A2,A3,A4,F1,F2,F3,F4,APP,N - 11,NCAL,KOUNT,JGOTO) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - COMMON /OUTPUT/ IOUT - DIMENSION X(N1), S(N1), NCAL(2) -C ROUTINE TO SOLVE ONE-DIMENSIONAL SEARCH IN UNCONSTRAINED -C MINIMIZATION USING 2-POINT QUADRATIC INTERPOLATION, 3-POINT -C CUBIC INTERPOLATION AND 4-POINT CUBIC INTERPOLATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C ALP = PROPOSED MOVE PARAMETER. -C SLOPE = INITIAL FUNCTION SLOPE = S-TRANSPOSE TIMES DF. -C SLOPE MUST BE NEGATIVE. -C OBJ = INITIAL FUNCTION VALUE. - ZRO=0. - IF (JGOTO.EQ.0) GO TO 10 - GO TO (50,80,110,140,180,220,270),JGOTO -C ------------------------------------------------------------------ -C INITIAL INFORMATION (ALPHA=0) -C ------------------------------------------------------------------ -10 IF (SLOPE.LT.0.) GO TO 20 - ALP=0. - RETURN -20 CONTINUE - IF (IPRINT.GT.4) WRITE (IOUT,360) - FFF=OBJ - AP1=0. - A1=0. - F1=OBJ - A2=ALP - A3=0. - F3=0. - AP=A2 - KOUNT=0 -C ------------------------------------------------------------------ -C MOVE A DISTANCE AP*S AND UPDATE FUNCTION VALUE -C ------------------------------------------------------------------ -30 CONTINUE - KOUNT=KOUNT+1 - DO 40 I=1,NDV -40 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) AP - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=1 - RETURN -50 CONTINUE - F2=OBJ - IF (IPRINT.GT.4) WRITE (IOUT,390) F2 - IF (F2.LT.F1) GO TO 120 -C ------------------------------------------------------------------ -C CHECK FOR ILL-CONDITIONING -C ------------------------------------------------------------------ - IF (KOUNT.GT.5) GO TO 60 - FF=2.*ABS(F1) - IF (F2.LT.FF) GO TO 90 - FF=5.*ABS(F1) - IF (F2.LT.FF) GO TO 60 - A2=.5*A2 - AP=-A2 - ALP=A2 - GO TO 30 -60 F3=F2 - A3=A2 - A2=.5*A2 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=A2-ALP - ALP=A2 - DO 70 I=1,NDV -70 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) A2 - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=2 - RETURN -80 CONTINUE - F2=OBJ - IF (IPRINT.GT.4) WRITE (IOUT,390) F2 -C PROCEED TO CUBIC INTERPOLATION. - GO TO 160 -90 CONTINUE -C ------------------------------------------------------------------ -C ********** 2-POINT QUADRATIC INTERPOLATION ********** -C ------------------------------------------------------------------ - JJ=1 - II=1 - CALL CNMN04 (II,APP,ZRO,A1,F1,SLOPE,A2,F2,ZRO,ZRO,ZRO,ZRO) - IF (APP.LT.ZRO.OR.APP.GT.A2) GO TO 120 - F3=F2 - A3=A2 - A2=APP - JJ=0 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=A2-ALP - ALP=A2 - DO 100 I=1,NDV -100 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) A2 - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=3 - RETURN -110 CONTINUE - F2=OBJ - IF (IPRINT.GT.4) WRITE (IOUT,390) F2 - GO TO 150 -120 A3=2.*A2 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=A3-ALP - ALP=A3 - DO 130 I=1,NDV -130 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) A3 - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=4 - RETURN -140 CONTINUE - F3=OBJ - IF (IPRINT.GT.4) WRITE (IOUT,390) F3 -150 CONTINUE - IF (F3.LT.F2) GO TO 190 -160 CONTINUE -C ------------------------------------------------------------------ -C ********** 3-POINT CUBIC INTERPOLATION ********** -C ------------------------------------------------------------------ - II=3 - CALL CNMN04 (II,APP,ZRO,A1,F1,SLOPE,A2,F2,A3,F3,ZRO,ZRO) - IF (APP.LT.ZRO.OR.APP.GT.A3) GO TO 190 -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE. -C ------------------------------------------------------------------ - AP1=APP - AP=APP-ALP - ALP=APP - DO 170 I=1,NDV -170 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) ALP - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=5 - RETURN -180 CONTINUE - IF (IPRINT.GT.4) WRITE (IOUT,390) OBJ -C ------------------------------------------------------------------ -C CHECK CONVERGENCE -C ------------------------------------------------------------------ - AA=1.-APP/A2 - AB2=ABS(F2) - AB3=ABS(OBJ) - AB=AB2 - IF (AB3.GT.AB) AB=AB3 - IF (AB.LT.1.0E-15) AB=1.0E-15 - AB=(AB2-AB3)/AB - IF (ABS(AB).LT.1.0E-15.AND.ABS(AA).LT..001) GO TO 330 - A4=A3 - F4=F3 - A3=APP - F3=OBJ - IF (A3.GT.A2) GO TO 230 - A3=A2 - F3=F2 - A2=APP - F2=OBJ - GO TO 230 -190 CONTINUE -C ------------------------------------------------------------------ -C ********** 4-POINT CUBIC INTERPOLATION ********** -C ------------------------------------------------------------------ -200 CONTINUE - A4=2.*A3 -C UPDATE DESIGN VECTOR AND FUNCTION VALUE. - AP=A4-ALP - ALP=A4 - DO 210 I=1,NDV -210 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) ALP - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=6 - RETURN -220 CONTINUE - F4=OBJ - IF (IPRINT.GT.4) WRITE (IOUT,390) F4 - IF (F4.GT.F3) GO TO 230 - A1=A2 - F1=F2 - A2=A3 - F2=F3 - A3=A4 - F3=F4 - GO TO 200 -230 CONTINUE - II=4 - CALL CNMN04 (II,APP,A1,A1,F1,SLOPE,A2,F2,A3,F3,A4,F4) - IF (APP.GT.A1) GO TO 250 - AP=A1-ALP - ALP=A1 - OBJ=F1 - DO 240 I=1,NDV -240 X(I)=X(I)+AP*S(I) - GO TO 280 -250 CONTINUE -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR AND FUNCTION VALUE -C ------------------------------------------------------------------ - AP=APP-ALP - ALP=APP - DO 260 I=1,NDV -260 X(I)=X(I)+AP*S(I) - IF (IPRINT.GT.4) WRITE (IOUT,370) ALP - IF (IPRINT.GT.4) WRITE (IOUT,380) (X(I),I=1,NDV) - NCAL(1)=NCAL(1)+1 - JGOTO=7 - RETURN -270 CONTINUE - IF (IPRINT.GT.4) WRITE (IOUT,390) OBJ -280 CONTINUE -C ------------------------------------------------------------------ -C CHECK FOR ILL-CONDITIONING -C ------------------------------------------------------------------ - IF (OBJ.GT.F2.OR.OBJ.GT.F3) GO TO 290 - IF (OBJ.LE.F1) GO TO 330 - AP=A1-ALP - ALP=A1 - OBJ=F1 - GO TO 310 -290 CONTINUE - IF (F2.LT.F3) GO TO 300 - OBJ=F3 - AP=A3-ALP - ALP=A3 - GO TO 310 -300 OBJ=F2 - AP=A2-ALP - ALP=A2 -310 CONTINUE -C ------------------------------------------------------------------ -C UPDATE DESIGN VECTOR -C ------------------------------------------------------------------ - DO 320 I=1,NDV -320 X(I)=X(I)+AP*S(I) -330 CONTINUE -C ------------------------------------------------------------------ -C CHECK FOR MULTIPLE MINIMA -C ------------------------------------------------------------------ - IF (OBJ.LE.FFF) GO TO 350 -C INITIAL FUNCTION IS MINIMUM. - DO 340 I=1,NDV -340 X(I)=X(I)-ALP*S(I) - ALP=0. - OBJ=FFF -350 CONTINUE - JGOTO=0 - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -360 FORMAT (/////5X,60H* * * UNCONSTRAINED ONE-DIMENSIONAL SEARCH INFO - 1RMATION * * *) -370 FORMAT (/5X,7HALPHA =,E14.5/5X,8HX-VECTOR) -380 FORMAT (5X,6E13.5) -390 FORMAT (/5X,5HOBJ =,E14.5) - END diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn04.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn04.f deleted file mode 100644 index 2635d11eb..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn04.f +++ /dev/null @@ -1,121 +0,0 @@ - SUBROUTINE CNMN04 (II,XBAR,EPS,X1,Y1,SLOPE,X2,Y2,X3,Y3,X4,Y4) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) -C ROUTINE TO FIND FIRST XBAR.GE.EPS CORRESPONDING TO A MINIMUM -C OF A ONE-DIMENSIONAL REAL FUNCTION BY POLYNOMIEL INTERPOLATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C -C II = CALCULATION CONTROL. -C 1: 2-POINT QUADRATIC INTERPOLATION, GIVEN X1, Y1, SLOPE, -C X2 AND Y2. -C 2: 3-POINT QUADRATIC INTERPOLATION, GIVEN X1, Y1, X2, Y2, -C X3 AND Y3. -C 3: 3-POINT CUBIC INTERPOLATION, GIVEN X1, Y1, SLOPE, X2, Y2, -C X3 AND Y3. -C 4: 4-POINT CUBIC INTERPOLATION, GIVEN X1, Y1, X2, Y2, X3, -C Y3, X4 AND Y4. -C EPS MAY BE NEGATIVE. -C IF REQUIRED MINIMUM ON Y DOES NOT EXITS, OR THE FUNCTION IS -C ILL-CONDITIONED, XBAR = EPS-1.0 WILL BE RETURNED AS AN ERROR -C INDICATOR. -C IF DESIRED INTERPOLATION IS ILL-CONDITIONED, A LOWER ORDER -C INTERPOLATION, CONSISTANT WITH INPUT DATA, WILL BE ATTEMPTED, -C AND II WILL BE CHANGED ACCORDINGLY. - XBAR1=EPS-1. - XBAR=XBAR1 - X21=X2-X1 - IF (ABS(X21).LT.1.0E-20) RETURN - NSLOP=MOD(II,2) - GO TO (10,20,40,50),II -10 CONTINUE -C ------------------------------------------------------------------ -C II=1: 2-POINT QUADRATIC INTERPOLATION -C ------------------------------------------------------------------ - II=1 - DX=X1-X2 - IF (ABS(DX).LT.1.0E-20) RETURN - AA=(SLOPE+(Y2-Y1)/DX)/DX - IF (AA.LT.1.0E-20) RETURN - BB=SLOPE-2.*AA*X1 - XBAR=-.5*BB/AA - IF (XBAR.LT.EPS) XBAR=XBAR1 - RETURN -20 CONTINUE -C ------------------------------------------------------------------ -C II=2: 3-POINT QUADRATIC INTERPOLATION -C ------------------------------------------------------------------ - II=2 - X21=X2-X1 - X31=X3-X1 - X32=X3-X2 - QQ=X21*X31*X32 - IF (ABS(QQ).LT.1.0E-20) RETURN - AA=(Y1*X32-Y2*X31+Y3*X21)/QQ - IF (AA.LT.1.0E-20) GO TO 30 - BB=(Y2-Y1)/X21-AA*(X1+X2) - XBAR=-.5*BB/AA - IF (XBAR.LT.EPS) XBAR=XBAR1 - RETURN -30 CONTINUE - IF (NSLOP.EQ.0) RETURN - GO TO 10 -40 CONTINUE -C ------------------------------------------------------------------ -C II=3: 3-POINT CUBIC INTERPOLATION -C ------------------------------------------------------------------ - II=3 - X21=X2-X1 - X31=X3-X1 - X32=X3-X2 - QQ=X21*X31*X32 - IF (ABS(QQ).LT.1.0E-20) RETURN - X11=X1*X1 - DNOM=X2*X2*X31-X11*X32-X3*X3*X21 - IF (ABS(DNOM).LT.1.0E-20) GO TO 20 - AA=((X31*X31*(Y2-Y1)-X21*X21*(Y3-Y1))/(X31*X21)-SLOPE*X32)/DNOM - IF (ABS(AA).LT.1.0E-20) GO TO 20 - BB=((Y2-Y1)/X21-SLOPE-AA*(X2*X2+X1*X2-2.*X11))/X21 - CC=SLOPE-3.*AA*X11-2.*BB*X1 - BAC=BB*BB-3.*AA*CC - IF (BAC.LT.0.) GO TO 20 - BAC=SQRT(BAC) - XBAR=(BAC-BB)/(3.*AA) - IF (XBAR.LT.EPS) XBAR=EPS - RETURN -50 CONTINUE -C ------------------------------------------------------------------ -C II=4: 4-POINT CUBIC INTERPOLATION -C ------------------------------------------------------------------ - X21=X2-X1 - X31=X3-X1 - X41=X4-X1 - X32=X3-X2 - X42=X4-X2 - X11=X1*X1 - X22=X2*X2 - X33=X3*X3 - X44=X4*X4 - X111=X1*X11 - X222=X2*X22 - Q2=X31*X21*X32 - IF (ABS(Q2).LT.1.0E-30) RETURN - Q1=X111*X32-X222*X31+X3*X33*X21 - Q4=X111*X42-X222*X41+X4*X44*X21 - Q5=X41*X21*X42 - DNOM=Q2*Q4-Q1*Q5 - IF (ABS(DNOM).LT.1.0E-30) GO TO 60 - Q3=Y3*X21-Y2*X31+Y1*X32 - Q6=Y4*X21-Y2*X41+Y1*X42 - AA=(Q2*Q6-Q3*Q5)/DNOM - BB=(Q3-Q1*AA)/Q2 - CC=(Y2-Y1-AA*(X222-X111))/X21-BB*(X1+X2) - BAC=BB*BB-3.*AA*CC - IF (ABS(AA).LT.1.0E-20.OR.BAC.LT.0.) GO TO 60 - BAC=SQRT(BAC) - XBAR=(BAC-BB)/(3.*AA) - IF (XBAR.LT.EPS) XBAR=XBAR1 - RETURN -60 CONTINUE - IF (NSLOP.EQ.1) GO TO 40 - GO TO 20 - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn05.bak b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn05.bak deleted file mode 100644 index a7b23c4b0..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn05.bak +++ /dev/null @@ -1,224 +0,0 @@ - SUBROUTINE CNMN05 (G,DF,A,S,B,C,SLOPE,PHI,ISC,IC,MS1,NVC,N1,N2,N3, - 1N4,N5) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - DIMENSION DF(N1), G(N2), ISC(N2), IC(N3), A(N1,N3), S(N1), C(N4), - 1MS1(N5), B(N3,N3) -C ROUTINE TO SOLVE DIRECTION FINDING PROBLEM IN MODIFIED METHOD OF -C FEASIBLE DIRECTIONS. -C BY G. N. VANDERPLAATS MAY, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C NORM OF S VECTOR USED HERE IS S-TRANSPOSE TIMES S.LE.1. -C IF NVC = 0 FIND DIRECTION BY ZOUTENDIJK'S METHOD. OTHERWISE -C FIND MODIFIED DIRECTION. -C ------------------------------------------------------------------ -C *** NORMALIZE GRADIENTS, CALCULATE THETA'S AND DETERMINE NVC *** -C ------------------------------------------------------------------ - NDV1=NDV+1 - NDV2=NDV+2 - NAC1=NAC+1 - NVC=0 - THMAX=0. - CTA=ABS(CT) - CT1=1./CTA - CTAM=ABS(CTMIN) - CTB=ABS(CTL) - CT2=1./CTB - CTBM=ABS(CTLMIN) - A1=1. - DO 40 I=1,NAC -C CALCULATE THETA - NCI=IC(I) - NCJ=1 - IF (NCI.LE.NCON) NCJ=ISC(NCI) - C1=G(NCI) - CTD=CT1 - CTC=CTAM - IF (NCJ.LE.0) GO TO 10 - CTC=CTBM - CTD=CT2 -10 IF (C1.GT.CTC) NVC=NVC+1 - THT=0. - GG=1.+CTD*C1 - IF (NCJ.EQ.0.OR.C1.GT.CTC) THT=THETA*GG*GG - IF (THT.GT.50.) THT=50. - IF (THT.GT.THMAX) THMAX=THT - A(NDV1,I)=THT -C ------------------------------------------------------------------ -C NORMALIZE GRADIENTS OF CONSTRAINTS -C ------------------------------------------------------------------ - A(NDV2,I)=1. - IF (NCI.GT.NCON) GO TO 40 - A1=0. - DO 20 J=1,NDV - A1=A1+A(J,I)**2 -20 CONTINUE - IF (A1.LT.1.0E-20) A1=1.0E-20 - A1=SQRT(A1) - A(NDV2,I)=A1 - A1=1./A1 - DO 30 J=1,NDV -30 A(J,I)=A1*A(J,I) -40 CONTINUE -C ------------------------------------------------------------------ -C CHECK FOR ZERO GRADIENT. PROGRAM CHANGE-FEB, 1981, GV. -C ------------------------------------------------------------------ - I=0 -41 I=I+1 -42 CONTINUE - IF(A(NDV2,I).GT.1.0E-6) GO TO 45 -C ZERO GRADIENT IS FOUND. WRITE ERROR MESSAGE. - IF(IPRINT.GE.2) WRITE(6,43)IC(I) -43 FORMAT(5X,13H** CONSTRAINT,I5,18H HAS ZERO GRADIENT/ - *5X,23HDELETED FROM ACTIVE SET) -C REDUCE NAC BY ONE. - NAC=NAC-1 -C SHIFT COLUMNS OF A AND ROWS OF IC IF I.LE.NAC. - IF(I.GT.NAC) GO TO 46 -C SHIFT. - DO 44 J=I,NAC - J1=J+1 - IC(J)=IC(J1) - DO 44 K=1,NDV2 -44 A(K,J)=A(K,J1) - IF(I.LE.NAC) GO TO 42 -45 CONTINUE - IF(I.LT.NAC) GO TO 41 -46 CONTINUE - IF(NAC.LE.0) RETURN - NAC1=NAC+1 -C DETERMINE IF CONSTRAINTS ARE VIOLATED. - NVC=0 - DO 47 I=1,NAC - NCI=IC(I) - NCJ=1 - IF(NCI.LE.NCON) NCJ=ISC(NCI) - CTC=CTAM - IF(NCJ.GT.0) CTC=CTBM - IF(G(NCI).GT.CTC) NVC=NVC+1 -47 CONTINUE -C ------------------------------------------------------------------ -C NORMALIZE GRADIENT OF OBJECTIVE FUNCTION AND STORE IN NAC+1 -C COLUMN OF A -C ------------------------------------------------------------------ - A1=0. - DO 50 I=1,NDV - A1=A1+DF(I)**2 -50 CONTINUE - IF (A1.LT.1.0E-20) A1=1.0E-20 - A1=SQRT(A1) - A1=1./A1 - DO 60 I=1,NDV -60 A(I,NAC1)=A1*DF(I) -C BUILD C VECTOR. - IF (NVC.GT.0) GO TO 80 -C ------------------------------------------------------------------ -C BUILD C FOR CLASSICAL METHOD -C ------------------------------------------------------------------ - NDB=NAC1 - A(NDV1,NDB)=1. - DO 70 I=1,NDB -70 C(I)=-A(NDV1,I) - GO TO 110 -80 CONTINUE -C ------------------------------------------------------------------ -C BUILD C FOR MODIFIED METHOD -C ------------------------------------------------------------------ - NDB=NAC - A(NDV1,NAC1)=-PHI -C ------------------------------------------------------------------ -C SCALE THETA'S SO THAT MAXIMUM THETA IS UNITY -C ------------------------------------------------------------------ - IF (THMAX.GT.0.00001) THMAX=1./THMAX - DO 90 I=1,NDB - A(NDV1,I)=A(NDV1,I)*THMAX -90 CONTINUE - DO 100 I=1,NDB - C(I)=0. - DO 100 J=1,NDV1 -100 C(I)=C(I)+A(J,I)*A(J,NAC1) -110 CONTINUE -C ------------------------------------------------------------------ -C BUILD B MATRIX -C ------------------------------------------------------------------ - DO 120 I=1,NDB - DO 120 J=1,NDB - B(I,J)=0. - DO 120 K=1,NDV1 -120 B(I,J)=B(I,J)-A(K,I)*A(K,J) -C ------------------------------------------------------------------ -C SOLVE SPECIAL L. P. PROBLEM -C ------------------------------------------------------------------ - CALL CNMN08 (NDB,NER,C,MS1,B,N3,N4,N5) - IF (IPRINT.GT.1.AND.NER.GT.0) WRITE (6,180) -C CALCULATE RESULTING DIRECTION VECTOR, S. - SLOPE=0. -C ------------------------------------------------------------------ -C USABLE-FEASIBLE DIRECTION -C ------------------------------------------------------------------ - DO 140 I=1,NDV - S1=0. - IF (NVC.GT.0) S1=-A(I,NAC1) - DO 130 J=1,NDB -130 S1=S1-A(I,J)*C(J) - SLOPE=SLOPE+S1*DF(I) -140 S(I)=S1 - S(NDV1)=1. - IF (NVC.GT.0) S(NDV1)=-A(NDV1,NAC1) - DO 150 J=1,NDB -150 S(NDV1)=S(NDV1)-A(NDV1,J)*C(J) -C ------------------------------------------------------------------ -C CHECK TO INSURE THE S-VECTOR IS FEASIBLE. -C PROGRAM MOD-FEB, 1981, GV. -C ------------------------------------------------------------------ - DO 174 J=1,NAC -C S DOT DEL(G). - SG=0. - DO 172 I=1,NDV -172 SG=SG+S(I)*A(I,J) -C IF(SG.GT.0.) GO TO 176 -C -C THIS CHANGE MADE ON 4/8/81 FOR G. VANDERPLAATS -C - IF(SG.GT.1.0E-04) GO TO 176 -C FEASIBLE FOR THIS CONSTRAINT. CONTINUE. -174 CONTINUE - GO TO 179 -176 CONTINUE -C S-VECTOR IS NOT FEASIBLE DUE TO SOME NUMERICAL PROBLEM. - IF(IPRINT.GE.2) WRITE(6,178) -178 FORMAT(5X,38H** CALCULATED S-VECTOR IS NOT FEASIBLE/5X, - * 19HBETA IS SET TO ZERO) - S(NDV1)=0. - NVC=0 - RETURN -179 CONTINUE -C ------------------------------------------------------------------ -C NORMALIZE S TO MAX ABS OF UNITY -C ------------------------------------------------------------------ - S1=0. - DO 160 I=1,NDV - A1=ABS(S(I)) - IF (A1.GT.S1) S1=A1 -160 CONTINUE -C IF (S1.LT.1.0E-10) RETURN -C -C E-10 CHANGED TO E-04 ON 1/12/81 -C - IF (S1.LT.1.0E-04) RETURN - S1=1./S1 - DO 170 I=1,NDV -170 S(I)=S1*S(I) - SLOPE=S1*SLOPE - S(NDV1)=S1*S(NDV1) - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -180 FORMAT (//5X,46H* * DIRECTION FINDING PROCESS DID NOT CONVERGE/5X, - 129H* * S-VECTOR MAY NOT BE VALID) - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn05.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn05.f deleted file mode 100644 index 6889d5e60..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn05.f +++ /dev/null @@ -1,225 +0,0 @@ - SUBROUTINE CNMN05 (G,DF,A,S,B,C,SLOPE,PHI,ISC,IC,MS1,NVC,N1,N2,N3, - 1N4,N5) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - COMMON /OUTPUT/ IOUT - DIMENSION DF(N1), G(N2), ISC(N2), IC(N3), A(N1,N3), S(N1), C(N4), - 1MS1(N5), B(N3,N3) -C ROUTINE TO SOLVE DIRECTION FINDING PROBLEM IN MODIFIED METHOD OF -C FEASIBLE DIRECTIONS. -C BY G. N. VANDERPLAATS MAY, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C NORM OF S VECTOR USED HERE IS S-TRANSPOSE TIMES S.LE.1. -C IF NVC = 0 FIND DIRECTION BY ZOUTENDIJK'S METHOD. OTHERWISE -C FIND MODIFIED DIRECTION. -C ------------------------------------------------------------------ -C *** NORMALIZE GRADIENTS, CALCULATE THETA'S AND DETERMINE NVC *** -C ------------------------------------------------------------------ - NDV1=NDV+1 - NDV2=NDV+2 - NAC1=NAC+1 - NVC=0 - THMAX=0. - CTA=ABS(CT) - CT1=1./CTA - CTAM=ABS(CTMIN) - CTB=ABS(CTL) - CT2=1./CTB - CTBM=ABS(CTLMIN) - A1=1. - DO 40 I=1,NAC -C CALCULATE THETA - NCI=IC(I) - NCJ=1 - IF (NCI.LE.NCON) NCJ=ISC(NCI) - C1=G(NCI) - CTD=CT1 - CTC=CTAM - IF (NCJ.LE.0) GO TO 10 - CTC=CTBM - CTD=CT2 -10 IF (C1.GT.CTC) NVC=NVC+1 - THT=0. - GG=1.+CTD*C1 - IF (NCJ.EQ.0.OR.C1.GT.CTC) THT=THETA*GG*GG - IF (THT.GT.50.) THT=50. - IF (THT.GT.THMAX) THMAX=THT - A(NDV1,I)=THT -C ------------------------------------------------------------------ -C NORMALIZE GRADIENTS OF CONSTRAINTS -C ------------------------------------------------------------------ - A(NDV2,I)=1. - IF (NCI.GT.NCON) GO TO 40 - A1=0. - DO 20 J=1,NDV - A1=A1+A(J,I)**2 -20 CONTINUE - IF (A1.LT.1.0E-20) A1=1.0E-20 - A1=SQRT(A1) - A(NDV2,I)=A1 - A1=1./A1 - DO 30 J=1,NDV -30 A(J,I)=A1*A(J,I) -40 CONTINUE -C ------------------------------------------------------------------ -C CHECK FOR ZERO GRADIENT. PROGRAM CHANGE-FEB, 1981, GV. -C ------------------------------------------------------------------ - I=0 -41 I=I+1 -42 CONTINUE - IF(A(NDV2,I).GT.1.0E-6) GO TO 45 -C ZERO GRADIENT IS FOUND. WRITE ERROR MESSAGE. - IF(IPRINT.GE.2) WRITE(IOUT,43)IC(I) -43 FORMAT(5X,13H** CONSTRAINT,I5,18H HAS ZERO GRADIENT/ - *5X,23HDELETED FROM ACTIVE SET) -C REDUCE NAC BY ONE. - NAC=NAC-1 -C SHIFT COLUMNS OF A AND ROWS OF IC IF I.LE.NAC. - IF(I.GT.NAC) GO TO 46 -C SHIFT. - DO 44 J=I,NAC - J1=J+1 - IC(J)=IC(J1) - DO 44 K=1,NDV2 -44 A(K,J)=A(K,J1) - IF(I.LE.NAC) GO TO 42 -45 CONTINUE - IF(I.LT.NAC) GO TO 41 -46 CONTINUE - IF(NAC.LE.0) RETURN - NAC1=NAC+1 -C DETERMINE IF CONSTRAINTS ARE VIOLATED. - NVC=0 - DO 47 I=1,NAC - NCI=IC(I) - NCJ=1 - IF(NCI.LE.NCON) NCJ=ISC(NCI) - CTC=CTAM - IF(NCJ.GT.0) CTC=CTBM - IF(G(NCI).GT.CTC) NVC=NVC+1 -47 CONTINUE -C ------------------------------------------------------------------ -C NORMALIZE GRADIENT OF OBJECTIVE FUNCTION AND STORE IN NAC+1 -C COLUMN OF A -C ------------------------------------------------------------------ - A1=0. - DO 50 I=1,NDV - A1=A1+DF(I)**2 -50 CONTINUE - IF (A1.LT.1.0E-20) A1=1.0E-20 - A1=SQRT(A1) - A1=1./A1 - DO 60 I=1,NDV -60 A(I,NAC1)=A1*DF(I) -C BUILD C VECTOR. - IF (NVC.GT.0) GO TO 80 -C ------------------------------------------------------------------ -C BUILD C FOR CLASSICAL METHOD -C ------------------------------------------------------------------ - NDB=NAC1 - A(NDV1,NDB)=1. - DO 70 I=1,NDB -70 C(I)=-A(NDV1,I) - GO TO 110 -80 CONTINUE -C ------------------------------------------------------------------ -C BUILD C FOR MODIFIED METHOD -C ------------------------------------------------------------------ - NDB=NAC - A(NDV1,NAC1)=-PHI -C ------------------------------------------------------------------ -C SCALE THETA'S SO THAT MAXIMUM THETA IS UNITY -C ------------------------------------------------------------------ - IF (THMAX.GT.0.00001) THMAX=1./THMAX - DO 90 I=1,NDB - A(NDV1,I)=A(NDV1,I)*THMAX -90 CONTINUE - DO 100 I=1,NDB - C(I)=0. - DO 100 J=1,NDV1 -100 C(I)=C(I)+A(J,I)*A(J,NAC1) -110 CONTINUE -C ------------------------------------------------------------------ -C BUILD B MATRIX -C ------------------------------------------------------------------ - DO 120 I=1,NDB - DO 120 J=1,NDB - B(I,J)=0. - DO 120 K=1,NDV1 -120 B(I,J)=B(I,J)-A(K,I)*A(K,J) -C ------------------------------------------------------------------ -C SOLVE SPECIAL L. P. PROBLEM -C ------------------------------------------------------------------ - CALL CNMN08 (NDB,NER,C,MS1,B,N3,N4,N5) - IF (IPRINT.GT.1.AND.NER.GT.0) WRITE (IOUT,180) -C CALCULATE RESULTING DIRECTION VECTOR, S. - SLOPE=0. -C ------------------------------------------------------------------ -C USABLE-FEASIBLE DIRECTION -C ------------------------------------------------------------------ - DO 140 I=1,NDV - S1=0. - IF (NVC.GT.0) S1=-A(I,NAC1) - DO 130 J=1,NDB -130 S1=S1-A(I,J)*C(J) - SLOPE=SLOPE+S1*DF(I) -140 S(I)=S1 - S(NDV1)=1. - IF (NVC.GT.0) S(NDV1)=-A(NDV1,NAC1) - DO 150 J=1,NDB -150 S(NDV1)=S(NDV1)-A(NDV1,J)*C(J) -C ------------------------------------------------------------------ -C CHECK TO INSURE THE S-VECTOR IS FEASIBLE. -C PROGRAM MOD-FEB, 1981, GV. -C ------------------------------------------------------------------ - DO 174 J=1,NAC -C S DOT DEL(G). - SG=0. - DO 172 I=1,NDV -172 SG=SG+S(I)*A(I,J) -C IF(SG.GT.0.) GO TO 176 -C -C THIS CHANGE MADE ON 4/8/81 FOR G. VANDERPLAATS -C - IF(SG.GT.1.0E-04) GO TO 176 -C FEASIBLE FOR THIS CONSTRAINT. CONTINUE. -174 CONTINUE - GO TO 179 -176 CONTINUE -C S-VECTOR IS NOT FEASIBLE DUE TO SOME NUMERICAL PROBLEM. - IF(IPRINT.GE.2) WRITE(IOUT,178) -178 FORMAT(5X,38H** CALCULATED S-VECTOR IS NOT FEASIBLE/5X, - * 19HBETA IS SET TO ZERO) - S(NDV1)=0. - NVC=0 - RETURN -179 CONTINUE -C ------------------------------------------------------------------ -C NORMALIZE S TO MAX ABS OF UNITY -C ------------------------------------------------------------------ - S1=0. - DO 160 I=1,NDV - A1=ABS(S(I)) - IF (A1.GT.S1) S1=A1 -160 CONTINUE -C IF (S1.LT.1.0E-10) RETURN -C -C E-10 CHANGED TO E-04 ON 1/12/81 -C - IF (S1.LT.1.0E-04) RETURN - S1=1./S1 - DO 170 I=1,NDV -170 S(I)=S1*S(I) - SLOPE=S1*SLOPE - S(NDV1)=S1*S(NDV1) - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -180 FORMAT (//5X,46H* * DIRECTION FINDING PROCESS DID NOT CONVERGE/5X, - 129H* * S-VECTOR MAY NOT BE VALID) - END diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn06.bak b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn06.bak deleted file mode 100644 index ecf2c6ff3..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn06.bak +++ /dev/null @@ -1,552 +0,0 @@ - SUBROUTINE CNMN06 (X,VLB,VUB,G,SCAL,DF,S,G1,G2,CTAM,CTBM,SLOPE,ALP - 1,A2,A3,A4,F1,F2,F3,CV1,CV2,CV3,CV4,ALPCA,ALPFES,ALPLN,ALPMIN,ALPNC - 2,ALPSAV,ALPSID,ALPTOT,ISC,N1,N2,NCAL,NVC,ICOUNT,IGOOD1,IGOOD2,IGOO - 3D3,IGOOD4,IBEST,III,NLNC,JGOTO) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - DIMENSION X(N1), VLB(N1), VUB(N1), G(N2), SCAL(N1), DF(N1), S(N1), - 1 G1(N2), G2(N2), ISC(N2), NCAL(2) -C ROUTINE TO SOLVE ONE-DIMENSIONAL SEARCH PROBLEM FOR CONSTRAINED -C FUNCTION MINIMIZATION. -C BY G. N. VANDERPLAATS AUG., 1974. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C OBJ = INITIAL AND FINAL FUNCTION VALUE. -C ALP = MOVE PARAMETER. -C SLOPE = INITIAL SLOPE. -C -C ALPSID = MOVE TO SIDE CONSTRAINT. -C ALPFES = MOVE TO FEASIBLE REGION. -C ALPNC = MOVE TO NEW NON-LINEAR CONSTRAINT. -C ALPLN = MOVE TO LINEAR CONSTRAINT. -C ALPCA = MOVE TO RE-ENCOUNTER CURRENTLY ACTIVE CONSTRAINT. -C ALPMIN = MOVE TO MINIMIZE FUNCTION. -C ALPTOT = TOTAL MOVE PARAMETER. - ZRO=0. - IF (JGOTO.EQ.0) GO TO 10 - GO TO (140,310,520),JGOTO -10 IF (IPRINT.GE.5) WRITE (6,730) - ALPSAV=ALP - ICOUNT=0 - ALPTOT=0. -C TOLERANCES. - CTAM=ABS(CTMIN) - CTBM=ABS(CTLMIN) -C PROPOSED MOVE. -20 CONTINUE -C ------------------------------------------------------------------ -C ***** BEGIN SEARCH OR IMPOSE SIDE CONSTRAINT MODIFICATION ***** -C ------------------------------------------------------------------ - A2=ALPSAV - ICOUNT=ICOUNT+1 - ALPSID=1.0E+20 -C INITIAL ALPHA AND OBJ. - ALP=0. - F1=OBJ - KSID=0 - IF (NSIDE.EQ.0) GO TO 70 -C ------------------------------------------------------------------ -C FIND MOVE TO SIDE CONSTRAINT AND INSURE AGAINST VIOLATION OF -C SIDE CONSTRAINTS -C ------------------------------------------------------------------ - DO 60 I=1,NDV - SI=S(I) - IF (ABS(SI).GT.1.0E-20) GO TO 30 -C ITH COMPONENT OF S IS SMALL. SET TO ZERO. - S(I)=0. - SLOPE=SLOPE-SI*DF(I) - GO TO 60 -30 CONTINUE - XI=X(I) - SI=1./SI - IF (SI.GT.0.) GO TO 40 -C LOWER BOUND. - XI2=VLB(I) - XI1=ABS(XI2) - IF (XI1.LT.1.) XI1=1. -C CONSTRAINT VALUE. - GI=(XI2-XI)/XI1 - IF (GI.GT.-1.0E-6) GO TO 50 -C PROPOSED MOVE TO LOWER BOUND. - ALPA=(XI2-XI)*SI - IF (ALPA.LT.ALPSID) ALPSID=ALPA - GO TO 60 -40 CONTINUE -C UPPER BOUND. - XI2=VUB(I) - XI1=ABS(XI2) - IF (XI1.LT.1.) XI1=1. -C CONSTRAINT VALUE. - GI=(XI-XI2)/XI1 - IF (GI.GT.-1.0E-6) GO TO 50 -C PROPOSED MOVE TO UPPER BOUND. - ALPA=(XI2-XI)*SI - IF (ALPA.LT.ALPSID) ALPSID=ALPA - GO TO 60 -50 CONTINUE -C MOVE WILL VIOLATE SIDE CONSTRAINT. SET S(I)=0. - SLOPE=SLOPE-S(I)*DF(I) - S(I)=0. - KSID=KSID+1 -60 CONTINUE -C ALPSID IS UPPER BOUND ON ALPHA. - IF (A2.GT.ALPSID) A2=ALPSID -70 CONTINUE -C ------------------------------------------------------------------ -C CHECK ILL-CONDITIONING -C ------------------------------------------------------------------ - IF (KSID.EQ.NDV.OR.ICOUNT.GT.10) GO TO 710 - IF (NVC.EQ.0.AND.SLOPE.GT.0.) GO TO 710 - ALPFES=-1. - ALPMIN=-1. - ALPLN=1.1*ALPSID - ALPNC=ALPSID - ALPCA=ALPSID - IF (NCON.EQ.0) GO TO 90 -C STORE CONSTRAINT VALUES IN G1. - DO 80 I=1,NCON - G1(I)=G(I) -80 CONTINUE -90 CONTINUE -C ------------------------------------------------------------------ -C MOVE A DISTANCE A2*S -C ------------------------------------------------------------------ - ALPTOT=ALPTOT+A2 - DO 100 I=1,NDV - X(I)=X(I)+A2*S(I) -100 CONTINUE - IF (IPRINT.LT.5) GO TO 130 - WRITE (6,740) A2 - IF (NSCAL.EQ.0) GO TO 120 - DO 110 I=1,NDV -110 G(I)=SCAL(I)*X(I) - WRITE (6,750) (G(I),I=1,NDV) - GO TO 130 -120 WRITE (6,750) (X(I),I=1,NDV) -C ------------------------------------------------------------------ -C UPDATE FUNCTION AND CONSTRAINT VALUES -C ------------------------------------------------------------------ -130 NCAL(1)=NCAL(1)+1 - JGOTO=1 - RETURN -140 CONTINUE - F2=OBJ - IF (IPRINT.GE.5) WRITE (6,760) F2 - IF (IPRINT.LT.5.OR.NCON.EQ.0) GO TO 150 - WRITE (6,770) - WRITE (6,750) (G(I),I=1,NCON) -150 CONTINUE -C ------------------------------------------------------------------ -C IDENTIFY ACCAPTABILITY OF DESIGNS F1 AND F2 -C ------------------------------------------------------------------ -C IGOOD = 0 IS ACCAPTABLE. -C CV = MAXIMUM CONSTRAINT VIOLATION. - IGOOD1=0 - IGOOD2=0 - CV1=0. - CV2=0. - NVC1=0 - IF (NCON.EQ.0) GO TO 170 - DO 160 I=1,NCON - CC=CTAM - IF (ISC(I).GT.0) CC=CTBM - C1=G1(I)-CC - C2=G(I)-CC - IF (C2.GT.0.) NVC1=NVC1+1 - IF (C1.GT.CV1) CV1=C1 - IF (C2.GT.CV2) CV2=C2 -160 CONTINUE - IF (CV1.GT.0.) IGOOD1=1 - IF (CV2.GT.0.) IGOOD2=1 -170 CONTINUE - ALP=A2 - OBJ=F2 -C ------------------------------------------------------------------ -C IF F2 VIOLATES FEWER CONSTRAINTS THAN F1 BUT STILL HAS CONSTRAINT -C VIOLATIONS RETURN -C ------------------------------------------------------------------ - IF (NVC1.LT.NVC.AND.NVC1.GT.0) GO TO 710 -C ------------------------------------------------------------------ -C IDENTIFY BEST OF DESIGNS F1 ANF F2 -C ------------------------------------------------------------------ -C IBEST CORRESPONDS TO MINIMUM VALUE DESIGN. -C IF CONSTRAINTS ARE VIOLATED, IBEST CORRESPONDS TO MINIMUM -C CONSTRAINT VIOLATION. - IF (IGOOD1.EQ.0.AND.IGOOD2.EQ.0) GO TO 180 -C VIOLATED CONSTRAINTS. PICK MINIMUM VIOLATION. - IBEST=1 - IF (CV1.GE.CV2) IBEST=2 - GO TO 190 -180 CONTINUE -C NO CONSTRAINT VIOLATION. PICK MINIMUM F. - IBEST=1 - IF (F2.LE.F1) IBEST=2 -190 CONTINUE - II=1 -C ------------------------------------------------------------------ -C IF CV2 IS GREATER THAN CV1, SET MOVE LIMITS TO A2. -C PROGRAM MOD-FEB, 1981, GV. -C ------------------------------------------------------------------ - IF(CV2.LE.CV1) GO TO 195 - ALPLN=A2 - ALPNC=A2 - ALPCA=A2 -195 CONTINUE - IF (NCON.EQ.0) GO TO 230 -C ------------------------------------------------------------------ -C ***** 2 - POINT INTERPOLATION ***** -C ------------------------------------------------------------------ - III=0 -200 III=III+1 - C1=G1(III) - C2=G(III) - IF (ISC(III).EQ.0) GO TO 210 -C ------------------------------------------------------------------ -C LINEAR CONSTRAINT -C ------------------------------------------------------------------ - IF (C1.GE.1.0E-5.AND.C1.LE.CTBM) GO TO 220 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A2,C2,ZRO,ZRO) - IF (ALP.LE.0.) GO TO 220 - IF (C1.GT.CTBM.AND.ALP.GT.ALPFES) ALPFES=ALP - IF (C1.LT.CTL.AND.ALP.LT.ALPLN) ALPLN=ALP - GO TO 220 -210 CONTINUE -C ------------------------------------------------------------------ -C NON-LINEAR CONSTRAINT -C ------------------------------------------------------------------ - IF (C1.GE.1.0E-5.AND.C1.LE.CTAM) GO TO 220 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A2,C2,ZRO,ZRO) - IF (ALP.LE.0.) GO TO 220 - IF (C1.GT.CTAM.AND.ALP.GT.ALPFES) ALPFES=ALP - IF (C1.LT.CT.AND.ALP.LT.ALPNC) ALPNC=ALP -220 CONTINUE - IF (III.LT.NCON) GO TO 200 -230 CONTINUE - IF (LINOBJ.GT.0.OR.SLOPE.GE.0.) GO TO 240 -C CALCULATE ALPHA TO MINIMIZE FUNCTION. - CALL CNMN04 (II,ALPMIN,ZRO,ZRO,F1,SLOPE,A2,F2,ZRO,ZRO,ZRO,ZRO) -240 CONTINUE -C ------------------------------------------------------------------ -C PROPOSED MOVE -C ------------------------------------------------------------------ -C MOVE AT LEAST FAR ENOUGH TO OVERCOME CONSTRAINT VIOLATIONS. - A3=ALPFES -C MOVE TO MINIMIZE FUNCTION. - IF (ALPMIN.GT.A3) A3=ALPMIN -C IF A3.LE.0, SET A3 = ALPSID. - IF (A3.LE.0.) A3=ALPSID -C LIMIT MOVE TO NEW CONSTRAINT ENCOUNTER. - IF (A3.GT.ALPNC) A3=ALPNC - IF (A3.GT.ALPLN) A3=ALPLN -C MAKE A3 NON-ZERO. - IF (A3.LE.1.0E-20) A3=1.0E-20 -C IF A3=A2=ALPSID AND F2 IS BEST, GO INVOKE SIDE CONSTRAINT -C MODIFICATION. - ALPB=1.-A2/A3 - ALPA=1.-ALPSID/A3 - JBEST=0 - IF (ABS(ALPB).LT.1.0E-10.AND.ABS(ALPA).LT.1.0E-10) JBEST=1 - IF (JBEST.EQ.1.AND.IBEST.EQ.2) GO TO 20 -C SIDE CONSTRAINT CHECK NOT SATISFIED. - IF (NCON.EQ.0) GO TO 260 -C STORE CONSTRAINT VALUES IN G2. - DO 250 I=1,NCON - G2(I)=G(I) -250 CONTINUE -260 CONTINUE -C IF A3=A2, SET A3=.9*A2. - IF (ABS(ALPB).LT.1.0E-10) A3=.9*A2 -C MOVE AT LEAST .01*A2. - IF (A3.LT.(.01*A2)) A3=.01*A2 -C LIMIT MOVE TO 5.*A2. - IF (A3.GT.(5.*A2)) A3=5.*A2 -C LIMIT MOVE TO ALPSID. - IF (A3.GT.ALPSID) A3=ALPSID -C MOVE A DISTANCE A3*S. - ALP=A3-A2 - ALPTOT=ALPTOT+ALP - DO 270 I=1,NDV - X(I)=X(I)+ALP*S(I) -270 CONTINUE - IF (IPRINT.LT.5) GO TO 300 - WRITE (6,780) - WRITE (6,740) A3 - IF (NSCAL.EQ.0) GO TO 290 - DO 280 I=1,NDV -280 G(I)=SCAL(I)*X(I) - WRITE (6,750) (G(I),I=1,NDV) - GO TO 300 -290 WRITE (6,750) (X(I),I=1,NDV) -300 CONTINUE -C ------------------------------------------------------------------ -C UPDATE FUNCTION AND CONSTRAINT VALUES -C ------------------------------------------------------------------ - NCAL(1)=NCAL(1)+1 - JGOTO=2 - RETURN -310 CONTINUE - F3=OBJ - IF (IPRINT.GE.5) WRITE (6,760) F3 - IF (IPRINT.LT.5.OR.NCON.EQ.0) GO TO 320 - WRITE (6,770) - WRITE (6,750) (G(I),I=1,NCON) -320 CONTINUE -C ------------------------------------------------------------------ -C CALCULATE MAXIMUM CONSTRAINT VIOLATION AND PICK BEST DESIGN -C ------------------------------------------------------------------ - CV3=0. - IGOOD3=0 - NVC1=0 - IF (NCON.EQ.0) GO TO 340 - DO 330 I=1,NCON - CC=CTAM - IF (ISC(I).GT.0) CC=CTBM - C1=G(I)-CC - IF (C1.GT.CV3) CV3=C1 - IF (C1.GT.0.) NVC1=NVC1+1 -330 CONTINUE - IF (CV3.GT.0.) IGOOD3=1 -340 CONTINUE -C DETERMINE BEST DESIGN. - IF (IBEST.EQ.2) GO TO 360 -C CHOOSE BETWEEN F1 AND F3. - IF (IGOOD1.EQ.0.AND.IGOOD3.EQ.0) GO TO 350 - IF (CV1.GE.CV3) IBEST=3 - GO TO 380 -350 IF (F3.LE.F1) IBEST=3 - GO TO 380 -360 CONTINUE -C CHOOSE BETWEEN F2 AND F3. - IF (IGOOD2.EQ.0.AND.IGOOD3.EQ.0) GO TO 370 - IF (CV2.GE.CV3) IBEST=3 - GO TO 380 -370 IF (F3.LE.F2) IBEST=3 -380 CONTINUE - ALP=A3 - OBJ=F3 -C IF F3 VIOLATES FEWER CONSTRAINTS THAN F1 RETURN. - IF (NVC1.LT.NVC) GO TO 710 -C IF OBJECTIVE AND ALL CONSTRAINTS ARE LINEAR, RETURN. - IF (LINOBJ.NE.0.AND.NLNC.EQ.NCON) GO TO 710 -C IF A3 = ALPLN AND F3 IS BOTH GOOD AND BEST RETURN. - ALPB=1.-ALPLN/A3 - IF ((ABS(ALPB).LT.1.0E-20.AND.IBEST.EQ.3).AND.(IGOOD3.EQ.0)) GO TO - 1 710 -C IF A3 = ALPSID AND F3 IS BEST, GO INVOKE SIDE CONSTRAINT -C MODIFICATION. - ALPA=1.-ALPSID/A3 - IF (ABS(ALPA).LT.1.0E-20.AND.IBEST.EQ.3) GO TO 20 -C ------------------------------------------------------------------ -C ********** 3 - POINT INTERPOLATION ********* -C ------------------------------------------------------------------ - ALPNC=ALPSID - ALPCA=ALPSID - ALPFES=-1. - ALPMIN=-1. -C ------------------------------------------------------------------ -C IF A3 IS GREATER THAN A2 AND CV3 IS GREATER THAN CV2, SET -C MOVE LIMITS TO A3. PROGRAM MOD-FEB, 1981, GV. -C ------------------------------------------------------------------ - IF(A3.LE.A2.OR.CV3.LE.CV2) GO TO 285 - ALPLN=A3 - ALPNC=A3 - ALPCA=A3 -285 CONTINUE - IF (NCON.EQ.0) GO TO 440 - III=0 -390 III=III+1 - C1=G1(III) - C2=G2(III) - C3=G(III) - IF (ISC(III).EQ.0) GO TO 400 -C ------------------------------------------------------------------ -C LINEAR CONSTRAINT. FIND ALPFES ONLY. ALPLN SAME AS BEFORE. -C ------------------------------------------------------------------ - IF (C1.LE.CTBM) GO TO 430 - II=1 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A3,C3,ZRO,ZRO) - IF (ALP.GT.ALPFES) ALPFES=ALP - GO TO 430 -400 CONTINUE -C ------------------------------------------------------------------ -C NON-LINEAR CONSTRAINT -C ------------------------------------------------------------------ - II=2 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A2,C2,A3,C3) - IF (ALP.LE.ZRO) GO TO 430 - IF (C1.GE.CT.AND.C1.LE.0.) GO TO 410 - IF (C1.GT.CTAM.OR.C1.LT.0.) GO TO 420 -C ALP IS MINIMUM MOVE. UPDATE FOR NEXT CONSTRAINT ENCOUNTER. -410 ALPA=ALP - CALL CNMN07 (II,ALP,ALPA,ZRO,C1,A2,C2,A3,C3) - IF (ALP.LT.ALPCA.AND.ALP.GE.ALPA) ALPCA=ALP - GO TO 430 -420 CONTINUE - IF (ALP.GT.ALPFES.AND.C1.GT.CTAM) ALPFES=ALP - IF (ALP.LT.ALPNC.AND.C1.LT.0.) ALPNC=ALP -430 CONTINUE - IF (III.LT.NCON) GO TO 390 -440 CONTINUE - IF (LINOBJ.GT.0.OR.SLOPE.GT.0.) GO TO 450 -C ------------------------------------------------------------------ -C CALCULATE ALPHA TO MINIMIZE FUNCTION -C ------------------------------------------------------------------ - II=3 - IF (A2.GT.A3.AND.(IGOOD2.EQ.0.AND.IBEST.EQ.2)) II=2 - CALL CNMN04 (II,ALPMIN,ZRO,ZRO,F1,SLOPE,A2,F2,A3,F3,ZRO,ZRO) -450 CONTINUE -C ------------------------------------------------------------------ -C PROPOSED MOVE -C ------------------------------------------------------------------ -C MOVE AT LEAST ENOUGH TO OVERCOME CONSTRAINT VIOLATIONS. - A4=ALPFES -C MOVE TO MINIMIZE FUNCTION. - IF (ALPMIN.GT.A4) A4=ALPMIN -C IF A4.LE.0, SET A4 = ALPSID. - IF (A4.LE.0.) A4=ALPSID -C LIMIT MOVE TO NEW CONSTRAINT ENCOUNTER. - IF (A4.GT.ALPLN) A4=ALPLN - IF (A4.GT.ALPNC) A4=ALPNC -C LIMIT MOVE TO RE-ENCOUNTER CURRENTLY ACTIVE CONSTRAINT. - IF (A4.GT.ALPCA) A4=ALPCA -C LIMIT A4 TO 5.*A3. - IF (A4.GT.(5.*A3)) A4=5.*A3 -C UPDATE DESIGN. - IF (IBEST.NE.3.OR.NCON.EQ.0) GO TO 470 -C STORE CONSTRAINT VALUES IN G2. F3 IS BEST. F2 IS NOT. - DO 460 I=1,NCON - G2(I)=G(I) -460 CONTINUE -470 CONTINUE -C IF A4=A3 AND IGOOD1=0 AND IGOOD3=1, SET A4=.9*A3. - ALP=A4-A3 - IF ((IGOOD1.EQ.0.AND.IGOOD3.EQ.1).AND.ABS(ALP).LT.1.0E-20) A4=.9*A - 13 -C ------------------------------------------------------------------ -C MOVE A DISTANCE A4*S -C ------------------------------------------------------------------ - ALP=A4-A3 - ALPTOT=ALPTOT+ALP - DO 480 I=1,NDV - X(I)=X(I)+ALP*S(I) -480 CONTINUE - IF (IPRINT.LT.5) GO TO 510 - WRITE (6,720) - WRITE (6,740) A4 - IF (NSCAL.EQ.0) GO TO 500 - DO 490 I=1,NDV -490 G(I)=SCAL(I)*X(I) - WRITE (6,750) (G(I),I=1,NDV) - GO TO 510 -500 WRITE (6,750) (X(I),I=1,NDV) -510 CONTINUE -C ------------------------------------------------------------------ -C UPDATE FUNCTION AND CONSTRAINT VALUES -C ------------------------------------------------------------------ - NCAL(1)=NCAL(1)+1 - JGOTO=3 - RETURN -520 CONTINUE - F4=OBJ - IF (IPRINT.GE.5) WRITE (6,760) F4 - IF (IPRINT.LT.5.OR.NCON.EQ.0) GO TO 530 - WRITE (6,770) - WRITE (6,750) (G(I),I=1,NCON) -530 CONTINUE -C DETERMINE ACCAPTABILITY OF F4. - IGOOD4=0 - CV4=0. - IF (NCON.EQ.0) GO TO 550 - DO 540 I=1,NCON - CC=CTAM - IF (ISC(I).GT.0) CC=CTBM - C1=G(I)-CC - IF (C1.GT.CV4) CV4=C1 -540 CONTINUE - IF (CV4.GT.0.) IGOOD4=1 -550 CONTINUE - ALP=A4 - OBJ=F4 -C ------------------------------------------------------------------ -C DETERMINE BEST DESIGN -C ------------------------------------------------------------------ - GO TO (560,610,660),IBEST -560 CONTINUE -C CHOOSE BETWEEN F1 AND F4. - IF (IGOOD1.EQ.0.AND.IGOOD4.EQ.0) GO TO 570 - IF (CV1.GT.CV4) GO TO 710 - GO TO 580 -570 CONTINUE - IF (F4.LE.F1) GO TO 710 -580 CONTINUE -C F1 IS BEST. - ALPTOT=ALPTOT-A4 - OBJ=F1 - DO 590 I=1,NDV - X(I)=X(I)-A4*S(I) -590 CONTINUE - IF (NCON.EQ.0) GO TO 710 - DO 600 I=1,NCON - G(I)=G1(I) -600 CONTINUE - GO TO 710 -610 CONTINUE -C CHOOSE BETWEEN F2 AND F4. - IF (IGOOD2.EQ.0.AND.IGOOD4.EQ.0) GO TO 620 - IF (CV2.GT.CV4) GO TO 710 - GO TO 630 -620 CONTINUE - IF (F4.LE.F2) GO TO 710 -630 CONTINUE -C F2 IS BEST. - OBJ=F2 - A2=A4-A2 - ALPTOT=ALPTOT-A2 - DO 640 I=1,NDV - X(I)=X(I)-A2*S(I) -640 CONTINUE - IF (NCON.EQ.0) GO TO 710 - DO 650 I=1,NCON - G(I)=G2(I) -650 CONTINUE - GO TO 710 -660 CONTINUE -C CHOOSE BETWEEN F3 AND F4. - IF (IGOOD3.EQ.0.AND.IGOOD4.EQ.0) GO TO 670 - IF (CV3.GT.CV4) GO TO 710 - GO TO 680 -670 CONTINUE - IF (F4.LE.F3) GO TO 710 -680 CONTINUE -C F3 IS BEST. - OBJ=F3 - A3=A4-A3 - ALPTOT=ALPTOT-A3 - DO 690 I=1,NDV - X(I)=X(I)-A3*S(I) -690 CONTINUE - IF (NCON.EQ.0) GO TO 710 - DO 700 I=1,NCON - G(I)=G2(I) -700 CONTINUE -710 CONTINUE - ALP=ALPTOT - IF (IPRINT.GE.5) WRITE (6,790) - JGOTO=0 - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -720 FORMAT (/5X,25HTHREE-POINT INTERPOLATION) -730 FORMAT (/////58H* * * CONSTRAINED ONE-DIMENSIONAL SEARCH INFORMATI - 1ON * * *) -740 FORMAT (//5X,15HPROPOSED DESIGN/5X,7HALPHA =,E12.5/5X,8HX-VECTOR) -750 FORMAT (1X,8E12.4) -760 FORMAT (/5X,5HOBJ =,E13.5) -770 FORMAT (/5X,17HCONSTRAINT VALUES) -780 FORMAT (/5X,23HTWO-POINT INTERPOLATION) -790 FORMAT (/5X,35H* * * END OF ONE-DIMENSIONAL SEARCH) - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn06.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn06.f deleted file mode 100644 index 82dd7d0d8..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn06.f +++ /dev/null @@ -1,553 +0,0 @@ - SUBROUTINE CNMN06 (X,VLB,VUB,G,SCAL,DF,S,G1,G2,CTAM,CTBM,SLOPE,ALP - 1,A2,A3,A4,F1,F2,F3,CV1,CV2,CV3,CV4,ALPCA,ALPFES,ALPLN,ALPMIN,ALPNC - 2,ALPSAV,ALPSID,ALPTOT,ISC,N1,N2,NCAL,NVC,ICOUNT,IGOOD1,IGOOD2,IGOO - 3D3,IGOOD4,IBEST,III,NLNC,JGOTO) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN,ALPHAX - 1,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ,ITMAX,IT - 2RM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER,NFEASCT - COMMON /OUTPUT/ IOUT - DIMENSION X(N1), VLB(N1), VUB(N1), G(N2), SCAL(N1), DF(N1), S(N1), - 1 G1(N2), G2(N2), ISC(N2), NCAL(2) -C ROUTINE TO SOLVE ONE-DIMENSIONAL SEARCH PROBLEM FOR CONSTRAINED -C FUNCTION MINIMIZATION. -C BY G. N. VANDERPLAATS AUG., 1974. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C OBJ = INITIAL AND FINAL FUNCTION VALUE. -C ALP = MOVE PARAMETER. -C SLOPE = INITIAL SLOPE. -C -C ALPSID = MOVE TO SIDE CONSTRAINT. -C ALPFES = MOVE TO FEASIBLE REGION. -C ALPNC = MOVE TO NEW NON-LINEAR CONSTRAINT. -C ALPLN = MOVE TO LINEAR CONSTRAINT. -C ALPCA = MOVE TO RE-ENCOUNTER CURRENTLY ACTIVE CONSTRAINT. -C ALPMIN = MOVE TO MINIMIZE FUNCTION. -C ALPTOT = TOTAL MOVE PARAMETER. - ZRO=0. - IF (JGOTO.EQ.0) GO TO 10 - GO TO (140,310,520),JGOTO -10 IF (IPRINT.GE.5) WRITE (IOUT,730) - ALPSAV=ALP - ICOUNT=0 - ALPTOT=0. -C TOLERANCES. - CTAM=ABS(CTMIN) - CTBM=ABS(CTLMIN) -C PROPOSED MOVE. -20 CONTINUE -C ------------------------------------------------------------------ -C ***** BEGIN SEARCH OR IMPOSE SIDE CONSTRAINT MODIFICATION ***** -C ------------------------------------------------------------------ - A2=ALPSAV - ICOUNT=ICOUNT+1 - ALPSID=1.0E+20 -C INITIAL ALPHA AND OBJ. - ALP=0. - F1=OBJ - KSID=0 - IF (NSIDE.EQ.0) GO TO 70 -C ------------------------------------------------------------------ -C FIND MOVE TO SIDE CONSTRAINT AND INSURE AGAINST VIOLATION OF -C SIDE CONSTRAINTS -C ------------------------------------------------------------------ - DO 60 I=1,NDV - SI=S(I) - IF (ABS(SI).GT.1.0E-20) GO TO 30 -C ITH COMPONENT OF S IS SMALL. SET TO ZERO. - S(I)=0. - SLOPE=SLOPE-SI*DF(I) - GO TO 60 -30 CONTINUE - XI=X(I) - SI=1./SI - IF (SI.GT.0.) GO TO 40 -C LOWER BOUND. - XI2=VLB(I) - XI1=ABS(XI2) - IF (XI1.LT.1.) XI1=1. -C CONSTRAINT VALUE. - GI=(XI2-XI)/XI1 - IF (GI.GT.-1.0E-6) GO TO 50 -C PROPOSED MOVE TO LOWER BOUND. - ALPA=(XI2-XI)*SI - IF (ALPA.LT.ALPSID) ALPSID=ALPA - GO TO 60 -40 CONTINUE -C UPPER BOUND. - XI2=VUB(I) - XI1=ABS(XI2) - IF (XI1.LT.1.) XI1=1. -C CONSTRAINT VALUE. - GI=(XI-XI2)/XI1 - IF (GI.GT.-1.0E-6) GO TO 50 -C PROPOSED MOVE TO UPPER BOUND. - ALPA=(XI2-XI)*SI - IF (ALPA.LT.ALPSID) ALPSID=ALPA - GO TO 60 -50 CONTINUE -C MOVE WILL VIOLATE SIDE CONSTRAINT. SET S(I)=0. - SLOPE=SLOPE-S(I)*DF(I) - S(I)=0. - KSID=KSID+1 -60 CONTINUE -C ALPSID IS UPPER BOUND ON ALPHA. - IF (A2.GT.ALPSID) A2=ALPSID -70 CONTINUE -C ------------------------------------------------------------------ -C CHECK ILL-CONDITIONING -C ------------------------------------------------------------------ - IF (KSID.EQ.NDV.OR.ICOUNT.GT.10) GO TO 710 - IF (NVC.EQ.0.AND.SLOPE.GT.0.) GO TO 710 - ALPFES=-1. - ALPMIN=-1. - ALPLN=1.1*ALPSID - ALPNC=ALPSID - ALPCA=ALPSID - IF (NCON.EQ.0) GO TO 90 -C STORE CONSTRAINT VALUES IN G1. - DO 80 I=1,NCON - G1(I)=G(I) -80 CONTINUE -90 CONTINUE -C ------------------------------------------------------------------ -C MOVE A DISTANCE A2*S -C ------------------------------------------------------------------ - ALPTOT=ALPTOT+A2 - DO 100 I=1,NDV - X(I)=X(I)+A2*S(I) -100 CONTINUE - IF (IPRINT.LT.5) GO TO 130 - WRITE (IOUT,740) A2 - IF (NSCAL.EQ.0) GO TO 120 - DO 110 I=1,NDV -110 G(I)=SCAL(I)*X(I) - WRITE (IOUT,750) (G(I),I=1,NDV) - GO TO 130 -120 WRITE (IOUT,750) (X(I),I=1,NDV) -C ------------------------------------------------------------------ -C UPDATE FUNCTION AND CONSTRAINT VALUES -C ------------------------------------------------------------------ -130 NCAL(1)=NCAL(1)+1 - JGOTO=1 - RETURN -140 CONTINUE - F2=OBJ - IF (IPRINT.GE.5) WRITE (IOUT,760) F2 - IF (IPRINT.LT.5.OR.NCON.EQ.0) GO TO 150 - WRITE (IOUT,770) - WRITE (IOUT,750) (G(I),I=1,NCON) -150 CONTINUE -C ------------------------------------------------------------------ -C IDENTIFY ACCAPTABILITY OF DESIGNS F1 AND F2 -C ------------------------------------------------------------------ -C IGOOD = 0 IS ACCAPTABLE. -C CV = MAXIMUM CONSTRAINT VIOLATION. - IGOOD1=0 - IGOOD2=0 - CV1=0. - CV2=0. - NVC1=0 - IF (NCON.EQ.0) GO TO 170 - DO 160 I=1,NCON - CC=CTAM - IF (ISC(I).GT.0) CC=CTBM - C1=G1(I)-CC - C2=G(I)-CC - IF (C2.GT.0.) NVC1=NVC1+1 - IF (C1.GT.CV1) CV1=C1 - IF (C2.GT.CV2) CV2=C2 -160 CONTINUE - IF (CV1.GT.0.) IGOOD1=1 - IF (CV2.GT.0.) IGOOD2=1 -170 CONTINUE - ALP=A2 - OBJ=F2 -C ------------------------------------------------------------------ -C IF F2 VIOLATES FEWER CONSTRAINTS THAN F1 BUT STILL HAS CONSTRAINT -C VIOLATIONS RETURN -C ------------------------------------------------------------------ - IF (NVC1.LT.NVC.AND.NVC1.GT.0) GO TO 710 -C ------------------------------------------------------------------ -C IDENTIFY BEST OF DESIGNS F1 ANF F2 -C ------------------------------------------------------------------ -C IBEST CORRESPONDS TO MINIMUM VALUE DESIGN. -C IF CONSTRAINTS ARE VIOLATED, IBEST CORRESPONDS TO MINIMUM -C CONSTRAINT VIOLATION. - IF (IGOOD1.EQ.0.AND.IGOOD2.EQ.0) GO TO 180 -C VIOLATED CONSTRAINTS. PICK MINIMUM VIOLATION. - IBEST=1 - IF (CV1.GE.CV2) IBEST=2 - GO TO 190 -180 CONTINUE -C NO CONSTRAINT VIOLATION. PICK MINIMUM F. - IBEST=1 - IF (F2.LE.F1) IBEST=2 -190 CONTINUE - II=1 -C ------------------------------------------------------------------ -C IF CV2 IS GREATER THAN CV1, SET MOVE LIMITS TO A2. -C PROGRAM MOD-FEB, 1981, GV. -C ------------------------------------------------------------------ - IF(CV2.LE.CV1) GO TO 195 - ALPLN=A2 - ALPNC=A2 - ALPCA=A2 -195 CONTINUE - IF (NCON.EQ.0) GO TO 230 -C ------------------------------------------------------------------ -C ***** 2 - POINT INTERPOLATION ***** -C ------------------------------------------------------------------ - III=0 -200 III=III+1 - C1=G1(III) - C2=G(III) - IF (ISC(III).EQ.0) GO TO 210 -C ------------------------------------------------------------------ -C LINEAR CONSTRAINT -C ------------------------------------------------------------------ - IF (C1.GE.1.0E-5.AND.C1.LE.CTBM) GO TO 220 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A2,C2,ZRO,ZRO) - IF (ALP.LE.0.) GO TO 220 - IF (C1.GT.CTBM.AND.ALP.GT.ALPFES) ALPFES=ALP - IF (C1.LT.CTL.AND.ALP.LT.ALPLN) ALPLN=ALP - GO TO 220 -210 CONTINUE -C ------------------------------------------------------------------ -C NON-LINEAR CONSTRAINT -C ------------------------------------------------------------------ - IF (C1.GE.1.0E-5.AND.C1.LE.CTAM) GO TO 220 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A2,C2,ZRO,ZRO) - IF (ALP.LE.0.) GO TO 220 - IF (C1.GT.CTAM.AND.ALP.GT.ALPFES) ALPFES=ALP - IF (C1.LT.CT.AND.ALP.LT.ALPNC) ALPNC=ALP -220 CONTINUE - IF (III.LT.NCON) GO TO 200 -230 CONTINUE - IF (LINOBJ.GT.0.OR.SLOPE.GE.0.) GO TO 240 -C CALCULATE ALPHA TO MINIMIZE FUNCTION. - CALL CNMN04 (II,ALPMIN,ZRO,ZRO,F1,SLOPE,A2,F2,ZRO,ZRO,ZRO,ZRO) -240 CONTINUE -C ------------------------------------------------------------------ -C PROPOSED MOVE -C ------------------------------------------------------------------ -C MOVE AT LEAST FAR ENOUGH TO OVERCOME CONSTRAINT VIOLATIONS. - A3=ALPFES -C MOVE TO MINIMIZE FUNCTION. - IF (ALPMIN.GT.A3) A3=ALPMIN -C IF A3.LE.0, SET A3 = ALPSID. - IF (A3.LE.0.) A3=ALPSID -C LIMIT MOVE TO NEW CONSTRAINT ENCOUNTER. - IF (A3.GT.ALPNC) A3=ALPNC - IF (A3.GT.ALPLN) A3=ALPLN -C MAKE A3 NON-ZERO. - IF (A3.LE.1.0E-20) A3=1.0E-20 -C IF A3=A2=ALPSID AND F2 IS BEST, GO INVOKE SIDE CONSTRAINT -C MODIFICATION. - ALPB=1.-A2/A3 - ALPA=1.-ALPSID/A3 - JBEST=0 - IF (ABS(ALPB).LT.1.0E-10.AND.ABS(ALPA).LT.1.0E-10) JBEST=1 - IF (JBEST.EQ.1.AND.IBEST.EQ.2) GO TO 20 -C SIDE CONSTRAINT CHECK NOT SATISFIED. - IF (NCON.EQ.0) GO TO 260 -C STORE CONSTRAINT VALUES IN G2. - DO 250 I=1,NCON - G2(I)=G(I) -250 CONTINUE -260 CONTINUE -C IF A3=A2, SET A3=.9*A2. - IF (ABS(ALPB).LT.1.0E-10) A3=.9*A2 -C MOVE AT LEAST .01*A2. - IF (A3.LT.(.01*A2)) A3=.01*A2 -C LIMIT MOVE TO 5.*A2. - IF (A3.GT.(5.*A2)) A3=5.*A2 -C LIMIT MOVE TO ALPSID. - IF (A3.GT.ALPSID) A3=ALPSID -C MOVE A DISTANCE A3*S. - ALP=A3-A2 - ALPTOT=ALPTOT+ALP - DO 270 I=1,NDV - X(I)=X(I)+ALP*S(I) -270 CONTINUE - IF (IPRINT.LT.5) GO TO 300 - WRITE (IOUT,780) - WRITE (IOUT,740) A3 - IF (NSCAL.EQ.0) GO TO 290 - DO 280 I=1,NDV -280 G(I)=SCAL(I)*X(I) - WRITE (IOUT,750) (G(I),I=1,NDV) - GO TO 300 -290 WRITE (IOUT,750) (X(I),I=1,NDV) -300 CONTINUE -C ------------------------------------------------------------------ -C UPDATE FUNCTION AND CONSTRAINT VALUES -C ------------------------------------------------------------------ - NCAL(1)=NCAL(1)+1 - JGOTO=2 - RETURN -310 CONTINUE - F3=OBJ - IF (IPRINT.GE.5) WRITE (IOUT,760) F3 - IF (IPRINT.LT.5.OR.NCON.EQ.0) GO TO 320 - WRITE (IOUT,770) - WRITE (IOUT,750) (G(I),I=1,NCON) -320 CONTINUE -C ------------------------------------------------------------------ -C CALCULATE MAXIMUM CONSTRAINT VIOLATION AND PICK BEST DESIGN -C ------------------------------------------------------------------ - CV3=0. - IGOOD3=0 - NVC1=0 - IF (NCON.EQ.0) GO TO 340 - DO 330 I=1,NCON - CC=CTAM - IF (ISC(I).GT.0) CC=CTBM - C1=G(I)-CC - IF (C1.GT.CV3) CV3=C1 - IF (C1.GT.0.) NVC1=NVC1+1 -330 CONTINUE - IF (CV3.GT.0.) IGOOD3=1 -340 CONTINUE -C DETERMINE BEST DESIGN. - IF (IBEST.EQ.2) GO TO 360 -C CHOOSE BETWEEN F1 AND F3. - IF (IGOOD1.EQ.0.AND.IGOOD3.EQ.0) GO TO 350 - IF (CV1.GE.CV3) IBEST=3 - GO TO 380 -350 IF (F3.LE.F1) IBEST=3 - GO TO 380 -360 CONTINUE -C CHOOSE BETWEEN F2 AND F3. - IF (IGOOD2.EQ.0.AND.IGOOD3.EQ.0) GO TO 370 - IF (CV2.GE.CV3) IBEST=3 - GO TO 380 -370 IF (F3.LE.F2) IBEST=3 -380 CONTINUE - ALP=A3 - OBJ=F3 -C IF F3 VIOLATES FEWER CONSTRAINTS THAN F1 RETURN. - IF (NVC1.LT.NVC) GO TO 710 -C IF OBJECTIVE AND ALL CONSTRAINTS ARE LINEAR, RETURN. - IF (LINOBJ.NE.0.AND.NLNC.EQ.NCON) GO TO 710 -C IF A3 = ALPLN AND F3 IS BOTH GOOD AND BEST RETURN. - ALPB=1.-ALPLN/A3 - IF ((ABS(ALPB).LT.1.0E-20.AND.IBEST.EQ.3).AND.(IGOOD3.EQ.0)) GO TO - 1 710 -C IF A3 = ALPSID AND F3 IS BEST, GO INVOKE SIDE CONSTRAINT -C MODIFICATION. - ALPA=1.-ALPSID/A3 - IF (ABS(ALPA).LT.1.0E-20.AND.IBEST.EQ.3) GO TO 20 -C ------------------------------------------------------------------ -C ********** 3 - POINT INTERPOLATION ********* -C ------------------------------------------------------------------ - ALPNC=ALPSID - ALPCA=ALPSID - ALPFES=-1. - ALPMIN=-1. -C ------------------------------------------------------------------ -C IF A3 IS GREATER THAN A2 AND CV3 IS GREATER THAN CV2, SET -C MOVE LIMITS TO A3. PROGRAM MOD-FEB, 1981, GV. -C ------------------------------------------------------------------ - IF(A3.LE.A2.OR.CV3.LE.CV2) GO TO 285 - ALPLN=A3 - ALPNC=A3 - ALPCA=A3 -285 CONTINUE - IF (NCON.EQ.0) GO TO 440 - III=0 -390 III=III+1 - C1=G1(III) - C2=G2(III) - C3=G(III) - IF (ISC(III).EQ.0) GO TO 400 -C ------------------------------------------------------------------ -C LINEAR CONSTRAINT. FIND ALPFES ONLY. ALPLN SAME AS BEFORE. -C ------------------------------------------------------------------ - IF (C1.LE.CTBM) GO TO 430 - II=1 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A3,C3,ZRO,ZRO) - IF (ALP.GT.ALPFES) ALPFES=ALP - GO TO 430 -400 CONTINUE -C ------------------------------------------------------------------ -C NON-LINEAR CONSTRAINT -C ------------------------------------------------------------------ - II=2 - CALL CNMN07 (II,ALP,ZRO,ZRO,C1,A2,C2,A3,C3) - IF (ALP.LE.ZRO) GO TO 430 - IF (C1.GE.CT.AND.C1.LE.0.) GO TO 410 - IF (C1.GT.CTAM.OR.C1.LT.0.) GO TO 420 -C ALP IS MINIMUM MOVE. UPDATE FOR NEXT CONSTRAINT ENCOUNTER. -410 ALPA=ALP - CALL CNMN07 (II,ALP,ALPA,ZRO,C1,A2,C2,A3,C3) - IF (ALP.LT.ALPCA.AND.ALP.GE.ALPA) ALPCA=ALP - GO TO 430 -420 CONTINUE - IF (ALP.GT.ALPFES.AND.C1.GT.CTAM) ALPFES=ALP - IF (ALP.LT.ALPNC.AND.C1.LT.0.) ALPNC=ALP -430 CONTINUE - IF (III.LT.NCON) GO TO 390 -440 CONTINUE - IF (LINOBJ.GT.0.OR.SLOPE.GT.0.) GO TO 450 -C ------------------------------------------------------------------ -C CALCULATE ALPHA TO MINIMIZE FUNCTION -C ------------------------------------------------------------------ - II=3 - IF (A2.GT.A3.AND.(IGOOD2.EQ.0.AND.IBEST.EQ.2)) II=2 - CALL CNMN04 (II,ALPMIN,ZRO,ZRO,F1,SLOPE,A2,F2,A3,F3,ZRO,ZRO) -450 CONTINUE -C ------------------------------------------------------------------ -C PROPOSED MOVE -C ------------------------------------------------------------------ -C MOVE AT LEAST ENOUGH TO OVERCOME CONSTRAINT VIOLATIONS. - A4=ALPFES -C MOVE TO MINIMIZE FUNCTION. - IF (ALPMIN.GT.A4) A4=ALPMIN -C IF A4.LE.0, SET A4 = ALPSID. - IF (A4.LE.0.) A4=ALPSID -C LIMIT MOVE TO NEW CONSTRAINT ENCOUNTER. - IF (A4.GT.ALPLN) A4=ALPLN - IF (A4.GT.ALPNC) A4=ALPNC -C LIMIT MOVE TO RE-ENCOUNTER CURRENTLY ACTIVE CONSTRAINT. - IF (A4.GT.ALPCA) A4=ALPCA -C LIMIT A4 TO 5.*A3. - IF (A4.GT.(5.*A3)) A4=5.*A3 -C UPDATE DESIGN. - IF (IBEST.NE.3.OR.NCON.EQ.0) GO TO 470 -C STORE CONSTRAINT VALUES IN G2. F3 IS BEST. F2 IS NOT. - DO 460 I=1,NCON - G2(I)=G(I) -460 CONTINUE -470 CONTINUE -C IF A4=A3 AND IGOOD1=0 AND IGOOD3=1, SET A4=.9*A3. - ALP=A4-A3 - IF ((IGOOD1.EQ.0.AND.IGOOD3.EQ.1).AND.ABS(ALP).LT.1.0E-20) A4=.9*A - 13 -C ------------------------------------------------------------------ -C MOVE A DISTANCE A4*S -C ------------------------------------------------------------------ - ALP=A4-A3 - ALPTOT=ALPTOT+ALP - DO 480 I=1,NDV - X(I)=X(I)+ALP*S(I) -480 CONTINUE - IF (IPRINT.LT.5) GO TO 510 - WRITE (IOUT,720) - WRITE (IOUT,740) A4 - IF (NSCAL.EQ.0) GO TO 500 - DO 490 I=1,NDV -490 G(I)=SCAL(I)*X(I) - WRITE (IOUT,750) (G(I),I=1,NDV) - GO TO 510 -500 WRITE (IOUT,750) (X(I),I=1,NDV) -510 CONTINUE -C ------------------------------------------------------------------ -C UPDATE FUNCTION AND CONSTRAINT VALUES -C ------------------------------------------------------------------ - NCAL(1)=NCAL(1)+1 - JGOTO=3 - RETURN -520 CONTINUE - F4=OBJ - IF (IPRINT.GE.5) WRITE (IOUT,760) F4 - IF (IPRINT.LT.5.OR.NCON.EQ.0) GO TO 530 - WRITE (IOUT,770) - WRITE (IOUT,750) (G(I),I=1,NCON) -530 CONTINUE -C DETERMINE ACCAPTABILITY OF F4. - IGOOD4=0 - CV4=0. - IF (NCON.EQ.0) GO TO 550 - DO 540 I=1,NCON - CC=CTAM - IF (ISC(I).GT.0) CC=CTBM - C1=G(I)-CC - IF (C1.GT.CV4) CV4=C1 -540 CONTINUE - IF (CV4.GT.0.) IGOOD4=1 -550 CONTINUE - ALP=A4 - OBJ=F4 -C ------------------------------------------------------------------ -C DETERMINE BEST DESIGN -C ------------------------------------------------------------------ - GO TO (560,610,660),IBEST -560 CONTINUE -C CHOOSE BETWEEN F1 AND F4. - IF (IGOOD1.EQ.0.AND.IGOOD4.EQ.0) GO TO 570 - IF (CV1.GT.CV4) GO TO 710 - GO TO 580 -570 CONTINUE - IF (F4.LE.F1) GO TO 710 -580 CONTINUE -C F1 IS BEST. - ALPTOT=ALPTOT-A4 - OBJ=F1 - DO 590 I=1,NDV - X(I)=X(I)-A4*S(I) -590 CONTINUE - IF (NCON.EQ.0) GO TO 710 - DO 600 I=1,NCON - G(I)=G1(I) -600 CONTINUE - GO TO 710 -610 CONTINUE -C CHOOSE BETWEEN F2 AND F4. - IF (IGOOD2.EQ.0.AND.IGOOD4.EQ.0) GO TO 620 - IF (CV2.GT.CV4) GO TO 710 - GO TO 630 -620 CONTINUE - IF (F4.LE.F2) GO TO 710 -630 CONTINUE -C F2 IS BEST. - OBJ=F2 - A2=A4-A2 - ALPTOT=ALPTOT-A2 - DO 640 I=1,NDV - X(I)=X(I)-A2*S(I) -640 CONTINUE - IF (NCON.EQ.0) GO TO 710 - DO 650 I=1,NCON - G(I)=G2(I) -650 CONTINUE - GO TO 710 -660 CONTINUE -C CHOOSE BETWEEN F3 AND F4. - IF (IGOOD3.EQ.0.AND.IGOOD4.EQ.0) GO TO 670 - IF (CV3.GT.CV4) GO TO 710 - GO TO 680 -670 CONTINUE - IF (F4.LE.F3) GO TO 710 -680 CONTINUE -C F3 IS BEST. - OBJ=F3 - A3=A4-A3 - ALPTOT=ALPTOT-A3 - DO 690 I=1,NDV - X(I)=X(I)-A3*S(I) -690 CONTINUE - IF (NCON.EQ.0) GO TO 710 - DO 700 I=1,NCON - G(I)=G2(I) -700 CONTINUE -710 CONTINUE - ALP=ALPTOT - IF (IPRINT.GE.5) WRITE (IOUT,790) - JGOTO=0 - RETURN -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C -C -720 FORMAT (/5X,25HTHREE-POINT INTERPOLATION) -730 FORMAT (/////58H* * * CONSTRAINED ONE-DIMENSIONAL SEARCH INFORMATI - 1ON * * *) -740 FORMAT (//5X,15HPROPOSED DESIGN/5X,7HALPHA =,E12.5/5X,8HX-VECTOR) -750 FORMAT (1X,8E12.4) -760 FORMAT (/5X,5HOBJ =,E13.5) -770 FORMAT (/5X,17HCONSTRAINT VALUES) -780 FORMAT (/5X,23HTWO-POINT INTERPOLATION) -790 FORMAT (/5X,35H* * * END OF ONE-DIMENSIONAL SEARCH) - END diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn07.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn07.f deleted file mode 100644 index 65fdace0d..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn07.f +++ /dev/null @@ -1,67 +0,0 @@ - SUBROUTINE CNMN07 (II,XBAR,EPS,X1,Y1,X2,Y2,X3,Y3) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) -C ROUTINE TO FIND FIRST XBAR.GE.EPS CORRESPONDING TO A REAL ZERO -C OF A ONE-DIMENSIONAL FUNCTION BY POLYNOMIEL INTERPOLATION. -C BY G. N. VANDERPLAATS APRIL, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C II = CALCULATION CONTROL. -C 1: 2-POINT LINEAR INTERPOLATION, GIVEN X1, Y1, X2 AND Y2. -C 2: 3-POINT QUADRATIC INTERPOLATION, GIVEN X1, Y1, X2, Y2, -C X3 AND Y3. -C EPS MAY BE NEGATIVE. -C IF REQUIRED ZERO ON Y DOES NOT EXITS, OR THE FUNCTION IS -C ILL-CONDITIONED, XBAR = EPS-1.0 WILL BE RETURNED AS AN ERROR -C INDICATOR. -C IF DESIRED INTERPOLATION IS ILL-CONDITIONED, A LOWER ORDER -C INTERPOLATION, CONSISTANT WITH INPUT DATA, WILL BE ATTEMPTED AND -C II WILL BE CHANGED ACCORDINGLY. - XBAR1=EPS-1. - XBAR=XBAR1 - JJ=0 - X21=X2-X1 - IF (ABS(X21).LT.1.0E-20) RETURN - IF (II.EQ.2) GO TO 30 -C -10 CONTINUE -C ------------------------------------------------------------------ -C II=1: 2-POINT LINEAR INTERPOLATION -C ------------------------------------------------------------------ - II=1 - YY=Y1*Y2 - IF (JJ.EQ.0.OR.YY.LT.0.) GO TO 20 -C INTERPOLATE BETWEEN X2 AND X3. - DY=Y3-Y2 - IF (ABS(DY).LT.1.0E-20) GO TO 20 - XBAR=X2+Y2*(X2-X3)/DY - IF (XBAR.LT.EPS) XBAR=XBAR1 - RETURN -20 DY=Y2-Y1 -C INTERPOLATE BETWEEN X1 AND X2. - IF (ABS(DY).LT.1.0E-20) RETURN - XBAR=X1+Y1*(X1-X2)/DY - IF (XBAR.LT.EPS) XBAR=XBAR1 - RETURN -30 CONTINUE -C ------------------------------------------------------------------ -C II=2: 3-POINT QUADRATIC INTERPOLATION -C ------------------------------------------------------------------ - JJ=1 - X31=X3-X1 - X32=X3-X2 - QQ=X21*X31*X32 - IF (ABS(QQ).LT.1.0E-20) RETURN - AA=(Y1*X32-Y2*X31+Y3*X21)/QQ - IF (ABS(AA).LT.1.0E-20) GO TO 10 - BB=(Y2-Y1)/X21-AA*(X1+X2) - CC=Y1-X1*(AA*X1+BB) - BAC=BB*BB-4.*AA*CC - IF (BAC.LT.0.) GO TO 10 - BAC=SQRT(BAC) - AA=.5/AA - XBAR=AA*(BAC-BB) - XB2=-AA*(BAC+BB) - IF (XBAR.LT.EPS) XBAR=XB2 - IF (XB2.LT.XBAR.AND.XB2.GT.EPS) XBAR=XB2 - IF (XBAR.LT.EPS) XBAR=XBAR1 - RETURN - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn08.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn08.f deleted file mode 100644 index cf4be6c12..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn08.f +++ /dev/null @@ -1,112 +0,0 @@ - SUBROUTINE CNMN08 (NDB,NER,C,MS1,B,N3,N4,N5) - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - DIMENSION C(N4), B(N3,N3), MS1(N5) -C ROUTINE TO SOLVE SPECIAL LINEAR PROBLEM FOR IMPOSING S-TRANSPOSE -C TIMES S.LE.1 BOUNDS IN THE MODIFIED METHOD OF FEASIBLE DIRECTIONS. -C BY G. N. VANDERPLAATS APRIL, 1972. -C NASA-AMES RESEARCH CENTER, MOFFETT FIELD, CALIF. -C REF. 'STRUCTURAL OPTIMIZATION BY METHODS OF FEASIBLE DIRECTIONS', -C G. N. VANDERPLAATS AND F. MOSES, JOURNAL OF COMPUTERS -C AND STRUCTURES, VOL 3, PP 739-755, 1973. -C FORM OF L. P. IS BX=C WHERE 1ST NDB COMPONENTS OF X CONTAIN VECTOR -C U AND LAST NDB COMPONENTS CONTAIN VECTOR V. CONSTRAINTS ARE -C U.GE.0, V.GE.0, AND U-TRANSPOSE TIMES V = 0. -C NER = ERROR FLAG. IF NER.NE.0 ON RETURN, PROCESS HAS NOT -C CONVERGED IN 5*NDB ITERATIONS. -C VECTOR MS1 IDENTIFIES THE SET OF BASIC VARIABLES. -C ------------------------------------------------------------------ -C CHOOSE INITIAL BASIC VARIABLES AS V, AND INITIALIZE VECTOR MS1 -C ------------------------------------------------------------------ - NER=1 - M2=2*NDB -C CALCULATE CBMIN AND EPS AND INITIALIZE MS1. - EPS=-1.0E+10 - CBMIN=0. - DO 10 I=1,NDB - BI=B(I,I) - CBMAX=0. - IF (BI.LT.-1.0E-6) CBMAX=C(I)/BI - IF (BI.GT.EPS) EPS=BI - IF (CBMAX.GT.CBMIN) CBMIN=CBMAX -10 MS1(I)=0 - EPS=.0001*EPS -C IF (EPS.LT.-1.0E-10) EPS=-1.0E-10 -C -C E-10 CHANGED TO E-03 ON 1/12/81 -C - IF (EPS.LT.-1.0E-03) EPS=-1.0E-03 - IF (EPS.GT.-.0001) EPS=-.0001 - CBMIN=CBMIN*1.0E-6 -C IF (CBMIN.LT.1.0E-10) CBMIN=1.0E-10 -C -C E-10 CHANGED TO E-05 ON 1/12/81 -C - IF (CBMIN.LT.1.0E-05) CBMIN=1.0E-05 - ITER1=0 - NMAX=5*NDB -C ------------------------------------------------------------------ -C ********** BEGIN NEW ITERATION ********** -C ------------------------------------------------------------------ -20 ITER1=ITER1+1 - IF (ITER1.GT.NMAX) RETURN -C FIND MAX. C(I)/B(I,I) FOR I=1,NDB. - CBMAX=.9*CBMIN - ICHK=0 - DO 30 I=1,NDB - C1=C(I) - BI=B(I,I) -C IF (BI.GT.EPS.OR.C1.GT.0.) GO TO 30 - IF (BI.GT.EPS.OR.C1.GT.-1.0E-05) GO TO 30 -C -C 0. CHANGED TO -1.0E-05 ON 1/12/81 -C - CB=C1/BI - IF (CB.LE.CBMAX) GO TO 30 - ICHK=I - CBMAX=CB -30 CONTINUE - IF (CBMAX.LT.CBMIN) GO TO 70 - IF (ICHK.EQ.0) GO TO 70 -C UPDATE VECTOR MS1. - JJ=ICHK - IF (MS1(JJ).EQ.0) JJ=ICHK+NDB - KK=JJ+NDB - IF (KK.GT.M2) KK=JJ-NDB - MS1(KK)=ICHK - MS1(JJ)=0 -C ------------------------------------------------------------------ -C PIVOT OF B(ICHK,ICHK) -C ------------------------------------------------------------------ - BB=1./B(ICHK,ICHK) - DO 40 J=1,NDB -40 B(ICHK,J)=BB*B(ICHK,J) - C(ICHK)=CBMAX - B(ICHK,ICHK)=BB -C ELIMINATE COEFICIENTS ON VARIABLE ENTERING BASIS AND STORE -C COEFICIENTS ON VARIABLE LEAVING BASIS IN THEIR PLACE. - DO 60 I=1,NDB - IF (I.EQ.ICHK) GO TO 60 - BB1=B(I,ICHK) - B(I,ICHK)=0. - DO 50 J=1,NDB -50 B(I,J)=B(I,J)-BB1*B(ICHK,J) - C(I)=C(I)-BB1*CBMAX -60 CONTINUE - GO TO 20 -70 CONTINUE - NER=0 -C ------------------------------------------------------------------ -C STORE ONLY COMPONENTS OF U-VECTOR IN 'C'. USE B(I,1) FOR -C TEMPORARY STORAGE -C ------------------------------------------------------------------ - DO 80 I=1,NDB - B(I,1)=C(I) -80 CONTINUE - DO 90 I=1,NDB - C(I)=0. - J=MS1(I) - IF (J.GT.0) C(I)=B(J,1) - IF (C(I).LT.0.) C(I)=0. -90 CONTINUE - RETURN - END \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn09.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn09.f deleted file mode 100644 index 6e3b5e6bb..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/cnmn09.f +++ /dev/null @@ -1,39 +0,0 @@ - SUBROUTINE CNMN09(CNMNFUN,CNMNGRD,X,G,IC,DF,A, - . N1,N2,N3,N4,N5) - - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT, - . CTMIN,CTL,CTLMIN,ALPHAX,ABOBJ1,THETA,OBJ, - . NDV,NCON,NSIDE,IPRINT,NFDG,NSCAL,LINOBJ, - . ITMAX,ITRM,ICNDIR,IGOTO,NAC,INFO,INFOG,ITER - - COMMON /VARABLE/ AOBJ - COMMON /FEVALS/ NFUN,NGRD - - DIMENSION X(N1),G(N2),IC(N2),DF(N1),A(N1,N2) - - EXTERNAL CNMNFUN,CNMNGRD - -C -C - IF(INFO.GE.2) GO TO 10 -C -C OBJECTIVE FUNCTION & CONSTRAINTS -C - CALL CNMNFUN(N1,N2,X,AOBJ,G) - NFUN=NFUN+1 - GO TO 20 - - 10 CONTINUE -C -C -C GRADIENT INFORMATION -C - CALL CNMNGRD(N1,N2,X,AOBJ,G,CT,DF,A,IC,NAC) - NGRD=NGRD+1 - - 20 CONTINUE - - RETURN - END diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/conmin.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/conmin.f deleted file mode 100644 index 36d84034c..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/conmin.f +++ /dev/null @@ -1,138 +0,0 @@ - SUBROUTINE CONMIN(NDV_,NCON_,X_,VLB_,VUB_,OBJ_,G_, - 1 N1,N2,N3,N4,N5,IPRINT_,IOUT_,IFILE,ITMAX_,DELFUN_, - 2 DABFUN_,ITRM_,NFEASCT_,NFDG_,NFUN_,NGRD_,CNMNFUN,CNMNGRD) - - IMPLICIT DOUBLE PRECISION(A-H,O-Z) - - EXTERNAL CNMNFUN,CNMNGRD - - CHARACTER*(*) IFILE - - DIMENSION X_(NDV_),VLB_(NDV_),VUB_(NDV_),G_(NCON_) - - DIMENSION X(N1),VLB(N1),VUB(N1),SCAL(N1),S(N1),DF(N1) - DIMENSION G(N2),G1(N2),G2(N2),ISC(N2) - DIMENSION IC(N3),B(N3,N3) - DIMENSION C(N4) - DIMENSION MS1(N5) - DIMENSION A(N1,N3) - - COMMON /CNMN1/ DELFUN,DABFUN,FDCH,FDCHM,CT,CTMIN,CTL,CTLMIN, - . ALPHAX,ABOBJ1,THETA,OBJ,NDV,NCON,NSIDE,IPRINT, - . NFDG,NSCAL,LINOBJ,ITMAX,ITRM,ICNDIR,IGOTO,NAC, - . INFO,INFOG,ITER,NFEASCT - - COMMON /VARABLE/ AOBJ - COMMON /OUTPUT/ IOUT - COMMON /FEVALS/ NFUN,NGRD -C -C INITIALIZE -C - INFOG=0 - INFO=0 - NDV=NDV_ - NCON=NCON_ - DO 5 I=1,NDV - X(I)=X_(I) - VLB(I)=VLB_(I) - VUB(I)=VUB_(I) - 5 CONTINUE - IPRINT=IPRINT_ - ITMAX=ITMAX_ - DO 6 J=1,NCON - ISC(J)=0 - 6 CONTINUE - NFDG=NFDG_ - NSIDE=1 - ICNDIR=0 - NSCAL=0 - NFEASCT=NFEASCT_ - FDCH=0.0 - FDCHM=0.0 - CT=0.0 - CTMIN=0.0 - CTL=0.0 - CTLMIN=0.0 - THETA=0.0 - PHI=0.0 - DELFUN=DELFUN_ - DABFUN=DABFUN_ - LINOBJ=0.0 - ITRM=ITRM_ - ALPHAX=0.0 - ABOBJ1=0.0 -C - NFUN=0 - NGRD=0 -C -C OPEN WRITE FILE -C - IOUT=IOUT_ - IF (IPRINT.EQ.0) GO TO 10 - OPEN(UNIT=IOUT,FILE=IFILE(1:LEN_TRIM(IFILE)), - . STATUS='UNKNOWN') - 10 CONTINUE -C -C MAXIMUM NUMBER OF ITERATIONS -C - NLIM=ITMAX*(NDV+5) -C -C NON-ITERATIVE PART OF ANALYSIS -C - IGOTO = 0 -C -C ITERATIVE PART OF ANALYSIS -C - DO 20 I = 1,NLIM -C - LOOPCNT=I -C -C CALL THE OPTIMIZATION ROUTINE CONMIN -C - CALL CNMN00(X,VLB,VUB,G,SCAL,DF,A,S,G1,G2,B, - . C,ISC,IC,MS1,N1,N2,N3,N4,N5) -C -C CHECK TERMINATION CRITERIA -C - IF(IGOTO.EQ.0) LOOPCNT=-999 -C -C ANALYSIS MODULE -C - CALL CNMN09(CNMNFUN,CNMNGRD,X,G,IC,DF,A, - . N1,N2,N3,N4,N5) - OBJ=AOBJ -C - IF (IGOTO.EQ.0) GO TO 30 - 20 CONTINUE -C - 30 CONTINUE -C -C PRINT FINAL RESULTS -C - IF (IPRINT.EQ.0) GO TO 32 - WRITE(6,1650) NFUN-1 - WRITE(6,1750) NGRD -C - 32 CONTINUE -C -C OUTPUT HANDLING -C - DO 35 I=1,NDV - X_(I)=X(I) - 35 CONTINUE - OBJ_=OBJ - DO 36 J=1,NCON - G_(J)=G(J) - 36 CONTINUE - NFUN_=NFUN-1 - NGRD_=NGRD - - RETURN - -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -1650 FORMAT(//8X,'NUMBER OF FUNC-CALLS: NFUN =',I5) -1750 FORMAT(8X,'NUMBER OF GRAD-CALLS: NGRD =',I5) - - END diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/README b/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/README deleted file mode 100644 index 54e48d046..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the f2py signature file. -Do not edit these file unless you really know what you are doing. diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conmin-f2pywrappers.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conmin-f2pywrappers.f deleted file mode 100644 index 89d15405d..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conmin-f2pywrappers.f +++ /dev/null @@ -1,56 +0,0 @@ -C -*- fortran -*- -C This file is autogenerated with f2py (version:2) -C It contains Fortran 77 wrappers to fortran functions. - - subroutine f2pyinitoutput(setupfunc) - external setupfunc - integer iout - common /output/ iout - call setupfunc(iout) - end - - subroutine f2pyinitvarable(setupfunc) - external setupfunc - double precision aobj - common /varable/ aobj - call setupfunc(aobj) - end - - subroutine f2pyinitcnmn1(setupfunc) - external setupfunc - double precision delfun - double precision dabfun - double precision fdch - double precision fdchm - double precision ct - double precision ctmin - double precision ctl - double precision ctlmin - double precision alphax - double precision abobj1 - double precision theta - double precision obj - integer ndv - integer ncon - integer nside - integer iprint - integer nfdg - integer nscal - integer linobj - integer itmax - integer itrm - integer icndir - integer igoto - integer nac - integer info - integer infog - integer iter - common /cnmn1/ delfun,dabfun,fdch,fdchm,ct,ctmin,ctl,ctlmin, - &alphax,abobj1,theta,obj,ndv,ncon,nside,iprint,nfdg,nscal,linobj,it - &max,itrm,icndir,igoto,nac,info,infog,iter - call setupfunc(delfun,dabfun,fdch,fdchm,ct,ctmin,ctl,ctlmin, - &alphax,abobj1,theta,obj,ndv,ncon,nside,iprint,nfdg,nscal,linobj,it - &max,itrm,icndir,igoto,nac,info,infog,iter) - end - - diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conmin.pyf b/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conmin.pyf deleted file mode 100644 index e6a4488b5..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conmin.pyf +++ /dev/null @@ -1,103 +0,0 @@ -! -*- f90 -*- -! Note: the context of this file is case sensitive. - -python module conmin__user__routines - interface conmin_user_interface - subroutine cnmnfun(n1,n2,x,aobj,g) - integer intent(in) :: n1 - integer intent(in) :: n2 - double precision dimension(n1),intent(in),depend(n1) :: x - double precision intent(in,out) :: aobj - double precision dimension(n2),intent(in,out),depend(n2) :: g - end subroutine cnmnfun - subroutine cnmngrd(n1,n2,x,aobj,g,ct,df,a,ic,nac) - integer intent(in) :: n1 - integer intent(in) :: n2 - double precision dimension(n1),intent(in),depend(n1) :: x - double precision intent(in) :: aobj - double precision dimension(n2),intent(in),depend(n2) :: g - double precision intent(in) :: ct - double precision dimension(n1),intent(in,out),depend(n1) :: df - double precision dimension(n1,n2),intent(in,out),depend(n1,n2) :: a - integer dimension(n2),intent(in,out),depend(n2) :: ic - integer intent(in,out) :: nac - end subroutine cnmngrd - end interface conmin_user_interface -end python module conmin__user__routines -python module conmin ! in - interface ! in :conmin - subroutine conmin(ndv_,ncon_,x_,vlb_,vub_,obj_,g_,n1,n2,n3,n4,n5,iprint_,iout_,ifile,itmax_,delfun_,dabfun_,itrm_,nfeasct_,nfdg_,nfun_,ngrd_,cnmnfun,cnmngrd) ! in :conmin:source/conmin.f - use conmin__user__routines - integer intent(in) :: ndv - integer intent(in) :: ncon - double precision dimension(ndv_),intent(inout),depend(ndv_) :: x_ - double precision dimension(ndv_),depend(ndv_) :: vlb_ - double precision dimension(ndv_),depend(ndv_) :: vub_ - double precision intent(inout) :: obj_ - double precision dimension(ncon_),intent(inout),depend(ncon_) :: g_ - integer intent(in) :: n1 - integer intent(in) :: n2 - integer intent(in) :: n3 - integer intent(in) :: n4 - integer intent(in) :: n5 - integer intent(in) :: iprint_ - integer intent(in) :: iout_ - character*(*) intent(in) :: ifile - integer intent(in) :: itmax_ - double precision intent(in) :: delfun_ - double precision intent(in) :: dabfun_ - integer intent(in) :: itrm_ - integer intent(in) :: nfeasct_ - integer intent(in) :: nfdg_ - integer intent(inout) :: nfun_ - integer intent(inout) :: ngrd_ - external cnmnfun - external cnmngrd - double precision :: aobj - double precision :: delfun - double precision :: dabfun - double precision :: fdch - double precision :: fdchm - double precision :: ct - double precision :: ctmin - double precision :: ctl - double precision :: ctlmin - double precision :: alphax - double precision :: abobj1 - double precision :: theta - double precision :: obj - integer :: ndv - integer :: ncon - integer :: nside - integer :: iprint - integer :: nfdg - integer :: nscal - integer :: linobj - integer :: itmax - integer :: itrm - integer :: icndir - integer :: igoto - integer :: nac - integer :: info - integer :: infog - integer :: iter - common /varable/ aobj - common /output/ iout - common /cnmn1/ delfun,dabfun,fdch,fdchm,ct,ctmin,ctl,ctlmin,alphax,abobj1,theta,obj,ndv,ncon,nside,iprint,nfdg,nscal,linobj,itmax,itrm,icndir,igoto,nac,info,infog,iter - end subroutine conmin - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) ! in :conmin:source/openunit.f - integer intent(in) :: unitnum - character*(*) intent(in) :: filename - character*(*) intent(in) :: filestatus - character*(*) intent(in) :: fileaction - integer intent(out) :: ierror - end subroutine openunit - subroutine pyflush(unitnum) - integer unitnum - return - end subroutine pyflush - subroutine closeunit(unitnum) ! in :conmin:source/closeunit.f - integer intent(in) :: unitnum - end subroutine closeunit - end interface -end python module conmin diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conminmodule.c b/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conminmodule.c deleted file mode 100644 index 8b8e11f66..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/f2py/conminmodule.c +++ /dev/null @@ -1,1675 +0,0 @@ -/* File: conminmodule.c - * This file is auto-generated with f2py (version:2). - * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, - * written by Pearu Peterson . - * See http://cens.ioc.ee/projects/f2py2e/ - * Generation date: Mon Sep 7 14:26:48 2015 - * $Revision:$ - * $Date:$ - * Do not edit this file directly unless you know what you are doing!!! - */ -#ifdef __cplusplus -extern "C" { -#endif - -/*********************** See f2py2e/cfuncs.py: includes ***********************/ -#include "Python.h" -#include -#include "fortranobject.h" -#include -#include - -/**************** See f2py2e/rules.py: mod_rules['modulebody'] ****************/ -static PyObject *conmin_error; -static PyObject *conmin_module; - -/*********************** See f2py2e/cfuncs.py: typedefs ***********************/ -typedef char * string; -typedef signed char signed_char; - -/****************** See f2py2e/cfuncs.py: typedefs_generated ******************/ -typedef void(*cb_cnmngrd_in_conmin__user__routines_typedef)(int *,int *,double *,double *,double *,double *,double *,double *,int *,int *); -typedef void(*cb_cnmnfun_in_conmin__user__routines_typedef)(int *,int *,double *,double *,double *); - -/********************** See f2py2e/cfuncs.py: cppmacros **********************/ -#define STRINGMALLOC(str,len)\ - if ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\ - PyErr_SetString(PyExc_MemoryError, "out of memory");\ - goto capi_fail;\ - } else {\ - (str)[len] = '\0';\ - } - -#ifndef max -#define max(a,b) ((a > b) ? (a) : (b)) -#endif -#ifndef min -#define min(a,b) ((a < b) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a > b) ? (a) : (b)) -#endif -#ifndef MIN -#define MIN(a,b) ((a < b) ? (a) : (b)) -#endif - -#define PRINTPYOBJERR(obj)\ - fprintf(stderr,"conmin.error is related to ");\ - PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\ - fprintf(stderr,"\n"); - -\ -#define FAILNULL(p) do { \ - if ((p) == NULL) { \ - PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \ - goto capi_fail; \ - } \ -} while (0) - -#define pyobj_from_int1(v) (PyInt_FromLong(v)) -#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\ - if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\ - if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\ - goto capi_fail;\ - } - -#define pyobj_from_double1(v) (PyFloat_FromDouble(v)) -#define MEMCOPY(to,from,n)\ - do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0) - -#ifdef DEBUGCFUNCS -#define CFUNCSMESS(mess) fprintf(stderr,"debug-capi:"mess); -#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \ - PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\ - fprintf(stderr,"\n"); -#else -#define CFUNCSMESS(mess) -#define CFUNCSMESSPY(mess,obj) -#endif - -#if defined(PREPEND_FORTRAN) -#if defined(NO_APPEND_FORTRAN) -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) _##F -#else -#define F_FUNC(f,F) _##f -#endif -#else -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) _##F##_ -#else -#define F_FUNC(f,F) _##f##_ -#endif -#endif -#else -#if defined(NO_APPEND_FORTRAN) -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) F -#else -#define F_FUNC(f,F) f -#endif -#else -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) F##_ -#else -#define F_FUNC(f,F) f##_ -#endif -#endif -#endif -#if defined(UNDERSCORE_G77) -#define F_FUNC_US(f,F) F_FUNC(f##_,F##_) -#else -#define F_FUNC_US(f,F) F_FUNC(f,F) -#endif - -#define rank(var) var ## _Rank -#define shape(var,dim) var ## _Dims[dim] -#define old_rank(var) (((PyArrayObject *)(capi_ ## var ## _tmp))->nd) -#define old_shape(var,dim) (((PyArrayObject *)(capi_ ## var ## _tmp))->dimensions[dim]) -#define fshape(var,dim) shape(var,rank(var)-dim-1) -#define len(var) shape(var,0) -#define flen(var) fshape(var,0) -#define old_size(var) PyArray_SIZE((PyArrayObject *)(capi_ ## var ## _tmp)) -/* #define index(i) capi_i ## i */ -#define slen(var) capi_ ## var ## _len -#define size(var, ...) f2py_size((PyArrayObject *)(capi_ ## var ## _tmp), ## __VA_ARGS__, -1) - -#define SWAP(a,b,t) {\ - t *c;\ - c = a;\ - a = b;\ - b = c;} - -#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0) - -#define STRINGCOPYN(to,from,buf_size) \ - do { \ - int _m = (buf_size); \ - char *_to = (to); \ - char *_from = (from); \ - FAILNULL(_to); FAILNULL(_from); \ - (void)strncpy(_to, _from, sizeof(char)*_m); \ - _to[_m-1] = '\0'; \ - /* Padding with spaces instead of nulls */ \ - for (_m -= 2; _m >= 0 && _to[_m] == '\0'; _m--) { \ - _to[_m] = ' '; \ - } \ - } while (0) - -/* New SciPy */ -#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(arr->data)=*v; break; -#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(arr->data)=*v; break; -#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_ ## ctype ## 1(*v),arr->data); break; - -#define TRYPYARRAYTEMPLATE(ctype,typecode) \ - PyArrayObject *arr = NULL;\ - if (!obj) return -2;\ - if (!PyArray_Check(obj)) return -1;\ - if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,"TRYPYARRAYTEMPLATE:");PRINTPYOBJERR(obj);return 0;}\ - if (arr->descr->type==typecode) {*(ctype *)(arr->data)=*v; return 1;}\ - switch (arr->descr->type_num) {\ - case NPY_DOUBLE: *(double *)(arr->data)=*v; break;\ - case NPY_INT: *(int *)(arr->data)=*v; break;\ - case NPY_LONG: *(long *)(arr->data)=*v; break;\ - case NPY_FLOAT: *(float *)(arr->data)=*v; break;\ - case NPY_CDOUBLE: *(double *)(arr->data)=*v; break;\ - case NPY_CFLOAT: *(float *)(arr->data)=*v; break;\ - case NPY_BOOL: *(npy_bool *)(arr->data)=(*v!=0); break;\ - case NPY_UBYTE: *(unsigned char *)(arr->data)=*v; break;\ - case NPY_BYTE: *(signed char *)(arr->data)=*v; break;\ - case NPY_SHORT: *(short *)(arr->data)=*v; break;\ - case NPY_USHORT: *(npy_ushort *)(arr->data)=*v; break;\ - case NPY_UINT: *(npy_uint *)(arr->data)=*v; break;\ - case NPY_ULONG: *(npy_ulong *)(arr->data)=*v; break;\ - case NPY_LONGLONG: *(npy_longlong *)(arr->data)=*v; break;\ - case NPY_ULONGLONG: *(npy_ulonglong *)(arr->data)=*v; break;\ - case NPY_LONGDOUBLE: *(npy_longdouble *)(arr->data)=*v; break;\ - case NPY_CLONGDOUBLE: *(npy_longdouble *)(arr->data)=*v; break;\ - case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_ ## ctype ## 1(*v),arr->data, arr); break;\ - default: return -2;\ - };\ - return 1 - - -/************************ See f2py2e/cfuncs.py: cfuncs ************************/ -static int f2py_size(PyArrayObject* var, ...) -{ - npy_int sz = 0; - npy_int dim; - npy_int rank; - va_list argp; - va_start(argp, var); - dim = va_arg(argp, npy_int); - if (dim==-1) - { - sz = PyArray_SIZE(var); - } - else - { - rank = PyArray_NDIM(var); - if (dim>=1 && dim<=rank) - sz = PyArray_DIM(var, dim-1); - else - fprintf(stderr, "f2py_size: 2nd argument value=%d fails to satisfy 1<=value<=%d. Result will be 0.\n", dim, rank); - } - va_end(argp); - return sz; -} - -static int double_from_pyobj(double* v,PyObject *obj,const char *errmess) { - PyObject* tmp = NULL; - if (PyFloat_Check(obj)) { -#ifdef __sgi - *v = PyFloat_AsDouble(obj); -#else - *v = PyFloat_AS_DOUBLE(obj); -#endif - return 1; - } - tmp = PyNumber_Float(obj); - if (tmp) { -#ifdef __sgi - *v = PyFloat_AsDouble(tmp); -#else - *v = PyFloat_AS_DOUBLE(tmp); -#endif - Py_DECREF(tmp); - return 1; - } - if (PyComplex_Check(obj)) - tmp = PyObject_GetAttrString(obj,"real"); - else if (PyString_Check(obj) || PyUnicode_Check(obj)) - /*pass*/; - else if (PySequence_Check(obj)) - tmp = PySequence_GetItem(obj,0); - if (tmp) { - PyErr_Clear(); - if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} - Py_DECREF(tmp); - } - { - PyObject* err = PyErr_Occurred(); - if (err==NULL) err = conmin_error; - PyErr_SetString(err,errmess); - } - return 0; -} - -static int int_from_pyobj(int* v,PyObject *obj,const char *errmess) { - PyObject* tmp = NULL; - if (PyInt_Check(obj)) { - *v = (int)PyInt_AS_LONG(obj); - return 1; - } - tmp = PyNumber_Int(obj); - if (tmp) { - *v = PyInt_AS_LONG(tmp); - Py_DECREF(tmp); - return 1; - } - if (PyComplex_Check(obj)) - tmp = PyObject_GetAttrString(obj,"real"); - else if (PyString_Check(obj) || PyUnicode_Check(obj)) - /*pass*/; - else if (PySequence_Check(obj)) - tmp = PySequence_GetItem(obj,0); - if (tmp) { - PyErr_Clear(); - if (int_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} - Py_DECREF(tmp); - } - { - PyObject* err = PyErr_Occurred(); - if (err==NULL) err = conmin_error; - PyErr_SetString(err,errmess); - } - return 0; -} - -static int try_pyarr_from_double(PyObject* obj,double* v) { - TRYPYARRAYTEMPLATE(double,'d'); -} - -static int try_pyarr_from_int(PyObject* obj,int* v) { - TRYPYARRAYTEMPLATE(int,'i'); -} - -static int create_cb_arglist(PyObject* fun,PyTupleObject* xa,const int maxnofargs,const int nofoptargs,int *nofargs,PyTupleObject **args,const char *errmess) { - PyObject *tmp = NULL; - PyObject *tmp_fun = NULL; - int tot,opt,ext,siz,i,di=0; - CFUNCSMESS("create_cb_arglist\n"); - tot=opt=ext=siz=0; - /* Get the total number of arguments */ - if (PyFunction_Check(fun)) - tmp_fun = fun; - else { - di = 1; - if (PyObject_HasAttrString(fun,"im_func")) { - tmp_fun = PyObject_GetAttrString(fun,"im_func"); - } - else if (PyObject_HasAttrString(fun,"__call__")) { - tmp = PyObject_GetAttrString(fun,"__call__"); - if (PyObject_HasAttrString(tmp,"im_func")) - tmp_fun = PyObject_GetAttrString(tmp,"im_func"); - else { - tmp_fun = fun; /* built-in function */ - tot = maxnofargs; - if (xa != NULL) - tot += PyTuple_Size((PyObject *)xa); - } - Py_XDECREF(tmp); - } - else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) { - tot = maxnofargs; - if (xa != NULL) - tot += PyTuple_Size((PyObject *)xa); - tmp_fun = fun; - } - else if (F2PyCapsule_Check(fun)) { - tot = maxnofargs; - if (xa != NULL) - ext = PyTuple_Size((PyObject *)xa); - if(ext>0) { - fprintf(stderr,"extra arguments tuple cannot be used with CObject call-back\n"); - goto capi_fail; - } - tmp_fun = fun; - } - } -if (tmp_fun==NULL) { -fprintf(stderr,"Call-back argument must be function|instance|instance.__call__|f2py-function but got %s.\n",(fun==NULL?"NULL":Py_TYPE(fun)->tp_name)); -goto capi_fail; -} -#if PY_VERSION_HEX >= 0x03000000 - if (PyObject_HasAttrString(tmp_fun,"__code__")) { - if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,"__code__"),"co_argcount")) -#else - if (PyObject_HasAttrString(tmp_fun,"func_code")) { - if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,"func_code"),"co_argcount")) -#endif - tot = PyInt_AsLong(PyObject_GetAttrString(tmp,"co_argcount")) - di; - Py_XDECREF(tmp); - } - /* Get the number of optional arguments */ -#if PY_VERSION_HEX >= 0x03000000 - if (PyObject_HasAttrString(tmp_fun,"__defaults__")) { - if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,"__defaults__"))) -#else - if (PyObject_HasAttrString(tmp_fun,"func_defaults")) { - if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,"func_defaults"))) -#endif - opt = PyTuple_Size(tmp); - Py_XDECREF(tmp); - } - /* Get the number of extra arguments */ - if (xa != NULL) - ext = PyTuple_Size((PyObject *)xa); - /* Calculate the size of call-backs argument list */ - siz = MIN(maxnofargs+ext,tot); - *nofargs = MAX(0,siz-ext); -#ifdef DEBUGCFUNCS - fprintf(stderr,"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),tot,opt,ext,siz,nofargs=%d(-%d),%d,%d,%d,%d,%d\n",maxnofargs,nofoptargs,tot,opt,ext,siz,*nofargs); -#endif - if (sizdescr->elsize)*PyArray_SIZE(arr); - STRINGMALLOC(*str,*len); - STRINGCOPYN(*str,arr->data,*len+1); - return 1; - } - if (PyString_Check(obj)) { - tmp = obj; - Py_INCREF(tmp); - } -#if PY_VERSION_HEX >= 0x03000000 - else if (PyUnicode_Check(obj)) { - tmp = PyUnicode_AsASCIIString(obj); - } - else { - PyObject *tmp2; - tmp2 = PyObject_Str(obj); - if (tmp2) { - tmp = PyUnicode_AsASCIIString(tmp2); - Py_DECREF(tmp2); - } - else { - tmp = NULL; - } - } -#else - else { - tmp = PyObject_Str(obj); - } -#endif - if (tmp == NULL) goto capi_fail; - if (*len == -1) - *len = PyString_GET_SIZE(tmp); - STRINGMALLOC(*str,*len); - STRINGCOPYN(*str,PyString_AS_STRING(tmp),*len+1); - Py_DECREF(tmp); - return 1; -capi_fail: - Py_XDECREF(tmp); - { - PyObject* err = PyErr_Occurred(); - if (err==NULL) err = conmin_error; - PyErr_SetString(err,errmess); - } - return 0; -} - - -/********************* See f2py2e/cfuncs.py: userincludes *********************/ -/*need_userincludes*/ - -/********************* See f2py2e/capi_rules.py: usercode *********************/ - - -/* See f2py2e/rules.py */ -extern void F_FUNC(conmin,CONMIN)(int*,int*,double*,double*,double*,double*,double*,int*,int*,int*,int*,int*,int*,int*,string,int*,double*,double*,int*,int*,int*,int*,int*,cb_cnmnfun_in_conmin__user__routines_typedef,cb_cnmngrd_in_conmin__user__routines_typedef,size_t); -extern void F_FUNC(openunit,OPENUNIT)(int*,string,string,string,int*,size_t,size_t,size_t); -extern void F_FUNC(pyflush,PYFLUSH)(int*); -extern void F_FUNC(closeunit,CLOSEUNIT)(int*); -/*eof externroutines*/ - -/******************** See f2py2e/capi_rules.py: usercode1 ********************/ - - -/******************* See f2py2e/cb_rules.py: buildcallback *******************/ - -/******************** cb_cnmnfun_in_conmin__user__routines ********************/ -PyObject *cb_cnmnfun_in_conmin__user__routines_capi = NULL;/*was Py_None*/ -PyTupleObject *cb_cnmnfun_in_conmin__user__routines_args_capi = NULL; -int cb_cnmnfun_in_conmin__user__routines_nofargs = 0; -jmp_buf cb_cnmnfun_in_conmin__user__routines_jmpbuf; -/*typedef void(*cb_cnmnfun_in_conmin__user__routines_typedef)(int *,int *,double *,double *,double *);*/ -static void cb_cnmnfun_in_conmin__user__routines (int *n1_cb_capi,int *n2_cb_capi,double *x,double *aobj_cb_capi,double *g) { - PyTupleObject *capi_arglist = cb_cnmnfun_in_conmin__user__routines_args_capi; - PyObject *capi_return = NULL; - PyObject *capi_tmp = NULL; - int capi_j,capi_i = 0; - int capi_longjmp_ok = 1; -/*decl*/ - int n1=(*n1_cb_capi); - int n2=(*n2_cb_capi); - double aobj=(*aobj_cb_capi); - npy_intp g_Dims[1] = {-1}; - npy_intp x_Dims[1] = {-1}; -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_clock(); -#endif - CFUNCSMESS("cb:Call-back function cb_cnmnfun_in_conmin__user__routines (maxnofargs=5(-0))\n"); - CFUNCSMESSPY("cb:cb_cnmnfun_in_conmin__user__routines_capi=",cb_cnmnfun_in_conmin__user__routines_capi); - if (cb_cnmnfun_in_conmin__user__routines_capi==NULL) { - capi_longjmp_ok = 0; - cb_cnmnfun_in_conmin__user__routines_capi = PyObject_GetAttrString(conmin_module,"cnmnfun"); - } - if (cb_cnmnfun_in_conmin__user__routines_capi==NULL) { - PyErr_SetString(conmin_error,"cb: Callback cnmnfun not defined (as an argument or module conmin attribute).\n"); - goto capi_fail; - } - if (F2PyCapsule_Check(cb_cnmnfun_in_conmin__user__routines_capi)) { - cb_cnmnfun_in_conmin__user__routines_typedef cb_cnmnfun_in_conmin__user__routines_cptr; - cb_cnmnfun_in_conmin__user__routines_cptr = F2PyCapsule_AsVoidPtr(cb_cnmnfun_in_conmin__user__routines_capi); - (*cb_cnmnfun_in_conmin__user__routines_cptr)(n1_cb_capi,n2_cb_capi,x,aobj_cb_capi,g); - return; - } - if (capi_arglist==NULL) { - capi_longjmp_ok = 0; - capi_tmp = PyObject_GetAttrString(conmin_module,"cnmnfun_extra_args"); - if (capi_tmp) { - capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp); - if (capi_arglist==NULL) { - PyErr_SetString(conmin_error,"Failed to convert conmin.cnmnfun_extra_args to tuple.\n"); - goto capi_fail; - } - } else { - PyErr_Clear(); - capi_arglist = (PyTupleObject *)Py_BuildValue("()"); - } - } - if (capi_arglist == NULL) { - PyErr_SetString(conmin_error,"Callback cnmnfun argument list is not set.\n"); - goto capi_fail; - } -/*setdims*/ - g_Dims[0]=n2; - x_Dims[0]=n1; -/*pyobjfrom*/ - if (cb_cnmnfun_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(n1))) - goto capi_fail; - if (cb_cnmnfun_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(n2))) - goto capi_fail; - if (cb_cnmnfun_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,x_Dims,NPY_DOUBLE,NULL,(char*)x,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_cnmnfun_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_double1(aobj))) - goto capi_fail; - if (cb_cnmnfun_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,g_Dims,NPY_DOUBLE,NULL,(char*)g,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - CFUNCSMESSPY("cb:capi_arglist=",capi_arglist); - CFUNCSMESS("cb:Call-back calling Python function cnmnfun.\n"); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_call_clock(); -#endif - capi_return = PyObject_CallObject(cb_cnmnfun_in_conmin__user__routines_capi,(PyObject *)capi_arglist); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_call_clock(); -#endif - CFUNCSMESSPY("cb:capi_return=",capi_return); - if (capi_return == NULL) { - fprintf(stderr,"capi_return is NULL\n"); - goto capi_fail; - } - if (capi_return == Py_None) { - Py_DECREF(capi_return); - capi_return = Py_BuildValue("()"); - } - else if (!PyTuple_Check(capi_return)) { - capi_return = Py_BuildValue("(N)",capi_return); - } - capi_j = PyTuple_Size(capi_return); - capi_i = 0; -/*frompyobj*/ - if (capi_j>capi_i) - GETSCALARFROMPYTUPLE(capi_return,capi_i++,aobj_cb_capi,double,"double_from_pyobj failed in converting argument aobj of call-back function cb_cnmnfun_in_conmin__user__routines to C double\n"); - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_DOUBLE,g_Dims,1,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(g,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - CFUNCSMESS("cb:cb_cnmnfun_in_conmin__user__routines:successful\n"); - Py_DECREF(capi_return); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_clock(); -#endif - goto capi_return_pt; -capi_fail: - fprintf(stderr,"Call-back cb_cnmnfun_in_conmin__user__routines failed.\n"); - Py_XDECREF(capi_return); - if (capi_longjmp_ok) - longjmp(cb_cnmnfun_in_conmin__user__routines_jmpbuf,-1); -capi_return_pt: - ; -return; -} -/**************** end of cb_cnmnfun_in_conmin__user__routines ****************/ - - -/******************** cb_cnmngrd_in_conmin__user__routines ********************/ -PyObject *cb_cnmngrd_in_conmin__user__routines_capi = NULL;/*was Py_None*/ -PyTupleObject *cb_cnmngrd_in_conmin__user__routines_args_capi = NULL; -int cb_cnmngrd_in_conmin__user__routines_nofargs = 0; -jmp_buf cb_cnmngrd_in_conmin__user__routines_jmpbuf; -/*typedef void(*cb_cnmngrd_in_conmin__user__routines_typedef)(int *,int *,double *,double *,double *,double *,double *,double *,int *,int *);*/ -static void cb_cnmngrd_in_conmin__user__routines (int *n1_cb_capi,int *n2_cb_capi,double *x,double *aobj_cb_capi,double *g,double *ct_cb_capi,double *df,double *a,int *ic,int *nac_cb_capi) { - PyTupleObject *capi_arglist = cb_cnmngrd_in_conmin__user__routines_args_capi; - PyObject *capi_return = NULL; - PyObject *capi_tmp = NULL; - int capi_j,capi_i = 0; - int capi_longjmp_ok = 1; -/*decl*/ - int n1=(*n1_cb_capi); - int n2=(*n2_cb_capi); - double aobj=(*aobj_cb_capi); - double ct=(*ct_cb_capi); - int nac=(*nac_cb_capi); - npy_intp a_Dims[2] = {-1, -1}; - npy_intp g_Dims[1] = {-1}; - npy_intp df_Dims[1] = {-1}; - npy_intp x_Dims[1] = {-1}; - npy_intp ic_Dims[1] = {-1}; -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_clock(); -#endif - CFUNCSMESS("cb:Call-back function cb_cnmngrd_in_conmin__user__routines (maxnofargs=10(-0))\n"); - CFUNCSMESSPY("cb:cb_cnmngrd_in_conmin__user__routines_capi=",cb_cnmngrd_in_conmin__user__routines_capi); - if (cb_cnmngrd_in_conmin__user__routines_capi==NULL) { - capi_longjmp_ok = 0; - cb_cnmngrd_in_conmin__user__routines_capi = PyObject_GetAttrString(conmin_module,"cnmngrd"); - } - if (cb_cnmngrd_in_conmin__user__routines_capi==NULL) { - PyErr_SetString(conmin_error,"cb: Callback cnmngrd not defined (as an argument or module conmin attribute).\n"); - goto capi_fail; - } - if (F2PyCapsule_Check(cb_cnmngrd_in_conmin__user__routines_capi)) { - cb_cnmngrd_in_conmin__user__routines_typedef cb_cnmngrd_in_conmin__user__routines_cptr; - cb_cnmngrd_in_conmin__user__routines_cptr = F2PyCapsule_AsVoidPtr(cb_cnmngrd_in_conmin__user__routines_capi); - (*cb_cnmngrd_in_conmin__user__routines_cptr)(n1_cb_capi,n2_cb_capi,x,aobj_cb_capi,g,ct_cb_capi,df,a,ic,nac_cb_capi); - return; - } - if (capi_arglist==NULL) { - capi_longjmp_ok = 0; - capi_tmp = PyObject_GetAttrString(conmin_module,"cnmngrd_extra_args"); - if (capi_tmp) { - capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp); - if (capi_arglist==NULL) { - PyErr_SetString(conmin_error,"Failed to convert conmin.cnmngrd_extra_args to tuple.\n"); - goto capi_fail; - } - } else { - PyErr_Clear(); - capi_arglist = (PyTupleObject *)Py_BuildValue("()"); - } - } - if (capi_arglist == NULL) { - PyErr_SetString(conmin_error,"Callback cnmngrd argument list is not set.\n"); - goto capi_fail; - } -/*setdims*/ - a_Dims[0]=n1,a_Dims[1]=n2; - g_Dims[0]=n2; - df_Dims[0]=n1; - x_Dims[0]=n1; - ic_Dims[0]=n2; -/*pyobjfrom*/ - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(n1))) - goto capi_fail; - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(n2))) - goto capi_fail; - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,x_Dims,NPY_DOUBLE,NULL,(char*)x,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_double1(aobj))) - goto capi_fail; - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,g_Dims,NPY_DOUBLE,NULL,(char*)g,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_double1(ct))) - goto capi_fail; - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,df_Dims,NPY_DOUBLE,NULL,(char*)df,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,2,a_Dims,NPY_DOUBLE,NULL,(char*)a,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,ic_Dims,NPY_INT,NULL,(char*)ic,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_cnmngrd_in_conmin__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(nac))) - goto capi_fail; - CFUNCSMESSPY("cb:capi_arglist=",capi_arglist); - CFUNCSMESS("cb:Call-back calling Python function cnmngrd.\n"); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_call_clock(); -#endif - capi_return = PyObject_CallObject(cb_cnmngrd_in_conmin__user__routines_capi,(PyObject *)capi_arglist); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_call_clock(); -#endif - CFUNCSMESSPY("cb:capi_return=",capi_return); - if (capi_return == NULL) { - fprintf(stderr,"capi_return is NULL\n"); - goto capi_fail; - } - if (capi_return == Py_None) { - Py_DECREF(capi_return); - capi_return = Py_BuildValue("()"); - } - else if (!PyTuple_Check(capi_return)) { - capi_return = Py_BuildValue("(N)",capi_return); - } - capi_j = PyTuple_Size(capi_return); - capi_i = 0; -/*frompyobj*/ - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_DOUBLE,df_Dims,1,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(df,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_DOUBLE,a_Dims,2,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(a,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_INT,ic_Dims,1,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(ic,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - if (capi_j>capi_i) - GETSCALARFROMPYTUPLE(capi_return,capi_i++,nac_cb_capi,int,"int_from_pyobj failed in converting argument nac of call-back function cb_cnmngrd_in_conmin__user__routines to C int\n"); - CFUNCSMESS("cb:cb_cnmngrd_in_conmin__user__routines:successful\n"); - Py_DECREF(capi_return); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_clock(); -#endif - goto capi_return_pt; -capi_fail: - fprintf(stderr,"Call-back cb_cnmngrd_in_conmin__user__routines failed.\n"); - Py_XDECREF(capi_return); - if (capi_longjmp_ok) - longjmp(cb_cnmngrd_in_conmin__user__routines_jmpbuf,-1); -capi_return_pt: - ; -return; -} -/**************** end of cb_cnmngrd_in_conmin__user__routines ****************/ - - -/*********************** See f2py2e/rules.py: buildapi ***********************/ - -/*********************************** conmin ***********************************/ -static char doc_f2py_rout_conmin_conmin[] = "\ -conmin(ndv_,ncon_,x_,vlb_,vub_,obj_,g_,n1,n2,n3,n4,n5,iprint_,iout_,ifile,itmax_,delfun_,dabfun_,itrm_,nfeasct_,nfdg_,nfun_,ngrd_,cnmnfun,cnmngrd,[cnmnfun_extra_args,cnmngrd_extra_args])\n\nWrapper for ``conmin``.\ -\n\nParameters\n----------\n" -"ndv_ : input int\n" -"ncon_ : input int\n" -"x_ : in/output rank-1 array('d') with bounds (ndv_)\n" -"vlb_ : input rank-1 array('d') with bounds (ndv_)\n" -"vub_ : input rank-1 array('d') with bounds (ndv_)\n" -"obj_ : in/output rank-0 array(float,'d')\n" -"g_ : in/output rank-1 array('d') with bounds (ncon_)\n" -"n1 : input int\n" -"n2 : input int\n" -"n3 : input int\n" -"n4 : input int\n" -"n5 : input int\n" -"iprint_ : input int\n" -"iout_ : input int\n" -"ifile : input string(len=-1)\n" -"itmax_ : input int\n" -"delfun_ : input float\n" -"dabfun_ : input float\n" -"itrm_ : input int\n" -"nfeasct_ : input int\n" -"nfdg_ : input int\n" -"nfun_ : in/output rank-0 array(int,'i')\n" -"ngrd_ : in/output rank-0 array(int,'i')\n" -"cnmnfun : call-back function\n" -"cnmngrd : call-back function\n" -"\nOther Parameters\n----------------\n" -"cnmnfun_extra_args : input tuple, optional\n Default: ()\n" -"cnmngrd_extra_args : input tuple, optional\n Default: ()\n" -"\nNotes\n-----\nCall-back functions::\n\n" -" def cnmnfun(n1,n2,x,aobj,g): return aobj,g\n\ - Required arguments:\n" -" n1 : input int\n" -" n2 : input int\n" -" x : input rank-1 array('d') with bounds (n1)\n" -" aobj : input float\n" -" g : input rank-1 array('d') with bounds (n2)\n" -" Return objects:\n" -" aobj : float\n" -" g : rank-1 array('d') with bounds (n2)\n" -" def cnmngrd(n1,n2,x,aobj,g,ct,df,a,ic,nac): return df,a,ic,nac\n\ - Required arguments:\n" -" n1 : input int\n" -" n2 : input int\n" -" x : input rank-1 array('d') with bounds (n1)\n" -" aobj : input float\n" -" g : input rank-1 array('d') with bounds (n2)\n" -" ct : input float\n" -" df : input rank-1 array('d') with bounds (n1)\n" -" a : input rank-2 array('d') with bounds (n1,n2)\n" -" ic : input rank-1 array('i') with bounds (n2)\n" -" nac : input int\n" -" Return objects:\n" -" df : rank-1 array('d') with bounds (n1)\n" -" a : rank-2 array('d') with bounds (n1,n2)\n" -" ic : rank-1 array('i') with bounds (n2)\n" -" nac : int"; -/* extern void F_FUNC(conmin,CONMIN)(int*,int*,double*,double*,double*,double*,double*,int*,int*,int*,int*,int*,int*,int*,string,int*,double*,double*,int*,int*,int*,int*,int*,cb_cnmnfun_in_conmin__user__routines_typedef,cb_cnmngrd_in_conmin__user__routines_typedef,size_t); */ -static PyObject *f2py_rout_conmin_conmin(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*,int*,double*,double*,double*,double*,double*,int*,int*,int*,int*,int*,int*,int*,string,int*,double*,double*,int*,int*,int*,int*,int*,cb_cnmnfun_in_conmin__user__routines_typedef,cb_cnmngrd_in_conmin__user__routines_typedef,size_t)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int ndv_ = 0; - PyObject *ndv__capi = Py_None; - int ncon_ = 0; - PyObject *ncon__capi = Py_None; - double *x_ = NULL; - npy_intp x__Dims[1] = {-1}; - const int x__Rank = 1; - PyArrayObject *capi_x__tmp = NULL; - int capi_x__intent = 0; - PyObject *x__capi = Py_None; - double *vlb_ = NULL; - npy_intp vlb__Dims[1] = {-1}; - const int vlb__Rank = 1; - PyArrayObject *capi_vlb__tmp = NULL; - int capi_vlb__intent = 0; - PyObject *vlb__capi = Py_None; - double *vub_ = NULL; - npy_intp vub__Dims[1] = {-1}; - const int vub__Rank = 1; - PyArrayObject *capi_vub__tmp = NULL; - int capi_vub__intent = 0; - PyObject *vub__capi = Py_None; - double obj_ = 0; - PyObject *obj__capi = Py_None; - double *g_ = NULL; - npy_intp g__Dims[1] = {-1}; - const int g__Rank = 1; - PyArrayObject *capi_g__tmp = NULL; - int capi_g__intent = 0; - PyObject *g__capi = Py_None; - int n1 = 0; - PyObject *n1_capi = Py_None; - int n2 = 0; - PyObject *n2_capi = Py_None; - int n3 = 0; - PyObject *n3_capi = Py_None; - int n4 = 0; - PyObject *n4_capi = Py_None; - int n5 = 0; - PyObject *n5_capi = Py_None; - int iprint_ = 0; - PyObject *iprint__capi = Py_None; - int iout_ = 0; - PyObject *iout__capi = Py_None; - string ifile = NULL; - int slen(ifile); - PyObject *ifile_capi = Py_None; - int itmax_ = 0; - PyObject *itmax__capi = Py_None; - double delfun_ = 0; - PyObject *delfun__capi = Py_None; - double dabfun_ = 0; - PyObject *dabfun__capi = Py_None; - int itrm_ = 0; - PyObject *itrm__capi = Py_None; - int nfeasct_ = 0; - PyObject *nfeasct__capi = Py_None; - int nfdg_ = 0; - PyObject *nfdg__capi = Py_None; - int nfun_ = 0; - PyObject *nfun__capi = Py_None; - int ngrd_ = 0; - PyObject *ngrd__capi = Py_None; - PyObject *cnmnfun_capi = Py_None; - PyTupleObject *cnmnfun_xa_capi = NULL; - PyTupleObject *cnmnfun_args_capi = NULL; - int cnmnfun_nofargs_capi = 0; - cb_cnmnfun_in_conmin__user__routines_typedef cnmnfun_cptr; - PyObject *cnmngrd_capi = Py_None; - PyTupleObject *cnmngrd_xa_capi = NULL; - PyTupleObject *cnmngrd_args_capi = NULL; - int cnmngrd_nofargs_capi = 0; - cb_cnmngrd_in_conmin__user__routines_typedef cnmngrd_cptr; - static char *capi_kwlist[] = {"ndv_","ncon_","x_","vlb_","vub_","obj_","g_","n1","n2","n3","n4","n5","iprint_","iout_","ifile","itmax_","delfun_","dabfun_","itrm_","nfeasct_","nfdg_","nfun_","ngrd_","cnmnfun","cnmngrd","cnmnfun_extra_args","cnmngrd_extra_args",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "OOOOOOOOOOOOOOOOOOOOOOOOO|O!O!:conmin.conmin",\ - capi_kwlist,&ndv__capi,&ncon__capi,&x__capi,&vlb__capi,&vub__capi,&obj__capi,&g__capi,&n1_capi,&n2_capi,&n3_capi,&n4_capi,&n5_capi,&iprint__capi,&iout__capi,&ifile_capi,&itmax__capi,&delfun__capi,&dabfun__capi,&itrm__capi,&nfeasct__capi,&nfdg__capi,&nfun__capi,&ngrd__capi,&cnmnfun_capi,&cnmngrd_capi,&PyTuple_Type,&cnmnfun_xa_capi,&PyTuple_Type,&cnmngrd_xa_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable delfun_ */ - f2py_success = double_from_pyobj(&delfun_,delfun__capi,"conmin.conmin() 17th argument (delfun_) can't be converted to double"); - if (f2py_success) { - /* Processing variable itrm_ */ - f2py_success = int_from_pyobj(&itrm_,itrm__capi,"conmin.conmin() 19th argument (itrm_) can't be converted to int"); - if (f2py_success) { - /* Processing variable nfeasct_ */ - f2py_success = int_from_pyobj(&nfeasct_,nfeasct__capi,"conmin.conmin() 20th argument (nfeasct_) can't be converted to int"); - if (f2py_success) { - /* Processing variable cnmnfun */ -if(F2PyCapsule_Check(cnmnfun_capi)) { - cnmnfun_cptr = F2PyCapsule_AsVoidPtr(cnmnfun_capi); -} else { - cnmnfun_cptr = cb_cnmnfun_in_conmin__user__routines; -} - - cnmnfun_nofargs_capi = cb_cnmnfun_in_conmin__user__routines_nofargs; - if (create_cb_arglist(cnmnfun_capi,cnmnfun_xa_capi,5,0,&cb_cnmnfun_in_conmin__user__routines_nofargs,&cnmnfun_args_capi,"failed in processing argument list for call-back cnmnfun.")) { - jmp_buf cnmnfun_jmpbuf; - CFUNCSMESS("Saving jmpbuf for `cnmnfun`.\n"); - SWAP(cnmnfun_capi,cb_cnmnfun_in_conmin__user__routines_capi,PyObject); - SWAP(cnmnfun_args_capi,cb_cnmnfun_in_conmin__user__routines_args_capi,PyTupleObject); - memcpy(&cnmnfun_jmpbuf,&cb_cnmnfun_in_conmin__user__routines_jmpbuf,sizeof(jmp_buf)); - /* Processing variable dabfun_ */ - f2py_success = double_from_pyobj(&dabfun_,dabfun__capi,"conmin.conmin() 18th argument (dabfun_) can't be converted to double"); - if (f2py_success) { - /* Processing variable obj_ */ - f2py_success = double_from_pyobj(&obj_,obj__capi,"conmin.conmin() 6th argument (obj_) can't be converted to double"); - if (f2py_success) { - /* Processing variable ifile */ - slen(ifile) = -1; - f2py_success = string_from_pyobj(&ifile,&slen(ifile),"",ifile_capi,"string_from_pyobj failed in converting 15th argument `ifile' of conmin.conmin to C string"); - if (f2py_success) { - /* Processing variable cnmngrd */ -if(F2PyCapsule_Check(cnmngrd_capi)) { - cnmngrd_cptr = F2PyCapsule_AsVoidPtr(cnmngrd_capi); -} else { - cnmngrd_cptr = cb_cnmngrd_in_conmin__user__routines; -} - - cnmngrd_nofargs_capi = cb_cnmngrd_in_conmin__user__routines_nofargs; - if (create_cb_arglist(cnmngrd_capi,cnmngrd_xa_capi,10,0,&cb_cnmngrd_in_conmin__user__routines_nofargs,&cnmngrd_args_capi,"failed in processing argument list for call-back cnmngrd.")) { - jmp_buf cnmngrd_jmpbuf; - CFUNCSMESS("Saving jmpbuf for `cnmngrd`.\n"); - SWAP(cnmngrd_capi,cb_cnmngrd_in_conmin__user__routines_capi,PyObject); - SWAP(cnmngrd_args_capi,cb_cnmngrd_in_conmin__user__routines_args_capi,PyTupleObject); - memcpy(&cnmngrd_jmpbuf,&cb_cnmngrd_in_conmin__user__routines_jmpbuf,sizeof(jmp_buf)); - /* Processing variable ngrd_ */ - f2py_success = int_from_pyobj(&ngrd_,ngrd__capi,"conmin.conmin() 23rd argument (ngrd_) can't be converted to int"); - if (f2py_success) { - /* Processing variable ndv_ */ - f2py_success = int_from_pyobj(&ndv_,ndv__capi,"conmin.conmin() 1st argument (ndv_) can't be converted to int"); - if (f2py_success) { - /* Processing variable itmax_ */ - f2py_success = int_from_pyobj(&itmax_,itmax__capi,"conmin.conmin() 16th argument (itmax_) can't be converted to int"); - if (f2py_success) { - /* Processing variable nfdg_ */ - f2py_success = int_from_pyobj(&nfdg_,nfdg__capi,"conmin.conmin() 21st argument (nfdg_) can't be converted to int"); - if (f2py_success) { - /* Processing variable iout_ */ - f2py_success = int_from_pyobj(&iout_,iout__capi,"conmin.conmin() 14th argument (iout_) can't be converted to int"); - if (f2py_success) { - /* Processing variable nfun_ */ - f2py_success = int_from_pyobj(&nfun_,nfun__capi,"conmin.conmin() 22nd argument (nfun_) can't be converted to int"); - if (f2py_success) { - /* Processing variable ncon_ */ - f2py_success = int_from_pyobj(&ncon_,ncon__capi,"conmin.conmin() 2nd argument (ncon_) can't be converted to int"); - if (f2py_success) { - /* Processing variable iprint_ */ - f2py_success = int_from_pyobj(&iprint_,iprint__capi,"conmin.conmin() 13rd argument (iprint_) can't be converted to int"); - if (f2py_success) { - /* Processing variable n1 */ - f2py_success = int_from_pyobj(&n1,n1_capi,"conmin.conmin() 8th argument (n1) can't be converted to int"); - if (f2py_success) { - /* Processing variable n2 */ - f2py_success = int_from_pyobj(&n2,n2_capi,"conmin.conmin() 9th argument (n2) can't be converted to int"); - if (f2py_success) { - /* Processing variable n3 */ - f2py_success = int_from_pyobj(&n3,n3_capi,"conmin.conmin() 10th argument (n3) can't be converted to int"); - if (f2py_success) { - /* Processing variable n4 */ - f2py_success = int_from_pyobj(&n4,n4_capi,"conmin.conmin() 11st argument (n4) can't be converted to int"); - if (f2py_success) { - /* Processing variable n5 */ - f2py_success = int_from_pyobj(&n5,n5_capi,"conmin.conmin() 12nd argument (n5) can't be converted to int"); - if (f2py_success) { - /* Processing variable vlb_ */ - vlb__Dims[0]=ndv_; - capi_vlb__intent |= F2PY_INTENT_IN; - capi_vlb__tmp = array_from_pyobj(NPY_DOUBLE,vlb__Dims,vlb__Rank,capi_vlb__intent,vlb__capi); - if (capi_vlb__tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(conmin_error,"failed in converting 4th argument `vlb_' of conmin.conmin to C/Fortran array" ); - } else { - vlb_ = (double *)(capi_vlb__tmp->data); - - /* Processing variable g_ */ - g__Dims[0]=ncon_; - capi_g__intent |= F2PY_INTENT_INOUT; - capi_g__tmp = array_from_pyobj(NPY_DOUBLE,g__Dims,g__Rank,capi_g__intent,g__capi); - if (capi_g__tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(conmin_error,"failed in converting 7th argument `g_' of conmin.conmin to C/Fortran array" ); - } else { - g_ = (double *)(capi_g__tmp->data); - - /* Processing variable vub_ */ - vub__Dims[0]=ndv_; - capi_vub__intent |= F2PY_INTENT_IN; - capi_vub__tmp = array_from_pyobj(NPY_DOUBLE,vub__Dims,vub__Rank,capi_vub__intent,vub__capi); - if (capi_vub__tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(conmin_error,"failed in converting 5th argument `vub_' of conmin.conmin to C/Fortran array" ); - } else { - vub_ = (double *)(capi_vub__tmp->data); - - /* Processing variable x_ */ - x__Dims[0]=ndv_; - capi_x__intent |= F2PY_INTENT_INOUT; - capi_x__tmp = array_from_pyobj(NPY_DOUBLE,x__Dims,x__Rank,capi_x__intent,x__capi); - if (capi_x__tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(conmin_error,"failed in converting 3rd argument `x_' of conmin.conmin to C/Fortran array" ); - } else { - x_ = (double *)(capi_x__tmp->data); - -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - if ((setjmp(cb_cnmnfun_in_conmin__user__routines_jmpbuf)) || (setjmp(cb_cnmngrd_in_conmin__user__routines_jmpbuf))) { - f2py_success = 0; - } else { - (*f2py_func)(&ndv_,&ncon_,x_,vlb_,vub_,&obj_,g_,&n1,&n2,&n3,&n4,&n5,&iprint_,&iout_,ifile,&itmax_,&delfun_,&dabfun_,&itrm_,&nfeasct_,&nfdg_,&nfun_,&ngrd_,cnmnfun_cptr,cnmngrd_cptr,slen(ifile)); - } -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ - f2py_success = try_pyarr_from_double(obj__capi,&obj_); - if (f2py_success) { - f2py_success = try_pyarr_from_int(nfun__capi,&nfun_); - if (f2py_success) { - f2py_success = try_pyarr_from_int(ngrd__capi,&ngrd_); - if (f2py_success) { -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue(""); -/*closepyobjfrom*/ - } /*if (f2py_success) of ngrd_ pyobjfrom*/ - } /*if (f2py_success) of nfun_ pyobjfrom*/ - } /*if (f2py_success) of obj_ pyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - if((PyObject *)capi_x__tmp!=x__capi) { - Py_XDECREF(capi_x__tmp); } - } /*if (capi_x__tmp == NULL) ... else of x_*/ - /* End of cleaning variable x_ */ - if((PyObject *)capi_vub__tmp!=vub__capi) { - Py_XDECREF(capi_vub__tmp); } - } /*if (capi_vub__tmp == NULL) ... else of vub_*/ - /* End of cleaning variable vub_ */ - if((PyObject *)capi_g__tmp!=g__capi) { - Py_XDECREF(capi_g__tmp); } - } /*if (capi_g__tmp == NULL) ... else of g_*/ - /* End of cleaning variable g_ */ - if((PyObject *)capi_vlb__tmp!=vlb__capi) { - Py_XDECREF(capi_vlb__tmp); } - } /*if (capi_vlb__tmp == NULL) ... else of vlb_*/ - /* End of cleaning variable vlb_ */ - } /*if (f2py_success) of n5*/ - /* End of cleaning variable n5 */ - } /*if (f2py_success) of n4*/ - /* End of cleaning variable n4 */ - } /*if (f2py_success) of n3*/ - /* End of cleaning variable n3 */ - } /*if (f2py_success) of n2*/ - /* End of cleaning variable n2 */ - } /*if (f2py_success) of n1*/ - /* End of cleaning variable n1 */ - } /*if (f2py_success) of iprint_*/ - /* End of cleaning variable iprint_ */ - } /*if (f2py_success) of ncon_*/ - /* End of cleaning variable ncon_ */ - } /*if (f2py_success) of nfun_*/ - /* End of cleaning variable nfun_ */ - } /*if (f2py_success) of iout_*/ - /* End of cleaning variable iout_ */ - } /*if (f2py_success) of nfdg_*/ - /* End of cleaning variable nfdg_ */ - } /*if (f2py_success) of itmax_*/ - /* End of cleaning variable itmax_ */ - } /*if (f2py_success) of ndv_*/ - /* End of cleaning variable ndv_ */ - } /*if (f2py_success) of ngrd_*/ - /* End of cleaning variable ngrd_ */ - CFUNCSMESS("Restoring jmpbuf for `cnmngrd`.\n"); - cb_cnmngrd_in_conmin__user__routines_capi = cnmngrd_capi; - Py_DECREF(cb_cnmngrd_in_conmin__user__routines_args_capi); - cb_cnmngrd_in_conmin__user__routines_args_capi = cnmngrd_args_capi; - cb_cnmngrd_in_conmin__user__routines_nofargs = cnmngrd_nofargs_capi; - memcpy(&cb_cnmngrd_in_conmin__user__routines_jmpbuf,&cnmngrd_jmpbuf,sizeof(jmp_buf)); - } - /* End of cleaning variable cnmngrd */ - STRINGFREE(ifile); - } /*if (f2py_success) of ifile*/ - /* End of cleaning variable ifile */ - } /*if (f2py_success) of obj_*/ - /* End of cleaning variable obj_ */ - } /*if (f2py_success) of dabfun_*/ - /* End of cleaning variable dabfun_ */ - CFUNCSMESS("Restoring jmpbuf for `cnmnfun`.\n"); - cb_cnmnfun_in_conmin__user__routines_capi = cnmnfun_capi; - Py_DECREF(cb_cnmnfun_in_conmin__user__routines_args_capi); - cb_cnmnfun_in_conmin__user__routines_args_capi = cnmnfun_args_capi; - cb_cnmnfun_in_conmin__user__routines_nofargs = cnmnfun_nofargs_capi; - memcpy(&cb_cnmnfun_in_conmin__user__routines_jmpbuf,&cnmnfun_jmpbuf,sizeof(jmp_buf)); - } - /* End of cleaning variable cnmnfun */ - } /*if (f2py_success) of nfeasct_*/ - /* End of cleaning variable nfeasct_ */ - } /*if (f2py_success) of itrm_*/ - /* End of cleaning variable itrm_ */ - } /*if (f2py_success) of delfun_*/ - /* End of cleaning variable delfun_ */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/******************************* end of conmin *******************************/ - -/********************************** openunit **********************************/ -static char doc_f2py_rout_conmin_openunit[] = "\ -ierror = openunit(unitnum,filename,filestatus,fileaction)\n\nWrapper for ``openunit``.\ -\n\nParameters\n----------\n" -"unitnum : input int\n" -"filename : input string(len=-1)\n" -"filestatus : input string(len=-1)\n" -"fileaction : input string(len=-1)\n" -"\nReturns\n-------\n" -"ierror : int"; -/* extern void F_FUNC(openunit,OPENUNIT)(int*,string,string,string,int*,size_t,size_t,size_t); */ -static PyObject *f2py_rout_conmin_openunit(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*,string,string,string,int*,size_t,size_t,size_t)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int unitnum = 0; - PyObject *unitnum_capi = Py_None; - string filename = NULL; - int slen(filename); - PyObject *filename_capi = Py_None; - string filestatus = NULL; - int slen(filestatus); - PyObject *filestatus_capi = Py_None; - string fileaction = NULL; - int slen(fileaction); - PyObject *fileaction_capi = Py_None; - int ierror = 0; - static char *capi_kwlist[] = {"unitnum","filename","filestatus","fileaction",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "OOOO:conmin.openunit",\ - capi_kwlist,&unitnum_capi,&filename_capi,&filestatus_capi,&fileaction_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable filestatus */ - slen(filestatus) = -1; - f2py_success = string_from_pyobj(&filestatus,&slen(filestatus),"",filestatus_capi,"string_from_pyobj failed in converting 3rd argument `filestatus' of conmin.openunit to C string"); - if (f2py_success) { - /* Processing variable filename */ - slen(filename) = -1; - f2py_success = string_from_pyobj(&filename,&slen(filename),"",filename_capi,"string_from_pyobj failed in converting 2nd argument `filename' of conmin.openunit to C string"); - if (f2py_success) { - /* Processing variable unitnum */ - f2py_success = int_from_pyobj(&unitnum,unitnum_capi,"conmin.openunit() 1st argument (unitnum) can't be converted to int"); - if (f2py_success) { - /* Processing variable fileaction */ - slen(fileaction) = -1; - f2py_success = string_from_pyobj(&fileaction,&slen(fileaction),"",fileaction_capi,"string_from_pyobj failed in converting 4th argument `fileaction' of conmin.openunit to C string"); - if (f2py_success) { - /* Processing variable ierror */ -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - (*f2py_func)(&unitnum,filename,filestatus,fileaction,&ierror,slen(filename),slen(filestatus),slen(fileaction)); -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue("i",ierror); -/*closepyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - /* End of cleaning variable ierror */ - STRINGFREE(fileaction); - } /*if (f2py_success) of fileaction*/ - /* End of cleaning variable fileaction */ - } /*if (f2py_success) of unitnum*/ - /* End of cleaning variable unitnum */ - STRINGFREE(filename); - } /*if (f2py_success) of filename*/ - /* End of cleaning variable filename */ - STRINGFREE(filestatus); - } /*if (f2py_success) of filestatus*/ - /* End of cleaning variable filestatus */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/****************************** end of openunit ******************************/ - -/********************************** pyflush **********************************/ -static char doc_f2py_rout_conmin_pyflush[] = "\ -pyflush(unitnum)\n\nWrapper for ``pyflush``.\ -\n\nParameters\n----------\n" -"unitnum : input int"; -/* extern void F_FUNC(pyflush,PYFLUSH)(int*); */ -static PyObject *f2py_rout_conmin_pyflush(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int unitnum = 0; - PyObject *unitnum_capi = Py_None; - static char *capi_kwlist[] = {"unitnum",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "O:conmin.pyflush",\ - capi_kwlist,&unitnum_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable unitnum */ - f2py_success = int_from_pyobj(&unitnum,unitnum_capi,"conmin.pyflush() 1st argument (unitnum) can't be converted to int"); - if (f2py_success) { -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - (*f2py_func)(&unitnum); -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue(""); -/*closepyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - } /*if (f2py_success) of unitnum*/ - /* End of cleaning variable unitnum */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/******************************* end of pyflush *******************************/ - -/********************************* closeunit *********************************/ -static char doc_f2py_rout_conmin_closeunit[] = "\ -closeunit(unitnum)\n\nWrapper for ``closeunit``.\ -\n\nParameters\n----------\n" -"unitnum : input int"; -/* extern void F_FUNC(closeunit,CLOSEUNIT)(int*); */ -static PyObject *f2py_rout_conmin_closeunit(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int unitnum = 0; - PyObject *unitnum_capi = Py_None; - static char *capi_kwlist[] = {"unitnum",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "O:conmin.closeunit",\ - capi_kwlist,&unitnum_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable unitnum */ - f2py_success = int_from_pyobj(&unitnum,unitnum_capi,"conmin.closeunit() 1st argument (unitnum) can't be converted to int"); - if (f2py_success) { -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - (*f2py_func)(&unitnum); -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue(""); -/*closepyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - } /*if (f2py_success) of unitnum*/ - /* End of cleaning variable unitnum */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/****************************** end of closeunit ******************************/ -/*eof body*/ - -/******************* See f2py2e/f90mod_rules.py: buildhooks *******************/ -/*need_f90modhooks*/ - -/************** See f2py2e/rules.py: module_rules['modulebody'] **************/ - -/******************* See f2py2e/common_rules.py: buildhooks *******************/ - -static FortranDataDef f2py_output_def[] = { - {"iout",0,{{-1}},NPY_INT}, - {NULL} -}; -static void f2py_setup_output(char *iout) { - int i_f2py=0; - f2py_output_def[i_f2py++].data = iout; -} -extern void F_FUNC(f2pyinitoutput,F2PYINITOUTPUT)(void(*)(char*)); -static void f2py_init_output(void) { - F_FUNC(f2pyinitoutput,F2PYINITOUTPUT)(f2py_setup_output); -} - -static FortranDataDef f2py_varable_def[] = { - {"aobj",0,{{-1}},NPY_DOUBLE}, - {NULL} -}; -static void f2py_setup_varable(char *aobj) { - int i_f2py=0; - f2py_varable_def[i_f2py++].data = aobj; -} -extern void F_FUNC(f2pyinitvarable,F2PYINITVARABLE)(void(*)(char*)); -static void f2py_init_varable(void) { - F_FUNC(f2pyinitvarable,F2PYINITVARABLE)(f2py_setup_varable); -} - -static FortranDataDef f2py_cnmn1_def[] = { - {"delfun",0,{{-1}},NPY_DOUBLE}, - {"dabfun",0,{{-1}},NPY_DOUBLE}, - {"fdch",0,{{-1}},NPY_DOUBLE}, - {"fdchm",0,{{-1}},NPY_DOUBLE}, - {"ct",0,{{-1}},NPY_DOUBLE}, - {"ctmin",0,{{-1}},NPY_DOUBLE}, - {"ctl",0,{{-1}},NPY_DOUBLE}, - {"ctlmin",0,{{-1}},NPY_DOUBLE}, - {"alphax",0,{{-1}},NPY_DOUBLE}, - {"abobj1",0,{{-1}},NPY_DOUBLE}, - {"theta",0,{{-1}},NPY_DOUBLE}, - {"obj",0,{{-1}},NPY_DOUBLE}, - {"ndv",0,{{-1}},NPY_INT}, - {"ncon",0,{{-1}},NPY_INT}, - {"nside",0,{{-1}},NPY_INT}, - {"iprint",0,{{-1}},NPY_INT}, - {"nfdg",0,{{-1}},NPY_INT}, - {"nscal",0,{{-1}},NPY_INT}, - {"linobj",0,{{-1}},NPY_INT}, - {"itmax",0,{{-1}},NPY_INT}, - {"itrm",0,{{-1}},NPY_INT}, - {"icndir",0,{{-1}},NPY_INT}, - {"igoto",0,{{-1}},NPY_INT}, - {"nac",0,{{-1}},NPY_INT}, - {"info",0,{{-1}},NPY_INT}, - {"infog",0,{{-1}},NPY_INT}, - {"iter",0,{{-1}},NPY_INT}, - {NULL} -}; -static void f2py_setup_cnmn1(char *delfun,char *dabfun,char *fdch,char *fdchm,char *ct,char *ctmin,char *ctl,char *ctlmin,char *alphax,char *abobj1,char *theta,char *obj,char *ndv,char *ncon,char *nside,char *iprint,char *nfdg,char *nscal,char *linobj,char *itmax,char *itrm,char *icndir,char *igoto,char *nac,char *info,char *infog,char *iter) { - int i_f2py=0; - f2py_cnmn1_def[i_f2py++].data = delfun; - f2py_cnmn1_def[i_f2py++].data = dabfun; - f2py_cnmn1_def[i_f2py++].data = fdch; - f2py_cnmn1_def[i_f2py++].data = fdchm; - f2py_cnmn1_def[i_f2py++].data = ct; - f2py_cnmn1_def[i_f2py++].data = ctmin; - f2py_cnmn1_def[i_f2py++].data = ctl; - f2py_cnmn1_def[i_f2py++].data = ctlmin; - f2py_cnmn1_def[i_f2py++].data = alphax; - f2py_cnmn1_def[i_f2py++].data = abobj1; - f2py_cnmn1_def[i_f2py++].data = theta; - f2py_cnmn1_def[i_f2py++].data = obj; - f2py_cnmn1_def[i_f2py++].data = ndv; - f2py_cnmn1_def[i_f2py++].data = ncon; - f2py_cnmn1_def[i_f2py++].data = nside; - f2py_cnmn1_def[i_f2py++].data = iprint; - f2py_cnmn1_def[i_f2py++].data = nfdg; - f2py_cnmn1_def[i_f2py++].data = nscal; - f2py_cnmn1_def[i_f2py++].data = linobj; - f2py_cnmn1_def[i_f2py++].data = itmax; - f2py_cnmn1_def[i_f2py++].data = itrm; - f2py_cnmn1_def[i_f2py++].data = icndir; - f2py_cnmn1_def[i_f2py++].data = igoto; - f2py_cnmn1_def[i_f2py++].data = nac; - f2py_cnmn1_def[i_f2py++].data = info; - f2py_cnmn1_def[i_f2py++].data = infog; - f2py_cnmn1_def[i_f2py++].data = iter; -} -extern void F_FUNC(f2pyinitcnmn1,F2PYINITCNMN1)(void(*)(char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*,char*)); -static void f2py_init_cnmn1(void) { - F_FUNC(f2pyinitcnmn1,F2PYINITCNMN1)(f2py_setup_cnmn1); -} - -/*need_commonhooks*/ - -/**************************** See f2py2e/rules.py ****************************/ - -static FortranDataDef f2py_routine_defs[] = { - {"conmin",-1,{{-1}},0,(char *)F_FUNC(conmin,CONMIN),(f2py_init_func)f2py_rout_conmin_conmin,doc_f2py_rout_conmin_conmin}, - {"openunit",-1,{{-1}},0,(char *)F_FUNC(openunit,OPENUNIT),(f2py_init_func)f2py_rout_conmin_openunit,doc_f2py_rout_conmin_openunit}, - {"pyflush",-1,{{-1}},0,(char *)F_FUNC(pyflush,PYFLUSH),(f2py_init_func)f2py_rout_conmin_pyflush,doc_f2py_rout_conmin_pyflush}, - {"closeunit",-1,{{-1}},0,(char *)F_FUNC(closeunit,CLOSEUNIT),(f2py_init_func)f2py_rout_conmin_closeunit,doc_f2py_rout_conmin_closeunit}, - -/*eof routine_defs*/ - {NULL} -}; - -static PyMethodDef f2py_module_methods[] = { - - {NULL,NULL} -}; - -#if PY_VERSION_HEX >= 0x03000000 -static struct PyModuleDef moduledef = { - PyModuleDef_HEAD_INIT, - "conmin", - NULL, - -1, - f2py_module_methods, - NULL, - NULL, - NULL, - NULL -}; -#endif - -#if PY_VERSION_HEX >= 0x03000000 -#define RETVAL m -PyMODINIT_FUNC PyInit_conmin(void) { -#else -#define RETVAL -PyMODINIT_FUNC initconmin(void) { -#endif - int i; - PyObject *m,*d, *s; -#if PY_VERSION_HEX >= 0x03000000 - m = conmin_module = PyModule_Create(&moduledef); -#else - m = conmin_module = Py_InitModule("conmin", f2py_module_methods); -#endif - Py_TYPE(&PyFortran_Type) = &PyType_Type; - import_array(); - if (PyErr_Occurred()) - {PyErr_SetString(PyExc_ImportError, "can't initialize module conmin (failed to import numpy)"); return RETVAL;} - d = PyModule_GetDict(m); - s = PyString_FromString("$Revision: $"); - PyDict_SetItemString(d, "__version__", s); -#if PY_VERSION_HEX >= 0x03000000 - s = PyUnicode_FromString( -#else - s = PyString_FromString( -#endif - "This module 'conmin' is auto-generated with f2py (version:2).\nFunctions:\n" -" conmin(ndv_,ncon_,x_,vlb_,vub_,obj_,g_,n1,n2,n3,n4,n5,iprint_,iout_,ifile,itmax_,delfun_,dabfun_,itrm_,nfeasct_,nfdg_,nfun_,ngrd_,cnmnfun,cnmngrd,cnmnfun_extra_args=(),cnmngrd_extra_args=())\n" -" ierror = openunit(unitnum,filename,filestatus,fileaction)\n" -" pyflush(unitnum)\n" -" closeunit(unitnum)\n" -"COMMON blocks:\n"" /output/ iout\n"" /varable/ aobj\n"" /cnmn1/ delfun,dabfun,fdch,fdchm,ct,ctmin,ctl,ctlmin,alphax,abobj1,theta,obj,ndv,ncon,nside,iprint,nfdg,nscal,linobj,itmax,itrm,icndir,igoto,nac,info,infog,iter\n""."); - PyDict_SetItemString(d, "__doc__", s); - conmin_error = PyErr_NewException ("conmin.error", NULL, NULL); - Py_DECREF(s); - for(i=0;f2py_routine_defs[i].name!=NULL;i++) - PyDict_SetItemString(d, f2py_routine_defs[i].name,PyFortranObject_NewAsAttr(&f2py_routine_defs[i])); - - - - -/*eof initf2pywraphooks*/ -/*eof initf90modhooks*/ - - F2PyDict_SetItemString(d, "output", PyFortranObject_New(f2py_output_def,f2py_init_output)); - F2PyDict_SetItemString(d, "varable", PyFortranObject_New(f2py_varable_def,f2py_init_varable)); - F2PyDict_SetItemString(d, "cnmn1", PyFortranObject_New(f2py_cnmn1_def,f2py_init_cnmn1)); -/*eof initcommonhooks*/ - - -#ifdef F2PY_REPORT_ATEXIT - if (! PyErr_Occurred()) - on_exit(f2py_report_on_exit,(void*)"conmin"); -#endif - - return RETVAL; -} -#ifdef __cplusplus -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyCONMIN/source/openunit.f b/pyoptsparse/pyoptsparse/pyCONMIN/source/openunit.f deleted file mode 100644 index ebd1cd388..000000000 --- a/pyoptsparse/pyoptsparse/pyCONMIN/source/openunit.f +++ /dev/null @@ -1,29 +0,0 @@ -C Helper subroutine to open files in the Fortran world - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) - - integer unitnum -Cf2py intent(in) unitnum - character*(*) filename -Cf2py intent(in) filename - character*(*) filestatus -Cf2py intent(in) filestatus - character*(*) fileaction -Cf2py intent(in) fileaction - integer ierror -Cf2py intent(out) ierror - - open(unit=unitnum,file=filename,status=filestatus, - &access=fileaction,iostat=ierror) - - return - end - -C Helper routine to flush buffers to files - subroutine pyflush(unitnum) - - integer unitnum - - call flush(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pyFSQP/LICENSE b/pyoptsparse/pyoptsparse/pyFSQP/LICENSE deleted file mode 100644 index f5c291417..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -FSQP - Feasible Sequential Quadratic Programming -Copyright (c) 1993-1998 by Craig T. Lawrence, Jian L. Zhou, and Andre L. Tits -Patched for pyOpt - 2009, Ruben E. Perez (Ruben.Perez@rmc.ca) - -FSQP is a licensed software, for term and conditions of use -please refer to the specific commercial or academic agreement -made with AEM Design, Inc. diff --git a/pyoptsparse/pyoptsparse/pyFSQP/README b/pyoptsparse/pyoptsparse/pyFSQP/README deleted file mode 100644 index 71e79e6fc..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the fsqp class definition -and the fsqp shared libraries, ffsqp.so or ffsqp.pyd. diff --git a/pyoptsparse/pyoptsparse/pyFSQP/__init__.py b/pyoptsparse/pyoptsparse/pyFSQP/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyFSQP/pyFSQP.py b/pyoptsparse/pyoptsparse/pyFSQP/pyFSQP.py deleted file mode 100644 index ec13f9900..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/pyFSQP.py +++ /dev/null @@ -1,309 +0,0 @@ -#/bin/env python -""" -pyFSQP - A variation of the pyFSQP wrapper specificially designed to -work with sparse optimization problems. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# FSQP Library -# ============================================================================= -try: - from . import ffsqp -except ImportError: - ffsqp = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# # =========================================================================== -# # Extension modules -# # =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -# ============================================================================= -# FSQP Optimizer Class -# ============================================================================= -class FSQP(Optimizer): - """ - FSQP Optimizer Class - Inherited from Optimizer Abstract Class - """ - def __init__(self, *args, **kwargs): - - name = 'FSQP' - category = 'Local Optimizer' - defOpts = { - 'mode':[int, 100], # FSQP Mode (See Manual) - 'iprint':[int, 2], # Output Level (0 - None, 1 - Final, 2 - Major, 3 - Major Details) - 'miter':[int, 500], # Maximum Number of Iterations - 'bigbnd':[float, 1e10], # Plus Infinity Value - 'epstol':[float, 1e-8], # Convergence Tolerance - 'epseqn':[float, 0], # Equality Constraints Tolerance - 'iout':[int, 6], # Output Unit Number - 'ifile':[str, 'FSQP.out'], # Output File Name - } - informs = { - 0 : 'Normal termination of execution', - 1 : 'User-provided initial guess is infeasible for linear constraints, unable to generate a point satisfying all these constraints', - 2 : 'User-provided initial guess is infeasible for nonlinear inequality constraints and linear constraints, unable to generate a point satisfying all these constraints', - 3 : 'The maximum number of iterations has been reached before a solution is obtained', - 4 : 'The line search fails to find a new iterate', - 5 : 'Failure of the QP solver in attempting to construct d0, a more robust QP solver may succeed', - 6 : 'Failure of the QP solver in attempting to construct d1, a more robust QP solver may succeed', - 7 : 'Input data are not consistent, check print out error messages', - 8 : 'Two consecutive iterates are numerically equivalent before a stopping criterion is satisfied', - 9 : 'One of the penalty parameters exceeded bigbnd, the algorithm is having trouble satisfying a nonlinear equality constraint', - } - if ffsqp is None: - raise Error('There was an error importing the compiled \ - ffsqp module') - - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - # We need jacobians in dens2d formation - self.jacType = 'dense2d' - - def __call__(self, optProb, sens=None, sensStep=None, sensMode='FD', - storeHistory=None, hotStart=None, storeSens=True): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. To explictly - use pyOptSparse gradient class to do the derivatives with - finite differenes use 'FD'. 'sens' may also be 'CS' - which will cause pyOptSpare to compute the derivatives - using the complex step method. Finally, 'sens' may be a - python function handle which is expected to compute the - sensitivities directly. For expensive function evaluations - and/or problems with large numbers of design variables - this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is 'FD' and 1e-40j when sens is 'CS'. - - sensMode : str - Use 'pgc' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from SNOPT does not match the history, function and - gradient evaluations revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if len(optProb.constraints) == 0: - self.unconstrained = True - optProb.dummyConstraint = False - - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - - self._setInitialCacheValues() - self._setSens(sens, sensStep, sensMode) - blx, bux, xs = self._assembleContinuousVariables() - ff = self._assembleObjective() - - # Determine all the constraint information, numbers etc. - if self.optProb.nCon > 0: - # We need to reorder this full jacobian...so get ordering: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ni','li','ne','le'], oneSided=True) - ncon = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - # We need to call getOrdering a few more times to get - # the remaining sizes: - indices, __, __, __ = self.optProb.getOrdering( - ['ni'], oneSided=True) - nineqn = len(indices) - - indices, __, __, __ = self.optProb.getOrdering( - ['ni', 'li'], oneSided=True) - nineq = len(indices) - - indices, __, __, __ = self.optProb.getOrdering( - ['ne'], oneSided=True) - neqn = len(indices) - - indices, __, __, __ = self.optProb.getOrdering( - ['ne', 'le'], oneSided=True) - neq = len(indices) - else: - nineqn = 0 - nineq = 0 - neqn = 0 - neq = 0 - ncon = 0 - - # We make a split here: If the rank is zero we setup the - # problem and run SNOPT, otherwise we go to the waiting loop: - if self.optProb.comm.rank == 0: - # Set history/hotstart/coldstart - self._setHistory(storeHistory, hotStart) - - #====================================================================== - # FSQP - Objective Values Function - #====================================================================== - def obj(nparam, j, x, fj): - if self._checkEval(x): - self._internalEval(x) - - fj = self.storedData['fobj'] - - return fj - - #====================================================================== - # FSQP - Constraint Values Function - #====================================================================== - def cntr(nparam, j, x, gj): - - # for given j, assign to gj the value of the jth constraint evaluated at x - if self._checkEval(x): - self._internalEval(x) - - gj = self.storedData['fcon'][j-1] - - return gj - - #====================================================================== - # FSQP - Objective Gradients Function - #====================================================================== - def gradobj(nparam, j, x, gradfj, obj): - - # assign to gradfj the gradient of the jth objective function evaluated at x - if self._checkEval(x): - self._internalEval(x) - - gradfj[0:nparam] = self.storedData['gobj'] - - return gradfj - - #====================================================================== - # FSQP - Constraint Gradients Function - #====================================================================== - def gradcntr(nparam, j, x, gradgj, obj): - - # assign to gradgj the gradient of the jth constraint evaluated at x - if self._checkEval(x): - self._internalEval(x) - - gradgj[0:nparam] = self.storedData['gcon'][j-1] - - return gradgj - - # Setup argument list values - nparam = len(xs) - nvar = nparam - nf = 1 - - mode = self.getOption('mode') - if self.getOption('iprint') >= 0: - iprint = self.getOption('iprint') - else: - raise Error('Incorrect iprint option. Must be >= 0') - iout = self.getOption('iout') - ifile = self.getOption('ifile') - - if iprint > 0: - if os.path.isfile(ifile): - os.remove(ifile) - - gg = numpy.zeros(max(ncon,1)) - miter = self.getOption('miter') - inform = 0 - bigbnd = self.getOption('bigbnd') - epstol = self.getOption('epstol') - epsneq = self.getOption('epseqn') - udelta = 0 - nobj = 1 - iwsize = 6*nvar + 8*max([1,ncon]) + 7*max([1,nobj]) + 30 - iw = numpy.zeros([iwsize], numpy.float) - nwsize = (4*nvar**2 + 5*max([1,ncon])*nvar + 3*max([1,nobj])*nvar + - 26*(nvar+max([1,nobj])) + 45*max([1,ncon]) + 100) - w = numpy.zeros([nwsize], numpy.float) - - # Run FSQP - t0 = time.time() - ffsqp.ffsqp(nparam, nf, nineqn, nineq, neqn, neq, mode, iprint, miter, - inform, bigbnd, epstol, epsneq, udelta, blx, bux, xs, ff, - gg, iw, iwsize, w, nwsize, obj, cntr, gradobj, gradcntr, - iout, ifile) - optTime = time.time() - t0 - - if iprint > 0: - ffsqp.closeunit(iprint) - - # Broadcast a -1 to indcate SLSQP has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - # sol_inform['value'] = inform - # sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name): - pass diff --git a/pyoptsparse/pyoptsparse/pyFSQP/setup.py b/pyoptsparse/pyoptsparse/pyFSQP/setup.py deleted file mode 100644 index 77cccf9d1..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/setup.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/local/bin/python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyFSQP',parent_package,top_path) - - config.add_library('ffsqp', - sources=[os.path.join('source', '*.f')]) - config.add_extension('ffsqp', - sources=['source/f2py/ffsqp.pyf'], - libraries=['ffsqp']) - config.add_data_files('LICENSE','README') - - return config diff --git a/pyoptsparse/pyoptsparse/pyFSQP/source/README b/pyoptsparse/pyoptsparse/pyFSQP/source/README deleted file mode 100644 index 506493035..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/source/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains the Fortran 77 source for -FSQP, plus two helper files called openunit.f and -closeunit.f to manipulate Fortran units from Python. diff --git a/pyoptsparse/pyoptsparse/pyFSQP/source/closeunit.f b/pyoptsparse/pyoptsparse/pyFSQP/source/closeunit.f deleted file mode 100644 index f1d9f8377..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/source/closeunit.f +++ /dev/null @@ -1,10 +0,0 @@ -C Helper subroutine to close files in the Fortran world - subroutine closeunit(unitnum) - - integer unitnum -Cf2py intent(in) unitnum - - close(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pyFSQP/source/f2py/README b/pyoptsparse/pyoptsparse/pyFSQP/source/f2py/README deleted file mode 100644 index 54e48d046..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/source/f2py/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the f2py signature file. -Do not edit these file unless you really know what you are doing. diff --git a/pyoptsparse/pyoptsparse/pyFSQP/source/f2py/ffsqp.pyf b/pyoptsparse/pyoptsparse/pyFSQP/source/f2py/ffsqp.pyf deleted file mode 100644 index 1961b1cc7..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/source/f2py/ffsqp.pyf +++ /dev/null @@ -1,118 +0,0 @@ -! -*- f90 -*- -! Note: the context of this file is case sensitive. - -python module ffsqp__user__routines - interface ffsqp_user_interface - subroutine obj(nparam,j,x,fj) - integer intent(in) :: nparam - integer intent(in) :: j - double precision dimension(nparam),intent(in),depend(nparam) :: x - double precision intent(in,out) :: fj - end subroutine obj - subroutine constr(nparam,j,x,gj) - integer intent(in) :: nparam - integer intent(in) :: j - double precision dimension(nparam),intent(in),depend(nparam) :: x - double precision intent(in,out) :: gj - end subroutine constr - subroutine gradob(nparam,j,x,gradfj,obj) - integer intent(in) :: nparam - integer intent(in) :: j - double precision dimension(nparam),intent(in),depend(nparam) :: x - double precision dimension(nparam),intent(in,out),depend(nparam) :: gradfj - external obj - end subroutine gradob - subroutine gradcn(nparam,j,x,gradgj,obj) - integer intent(in) :: nparam - integer intent(in) :: j - double precision dimension(nparam),intent(in),depend(nparam) :: x - double precision dimension(nparam),intent(in,out),depend(nparam) :: gradgj - external obj - end subroutine gradcn - end interface ffsqp_user_interface -end python module ffsqp__user__routines -python module ffsqp ! in - interface ! in :ffsqp - subroutine ffsqp(nparam,nf,nineqn,nineq,neqn,neq,mode,iprint,miter,inform,bigbnd,eps,epseqn,udelta,bl,bu,x,f,g,iw,iwsize,w,nwsize,obj,constr,gradob,gradcn,iounit,ifile) ! in :ffsqp:source/ffsqp.f - use ffsqp__user__routines - integer intent(in) :: nparam - integer intent(in) :: nf - integer intent(in) :: nineqn - integer intent(in) :: nineq - integer intent(in) :: neqn - integer intent(in) :: neq - integer intent(in) :: mode - integer intent(in) :: iprint - integer intent(in) :: miter - integer intent(inout) :: inform - double precision intent(in) :: bigbnd - double precision intent(in) :: eps - double precision intent(in) :: epseqn - double precision intent(in) :: udelta - double precision dimension(nparam),intent(in),depend(nparam) :: bl - double precision dimension(nparam),intent(in),depend(nparam) :: bu - double precision dimension(nparam),intent(inout),depend(nparam) :: x - double precision dimension(nf),intent(inout),depend(nf) :: f - double precision dimension(nineq+neq),intent(inout),depend(nineq,neq) :: g - integer dimension(iwsize),intent(in),depend(iwsize) :: iw - integer intent(in) :: iwsize - double precision intent(inout),dimension(nwsize),depend(nwsize) :: w - integer intent(in) :: nwsize - external obj - external constr - external gradob - external gradcn - integer intent(in) :: iounit - character*(*) intent(in) :: ifile - double precision :: qleps - integer :: nnineq - integer :: m - integer :: ncallg - integer :: ncallf - integer :: modd - integer :: lstype - integer :: nstop - integer :: io - integer :: ipp - integer :: ipsp - integer :: ipyes - integer :: info - integer :: idummy - integer :: iter - integer :: initvl - double precision :: epsmac - double precision :: rteps - double precision :: upert - double precision :: valnom - logical :: rolis1 - logical :: d0is0 - integer :: maxit - double precision :: big - double precision :: tolfea - common /cmache/ qleps - common /fsqpp1/ nnineq,m,ncallg,ncallf,modd,lstype,nstop - common /fsqpp2/ io,ipp,ipsp,ipyes,info,idummy,iter,initvl - common /fsqpp3/ epsmac,rteps,upert,valnom - common /fsqpp4/ rolis1,d0is0 - common /fsqpq2/ maxit - common /fsqpq1/ big,tolfea - end subroutine ffsqp - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) ! in :conmin:source/openunit.f - integer intent(in) :: unitnum - character*(*) intent(in) :: filename - character*(*) intent(in) :: filestatus - character*(*) intent(in) :: fileaction - integer intent(out) :: ierror - end subroutine openunit - subroutine pyflush(unitnum) - integer unitnum - return - end subroutine pyflush - subroutine closeunit(unitnum) ! in :conmin:source/closeunit.f - integer intent(in) :: unitnum - end subroutine closeunit - end interface -end python module ffsqp - -! This file was auto-generated with f2py (version:2_3979). -! See http://cens.ioc.ee/projects/f2py2e/ diff --git a/pyoptsparse/pyoptsparse/pyFSQP/source/openunit.f b/pyoptsparse/pyoptsparse/pyFSQP/source/openunit.f deleted file mode 100644 index ebd1cd388..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/source/openunit.f +++ /dev/null @@ -1,29 +0,0 @@ -C Helper subroutine to open files in the Fortran world - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) - - integer unitnum -Cf2py intent(in) unitnum - character*(*) filename -Cf2py intent(in) filename - character*(*) filestatus -Cf2py intent(in) filestatus - character*(*) fileaction -Cf2py intent(in) fileaction - integer ierror -Cf2py intent(out) ierror - - open(unit=unitnum,file=filename,status=filestatus, - &access=fileaction,iostat=ierror) - - return - end - -C Helper routine to flush buffers to files - subroutine pyflush(unitnum) - - integer unitnum - - call flush(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pyFSQP/source/qld.f b/pyoptsparse/pyoptsparse/pyFSQP/source/qld.f deleted file mode 100644 index 345f1fa36..000000000 --- a/pyoptsparse/pyoptsparse/pyFSQP/source/qld.f +++ /dev/null @@ -1,1167 +0,0 @@ - SUBROUTINE QL0001(M,ME,MMAX,N,NMAX,MNN,C,D,A,B,XL,XU, - 1 X,U,IOUT,IFAIL,IPRINT,WAR,LWAR,IWAR,LIWAR) -c -cCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC -c -c !!!! NOTICE !!!! -c -c 1. The routines contained in this file are due to Prof. K.Schittkowski -c of the University of Bayreuth, Germany (modification of routines -c due to Prof. MJD Powell at the University of Cambridge). They can -c be freely distributed. -c -c 2. A minor modification was performed at the University of Maryland. -c It is marked in the code by "c umd". -c -c A.L. Tits and J.L. Zhou -c University of Maryland -C -C*********************************************************************** -C -C -C SOLUTION OF QUADRATIC PROGRAMMING PROBLEMS -C -C -C -C QL0001 SOLVES THE QUADRATIC PROGRAMMING PROBLEM -C -C MINIMIZE .5*X'*C*X + D'*X -C SUBJECT TO A(J)*X + B(J) = 0 , J=1,...,ME -C A(J)*X + B(J) >= 0 , J=ME+1,...,M -C XL <= X <= XU -C -C HERE C MUST BE AN N BY N SYMMETRIC AND POSITIVE MATRIX, D AN N-DIMENSIONAL -C VECTOR, A AN M BY N MATRIX AND B AN M-DIMENSIONAL VECTOR. THE ABOVE -C SITUATION IS INDICATED BY IWAR(1)=1. ALTERNATIVELY, I.E. IF IWAR(1)=0, -C THE OBJECTIVE FUNCTION MATRIX CAN ALSO BE PROVIDED IN FACTORIZED FORM. -C IN THIS CASE, C IS AN UPPER TRIANGULAR MATRIX. -C -C THE SUBROUTINE REORGANIZES SOME DATA SO THAT THE PROBLEM CAN BE SOLVED -C BY A MODIFICATION OF AN ALGORITHM PROPOSED BY POWELL (1983). -C -C -C USAGE: -C -C QL0001(M,ME,MMAX,N,NMAX,MNN,C,D,A,B,XL,XU,X,U,IOUT,IFAIL,IPRINT, -C WAR,LWAR,IWAR,LIWAR) -C -C -C DEFINITION OF THE PARAMETERS: -C -C M : TOTAL NUMBER OF CONSTRAINTS. -C ME : NUMBER OF EQUALITY CONSTRAINTS. -C MMAX : ROW DIMENSION OF A. MMAX MUST BE AT LEAST ONE AND GREATER -C THAN M. -C N : NUMBER OF VARIABLES. -C NMAX : ROW DIMENSION OF C. NMAX MUST BE GREATER OR EQUAL TO N. -C MNN : MUST BE EQUAL TO M + N + N. -C C(NMAX,NMAX): OBJECTIVE FUNCTION MATRIX WHICH SHOULD BE SYMMETRIC AND -C POSITIVE DEFINITE. IF IWAR(1) = 0, C IS SUPPOSED TO BE THE -C CHOLESKEY-FACTOR OF ANOTHER MATRIX, I.E. C IS UPPER -C TRIANGULAR. -C D(NMAX) : CONTAINS THE CONSTANT VECTOR OF THE OBJECTIVE FUNCTION. -C A(MMAX,NMAX): CONTAINS THE DATA MATRIX OF THE LINEAR CONSTRAINTS. -C B(MMAX) : CONTAINS THE CONSTANT DATA OF THE LINEAR CONSTRAINTS. -C XL(N),XU(N): CONTAIN THE LOWER AND UPPER BOUNDS FOR THE VARIABLES. -C X(N) : ON RETURN, X CONTAINS THE OPTIMAL SOLUTION VECTOR. -C U(MNN) : ON RETURN, U CONTAINS THE LAGRANGE MULTIPLIERS. THE FIRST -C M POSITIONS ARE RESERVED FOR THE MULTIPLIERS OF THE M -C LINEAR CONSTRAINTS AND THE SUBSEQUENT ONES FOR THE -C MULTIPLIERS OF THE LOWER AND UPPER BOUNDS. ON SUCCESSFUL -C TERMINATION, ALL VALUES OF U WITH RESPECT TO INEQUALITIES -C AND BOUNDS SHOULD BE GREATER OR EQUAL TO ZERO. -C IOUT : INTEGER INDICATING THE DESIRED OUTPUT UNIT NUMBER, I.E. -C ALL WRITE-STATEMENTS START WITH 'WRITE(IOUT,... '. -C IFAIL : SHOWS THE TERMINATION REASON. -C IFAIL = 0 : SUCCESSFUL RETURN. -C IFAIL = 1 : TOO MANY ITERATIONS (MORE THAN 40*(N+M)). -C IFAIL = 2 : ACCURACY INSUFFICIENT TO SATISFY CONVERGENCE -C CRITERION. -C IFAIL = 5 : LENGTH OF A WORKING ARRAY IS TOO SHORT. -C IFAIL > 10 : THE CONSTRAINTS ARE INCONSISTENT. -C IPRINT : OUTPUT CONTROL. -C IPRINT = 0 : NO OUTPUT OF QL0001. -C IPRINT > 0 : BRIEF OUTPUT IN ERROR CASES. -C WAR(LWAR) : REAL WORKING ARRAY. THE LENGTH LWAR SHOULD BE GRATER THAN -C 3*NMAX*NMAX/2 + 10*NMAX + 2*MMAX. -C IWAR(LIWAR): INTEGER WORKING ARRAY. THE LENGTH LIWAR SHOULD BE AT -C LEAST N. -C IF IWAR(1)=0 INITIALLY, THEN THE CHOLESKY DECOMPOSITION -C WHICH IS REQUIRED BY THE DUAL ALGORITHM TO GET THE FIRST -C UNCONSTRAINED MINIMUM OF THE OBJECTIVE FUNCTION, IS -C PERFORMED INTERNALLY. OTHERWISE, I.E. IF IWAR(1)=1, THEN -C IT IS ASSUMED THAT THE USER PROVIDES THE INITIAL FAC- -C TORIZATION BY HIMSELF AND STORES IT IN THE UPPER TRIAN- -C GULAR PART OF THE ARRAY C. -C -C A NAMED COMMON-BLOCK /CMACHE/EPS MUST BE PROVIDED BY THE USER, -C WHERE EPS DEFINES A GUESS FOR THE UNDERLYING MACHINE PRECISION. -C -C -C AUTHOR: K. SCHITTKOWSKI, -C MATHEMATISCHES INSTITUT, -C UNIVERSITAET BAYREUTH, -C 8580 BAYREUTH, -C GERMANY, F.R. -C -C -C VERSION: 1.4 (MARCH, 1987) -C -C -C********************************************************************* -C -C - INTEGER NMAX,MMAX,N,MNN,LWAR,LIWAR - DIMENSION C(NMAX,NMAX),D(NMAX),A(MMAX,NMAX),B(MMAX), - 1 XL(N),XU(N),X(N),U(MNN),WAR(LWAR),IWAR(LIWAR) - DOUBLE PRECISION C,D,A,B,X,XL,XU,U,WAR,DIAG,ZERO, - 1 EPS,QPEPS,TEN - INTEGER M,ME,IOUT,IFAIL,IPRINT,IWAR,INW1,INW2,IN,J,LW,MN,I, - 1 IDIAG,INFO,NACT,MAXIT - LOGICAL LQL -C -C INTRINSIC FUNCTIONS: DSQRT -C - COMMON /CMACHE/EPS -C -C CONSTANT DATA -C -c################################################################# -c - - if(dabs(c(nmax,nmax)).lt.eps) c(nmax,nmax)=eps -c -c umd -c This prevents a subsequent more major modification of the Hessian -c matrix in the important case when a minmax problem (yielding a -c singular Hessian matrix) is being solved. -c ----UMCP, April 1991, Jian L. Zhou -c################################################################# -c - LQL=.FALSE. - IF (IWAR(1).EQ.1) LQL=.TRUE. - ZERO=0.0D+0 - TEN=1.D+1 - MAXIT=40*(M+N) - QPEPS=EPS - INW1=1 - INW2=INW1+MMAX -C -C PREPARE PROBLEM DATA FOR EXECUTION -C - IF (M.LE.0) GOTO 20 - IN=INW1 - DO 10 J=1,M - WAR(IN)=-B(J) - 10 IN=IN+1 - 20 LW=3*NMAX*NMAX/2 + 10*NMAX + M - IF ((INW2+LW).GT.LWAR) GOTO 80 - IF (LIWAR.LT.N) GOTO 81 - IF (MNN.LT.M+N+N) GOTO 82 - MN=M+N -C -C CALL OF QL0002 -C - CALL QL0002(N,M,ME,MMAX,MN,MNN,NMAX,LQL,A,WAR(INW1), - 1 D,C,XL,XU,X,NACT,IWAR,MAXIT,QPEPS,INFO,DIAG, - 2 WAR(INW2),LW) -C -C TEST OF MATRIX CORRECTIONS -C - IFAIL=0 - IF (INFO.EQ.1) GOTO 40 - IF (INFO.EQ.2) GOTO 90 - IDIAG=0 - IF ((DIAG.GT.ZERO).AND.(DIAG.LT.1000.0)) IDIAG=DIAG - IF ((IPRINT.GT.0).AND.(IDIAG.GT.0)) - 1 WRITE(IOUT,1000) IDIAG - IF (INFO .LT. 0) GOTO 70 -C -C REORDER MULTIPLIER -C - DO 50 J=1,MNN - 50 U(J)=ZERO - IN=INW2-1 - IF (NACT.EQ.0) GOTO 30 - DO 60 I=1,NACT - J=IWAR(I) - U(J)=WAR(IN+I) - 60 CONTINUE - 30 CONTINUE - RETURN -C -C ERROR MESSAGES -C - 70 IFAIL=-INFO+10 - IF ((IPRINT.GT.0).AND.(NACT.GT.0)) - 1 WRITE(IOUT,1100) -INFO,(IWAR(I),I=1,NACT) - RETURN - 80 IFAIL=5 - IF (IPRINT .GT. 0) WRITE(IOUT,1200) - RETURN - 81 IFAIL=5 - IF (IPRINT .GT. 0) WRITE(IOUT,1210) - RETURN - 82 IFAIL=5 - IF (IPRINT .GT. 0) WRITE(IOUT,1220) - RETURN - 40 IFAIL=1 - IF (IPRINT.GT.0) WRITE(IOUT,1300) MAXIT - RETURN - 90 IFAIL=2 - IF (IPRINT.GT.0) WRITE(IOUT,1400) - RETURN -C -C FORMAT-INSTRUCTIONS -C - 1000 FORMAT(/8X,28H***QL: MATRIX G WAS ENLARGED,I3, - 1 20H-TIMES BY UNITMATRIX) - 1100 FORMAT(/8X,18H***QL: CONSTRAINT ,I5, - 1 19H NOT CONSISTENT TO ,/,(10X,10I5)) - 1200 FORMAT(/8X,21H***QL: LWAR TOO SMALL) - 1210 FORMAT(/8X,22H***QL: LIWAR TOO SMALL) - 1220 FORMAT(/8X,20H***QL: MNN TOO SMALL) - 1300 FORMAT(/8X,37H***QL: TOO MANY ITERATIONS (MORE THAN,I6,1H)) - 1400 FORMAT(/8X,50H***QL: ACCURACY INSUFFICIENT TO ATTAIN CONVERGENCE) - END -C - SUBROUTINE QL0002(N,M,MEQ,MMAX,MN,MNN,NMAX,LQL,A,B,GRAD,G, - 1 XL,XU,X,NACT,IACT,MAXIT,VSMALL,INFO,DIAG,W,LW) -C -C************************************************************************** -C -C -C THIS SUBROUTINE SOLVES THE QUADRATIC PROGRAMMING PROBLEM -C -C MINIMIZE GRAD'*X + 0.5 * X*G*X -C SUBJECT TO A(K)*X = B(K) K=1,2,...,MEQ, -C A(K)*X >= B(K) K=MEQ+1,...,M, -C XL <= X <= XU -C -C THE QUADRATIC PROGRAMMING METHOD PROCEEDS FROM AN INITIAL CHOLESKY- -C DECOMPOSITION OF THE OBJECTIVE FUNCTION MATRIX, TO CALCULATE THE -C UNIQUELY DETERMINED MINIMIZER OF THE UNCONSTRAINED PROBLEM. -C SUCCESSIVELY ALL VIOLATED CONSTRAINTS ARE ADDED TO A WORKING SET -C AND A MINIMIZER OF THE OBJECTIVE FUNCTION SUBJECT TO ALL CONSTRAINTS -C IN THIS WORKING SET IS COMPUTED. IT IS POSSIBLE THAT CONSTRAINTS -C HAVE TO LEAVE THE WORKING SET. -C -C -C DESCRIPTION OF PARAMETERS: -C -C N : IS THE NUMBER OF VARIABLES. -C M : TOTAL NUMBER OF CONSTRAINTS. -C MEQ : NUMBER OF EQUALITY CONTRAINTS. -C MMAX : ROW DIMENSION OF A, DIMENSION OF B. MMAX MUST BE AT -C LEAST ONE AND GREATER OR EQUAL TO M. -C MN : MUST BE EQUAL M + N. -C MNN : MUST BE EQUAL M + N + N. -C NMAX : ROW DIEMSION OF G. MUST BE AT LEAST N. -C LQL : DETERMINES INITIAL DECOMPOSITION. -C LQL = .FALSE. : THE UPPER TRIANGULAR PART OF THE MATRIX G -C CONTAINS INITIALLY THE CHOLESKY-FACTOR OF A SUITABLE -C DECOMPOSITION. -C LQL = .TRUE. : THE INITIAL CHOLESKY-FACTORISATION OF G IS TO BE -C PERFORMED BY THE ALGORITHM. -C A(MMAX,NMAX) : A IS A MATRIX WHOSE COLUMNS ARE THE CONSTRAINTS NORMALS. -C B(MMAX) : CONTAINS THE RIGHT HAND SIDES OF THE CONSTRAINTS. -C GRAD(N) : CONTAINS THE OBJECTIVE FUNCTION VECTOR GRAD. -C G(NMAX,N): CONTAINS THE SYMMETRIC OBJECTIVE FUNCTION MATRIX. -C XL(N), XU(N): CONTAIN THE LOWER AND UPPER BOUNDS FOR X. -C X(N) : VECTOR OF VARIABLES. -C NACT : FINAL NUMBER OF ACTIVE CONSTRAINTS. -C IACT(K) (K=1,2,...,NACT): INDICES OF THE FINAL ACTIVE CONSTRAINTS. -C INFO : REASON FOR THE RETURN FROM THE SUBROUTINE. -C INFO = 0 : CALCULATION WAS TERMINATED SUCCESSFULLY. -C INFO = 1 : MAXIMUM NUMBER OF ITERATIONS ATTAINED. -C INFO = 2 : ACCURACY IS INSUFFICIENT TO MAINTAIN INCREASING -C FUNCTION VALUES. -C INFO < 0 : THE CONSTRAINT WITH INDEX ABS(INFO) AND THE CON- -C STRAINTS WHOSE INDICES ARE IACT(K), K=1,2,...,NACT, -C ARE INCONSISTENT. -C MAXIT : MAXIMUM NUMBER OF ITERATIONS. -C VSMALL : REQUIRED ACCURACY TO BE ACHIEVED (E.G. IN THE ORDER OF THE -C MACHINE PRECISION FOR SMALL AND WELL-CONDITIONED PROBLEMS). -C DIAG : ON RETURN DIAG IS EQUAL TO THE MULTIPLE OF THE UNIT MATRIX -C THAT WAS ADDED TO G TO ACHIEVE POSITIVE DEFINITENESS. -C W(LW) : THE ELEMENTS OF W(.) ARE USED FOR WORKING SPACE. THE LENGTH -C OF W MUST NOT BE LESS THAN (1.5*NMAX*NMAX + 10*NMAX + M). -C WHEN INFO = 0 ON RETURN, THE LAGRANGE MULTIPLIERS OF THE -C FINAL ACTIVE CONSTRAINTS ARE HELD IN W(K), K=1,2,...,NACT. -C THE VALUES OF N, M, MEQ, MMAX, MN, MNN AND NMAX AND THE ELEMENTS OF -C A, B, GRAD AND G ARE NOT ALTERED. -C -C THE FOLLOWING INTEGERS ARE USED TO PARTITION W: -C THE FIRST N ELEMENTS OF W HOLD LAGRANGE MULTIPLIER ESTIMATES. -C W(IWZ+I+(N-1)*J) HOLDS THE MATRIX ELEMENT Z(I,J). -C W(IWR+I+0.5*J*(J-1)) HOLDS THE UPPER TRIANGULAR MATRIX -C ELEMENT R(I,J). THE SUBSEQUENT N COMPONENTS OF W MAY BE -C TREATED AS AN EXTRA COLUMN OF R(.,.). -C W(IWW-N+I) (I=1,2,...,N) ARE USED FOR TEMPORARY STORAGE. -C W(IWW+I) (I=1,2,...,N) ARE USED FOR TEMPORARY STORAGE. -C W(IWD+I) (I=1,2,...,N) HOLDS G(I,I) DURING THE CALCULATION. -C W(IWX+I) (I=1,2,...,N) HOLDS VARIABLES THAT WILL BE USED TO -C TEST THAT THE ITERATIONS INCREASE THE OBJECTIVE FUNCTION. -C W(IWA+K) (K=1,2,...,M) USUALLY HOLDS THE RECIPROCAL OF THE -C LENGTH OF THE K-TH CONSTRAINT, BUT ITS SIGN INDICATES -C WHETHER THE CONSTRAINT IS ACTIVE. -C -C -C AUTHOR: K. SCHITTKOWSKI, -C MATHEMATISCHES INSTITUT, -C UNIVERSITAET BAYREUTH, -C 8580 BAYREUTH, -C GERMANY, F.R. -C -C AUTHOR OF ORIGINAL VERSION: -C M.J.D. POWELL, DAMTP, -C UNIVERSITY OF CAMBRIDGE, SILVER STREET -C CAMBRIDGE, -C ENGLAND -C -C -C REFERENCE: M.J.D. POWELL: ZQPCVX, A FORTRAN SUBROUTINE FOR CONVEX -C PROGRAMMING, REPORT DAMTP/1983/NA17, UNIVERSITY OF -C CAMBRIDGE, ENGLAND, 1983. -C -C -C VERSION : 2.0 (MARCH, 1987) -C -C -C************************************************************************* -C - INTEGER MMAX,NMAX,N,LW - DIMENSION A(MMAX,NMAX),B(MMAX),GRAD(N),G(NMAX,N),X(N),IACT(N), - 1 W(LW),XL(N),XU(N) - INTEGER M,MEQ,MN,MNN,NACT,IACT,INFO,MAXIT - DOUBLE PRECISION CVMAX,DIAG,DIAGR,FDIFF,FDIFFA,GA,GB,PARINC,PARNEW - 1 ,RATIO,RES,STEP,SUM,SUMX,SUMY,SUMA,SUMB,SUMC,TEMP,TEMPA, - 2 VSMALL,XMAG,XMAGR,ZERO,ONE,TWO,ONHA,VFACT - DOUBLE PRECISION A,B,G,GRAD,W,X,XL,XU -C -C INTRINSIC FUNCTIONS: DMAX1,DSQRT,DABS,DMIN1 -C - INTEGER IWZ,IWR,IWW,IWD,IWA,IFINC,KFINC,K,I,IA,ID,II,IR,IRA, - 1 IRB,J,NM,IZ,IZA,ITERC,ITREF,JFINC,IFLAG,IWS,IS,K1,IW,KK,IP, - 2 IPP,IL,IU,JU,KFLAG,LFLAG,JFLAG,KDROP,NU,MFLAG,KNEXT,IX,IWX, - 3 IWY,IY,JL - LOGICAL LQL,LOWER -C -C INITIAL ADDRESSES -C - IWZ=NMAX - IWR=IWZ+NMAX*NMAX - IWW=IWR+(NMAX*(NMAX+3))/2 - IWD=IWW+NMAX - IWX=IWD+NMAX - IWA=IWX+NMAX -C -C SET SOME CONSTANTS. -C - ZERO=0.D+0 - ONE=1.D+0 - TWO=2.D+0 - ONHA=1.5D+0 - VFACT=1.D+0 -C -C SET SOME PARAMETERS. -C NUMBER LESS THAN VSMALL ARE ASSUMED TO BE NEGLIGIBLE. -C THE MULTIPLE OF I THAT IS ADDED TO G IS AT MOST DIAGR TIMES -C THE LEAST MULTIPLE OF I THAT GIVES POSITIVE DEFINITENESS. -C X IS RE-INITIALISED IF ITS MAGNITUDE IS REDUCED BY THE -C FACTOR XMAGR. -C A CHECK IS MADE FOR AN INCREASE IN F EVERY IFINC ITERATIONS, -C AFTER KFINC ITERATIONS ARE COMPLETED. -C - DIAGR=TWO - XMAGR=1.0D-2 - IFINC=3 - KFINC=MAX0(10,N) -C -C FIND THE RECIPROCALS OF THE LENGTHS OF THE CONSTRAINT NORMALS. -C RETURN IF A CONSTRAINT IS INFEASIBLE DUE TO A ZERO NORMAL. -C - NACT=0 - IF (M .LE. 0) GOTO 45 - DO 40 K=1,M - SUM=ZERO - DO 10 I=1,N - 10 SUM=SUM+A(K,I)**2 - IF (SUM .GT. ZERO) GOTO 20 - IF (B(K) .EQ. ZERO) GOTO 30 - INFO=-K - IF (K .LE. MEQ) GOTO 730 - IF (B(K)) 30,30,730 - 20 SUM=ONE/DSQRT(SUM) - 30 IA=IWA+K - 40 W(IA)=SUM - 45 DO 50 K=1,N - IA=IWA+M+K - 50 W(IA)=ONE -C -C IF NECESSARY INCREASE THE DIAGONAL ELEMENTS OF G. -C - IF (.NOT. LQL) GOTO 165 - DIAG=ZERO - DO 60 I=1,N - ID=IWD+I - W(ID)=G(I,I) - DIAG=DMAX1(DIAG,VSMALL-W(ID)) - IF (I .EQ. N) GOTO 60 - II=I+1 - DO 55 J=II,N - GA=-DMIN1(W(ID),G(J,J)) - GB=DABS(W(ID)-G(J,J))+DABS(G(I,J)) - IF (GB .GT. ZERO) GA=GA+G(I,J)**2/GB - 55 DIAG=DMAX1(DIAG,GA) - 60 CONTINUE - IF (DIAG .LE. ZERO) GOTO 90 - 70 DIAG=DIAGR*DIAG - DO 80 I=1,N - ID=IWD+I - 80 G(I,I)=DIAG+W(ID) -C -C FORM THE CHOLESKY FACTORISATION OF G. THE TRANSPOSE -C OF THE FACTOR WILL BE PLACED IN THE R-PARTITION OF W. -C - 90 IR=IWR - DO 130 J=1,N - IRA=IWR - IRB=IR+1 - DO 120 I=1,J - TEMP=G(I,J) - IF (I .EQ. 1) GOTO 110 - DO 100 K=IRB,IR - IRA=IRA+1 - 100 TEMP=TEMP-W(K)*W(IRA) - 110 IR=IR+1 - IRA=IRA+1 - IF (I .LT. J) W(IR)=TEMP/W(IRA) - 120 CONTINUE - IF (TEMP .LT. VSMALL) GOTO 140 - 130 W(IR)=DSQRT(TEMP) - GOTO 170 -C -C INCREASE FURTHER THE DIAGONAL ELEMENT OF G. -C - 140 W(J)=ONE - SUMX=ONE - K=J - 150 SUM=ZERO - IRA=IR-1 - DO 160 I=K,J - SUM=SUM-W(IRA)*W(I) - 160 IRA=IRA+I - IR=IR-K - K=K-1 - W(K)=SUM/W(IR) - SUMX=SUMX+W(K)**2 - IF (K .GE. 2) GOTO 150 - DIAG=DIAG+VSMALL-TEMP/SUMX - GOTO 70 -C -C STORE THE CHOLESKY FACTORISATION IN THE R-PARTITION -C OF W. -C - 165 IR=IWR - DO 166 I=1,N - DO 166 J=1,I - IR=IR+1 - 166 W(IR)=G(J,I) -C -C SET Z THE INVERSE OF THE MATRIX IN R. -C - 170 NM=N-1 - DO 220 I=1,N - IZ=IWZ+I - IF (I .EQ. 1) GOTO 190 - DO 180 J=2,I - W(IZ)=ZERO - 180 IZ=IZ+N - 190 IR=IWR+(I+I*I)/2 - W(IZ)=ONE/W(IR) - IF (I .EQ. N) GOTO 220 - IZA=IZ - DO 210 J=I,NM - IR=IR+I - SUM=ZERO - DO 200 K=IZA,IZ,N - SUM=SUM+W(K)*W(IR) - 200 IR=IR+1 - IZ=IZ+N - 210 W(IZ)=-SUM/W(IR) - 220 CONTINUE -C -C SET THE INITIAL VALUES OF SOME VARIABLES. -C ITERC COUNTS THE NUMBER OF ITERATIONS. -C ITREF IS SET TO ONE WHEN ITERATIVE REFINEMENT IS REQUIRED. -C JFINC INDICATES WHEN TO TEST FOR AN INCREASE IN F. -C - ITERC=1 - ITREF=0 - JFINC=-KFINC -C -C SET X TO ZERO AND SET THE CORRESPONDING RESIDUALS OF THE -C KUHN-TUCKER CONDITIONS. -C - 230 IFLAG=1 - IWS=IWW-N - DO 240 I=1,N - X(I)=ZERO - IW=IWW+I - W(IW)=GRAD(I) - IF (I .GT. NACT) GOTO 240 - W(I)=ZERO - IS=IWS+I - K=IACT(I) - IF (K .LE. M) GOTO 235 - IF (K .GT. MN) GOTO 234 - K1=K-M - W(IS)=XL(K1) - GOTO 240 - 234 K1=K-MN - W(IS)=-XU(K1) - GOTO 240 - 235 W(IS)=B(K) - 240 CONTINUE - XMAG=ZERO - VFACT=1.D+0 - IF (NACT) 340,340,280 -C -C SET THE RESIDUALS OF THE KUHN-TUCKER CONDITIONS FOR GENERAL X. -C - 250 IFLAG=2 - IWS=IWW-N - DO 260 I=1,N - IW=IWW+I - W(IW)=GRAD(I) - IF (LQL) GOTO 259 - ID=IWD+I - W(ID)=ZERO - DO 251 J=I,N - 251 W(ID)=W(ID)+G(I,J)*X(J) - DO 252 J=1,I - ID=IWD+J - 252 W(IW)=W(IW)+G(J,I)*W(ID) - GOTO 260 - 259 DO 261 J=1,N - 261 W(IW)=W(IW)+G(I,J)*X(J) - 260 CONTINUE - IF (NACT .EQ. 0) GOTO 340 - DO 270 K=1,NACT - KK=IACT(K) - IS=IWS+K - IF (KK .GT. M) GOTO 265 - W(IS)=B(KK) - DO 264 I=1,N - IW=IWW+I - W(IW)=W(IW)-W(K)*A(KK,I) - 264 W(IS)=W(IS)-X(I)*A(KK,I) - GOTO 270 - 265 IF (KK .GT. MN) GOTO 266 - K1=KK-M - IW=IWW+K1 - W(IW)=W(IW)-W(K) - W(IS)=XL(K1)-X(K1) - GOTO 270 - 266 K1=KK-MN - IW=IWW+K1 - W(IW)=W(IW)+W(K) - W(IS)=-XU(K1)+X(K1) - 270 CONTINUE -C -C PRE-MULTIPLY THE VECTOR IN THE S-PARTITION OF W BY THE -C INVERS OF R TRANSPOSE. -C - 280 IR=IWR - IP=IWW+1 - IPP=IWW+N - IL=IWS+1 - IU=IWS+NACT - DO 310 I=IL,IU - SUM=ZERO - IF (I .EQ. IL) GOTO 300 - JU=I-1 - DO 290 J=IL,JU - IR=IR+1 - 290 SUM=SUM+W(IR)*W(J) - 300 IR=IR+1 - 310 W(I)=(W(I)-SUM)/W(IR) -C -C SHIFT X TO SATISFY THE ACTIVE CONSTRAINTS AND MAKE THE -C CORRESPONDING CHANGE TO THE GRADIENT RESIDUALS. -C - DO 330 I=1,N - IZ=IWZ+I - SUM=ZERO - DO 320 J=IL,IU - SUM=SUM+W(J)*W(IZ) - 320 IZ=IZ+N - X(I)=X(I)+SUM - IF (LQL) GOTO 329 - ID=IWD+I - W(ID)=ZERO - DO 321 J=I,N - 321 W(ID)=W(ID)+G(I,J)*SUM - IW=IWW+I - DO 322 J=1,I - ID=IWD+J - 322 W(IW)=W(IW)+G(J,I)*W(ID) - GOTO 330 - 329 DO 331 J=1,N - IW=IWW+J - 331 W(IW)=W(IW)+SUM*G(I,J) - 330 CONTINUE -C -C FORM THE SCALAR PRODUCT OF THE CURRENT GRADIENT RESIDUALS -C WITH EACH COLUMN OF Z. -C - 340 KFLAG=1 - GOTO 930 - 350 IF (NACT .EQ. N) GOTO 380 -C -C SHIFT X SO THAT IT SATISFIES THE REMAINING KUHN-TUCKER -C CONDITIONS. -C - IL=IWS+NACT+1 - IZA=IWZ+NACT*N - DO 370 I=1,N - SUM=ZERO - IZ=IZA+I - DO 360 J=IL,IWW - SUM=SUM+W(IZ)*W(J) - 360 IZ=IZ+N - 370 X(I)=X(I)-SUM - INFO=0 - IF (NACT .EQ. 0) GOTO 410 -C -C UPDATE THE LAGRANGE MULTIPLIERS. -C - 380 LFLAG=3 - GOTO 740 - 390 DO 400 K=1,NACT - IW=IWW+K - 400 W(K)=W(K)+W(IW) -C -C REVISE THE VALUES OF XMAG. -C BRANCH IF ITERATIVE REFINEMENT IS REQUIRED. -C - 410 JFLAG=1 - GOTO 910 - 420 IF (IFLAG .EQ. ITREF) GOTO 250 -C -C DELETE A CONSTRAINT IF A LAGRANGE MULTIPLIER OF AN -C INEQUALITY CONSTRAINT IS NEGATIVE. -C - KDROP=0 - GOTO 440 - 430 KDROP=KDROP+1 - IF (W(KDROP) .GE. ZERO) GOTO 440 - IF (IACT(KDROP) .LE. MEQ) GOTO 440 - NU=NACT - MFLAG=1 - GOTO 800 - 440 IF (KDROP .LT. NACT) GOTO 430 -C -C SEEK THE GREATEAST NORMALISED CONSTRAINT VIOLATION, DISREGARDING -C ANY THAT MAY BE DUE TO COMPUTER ROUNDING ERRORS. -C - 450 CVMAX=ZERO - IF (M .LE. 0) GOTO 481 - DO 480 K=1,M - IA=IWA+K - IF (W(IA) .LE. ZERO) GOTO 480 - SUM=-B(K) - DO 460 I=1,N - 460 SUM=SUM+X(I)*A(K,I) - SUMX=-SUM*W(IA) - IF (K .LE. MEQ) SUMX=DABS(SUMX) - IF (SUMX .LE. CVMAX) GOTO 480 - TEMP=DABS(B(K)) - DO 470 I=1,N - 470 TEMP=TEMP+DABS(X(I)*A(K,I)) - TEMPA=TEMP+DABS(SUM) - IF (TEMPA .LE. TEMP) GOTO 480 - TEMP=TEMP+ONHA*DABS(SUM) - IF (TEMP .LE. TEMPA) GOTO 480 - CVMAX=SUMX - RES=SUM - KNEXT=K - 480 CONTINUE - 481 DO 485 K=1,N - LOWER=.TRUE. - IA=IWA+M+K - IF (W(IA) .LE. ZERO) GOTO 485 - SUM=XL(K)-X(K) - IF (SUM) 482,485,483 - 482 SUM=X(K)-XU(K) - LOWER=.FALSE. - 483 IF (SUM .LE. CVMAX) GOTO 485 - CVMAX=SUM - RES=-SUM - KNEXT=K+M - IF (LOWER) GOTO 485 - KNEXT=K+MN - 485 CONTINUE -C -C TEST FOR CONVERGENCE -C - INFO=0 - IF (CVMAX .LE. VSMALL) GOTO 700 -C -C RETURN IF, DUE TO ROUNDING ERRORS, THE ACTUAL CHANGE IN -C X MAY NOT INCREASE THE OBJECTIVE FUNCTION -C - JFINC=JFINC+1 - IF (JFINC .EQ. 0) GOTO 510 - IF (JFINC .NE. IFINC) GOTO 530 - FDIFF=ZERO - FDIFFA=ZERO - DO 500 I=1,N - SUM=TWO*GRAD(I) - SUMX=DABS(SUM) - IF (LQL) GOTO 489 - ID=IWD+I - W(ID)=ZERO - DO 486 J=I,N - IX=IWX+J - 486 W(ID)=W(ID)+G(I,J)*(W(IX)+X(J)) - DO 487 J=1,I - ID=IWD+J - TEMP=G(J,I)*W(ID) - SUM=SUM+TEMP - 487 SUMX=SUMX+DABS(TEMP) - GOTO 495 - 489 DO 490 J=1,N - IX=IWX+J - TEMP=G(I,J)*(W(IX)+X(J)) - SUM=SUM+TEMP - 490 SUMX=SUMX+DABS(TEMP) - 495 IX=IWX+I - FDIFF=FDIFF+SUM*(X(I)-W(IX)) - 500 FDIFFA=FDIFFA+SUMX*DABS(X(I)-W(IX)) - INFO=2 - SUM=FDIFFA+FDIFF - IF (SUM .LE. FDIFFA) GOTO 700 - TEMP=FDIFFA+ONHA*FDIFF - IF (TEMP .LE. SUM) GOTO 700 - JFINC=0 - INFO=0 - 510 DO 520 I=1,N - IX=IWX+I - 520 W(IX)=X(I) -C -C FORM THE SCALAR PRODUCT OF THE NEW CONSTRAINT NORMAL WITH EACH -C COLUMN OF Z. PARNEW WILL BECOME THE LAGRANGE MULTIPLIER OF -C THE NEW CONSTRAINT. -C - 530 ITERC=ITERC+1 - IF (ITERC.LE.MAXIT) GOTO 531 - INFO=1 - GOTO 710 - 531 CONTINUE - IWS=IWR+(NACT+NACT*NACT)/2 - IF (KNEXT .GT. M) GOTO 541 - DO 540 I=1,N - IW=IWW+I - 540 W(IW)=A(KNEXT,I) - GOTO 549 - 541 DO 542 I=1,N - IW=IWW+I - 542 W(IW)=ZERO - K1=KNEXT-M - IF (K1 .GT. N) GOTO 545 - IW=IWW+K1 - W(IW)=ONE - IZ=IWZ+K1 - DO 543 I=1,N - IS=IWS+I - W(IS)=W(IZ) - 543 IZ=IZ+N - GOTO 550 - 545 K1=KNEXT-MN - IW=IWW+K1 - W(IW)=-ONE - IZ=IWZ+K1 - DO 546 I=1,N - IS=IWS+I - W(IS)=-W(IZ) - 546 IZ=IZ+N - GOTO 550 - 549 KFLAG=2 - GOTO 930 - 550 PARNEW=ZERO -C -C APPLY GIVENS ROTATIONS TO MAKE THE LAST (N-NACT-2) SCALAR -C PRODUCTS EQUAL TO ZERO. -C - IF (NACT .EQ. N) GOTO 570 - NU=N - NFLAG=1 - GOTO 860 -C -C BRANCH IF THERE IS NO NEED TO DELETE A CONSTRAINT. -C - 560 IS=IWS+NACT - IF (NACT .EQ. 0) GOTO 640 - SUMA=ZERO - SUMB=ZERO - SUMC=ZERO - IZ=IWZ+NACT*N - DO 563 I=1,N - IZ=IZ+1 - IW=IWW+I - SUMA=SUMA+W(IW)*W(IZ) - SUMB=SUMB+DABS(W(IW)*W(IZ)) - 563 SUMC=SUMC+W(IZ)**2 - TEMP=SUMB+.1D+0*DABS(SUMA) - TEMPA=SUMB+.2D+0*DABS(SUMA) - IF (TEMP .LE. SUMB) GOTO 570 - IF (TEMPA .LE. TEMP) GOTO 570 - IF (SUMB .GT. VSMALL) GOTO 5 - GOTO 570 - 5 SUMC=DSQRT(SUMC) - IA=IWA+KNEXT - IF (KNEXT .LE. M) SUMC=SUMC/W(IA) - TEMP=SUMC+.1D+0*DABS(SUMA) - TEMPA=SUMC+.2D+0*DABS(SUMA) - IF (TEMP .LE. SUMC) GOTO 567 - IF (TEMPA .LE. TEMP) GOTO 567 - GOTO 640 -C -C CALCULATE THE MULTIPLIERS FOR THE NEW CONSTRAINT NORMAL -C EXPRESSED IN TERMS OF THE ACTIVE CONSTRAINT NORMALS. -C THEN WORK OUT WHICH CONTRAINT TO DROP. -C - 567 LFLAG=4 - GOTO 740 - 570 LFLAG=1 - GOTO 740 -C -C COMPLETE THE TEST FOR LINEARLY DEPENDENT CONSTRAINTS. -C - 571 IF (KNEXT .GT. M) GOTO 574 - DO 573 I=1,N - SUMA=A(KNEXT,I) - SUMB=DABS(SUMA) - IF (NACT.EQ.0) GOTO 581 - DO 572 K=1,NACT - KK=IACT(K) - IF (KK.LE.M) GOTO 568 - KK=KK-M - TEMP=ZERO - IF (KK.EQ.I) TEMP=W(IWW+KK) - KK=KK-N - IF (KK.EQ.I) TEMP=-W(IWW+KK) - GOTO 569 - 568 CONTINUE - IW=IWW+K - TEMP=W(IW)*A(KK,I) - 569 CONTINUE - SUMA=SUMA-TEMP - 572 SUMB=SUMB+DABS(TEMP) - 581 IF (SUMA .LE. VSMALL) GOTO 573 - TEMP=SUMB+.1D+0*DABS(SUMA) - TEMPA=SUMB+.2D+0*DABS(SUMA) - IF (TEMP .LE. SUMB) GOTO 573 - IF (TEMPA .LE. TEMP) GOTO 573 - GOTO 630 - 573 CONTINUE - LFLAG=1 - GOTO 775 - 574 K1=KNEXT-M - IF (K1 .GT. N) K1=K1-N - DO 578 I=1,N - SUMA=ZERO - IF (I .NE. K1) GOTO 575 - SUMA=ONE - IF (KNEXT .GT. MN) SUMA=-ONE - 575 SUMB=DABS(SUMA) - IF (NACT.EQ.0) GOTO 582 - DO 577 K=1,NACT - KK=IACT(K) - IF (KK .LE. M) GOTO 579 - KK=KK-M - TEMP=ZERO - IF (KK.EQ.I) TEMP=W(IWW+KK) - KK=KK-N - IF (KK.EQ.I) TEMP=-W(IWW+KK) - GOTO 576 - 579 IW=IWW+K - TEMP=W(IW)*A(KK,I) - 576 SUMA=SUMA-TEMP - 577 SUMB=SUMB+DABS(TEMP) - 582 TEMP=SUMB+.1D+0*DABS(SUMA) - TEMPA=SUMB+.2D+0*DABS(SUMA) - IF (TEMP .LE. SUMB) GOTO 578 - IF (TEMPA .LE. TEMP) GOTO 578 - GOTO 630 - 578 CONTINUE - LFLAG=1 - GOTO 775 -C -C BRANCH IF THE CONTRAINTS ARE INCONSISTENT. -C - 580 INFO=-KNEXT - IF (KDROP .EQ. 0) GOTO 700 - PARINC=RATIO - PARNEW=PARINC -C -C REVISE THE LAGRANGE MULTIPLIERS OF THE ACTIVE CONSTRAINTS. -C - 590 IF (NACT.EQ.0) GOTO 601 - DO 600 K=1,NACT - IW=IWW+K - W(K)=W(K)-PARINC*W(IW) - IF (IACT(K) .GT. MEQ) W(K)=DMAX1(ZERO,W(K)) - 600 CONTINUE - 601 IF (KDROP .EQ. 0) GOTO 680 -C -C DELETE THE CONSTRAINT TO BE DROPPED. -C SHIFT THE VECTOR OF SCALAR PRODUCTS. -C THEN, IF APPROPRIATE, MAKE ONE MORE SCALAR PRODUCT ZERO. -C - NU=NACT+1 - MFLAG=2 - GOTO 800 - 610 IWS=IWS-NACT-1 - NU=MIN0(N,NU) - DO 620 I=1,NU - IS=IWS+I - J=IS+NACT - 620 W(IS)=W(J+1) - NFLAG=2 - GOTO 860 -C -C CALCULATE THE STEP TO THE VIOLATED CONSTRAINT. -C - 630 IS=IWS+NACT - 640 SUMY=W(IS+1) - STEP=-RES/SUMY - PARINC=STEP/SUMY - IF (NACT .EQ. 0) GOTO 660 -C -C CALCULATE THE CHANGES TO THE LAGRANGE MULTIPLIERS, AND REDUCE -C THE STEP ALONG THE NEW SEARCH DIRECTION IF NECESSARY. -C - LFLAG=2 - GOTO 740 - 650 IF (KDROP .EQ. 0) GOTO 660 - TEMP=ONE-RATIO/PARINC - IF (TEMP .LE. ZERO) KDROP=0 - IF (KDROP .EQ. 0) GOTO 660 - STEP=RATIO*SUMY - PARINC=RATIO - RES=TEMP*RES -C -C UPDATE X AND THE LAGRANGE MULTIPIERS. -C DROP A CONSTRAINT IF THE FULL STEP IS NOT TAKEN. -C - 660 IWY=IWZ+NACT*N - DO 670 I=1,N - IY=IWY+I - 670 X(I)=X(I)+STEP*W(IY) - PARNEW=PARNEW+PARINC - IF (NACT .GE. 1) GOTO 590 -C -C ADD THE NEW CONSTRAINT TO THE ACTIVE SET. -C - 680 NACT=NACT+1 - W(NACT)=PARNEW - IACT(NACT)=KNEXT - IA=IWA+KNEXT - IF (KNEXT .GT. MN) IA=IA-N - W(IA)=-W(IA) -C -C ESTIMATE THE MAGNITUDE OF X. THEN BEGIN A NEW ITERATION, -C RE-INITILISING X IF THIS MAGNITUDE IS SMALL. -C - JFLAG=2 - GOTO 910 - 690 IF (SUM .LT. (XMAGR*XMAG)) GOTO 230 - IF (ITREF) 450,450,250 -C -C INITIATE ITERATIVE REFINEMENT IF IT HAS NOT YET BEEN USED, -C OR RETURN AFTER RESTORING THE DIAGONAL ELEMENTS OF G. -C - 700 IF (ITERC .EQ. 0) GOTO 710 - ITREF=ITREF+1 - JFINC=-1 - IF (ITREF .EQ. 1) GOTO 250 - 710 IF (.NOT. LQL) RETURN - DO 720 I=1,N - ID=IWD+I - 720 G(I,I)=W(ID) - 730 RETURN -C -C -C THE REMAINIG INSTRUCTIONS ARE USED AS SUBROUTINES. -C -C -C******************************************************************** -C -C -C CALCULATE THE LAGRANGE MULTIPLIERS BY PRE-MULTIPLYING THE -C VECTOR IN THE S-PARTITION OF W BY THE INVERSE OF R. -C - 740 IR=IWR+(NACT+NACT*NACT)/2 - I=NACT - SUM=ZERO - GOTO 770 - 750 IRA=IR-1 - SUM=ZERO - IF (NACT.EQ.0) GOTO 761 - DO 760 J=I,NACT - IW=IWW+J - SUM=SUM+W(IRA)*W(IW) - 760 IRA=IRA+J - 761 IR=IR-I - I=I-1 - 770 IW=IWW+I - IS=IWS+I - W(IW)=(W(IS)-SUM)/W(IR) - IF (I .GT. 1) GOTO 750 - IF (LFLAG .EQ. 3) GOTO 390 - IF (LFLAG .EQ. 4) GOTO 571 -C -C CALCULATE THE NEXT CONSTRAINT TO DROP. -C - 775 IP=IWW+1 - IPP=IWW+NACT - KDROP=0 - IF (NACT.EQ.0) GOTO 791 - DO 790 K=1,NACT - IF (IACT(K) .LE. MEQ) GOTO 790 - IW=IWW+K - IF ((RES*W(IW)) .GE. ZERO) GOTO 790 - TEMP=W(K)/W(IW) - IF (KDROP .EQ. 0) GOTO 780 - IF (DABS(TEMP) .GE. DABS(RATIO)) GOTO 790 - 780 KDROP=K - RATIO=TEMP - 790 CONTINUE - 791 GOTO (580,650), LFLAG -C -C -C******************************************************************** -C -C -C DROP THE CONSTRAINT IN POSITION KDROP IN THE ACTIVE SET. -C - 800 IA=IWA+IACT(KDROP) - IF (IACT(KDROP) .GT. MN) IA=IA-N - W(IA)=-W(IA) - IF (KDROP .EQ. NACT) GOTO 850 -C -C SET SOME INDICES AND CALCULATE THE ELEMENTS OF THE NEXT -C GIVENS ROTATION. -C - IZ=IWZ+KDROP*N - IR=IWR+(KDROP+KDROP*KDROP)/2 - 810 IRA=IR - IR=IR+KDROP+1 - TEMP=DMAX1(DABS(W(IR-1)),DABS(W(IR))) - SUM=TEMP*DSQRT((W(IR-1)/TEMP)**2+(W(IR)/TEMP)**2) - GA=W(IR-1)/SUM - GB=W(IR)/SUM -C -C EXCHANGE THE COLUMNS OF R. -C - DO 820 I=1,KDROP - IRA=IRA+1 - J=IRA-KDROP - TEMP=W(IRA) - W(IRA)=W(J) - 820 W(J)=TEMP - W(IR)=ZERO -C -C APPLY THE ROTATION TO THE ROWS OF R. -C - W(J)=SUM - KDROP=KDROP+1 - DO 830 I=KDROP,NU - TEMP=GA*W(IRA)+GB*W(IRA+1) - W(IRA+1)=GA*W(IRA+1)-GB*W(IRA) - W(IRA)=TEMP - 830 IRA=IRA+I -C -C APPLY THE ROTATION TO THE COLUMNS OF Z. -C - DO 840 I=1,N - IZ=IZ+1 - J=IZ-N - TEMP=GA*W(J)+GB*W(IZ) - W(IZ)=GA*W(IZ)-GB*W(J) - 840 W(J)=TEMP -C -C REVISE IACT AND THE LAGRANGE MULTIPLIERS. -C - IACT(KDROP-1)=IACT(KDROP) - W(KDROP-1)=W(KDROP) - IF (KDROP .LT. NACT) GOTO 810 - 850 NACT=NACT-1 - GOTO (250,610), MFLAG -C -C -C******************************************************************** -C -C -C APPLY GIVENS ROTATION TO REDUCE SOME OF THE SCALAR -C PRODUCTS IN THE S-PARTITION OF W TO ZERO. -C - 860 IZ=IWZ+NU*N - 870 IZ=IZ-N - 880 IS=IWS+NU - NU=NU-1 - IF (NU .EQ. NACT) GOTO 900 - IF (W(IS) .EQ. ZERO) GOTO 870 - TEMP=DMAX1(DABS(W(IS-1)),DABS(W(IS))) - SUM=TEMP*DSQRT((W(IS-1)/TEMP)**2+(W(IS)/TEMP)**2) - GA=W(IS-1)/SUM - GB=W(IS)/SUM - W(IS-1)=SUM - DO 890 I=1,N - K=IZ+N - TEMP=GA*W(IZ)+GB*W(K) - W(K)=GA*W(K)-GB*W(IZ) - W(IZ)=TEMP - 890 IZ=IZ-1 - GOTO 880 - 900 GOTO (560,630), NFLAG -C -C -C******************************************************************** -C -C -C CALCULATE THE MAGNITUDE OF X AN REVISE XMAG. -C - 910 SUM=ZERO - DO 920 I=1,N - SUM=SUM+DABS(X(I))*VFACT*(DABS(GRAD(I))+DABS(G(I,I)*X(I))) - IF (LQL) GOTO 920 - IF (SUM .LT. 1.D-30) GOTO 920 - VFACT=1.D-10*VFACT - SUM=1.D-10*SUM - XMAG=1.D-10*XMAG - 920 CONTINUE - 925 XMAG=DMAX1(XMAG,SUM) - GOTO (420,690), JFLAG -C -C -C******************************************************************** -C -C -C PRE-MULTIPLY THE VECTOR IN THE W-PARTITION OF W BY Z TRANSPOSE. -C - 930 JL=IWW+1 - IZ=IWZ - DO 940 I=1,N - IS=IWS+I - W(IS)=ZERO - IWWN=IWW+N - DO 940 J=JL,IWWN - IZ=IZ+1 - 940 W(IS)=W(IS)+W(IZ)*W(J) - GOTO (350,550), KFLAG - RETURN - END diff --git a/pyoptsparse/pyoptsparse/pyIPOPT/__init__.py b/pyoptsparse/pyoptsparse/pyIPOPT/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyIPOPT/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyIPOPT/pyIPOPT.py b/pyoptsparse/pyoptsparse/pyIPOPT/pyIPOPT.py deleted file mode 100644 index 7446813f0..000000000 --- a/pyoptsparse/pyoptsparse/pyIPOPT/pyIPOPT.py +++ /dev/null @@ -1,597 +0,0 @@ -#/bin/env python -""" -pyIPOPT - A python wrapper to the core IPOPT compiled module. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) -- Dr. Graeme Kennedy (GJK) -History -------- - v. 0.1 - Initial Wrapper Creation -""" -# ============================================================================= -# IPOPT Library -# ============================================================================= - -try: - from . import pyipoptcore -except ImportError: - pyipoptcore = None - -# ============================================================================= -# standard Python modules -# ============================================================================= -import copy -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy - -# ============================================================================= -# Extension modules -# ============================================================================= -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -from ..pyOpt_utils import IROW, ICOL, convertToCOO, extractRows, scaleRows -# ============================================================================= -# IPOPT Optimizer Class -# ============================================================================= -class IPOPT(Optimizer): - """ - IPOPT Optimizer Class - Inherited from Optimizer Abstract Class - """ - - def __init__(self, *args, **kwargs): - """ - IPOPT Optimizer Class Initialization - """ - - name = 'IPOPT' - category = 'Local Optimizer' - - # These options are documented on the website: - # http://www.coin-or.org/Ipopt/documentation/node39.html - # accessed on March 26, 2014. - - def_opts = { - 'print_level' : [int, 0], - 'output_file': [str, 'IPOPT.out'], - # Output verbosity level. '0-12' - 'file_print_level' : [int, 5], - 'print_user_options' : [str, "no"], - 'print_options_documentation' : [str, "no"], - 'print_timing_statistics' : [str, "no"], - 'option_file_name' : [str, "IPOPT_options.opt"], - 'replace_bounds' : [str, "no"], - 'skip_finalize_solution_call' : [str, "no"], - # Enables printing of additional info string at - # end of iteration output. - 'print_info_string' : [str, "no"], - # Determines what value is printed in the "inf_pr" - # output column. 'internal' or 'original' - 'inf_pr_output' : [str, "original"], # - 'print_frequency_iter' : [int, 1], - # Determines at which time frequency the - # summarizing iteration output line should be - # printed. - 'print_frequency_time' : [float, 0.], # - - # Convergence. - # 's_max' : 100.0, # - 'tol' : [float, 1e-06], - 'max_iter' : [int, 100], - 'max_cpu_time' : [float, 1e+06], - 'dual_inf_tol' : [float, 1.0], - 'constr_viol_tol' : [float, 0.0001], - 'compl_inf_tol' : [float, 0.0001], - 'acceptable_tol' : [float, 1e-06], - 'acceptable_iter' : [int, 15], - 'acceptable_dual_inf_tol' : [float, 1e+10], - 'acceptable_constr_viol_tol' : [float, 0.01], - 'acceptable_compl_inf_tol' : [float, 0.01], - 'acceptable_obj_change_tol' : [float, 1e+20], - 'diverging_iterates_tol' : [float, 1e+20], - 'mu_target' : [float, 0.0], - - # NLP Scaling. - 'nlp_scaling_method' : [str, "gradient-based"], - 'obj_scaling_factor' : [float, 1.], - 'nlp_scaling_max_gradient' : [float, 100.0], - 'nlp_scaling_obj_target_gradient' : [float, 0.0], - 'nlp_scaling_constr_target_gradient' : [float, 0.0], - 'nlp_scaling_min_value' : [float, 1e-08], - - # NLP. - 'nlp_lower_bound_inf' : [float, -1e+19], - 'nlp_upper_bound_inf' : [float, 1e+19], - 'fixed_variable_treatment' : [str, "make_parameter"], - 'dependency_detector' : [str, "none"], - 'dependency_detection_with_rhs' : [str, "no"], - 'num_linear_variables' : [int, 0], - 'kappa_d' : [float, 1e-05], - 'bound_relax_factor' : [float, 1e-08], - 'honor_original_bounds' : [str, "yes"], - 'check_derivatives_for_naninf' : [str, "no"], - 'jac_c_constant' : [str, "no"], - 'jac_d_constant' : [str, "no"], - 'hessian_constant' : [str, "no"], - - # Initialization. - 'bound_push' : [float, 0.01], - 'bound_frac' : [float, 0.01], - 'slack_bound_push' : [float, 0.01], - 'slack_bound_frac' : [float, 0.01], - 'constr_mult_init_max' : [float, 1000.0], - 'bound_mult_init_val' : [float, 1.0], - 'bound_mult_init_method' : [str, "constant"], - 'least_square_init_primal' : [str, "no"], - 'least_square_init_duals' : [str, "no"], - - # Barrier parameter update. - 'mu_max_fact' : [float, 1000.0], - 'mu_max' : [float, 100000.0], - 'mu_min' : [float, 1e-11], - # Controls how the globalization strategy is applied - # when the adaptive mu strategy is employed. This - # controls what quantity is used to control the switch back - # to monotone mode. Other options are: 'kkt-error', and - # 'never-monotone-mode' which disables globalization - 'adaptive_mu_globalization' : [str, "obj-constr-filter"], - 'adaptive_mu_kkterror_red_iters' : [float, 4], - 'adaptive_mu_kkterror_red_fact' : [float, 0.9999], - 'filter_margin_fact' : [float, 1e-05], - 'filter_max_margin' : [float, 1.0], - 'adaptive_mu_restore_previous_iterate' : [str, "no"], - 'adaptive_mu_monotone_init_factor' : [float, 0.8], - 'adaptive_mu_kkt_norm_type' : [str, "2-norm-squared"], - # Use the mu update strategy: Defaults to - # Fiacco-McCormick monotone, the other option is - # 'adaptive' - 'mu_strategy' : [str, "monotone"], - # Select the method used to pick the next mu in - # the adaptive strategy: Other options: 'loqo': - # the LOQO adaptive barrier strategy and - # 'probing': Mehrotra's probing method - 'mu_oracle' : [str, "quality-function"], - 'fixed_mu_oracle' : [str, "average_compl"], - - # Options for the barrier strategy in IPOPT - - # these can make a big difference in the - # performance of the IP algorithm. - 'mu_init' : [float, 0.1], - # Parameter that controls how tightly each barrier - # problem is solved before the next mu update. A scaled - # version of: ||KKT||_{infty} < mu*barrier_tol_factor - 'barrier_tol_factor' : [float, 10.0], - # For the monotone strategy, decrease the value of - # mu by this fixed fraction after each barrrier - # problem is solved - 'mu_linear_decrease_factor' : [float, 0.2], - # Use the min of the linear decrease factor and - # mu**(mu_superlinear_decrease_power) for the next - # barrier value: enables superlinear rates of - # convergence - 'mu_superlinear_decrease_power' : [float, 1.5], - 'mu_allow_fast_monotone_decrease' : [str, "yes"], - 'tau_min' : [float, 0.99], - 'sigma_max' : [float, 100.0], - 'sigma_min' : [float, 1e-06], - 'quality_function_norm_type' : [str, "2-norm-squared"], - 'quality_function_centrality' : [str, "none"], - 'quality_function_balancing_term' : [str, "none"], - 'quality_function_max_section_steps' : [int, 8], - 'quality_function_section_sigma_tol' : [float, 0.01], - 'quality_function_section_qf_tol' : [float, 0.0], - - # Line Search. - 'line_search_method' : [str, "filter"], - 'alpha_red_factor' : [float, 0.5], - 'accept_every_trial_step' : [str, "no"], - 'accept_after_max_steps' : [int, -1], - 'alpha_for_y' : [str, "primal"], - 'alpha_for_y_tol' : [float, 10.0], - 'tiny_step_tol' : [float, 2.22045e-15], - 'tiny_step_y_tol' : [float, 0.01], - 'watchdog_shortened_iter_trigger' : [int, 10], - 'watchdog_trial_iter_max' : [int, 3], - 'theta_max_fact' : [float, 10000.0], - 'theta_min_fact' : [float, 0.0001], - 'eta_phi' : [float, 1e-08], - 'delta' : [float, 1.0], - 's_phi' : [float, 2.3], - 's_theta' : [float, 1.1], - 'gamma_phi' : [float, 1e-08], - 'gamma_theta' : [float, 1e-05], - 'alpha_min_frac' : [float, 0.05], - # Maximum number of second order correction trial - # steps at each iteration - 'max_soc' : [int, 4], - 'kappa_soc' : [float, 0.99], - 'obj_max_inc' : [float, 5.0], - 'max_filter_resets' : [int, 5], - 'filter_reset_trigger' : [int, 5], - 'corrector_type' : [str, "none"], - 'skip_corr_if_neg_curv' : [str, "yes"], - 'skip_corr_in_monotone_mode' : [str, "yes"], - 'corrector_compl_avrg_red_fact' : [float, 1.0], - 'nu_init' : [float, 1e-06], - 'nu_inc' : [float, 0.0001], - 'rho' : [float, 0.1], - 'kappa_sigma' : [float, 1e+10], - 'recalc_y' : [str, "no"], - 'recalc_y_feas_tol' : [float, 1e-06], - 'slack_move' : [float, 1.81899e-12], - 'constraint_violation_norm_type' : [str, "1-norm"], - - # Warm Start. - 'warm_start_init_point' : [str, "no"], - 'warm_start_same_structure' : [str, "no"], - 'warm_start_bound_push' : [float, 0.001], - 'warm_start_bound_frac' : [float, 0.001], - 'warm_start_slack_bound_push' : [float, 0.001], - 'warm_start_slack_bound_frac' : [float, 0.001], - 'warm_start_mult_bound_push' : [float, 0.001], - 'warm_start_mult_init_max' : [float, 1e+06], - 'warm_start_entire_iterate' : [float, "no"], - - # Linear Solver. - 'linear_solver' : [str, "ma27"], - 'linear_system_scaling' : [str, "none"], # Had been "mc19", but not always available. - 'linear_scaling_on_demand' : [str, "yes"], - - # Step Calculation. - # Use Mehrotra's predictor-corrector algorithm - - # warning: no globalization - 'mehrotra_algorithm' : [str, "no"], - 'fast_step_computation' : [str, "no"], - 'min_refinement_steps' : [int, 1], - 'max_refinement_steps' : [int, 10], - 'residual_ratio_max' : [float, 1e-10], - 'residual_ratio_singular' : [float, 1e-05], - 'residual_improvement_factor' : [float, 1.0], - 'neg_curv_test_tol' : [float, 1.0], - 'max_hessian_perturbation' : [float, 1e+20], - 'min_hessian_perturbation' : [float, 1e-20], - 'perturb_inc_fact_first' : [float, 100.0], - 'perturb_inc_fact' : [float, 8.0], - 'perturb_dec_fact' : [float, 0.333333], - 'first_hessian_perturbation' : [float, 0.0001], - 'jacobian_regularization_value' : [float, 1e-08], - 'jacobian_regularization_exponent' : [float, 0.25], - 'perturb_always_cd' : [str, "no"], - - # Restoration Phase. - 'expect_infeasible_problem' : [str, "no"], - 'expect_infeasible_problem_ctol' : [float, 0.001], - 'expect_infeasible_problem_ytol' : [float, 1e+08], - 'start_with_resto' : [str, "no"], - 'soft_resto_pderror_reduction_factor' : [float, 0.9999], - 'max_soft_resto_iters' : [int, 10], - 'required_infeasibility_reduction' : [float, 0.9], - 'max_resto_iter' : [int, 3000000], - 'evaluate_orig_obj_at_resto_trial' : [str, "yes"], - 'resto_penalty_parameter' : [float, 1000.0], - 'resto_proximity_weight' : [float, 1.0], - 'bound_mult_reset_threshold' : [float, 1000.0], - 'constr_mult_reset_threshold' : [float, 0.0], - 'resto_failure_feasibility_threshold' : [float, 0.0], - - # Derivative Checker. - # Derivative Testing options - # none, first-order, second-order, only-second-order - 'derivative_test' : [str, "none"], - 'derivative_test_first_index' : [int, -2], - 'derivative_test_perturbation' : [float, 1e-08], - 'derivative_test_tol' : [float, 1e-4], - 'derivative_test_print_all' : [str, "no"], - 'jacobian_approximation' : [str, "exact"], - 'findiff_perturbation' : [float, 1e-07], - 'point_perturbation_radius' : [float, 10.0], - - # Hessian Approximation. - 'limited_memory_aug_solver' : [str, "sherman-morrison"], - 'limited_memory_max_history' : [int, 6], - 'limited_memory_update_type' : [str, "bfgs"], - 'limited_memory_initialization' : [str, "scalar1"], - 'limited_memory_init_val' : [float, 1.0], - 'limited_memory_init_val_max' : [float, 1e+08], - 'limited_memory_init_val_min' : [float, 1e-08], - 'limited_memory_max_skipping' : [int, 2], - 'limited_memory_special_for_resto' : [str, "no"], - 'hessian_approximation':[str, 'limited-memory'], - 'hessian_approximation_space' : [str, "nonlinear-variables"], - - # MA27 Linear Solver. - 'ma27_pivtol' : [float, 1e-08], - 'ma27_pivtolmax' : [float, 0.0001], - 'ma27_liw_init_factor' : [float, 5.0], - 'ma27_la_init_factor' : [float, 5.0], - 'ma27_meminc_factor' : [float, 10.0], - 'ma27_skip_inertia_check' : [str, "no"], - 'ma27_ignore_singularity' : [str, "no"], - - # # MA57 Linear Solver. - # 'ma57_pivtol' : [float, 1e-08], - # 'ma57_pivtolmax' : [float, 0.0001], - # 'ma57_pre_alloc' : [float, 1.05], - # 'ma57_pivot_order' : [int, 5], - # 'ma57_automatic_scaling' : [str, "yes"], # ipopt default is "no". - # 'ma57_block_size' : [int, 16], - # 'ma57_node_amalgamation' : [int, 16], - # 'ma57_small_pivot_flag' : [int, 0], - - # # Paridiso Linear Solver. - # 'pardiso_matching_strategy' : [str, "complete+2x2"], - # 'pardiso_redo_symbolic_fact_only_if_inertia_wrong' : [str, "no"], - # 'pardiso_repeated_perturbation_means_singular' : [str, "no"], - # 'pardiso_msglvl' : [int, 0], - # 'pardiso_skip_inertia_check' : [str, "no"], - # 'pardiso_max_iter' : [int, 500], - # 'pardiso_iter_relative_tol' : [float, 1e-06], - # 'pardiso_iter_coarse_size' : [int, 5000], - # 'pardiso_iter_max_levels' : [int, 10000], - # 'pardiso_iter_dropping_factor' : [float, 0.5], - # 'pardiso_iter_dropping_schur' : [float, 0.1], - # 'pardiso_iter_max_row_fill' : [int, 10000000], - # 'pardiso_iter_inverse_norm_factor' : [float, 5e+06], - # 'pardiso_iterative' : [str, "no"], - # 'pardiso_max_droptol_corrections' : [int, 4], - - # # Mumps Linear Solver. - # 'mumps_pivtol' : [float, 1e-06], - # 'mumps_pivtolmax' : [float, 0.1], - # 'mumps_mem_percent' : [int, 1000], - # 'mumps_permuting_scaling' : [int, 7], - # 'mumps_pivot_order' : [int, 7], - # 'mumps_scaling' : [int, 77], - # 'mumps_dep_tol' : [float, -1.0], - - # # MA28 Linear Solver. - # 'ma28_pivtol' : [float, 0.01], - - # # Uncategorized. - # 'warm_start_target_mu' : [float, 0.0] - } - - informs = { # Don't have any of these yet either.. - } - - if pyipoptcore is None: - raise Error('There was an error importing the compiled \ - IPOPT module') - - self.set_options = [] - Optimizer.__init__(self, name, category, def_opts, informs, *args, - **kwargs) - - # IPOPT needs jacobians in coo format - self.jacType = 'coo' - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. To explictly - use pyOptSparse gradient class to do the derivatives with - finite differenes use \'FD\'. \'sens\' may also be \'CS\' - which will cause pyOptSpare to compute the derivatives - using the complex step method. Finally, \'sens\' may be a - python function handle which is expected to compute the - sensitivities directly. For expensive function evaluations - and/or problems with large numbers of design variables - this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is \'FD\' and 1e-40j when sens is \'CS\'. - - sensMode : str - Use \'pgc\' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in \'hotStart\' must be - **IDENTICAL** to the currently supplied \'optProb\'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point does - not match the history, function and gradient evaluations - revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if len(optProb.constraints) == 0: - # If the user *actually* has an unconstrained problem, - # snopt sort of chokes with that....it has to have at - # least one constraint. So we will add one - # automatically here: - self.unconstrained = True - optProb.dummyConstraint = True - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - blx, bux, xs = self._assembleContinuousVariables() - self._setSens(sens, sensStep, sensMode) - ff = self._assembleObjective() - - # Determine the sparsity structure of the full jacobian - # ----------------------------------------------------- - - # Gather dummy data and process jacobian: - gcon = {} - for iCon in self.optProb.constraints: - gcon[iCon] = self.optProb.constraints[iCon].jac - - jac = self.optProb.processConstraintJacobian(gcon) - - if self.optProb.nCon > 0: - # We need to reorder this full jacobian...so get ordering: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'ni', 'le', 'li'], oneSided=False) - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = numpy.zeros(len(indices)) - ncon = len(indices) - jac = extractRows(jac, indices) # Does reordering - scaleRows(jac, fact) # Perform logical scaling - else: - blc = numpy.array([-1e20]) - buc = numpy.array([1e20]) - ncon = 1 - - jac = convertToCOO(jac)# Conver to coo format for IPOPT - - # We make a split here: If the rank is zero we setup the - # problem and run IPOPT, otherwise we go to the waiting loop: - - if self.optProb.comm.rank == 0: - - # Now what we need for IPOPT is precisely the .row and - # .col attributes of the fullJacobian array - matStruct = (jac['coo'][IROW].copy().astype('int_'), - jac['coo'][ICOL].copy().astype('int_')) - - # Set history/hotstart - self._setHistory(storeHistory, hotStart) - - # Define the 4 call back functions that ipopt needs: - def eval_f(x, user_data=None): - fobj, fail = self._masterFunc(x, ['fobj']) - return fobj - - def eval_g(x, user_data=None): - fcon, fail = self._masterFunc(x, ['fcon']) - return fcon.copy() - - def eval_grad_f(x, user_data=None): - gobj, fail = self._masterFunc(x, ['gobj']) - return gobj.copy() - - def eval_jac_g(x, flag, user_data=None): - if flag: - return copy.deepcopy(matStruct) - else: - gcon, fail = self._masterFunc(x, ['gcon']) - return gcon.copy() - - timeA = time.time() - nnzj = len(matStruct[0]) - nnzh = 0 - - nlp = pyipoptcore.create(len(xs), blx, bux, ncon, blc, buc, nnzj, - nnzh, eval_f, eval_grad_f, eval_g, - eval_jac_g) - - self._set_ipopt_options(nlp) - x, zl, zu, constraint_multipliers, obj, status = nlp.solve(xs) - nlp.close() - optTime = time.time()-timeA - - if self.storeHistory: - self.hist.close() - - # Store Results - sol_inform = {} - # sol_inform['value'] = inform - # sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, obj, x) - - # Indicate solution finished - self.optProb.comm.bcast(-1, root=0) - else: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _set_ipopt_options(self, nlp): - """ - set all of the the options in self.set_options in the ipopt instance nlp - """ - # Set Options from the local options dictionary - # --------------------------------------------- - - for key in self.options: - if key != 'defaults': - name = key - value = self.getOption(key) - - if isinstance(value, str): - nlp.str_option(name, value) - elif isinstance(value, float): - nlp.num_option(name, value) - elif isinstance(value, int): - nlp.int_option(name, value) - else: - print('invalid option type', type(value)) - - def _on_setOption(self, name, value): - """ - Set Optimizer Option Value (Optimizer Specific Routine) - - Documentation last updated: May. 07, 2008 - Ruben E. Perez - """ - - self.set_options.append([name, value]) - - def _on_getOption(self, name): - """ - Routine to be implemented by optimizer - """ - - pass - - def _on_getInform(self, info): - """ - Routine to be implemented by optimizer - """ - - pass - - -#============================================================================== -# IPOPT Optimizer Test -#============================================================================== -if __name__ == '__main__': - - ipopt = IPOPT() - print(ipopt) diff --git a/pyoptsparse/pyoptsparse/pyIPOPT/setup.py b/pyoptsparse/pyoptsparse/pyIPOPT/setup.py deleted file mode 100644 index 082c14418..000000000 --- a/pyoptsparse/pyoptsparse/pyIPOPT/setup.py +++ /dev/null @@ -1,52 +0,0 @@ -# Originally contributed by Lorne McIntosh. -# Modified by Eric Xu -# Further modification by random internet people. - -# You will probably have to edit this file in unpredictable ways -# if you want pyipopt to work for you, sorry. - -# When I installed Ipopt from source, I used the -# --prefix=/usr/local -# option, so this is where I want pyipopt to look for my ipopt installation. -# I only installed from source because the ipopt packaging -# for my linux distribution was buggy, -# so by the time you read this the bugs have probably been fixed -# and you will want to specify a different directory here. - -# Futher modification by Gaetan Kenway to work with the pyOptSparse -# build system. - -import os, sys -import numpy - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - - config = Configuration('pyIPOPT', parent_package, top_path) - - # Check if we have Ipopt dir....is so assume the user has setup - # stuff correctly - add_ipopt = False - if os.path.exists('pyoptsparse/pyIPOPT/Ipopt'): - IPOPT_DIR = os.path.join(top_path, 'pyoptsparse/pyIPOPT/Ipopt/') - IPOPT_LIB = os.path.join(top_path, 'pyoptsparse/pyIPOPT/Ipopt/lib') - IPOPT_INC = os.path.join(IPOPT_DIR, 'include/coin/') - add_ipopt = True - elif os.getenv('IPOPT_DIR') is not None: - IPOPT_DIR = os.getenv('IPOPT_DIR') - IPOPT_LIB = os.path.join(IPOPT_DIR, 'lib') - IPOPT_INC = os.path.join(IPOPT_DIR, 'include/coin/') - add_ipopt = True - if add_ipopt: - numpy_include = numpy.get_include() - FILES = ['src/callback.c', 'src/pyipoptcoremodule.c'] - config.add_extension('pyipoptcore', - FILES, - library_dirs=[IPOPT_LIB], - libraries=['ipopt', 'coinblas','coinhsl','coinlapack','dl','m'], - extra_link_args=['-Wl,-rpath,%s -L%s'% (IPOPT_LIB, IPOPT_LIB)], - include_dirs=[numpy_include, IPOPT_INC]) - return config - diff --git a/pyoptsparse/pyoptsparse/pyIPOPT/src/callback.c b/pyoptsparse/pyoptsparse/pyIPOPT/src/callback.c deleted file mode 100644 index 8c4ab3795..000000000 --- a/pyoptsparse/pyoptsparse/pyIPOPT/src/callback.c +++ /dev/null @@ -1,648 +0,0 @@ -/* - * Copyright (c) 2008, Eric You Xu, Washington University All rights - * reserved. Redistribution and use in source and binary forms, with or - * without modification, are permitted provided that the following conditions - * are met: - * - * Redistributions of source code must retain the above copyright notice, this - * list of conditions and the following disclaimer. * Redistributions in - * binary form must reproduce the above copyright notice, this list of - * conditions and the following disclaimer in the documentation and/or other - * materials provided with the distribution. * Neither the name of the - * Washington University nor the names of its contributors may be used to - * endorse or promote products derived from this software without specific - * prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -/* - * Added "eval_intermediate_callback" by - * OpenMDAO at NASA Glenn Research Center, 2010 and 2011 - * - * Changed logger from code contributed by alanfalloon -*/ - -#include "hook.h" -#include - -void logger(const char *fmt, ...) -{ - if (user_log_level == VERBOSE) { - va_list ap; - va_start(ap, fmt); - vprintf(fmt, ap); - va_end(ap); - printf("\n"); - fflush(stdout); - } -} - -Bool eval_intermediate_callback(Index alg_mod, /* 0 is regular, 1 is resto */ - Index iter_count, Number obj_value, - Number inf_pr, Number inf_du, - Number mu, Number d_norm, - Number regularization_size, - Number alpha_du, Number alpha_pr, - Index ls_trials, UserDataPtr data) -{ - logger("[Callback:E]intermediate_callback"); - - DispatchData *myowndata = (DispatchData *) data; - UserDataPtr user_data = (UserDataPtr) myowndata->userdata; - - long result_as_long; - Bool result_as_bool; - - PyObject *python_algmod = Py_BuildValue("i", alg_mod); - PyObject *python_iter_count = Py_BuildValue("i", iter_count); - PyObject *python_obj_value = Py_BuildValue("d", obj_value); - PyObject *python_inf_pr = Py_BuildValue("d", inf_pr); - PyObject *python_inf_du = Py_BuildValue("d", inf_du); - PyObject *python_mu = Py_BuildValue("d", mu); - PyObject *python_d_norm = Py_BuildValue("d", d_norm); - PyObject *python_regularization_size = - Py_BuildValue("d", regularization_size); - PyObject *python_alpha_du = Py_BuildValue("d", alpha_du); - PyObject *python_alpha_pr = Py_BuildValue("d", alpha_pr); - PyObject *python_ls_trials = Py_BuildValue("i", ls_trials); - - PyObject *arglist = NULL; - - if (user_data != NULL) - arglist = Py_BuildValue("(OOOOOOOOOOOO)", - python_algmod, - python_iter_count, - python_obj_value, - python_inf_pr, - python_inf_du, - python_mu, - python_d_norm, - python_regularization_size, - python_alpha_du, - python_alpha_pr, - python_ls_trials, - (PyObject *) user_data); - else - arglist = Py_BuildValue("(OOOOOOOOOOO)", - python_algmod, - python_iter_count, - python_obj_value, - python_inf_pr, - python_inf_du, - python_mu, - python_d_norm, - python_regularization_size, - python_alpha_du, - python_alpha_pr, python_ls_trials); - - PyObject *result = - PyObject_CallObject(myowndata->eval_intermediate_callback_python, - arglist); - - if (!result) - PyErr_Print(); - - result_as_long = PyInt_AsLong(result); - result_as_bool = (Bool) result_as_long; - - Py_DECREF(result); - Py_CLEAR(arglist); - logger("[Callback:R] intermediate_callback"); - return result_as_bool; -} - -Bool -eval_f(Index n, Number * x, Bool new_x, Number * obj_value, UserDataPtr data) -{ - logger("[Callback:E] eval_f"); - - npy_intp dims[1]; - dims[0] = n; - - DispatchData *myowndata = (DispatchData *) data; - UserDataPtr user_data = (UserDataPtr) myowndata->userdata; - - // import_array (); - - import_array1(FALSE); - PyObject *arrayx = - PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); - if (!arrayx) - return FALSE; - - if (new_x && myowndata->apply_new_python) { - /* Call the python function to applynew */ - PyObject *arg1; - arg1 = Py_BuildValue("(O)", arrayx); - PyObject *tempresult = PyObject_CallObject( - myowndata->apply_new_python, arg1); - if (tempresult == NULL) { - logger("[Error] Python function apply_new returns NULL"); - PyErr_Print(); - Py_DECREF(arg1); - return FALSE; - } - Py_DECREF(arg1); - Py_DECREF(tempresult); - } - - PyObject *arglist; - if (user_data != NULL) { - arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); - } else { - arglist = Py_BuildValue("(O)", arrayx); - } - - PyObject *result = PyObject_CallObject(myowndata->eval_f_python, arglist); - - if (result == NULL) { - logger("[Error] Python function eval_f returns NULL"); - PyErr_Print(); - Py_DECREF(arrayx); - Py_CLEAR(arglist); - return FALSE; - } - - *obj_value = PyFloat_AsDouble(result); - - if (PyErr_Occurred()) { - logger("[Error] Python function eval_f returns non-PyFloat"); - PyErr_Print(); - Py_DECREF(result); - Py_DECREF(arrayx); - Py_CLEAR(arglist); - return FALSE; - } - - Py_DECREF(result); - Py_DECREF(arrayx); - Py_CLEAR(arglist); - logger("[Callback:R] eval_f"); - return TRUE; -} - -Bool -eval_grad_f(Index n, Number * x, Bool new_x, Number * grad_f, UserDataPtr data) -{ - logger("[Callback:E] eval_grad_f"); - - DispatchData *myowndata = (DispatchData *) data; - UserDataPtr user_data = (UserDataPtr) myowndata->userdata; - - if (myowndata->eval_grad_f_python == NULL) - PyErr_Print(); - - /* int dims[1]; */ - npy_intp dims[1]; - dims[0] = n; - // import_array (); - - import_array1(FALSE); - - /* - * PyObject *arrayx = PyArray_FromDimsAndData(1, dims, PyArray_DOUBLE - * , (char*) x); - */ - PyObject *arrayx = - PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); - if (!arrayx) - return FALSE; - - if (new_x && myowndata->apply_new_python) { - /* Call the python function to applynew */ - PyObject *arg1 = Py_BuildValue("(O)", arrayx); - PyObject *tempresult = PyObject_CallObject( - myowndata->apply_new_python, arg1); - if (tempresult == NULL) { - logger("[Error] Python function apply_new returns NULL"); - PyErr_Print(); - Py_DECREF(arg1); - return FALSE; - } - Py_DECREF(arg1); - Py_DECREF(tempresult); - } - - PyObject *arglist; - if (user_data != NULL) - arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); - else - arglist = Py_BuildValue("(O)", arrayx); - - PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( - myowndata->eval_grad_f_python, arglist); - - if (result == NULL) { - logger("[Error] Python function eval_grad_f returns NULL"); - PyErr_Print(); - return FALSE; - } - - if (!PyArray_Check(result)) { - logger("[Error] Python function eval_grad_f returns non-PyArray"); - Py_DECREF(result); - return FALSE; - } - - double *tempdata = (double *)result->data; - int i; - for (i = 0; i < n; i++) - grad_f[i] = tempdata[i]; - - Py_DECREF(result); - Py_CLEAR(arrayx); - Py_CLEAR(arglist); - logger("[Callback:R] eval_grad_f"); - return TRUE; -} - -Bool -eval_g(Index n, Number * x, Bool new_x, Index m, Number * g, UserDataPtr data) -{ - - logger("[Callback:E] eval_g"); - - DispatchData *myowndata = (DispatchData *) data; - UserDataPtr user_data = (UserDataPtr) myowndata->userdata; - - if (myowndata->eval_g_python == NULL) - PyErr_Print(); - /* int dims[1]; */ - npy_intp dims[1]; - int i; - double *tempdata; - - dims[0] = n; - // import_array (); - - import_array1(FALSE); - - /* - * PyObject *arrayx = PyArray_FromDimsAndData(1, dims, PyArray_DOUBLE - * , (char*) x); - */ - PyObject *arrayx = - PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); - if (!arrayx) - return FALSE; - - if (new_x && myowndata->apply_new_python) { - /* Call the python function to applynew */ - PyObject *arg1 = Py_BuildValue("(O)", arrayx); - PyObject *tempresult = PyObject_CallObject( - myowndata->apply_new_python, arg1); - if (tempresult == NULL) { - logger("[Error] Python function apply_new returns NULL"); - PyErr_Print(); - Py_DECREF(arg1); - return FALSE; - } - Py_DECREF(arg1); - Py_DECREF(tempresult); - } - - PyObject *arglist; - if (user_data != NULL) - arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); - else - arglist = Py_BuildValue("(O)", arrayx); - - PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( - myowndata->eval_g_python, arglist); - - if (result == NULL) { - logger("[Error] Python function eval_g returns NULL"); - PyErr_Print(); - return FALSE; - } - - if (!PyArray_Check(result)) { - logger("[Error] Python function eval_g returns non-PyArray"); - Py_DECREF(result); - return FALSE; - } - - tempdata = (double *)result->data; - for (i = 0; i < m; i++) { - g[i] = tempdata[i]; - } - - Py_DECREF(result); - Py_CLEAR(arrayx); - Py_CLEAR(arglist); - logger("[Callback:R] eval_g"); - return TRUE; -} - -Bool -eval_jac_g(Index n, Number * x, Bool new_x, - Index m, Index nele_jac, - Index * iRow, Index * jCol, Number * values, UserDataPtr data) -{ - - logger("[Callback:E] eval_jac_g"); - - DispatchData *myowndata = (DispatchData *) data; - UserDataPtr user_data = (UserDataPtr) myowndata->userdata; - - int i; - long *rowd = NULL; - long *cold = NULL; - - /* int dims[1]; */ - npy_intp dims[1]; - dims[0] = n; - - double *tempdata; - - if (myowndata->eval_grad_f_python == NULL) /* Why??? */ - PyErr_Print(); - - if (values == NULL) { - /* import_array (); */ - import_array1(FALSE); - - PyObject *arrayx = - PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, - (char *)x); - if (!arrayx) - return FALSE; - - PyObject *arglist; - - if (user_data != NULL) - arglist = Py_BuildValue("(OOO)", - arrayx, Py_True, - (PyObject *) user_data); - else - arglist = Py_BuildValue("(OO)", arrayx, Py_True); - - PyObject *result = - PyObject_CallObject(myowndata->eval_jac_g_python, arglist); - if (!result) { - - logger("[PyIPOPT] return from eval_jac_g is null\n"); - /* TODO: need to deal with reference counting here */ - return FALSE; - } - if (!PyTuple_Check(result)) { - PyErr_Print(); - } - PyArrayObject *row = - (PyArrayObject *) PyTuple_GetItem(result, 0); - PyArrayObject *col = - (PyArrayObject *) PyTuple_GetItem(result, 1); - - if (!row || !col || !PyArray_Check(row) || !PyArray_Check(col)) { - logger - ("[Error] there are problems with row or col in eval_jac_g.\n"); - PyErr_Print(); - } - rowd = (long *)row->data; - cold = (long *)col->data; - - for (i = 0; i < nele_jac; i++) { - iRow[i] = (Index) rowd[i]; - jCol[i] = (Index) cold[i]; - } - Py_CLEAR(arrayx); - Py_DECREF(result); - Py_CLEAR(arglist); - logger("[Callback:R] eval_jac_g(1)"); - } else { - PyObject *arrayx = - PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, - (char *)x); - - if (!arrayx) - return FALSE; - - if (new_x && myowndata->apply_new_python) { - /* Call the python function to applynew */ - PyObject *arg1 = Py_BuildValue("(O)", arrayx); - PyObject *tempresult = - PyObject_CallObject(myowndata->apply_new_python, - arg1); - if (tempresult == NULL) { - logger("[Error] Python function apply_new returns NULL"); - Py_DECREF(arg1); - return FALSE; - } - Py_DECREF(arg1); - Py_DECREF(tempresult); - } - PyObject *arglist; - if (user_data != NULL) - arglist = Py_BuildValue("(OOO)", - arrayx, Py_False, - (PyObject *) user_data); - else - arglist = Py_BuildValue("(OO)", arrayx, Py_False); - - PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( - myowndata->eval_jac_g_python, arglist); - - if (result == NULL) { - logger("[Error] Python function eval_jac_g returns NULL"); - PyErr_Print(); - return FALSE; - } - - if (!PyArray_Check(result)) { - logger("[Error] Python function eval_jac_g returns non-PyArray"); - Py_DECREF(result); - return FALSE; - } - - /* - * Code is buggy here. We assume that result is a double - * array - */ - assert(result->descr->type == 'd'); - tempdata = (double *)result->data; - - for (i = 0; i < nele_jac; i++) - values[i] = tempdata[i]; - - Py_DECREF(result); - Py_CLEAR(arrayx); - Py_CLEAR(arglist); - logger("[Callback:R] eval_jac_g(2)"); - } - logger("[Callback:R] eval_jac_g"); - return TRUE; -} - -Bool -eval_h(Index n, Number * x, Bool new_x, Number obj_factor, - Index m, Number * lambda, Bool new_lambda, - Index nele_hess, Index * iRow, Index * jCol, - Number * values, UserDataPtr data) -{ - logger("[Callback:E] eval_h"); - - DispatchData *myowndata = (DispatchData *) data; - UserDataPtr user_data = (UserDataPtr) myowndata->userdata; - - int i; - npy_intp dims[1]; - npy_intp dims2[1]; - - if (myowndata->eval_h_python == NULL) { - logger("[Error] There is no eval_h assigned"); - return FALSE; - } - if (values == NULL) { - logger("[Callback:E] eval_h (1a)"); - PyObject *newx = Py_True; - PyObject *objfactor = Py_BuildValue("d", obj_factor); - PyObject *lagrange = Py_True; - - PyObject *arglist; - - if (user_data != NULL) { - arglist = Py_BuildValue( - "(OOOOO)", newx, lagrange, objfactor, Py_True, - (PyObject *) user_data); - } else { - arglist = Py_BuildValue( - "(OOOO)", newx, lagrange, objfactor, Py_True); - } - - if (arglist == NULL) { - logger("[Error] failed to build arglist for eval_h"); - PyErr_Print(); - return FALSE; - } else { - logger("[Logspam] built arglist for eval_h"); - } - - PyObject *result = PyObject_CallObject(myowndata->eval_h_python, arglist); - - if (result == NULL) { - logger("[Error] Python function eval_h returns NULL"); - PyErr_Print(); - return FALSE; - } else { - logger("[Logspam] Python function eval_h returns non-NULL"); - } - - int result_size = PyTuple_Size(result); - - if (result_size == -1) { - logger("[Error] Python function eval_h returns non-PyTuple"); - Py_DECREF(result); - return FALSE; - } - - if (result_size != 2) { - logger("[Error] Python function eval_h returns a tuple whose len != 2"); - Py_DECREF(result); - return FALSE; - } - - logger("[Callback:E] eval_h (tuple is the right length)"); - - PyArrayObject *row = (PyArrayObject *) PyTuple_GetItem(result, 0); - PyArrayObject *col = (PyArrayObject *) PyTuple_GetItem(result, 1); - - long *rdata = (long *)row->data; - long *cdata = (long *)col->data; - - for (i = 0; i < nele_hess; i++) { - iRow[i] = (Index) rdata[i]; - jCol[i] = (Index) cdata[i]; - /* - * logger("PyIPOPT_DEBUG %d, %d\n", iRow[i], - * jCol[i]); - */ - } - - logger("[Callback:E] eval_h (clearing stuff now)"); - - Py_DECREF(objfactor); - Py_DECREF(result); - Py_CLEAR(arglist); - logger("[Callback:R] eval_h (1b)"); - } else { - logger("[Callback:R] eval_h (2a)"); - - PyObject *objfactor = Py_BuildValue("d", obj_factor); - - dims[0] = n; - PyObject *arrayx = - PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, - (char *)x); - if (!arrayx) - return FALSE; - - if (new_x && myowndata->apply_new_python) { - /* Call the python function to applynew */ - PyObject *arg1 = Py_BuildValue("(O)", arrayx); - PyObject *tempresult = PyObject_CallObject( - myowndata->apply_new_python, arg1); - if (tempresult == NULL) { - logger("[Error] Python function apply_new returns NULL"); - PyErr_Print(); - Py_DECREF(arg1); - return FALSE; - } - Py_DECREF(arg1); - Py_DECREF(tempresult); - } - dims2[0] = m; - PyObject *lagrangex = PyArray_SimpleNewFromData( - 1, dims2, PyArray_DOUBLE, (char *)lambda); - if (!lagrangex) - return FALSE; - - PyObject *arglist; - - if (user_data != NULL) { - arglist = Py_BuildValue( - "(OOOOO)", arrayx, lagrangex, objfactor, Py_False, - (PyObject *) user_data); - } else { - arglist = Py_BuildValue( - "(OOOO)", arrayx, lagrangex, objfactor, Py_False); - } - PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( - myowndata->eval_h_python, arglist); - - if (result == NULL) { - logger("[Error] Python function eval_h returns NULL"); - PyErr_Print(); - return FALSE; - } - - if (!PyArray_Check(result)) { - logger("[Error] Python function eval_h returns non-PyArray"); - Py_DECREF(result); - return FALSE; - } - - double *tempdata = (double *)result->data; - for (i = 0; i < nele_hess; i++) { - values[i] = tempdata[i]; - logger("PyDebug %lf", values[i]); - } - Py_CLEAR(arrayx); - Py_CLEAR(lagrangex); - Py_CLEAR(objfactor); - Py_DECREF(result); - Py_CLEAR(arglist); - logger("[Callback:R] eval_h (2b)"); - } - return TRUE; -} diff --git a/pyoptsparse/pyoptsparse/pyIPOPT/src/hook.h b/pyoptsparse/pyoptsparse/pyIPOPT/src/hook.h deleted file mode 100644 index 8625a971c..000000000 --- a/pyoptsparse/pyoptsparse/pyIPOPT/src/hook.h +++ /dev/null @@ -1,68 +0,0 @@ -// Author: Eric Xu -// Licensed under BSD - -#include "Python.h" -#include "IpStdCInterface.h" -#include -#include "numpy/arrayobject.h" - -#ifndef PY_IPOPT_HOOK_ -#define PY_IPOPT_HOOK_ - -// A series of callback functions used by Ipopt C Interface -Bool eval_f(Index n, - Number * x, Bool new_x, Number * obj_value, UserDataPtr user_data); - -Bool eval_grad_f(Index n, - Number * x, - Bool new_x, Number * grad_f, UserDataPtr user_data); - -Bool eval_g(Index n, - Number * x, Bool new_x, Index m, Number * g, UserDataPtr user_data); - -Bool eval_jac_g(Index n, Number * x, Bool new_x, - Index m, Index nele_jac, - Index * iRow, Index * jCol, Number * values, - UserDataPtr user_data); - -Bool eval_h(Index n, Number * x, Bool new_x, Number obj_factor, - Index m, Number * lambda, Bool new_lambda, - Index nele_hess, Index * iRow, Index * jCol, - Number * values, UserDataPtr user_data); - -Bool eval_intermediate_callback(Index alg_mod, - Index iter_count, Number obj_value, - Number inf_pr, Number inf_du, - Number mu, Number d_norm, - Number regularization_size, - Number alpha_du, Number alpha_pr, - Index ls_trials, UserDataPtr data); - -typedef struct { - PyObject *eval_f_python; - PyObject *eval_grad_f_python; - PyObject *eval_g_python; - PyObject *eval_jac_g_python; - PyObject *eval_h_python; - PyObject *apply_new_python; - PyObject *eval_intermediate_callback_python; - PyObject *userdata; -} DispatchData; - -PyObject *problem_getattr(PyObject * self, char *attrname); - -/* Logging */ -#define VERBOSE 2 -#define IPOPT_OUTPUT 1 -#define TERSE 0 -extern int user_log_level; -void logger(const char *fmt, ...); - -typedef struct { - PyObject_HEAD IpoptProblem nlp; - DispatchData *data; - Index n_variables; - Index m_constraints; -} problem; - -#endif // PY_IPOPT_HOOK_ diff --git a/pyoptsparse/pyoptsparse/pyIPOPT/src/pyipoptcoremodule.c b/pyoptsparse/pyoptsparse/pyIPOPT/src/pyipoptcoremodule.c deleted file mode 100644 index 1d0c3c8de..000000000 --- a/pyoptsparse/pyoptsparse/pyIPOPT/src/pyipoptcoremodule.c +++ /dev/null @@ -1,711 +0,0 @@ -/* Author: Eric Xu */ -/* Licensed under BSD */ -/* */ -/* Modifications on logger made by */ -/* OpenMDAO at NASA Glenn Research Center, 2010 and 2011 */ -/* Modifications on the SAFE_FREE macro made by */ -/* Guillaume Jacquenot, 2012 */ - -#include "hook.h" - -#ifndef SAFE_FREE -#define SAFE_FREE(p) {if (p) {free(p); (p)= NULL;}} -#endif - -/* - * Let's put the static char docs at the beginning of this file... - */ - -static char PYIPOPT_SOLVE_DOC[] = "solve(x) -> (x, ml, mu, obj)\n \ - \n \ - Call Ipopt to solve problem created before and return \n \ - a tuple that contains final solution x, upper and lower\n \ - bound for multiplier, final objective function obj, \n \ - and the return status of ipopt. \n"; - -static char PYIPOPT_SET_INTERMEDIATE_CALLBACK_DOC[] = - "set_intermediate_callback(callback_function)\n \ - \n \ - Set the intermediate callback function. \ - This gets called each iteration."; - -static char PYIPOPT_CLOSE_DOC[] = "After all the solving, close the model\n"; - -static char PYIPOPT_ADD_STR_OPTION_DOC[] = - "Set the String (char* in C) option for Ipopt. Refer to the Ipopt \n \ - document for more information about Ipopt options, or use \n \ - ipopt --print-options \n \ - to see a list of available options."; - -static char PYIPOPT_ADD_INT_OPTION_DOC[] = - "Set the Int (int in C) option for Ipopt. Refer to the Ipopt \n \ - document for more information about Ipopt options, or use \n \ - ipopt --print-options \n \ - to see a list of available options."; - -static char PYIPOPT_ADD_NUM_OPTION_DOC[] = - "Set the Number (double in C) option for Ipopt. Refer to the Ipopt \n \ - document for more information about Ipopt options, or use \n \ - ipopt --print-options \n \ - to see a list of available options."; - -static char PYIPOPT_CREATE_DOC[] = - "create(n, xl, xu, m, gl, gu, nnzj, nnzh, eval_f, eval_grad_f, eval_g, eval_jac_g) -> Boolean\n \ - \n \ - Create a problem instance and return True if succeed \n \ - \n \ - n is the number of variables, \n \ - xl is the lower bound of x as bounded constraints \n \ - xu is the upper bound of x as bounded constraints \n \ - both xl, xu should be one dimension arrays with length n \n \ - \n \ - m is the number of constraints, \n \ - gl is the lower bound of constraints \n \ - gu is the upper bound of constraints \n \ - both gl, gu should be one dimension arrays with length m \n \ - nnzj is the number of nonzeros in Jacobi matrix \n \ - nnzh is the number of non-zeros in Hessian matrix, you can set it to 0 \n \ - \n \ - eval_f is the call back function to calculate objective value, \n \ - it takes one single argument x as input vector \n \ - eval_grad_f calculates gradient for objective function \n \ - eval_g calculates the constraint values and return an array \n \ - eval_jac_g calculates the Jacobi matrix. It takes two arguments, \n \ - the first is the variable x and the second is a Boolean flag \n \ - if the flag is true, it supposed to return a tuple (row, col) \n \ - to indicate the sparse Jacobi matrix's structure. \n \ - if the flag is false if returns the values of the Jacobi matrix \n \ - with length nnzj \n \ - eval_h calculates the hessian matrix, it's optional. \n \ - if omitted, please set nnzh to 0 and Ipopt will use approximated hessian \n \ - which will make the convergence slower. "; - -static char PYIPOPT_LOG_DOC[] = "set_loglevel(level)\n \ - \n \ - Set the log level of PyIPOPT \n \ - levels: \n \ - 0: Terse, no log from pyipopt \n \ - 1: Moderate, logs for ipopt \n \ - 2: Verbose, logs for both ipopt and pyipopt. \n"; - - - -int user_log_level = TERSE; - -/* Object Section */ -/* sig of this is void foo(PyO*) */ -static void problem_dealloc(PyObject * self) -{ - problem *temp = (problem *) self; - SAFE_FREE(temp->data); - self->ob_type->tp_free((PyObject*)self); -} - -PyObject *solve(PyObject * self, PyObject * args); -PyObject *set_intermediate_callback(PyObject * self, PyObject * args); -PyObject *close_model(PyObject * self, PyObject * args); - -static PyObject *add_str_option(PyObject * self, PyObject * args) -{ - problem *temp = (problem *) self; - IpoptProblem nlp = (IpoptProblem) (temp->nlp); - char *param; - char *value; - Bool ret; - - if (!PyArg_ParseTuple(args, "ss:str_option", ¶m, &value)) { - return NULL; - } - ret = AddIpoptStrOption(nlp, (char *)param, value); - if (ret) { - Py_INCREF(Py_True); - return Py_True; - } else { - return PyErr_Format(PyExc_ValueError, - "%s is not a valid string option", param); - } -} - -static PyObject *add_int_option(PyObject * self, PyObject * args) -{ - - problem *temp = (problem *) self; - IpoptProblem nlp = (IpoptProblem) (temp->nlp); - - char *param; - int value; - - Bool ret; - - if (!PyArg_ParseTuple(args, "si:int_option", ¶m, &value)) { - return NULL; - } - ret = AddIpoptIntOption(nlp, (char *)param, value); - if (ret) { - Py_INCREF(Py_True); - return Py_True; - } else { - return PyErr_Format(PyExc_ValueError, - "%s is not a valid int option", param); - } -} - -static PyObject *add_num_option(PyObject * self, PyObject * args) -{ - problem *temp = (problem *) self; - IpoptProblem nlp = (IpoptProblem) (temp->nlp); - - char *param; - double value; - - Bool ret; - - if (!PyArg_ParseTuple(args, "sd:num_option", ¶m, &value)) { - return NULL; - } - ret = AddIpoptNumOption(nlp, (char *)param, value); - if (ret) { - Py_INCREF(Py_True); - return Py_True; - } else { - return PyErr_Format(PyExc_ValueError, - "%s is not a valid num option", param); - } -} - -PyMethodDef problem_methods[] = { - {"solve", solve, METH_VARARGS, PYIPOPT_SOLVE_DOC} - , - {"set_intermediate_callback", set_intermediate_callback, METH_VARARGS, - PYIPOPT_SET_INTERMEDIATE_CALLBACK_DOC} - , - {"close", close_model, METH_VARARGS, PYIPOPT_CLOSE_DOC} - , - {"int_option", add_int_option, METH_VARARGS, PYIPOPT_ADD_INT_OPTION_DOC} - , - {"str_option", add_str_option, METH_VARARGS, PYIPOPT_ADD_STR_OPTION_DOC} - , - {"num_option", add_num_option, METH_VARARGS, PYIPOPT_ADD_NUM_OPTION_DOC} - , - {NULL, NULL} - , -}; - -PyObject *problem_getattr(PyObject * self, char *attrname) -{ - PyObject *result = NULL; - result = Py_FindMethod(problem_methods, self, attrname); - return result; -} - -/* - * had to replace PyObject_HEAD_INIT(&PyType_Type) in order to get this to - * compile on Windows - */ -PyTypeObject IpoptProblemType = { - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ - "pyipoptcore.Problem", /* tp_name */ - sizeof(problem), /* tp_basicsize */ - 0, /* tp_itemsize */ - problem_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - problem_getattr, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - 0, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - "The IPOPT problem object in python", /* tp_doc */ -}; - -/* - * FIXME: use module or package constants for the log levels, - * either in pyipoptcore or in the parent package. - * They are currently #defined in a header file. - */ -static PyObject *set_loglevel(PyObject * obj, PyObject * args) -{ - int l; - if (!PyArg_ParseTuple(args, "i", &l)) { - printf("l is %d \n", l); - return NULL; - } - if (l < 0 || l > 2) { - return NULL; - } - user_log_level = l; - Py_INCREF(Py_True); - return Py_True; -} - -static PyObject *create(PyObject * obj, PyObject * args) -{ - PyObject *f = NULL; - PyObject *gradf = NULL; - PyObject *g = NULL; - PyObject *jacg = NULL; - PyObject *h = NULL; - PyObject *applynew = NULL; - - DispatchData myowndata; - - /* - * I have to create a new python object here, return this python object - */ - - int n; /* Number of variables */ - PyArrayObject *xL = NULL; - PyArrayObject *xU = NULL; - int m; /* Number of constraints */ - PyArrayObject *gL = NULL; - PyArrayObject *gU = NULL; - - problem *object = NULL; - - int nele_jac; - int nele_hess; - - Number *x_L = NULL; /* lower bounds on x */ - Number *x_U = NULL; /* upper bounds on x */ - Number *g_L = NULL; /* lower bounds on g */ - Number *g_U = NULL; /* upper bounds on g */ - - double *xldata, *xudata; - double *gldata, *gudata; - - int i; - - DispatchData *dp = NULL; - - PyObject *retval = NULL; - - /* Init the myowndata field */ - myowndata.eval_f_python = NULL; - myowndata.eval_grad_f_python = NULL; - myowndata.eval_g_python = NULL; - myowndata.eval_jac_g_python = NULL; - myowndata.eval_h_python = NULL; - myowndata.apply_new_python = NULL; - myowndata.userdata = NULL; - - /* "O!", &PyArray_Type &a_x */ - if (!PyArg_ParseTuple(args, "iO!O!iO!O!iiOOOO|OO:pyipoptcreate", - &n, &PyArray_Type, &xL, - &PyArray_Type, &xU, - &m, - &PyArray_Type, &gL, - &PyArray_Type, &gU, - &nele_jac, &nele_hess, - &f, &gradf, &g, &jacg, &h, &applynew)) { - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - if (!PyCallable_Check(f) || - !PyCallable_Check(gradf) || - !PyCallable_Check(g) || !PyCallable_Check(jacg)) { - PyErr_SetString(PyExc_TypeError, - "Need a callable object for callback functions"); - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - myowndata.eval_f_python = f; - myowndata.eval_grad_f_python = gradf; - myowndata.eval_g_python = g; - myowndata.eval_jac_g_python = jacg; - - if (h != NULL) { - if (PyCallable_Check(h)) { - myowndata.eval_h_python = h; - } else { - PyErr_SetString(PyExc_TypeError, - "Need a callable object for function h."); - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - } else { - logger("[PyIPOPT] Ipopt will use Hessian approximation.\n"); - } - - if (applynew != NULL) { - if (PyCallable_Check(applynew)) { - myowndata.apply_new_python = applynew; - } else { - PyErr_SetString(PyExc_TypeError, - "Need a callable object for function applynew."); - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - } - if (m < 0 || n < 0) { - PyErr_SetString(PyExc_TypeError, "m or n can't be negative"); - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - x_L = (Number *) malloc(sizeof(Number) * n); - x_U = (Number *) malloc(sizeof(Number) * n); - if (!x_L || !x_U) { - retval = PyErr_NoMemory(); - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - xldata = (double *)xL->data; - xudata = (double *)xU->data; - for (i = 0; i < n; i++) { - x_L[i] = xldata[i]; - x_U[i] = xudata[i]; - } - - g_L = (Number *) malloc(sizeof(Number) * m); - g_U = (Number *) malloc(sizeof(Number) * m); - if (!g_L || !g_U) - PyErr_NoMemory(); - - gldata = (double *)gL->data; - gudata = (double *)gU->data; - - for (i = 0; i < m; i++) { - g_L[i] = gldata[i]; - g_U[i] = gudata[i]; - } - - /* Grab the callback objects because we want to use them later. */ - Py_XINCREF(f); - Py_XINCREF(gradf); - Py_XINCREF(g); - Py_XINCREF(jacg); - Py_XINCREF(h); - Py_XINCREF(applynew); - - /* create the Ipopt Problem */ - - int C_indexstyle = 0; - IpoptProblem thisnlp = CreateIpoptProblem(n, - x_L, x_U, m, g_L, g_U, - nele_jac, nele_hess, - C_indexstyle, - &eval_f, &eval_g, - &eval_grad_f, - &eval_jac_g, &eval_h); - logger("[PyIPOPT] Problem created"); - if (!thisnlp) { - PyErr_SetString(PyExc_MemoryError, "Cannot create IpoptProblem instance"); - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - object = PyObject_NEW(problem, &IpoptProblemType); - - if (object != NULL) { - object->n_variables = n; - object->m_constraints = m; - object->nlp = thisnlp; - dp = (DispatchData *) malloc(sizeof(DispatchData)); - if (!dp) { - retval = PyErr_NoMemory(); - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } - memcpy((void *)dp, (void *)&myowndata, sizeof(DispatchData)); - object->data = dp; - retval = (PyObject *) object; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } else { - PyErr_SetString(PyExc_MemoryError, "Can't create a new Problem instance"); - retval = NULL; - SAFE_FREE(x_L); - SAFE_FREE(x_U); - SAFE_FREE(g_L); - SAFE_FREE(g_U); - return retval; - } -} - -PyObject *set_intermediate_callback(PyObject * self, PyObject * args) -{ - PyObject *intermediate_callback; - problem *temp = (problem *) self; - IpoptProblem nlp = (IpoptProblem) (temp->nlp); - DispatchData myowndata; - DispatchData *bigfield = (DispatchData *) (temp->data); - - /* Init the myowndata field */ - myowndata.eval_intermediate_callback_python = NULL; - - if (!PyArg_ParseTuple(args, "O", &intermediate_callback)) { - return NULL; - } - if (!PyCallable_Check(intermediate_callback)) { - PyErr_SetString(PyExc_TypeError, - "Need a callable object for function!"); - return NULL; - } else { - - bigfield->eval_intermediate_callback_python = - intermediate_callback; - - /* Put a Python function object into this data structure */ - /* - * myowndata.eval_intermediate_callback_python = - * intermediate_callback; - */ - - /* DispatchData *dp = malloc(sizeof(DispatchData)); */ - /* - * memcpy((void*)dp, (void*)&myowndata, - * sizeof(DispatchData)); - */ - /* bigfield = dp; */ - /* - * logger( "qqq: inside set_intermediate_callback, bigfield - * is %p\n", bigfield ) ; - */ - /* - * logger("[PyIPOPT] User specified data field to callback - * function.\n"); - */ - - SetIntermediateCallback(nlp, eval_intermediate_callback); - Py_INCREF(Py_True); - return Py_True; - } -} - -PyObject *solve(PyObject * self, PyObject * args) -{ - enum ApplicationReturnStatus status; /* Solve return code */ - int i; - int n; - - /* Return values */ - problem *temp = (problem *) self; - - IpoptProblem nlp = (IpoptProblem) (temp->nlp); - DispatchData *bigfield = (DispatchData *) (temp->data); - int m = temp->m_constraints; - - /* int dX[1]; */ - npy_intp dX[1]; - npy_intp dlambda[1]; - - PyArrayObject *x = NULL, *mL = NULL, *mU = NULL, *lambda = NULL; - Number obj; /* objective value */ - - PyObject *retval = NULL; - PyArrayObject *x0 = NULL; - - PyObject *myuserdata = NULL; - - Number *newx0 = NULL; - - if (!PyArg_ParseTuple(args, "O!|O", &PyArray_Type, &x0, &myuserdata)) { - retval = NULL; - /* clean up and return */ - if (retval == NULL) { - Py_XDECREF(x); - Py_XDECREF(mL); - Py_XDECREF(mU); - Py_XDECREF(lambda); - } - SAFE_FREE(newx0); - return retval; - } - if (myuserdata != NULL) { - bigfield->userdata = myuserdata; - /* - * logger("[PyIPOPT] User specified data field to callback - * function.\n"); - */ - } - if (nlp == NULL) { - PyErr_SetString(PyExc_TypeError, - "nlp objective passed to solve is NULL\n Problem created?\n"); - retval = NULL; - /* clean up and return */ - if (retval == NULL) { - Py_XDECREF(x); - Py_XDECREF(mL); - Py_XDECREF(mU); - Py_XDECREF(lambda); - } - SAFE_FREE(newx0); - return retval; - } - if (bigfield->eval_h_python == NULL) { - AddIpoptStrOption(nlp, "hessian_approximation", "limited-memory"); - /* logger("Can't find eval_h callback function\n"); */ - } - /* allocate space for the initial point and set the values */ - npy_intp *dim = ((PyArrayObject *) x0)->dimensions; - n = dim[0]; - dX[0] = n; - - x = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE); - if (!x) { - retval = PyErr_NoMemory(); - /* clean up and return */ - if (retval == NULL) { - Py_XDECREF(x); - Py_XDECREF(mL); - Py_XDECREF(mU); - Py_XDECREF(lambda); - } - SAFE_FREE(newx0); - return retval; - } - newx0 = (Number *) malloc(sizeof(Number) * n); - if (!newx0) { - retval = PyErr_NoMemory(); - /* clean up and return */ - if (retval == NULL) { - Py_XDECREF(x); - Py_XDECREF(mL); - Py_XDECREF(mU); - Py_XDECREF(lambda); - } - SAFE_FREE(newx0); - return retval; - } - double *xdata = (double *)x0->data; - for (i = 0; i < n; i++) - newx0[i] = xdata[i]; - - /* Allocate multiplier arrays */ - - mL = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE); - mU = (PyArrayObject *) PyArray_SimpleNew(1, dX, PyArray_DOUBLE); - dlambda[0] = m; - lambda = (PyArrayObject *) PyArray_SimpleNew(1, dlambda, - PyArray_DOUBLE); - - /* For status code, see IpReturnCodes_inc.h in Ipopt */ - - status = - IpoptSolve(nlp, newx0, NULL, &obj, (double *)lambda->data, - (double *)mL->data, (double *)mU->data, - (UserDataPtr) bigfield); - double *return_x_data = (double *)x->data; - for (i = 0; i < n; i++) { - return_x_data[i] = newx0[i]; - } - retval = Py_BuildValue("OOOOdi", - PyArray_Return(x), - PyArray_Return(mL), - PyArray_Return(mU), - PyArray_Return(lambda), - obj, status - ); - /* clean up and return */ - - Py_XDECREF(x); - Py_XDECREF(mL); - Py_XDECREF(mU); - Py_XDECREF(lambda); - - SAFE_FREE(newx0); - return retval; -} - -PyObject *close_model(PyObject * self, PyObject * args) -{ - problem *obj = (problem *) self; - DispatchData *dp = obj->data; - - /* Ungrab the callback functions because we do not need them anymore. */ - Py_XDECREF(dp->eval_f_python); - Py_XDECREF(dp->eval_grad_f_python); - Py_XDECREF(dp->eval_g_python); - Py_XDECREF(dp->eval_jac_g_python); - Py_XDECREF(dp->eval_h_python); - Py_XDECREF(dp->apply_new_python); - - FreeIpoptProblem(obj->nlp); - obj->nlp = NULL; - Py_INCREF(Py_True); - return Py_True; -} - -/* static char PYTEST[] = "TestCreate\n"; */ - -/* static PyObject *test(PyObject *self, PyObject *args) */ -/* { */ -/* IpoptProblem thisnlp = NULL; */ -/* problem *object = NULL; */ -/* object = PyObject_NEW(problem , &IpoptProblemType); */ -/* if (object != NULL) */ -/* object->nlp = thisnlp; */ -/* /\* problem *object = problem_new(thisnlp); *\/ */ -/* return (PyObject *)object; */ -/* } */ - -/* Begin Python Module code section */ -static PyMethodDef ipoptMethods[] = { - /* { "solve", solve, METH_VARARGS, PYIPOPT_SOLVE_DOC}, */ - {"create", create, METH_VARARGS, PYIPOPT_CREATE_DOC}, - /* { "close", close_model, METH_VARARGS, PYIPOPT_CLOSE_DOC}, */ - /* { "test", test, METH_VARARGS, PYTEST}, */ - {"set_loglevel", set_loglevel, METH_VARARGS, PYIPOPT_LOG_DOC}, - {NULL, NULL} -}; - -PyMODINIT_FUNC initpyipoptcore(void) -{ - /* Finish initialization of the problem type */ - if (PyType_Ready(&IpoptProblemType) < 0) { - return; - } - - Py_InitModule3( - "pyipoptcore", ipoptMethods, "A hook between Ipopt and Python"); - - /* Initialize numpy. */ - /* A segfault will occur if I use numarray without this.. */ - import_array(); - if (PyErr_Occurred()) { - Py_FatalError("Unable to initialize module pyipoptcore"); - } - return; -} - -/* End Python Module code section */ diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/LICENSE b/pyoptsparse/pyoptsparse/pyNLPQLP/LICENSE deleted file mode 100644 index f206107f1..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -NLPQL - Non-Linear Programming by Quadratic Lagrangian -Copyright (c) 1991, Klaus Schittkowski (Klaus.Schittkowski@uni-bayreuth.de) -Patch for pyOpt - 2010, Ruben E. Perez (Ruben.Perez@rmc.ca) - -NLPQL is a licensed software, to obtain the program sources and -for term and conditions of use please refer to the specific -commercial or academic agreement made with Professor Schittkowski. diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/README b/pyoptsparse/pyoptsparse/pyNLPQLP/README deleted file mode 100644 index 9bf6a5324..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the nlpqlp class definition -and the nlpqlp shared library, nlpqlp.so or nlpqlp.pyd. diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/__init__.py b/pyoptsparse/pyoptsparse/pyNLPQLP/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/pyNLPQLP.py b/pyoptsparse/pyoptsparse/pyNLPQLP/pyNLPQLP.py deleted file mode 100644 index 1890a6da0..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/pyNLPQLP.py +++ /dev/null @@ -1,289 +0,0 @@ -#/bin/env python -"""pyNLPQLP - A pyOptSparse wrapper for Schittkowski's NLPQLP -optimizion algorithm. - -Copyright (c) 2013-2015 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Wrapper Creation - -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# NLPQL Library -# ============================================================================= -try: - from . import nlpqlp -except ImportError: - nlpqlp = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -eps = numpy.finfo(1.0).eps -# ============================================================================= -# NLPQL Optimizer Class -# ============================================================================= -class NLPQLP(Optimizer): - """ - NLPQL Optimizer Class - Inherited from Optimizer Abstract Class - """ - def __init__(self, *args, **kwargs): - name = 'NLPQLP' - category = 'Local Optimizer' - defOpts = { - # NLPQL Options - 'accuracy': [float, 1e-6], # Convergence Accurancy - 'accuracyQP': [float, 1e-14], # Convergence Accurancy for QP - 'stepMin': [float, 1e-6], # Minimum step length - 'maxFun': [int, 20], # Maximum Number of Function Calls During Line Search - 'maxIt': [int, 500], # Maximum Number of Iterations - 'maxNM': [int, 1], # Maximum stack size for non-monotone line search - 'rho': [float, 1.0], # Factor scaling identify for IFAIL=2 - 'iPrint': [int, 2], # Output Level (0 - None, 1 - Final, 2 - Major, 3 - Major/Minor, 4 - Full) - 'mode': [int, 0], # NLPQL Mode (0 - Normal Execution, 1 to 18 - See Manual) - 'iOut': [int, 6], # Output Unit Number - 'lMerit': [bool, True], # Merit Function Type (True - L2 Augmented Penalty, False - L1 Penalty) - 'lQl': [bool, False], # QP Subproblem Solver (True - Quasi-Newton, False - Cholesky) - 'iFile': [str,'NLPQLP.out'], # Output File Name - } - informs = { - -2 : 'Compute gradient values w.r.t. the variables stored in' \ - ' first column of X, and store them in DF and DG.' \ - ' Only derivatives for active constraints ACTIVE(J)=.TRUE. need to be computed.', - -1 : 'Compute objective fn and all constraint values subject' \ - 'the variables found in the first L columns of X, and store them in F and G.', - 0 : 'The optimality conditions are satisfied.', - 1 : ' The algorithm has been stopped after MAXIT iterations.', - 2 : ' The algorithm computed an uphill search direction.', - 3 : ' Underflow occurred when determining a new approximation matrix' \ - 'for the Hessian of the Lagrangian.', - 4 : 'The line search could not be terminated successfully.', - 5 : 'Length of a working array is too short.' \ - ' More detailed error information is obtained with IPRINT>0', - 6 : 'There are false dimensions, for example M>MMAX, N>=NMAX, or MNN2<>M+N+N+2.', - 7 : 'The search direction is close to zero, but the current iterate is still infeasible.', - 8 : 'The starting point violates a lower or upper bound.', - 9 : 'Wrong input parameter, i.e., MODE, LDL decomposition in D and C' \ - ' (in case of MODE=1), IPRINT, IOUT', - 10 : 'Internal inconsistency of the quadratic subproblem, division by zero.', - 100 : 'The solution of the quadratic programming subproblem has been' \ - ' terminated with an error message and IFAIL is set to IFQL+100,' \ - ' where IFQL denotes the index of an inconsistent constraint.', - } - if nlpqlp is None: - raise Error("There was an error importing the compiled " - "nlpqlp module") - - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - # NLPQLP needs jacobians in dense format - self.jacType = 'dense2d' - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. To - explictly use pyOptSparse gradient class to do the - derivatives with finite differenes use 'FD'. 'sens' - may also be 'CS' which will cause pyOptSpare to compute - the derivatives using the complex step method. Finally, - 'sens' may be a python function handle which is expected - to compute the sensitivities directly. For expensive - function evaluations and/or problems with large numbers of - design variables this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is 'FD' and 1e-40j when sens is 'CS'. - - sensMode : str - Use 'pgc' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from NLPQL does not match the history, function and - gradient evaluations revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if len(optProb.constraints) == 0: - self.unconstrained = True - optProb.dummyConstraint = False - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - self._setSens(sens, sensStep, sensMode) - blx, bux, xs = self._assembleContinuousVariables() - xs = numpy.maximum(xs, blx) - xs = numpy.minimum(xs, bux) - nvar = len(xs) - ff = self._assembleObjective() - - oneSided = True - # Set the number of nonlinear constraints snopt *thinks* we have: - if self.unconstrained: - m = 0 - meq = 0 - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'le', 'ni', 'li'], oneSided=oneSided) - m = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - # Also figure out the number of equality: - tmp0, __, __, __ = self.optProb.getOrdering( - ['ne', 'le'], oneSided=oneSided) - meq = len(tmp0) - - if self.optProb.comm.rank == 0: - # Set history/hotstart/coldstart - self._setHistory(storeHistory, hotStart) - - #================================================================= - # NLPQL - Objective/Constraint Values Function (Real Valued) - #================================================================= - def nlfunc(m, me, mmax, n, f, g, x, active, fail): - fobj, fcon, fail = self._masterFunc(x, ['fobj', 'fcon']) - f = fobj - g[0:m] = -fcon - return f, g, fail - - #================================================================= - # NLPQL - Objective/Constraint Gradients Function - #================================================================= - def nlgrad(m, me, mmax, n, f, g, df, dg, x, active, wa): - gobj, gcon, fail = self._masterFunc(x, ['gobj', 'gcon']) - df[0:n] = gobj.copy() - dg[0:m, 0:n] = -gcon.copy() - return df, dg - - # setup argument list values - - np = 1 # We only allow a single "processor" ie we are - # actually running NLPQL (no P) - - # Set som basic sizes - m = m - me = meq - mmax = max(1, m) - - n = nvar - nmax = max(2, n+2) - mnn2 = m+n+n+2 - - # xs, ff, and gg have to have an extra dimension - # associated with them for the NP. We will do this - # correctly even though np is hard-coded to 1. - xs = numpy.array([xs]).T - f = numpy.array([ff]) - g = numpy.zeros((mmax, np)) - - df = numpy.zeros(nmax) - dg = numpy.zeros((mmax, nmax)) - u = numpy.zeros(mnn2) - c = numpy.zeros((nmax, nmax)) - d = numpy.zeros(nmax) - go = self.getOption - if go('iPrint') < 0 or go('iPrint') > 4: - raise Error('Incorrect iPrint option. Must be >=0 and <= 4') - - if not(go('mode') >= 0 and go('mode') <= 18): - raise Error('Incorrect mode option. Must be >= 0 and <= 18.') - - if os.path.isfile(go('iFile')): - os.remove(go('iFile')) - ifail = 0 - # Run NLPQL - t0 = time.time() - - nlpqlp.wrapper(np, m, me, mmax, n, nmax, mnn2, xs, f, g, df, dg, u, - blx, bux, c, d, go('accuracy'), go('accuracyQP'), - go('stepMin'), go('maxFun'), go('maxIt'), go('maxNM'), - go('rho'), go('mode'), go('iPrint'), go('iOut'), - go('iFile'), ifail, go('lMerit'), go('lQl'), - nlfunc, nlgrad) - - optTime = time.time() - t0 - - # Broadcast a -1 to indcate NLPQL has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - #sol_inform['value'] = inform - #sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name, value): - pass - - diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/setup.py b/pyoptsparse/pyoptsparse/pyNLPQLP/setup.py deleted file mode 100644 index f506ac170..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/local/bin/python - -import os,sys - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - # Check if we have source fils...if we don't we don't build: - sources=[os.path.join('source', 'NLPQLP.F'), - os.path.join('source', 'QL.F'), - os.path.join('source', 'wrapper.F90')] - - config = Configuration('pyNLPQLP',parent_package,top_path) - config.add_data_files('LICENSE','README') - nlpqlp = os.path.join('pyoptsparse/pyNLPQLP/source', 'NLPQLP.F') - - if os.path.exists(nlpqlp): - config.add_library('nlpqlp',sources=sources) - config.add_extension('nlpqlp',sources=['source/f2py/nlpqlp.pyf'], libraries=['nlpqlp']) - - return config - diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/source/README b/pyoptsparse/pyoptsparse/pyNLPQLP/source/README deleted file mode 100644 index 07cac09fd..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/source/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains the Fortran 77 source for NLPQLP. To use, copy -the NLPQLP.FOR and QL.FOR source code here and rename the files to -NLPQLP.F and QL.F and pyOptSparse will take care of compiling it. \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/source/f2py/nlpqlp.pyf b/pyoptsparse/pyoptsparse/pyNLPQLP/source/f2py/nlpqlp.pyf deleted file mode 100644 index f056a014e..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/source/f2py/nlpqlp.pyf +++ /dev/null @@ -1,78 +0,0 @@ -! -*- f90 -*- -! Note: the context of this file is case sensitive. - -python module nlpqlp__user__routines - interface nlpqlp_user_interface - subroutine nlfunc(m,me,mmax,n,f,g,x,active,fail) - integer intent(in) :: m - integer intent(in) :: me - integer intent(in) :: mmax - integer intent(in) :: n - double precision intent(in,out) :: f - double precision dimension(mmax),intent(in,out),depend(mmax) :: g - double precision dimension(n),intent(in),depend(n) :: x - logical dimension(mmax),depend(mmax) :: active - logical intent(in,out) :: fail - end subroutine nlfunc - subroutine nlgrad(m,me,mmax,n,f,g,df,dg,x,active,wa) - integer intent(in) :: m - integer intent(in) :: me - !integer optional,check(len(g)>=mmax),depend(g) :: mmax=len(g) - !integer optional,check(len(x)>=n),depend(x) :: n=len(x) - integer intent(in) :: mmax - integer intent(in) :: n - double precision intent(in) :: f - double precision dimension(mmax),intent(in),depend(mmax) :: g - double precision dimension(n),depend(n),intent(in,out) :: df - double precision dimension(mmax,n),depend(mmax,n),intent(in,out) :: dg - double precision dimension(n),depend(n) :: x - logical dimension(mmax),depend(mmax) :: active - double precision dimension(mmax),depend(mmax) :: wa - end subroutine nlgrad - end interface nlpqlp_user_interface -end python module nlpqlp__user__routiness -python module nlpqlp ! in - interface ! in :nlpqlp - subroutine wrapper(np, m, me, mmax, n, nmax, mnn2, x, f, g, df, dg, u, xl, xu, & - c, d, acc, accqp, stpmin, maxfun, maxit, maxnm, rho, mode, iprint, iout, & - ifile, ifail, lmerit, lql, nlfunc, nlgrad) - use nlpqlp__user__routines - integer intent(in) :: np - integer intent(in) :: m - integer intent(in) :: me - integer intent(in) :: mmax - integer intent(in) :: n - integer intent(in) :: nmax - integer intent(in) :: mnn2 - double precision dimension(n,np),depend(n, np) :: x - double precision dimension(np), depend(np), intent(inout) :: f - double precision dimension(mmax, np),depend(mmax, np),intent(in,out) :: g - double precision dimension(nmax),depend(nmax),intent(inout) :: df - double precision dimension(mmax,nmax),depend(mmax,nmax),intent(in,out) :: dg - double precision dimension(mnn2),depend(mnn2),intent(in,out) :: u - double precision dimension(n),depend(n),intent(in) :: xl - double precision dimension(n),depend(n),intent(in) :: xu - double precision dimension(nmax,nmax),depend(nmax,nmax),intent(in,out) :: c - double precision dimension(nmax),depend(nmax),intent(in,out) :: d - double precision intent(in) :: acc - double precision intent(in) :: accqp - double precision intent(in) :: stpmin - integer intent(in) :: maxfun - integer intent(in) :: maxit - integer intent(in) :: maxnm - double precision intent(in) :: rho - integer intent(in) :: mode - integer intent(in) :: iprint - integer intent(in) :: iout - character*(*) intent(in) :: ifile - integer intent(inout) :: ifail - logical intent(in) :: lmerit - logical intent(in) :: lql - external nlfunc - external nlgrad - end subroutine wrapper - end interface -end python module nlpqlp - -! This file was auto-generated with f2py (version:2_3974). -! See http://cens.ioc.ee/projects/f2py2e/ diff --git a/pyoptsparse/pyoptsparse/pyNLPQLP/source/wrapper.F90 b/pyoptsparse/pyoptsparse/pyNLPQLP/source/wrapper.F90 deleted file mode 100644 index 53ce21198..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPQLP/source/wrapper.F90 +++ /dev/null @@ -1,91 +0,0 @@ -! This is pyOptSparse wrapper to NLPQLP. It currently only supports -! the serial version of NLPQLP. This file is used to catch the -! "reverse communication" call backs (that are not *actually* reverse -! mode call backs) and to call the *actual* user supplied -! function/gradient routines like all other *normal* optimizers. This -! is F90 wrapper and as such some of the work arrays etc are done as -! allocatable arrays here instead of in python. - -subroutine wrapper(np, m, me, mmax, n, nmax, mnn2, x, f, g, df, dg, u, xl, xu, & - c, d, acc, accqp, stpmin, maxfun, maxit, maxnm, rho, mode, iprint, iout, & - ifile, ifail, lmerit, lql, nlfunc, nlgrad) - - implicit none - - ! Input Variables - integer :: np, m, me, mmax, n, nmax, mnn2 - double precision :: X(nmax, np), F(np), G(mmax, np), df(nmax), dg(mmax, nmax) - double precision :: u(mnn2), xl(n), xu(n), c(nmax, nmax), d(nmax) - double precision :: acc, accqp, stpmin - integer :: maxit, maxnm, maxfun - double precision :: rho - character*(*) ifile - integer :: mode, iprint, iout, ifail - logical :: lmerit, lql - external nlfunc, nlgrad - - ! Local Variables - logical, allocatable, dimension(:) :: active - integer, allocatable :: kwa(:) - double precision, allocatable, dimension(:) :: wa - integer :: lwa, lkwa, lactiv - logical :: fail - external ql - - ! The structure of this routine is based on NLP_DEMOA.f90. It really - ! pains me to use goto statements, but they kind of make sense here. - - ifail = 0 - lwa = 23*N+4*M+3*MMAX+NP*(N+M+1)+150 + 3*NMAX*NMAX/2+10*NMAX+MMAX+M+1 - lkwa = n + 30 - lactiv = 2*m + 10 - - ! Allocate some workspace - allocate (wa(lwa), kwa(lkwa), active(lactiv)) - - ! Open the output file - open(unit=iout, file=trim(ifile), status='unknown') - - ! ------------ Call the user supplied function ---------------- -1 continue - - call nlfunc(m, me, mmax, n, f, g, x, active, fail) - call flush(iout) - if (fail) then - ! NLPQLP says to set ifail to -10 and it will back-off on the - ! step and try again - ifail = -10 - print *, "+===========================================+" - print *, "| Failed user supplied function in NLPQLP |" - print *, "+===========================================+" - end if - - ! Now go back to NLPQLP IF this ISN'T the first pass when ifail == 0 - if (ifail == -1 .or. ifail == -10) goto 4 - - ! ------------ Call the user supplied gradient ---------------- -2 continue - call nlgrad(m, me, mmax, n, f, g, df, dg, x, active, wa) - call flush(iout) - ! Now go back to NLPQLP - if (ifail == -2) goto 4 - - ! -------------------------------------------------------------- -4 continue - - ! The actual NLPQLP run command. - call nlpqlp (np, m, me, mmax, n, nmax, mnn2, x, f, g, & - df, dg, u, xl, xu, c, d, acc, accqp, stpmin, maxfun, maxit, & - maxnm, rho, iprint, mode, iout, ifail, wa, lwa, kwa, lkwa, & - active, lactiv, lql, ql) - - ! Now check to see what NLPQL has told us with the ifail call - if (ifail == -1) goto 1 - if (ifail == -2) goto 2 - - ! If we're here than NLPQL has finished. Clean up this routine and - ! return to python. - deallocate(wa, kwa, active) - close(iout) - -end subroutine wrapper diff --git a/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/__init__.py b/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/pyNLPY_AUGLAG.py b/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/pyNLPY_AUGLAG.py deleted file mode 100644 index 512e336ae..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/pyNLPY_AUGLAG.py +++ /dev/null @@ -1,783 +0,0 @@ -#/bin/env python -""" -pyNLPY_AUGLAG - A wrapper for the matrix-free augmented Lagrangian algorithm -from the NLPy package. This optimizer can exploit sparsity in the constraint -blocks. - -Some assumptions to get this wrapper working: -- the NLPy package has been downloaded from Github and installed locally - -Copyright (c) 2014 by Andrew Lambe -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Andrew Lambe (ABL) -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# NLPy Library -# ============================================================================= -try: - from nlpy.model.mfnlp import MFModel - from nlpy.optimize.solvers.sbmin import SBMINTotalLqnFramework - from nlpy.optimize.solvers.sbmin import SBMINPartialLqnFramework - from nlpy.optimize.solvers.sbmin import SBMINSplitLqnFramework - from nlpy.optimize.solvers.tron import TronPartialLqnFramework - from nlpy.optimize.solvers.tron import TronSplitLqnFramework - from nlpy.optimize.solvers.tron import TronTotalLqnFramework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianPartialLsr1Framework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianPartialLsr1TronFramework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianSplitLsr1Framework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianSplitSr1Framework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianSplitLsr1TronFramework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianTotalLsr1AdjBroyAFramework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianTotalSr1AdjBroyAFramework - from nlpy.optimize.solvers.auglag2 import AugmentedLagrangianTotalLsr1AdjBroyATronFramework -except: - MFModel=None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -import copy -import signal -from contextlib import contextmanager -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -eps = numpy.finfo(1.0).eps -import logging -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_gradient import Gradient -from ..pyOpt_error import Error - -# ============================================================================= -# Timeout Class -# ============================================================================= -class TimeoutException(Exception): pass - -@contextmanager -def time_limit(seconds): - def signal_handler(signum, frame): - raise TimeoutException("Timed out!") - signal.signal(signal.SIGALRM, signal_handler) - signal.alarm(seconds) - try: - yield - finally: - signal.alarm(0) - -# ============================================================================= -# NLPy Optimizer Class -# ============================================================================= -class NLPY_AUGLAG(Optimizer): - """ - NLPY_AUGLAG Optimizer Class - Inherited from Optimizer Abstract Class - """ - - def __init__(self, *args, **kwargs): - """ - NLPY_AUGLAG Optimizer Class Initialization - """ - - name = 'NLPY_AUGLAG' - category = 'Local Optimizer' - # Default options go here - many to be added - defOpts = { - 'Logger Name':[str,'nlpy_logging'], - 'Prefix':[str,'./'], - 'Save Current Point':[bool,True], - 'Warm Restart':[bool,False], - 'Absolute Optimality Tolerance':[float,1.0e-6], - 'Relative Optimality Tolerance':[float,1.0e-6], - 'Absolute Feasibility Tolerance':[float,1.0e-6], - 'Relative Feasibility Tolerance':[float,1.0e-6], - 'Number of Quasi-Newton Pairs':[int,5], - 'Feasibility Quasi-Newton Pairs':[int,5], - 'Use N-Y Backtracking':[bool,True], - 'Use Magical Steps':[bool,True], - # 'Use Tron':[bool,False], - 'Use Least-Squares Multipliers':[bool,False], - 'Use Damped Multiplier Update':[bool,True], - 'Use Quasi-Newton Jacobian':[bool,True], - 'Use Limited-Memory Approach':[bool,False], - 'Use Full-Memory Approach':[bool,False], - 'Use Tron':[bool,True], - 'Penalty Parameter':[float,10.], - 'Penalty Scaling':[float,0.1], - 'Maximum Inner Iterations':[int, 500], - 'Maximum Outer Iterations':[int, 20], - 'Maximum Time':[int,172000] - } - # Inform/Status codes go here - informs = { - 1: 'Current point could not be improved', - 0: 'Successfully converged', - -1: 'Maximum number of iterations reached', - -2: 'Problem appears to be infeasible', - -3: 'Solver stopped on user request', - -5: 'Maximum run time exceeded' - } - self.set_options = [] - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - # Additional Timing and call counters used by the matrix-free interface - self.userJProdTime = 0.0 - self.userJTProdTime = 0.0 - self.userJProdCalls = 0 - self.userJTProdCalls = 0 - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, timeLimit=None, - storeSens=True): - """ - This is the main routine used to call the optimizer. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function or list of functions. - Specifiy method to compute sensitivities. To explictly - use pyOptSparse gradient class to do the derivatives with - finite differenes use 'FD'. 'sens' may also be 'CS' - which will cause pyOptSpare to compute the derivatives - using the complex step method. Finally, 'sens' may be a - python function handle which is expected to compute the - sensitivities directly. For expensive function evaluations - and/or problems with large numbers of design variables - this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is 'FD' and 1e-40j when sens is 'CS'. - - sensMode : str - Use 'pgc' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point does - not match the history, function and gradient evaluations - revert back to normal evaluations. - - timeLimit : number - Number of seconds to run the optimization before a - terminate flag is given to the optimizer and a "clean" - exit is performed. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if MFModel is None: - raise Error('There was an error importing nlpy. nlpy must \ -be installed to use NLPY_AUGLAG.') - - self.callCounter = 0 - - # NLPy *can* handle unconstrained problems cleanly - # Check if we still need this later - # if len(optProb.constraints) == 0: - # self.unconstrained = True - # optProb.dummyConstraint = True - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - - self._setInitialCacheValues() - blx, bux, xs = self._assembleContinuousVariables() - - # Redefined _setSens function for the matrix-free case - self._setSens(sens, sensStep, sensMode) - ff = self._assembleObjective() - - if self.optProb.nCon > 0: - # We need to reorder this full jacobian...so get ordering: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne','ni','le','li'], oneSided=False) - self.optProb.jacIndices = indices - # Construct the inverse operator to self.optProb.jacIndices - self.optProb.jacIndicesInv = numpy.argsort(self.optProb.jacIndices) - self.optProb.fact = fact - self.optProb.offset = numpy.zeros_like(indices) - ncon = len(indices) - - # Count the number of nonlinear constraints for the quasi-Newton block - # (A somewhat costly way to do this) - tmp0, tmp1, tmp2, tmp3 = self.optProb.getOrdering( - ['ne','ni'], oneSided=False) - sparse_index = len(tmp0) - else: - blc = numpy.array([]) - buc = numpy.array([]) - sparse_index = 0 - - # Since this algorithm exploits parallel computing, define the - # callbacks on all processors - def obj(x): - fobj, fail = self._masterFunc(x, ['fobj']) - return fobj - - def cons(x): - fcon, fail = self._masterFunc(x, ['fcon']) - return fcon.copy() - - # Gradient callbacks are specialized for the matrix-free case - if self.matrix_free == True: - - # Note the different tags for calling matrix-free and - # standard matrix-vector product functions - - # Also note the different 'masterFunc' call for the objective - # gradient. This is necessary as the structure of the callback - # functions is fundamentally different. - - def grad(x): - gobj, fail = self._masterFunc3(x, None, ['gobj']) - return gobj.copy() - - def jprod(x,p,sparse_only=False): - q, fail = self._masterFunc3(x, p, ['jac_prod'], sparse_only=sparse_only) - return q.copy() - - def jtprod(x,q,sparse_only=False): - p, fail = self._masterFunc3(x, q, ['jac_T_prod'], sparse_only=sparse_only) - return p.copy() - - else: - - def grad(x): - gobj, fail = self._masterFunc(x, ['gobj']) - return gobj.copy() - - def jprod(x,p,sparse_only=False): - q, fail = self._masterFunc3(x, p, ['gcon_prod'], sparse_only=sparse_only) - return q.copy() - - def jtprod(x,q,sparse_only=False): - p, fail = self._masterFunc3(x, q, ['gcon_T_prod'], sparse_only=sparse_only) - return p.copy() - - # end if - - # Step 2: Set up the optimizer with all the necessary functions - nlpy_problem = MFModel(n=self.optProb.ndvs,m=self.optProb.nCon,name=optProb.name,x0=xs, - Lvar=blx, Uvar=bux, Lcon=blc, Ucon=buc) - nlpy_problem.obj = obj - nlpy_problem.cons = cons - nlpy_problem.grad = grad - nlpy_problem.jprod = jprod - nlpy_problem.jtprod = jtprod - - # Set up the loggers on one proc only - if self.optProb.comm.rank == 0: - lprefix = self.options['Prefix'][1] - lname = self.options['Logger Name'][1] - - fmt = logging.Formatter('%(name)-15s %(levelname)-8s %(message)s') - hndlr = logging.FileHandler(lprefix+lname+'_more.log',mode='w') - hndlr.setLevel(logging.DEBUG) - hndlr.setFormatter(fmt) - hndlr2 = logging.FileHandler(lprefix+lname+'.log',mode='w') - hndlr2.setLevel(logging.INFO) - hndlr2.setFormatter(fmt) - - # Configure auglag logger. - auglaglogger = logging.getLogger('nlpy.auglag') - auglaglogger.setLevel(logging.DEBUG) - auglaglogger.addHandler(hndlr) - auglaglogger.addHandler(hndlr2) - auglaglogger.propagate = False - - # Configure sbmin logger. - sbminlogger = logging.getLogger('nlpy.sbmin') - sbminlogger.setLevel(logging.DEBUG) - sbminlogger.addHandler(hndlr) - sbminlogger.addHandler(hndlr2) - sbminlogger.propagate = False - - # Configure bqp logger. - bqplogger = logging.getLogger('nlpy.bqp') - bqplogger.setLevel(logging.INFO) - bqplogger.addHandler(hndlr) - bqplogger.propagate = False - - # Configure tron logger for the case of using tron - tronlogger = logging.getLogger('nlpy.tron') - tronlogger.setLevel(logging.DEBUG) - tronlogger.addHandler(hndlr) - tronlogger.addHandler(hndlr2) - tronlogger.propagate = False - - # This logger is only used for debugging - # sr1logger = logging.getLogger('nlpy.lsr1') - # sr1logger.setLevel(logging.DEBUG) - # sr1logger.addHandler(hndlr) - # sr1logger.propagate = False - - # pyOpt History logging - only do this on one processor? - # dummy = self._setHistory(storeHistory,hotStart,coldStart,None) - self._setHistory(storeHistory, hotStart) - - else: - # Only the root proc stores the history - self._setHistory("", hotStart) - # end if - - # This optimizer has no hot start capability (too many vectors) - # self._hotStart(storeHistory, hotStart) - - # Step 3: Pass options and solve the problem - timeA = time.time() - - # Also need to pass the number of dense constraints - # Assume the dense block is listed first in the problem definition - # ** Simple sol'n: assume dense block is all nonlinear constraints ** - if self.options['Use Tron'][1]: - if self.options['Use Quasi-Newton Jacobian'][1]: - solver = AugmentedLagrangianTotalLsr1AdjBroyATronFramework(nlpy_problem, - TronTotalLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - sparse_index=sparse_index, - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - elif self.options['Use Limited-Memory Approach'][1]: - solver = AugmentedLagrangianSplitLsr1TronFramework(nlpy_problem, - TronSplitLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - feas_qn_pairs=self.options['Feasibility Quasi-Newton Pairs'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - sparse_index=sparse_index, - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - else: - # Try matrix-vector products with the exact Jacobian - # Useful for comparisons, but not recommended for larger problems - solver = AugmentedLagrangianPartialLsr1TronFramework(nlpy_problem, - TronPartialLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - else: - if self.options['Use Quasi-Newton Jacobian'][1]: - solver = AugmentedLagrangianTotalLsr1AdjBroyAFramework(nlpy_problem, - SBMINTotalLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - sparse_index=sparse_index, - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - elif self.options['Use Limited-Memory Approach'][1]: - solver = AugmentedLagrangianSplitLsr1Framework(nlpy_problem, - SBMINSplitLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - feas_qn_pairs=self.options['Feasibility Quasi-Newton Pairs'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - sparse_index=sparse_index, - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - elif self.options['Use Full-Memory Approach'][1]: - solver = AugmentedLagrangianSplitSr1Framework(nlpy_problem, - SBMINSplitLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - feas_qn_pairs=self.options['Feasibility Quasi-Newton Pairs'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - sparse_index=sparse_index, - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - else: - # Try matrix-vector products with the exact Jacobian - # Useful for comparisons, but not recommended for larger problems - solver = AugmentedLagrangianPartialLsr1Framework(nlpy_problem, - SBMINPartialLqnFramework, - omega_abs=self.options['Absolute Optimality Tolerance'][1], - eta_abs=self.options['Absolute Feasibility Tolerance'][1], - omega_rel=self.options['Relative Optimality Tolerance'][1], - eta_rel=self.options['Relative Feasibility Tolerance'][1], - qn_pairs=self.options['Number of Quasi-Newton Pairs'][1], - least_squares_pi=self.options['Use Least-Squares Multipliers'][1], - data_prefix=self.options['Prefix'][1], - save_data=self.options['Save Current Point'][1], - warmstart=self.options['Warm Restart'][1], - rho_init=self.options['Penalty Parameter'][1], - tau=self.options['Penalty Scaling'][1], - max_inner_iter=self.options['Maximum Inner Iterations'][1], - max_outer_iter=self.options['Maximum Outer Iterations'][1], - damped_pi=self.options['Use Damped Multiplier Update'][1]) - - # if self.optProb.comm.rank == 0: - # print("Starting solve") - try: - with time_limit(self.options['Maximum Time'][1]): - solver.solve(ny=self.options['Use N-Y Backtracking'], magic_steps_agg=self.options['Use Magical Steps']) - except TimeoutException: - solver.status = -5 - solver.tsolve = float(self.options['Maximum Time'][1]) - - # Step 4: Collect and return solution - optTime = time.time() - timeA - - if self.storeHistory: - self.hist.close() - - sol_inform = {} - sol_inform['value'] = solver.status - sol_inform['text'] = self.informs[solver.status] - xopt = solver.x[:self.optProb.ndvs].copy() - sol = self._createSolution(optTime, sol_inform, solver.f, xopt) - - return sol - - - def _clearTimings(self): - """Clear timings and call counters""" - Optimizer._clearTimings(self) - self.userJProdTime = 0.0 - self.userJTProdTime = 0.0 - self.userJProdCalls = 0 - self.userJTProdCalls = 0 - - - def _setSens(self, sens, sensStep, sensMode): - """ - For the matrix-free approach, the sens argument is actually a list - of three separate functions. The order of these functions must be - [obj_grad, jac_prod, jac_t_prod]. - - Otherwise, this function is identical to that of the base class. - """ - - self.matrix_free = False - if sens is None: - raise Error("'None' value given for sens. Must be one \ -of 'FD' or 'CS' or a user supplied function or group of functions.") - elif hasattr(sens, 'append'): - # A list of functions has been provided - self.sens = sens - self.matrix_free = True - elif hasattr(sens, '__call__'): - # A single function has been provided, old-style sensitivities - self.sens = sens - elif sens.lower() in ['fd', 'cs']: - # Create the gradient class that will operate just like if - # the user supplied fucntion - self.sens = Gradient(self.optProb, sens.lower(), sensStep, - sensMode, self.optProb.comm) - else: - raise Error("Unknown value given for sens. Must be None, 'FD', \ - 'CS', a python function handle, or a list of handles") - - - def _masterFunc3(self, x, invec, evaluate, writeHist=True, sparse_only=False): - """ - A shell function for the matrix-free case, called on all processors. - - ** Right now, we assume that the 'evaluate' list has only one element ** - """ - - timeAA = time.time() - - xscaled = self.optProb.invXScale*x - xuser = self.optProb.processX(xscaled) - - masterFail = False - - # History storage is a little different for the matrix-free case. - - # Storing the whole set of input and output vectors is ridiculously - # expensive, so we only store function information. - - # Set basic parameters in history - hist = {'xuser': xuser} - returns = [] - - # Evaluate the gradient of the objective function only - if 'gobj' in evaluate: - # if self.optProb.comm.rank == 0: - # print("userObjCalls = %d"%self.userObjCalls) - # print("userSensCalls = %d"%self.userSensCalls) - if numpy.linalg.norm(x-self.cache['x']) > eps: - # Previous evaluated point is *different* than the - # point requested for the derivative. Recusively call - # the routine with ['fobj', and 'fcon'] - self._masterFunc2(x, ['fobj', 'fcon'], writeHist=False) - - if self.cache['gobj'] is None: - # Only the objective function is cached in this version - timeA = time.time() - gobj, fail = self.sens[0](xuser, funcs=self.cache['funcs']) - self.userSensTime += time.time()-timeA - self.userSensCalls += 1 - # User values are stored immediately - self.cache['gobj_user'] = copy.deepcopy(gobj) - - # Process objective gradient for optimizer - gobj = self.optProb.processObjectiveGradient(gobj) - - # Set the cache values - self.cache['gobj'] = gobj.copy() - - # Update fail flag - masterFail = masterFail or fail - - # gobj is now in the cache - returns.append(self.cache['gobj']) - # hist['gobj'] = self.cache['gobj_user'] - - # Evaluate the matrix-vector products - if 'gcon_prod' in evaluate or 'gcon_T_prod' in evaluate: - if numpy.linalg.norm(x-self.cache['x']) > eps: - # Previous evaluated point is *different* than the - # point requested for the derivative. Recusively call - # the routine with ['fobj', and 'fcon'] - self._masterFunc2(x, ['fobj', 'fcon'], writeHist=False) - - # Now, the point has been evaluated correctly so we - # determine if we have to run the sens calc: - if self.cache['gcon'] is None: - timeA = time.time() - # gobj, gcon, fail = self.sens( - # xuser, self.cache['fobj'], self.cache['fcon_user']) - funcsSens, fail = self.sens(xuser, self.cache['funcs']) - self.userSensTime += time.time()-timeA - self.userSensCalls += 1 - # User values are stored immediately - # self.cache['gobj_user'] = copy.deepcopy(gobj) - # self.cache['gcon_user'] = copy.deepcopy(gcon) - self.cache['funcsSens'] = copy.deepcopy(funcsSens) - - # Process objective gradient for optimizer - gobj = self.optProb.processObjectiveGradient(funcsSens) - - # Process constraint gradients for optimizer - gcon = self.optProb.processConstraintJacobian(funcsSens) - gcon = self._convertJacobian(gcon) - - # Set cache values - self.cache['gobj'] = gobj.copy() - self.cache['gcon'] = gcon.copy() - - # Update fail flag - masterFail = masterFail or fail - else: - # gcon is now in the cache, so we just retrieve it - gcon = self.cache['gcon'] - - if 'gcon_prod' in evaluate: - outvec = gcon.dot(invec) - else: - outvec = gcon.T.dot(invec) - - # Set return values and history logging - returns.append(outvec) - # hist['invec'] = invec - # hist['outvec'] = outvec - - elif 'jac_prod' in evaluate or 'jac_T_prod' in evaluate: - # Call the true matrix-vector product functions, no matrix formation - # Convert input arrays to dictionaries before calling the callback function - # Also, scale vectors appropriately before and after the products are formed - if 'jac_prod' in evaluate: - invec = self.optProb.invXScale*invec - invec = self.optProb.processX(invec) - timeA = time.time() - outvec, fail = self.sens[1](xuser, invec, sparse_only=sparse_only, funcs=self.cache['funcs']) - self.userJProdTime += time.time() - timeA - self.userJProdCalls += 1 - outvec = self.optProb.processConstraints(outvec) - else: - invec = self.optProb.deProcessConstraints(invec) - timeA = time.time() - outvec, fail = self.sens[2](xuser, invec, sparse_only=sparse_only, funcs=self.cache['funcs']) - self.userJTProdTime += time.time() - timeA - self.userJTProdCalls += 1 - outvec = self.optProb.deProcessX(outvec) - outvec = self.optProb.invXScale*outvec - - # prodTime = time.time() - timeA - # if 'jac_prod' in evaluate: - # else: - - # Update fail flag - masterFail = masterFail or fail - - # Set return values and history logging - returns.append(outvec) - # hist['invec'] = invec - # hist['outvec'] = outvec - - # end if - - # Put the fail flag in the history - # hist['fail'] = masterFail - - # Write history if necessary - # if self.optProb.comm.rank == 0 and writeHist and self.storeHistory: - # self.hist.write(self.callCounter, hist) - - # We can now safely increment the call counter - self.callCounter += 1 - - # Tack the fail flag on at the end - returns.append(masterFail) - # Interface time specific to the Jacobian vector products - self.interfaceTime += time.time() - timeAA - - return returns - - - def _createSolution(self, optTime, sol_inform, obj, xopt): - """ - Create the solution for the optimizer and append the data that is - specific to the matrix-free optimizer. - """ - - sol = Optimizer._createSolution(self, optTime, sol_inform, obj, xopt) - sol.userJProdTime = self.userJProdTime - sol.userJProdCalls = self.userJProdCalls - sol.userJTProdTime = self.userJTProdTime - sol.userJTProdCalls = self.userJTProdCalls - - # Recompute the interface time and optimizer code time to account for the - # separate matrix-vector product interface - sol.interfaceTime = sol.interfaceTime - self.userJProdTime - self.userJTProdTime - sol.optCodeTime = sol.optTime - self.interfaceTime - - # Since NLPy optimizers exploit MPI, we have to add the objective - # function here since the broadcasting of the base class is not done - sol.objFun = self.optProb.objFun - - return sol - - - def _on_setOption(self, name, value): - """ - Set Optimizer Option Value (Optimizer Specific Routine) - - Parameters - ---------- - name -> STRING: Option Name - value: Option value - """ - - self.set_options.append([name, value]) - - - def _on_getOption(self, name): - """ - Get Optimizer Option Value (Optimizer Specific Routine) - - Parameters - ---------- - name -> STRING: Option Name - """ - - pass - - - def _on_getInform(self, infocode): - """ - Get Optimizer Result Information (Optimizer Specific Routine) - - Parameters - ---------- - infocode -> INT: Status code - """ - - pass diff --git a/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/setup.py b/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/setup.py deleted file mode 100644 index e0def1095..000000000 --- a/pyoptsparse/pyoptsparse/pyNLPY_AUGLAG/setup.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyNLPY_AUGLAG',parent_package,top_path) - - return config - - -if __name__ == '__main__': - from numpy.distutils.core import setup - setup(**configuration(top_path='').todict()) - diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/LICENSE b/pyoptsparse/pyoptsparse/pyNOMAD/LICENSE deleted file mode 100644 index 3c83ca6e4..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search -Creators: - Mark A. Abramson - Mark.A.Abramson@boeing.com - Charles Audet - www.gerad.ca/Charles.Audet - J.E. Dennis Jr. - www.caam.rice.edu/~dennis - Sebastien Le Digabel - www.gerad.ca/Sebastien.Le.Digabel - Christophe Tribes - -Contact: nomad@gerad.ca - -GNU Lesser General Public License v 3.0. diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/README b/pyoptsparse/pyoptsparse/pyNOMAD/README deleted file mode 100644 index cb5899e8a..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the nomad class definition -and the nomad shared library, _nomad.so or _nomad.pyd. diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/__init__.py b/pyoptsparse/pyoptsparse/pyNOMAD/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/pyNOMAD.py b/pyoptsparse/pyoptsparse/pyNOMAD/pyNOMAD.py deleted file mode 100644 index fd01405a6..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/pyNOMAD.py +++ /dev/null @@ -1,152 +0,0 @@ -# File: pyNOMAD.py -# Author: Nicolas Bons -# Description: This program finds the optimum solution for a given objective -# function using the optimization package NOMAD. - -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# NOMAD Library -# ============================================================================= -try: - from . import nomad -except ImportError: - nomad = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -# ============================================================================= -# SLSQP Optimizer Class -# ============================================================================= - -class NOMAD(Optimizer): - - def __init__(self, *args, **kwargs): - name = 'NOMAD' - category = 'MADS Optimizer' - defOpts = { - # NOMAD Options - 'maxiter':[int, 1000000], # Maximum number of function evaluations - 'minmeshsize':[float, 1e-12], # Minimum refinement size of mesh - 'minpollsize':[float, 1e-12], # Minimum step size for polling procedure - 'displaydegree':[int, 0], # 0-none, 1-minimal display, 2-normal display, 3-full display - 'printfile':[int, 1] # 0-no output file, 1-output to NOMAD.out - } - informs = {} - self.set_options = [] - if nomad is None: - raise Error('There was an error importing the compiled' - 'nomad module') - - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True): - - if len(optProb.constraints) == 0: - # If the user *actually* has an unconstrained problem, - # slsqp sort of chokes with that....it has to have at - # least one constraint. So we will add one - # automatically here: - self.unconstrained = True - optProb.dummyConstraint = False - - self.callCounter = 0 - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - blx, bux, xs = self._assembleContinuousVariables() - xs = numpy.maximum(xs, blx) - xs = numpy.minimum(xs, bux) - n = len(xs) - ff = self._assembleObjective() - - oneSided = True - if self.unconstrained: - m = 0 - meq = 0 - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'le', 'ni', 'li'], oneSided=oneSided, noEquality=True) - m = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - if self.optProb.comm.rank == 0: - # Set history/hotstart - self._setHistory(storeHistory, hotStart) - - # Define the objective function - #-------------------------------------------------------------- - def objfun(o, x_tuple): - x = numpy.asarray(x_tuple) - fail = False - fobj, fcon, fail = self._masterFunc(x, ['fobj', 'fcon']) - f = [fobj] - g = fcon.tolist() - if not fail: - cnt_eval = [0] - else: - cnt_eval = [1] - funcallreturns = cnt_eval + f + g - return funcallreturns - - # Set objfun as the callback function - problemset = nomad.NomadLinker() - problemset.setCallback(objfun) - - # Setup NOMAD options - maxit = self.getOption('maxiter') - min_mesh_size = self.getOption('minmeshsize') - min_poll_size = self.getOption('minpollsize') - display_degree = self.getOption('displaydegree') - print_file = self.getOption('printfile') - - # Run NOMAD - t0 = time.time() - solutionset = problemset.call(n, m+2, xs, blx, bux, min_poll_size, min_mesh_size, maxit, display_degree, print_file) - ff = solutionset[1] - optTime = time.time() -t0 - - if self.storeHistory: - self.hist.close() - - # Broadcast a -1 to indicate NOMAD has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - #sol_inform['value'] = inform - #sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name, value): - pass diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/setup.py b/pyoptsparse/pyoptsparse/pyNOMAD/setup.py deleted file mode 100644 index ff39cb4dc..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/setup.py +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env python - -import os,sys - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyNOMAD',parent_package,top_path) - - # platform-specific settings - extra_link_args = [] - if sys.platform == "darwin": - extra_link_args.append("-bundle") - #end - - config.add_library('nomad', - sources=[os.path.join('source/nomad_src', '*.cpp')]) - config.add_extension('_nomad', - sources=['source/NomadLinker.i','source/NomadLinker.cpp'], - include_dirs=['source', 'source/nomad_src'], - libraries=['nomad'], - extra_link_args=extra_link_args, - extra_compile_args=['-fPIC'], - swig_opts=[]) - config.add_data_files('LICENSE','README') - - return config diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/Callback.h b/pyoptsparse/pyoptsparse/pyNOMAD/source/Callback.h deleted file mode 100644 index 21a55183a..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/Callback.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef CALLBACK_H -#define CALLBACK_H - -#include - -class NomadLinker; - -class Callback -{ - public: - Callback() {} - virtual ~Callback() {} - virtual void call( NomadLinker& object, std::vector xvec ) {} -}; - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.cpp deleted file mode 100644 index aa801b22e..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.cpp +++ /dev/null @@ -1,156 +0,0 @@ -#include "NomadLinker.h" -#include "Callback.h" - -#include -#include "nomad.hpp" -using namespace NOMAD; - -NomadLinker::NomadLinker() : callback_(NULL) {} - -NomadLinker::~NomadLinker() -{ -} - -void NomadLinker::setCallback(Callback &callback) -{ - callback_ = &callback; -} - -std::vector NomadLinker::call( int n, int m, double* x, int xdim, double* lb, int - lbdim, double* ub, int ubdim, double min_poll_size, double min_mesh_size, int max_bbe, int display_degree, int print_file ) -{ - if( !callback_ ) - { - std::cerr << "No callback is set.\n"; - } - else - { - /*----------------------------------------*/ - /* The problem: the evaluation is made */ - /* by calling a FORTRAN routine */ - /*----------------------------------------*/ - class My_Evaluator : public Evaluator - { - private: - NomadLinker* nlobject; - public: - My_Evaluator( const Parameters &p , NomadLinker &nltransfer ) : Evaluator( p ) - { - nlobject = &nltransfer; - } - - ~My_Evaluator( void ) {} - - bool eval_x( Eval_Point &x, const Double &h_max, bool &count_eval ) const - { - int n = x.size(); - int m = x.get_bb_outputs().size(); - int i; - - // call the FORTRAN routine: - std::vector xvec( n ); - for( i=0; ipasscallback()->call( *nlobject, xvec ); - std::vector fxvec = nlobject->getSolution(); - - for ( i=0; i bbot( m ); // definition of output types: - bbot[0] = CNT_EVAL; - bbot[1] = OBJ; // first output : objective value to minimize - for( i=2; i -1e20 ) - plb[i] = lb[i]; - if( ub[i] < 1e20 ) - pub[i] = ub[i]; - } - p.set_X0( px0 ); - p.set_LOWER_BOUND( plb ); - p.set_UPPER_BOUND( pub ); - - // Stopping criteria - if(min_poll_size) - p.set_MIN_POLL_SIZE( min_poll_size); - if(min_mesh_size) - p.set_MIN_MESH_SIZE( min_mesh_size); - - // maximum number of black-box evaluations: - if( max_bbe > 0 ) - p.set_MAX_BB_EVAL( max_bbe ); - - // display degree: - p.set_DISPLAY_DEGREE( display_degree ); - // History file - if( print_file > 0 ) - p.set_HISTORY_FILE( "NOMAD.out" ); - // parameters validation: - p.check(); - - // custom evaluator creation: - My_Evaluator ev( p, *this); - - // algorithm creation and execution: - Mads mads( p, &ev ); - mads.run(); - - // get the solution: - const Eval_Point * bf = mads.get_best_feasible(); - if( bf ) - for( i=0; i transfer) -{ - solution = transfer; -} - -std::vector NomadLinker::getSolution() -{ - return solution; -} - diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.h b/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.h deleted file mode 100644 index eafb04651..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef NOMADLINKER_H -#define NOMADLINKER_H - -#include - -class Callback; - -class NomadLinker -{ - public: - NomadLinker(); - ~NomadLinker(); - void setCallback( Callback &callback); - std::vector call( int n, int m, double* x, int xdim, double* lb, int lbdim, - double* ub, int ubdim, double min_poll_size, double min_mesh_size, int max_bbe, int display_degree, int print_file ); - void setSolution( std::vector transfer); - std::vector getSolution(); - Callback* passcallback() { return callback_; } - - private: - std::vector solution; - Callback* callback_; -}; - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.i b/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.i deleted file mode 100644 index 6b576c903..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/NomadLinker.i +++ /dev/null @@ -1,44 +0,0 @@ -//-*- c++ -*- -%module nomad -%module(directors="1") nomad -%{ - #define SWIG_FILE_WITH_INIT - #include "Callback.h" - #include "NomadLinker.h" -%} -%feature("director") Callback; -%feature("nodirector") NomadLinker; - -%include "std_vector.i" -namespace std { - %template(fvector) vector; -} - -%include "numpy.i" -%init %{ -import_array(); -%} - -%apply (double* INPLACE_ARRAY1, int DIM1) {(double* x, int xdim)} -%apply (double* INPLACE_ARRAY1, int DIM1) {(double* lb, int lbdim)} -%apply (double* INPLACE_ARRAY1, int DIM1) {(double* ub, int ubdim)} - -%feature("pythonprepend") NomadLinker::setCallback(Callback&) %{ - if len(args) == 1 and (not isinstance(args[0], Callback) and callable(args[0])): - class CallableWrapper(Callback): - def __init__(self, f): - super(CallableWrapper, self).__init__() - self.f_ = f - def call(self, obj, x): - fx = self.f_(obj, x) - obj.setSolution(fx) - args = tuple([CallableWrapper(args[0])]) - args[0].__disown__() - elif len(args) == 1 and isinstance(args[0], Callback): - args[0].__disown__() - - -%} - -%include "Callback.h" -%include "NomadLinker.h" diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Barrier.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Barrier.cpp deleted file mode 100644 index 1fd0d03aa..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Barrier.cpp +++ /dev/null @@ -1,545 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Barrier.cpp - \brief Barrier for constraints handling (implementation) - \author Sebastien Le Digabel - \date 2010-04-12 - \see Barrier.hpp - */ -#include "Barrier.hpp" - -/*---------------------------------------------------------*/ -/* reset the barrier */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::reset ( void ) -{ - _prefilter.clear(); - _filter.clear(); - _h_max = _p.get_h_max_0(); - _best_feasible = NULL; - _ref = NULL; - _rho_leaps = 0; - _poll_center = NULL; - _sec_poll_center = NULL; - - if ( _peb_changes > 0 ) - _p.reset_PEB_changes(); - - _peb_changes = 0; - _peb_filter_reset = 0; - - _peb_lop.clear(); - _all_inserted.clear(); - - _one_eval_succ = _success = NOMAD::UNSUCCESSFUL; -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::display ( const Display & out ) const -{ - if ( _eval_type == NOMAD::SGTE ) - out << "surrogate barrier" << std::endl; - - if ( _p.get_barrier_type() == NOMAD::EB ) - out << "extreme barrier (EB)" << std::endl; - - else { - - out << "type : " - << ( (_p.get_barrier_type()==NOMAD::FILTER) ? "filter" : "progressive" ) - << std::endl - << "h_norm : " << _p.get_h_norm() << std::endl - << "h_min : " << _p.get_h_min() << std::endl - << "h_max : " << _h_max << std::endl; - if ( _p.get_barrier_type()==NOMAD::PB || _p.get_barrier_type()==NOMAD::PEB_P ) { - out << "poll center trigger rho : " << _p.get_rho() << std::endl - << "number of trigger leaps : " << _rho_leaps << std::endl; - if ( _p.get_barrier_type()==NOMAD::PEB_P ) - out << "number of PEB changes : " << _peb_changes << std::endl - << "number of PEB filter resets: " << _peb_filter_reset << std::endl; - } - if ( out.get_gen_dd() == NOMAD::FULL_DISPLAY ) - out << "number of pre-filter points: " << static_cast(_prefilter.size()) - << std::endl; - out << NOMAD::open_block ( "list of filter points (" - + NOMAD::itos ( _filter.size() ) - + ")" ) - << std::endl; - std::set::const_iterator end = _filter.end() , it; - for ( it = _filter.begin() ; it != end ; ++it ) - out << *it->get_point() << std::endl; - out.close_block(); - } - -#ifdef DEBUG - out << NOMAD::open_block ( "list of inserted points (" - + NOMAD::itos ( _all_inserted.size() ) - + ")" ) - << std::endl; - std::list::const_iterator it2 , end2 = _all_inserted.end(); - for ( it2 = _all_inserted.begin() ; it2 != end2 ; ++it2 ) - out << **it2 << std::endl; - out.close_block(); -#endif -} - -/*------------------------------------------------------------*/ -/* barrier update: invoked by Evaluator_Control::eval_lop() */ -/*------------------------------------------------------------*/ -void NOMAD::Barrier::update_and_reset_success ( void ) -{ - if ( ( _p.get_barrier_type() == NOMAD::PB || _p.get_barrier_type() == NOMAD::PEB_P ) && - _success != NOMAD::UNSUCCESSFUL ) { - - if ( _success == NOMAD::PARTIAL_SUCCESS ) { - - if ( _filter.empty() ) - throw Barrier::Update_Error ( "Barrier.cpp" , __LINE__ , - "filter empty after a partial success" ); - - std::set::const_iterator it = _filter.end(); - --it; - - while ( true ) { - - if ( it->get_point()->get_h().value() < _h_max.value() ) { - set_h_max ( it->get_point()->get_h() ); - break; - } - - if ( it == _filter.begin() ) - throw Barrier::Update_Error ( "Barrier.cpp" , __LINE__ , - "could not find a filter point with h < h_max after a partial success" ); - - --it; - } - } - - _ref = get_best_infeasible(); - if ( _ref ) - set_h_max ( _ref->get_h() ); - } - - // reset success types: - _one_eval_succ = _success = NOMAD::UNSUCCESSFUL; -} - -/*---------------------------------------------------------*/ -/* insertion of an Eval_Point in the barrier */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::insert ( const NOMAD::Eval_Point & x ) -{ - // we compare the eval types (_SGTE_ or _TRUTH_) of x and *this: - if ( x.get_eval_type() != _eval_type ) - throw Barrier::Insert_Error ( "Barrier.cpp" , __LINE__ , - "insertion of an Eval_Point into the bad Barrier object" ); - - // basic check: - if ( !x.is_eval_ok() ) { - _one_eval_succ = NOMAD::UNSUCCESSFUL; - return; - } - - // pre-filter: if tag(x) is already in the pre-filter, - // then return _UNSUCCESSFUL_: - size_t size_before = _prefilter.size(); - _prefilter.insert ( x.get_tag() ); - if ( _prefilter.size() == size_before ) { - _one_eval_succ = NOMAD::UNSUCCESSFUL; - return; - } - - // insertion in _all_inserted: - _all_inserted.push_back ( &x ); - - // other checks: - const NOMAD::Double & h = x.get_h(); - if ( !x.is_EB_ok () || - !x.get_f().is_defined () || - !h.is_defined () || - h.value() > _h_max.value() ) { - _one_eval_succ = NOMAD::UNSUCCESSFUL; - return; - } - - // insert_feasible or insert_infeasible: - _one_eval_succ = ( x.is_feasible ( _p.get_h_min() ) ) ? - insert_feasible ( x ) : insert_infeasible(x); - - if ( _one_eval_succ > _success ) - _success = _one_eval_succ; -} - -/*---------------------------------------------------------*/ -/* update the barrier from another barrier */ -/* (used by VNS search) */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::insert ( const Barrier & b ) -{ - _one_eval_succ = _success = NOMAD::UNSUCCESSFUL; - - NOMAD::Eval_Point * modifiable_x; - - std::list::const_iterator it , end = b._all_inserted.end(); - for ( it = b._all_inserted.begin() ; it != end ; ++it ) { - - modifiable_x = &NOMAD::Cache::get_modifiable_point ( **it ); - - modifiable_x->set_direction ( NULL ); - modifiable_x->set_poll_center_type ( NOMAD::UNDEFINED_POLL_CENTER_TYPE ); - modifiable_x->set_user_eval_priority ( NOMAD::Double() ); - modifiable_x->set_rand_eval_priority ( NOMAD::Double() ); - - insert ( **it ); - - if ( _one_eval_succ > _success ) - _success = _one_eval_succ; - } -} - -/*---------------------------------------------------------*/ -/* insertion of a feasible point (private) */ -/*---------------------------------------------------------*/ -NOMAD::success_type NOMAD::Barrier::insert_feasible ( const NOMAD::Eval_Point & x ) -{ - if ( !_best_feasible || ( x.get_f().value() < _best_feasible->get_f().value() ) ) { - _best_feasible = &x; - return NOMAD::FULL_SUCCESS; - } - return NOMAD::UNSUCCESSFUL; -} - -/*---------------------------------------------------------*/ -/* filter insertion (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::filter_insertion ( const NOMAD::Eval_Point & x , bool & insert ) -{ - if ( _filter.empty() ) { - _filter.insert (&x); - insert = true; - } - else { - - insert = false; - std::set::iterator it = _filter.begin(); - while ( it != _filter.end() ) { - if ( x < *(it->get_point()) ) { - _filter.erase(it++); - insert = true; - continue; - } - - ++it; - } - - if ( !insert ) { - insert = true; - std::set::iterator end = _filter.end(); - for ( it = _filter.begin() ; it != end ; ++it ) { - if ( *(it->get_point()) < x ) { - insert = false; - break; - } - } - } - - if ( insert ) - _filter.insert (&x); - } -} - -/*---------------------------------------------------------*/ -/* insertion of an infeasible point (private) */ -/*---------------------------------------------------------*/ -NOMAD::success_type NOMAD::Barrier::insert_infeasible ( const NOMAD::Eval_Point & x ) -{ - const NOMAD::Eval_Point * old_bi = get_best_infeasible(); - - // filter insertion: - // ----------------- - bool insert; - filter_insertion ( x , insert ); - - // filter: - // ------- - if ( _p.get_barrier_type() == NOMAD::FILTER ) { - const NOMAD::Eval_Point * bi = get_best_infeasible(); - if ( !bi ) - return NOMAD::UNSUCCESSFUL; - if ( old_bi ) { - if ( bi->get_h().value() < old_bi->get_h().value() ) - return NOMAD::FULL_SUCCESS; - if ( insert ) - return NOMAD::PARTIAL_SUCCESS; - return NOMAD::UNSUCCESSFUL; - } - return NOMAD::FULL_SUCCESS; - } - - // progressive barrier: - // -------------------- - - // with PEB constraints, we remember all points that we tried to insert: - if ( _p.get_barrier_type() == NOMAD::PEB_P ) - _peb_lop.push_back ( &x ); - - // first infeasible successes are considered as partial successes - // (improving iterations) - if ( !_ref ) - return NOMAD::PARTIAL_SUCCESS; - - double hx = x.get_h().value(); - double fx = x.get_f().value(); - double hr = _ref->get_h().value(); - double fr = _ref->get_f().value(); - - // failure: - if ( hx > hr || ( hx == hr && fx >= fr ) ) - return NOMAD::UNSUCCESSFUL; - - // partial success: - if ( fx > fr ) - return NOMAD::PARTIAL_SUCCESS; - - // full success: - return NOMAD::FULL_SUCCESS; -} - -/*---------------------------------------------------------*/ -/* get_best_infeasible() */ -/*---------------------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Barrier::get_best_infeasible ( void ) const -{ - if ( _filter.empty() || _p.get_barrier_type() == NOMAD::EB ) - return NULL; - - if ( _p.get_barrier_type() == NOMAD::FILTER ) - return _filter.begin()->get_point(); // original - - return (--_filter.end())->get_point(); // original -} - - -/*---------------------------------------------------------*/ -/* get_best_infeasible_min_viol() */ -/*---------------------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Barrier::get_best_infeasible_min_viol ( void ) const -{ - if ( _filter.empty() || _p.get_barrier_type() == NOMAD::EB ) - return NULL; - - if ( _p.get_barrier_type() == NOMAD::FILTER ) - return (--_filter.end())->get_point(); - - return _filter.begin()->get_point(); -} - - - -/*---------------------------------------------------------*/ -/* poll center selection */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::select_poll_center ( NOMAD::success_type last_it_success ) -{ - const NOMAD::Eval_Point * best_infeasible = get_best_infeasible(); - - _sec_poll_center = NULL; - if ( !_best_feasible && !best_infeasible ) { - _poll_center = NULL; - return; - } - if ( !best_infeasible ) { - _poll_center = _best_feasible; - return; - } - if ( !_best_feasible ) { - _poll_center = best_infeasible; - return; - } - - // filter: - if ( _p.get_barrier_type() == NOMAD::FILTER ) { - - if ( !_poll_center ) { - _poll_center = _best_feasible; - return; - } - - // switch: - if ( last_it_success == NOMAD::UNSUCCESSFUL ) - _poll_center = ( _poll_center==best_infeasible ) ? - _best_feasible : best_infeasible; - return; - } - - // progressive barrier: - if ( _p.get_barrier_type() == NOMAD::PB || _p.get_barrier_type() == NOMAD::PEB_P ) { - - const NOMAD::Point * last_poll_center = _poll_center; - - if ( best_infeasible->get_f() < (_best_feasible->get_f() - _p.get_rho()) ) { - _poll_center = best_infeasible; - _sec_poll_center = _best_feasible; - } - else { - _poll_center = _best_feasible; - _sec_poll_center = best_infeasible; - } - if ( _poll_center != last_poll_center ) - ++_rho_leaps; - } -} - -/*---------------------------------------------------------*/ -/* change the value of _h_max (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Barrier::set_h_max ( const NOMAD::Double & h_max ) -{ - // _h_max update: - _h_max = h_max; - - // we remove all filter points x such that h(x) > h_max: - if ( !_filter.empty() ) { - - if ( _filter.begin()->get_point()->get_h().value() > _h_max.value() ) { - _filter.clear(); - return; - } - - std::set::iterator it = _filter.end(); - do - --it; - while ( it != _filter.begin() && - it->get_point()->get_h().value() > _h_max.value() ); - ++it; - _filter.erase ( it , _filter.end() ); - } -} - -/*--------------------------------------------------------*/ -/* check the PEB constraints to change eventually their */ -/* status from _PEB_P_ to _PEB_E_ */ -/*--------------------------------------------------------*/ -void NOMAD::Barrier::check_PEB_constraints ( const NOMAD::Eval_Point & x , bool display ) -{ - const NOMAD::Double & h_min = _p.get_h_min(); - const std::vector & bbot = _p.get_bb_output_type(); - const NOMAD::Point & bbo = x.get_bb_outputs(); - int nb = static_cast(bbot.size()); - std::list ks; - - for ( int k = 0 ; k < nb ; ++k ) { - if ( bbot[k] == NOMAD::PEB_P && bbo[k] <= h_min ) { - if ( display ) - _p.out() << std::endl - << "change status of blackbox output " << k - << " from progressive barrier constraint to extreme barrier constraint" - << std::endl; - ++_peb_changes; - _p.change_PEB_constraint_status (k); - ks.push_back(k); - } - } - - // at least one constraint changed status, so we have to update the filter - // and remove all points that have their h value changed to infinity - // (it can add new dominant points from the list _peb_lop): - if ( !ks.empty() ) { - - std::list::const_iterator it_k , end_k = ks.end() , begin_k = ks.begin(); - - // we inspect the filter points if some have to be removed; if so, - // all filter candidates (stored in _peb_lop) will be re-inserted - // into the filter: - bool reset_filter = false; - std::set::const_iterator end = _filter.end() , it; - - for ( it = _filter.begin() ; it != end ; ++it ) { - - const NOMAD::Point & bbo_cur = it->get_point()->get_bb_outputs(); - for ( it_k = begin_k ; it_k != end_k ; ++it_k ) - if ( bbo_cur[*it_k] > h_min ) { - reset_filter = true; - break; - } - if ( reset_filter ) - break; - } - - if ( reset_filter ) { - - if ( display ) - _p.out() << std::endl << "PEB change of status: filter reset" << std::endl; - - ++_peb_filter_reset; - - _filter.clear(); - bool insert; - - std::list::const_iterator end2 = _peb_lop.end (); - std::list::iterator it2 = _peb_lop.begin(); - - while ( it2 != end2 ) { - - insert = true; - const NOMAD::Point & bbo_cur = (*it2)->get_bb_outputs(); - - for ( it_k = begin_k ; it_k != end_k ; ++it_k ) - if ( bbo_cur[*it_k] > h_min ) { - insert = false; - break; - } - - // if insert==true: this point is potentially a new filter point: - if ( insert ) { - filter_insertion ( **it2 , insert ); - ++it2; - } - - // if insert==false: it means that the current filter point - // has to be removed from filter and from _peb_lop, and - // in addition, its h is put to INF: - else { - NOMAD::Cache::get_modifiable_point ( **it2 ).set_h ( NOMAD::Double() ); - _peb_lop.erase(it2++); - } - } - } - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Barrier.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Barrier.hpp deleted file mode 100644 index dabbaee13..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Barrier.hpp +++ /dev/null @@ -1,306 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.6.2 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Barrier.hpp - \brief Barrier for constraints handling (headers) - \author Sebastien Le Digabel - \date 2010-04-12 - \see Barrier.cpp - */ -#ifndef __BARRIER__ -#define __BARRIER__ - -#include "Cache.hpp" -#include "Filter_Point.hpp" - -namespace NOMAD { - - /// Barrier class for constraints handling. - /** - The barrier is basically a structure that stores evaluation points. - */ - class Barrier : private NOMAD::Uncopyable { - - private: - - const NOMAD::Parameters & _p; ///< Parameters. - NOMAD::eval_type _eval_type; ///< Truth or surrogate. - NOMAD::Double _h_max; ///< Maximal value for \c h. - const NOMAD::Eval_Point * _best_feasible; ///< Best feasible solution. - - /// Progressive barrier reference point. - const NOMAD::Eval_Point * _ref; - - std::set _filter; ///< Filter. - std::set _prefilter; ///< Pre-filter based on point tags. - - int _rho_leaps; ///< Number of trigger (rho) leaps. - - const NOMAD::Eval_Point * _poll_center; ///< Primary poll center. - const NOMAD::Eval_Point * _sec_poll_center; ///< Secondary poll center. - - /** - Number of constraints that have been changed to NOMAD::PEB_E - (Extreme status for the PEB strategy). - */ - int _peb_changes; - - /** - Number of times that the filter has been reseted following a PEB - change of status. - */ - int _peb_filter_reset; - - /** - List of all points that we tried to insert into the filter, - with PEB constraints. - */ - std::list _peb_lop; - - /// List of all points that we tried to insert into the filter. - std::list _all_inserted; - - NOMAD::success_type _one_eval_succ; ///< Success for one evaluation. - NOMAD::success_type _success; ///< Success for a list of evaluations. - - /*----------------------------------------------------*/ - - /// Insertion of a feasible point. - /** - \param x The feasible point to insert -- \b IN. - \return Success type of the insertion - (NOMAD::FULL_SUCCESS or NOMAD::UNSUCCESSFUL). - */ - NOMAD::success_type insert_feasible ( const NOMAD::Eval_Point & x ); - - /// Insertion of an infeasible point. - /** - \param x The infeasible point to insert -- \b IN. - \return Success type of the insertion - (NOMAD::FULL_SUCCESS, NOMAD::UNSUCCESSFUL, or NOMAD::PARTIAL_SUCCESS). - */ - NOMAD::success_type insert_infeasible ( const NOMAD::Eval_Point & x ); - - /// Change the value of \c h_max. - /** - \param h_max The new value of \c h_max -- \b IN. - */ - void set_h_max ( const NOMAD::Double & h_max ); - - /// Insertion into the filter. - /** - \param x The point to insert -- \b IN. - \param insert A boolean equal to \c true if the point has been - inserted into the barrier -- \b OUT. - */ - void filter_insertion ( const NOMAD::Eval_Point & x , bool & insert ); - - /*----------------------------------------------------*/ - - public: - - /// Exception class for barrier update error. - class Update_Error : public NOMAD::Exception - { - public: - /// Constructor. - Update_Error ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /// Exception class for an insertion error. - class Insert_Error : public NOMAD::Exception - { - public: - /// Constructor. - Insert_Error ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /*----------------------------------------------------*/ - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param et Truth or surrogate -- \b IN. - */ - Barrier ( const NOMAD::Parameters & p , NOMAD::eval_type et ) - : _p ( p ) , - _eval_type ( et ) , - _h_max ( p.get_h_max_0() ) , - _best_feasible ( NULL ) , - _ref ( NULL ) , - _rho_leaps ( 0 ) , - _poll_center ( NULL ) , - _sec_poll_center ( NULL ) , - _peb_changes ( 0 ) , - _peb_filter_reset( 0 ) , - _one_eval_succ ( NOMAD::UNSUCCESSFUL ) , - _success ( NOMAD::UNSUCCESSFUL ) {} - - /// Destructor. - virtual ~Barrier ( void ) {} - - /// Reset the barrier. - void reset ( void ); - - /// Reset the success types. - void reset_success ( void ) { _one_eval_succ = _success = NOMAD::UNSUCCESSFUL; } - - /// Poll center selection. - /** - \param last_it_success Success of the last iteration -- \b IN. - */ - void select_poll_center ( NOMAD::success_type last_it_success ); - - /// Barrier updates. - void update_and_reset_success ( void ); - - /// Access to the best infeasible point. - /** - \return A pointer to the best infeasible point. - */ - const NOMAD::Eval_Point * get_best_infeasible ( void ) const; - - /// Access to the best feasible point. - /** - \return A pointer to the best feasible point. - */ - const NOMAD::Eval_Point * get_best_feasible ( void ) const { return _best_feasible; } - - /// Access to the best infeasible point with min. violation. - /** - \return A pointer to the best infeasible point with min. viol. - */ - const NOMAD::Eval_Point * get_best_infeasible_min_viol ( void ) const; - - /// Access to \c h_max. - /** - \return The value of \c h_max. - */ - const NOMAD::Double & get_h_max ( void ) const { return _h_max; } - - /// Access to the poll center. - /** - \return A pointer to the poll center. - */ - const NOMAD::Eval_Point * get_poll_center ( void ) const { return _poll_center; } - - /// Access to the success type of one evaluation. - /** - \return The success type of one evaluation. - */ - NOMAD::success_type get_one_eval_succ ( void ) const { return _one_eval_succ;} - - /// Access to the success type of a list of evaluations. - /** - \return The success type of a list of evaluations. - */ - NOMAD::success_type get_success ( void ) const { return _success; } - - /// Access to the secondary poll center. - /** - \return A pointer to the secondary poll center. - */ - const NOMAD::Eval_Point * get_sec_poll_center ( void ) const - { - return _sec_poll_center; - } - - /// Access the list of all inserted points. - /** - \return A list with pointers to the inserted points. - */ - const std::list & get_all_inserted ( void ) const - { - return _all_inserted; - } - - /// Insertion of a point into the barrier. - /** - \param x The point -- \b IN. - */ - void insert ( const NOMAD::Eval_Point & x ); - - /// Update the barrier from another barrier. - /** - Used by the VNS search. - \param b The other barrier -- \b IN. - */ - void insert ( const Barrier & b ); - - /// Check the PEB constraints. - /** - This will change eventually the status of PEB constraints - from NOMAD::PEB_P to NOMAD::PEB_E. - \param x Point at which the constraints are checked -- \b IN. - \param display A boolean equal to \c true if displays are authorized -- \b IN. - */ - void check_PEB_constraints ( const NOMAD::Eval_Point & x , bool display ); - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Display. - /** - Uses the NOMAD::Display object of the NOMAD::Parameters class. - */ - void display ( void ) const { display ( _p.out() ); } - - }; - - /// Display a NOMAD::Barrier object. - /** - \param out The NOMAD::Display object -- \b IN. - \param b The NOMAD::Barrier object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Barrier & b ) - { - b.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache.cpp deleted file mode 100644 index 1a5f00077..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache.cpp +++ /dev/null @@ -1,770 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache.cpp - \brief Cache memorizing all evaluations (implementation) - \author Sebastien Le Digabel - \date 2010-04-12 - \see Cache.hpp - */ -#include "Cache.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -std::set NOMAD::Cache::_locked_files; - -/*------------------------------------------------------*/ -/* init of _sizeof (private) */ -/*------------------------------------------------------*/ -int NOMAD::Cache::sizeof_init ( void ) const -{ - return - sizeof ( _cache1 ) + - sizeof ( _cache2 ) + - sizeof ( _cache3 ) + - sizeof ( _locked_file) + - sizeof ( _it ) + - sizeof ( _out ) + - sizeof ( _sizeof ); -} - -/*---------------------------------------------------------------------*/ -/* insertion of a point into the list of extern points (_extern_pts) */ -/*---------------------------------------------------------------------*/ -void NOMAD::Cache::insert_extern_point ( const NOMAD::Eval_Point & x ) const -{ - if ( !x.get_current_run() ) - _extern_pts.push_front ( &x ); -} - -/*----------------------------------------------------------*/ -/* get the first extern point and remove it from the list */ -/* (returns NULL if there is no extern point) */ -/*----------------------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Cache::get_and_remove_extern_point ( void ) const -{ - if ( _extern_pts.empty() ) - return NULL; - const NOMAD::Eval_Point * extern_point = *_extern_pts.begin(); - _extern_pts.pop_front(); - return extern_point; -} - -/*------------------------------------------*/ -/* . search x in the cache */ -/* . return NULL if x is not in the cache */ -/*------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Cache::find ( const NOMAD::Eval_Point & x ) const -{ - // check the eval types: - if ( x.get_eval_type() != _eval_type ) - throw NOMAD::Cache::Cache_Error ( "Cache.cpp" , __LINE__ , - "NOMAD::Cache:find(x): x.eval_type != cache.eval_type" ); - - // find: - std::set::const_iterator it; - NOMAD::cache_index_type cache_index; - const NOMAD::Eval_Point * cache_x - = NOMAD::Cache::find ( x , it , cache_index ); - - return cache_x; -} - -/*----------------------------------------------------*/ -/* . search x in the cache */ -/* . return NULL if x is not in the cache */ -/* . this version returns an iterator and indicates */ -/* in which set the point has been found */ -/* . private method */ -/*----------------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Cache::find -( const NOMAD::Eval_Point & x , - std::set::const_iterator & it , - NOMAD::cache_index_type & cache_index ) const -{ - // search in _cache2 (points to write in a cache file): - NOMAD::Cache_Point cp ( &x ); - it = _cache2.find ( cp ); - if ( it != _cache2.end() ) { - cache_index = NOMAD::CACHE_2; - return it->get_point(); - } - - // search in _cache3 (points saved in a file): - it = _cache3.find ( cp ); - if ( it != _cache3.end() ) { - cache_index = NOMAD::CACHE_3; - return it->get_point(); - } - - // search in _cache1 (points read in an initial cache file): - it = _cache1.find ( cp ); - if ( it != _cache1.end() ) { - cache_index = NOMAD::CACHE_1; - return it->get_point(); - } - - cache_index = NOMAD::UNDEFINED_CACHE; - return NULL; -} - -/*-----------------------------------------------------*/ -/* erase a point */ -/*-----------------------------------------------------*/ -/* . return true if the point has been found and */ -/* removed from the cache */ -/* . the point is not deleted from memory if its */ -/* address does not match the address of the point */ -/* in cache */ -/*-----------------------------------------------------*/ -bool NOMAD::Cache::erase ( const NOMAD::Eval_Point & x ) -{ - // check the eval types: - if ( x.get_eval_type() != _eval_type ) - throw NOMAD::Cache::Cache_Error ( "Cache.cpp" , __LINE__ , - "NOMAD::Cache:erase(x): x.eval_type != cache.eval_type" ); - - std::set::iterator it; - NOMAD::cache_index_type cache_index; - - // search in cache: - const NOMAD::Eval_Point * cache_x = find ( x , it , cache_index ); - - // the point has been found: - if ( cache_x ) { - - // remove the point from the list of extern points: - if ( cache_x->get_current_run() || x.get_current_run() ) { - std::list::const_iterator end2 = _extern_pts.end(); - std::list::iterator it2 = _extern_pts.begin(); - while ( it2 != end2 ) { - if ( *it2 == cache_x || *it2 == &x ) { - _extern_pts.erase ( it2 ); - break; - } - ++it2; - } - } - - // erase the point in cache if its address is different from &x: - if ( cache_x != &x ) - delete cache_x; - - // remove the point from the cache: - _sizeof -= x.size_of(); - - switch ( cache_index ) { - case NOMAD::CACHE_1: - _cache1.erase ( it ); - break; - case NOMAD::CACHE_2: - _cache2.erase ( it ); - break; - case NOMAD::CACHE_3: - _cache3.erase ( it ); - break; - case NOMAD::UNDEFINED_CACHE: - break; - } - return true; - } - return false; -} - -/*-----------------------------------------------------*/ -/* erase all points in cache and unlock _locked_file */ -/*-----------------------------------------------------*/ -void NOMAD::Cache::clear ( void ) -{ - const NOMAD::Eval_Point * x = begin(); - while ( x ) { - delete x; - x = next(); - } - _cache1.clear(); - _cache2.clear(); - _cache3.clear(); - unlock(); - - _extern_pts.clear(); - - _sizeof = static_cast ( sizeof_init() ); -} - -/*------------------------------------------------*/ -/* . insertion of a point in the cache (_cache2) */ -/* . supposes that x is NOT already in cache */ -/*------------------------------------------------*/ -void NOMAD::Cache::insert ( const NOMAD::Eval_Point & x ) -{ - // check the eval types: - if ( x.get_eval_type() != _eval_type ) - throw NOMAD::Cache::Cache_Error ( "Cache.cpp" , __LINE__ , - "NOMAD::Cache:insert(x): x.eval_type != cache.eval_type" ); - - // insertion in _extern_pts: - insert_extern_point ( x ); - - // insertion in _cache2: - NOMAD::Cache_Point cp ( &x ); - _cache2.insert ( cp ); - x.set_in_cache ( true ); - _sizeof += x.size_of(); -} - -/*-------------------------------------------------------------------------*/ -/* . insert all points of 'c' in the current cache */ -/* . this empties 'c' points (to avoid Eval_Point copies) */ -/* . c._locked_file and this->_locked_file are different by construction */ -/*-------------------------------------------------------------------------*/ -void NOMAD::Cache::insert ( Cache & c ) -{ - if ( &c == this ) - return; - - // check the eval types: - if ( c._eval_type != _eval_type ) - throw NOMAD::Cache::Cache_Error ( "Cache.cpp" , __LINE__ , - "NOMAD::Cache:insert(c): c._eval_type != this->_eval_type" ); - - // insertion: - NOMAD::Point bbo_cache , bbo_cur; - const NOMAD::Eval_Point * cache_x; - const NOMAD::Eval_Point * cur = c.begin(); - - while ( cur ) { - - cache_x = find ( *cur ); - - // the current point is already in cache: - if ( cache_x ) { - update ( get_modifiable_point ( *cache_x ) , *cur ); - delete cur; - } - - // point not in cache: - else - insert ( *cur ); - - cur = c.next(); - } - - c._sizeof = static_cast ( sizeof_init() ); - - c._cache1.clear(); - c._cache2.clear(); - c._cache3.clear(); - c._extern_pts.clear(); -} - -/*------------------------------------------------------------------*/ -/* . begin() and next() methods, to browse the cache */ -/* */ -/* . example of use: */ -/* */ -/* const NOMAD::Eval_Point * cur = cache.begin(); */ -/* while ( cur ) { */ -/* ... */ -/* cur = cache.next(); */ -/* } */ -/* */ -/* . we browse in this order: _cache2, _cache3, and _cache_1 */ -/*------------------------------------------------------------------*/ - -// begin(): -// -------- -const NOMAD::Eval_Point * NOMAD::Cache::begin ( void ) const -{ - if ( !_cache2.empty() ) { - _it = _cache2.begin(); - return _it->get_point(); - } - if ( !_cache3.empty() ) { - _it = _cache3.begin(); - return _it->get_point(); - } - if ( !_cache1.empty() ) { - _it = _cache1.begin(); - return _it->get_point(); - } - return NULL; -} - -// next() (supposes that begin() has been called) -// ------- -const NOMAD::Eval_Point * NOMAD::Cache::next ( void ) const -{ - ++_it; - - if ( !_cache2.empty() && _it == _cache2.end() ) { - if ( !_cache3.empty() ) { - _it = _cache3.begin(); - return _it->get_point(); - } - if ( !_cache1.empty() ) { - _it = _cache1.begin(); - return _it->get_point(); - } - return NULL; - } - - - if ( !_cache3.empty() && _it == _cache3.end() ) { - if ( !_cache1.empty() ) { - _it = _cache1.begin(); - return _it->get_point(); - } - return NULL; - } - - if ( !_cache1.empty() && _it == _cache1.end() ) - return NULL; - - return _it->get_point(); -} - -/*---------------------------------------------------------------------*/ -/* check if a file is locked (private) */ -/*---------------------------------------------------------------------*/ -bool NOMAD::Cache::is_locked ( const std::string & file_name ) -{ - if ( file_name == _locked_file ) - return true; - return ( Cache::_locked_files.find ( file_name ) != Cache::_locked_files.end() ); -} - -/*---------------------------------------------------------------------*/ -/* lock a file (private) */ -/*---------------------------------------------------------------------*/ -bool NOMAD::Cache::lock ( const std::string & file_name ) -{ - if ( is_locked ( file_name ) ) - return false; - - Cache::_locked_files.insert ( file_name ); - _locked_file = file_name; - - return true; -} - -/*---------------------------------------------------------------------*/ -/* unlock the locked file (private) */ -/*---------------------------------------------------------------------*/ -void NOMAD::Cache::unlock ( void ) -{ - if ( _locked_file.empty() ) - return; - - std::set::iterator it = Cache::_locked_files.find ( _locked_file ); - if ( it != Cache::_locked_files.end() ) - _locked_files.erase(it); - - _locked_file.clear(); -} - -/*----------------------------------------------------*/ -/* . reads points from a cache file */ -/* . fills the set _cache1 */ -/* . private method */ -/*----------------------------------------------------*/ -bool NOMAD::Cache::read_points_from_cache_file ( std::ifstream & fin , - const int * p_nb_bb_outputs , - bool display ) -{ - try { - - NOMAD::Clock c; - - // the stream is placed at the first point (after the CACHE_FILE_ID tag): - fin.seekg ( sizeof ( NOMAD::CACHE_FILE_ID ) , std::ios::beg ); - - NOMAD::Cache_File_Point cfp; - NOMAD::Eval_Point * cur; - const NOMAD::Eval_Point * cache_x; - - // main loop: - while ( !fin.eof() ) { - - // reading of the Cache_File_Point: - if ( !cfp.read ( fin ) ) { - if ( fin.eof() ) - break; - return false; - } - - // we ignore this cache file point if it has a different - // number of blackbox outputs than *p_nb_bb_outputs: - if ( p_nb_bb_outputs && cfp.get_m() != *p_nb_bb_outputs ) - continue; - - // creation of the Eval_Point: - cur = new NOMAD::Eval_Point ( cfp , _eval_type ); - - // we look if the current point is already in cache: - cache_x = find ( *cur ); - - // the current point is already in cache: - if ( cache_x ) { - update ( get_modifiable_point ( *cache_x ) , *cur ); - delete cur; - } - - // point not in cache: insertion: - else { - - // insertion in _extern_pts: - insert_extern_point ( *cur ); - - // insertion in _cache1: - NOMAD::Cache_Point cp ( cur ); - _cache1.insert ( cp ); - cur->set_in_cache ( true ); - _sizeof += cur->size_of(); - } - - } // end of main loop - - // display stats on the cache load: - if ( display ) { - _out << "number of points: " << static_cast(_cache1.size()) << std::endl - << "size : "; - _out.display_size_of ( _sizeof ); - _out << std::endl - << "load time : " << c.get_real_time() << 's' << std::endl; - } - } - catch ( ... ) { - return false; - } - return true; -} - -/*---------------------------------------------------------------------*/ -/* . load a cache file (fill the set _cache1) */ -/* . lock the file 'file_name' */ -/* . return false if 'file_name' exists and is not a valid cache file */ -/* . return false if 'file_name' is already locked */ -/* . return false if the object already locked a file */ -/* . return true if this object is already locked with this file */ -/* (and just do nothing) */ -/* . return true and create a valid cache file if 'file_name' */ -/* does not exist */ -/* . return false if the previous step did not work */ -/* */ -/* . parameter p_nb_bb_outputs (default=NULL): to indicate a number of */ -/* blackbox outputs; points in file with a different value are */ -/* ignored */ -/*---------------------------------------------------------------------*/ -bool NOMAD::Cache::load ( const std::string & file_name , - const int * p_nb_bb_outputs , - bool display ) -{ - if ( !file_name.empty() && file_name == _locked_file ) - return true; - - if ( file_name.empty() || !_locked_file.empty() || is_locked(file_name) ) - return false; - - // the file exists: - if ( NOMAD::check_read_file ( file_name ) ) { - - int id; - std::ifstream fin ( file_name.c_str() , std::ios::binary ); - - fin.read ( (char *) &id , sizeof(int) ); - - // it is a valid cache file: - if ( !fin.fail() && id == NOMAD::CACHE_FILE_ID ) { - - // display: - if ( display ) - _out << std::endl - << NOMAD::open_block ( "loading of \'" + file_name + "\'" ); - - // read the points: - if ( !read_points_from_cache_file ( fin , p_nb_bb_outputs , display ) ) { - fin.close(); - return false; // it is not a valid cache file - } - - // lock the file: - lock ( file_name ); - - fin.close(); - - if ( display ) - _out.close_block(); - - return true; - } - - // it is not a valid cache file: - else { - fin.close(); - return false; - } - } - - // the file does not exist: - else { - - // display: - if ( display ) - _out << std::endl << "creating cache file \'" << file_name << "\'" << std::endl; - - // create the file as a valid cache file: - std::ofstream fout ( file_name.c_str() , std::ios::binary ); - - if ( fout.fail() ) { - fout.close(); - return false; - } - - fout.write ( (char *) &NOMAD::CACHE_FILE_ID , sizeof ( NOMAD::CACHE_FILE_ID ) ); - fout.close(); - - // lock: - lock ( file_name ); - } - - return true; -} - -/*------------------------------------------------------------------*/ -/* if overwrite == false: */ -/* . write points at the end of the locked cache file */ -/* . write only points from _cache2 */ -/* . transfer points from _cache2 to _cache3 */ -/* else: */ -/* . write all points in the locked cache file */ -/*------------------------------------------------------------------*/ -bool NOMAD::Cache::save ( bool overwrite , bool display ) -{ - if ( _locked_file.empty() ) - return true; - - // display: - if ( display ) - _out << std::endl << "saving cache file \'" << _locked_file << "\'" << std::endl; - - std::ofstream fout; - - if ( overwrite ) { - - // open: - fout.open ( _locked_file.c_str() , std::ios::binary ); - if ( fout.fail() ) { - fout.close(); - return false; - } - - // cache file tag: - fout.write ( (char *) &NOMAD::CACHE_FILE_ID , sizeof ( NOMAD::CACHE_FILE_ID ) ); - - // save all cache points: - const NOMAD::Eval_Point * cur = begin(); - while ( cur ) { - NOMAD::Cache_File_Point cfp ( *cur ); - if ( !cfp.write ( fout ) ) { - fout.close(); - return false; - } - cur = next(); - } - } - - else { - - // open and go at the end of the file: - fout.open ( _locked_file.c_str() , std::ios::binary | std::ios::app ); - if ( fout.fail() ) { - fout.close(); - return false; - } - - std::set::iterator it = _cache2.begin(); - while ( it != _cache2.end() ) { - - // write it->get_point() in 'fout': - NOMAD::Cache_File_Point cfp ( *it->get_point() ); - if ( !cfp.write ( fout ) ) { - fout.close(); - return false; - } - - // transfer the point from _cache2 to _cache3: - NOMAD::Cache_Point cp = *it; // ( it->get_point() ); - _cache3.insert ( cp ); - _cache2.erase ( it++ ); - } - } - - // close the file: - fout.close(); - - return true; -} - -/*-----------------------------------------------------------------*/ -/* . update a point already in cache from another point with the */ -/* same coordinates */ -/* . if both points have a different number of blackbox outputs, */ -/* they are not comparable and we set cache_x = x */ -/* . private method */ -/*-----------------------------------------------------------------*/ -void NOMAD::Cache::update ( NOMAD::Eval_Point & cache_x , - const NOMAD::Eval_Point & x ) const -{ - const NOMAD::Point & bbo_x = x.get_bb_outputs(); - - if ( &cache_x == &x || - !x.is_eval_ok() || - !cache_x.is_in_cache() || - bbo_x.empty() || - cache_x != x ) - return; - - // check the eval types: - if ( x.get_eval_type () != _eval_type || - cache_x.get_eval_type() != _eval_type ) - throw NOMAD::Cache::Cache_Error ( "Cache.cpp" , __LINE__ , - "NOMAD::Cache:update(): problem with the eval. types" ); - - const NOMAD::Point & bbo_cache_x = cache_x.get_bb_outputs(); - int m = bbo_cache_x.size(); - - _sizeof -= cache_x.size_of(); - - // if the current point could not evaluate and x did, - // or if the number of bb outputs is different, we set cache_x = x: - if ( !cache_x.is_eval_ok() || m != bbo_x.size() ) - { - cache_x.set_eval_status ( NOMAD::EVAL_OK ); - cache_x.set_bb_output ( bbo_x ); - cache_x.set_signature ( x.get_signature () ); - cache_x.set_direction ( x.get_direction () ); - - _sizeof += cache_x.size_of(); - return; - } - - // we complete _bb_outputs: - int c1 = 0; - int c2 = 0; - - for ( int i = 0 ; i < m ; ++i ) { - - if ( bbo_cache_x[i].is_defined() ) - ++c1; - - if ( bbo_x[i].is_defined() ) - ++c2; - - if ( !bbo_cache_x[i].is_defined() && bbo_x[i].is_defined() ) - cache_x.set_bb_output ( i , bbo_x[i] ); - } - - // the two points are 'eval_ok' and have comparable outputs: - // we select the best as the one with the more defined bb_outputs: - if ( c2 > c1 ) { - cache_x.set_signature ( x.get_signature () ); - cache_x.set_direction ( x.get_direction () ); - - } - - _sizeof += cache_x.size_of(); -} - -/*---------------------------------------------------------*/ -/* display the list of extern points */ -/*---------------------------------------------------------*/ -void NOMAD::Cache::display_extern_pts ( const NOMAD::Display & out ) const -{ - int nb = static_cast(_extern_pts.size()); - int cnt = 0; - std::list::const_iterator it , end = _extern_pts.end(); - for ( it = _extern_pts.begin() ; it != end ; ++it ) { - out << "point "; - out.display_int_w ( ++cnt , nb ); - out << "/" << nb << ": "; - (*it)->display_eval ( out , false ); - out << std::endl; - } -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Cache::display ( const NOMAD::Display & out ) const -{ - out << "number of cache points: " << size() << std::endl - << "size in memory : "; - out.display_size_of ( _sizeof ); - out << std::endl << "cache file : "; - if ( _locked_file.empty() ) - out << "-" << std::endl; - else - out << _locked_file << std::endl; - -#ifdef DEBUG - int nb = size(); - int cnt = 0; - out << NOMAD::open_block ( "cache points" ) << std::endl; - const NOMAD::Eval_Point * cur = begin(); - while ( cur ) { - out << "point "; - out.display_int_w ( ++cnt , nb ); - out << "/" << nb << ": "; - cur->display_eval ( out , false ); - out << std::endl; - cur = next(); - } - out.close_block(); - - // this display is repeated here as there can - // be a lot of points displayed just before: - out << "number of cache points: " << size() << std::endl - << "size in memory : "; - out.display_size_of ( _sizeof ); - out << std::endl << "cache file : "; - if ( _locked_file.empty() ) - out << "-"; - else - out << _locked_file; - out << std::endl; -#endif -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache.hpp deleted file mode 100644 index 0c7c6e95d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache.hpp +++ /dev/null @@ -1,410 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache.hpp - \brief Cache memorizing all evaluations (headers) - \author Sebastien Le Digabel - \date 2010-04-12 - \see Cache.cpp -*/ - -// To browse the cache: -// --------------------- -// const NOMAD::Eval_Point * cur = cache.begin(); -// while ( cur ) { -// ... -// cur = cache.next(); -// } - -#ifndef __CACHE__ -#define __CACHE__ - -#include "Cache_Point.hpp" -#include "Clock.hpp" - -namespace NOMAD { - - /// Cache memorizing all evaluations. - /** - - The evaluation are stored as NOMAD::Eval_Point objects in - three \c std::set containers - ( \c _cache1 , \c _cache2 and \c _cache3 ). - - Browse the points inside the cache with the following instructions: - \code - const NOMAD::Eval_Point * cur = cache.begin(); - while ( cur ) { - ... - cur = cache.next(); - } - \endcode - */ - class Cache : private NOMAD::Uncopyable { - - protected: - - /// Display: - const NOMAD::Display & _out; - - private: - - /// Static list of locked files. - static std::set _locked_files; - - /// Cache file that is currently in use for load/save (this file is locked). - std::string _locked_file; - - /// Type of cache (truth or surrogate). - NOMAD::eval_type _eval_type; - - /// Points read in the (optional) initial cache file. - std::set _cache1; - - /// Points of the cache to write in the cache file. - std::set _cache2; - - /// Points of the cache already saved in the file. - std::set _cache3; - - /// Points not from the current run (from a cache file or from a user). - mutable std::list _extern_pts; - - /// Size in memory. - mutable float _sizeof; - - /// Iterator to browse the cache with \c begin() and \c next(). - mutable std::set::const_iterator _it; - - /*---------------------------------------------------------------------------*/ - - /// Read points in a cache file. - /** - - Reads points from a cache file. - - Fills the set \c _cache1. - \param fin The already opened input file -- \b IN. - \param p_nb_bb_outputs A pointer on an integer with the number - of blackbox outputs; can be \c NULL -- \b IN. - \param display A boolean equal to \c true if displays - are authorized -- \b IN. - \return A boolean equal to \c true if the file could be read. - */ - bool read_points_from_cache_file ( std::ifstream & fin , - const int * p_nb_bb_outputs , - bool display ); - - /// Check if a file is locked. - /** - \param file_name Name of the file -- \b IN. - \return A boolean equal to \c true if the file is locked. - */ - bool is_locked ( const std::string & file_name ); - - /// Lock a file. - /** - \param file_name Name of the file -- \b IN. - \return A boolean equal to \c false if the file was already locked. - */ - bool lock ( const std::string & file_name ); - - /// Unlock the locked file. - void unlock ( void ); - - /// Update a point already in cache. - /** - - The point already in cache is updated from another - point with the same coordinates. - - If both points have a different number of blackbox outputs, - they are not comparable and we set \c cache_x \c = \c x . - \param cache_x The point already in cache -- \b IN/OUT. - \param x The other point -- \b IN. - */ - void update ( NOMAD::Eval_Point & cache_x , const NOMAD::Eval_Point & x ) const; - - /// Find a point in the cache. - /** - \param x The point -- \b IN. - \param it An iterator indicating the position of the point - -- \b OUT. - \param cache_index Index of the std::set in which the point has been found - -- \b OUT. - \return A pointer to the point in cache. - \return \c NULL if \c x is not in the cache. - */ - const NOMAD::Eval_Point * find - ( const NOMAD::Eval_Point & x , - std::set::const_iterator & it , - NOMAD::cache_index_type & cache_index ) const; - - /// Initialization of \c _sizeof. - /** - \return The size of an empty cache. - */ - int sizeof_init ( void ) const; - - /*---------------------------------------------------------------------------*/ - - public: - - /// Exception class for a cache error. - /** - Occurs when points have not the same \c eval_type as \c this->_eval_type. - */ - class Cache_Error : public NOMAD::Exception - { - public: - /// Constructor. - Cache_Error ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /*---------------------------------------------------------------------------*/ - - /// Constructor. - /** - \param out The NOMAD::Display object -- \b IN. - \param type Type of the cache - -- \b IN -- \b optional (default = NOMAD::TRUTH). - */ - explicit Cache ( const NOMAD::Display & out , - NOMAD::eval_type type = NOMAD::TRUTH ) - : _out ( out ) , - _eval_type ( type ) , - _sizeof ( static_cast(sizeof_init()) ) {} - - /// Destructor. - virtual ~Cache ( void ) { clear(); } - - /// Access to the size of cache in memory. - /** - \return The size of cache in memory, in bytes. - */ - float size_of ( void ) const { return _sizeof; } - - /// Access to the number of points. - /** - \return The number of points in the cache. - */ - int size ( void ) const - { - return static_cast ( _cache1.size() + _cache2.size() + _cache3.size() ); - } - - /// check if the cache is empty. - /** - \return A boolean equal to \c true if the cache is empty. - */ - bool empty ( void ) const - { - return _cache1.empty() && _cache2.empty() && _cache3.empty(); - } - - /// Access to the evaluation type (truth or surrogate). - /** - \return The evaluation type. - */ - NOMAD::eval_type get_eval_type ( void ) const { return _eval_type; } - - /// Const cast for an evaluation point. - /** - Transforms a \c const NOMAD::Eval_Point \c & into a NOMAD::Eval_Point \c &. - \param x The const point -- \b IN. - \return The non-const point. - */ - static NOMAD::Eval_Point & get_modifiable_point ( const NOMAD::Eval_Point & x ) - { - return const_cast ( x ); - } - - /// Insertion of a point into the list of extern points. - /** - \param x The extern point -- \b IN. - */ - void insert_extern_point ( const NOMAD::Eval_Point & x ) const; - - /// Access to the number of extern points. - /** - \return The number of extern points. - */ - virtual int get_nb_extern_points ( void ) const { return static_cast(_extern_pts.size()); } - - /// Access to an extern point. - /** - Get the first extern point and remove it from the list. - \return A pointer to the extern point; - \c NULL if there is no extern point. - */ - virtual const NOMAD::Eval_Point * get_and_remove_extern_point ( void ) const; - - /// Find a point in the cache. - /** - \param x The point -- \b IN. - \return A pointer to the point in cache. - \return \c NULL if the point is not in cache. - */ - virtual const NOMAD::Eval_Point * find ( const NOMAD::Eval_Point & x ) const; - - /// Access to the first point in cache. - /** - We browse in this order: \c _cache2, \c _cache3, and \c _cache_1 . - \return A pointer to the first point in cache; - \c NULL if the cache is empty. - */ - const NOMAD::Eval_Point * begin ( void ) const; - - /// Access to the next point when browsing the cache. - /** - Supposes that \c begin() has already been called. - \return A pointer to the next point; \c NULL if there - is no more point. - */ - const NOMAD::Eval_Point * next ( void ) const; - - /// Erase a point. - /** - The point is not deleted from memory if its - address does not match the address of the point - in cache. - \param x The point -- \b IN. - \return A boolean equal to \c true - if the point has been found and removed from the cache. - */ - bool erase ( const NOMAD::Eval_Point & x ); - - /// Insertion of a point in the cache ( \c _cache2 ). - /** - Supposes that \c x is not already in cache. - \param x The point -- \b IN. - */ - virtual void insert ( const NOMAD::Eval_Point & x ); - - /// Insert all points of another cache into the current cache. - /** - This empties the points in \c c in order to avoid NOMAD::Eval_Point copies. - \c c._locked_file and \c this->_locked_file are different by construction. - \param c The other cache -- \b IN/OUT. - */ - void insert ( Cache & c ); - - /// Load a cache file. - /** - - fills the set \c _cache1. - - locks the file \c file_name. - - \param file_name The file -- \b IN. - - \param p_nb_bb_outputs A pointer to the number of blackbox outputs. - It is ignored if equal to \c NULL. - Points from the file with a different number - of outputs are ignored - -- \b IN -- \b optional (default = \c NULL). - - \param display A boolean equal to \c true if displays - are authorized - -- \b IN -- \b optional (default = \c true). - - \return \c false if the file exists and is not a valid cache file. - \return \c false if the file is already locked. - \return \c false if the object already locked another file. - \return \c true if the object is already locked with this file (and do nothing). - \return \c true and create a valid cache file if the file does not exist. - \return \c false if the previous anything else did not work. - */ - bool load ( const std::string & file_name , - const int * p_nb_bb_outputs = NULL , - bool display = true ); - - /// Save a cache file. - /** - \param overwrite A boolean. - If \c false, points are written - at the end of the locked file and only points - from \c _cache2 are considered. - These points are then transfered to \c _cache3. - If \c true, all the points are considered. - -- \b IN -- \b optional (default = \c false). - \param display A boolean equal to \c true if displays - are authorized - -- \b IN -- \b optional (default = \c true). - \return A boolean equal to \c true if the save could complete. - */ - bool save ( bool overwrite = false , - bool display = true ); - - /// Erase all points in cache and unlock the file. - void clear ( void ); - - /// Display the list of extern points. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display_extern_pts ( const NOMAD::Display & out ) const; - - /// Display the list of extern points. - /** - Uses the \c this->_out member as NOMAD::Display object. - */ - void display_extern_pts ( void ) const { display_extern_pts ( _out ); } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Display. - /** - Uses the \c this->_out member as NOMAD::Display object. - */ - void display ( void ) const { display ( _out ); } - - }; - - /// Display a NOMAD::Cache object. - /** - \param out The NOMAD::Display object -- \b IN. - \param c The NOMAD::Cache object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Cache & c ) - { - c.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_File_Point.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_File_Point.cpp deleted file mode 100644 index 9aab2005c..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_File_Point.cpp +++ /dev/null @@ -1,327 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache_File_Point.cpp - \brief Class for points in binary files (implementation) - \author Sebastien Le Digabel - \date 2010-04-06 - \see Cache_File_Point.hpp -*/ -#include "Cache_File_Point.hpp" -#include "Eval_Point.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -#ifdef MEMORY_DEBUG -int NOMAD::Cache_File_Point::_cardinality = 0; -int NOMAD::Cache_File_Point::_max_cardinality = 0; -#endif - -/*---------------------------------------------------------------------*/ -/* constructor 1 */ -/*---------------------------------------------------------------------*/ -NOMAD::Cache_File_Point::Cache_File_Point ( void ) - : _n ( 0 ) , - _m ( 0 ) , - _m_def ( 0 ) , - _eval_status ( 3 ) , - _coords ( NULL ) , - _bbo_def ( NULL ) , - _bbo_index ( NULL ) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Cache_File_Point::_cardinality; - if ( NOMAD::Cache_File_Point::_cardinality > - NOMAD::Cache_File_Point::_max_cardinality ) - ++NOMAD::Cache_File_Point::_max_cardinality; -#endif -} - -/*---------------------------------------------------------------------*/ -/* constructor 2 */ -/*---------------------------------------------------------------------*/ -NOMAD::Cache_File_Point::Cache_File_Point ( const NOMAD::Eval_Point & x ) - : _n ( x.size() ) , - _m ( 0 ) , - _m_def ( 0 ) , - _coords ( NULL ) , - _bbo_def ( NULL ) , - _bbo_index ( NULL ) -{ - int i; - - // eval_status: - switch ( x.get_eval_status() ) { - case NOMAD::EVAL_FAIL: - _eval_status = 0; - break; - case NOMAD::EVAL_OK: - _eval_status = 1; - break; - case NOMAD::EVAL_IN_PROGRESS: - _eval_status = 2; - break; - case NOMAD::UNDEFINED_STATUS: - _eval_status = 3; - break; - case NOMAD::EVAL_USER_REJECT: - _eval_status = 3; - break; - } - - // inputs: - if ( _n > 0 ) { - _coords = new double [_n]; - for ( i = 0 ; i < _n ; ++i ) - _coords[i] = x[i].value(); - } - else - _n = 0; - - // outputs: - const NOMAD::Point & bbo = x.get_bb_outputs(); - _m = bbo.size(); - if ( _m > 0 ) { - - std::vector vd; - std::vector vi; - - for ( i = 0 ; i < _m ; ++i ) - if ( bbo[i].is_defined() ) { - vd.push_back ( bbo[i].value() ); - vi.push_back ( i ); - } - - _m_def = static_cast ( vd.size() ); - if ( _m_def > 0 ) { - _bbo_def = new double [_m_def]; - _bbo_index = new int [_m_def]; - for ( i = 0 ; i < _m_def ; ++i ) { - _bbo_def [i] = vd[i]; - _bbo_index[i] = vi[i]; - } - } - } - else - _m = 0; - -#ifdef MEMORY_DEBUG - ++NOMAD::Cache_File_Point::_cardinality; - if ( NOMAD::Cache_File_Point::_cardinality > - NOMAD::Cache_File_Point::_max_cardinality ) - ++NOMAD::Cache_File_Point::_max_cardinality; -#endif -} - -/*---------------------------------------------------------------------*/ -/* destructor */ -/*---------------------------------------------------------------------*/ -NOMAD::Cache_File_Point::~Cache_File_Point ( void ) -{ - delete [] _coords; - delete [] _bbo_def; - delete [] _bbo_index; -#ifdef MEMORY_DEBUG - --NOMAD::Cache_File_Point::_cardinality; -#endif -} - -/*---------------------------------------------------------------------*/ -/* get_coord(i) */ -/*---------------------------------------------------------------------*/ -double NOMAD::Cache_File_Point::get_coord ( int i ) const -{ - if ( !_coords || i < 0 || i >= _n ) - throw NOMAD::Exception ( "Cache_File_Point.cpp" , __LINE__ , - "bad access in Cache_File_Point::get_coord()" ); - return _coords[i]; -} - -/*---------------------------------------------------------------------*/ -/* get_bb_outputs */ -/*---------------------------------------------------------------------*/ -const NOMAD::Point NOMAD::Cache_File_Point::get_bb_outputs ( void ) const -{ - NOMAD::Point bbo ( _m ); - for ( int i = 0 ; i < _m_def ; ++i ) - bbo [ _bbo_index[i] ] = _bbo_def[i]; - return bbo; -} - -/*---------------------------------------------------------*/ -/* reset (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Cache_File_Point::reset ( void ) -{ - _n = _m = _m_def = 0; - _eval_status = 3; - - delete [] _coords; - delete [] _bbo_def; - delete [] _bbo_index; - - _coords = NULL; - _bbo_def = NULL; - _bbo_index = NULL; -} - -/*---------------------------------------------------------*/ -/* write in binary file */ -/*---------------------------------------------------------*/ -bool NOMAD::Cache_File_Point::write ( std::ofstream & fout ) const -{ - // do nothing if no point: - if ( _n <= 0 ) - return true; - - // 1. _eval_status: - fout.write ( (char *) &_eval_status , sizeof(_eval_status) ); - - // 2. _n: - fout.write ( (char *) &_n , sizeof(_n) ); - - // 3. _m: - fout.write ( (char *) &_m , sizeof(_m) ); - - // 4. _m_def: - fout.write ( (char *) &_m_def , sizeof(_m_def) ); - - // 5. _coords: - fout.write ( (char *) _coords , _n*sizeof(double) ); - - if ( _m_def > 0 ) { - - // 6. _bbo_def: - fout.write ( (char *) _bbo_def , _m_def*sizeof(double) ); - - // 7. _bbo_index: - fout.write ( (char *) _bbo_index , _m_def*sizeof(int) ); - } - - return !fout.fail(); -} - -/*---------------------------------------------------------*/ -/* read in binary file */ -/*---------------------------------------------------------*/ -bool NOMAD::Cache_File_Point::read ( std::ifstream & fin ) -{ - reset(); - - // 1. _eval_status: - fin.read ( (char *) &_eval_status , sizeof(_eval_status) ); - if ( fin.fail() || _eval_status > 3 ) - return false; - - // 2. _n: - fin.read ( (char *) &_n , sizeof(_n) ); - if ( fin.fail() || _n <= 0 ) { - _n = 0; - return false; - } - - // 3. _m: - fin.read ( (char *) &_m , sizeof(_m) ); - if ( fin.fail() || _m < 0 ) { - _n = _m = 0; - return false; - } - - // 4. _m_def: - fin.read ( (char *) &_m_def , sizeof(_m_def) ); - if ( fin.fail() || _m_def < 0 ) { - _m_def = _n = _m = 0; - return false; - } - - // 5. _coords: - _coords = new double [_n]; - fin.read ( (char *) _coords , _n*sizeof(double) ); - if ( fin.fail() ) { - reset(); - return false; - } - - if ( _m_def > 0 ) { - - // 6. _bb_def: - _bbo_def = new double [_m_def]; - fin.read ( (char *) _bbo_def , _m_def*sizeof(double) ); - if ( fin.fail() ) { - reset(); - return false; - } - - // 7. _bbo_index: - _bbo_index = new int [_m_def]; - fin.read ( (char *) _bbo_index , _m_def*sizeof(int) ); - if ( fin.fail() ) { - reset(); - return false; - } - } - - return true; -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Cache_File_Point::display ( const NOMAD::Display & out ) const -{ - out << "n : " << _n << std::endl - << "m : " << _m << std::endl - << "m_def : " << _m_def << std::endl; - - int i; - if ( _n > 0 ) { - out << "coords : ( "; - for ( i = 0 ; i < _n ; ++i ) - out << _coords[i] << " "; - out << ")" << std::endl; - } - if ( _m_def > 0 ) { - out << "bbo_def : [ "; - for ( i = 0 ; i < _m_def ; ++i ) - out << _bbo_def[i] << " "; - out << "]" << std::endl - << "bbo_index : [ "; - for ( i = 0 ; i < _m_def ; ++i ) - out << _bbo_index[i] << " "; - out << "]" << std::endl; - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_File_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_File_Point.hpp deleted file mode 100644 index 9dc2aa508..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_File_Point.hpp +++ /dev/null @@ -1,202 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache_File_Point.hpp - \brief Class for points in binary files (headers) - \author Sebastien Le Digabel - \date 2010-04-06 - \see Cache_File_Point.cpp -*/ - -#ifndef __CACHE_FILE_POINT__ -#define __CACHE_FILE_POINT__ - -#include "Display.hpp" -#include "Uncopyable.hpp" - -namespace NOMAD { - - // forward declarations: - class Point; - class Eval_Point; - - /// Class to represent NOMAD::Eval_Point objects in binary files. - /** - - All point coordinates are saved. - - Only defined blackbox outputs are saved. - - To get all bb_outputs: - \code - NOMAD::Point bbo ( _m ); - for ( int i = 0 ; i < _m_def ; ++i ) - bbo [ _bbo_index[i] ] = _bbo_def[i]; - \endcode - */ - class Cache_File_Point : private NOMAD::Uncopyable { - - private: - -#ifdef MEMORY_DEBUG - /// Number of NOMAD::Cache_File_Point objects in memory. - static int _cardinality; - - /// Max number of NOMAD::Cache_File_Point objects in memory. - static int _max_cardinality; -#endif - - int _n; ///< Dimension of the point. - int _m; ///< Number of blackbox outputs (both defined and undefined). - int _m_def; ///< Number of defined blackbox outputs. - - /// Evaluation status. - /** - - 0: fail. - - 1: ok. - - 2: in progress. - - 3: undefined. - */ - unsigned char _eval_status; - - double * _coords; ///< The \c _n coordinates. - double * _bbo_def; ///< The \c _m_def defined blackbox output values. - int * _bbo_index; ///< The index for the blackbox output values. - - /// Reset. - void reset ( void ); - - public: - -#ifdef MEMORY_DEBUG - /// Access to the number of NOMAD::Cache_File_Point objects in memory. - /** - \return The number of NOMAD::Cache_File_Point objects in memory. - */ - static int get_cardinality ( void ) { return Cache_File_Point::_cardinality; } - - /// Access to the max number of NOMAD::Cache_File_Point objects in memory. - /** - \return The max number of NOMAD::Cache_File_Point objects in memory. - */ - static int get_max_cardinality ( void ) - { - return Cache_File_Point::_max_cardinality; - } -#endif - - /// Constructor #1. - explicit Cache_File_Point ( void ); - - /// Constructor #2. - /** - From a NOMAD::Eval_Point object. - \param x The evaluation point. - */ - explicit Cache_File_Point ( const NOMAD::Eval_Point & x ); - - /// Destructor. - virtual ~Cache_File_Point ( void ); - - /// Access to the dimension of the point. - /** - \return The dimension of the point. - */ - int get_n ( void ) const { return _n; } - - /// Access to the number of blackbox outputs. - /** - \return The number of blackbox outputs. - */ - int get_m ( void ) const { return _m; } - - /// Access to the evaluation status. - /** - Evaluation status as a character: - - 0: fail. - - 1: ok. - - 2: in progress. - - 3: undefined. - \return A character as the evaluation status. - */ - unsigned char get_eval_status ( void ) const { return _eval_status; } - - /// Access to the coordinates. - /** - \param i The index (0 for the first element) -- \b IN. - \return The \c (i+1)th coordinate. - */ - double get_coord ( int i ) const; - - /// Access to the blackbox outputs. - /** - \return A NOMAD::Point as the \c _m outputs. - */ - const NOMAD::Point get_bb_outputs ( void ) const; - - /// Write in a binary file. - /** - \param fout The output file -- \b IN/OUT. - \return A boolean equal to \c true if the file could be written. - */ - bool write ( std::ofstream & fout ) const; - - /// Read in a binary file. - /** - \param fin The input file -- \b IN/OUT. - \return A boolean equal to \c true if the file could be read. - */ - bool read ( std::ifstream & fin ); - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::Cache_File_Point object. - /** - \param out The NOMAD::Display object -- \b IN. - \param x The NOMAD::Cache_File_Point object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Cache_File_Point & x ) - { - x.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Point.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Point.cpp deleted file mode 100644 index 1891529b4..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Point.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache_Point.cpp - \brief Point stored in the cache (implementation) - \author Sebastien Le Digabel - \date 2010-04-08 - \see Cache_Point.hpp -*/ -#include "Cache_Point.hpp" - -/*-----------------------------------------------------------*/ -/* comparison operator */ -/*-----------------------------------------------------------*/ -bool NOMAD::Cache_Point::operator < ( const Set_Element & cp ) const -{ - if ( get_element()->get_tag() == cp.get_element()->get_tag() ) - return false; - return get_element()->Point::operator < ( *(cp.get_element()) ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Point.hpp deleted file mode 100644 index 57cf3158d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Point.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache_Point.hpp - \brief Point stored in the cache (headers) - \author Sebastien Le Digabel - \date 2010-04-08 - \see Cache_Point.cpp -*/ -#ifndef __CACHE_POINT__ -#define __CACHE_POINT__ - -#include "Eval_Point.hpp" - -namespace NOMAD { - - /// Class for the representation of NOMAD::Eval_Point objects stored in the cache. - class Cache_Point : public NOMAD::Set_Element { - - private: - - /// Affectation operator. - /** - \param cp The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Cache_Point & operator = ( const Cache_Point & cp ); - - public: - - /// Constructor. - /** - \param x A pointer to the NOMAD::Eval_Point object - that is stored in the cache -- \b IN. - */ - explicit Cache_Point ( const NOMAD::Eval_Point * x ) - : NOMAD::Set_Element ( x ) {} - - /// Copy constructor. - /** - \param cp The copied object -- \b IN. - */ - Cache_Point ( const Cache_Point & cp ) - : NOMAD::Set_Element ( cp.get_element() ) {} - - /// Destructor. - virtual ~Cache_Point ( void ) {} - - /// Comparison operator. - /** - \param cp The right-hand side object. - \return A boolean equal to \c true if \c *this \c < \c cp. - */ - virtual bool operator < ( const NOMAD::Set_Element & cp ) const; - - /// Access to the point. - /** - \return A pointer to the NOMAD::Eval_Point stored in the cache. - */ - const NOMAD::Eval_Point * get_point ( void ) const { return get_element(); } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Search.cpp deleted file mode 100644 index c76130466..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Search.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache_Search.cpp - \brief NOMAD::Search subclass for the cache search (implementation) - \author Sebastien Le Digabel - \date 2010-04-08 - \see Cache_Search.hpp -*/ -#include "Cache_Search.hpp" - -/*---------------------------------------------------------*/ -/* the search */ -/*---------------------------------------------------------*/ -void NOMAD::Cache_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - new_feas_inc = new_infeas_inc = NULL; - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - count_search = false; - - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - const Cache & cache = mads.get_cache(); - int nb_extern_pts = cache.get_nb_extern_points(); - - // do not perform the search if the number of extern points did not change: - if ( stop || nb_extern_pts == 0 || nb_extern_pts == _last_search_nb_extern_pts ) - return; - - count_search = true; - - // initial display: - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << NOMAD::CACHE_SEARCH; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - std::list list_of_extern_pts; - const NOMAD::Eval_Point * extern_pt = cache.get_and_remove_extern_point(); - NOMAD::Eval_Point * pt = NULL; - int n = _p.get_dimension(); - - // add the extern points to the list of points to be evaluated: - while ( extern_pt ) { - - list_of_extern_pts.push_front ( extern_pt ); - - pt = &NOMAD::Cache::get_modifiable_point ( *extern_pt ); - - if ( extern_pt->get_signature() ) - pt->set_signature ( extern_pt->get_signature() ); - else if ( extern_pt->size() == n ) - pt->set_signature ( _p.get_signature() ); - - if ( pt->get_signature() ) - ev_control.add_eval_point ( pt , - display_degree , - false , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - else { - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY ) - out << std::endl << "Warning (Cache_Search.cpp, " << __LINE__ - << "): could not use the point " << *pt - << "(no signature)" << std::endl; - } - - extern_pt = cache.get_and_remove_extern_point(); - } - - nb_search_pts = ev_control.get_nb_eval_points(); - - // display all the search points: - if ( display_degree == NOMAD::FULL_DISPLAY ) - ev_control.display_eval_lop ( NOMAD::CACHE_SEARCH ); - - // eval_list_of_points: - new_feas_inc = new_infeas_inc = NULL; - ev_control.eval_list_of_points ( NOMAD::CACHE_SEARCH , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - // the method cache.get_and_remove_extern_point() removes the first extern - // point from the cache. If the search is opportunistic and if there are - // extern points that have not been treated, then they must be put back - // in the cache list of extern points: - { - std::list::const_iterator - it , end = list_of_extern_pts.end(); - for ( it = list_of_extern_pts.begin() ; it != end ; ++it ) - if ( !(*it)->get_current_run() ) - cache.insert_extern_point ( **it ); - } - - // update _last_search_nb_extern_pts: - _last_search_nb_extern_pts = cache.get_nb_extern_points(); - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of cache search (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Search.hpp deleted file mode 100644 index 2269cba08..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Cache_Search.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Cache_Search.hpp - \brief NOMAD::Search subclass for the cache search (headers) - \author Sebastien Le Digabel - \date 2010-04-08 - \see Cache_Search.cpp -*/ -#ifndef __CACHE_SEARCH__ -#define __CACHE_SEARCH__ - -#include "Mads.hpp" -#include "Search.hpp" - -namespace NOMAD { - - /// Cache search. - class Cache_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - private: - - /// Number of extern points at the end of the last cache search. - int _last_search_nb_extern_pts; - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Cache_Search ( NOMAD::Parameters & p ) - : NOMAD::Search ( p , NOMAD::CACHE_SEARCH ) , - _last_search_nb_extern_pts ( 0 ) {} - - /// Destructor. - virtual ~Cache_Search ( void ) {} - - /// Reset. - virtual void reset ( void ) { _last_search_nb_extern_pts = 0; } - - /// The cache search. - /** - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - }; -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Clock.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Clock.cpp deleted file mode 100644 index aea34df55..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Clock.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Clock.cpp - \brief Clock class (implementation) - \author Sebastien Le Digabel - \date 2010-04-02 - \see Clock.hpp -*/ -#include "Clock.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -const double NOMAD::Clock::_D_CLOCKS_PER_SEC = static_cast(CLOCKS_PER_SEC); - -/*---------------------------------------------------------*/ -/* compute the wall-clock time (real time) elapsed since */ -/* the construction of the Clock object */ -/*---------------------------------------------------------*/ -int NOMAD::Clock::get_real_time ( void ) const -{ - time_t t2; - time (&t2); - return static_cast (difftime ( t2 , _real_t0 ) ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Clock.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Clock.hpp deleted file mode 100644 index bc2766fe4..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Clock.hpp +++ /dev/null @@ -1,121 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Clock.hpp - \brief Clock class (headers) - \author Sebastien Le Digabel - \date 2010-04-02 - \see Clock.cpp -*/ -#ifndef __CLOCK__ -#define __CLOCK__ - -#include - -namespace NOMAD { - - /// Clock class. - /** - Time measurement.\n\n - \b Example: - \code - Clock c; - - // some instructions here - - std::cout << "elapsed real time = " << c.get_real_time() << std::endl; - std::cout << "elapsed CPU time = " << c.get_CPU_time() << std::endl; - \endcode - */ - class Clock { - - private: - - time_t _real_t0; ///< Wall clock time measurement. - clock_t _CPU_t0; ///< CPU time measurement. - static const double _D_CLOCKS_PER_SEC; ///< System constant for CPU time measurement. - - public: - - /// Constructor. - Clock ( void ) : _CPU_t0 ( clock() ) { time (&_real_t0); } - - /// Copy constructor. - /** - \param c The copied object -- \b IN. - */ - Clock ( const Clock & c ) : _real_t0 ( c._real_t0 ) , _CPU_t0 ( c._CPU_t0 ) {} - - /// Affectation operator. - /** - \param c The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Clock & operator = ( const Clock & c ) - { - _real_t0 = c._real_t0; - _CPU_t0 = c._CPU_t0; - return *this; - } - - /// Destructor. - virtual ~Clock ( void ) {} - - /// Reset the clock. - void reset ( void ) - { - time ( &_real_t0 ); - _CPU_t0 = clock(); - } - - /// Get wall clock time. - /** - \return The wall clock time. - */ - int get_real_time ( void ) const; - - /// Get the CPU time. - /** - \return The CPU time. - */ - double get_CPU_time ( void ) const - { - return ( clock() - _CPU_t0 ) / _D_CLOCKS_PER_SEC; - } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Direction.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Direction.cpp deleted file mode 100644 index 6f140605a..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Direction.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Direction.cpp - \brief Polling direction (implementation) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Direction.hpp -*/ -#include "Direction.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -#ifdef MEMORY_DEBUG -int NOMAD::Direction::_cardinality = 0; -int NOMAD::Direction::_max_cardinality = 0; -#endif - -/*---------------------------------------------------------*/ -/* constructor 1 */ -/*---------------------------------------------------------*/ -NOMAD::Direction::Direction ( void ) - : NOMAD::Point ( ) , - _type ( NOMAD::UNDEFINED_DIRECTION ) , -_index ( -1 ), -_dir_group_index (-1) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Direction::_cardinality; - if ( NOMAD::Direction::_cardinality > NOMAD::Direction::_max_cardinality ) - ++NOMAD::Direction::_max_cardinality; -#endif -} - -/*---------------------------------------------------------*/ -/* constructor 2 */ -/*---------------------------------------------------------*/ -NOMAD::Direction::Direction ( int n , - const NOMAD::Double & v , - NOMAD::direction_type type , - int dir_group_index ) - : NOMAD::Point ( n , v ) , - _type ( type ) , - _index ( -1 ) , - _dir_group_index (dir_group_index) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Direction::_cardinality; - if ( NOMAD::Direction::_cardinality > NOMAD::Direction::_max_cardinality ) - ++NOMAD::Direction::_max_cardinality; -#endif -} - -/*---------------------------------------------------------*/ -/* constructor 2b */ -/*---------------------------------------------------------*/ -NOMAD::Direction::Direction ( int n , - const NOMAD::Double & v , - NOMAD::direction_type type ) -: NOMAD::Point ( n , v ) , -_type ( type ) , -_index ( -1 ), -_dir_group_index (-1) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Direction::_cardinality; - if ( NOMAD::Direction::_cardinality > NOMAD::Direction::_max_cardinality ) - ++NOMAD::Direction::_max_cardinality; -#endif -} - -/*---------------------------------------------------------*/ -/* constructor 3 */ -/*---------------------------------------------------------*/ -NOMAD::Direction::Direction ( const NOMAD::Point & x , - NOMAD::direction_type type ) - : NOMAD::Point ( x ) , - _type ( type ) , -_index ( -1 ), -_dir_group_index (-1) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Direction::_cardinality; - if ( NOMAD::Direction::_cardinality > NOMAD::Direction::_max_cardinality ) - ++NOMAD::Direction::_max_cardinality; -#endif -} - -/*---------------------------------------------------------*/ -/* copy constructor */ -/*---------------------------------------------------------*/ -NOMAD::Direction::Direction ( const Direction & d ) - : NOMAD::Point ( d ) , - _type ( d._type ) , - _index ( d._index ), -_dir_group_index (d._dir_group_index) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Direction::_cardinality; - if ( NOMAD::Direction::_cardinality > NOMAD::Direction::_max_cardinality ) - ++NOMAD::Direction::_max_cardinality; -#endif -} - -/*---------------------------------------------------------*/ -/* destructor */ -/*---------------------------------------------------------*/ -NOMAD::Direction::~Direction ( void ) -{ -#ifdef MEMORY_DEBUG - --NOMAD::Direction::_cardinality; -#endif -} - -/*---------------------------------------------------------*/ -/* affectation operator */ -/*---------------------------------------------------------*/ -NOMAD::Direction & NOMAD::Direction::operator = ( const NOMAD::Direction & d ) -{ - if ( this == &d ) - return *this; - - NOMAD::Point::operator = ( d ); - - _type = d._type; - _index = d._index; - - return *this; -} - -/*---------------------------------------------------------*/ -/* clear */ -/*---------------------------------------------------------*/ -void NOMAD::Direction::clear ( void ) -{ - NOMAD::Point::clear(); - _type = NOMAD::UNDEFINED_DIRECTION; - _index = -1; -} - -/*-----------------------------------------------------------*/ -/* negation */ -/*-----------------------------------------------------------*/ -const NOMAD::Direction NOMAD::Direction::operator - ( void ) const -{ - return NOMAD::Direction ( this->NOMAD::Point::operator-() , _type ); -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Direction::display ( const NOMAD::Display & out , - const std::string & sep , - int w , - int lim ) const -{ - if ( is_defined() ) { - out << "( "; - NOMAD::Point::display ( out , sep , w , lim ); - out << " ) " << _type; - } - else - out << "undefined"; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Direction.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Direction.hpp deleted file mode 100644 index 45175bec7..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Direction.hpp +++ /dev/null @@ -1,231 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Direction.hpp - \brief Polling direction (headers) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Direction.cpp -*/ -#ifndef __DIRECTION__ -#define __DIRECTION__ - -#include "Point.hpp" - -namespace NOMAD { - - - - /// Class describing a polling direction. - class Direction : public NOMAD::Point { - - private: - -#ifdef MEMORY_DEBUG - static int _cardinality; ///< Number of NOMAD::Direction objects in memory. - static int _max_cardinality; ///< Max number of NOMAD::Direction objects in memory. -#endif - - NOMAD::direction_type _type; ///< Type of direction. - mutable int _index; ///< Direction index (used only for display). - int _dir_group_index ; ///< Index a the group of direction - - public: - -#ifdef MEMORY_DEBUG - /// Access to the number of NOMAD::Direction objects in memory. - /** - \return The number of NOMAD::Direction objects in memory. - */ - static int get_cardinality ( void ) { return Direction::_cardinality; } - - /// Access to the max number of NOMAD::Direction objects in memory. - /** - \return The max number of NOMAD::Direction objects in memory. - */ - static int get_max_cardinality ( void ) { return Direction::_max_cardinality; } -#endif - - /// Constructor #1. - Direction ( void ); - - /// Constructor #2. - /** - \param n Dimension -- \b IN. - \param v Initial value for all coordinates -- \b IN. - \param type Type of direction -- \b IN. - \param dir_group_index Index of the variable group the direction belongs --\b IN. - */ - Direction ( int n , const NOMAD::Double & v , NOMAD::direction_type type, int dir_group_index ); - - /// Constructor #2b. - /** - \param n Dimension -- \b IN. - \param v Initial value for all coordinates -- \b IN. - \param type Type of direction -- \b IN. - */ - Direction ( int n , const NOMAD::Double & v , NOMAD::direction_type type); - - - /// Constructor #3. - /** - \param x Coordinates -- \b IN. - \param type Type of direction -- \b IN. - */ - Direction ( const NOMAD::Point & x , NOMAD::direction_type type ); - - /// Copy constructor. - /** - \param d The copied object. - */ - Direction ( const Direction & d ); - - /// Destructor. - virtual ~Direction ( void ); - - /// Affectation operator. - /** - \param d The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Direction & operator = ( const Direction & d ); - - /// Check if the direction is defined. - /** - \return A boolean equal to \c true if the direction has no defined type. - */ - virtual bool is_defined ( void ) const - { return _type != NOMAD::UNDEFINED_DIRECTION; } - - /// Clear the direction. - virtual void clear ( void ); - - /// Size of the direction in memory. - /** - \return An integer for the size of the direction in bytes. - */ virtual int size_of ( void ) const - { - return NOMAD::Point::size_of() + sizeof(_type) + sizeof(_index); - } - - /// Negation. - /** - The current object \c *this is not modified. - \return A new direction equal to \c -*this. - */ - const Direction operator - ( void ) const; - - /*---------------*/ - /* GET methods */ - /*---------------*/ - - /// Access to the type of direction. - /** - \return The type of the direction. - */ - NOMAD::direction_type get_type ( void ) const { return _type; } - - /// Access to the direction index. - /** - \return The direction index. - */ - int get_index ( void ) const { return _index; } - - /// Access to the direction group index. - /** - \return The direction group index. - */ - int get_dir_group_index ( void ) const { return _dir_group_index; } - - - /// Check if the direction is a MADS direction. - /** - \return A boolean equal to \c true if the direction is a MADS direction. - */ - bool is_mads ( void ) const { return NOMAD::dir_is_mads ( _type ); } - - /// Check if the direction is a GPS direction. - /** - \return A boolean equal to \c true if the direction is a GPS direction. - */ - bool is_gps ( void ) const { return NOMAD::dir_is_gps ( _type ); } - - /*---------------*/ - /* SET methods */ - /*---------------*/ - - /// Set the direction index. - /** - \param i The direction index -- \b IN. - */ - void set_index ( int i ) const { _index = i; } - - /// Set the direction type. - /** - \param t The direction type -- \b IN. - */ - void set_type ( NOMAD::direction_type t ) { _type = t; } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - \param sep A string that is used as a separator between the coordinates - -- \b IN. - \param w An integer indicating a width for the display of - each coordinate -- \b IN. - \param lim Max number of coordinates to display -- \b IN. - */ - virtual void display ( const NOMAD::Display & out , - const std::string & sep , - int w , - int lim ) const; - }; - - /// Display a NOMAD::Direction object. - /** - \param out The NOMAD::Display object -- \b IN. - \param d The NOMAD::Direction object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Direction & d ) - { - d.display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Directions.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Directions.cpp deleted file mode 100644 index e542f0952..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Directions.cpp +++ /dev/null @@ -1,885 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Directions.cpp - \brief Set of polling directions (implementation) - \author Sebastien Le Digabel - \date 2010-04-13 - \see Directions.hpp - */ -#include "Directions.hpp" -#include -#include "XMesh.hpp" -#include "SMesh.hpp" - - -/*---------------------------------------------------------*/ -/* constructor */ -/*---------------------------------------------------------*/ -NOMAD::Directions::Directions -( int nc , - const std::set & direction_types , - const std::set & sec_poll_dir_types , - const NOMAD::Display & out ) -: _nc ( nc ) , -_direction_types ( direction_types ) , -_sec_poll_dir_types ( sec_poll_dir_types ) , -_is_binary ( false ) , -_is_categorical ( false ) , -_lt_initialized ( false ) , -_out ( out ) -{ - // check the directions: - if ( _direction_types.find ( NOMAD::NO_DIRECTION ) != _direction_types.end() ) - _direction_types.clear(); - - if ( _sec_poll_dir_types.find ( NOMAD::NO_DIRECTION ) != _sec_poll_dir_types.end() ) - _sec_poll_dir_types.clear(); - - // is_orthomads: true if at least one direction is of type Ortho-MADS: - _is_orthomads = NOMAD::dirs_have_orthomads ( _direction_types ); - if ( !_is_orthomads ) - _is_orthomads = NOMAD::dirs_have_orthomads ( _sec_poll_dir_types ); - - -} - -/*---------------------------------------------------------*/ -/* destructor */ -/*---------------------------------------------------------*/ -NOMAD::Directions::~Directions ( void ) -{ - if ( _lt_initialized ) - { - int n = 2 * NOMAD::L_LIMITS; - for ( int i = 0 ; i <= n ; ++i ) - delete _bl[i]; - } - -} - -/*---------------------------------------------------------*/ -/* LT-MADS initializations (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Directions::lt_mads_init ( void ) -{ - int n = 2 * NOMAD::L_LIMITS; - for ( int i = 0 ; i <= n ; ++i ) - { - _bl [i] = NULL; - _hat_i[i] = -1; - } - _lt_initialized = true; -} - -/*---------------------------------------------------------*/ -/* set_binary */ -/*---------------------------------------------------------*/ -void NOMAD::Directions::set_binary ( void ) -{ - _is_binary = true; - _is_categorical = false; - _is_orthomads = false; - _direction_types.clear(); - _direction_types.insert ( NOMAD::GPS_BINARY ); - if ( !_sec_poll_dir_types.empty() ) { - _sec_poll_dir_types.clear(); - _sec_poll_dir_types.insert ( NOMAD::GPS_BINARY ); - } -} - -/*---------------------------------------------------------*/ -/* set_categorical */ -/*---------------------------------------------------------*/ -void NOMAD::Directions::set_categorical ( void ) -{ - _is_categorical = true; - _is_binary = false; - _is_orthomads = false; - _direction_types.clear(); - _sec_poll_dir_types.clear(); -} - -/*----------------------------------------------------------------------*/ -/* compute binary directions when all groups of variables are binary */ -/* (private) */ -/*----------------------------------------------------------------------*/ -void NOMAD::Directions::compute_binary_directions -( std::list & d ) const -{ - // _GPS_BINARY_ n directions: - NOMAD::Direction * pd; - for ( int i = 0 ; i < _nc ; ++i ) { - d.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_BINARY ) ); - pd = &(*(--d.end())); - (*pd)[i] = 1.0; - } -} - - -/*----------------------------------------------------------------------------*/ -/* get the directions on a unit n-sphere for a given mesh */ -/*----------------------------------------------------------------------------*/ -void NOMAD::Directions::compute ( std::list & dirs , - NOMAD::poll_type poll , - const NOMAD::OrthogonalMesh & mesh ) -{ - - dirs.clear(); - - // categorical variables: do nothing: - if ( _is_categorical ) - return; - - // binary variables: we use special directions: - if ( _is_binary ) - { - compute_binary_directions ( dirs ); - return; - } - - NOMAD::Double pow_gps , cst; - const NOMAD::Direction * bl; - NOMAD::Direction * pd; - int i , j , k , hat_i; - std::list::iterator it2 , end2; - - const NOMAD::Point mesh_indices=mesh.get_mesh_indices(); - int mesh_index=int(mesh_indices[0].value()); // single mesh_index used only for isotropic mesh - - - /*-----------------------------------*/ - /* loop on the types of directions */ - /*-----------------------------------*/ - const std::set & dir_types = - (poll == NOMAD::PRIMARY) ? _direction_types : _sec_poll_dir_types; - - std::set::const_iterator it , end = dir_types.end() ; - for ( it = dir_types.begin() ; it != end ; ++it ) - { - - if ( *it == NOMAD::UNDEFINED_DIRECTION || - *it == NOMAD::NO_DIRECTION || - *it == NOMAD::MODEL_SEARCH_DIR ) - continue; - - /*--------------------------------------------------*/ - /* Ortho-MADS */ - /* ---> dirs are on a unit n-sphere by construction */ - /*--------------------------------------------------*/ - if ( NOMAD::dir_is_orthomads (*it) ) - { - bool success_dir; - - - NOMAD::Direction dir ( _nc , 0.0 , *it ); - NOMAD::Double alpha_t_l; - - success_dir=compute_dir_on_unit_sphere ( dir ); - - if ( success_dir ) - { -#ifdef DEBUG - if ( dynamic_cast ( &mesh ) ) - { - _out << std::endl - << NOMAD::open_block ( "compute Ortho-MADS directions with XMesh" ) - << "type = " << *it << std::endl; - NOMAD::Point mesh_indices=mesh.get_mesh_indices(); - _out<< "Mesh indices = ( "; - mesh_indices.NOMAD::Point::display( _out, " " , -1 , -1 ); - _out << " )" << std::endl; - _out<< "Unit sphere Direction = ( "; - dir.NOMAD::Point::display ( _out , " " , -1 , -1 ); - _out << " )" << std::endl << NOMAD::close_block(); - } - else if ( dynamic_cast ( &mesh ) ) - { - _out << std::endl - << NOMAD::open_block ( "compute Ortho-MADS directions with SMesh" ) - << "type = " << *it - << " on isotropic mesh " << std::endl - << "mesh index (lk) = " << mesh_index << std::endl - << "alpha (tk,lk) = " << alpha_t_l << std::endl - << "Unit sphere Direction = ( "; - dir.NOMAD::Point::display ( _out , " " , -1 , -1 ); - _out << " )" << std::endl << NOMAD::close_block(); - - } - -#endif - // Ortho-MADS 2n and n+1: - // ---------------------- - if ( *it == NOMAD::ORTHO_2N || *it == NOMAD::ORTHO_NP1_QUAD || *it == NOMAD::ORTHO_NP1_NEG ) - { - - // creation of the 2n directions: - // For ORTHO_NP1 the reduction from 2N to N+1 is done in MADS::POLL - NOMAD::Direction ** H = new NOMAD::Direction * [2*_nc]; - - // Ordering D_k alternates Hk and -Hk instead of [H_k -H_k] - for ( i = 0 ; i < _nc ; ++i ) - { - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , *it ) ); - H[i ] = &(*(--dirs.end())); - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , *it ) ); - H[i+_nc] = &(*(--dirs.end())); - } - - // Householder transformations on the 2n directions on a unit n-sphere: - householder ( dir , true , H ); - - - delete [] H; - - - } - - // Ortho-MADS 1 or Ortho-MADS 2: - // ----------------------------- - else - { - dirs.push_back ( dir ); - if ( *it == NOMAD::ORTHO_2 ) - dirs.push_back ( -dir ); - } - } - } - - /*--------------------------------*/ - /* LT-MADS */ - /* ---> dirs NOT on unit n-sphere */ - /*--------------------------------*/ - else if ( NOMAD::dir_is_ltmads (*it) ) - { - - if ( !_lt_initialized) - lt_mads_init(); - - bl = get_bl ( mesh , *it , hat_i ); - - // LT-MADS 1 or LT-MADS 2: -b(l) and/or b(l): - // ------------------------------------------ - if ( *it == NOMAD::LT_1 || *it == NOMAD::LT_2 ) - { - dirs.push_back ( - *bl ); - if ( *it == NOMAD::LT_2 ) - dirs.push_back ( *bl ); - } - - // LT-MADS 2n or LT-MADS n+1: - // -------------------------- - else { - - // row permutation vector: - int * row_permutation_vector = new int [_nc]; - row_permutation_vector[hat_i] = hat_i; - - NOMAD::Random_Pickup rp ( _nc ); - - for ( i = 0 ; i < _nc ; ++i ) - if ( i != hat_i ) - { - j = rp.pickup(); - if ( j == hat_i ) - j = rp.pickup(); - row_permutation_vector[i] = j; - } - - rp.reset(); - - for ( j = 0 ; j < _nc ; ++j ) - { - i = rp.pickup(); - if ( i != hat_i ) - { - - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , *it ) ); - pd = &(*(--dirs.end())); - - create_lt_direction ( mesh , *it , i , hat_i , pd ); - permute_coords ( *pd , row_permutation_vector ); - } - else - dirs.push_back ( *bl ); - - // completion to maximal basis: - if ( *it == NOMAD::LT_2N ) - dirs.push_back ( NOMAD::Direction ( - *(--dirs.end()) , NOMAD::LT_2N ) ); - - } - - delete [] row_permutation_vector; - - // completion to minimal basis: - if ( *it == NOMAD::LT_NP1 ) - { - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::LT_NP1 ) ); - pd = &(*(--dirs.end())); - - end2 = --dirs.end(); - for ( it2 = dirs.begin() ; it2 != end2 ; ++it2 ) - { - for ( i = 0 ; i < _nc ; ++i ) - (*pd)[i] -= (*it2)[i]; - } - } - } - - - } - - /*--------------------------------*/ - /* GPS */ - /* ---> dirs NOT on unit n-sphere */ - /*--------------------------------*/ - else - { - - // GPS for binary variables: should'nt be here: - if ( *it == NOMAD::GPS_BINARY ) - { -#ifdef DEBUG - _out << std::endl << "Warning (" << "Directions.cpp" << ", " << __LINE__ - << "): tried to generate binary directions at the wrong place)" - << std::endl << std::endl; -#endif - dirs.clear(); - return; - } - - // this value represents the non-zero values in GPS directions - // (it is tau^{|ell_k|/2}, and it is such that delta_k * pow_gps = Delta_k): - if ( !pow_gps.is_defined() ) - pow_gps = pow ( mesh.get_update_basis() , abs(mesh_index) / 2.0 ); - - // GPS 2n, static: - // --------------- - - if ( *it == NOMAD::GPS_2N_STATIC ) - { - for ( i = 0 ; i < _nc ; ++i ) - { - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_2N_STATIC ) ); - pd = &(*(--dirs.end())); - (*pd)[i] = pow_gps; - - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_2N_STATIC ) ); - pd = &(*(--dirs.end())); - (*pd)[i] = -pow_gps; - } - } - - // GPS 2n, random: - // --------------- - else if ( *it == NOMAD::GPS_2N_RAND ) - { - - int v , cnt; - - std::list ::const_iterator end3; - std::list ::iterator it3; - std::list rem_cols; - std::vector rem_col_by_row ( _nc ); - - // creation of the 2n directions: - std::vector pdirs ( 2 * _nc ); - - for ( i = 0 ; i < _nc ; ++i ) - { - - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_2N_RAND ) ); - pdirs[i] = &(*(--dirs.end())); - (*pdirs[i])[i] = pow_gps; - - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_2N_RAND ) ); - pdirs[i+_nc] = &(*(--dirs.end())); - (*pdirs[i+_nc])[i] = -pow_gps; - - rem_cols.push_back(i); - rem_col_by_row[i] = i; - } - - // random perturbations: - for ( i = 1 ; i < _nc ; ++i ) - { - if ( rem_col_by_row[i] > 0 ) - { - v = NOMAD::RNG::rand()%3 - 1; // v in { -1 , 0 , 1 } - if ( v ) - { - - // we decide a (i,j) couple: - k = NOMAD::RNG::rand()%(rem_col_by_row[i]); - cnt = 0; - end3 = rem_cols.end(); - it3 = rem_cols.begin(); - while ( cnt != k ) - { - ++it3; - ++cnt; - } - j = *it3; - - // the perturbation: - (*pdirs[i])[j] = (*pdirs[j+_nc])[i] = -v * pow_gps; - (*pdirs[j])[i] = (*pdirs[i+_nc])[j] = v * pow_gps; - - // updates: - rem_cols.erase(it3); - it3 = rem_cols.begin(); - while ( *it3 != i ) - ++it3; - rem_cols.erase(it3); - for ( k = i+1 ; k < _nc ; ++k ) - rem_col_by_row[k] -= j(_nc)*(_nc+1))/_nc; - - // n first directions: - for ( j = _nc-1 ; j >= 0 ; --j ) - { - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_NP1_STATIC_UNIFORM ) ); - pd = &(*(--dirs.end())); - - k = _nc-j-1; - - for ( i = 0 ; i < k ; ++i ) - (*pd)[i] = -cst / sqrt(static_cast(_nc-i)*(_nc-i+1)); - - (*pd)[k] = (cst * (j+1)) / sqrt(static_cast(j+1)*(j+2)); - - } - - // (n+1)^st direction: - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_NP1_STATIC_UNIFORM ) ); - pd = &(*(--dirs.end())); - for ( i = 0 ; i < _nc ; ++i ) - (*pd)[i] = -cst / sqrt(static_cast(_nc-i)*(_nc-i+1)); - - } - - // GPS n+1, random, uniform angles: - // -------------------------------- - // (we apply the procedure defined in - // "Pattern Search Methods for user-provided points: - // application to molecular geometry problems", - // by Alberto, Nogueira, Rocha and Vicente, - // SIOPT 14-4, 1216-1236, 2004, doi:10.1137/S1052623400377955) - else if ( *it == NOMAD::GPS_NP1_RAND_UNIFORM ) - { - - cst = pow_gps * sqrt(static_cast(_nc)*(_nc+1))/_nc; - - // n first directions: - for ( j = _nc-1 ; j >= 0 ; --j ) - { - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_NP1_STATIC_UNIFORM ) ); - pd = &(*(--dirs.end())); - - k = _nc-j-1; - - for ( i = 0 ; i < k ; ++i ) - (*pd)[i] = -cst / sqrt(static_cast(_nc-i)*(_nc-i+1)); - - (*pd)[k] = (cst * (j+1)) / sqrt(static_cast(j+1)*(j+2)); - - } - - // (n+1)^st direction: - dirs.push_back ( NOMAD::Direction ( _nc , 0.0 , NOMAD::GPS_NP1_STATIC_UNIFORM ) ); - pd = &(*(--dirs.end())); - for ( i = 0 ; i < _nc ; ++i ) - (*pd)[i] = -cst / sqrt(static_cast(_nc-i)*(_nc-i+1)); - - // random perturbations: - NOMAD::Random_Pickup rp ( _nc ); - std::vector done ( _nc ); - bool chg_sgn; - std::list::iterator it; - NOMAD::Double tmp; - - end2 = dirs.end(); - for ( i = 0 ; i < _nc ; ++i ) - done[i] = false; - - for ( i = 0 ; i < _nc ; ++i ) - { - k = rp.pickup(); - if ( i != k && !done[i] ) - { - chg_sgn = ( NOMAD::RNG::rand()%2 != 0 ); - - for ( it = dirs.begin() ; it != end2 ; ++it ) - { - tmp = (*it)[i]; - (*it)[i] = ( chg_sgn ? -1.0 : 1.0 ) * (*it)[k]; - (*it)[k] = tmp; - } - - done[i] = done[k] = true; - } - else - if ( NOMAD::RNG::rand()%2 ) - for ( it = dirs.begin() ; it != end2 ; ++it ) - (*it)[i] = -(*it)[i]; - } - } - } - } // end of loop on the types of directions - - // The direction are unscaled on a unit n-sphere when necessary (that is directions that are not orthomads) - for ( it2 = dirs.begin() ; it2 != dirs.end() ; ++it2 ) - if ( ! NOMAD::dir_is_orthomads ( it2->get_type() ) ) - { - NOMAD::Double norm_dir=it2->norm(); - for (int i=0 ; i < _nc ; ++i ) - (*it2)[i] /= norm_dir; - } - -} - - -/*-----------------------------------------------------------------------------*/ -/* compute a random direction on a unit N-Sphere */ -/* see http://en.wikipedia.org/wiki/N-sphere */ -/*-----------------------------------------------------------------------------*/ -bool NOMAD::Directions::compute_dir_on_unit_sphere ( NOMAD::Direction & random_dir ) const -{ - - int i; - NOMAD::Double norm,d; - - for ( i = 0 ; i < _nc ; ++i ) - random_dir[i]=NOMAD::RNG::normal_rand(0,1); - - norm=random_dir.norm(); - - if ( norm==0 ) - return false; - - - for ( i = 0 ; i < _nc ; ++i ) - random_dir[i]/=norm; - - return true; - -} - - -/*-----------------------------------------------------------------*/ -/* compute the squared norm of normalized(2u_t-e) for Ortho-MADS */ -/* (private) */ -/*-----------------------------------------------------------------*/ -NOMAD::Double NOMAD::Directions::eval_ortho_norm ( const NOMAD::Double & x , - const NOMAD::Double & norm , - const NOMAD::Point & b , - NOMAD::Point & new_b ) const -{ - NOMAD::Double fx = 0.0; - - for ( int i = 0 ; i < _nc ; ++i ) { - new_b[i] = ( x * b[i] / norm ).round(); - fx += new_b[i]*new_b[i]; - } - - return fx; -} - -/*--------------------------------------------------------*/ -/* get the expression of an integer t in inverse base p */ -/* (private, static) */ -/*--------------------------------------------------------*/ -NOMAD::Double NOMAD::Directions::get_phi ( int t , int p ) -{ - int div; - int size = int ( ceil ( log(static_cast(t+1)) / - log(static_cast(p)) ) ); - int ll = t; - NOMAD::Double d = 0.0; - - for ( int i = 0 ; i < size ; ++i ) { - div = NOMAD::Double ( pow ( p , size-i-1.0 ) ).round(); - d += ( ll / div ) * pow ( static_cast(p) , i-size ); - ll = ll % div; - } - return d; -} - -/*----------------------------------------------------------------*/ -/* . Householder transformation to generate _nc directions from */ -/* a given direction */ -/* . compute also H[i+nc] = -H[i] (completion to 2n directions) */ -/* . private method */ -/*----------------------------------------------------------------*/ -void NOMAD::Directions::householder ( const NOMAD::Direction & dir , - bool complete_to_2n , - NOMAD::Direction ** H ) const -{ - int i , j; - - NOMAD::Double norm2 = dir.squared_norm() , v , h2i; - - for ( i = 0 ; i < _nc ; ++i ) { - - h2i = 2 * dir[i]; - - for ( j = 0 ; j < _nc ; ++j ) { - - // H[i]: - (*H[i])[j] = v = (i==j) ? norm2 - h2i * dir[j] : - h2i * dir[j]; - - // -H[i]: - if ( complete_to_2n ) - (*H[i+_nc])[j] = -v; - } - } -} - -/*---------------------------------------------------------*/ -/* get the LT-MADS b(l) direction (private) */ -/*---------------------------------------------------------*/ -const NOMAD::Direction * NOMAD::Directions::get_bl ( const NOMAD::OrthogonalMesh & mesh, - NOMAD::direction_type dtype , - int & hat_i ) -{ - - NOMAD::Point mesh_indices = mesh.get_mesh_indices(); - int mesh_index =static_cast(mesh_indices[0].value()); - NOMAD::Direction * bl = _bl [ mesh_index + NOMAD::L_LIMITS ]; - hat_i = _hat_i [ mesh_index + NOMAD::L_LIMITS ]; - - if ( !bl ) - { - hat_i = -1; - create_lt_direction ( mesh , dtype , -1 , hat_i , bl ); - } - - return bl; -} - -/*---------------------------------------------------------*/ -/* create a new LT-MADS direction (private) */ -/*---------------------------------------------------------*/ -/* (if hat_i == -1, a new b(l) direction */ -/* is created and hat_i is set) */ -/*---------------------------------------------------------*/ -void NOMAD::Directions::create_lt_direction ( const NOMAD::OrthogonalMesh & mesh , - NOMAD::direction_type dtype , - int diag_i , - int & hat_i , - NOMAD::Direction *& dir ) -{ - - int mesh_index=static_cast(mesh.get_mesh_indices()[0].value()); - int i_pow_tau = - static_cast - ( ceil ( pow ( mesh.get_update_basis() , abs(mesh_index) / 2.0 ) ) ); - - int j = diag_i+1; - - // new b(l) direction: - if ( hat_i < 0 ) - { - _hat_i [ mesh_index + NOMAD::L_LIMITS ] = diag_i = hat_i = NOMAD::RNG::rand()%_nc; - _bl [ mesh_index + NOMAD::L_LIMITS ] = dir - = new NOMAD::Direction ( _nc, 0.0, dtype ); - - j = 0; - } - - (*dir)[diag_i] = (NOMAD::RNG::rand()%2) ? -i_pow_tau : i_pow_tau; - - for ( int k = j ; k < _nc ; ++k ) - if ( k != hat_i ) - { - (*dir)[k] = NOMAD::RNG::rand()%i_pow_tau; - if ( NOMAD::RNG::rand()%2 && (*dir)[k] > 0.0 ) - (*dir)[k] = -(*dir)[k]; - } - -#ifdef DEBUG - if ( j==0 ) - _out << "new LT-MADS b(l) direction: b(" << mesh_index << ") = " - << *dir << std::endl << std::endl; -#endif -} - -/*---------------------------------------------------------*/ -/* permute the coordinates of a direction (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Directions::permute_coords ( NOMAD::Direction & dir , - const int * permutation_vector ) const -{ - NOMAD::Point tmp = dir; - for ( int i = 0 ; i < _nc ; ++i ) - dir [ permutation_vector[i] ] = tmp[i]; -} - - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Directions::display ( const NOMAD::Display & out ) const -{ - out << "n : " << _nc << std::endl - << "types : { "; - std::set::const_iterator it , end = _direction_types.end(); - for ( it = _direction_types.begin() ; it != end ; ++it ) - out << "[" << *it << "] "; - out << "}" << std::endl - << "sec poll types: { "; - end = _sec_poll_dir_types.end(); - for ( it = _sec_poll_dir_types.begin() ; it != end ; ++it ) - out << "[" << *it << "] "; - out << "}" << std::endl; - if ( _is_orthomads ) - { - out << "seed : " << NOMAD::RNG::get_seed() << endl; - } -} - -/*---------------------------------------------------------*/ -/* comparison operator */ -/*---------------------------------------------------------*/ -bool NOMAD::Directions::operator < ( const NOMAD::Directions & d ) const -{ - // number of variables: - if ( _nc < d._nc ) - return true; - if ( d._nc < _nc ) - return false; - - // boolean variables: - if ( _is_binary != d._is_binary ) - return _is_binary; - if ( _is_categorical != d._is_categorical ) - return _is_categorical; - if ( _is_orthomads != d._is_orthomads ) - return _is_orthomads; - - // direction types: - size_t nd = _direction_types.size(); - if ( nd < d._direction_types.size() ) - return true; - if ( d._direction_types.size() < nd ) - return false; - - size_t ns = _sec_poll_dir_types.size(); - if ( ns < d._sec_poll_dir_types.size() ) - return true; - if ( d._sec_poll_dir_types.size() < ns ) - return false; - - std::set::const_iterator - it1 = _direction_types.begin() , - it2 = d._direction_types.begin() , - end = _direction_types.end(); - - while ( it1 != end ) { - if ( *it1 < *it2 ) - return true; - if ( *it2 < *it1 ) - return false; - ++it1; - ++it2; - } - - it1 = _sec_poll_dir_types.begin(); - it2 = d._sec_poll_dir_types.begin(); - end = _sec_poll_dir_types.end(); - - while ( it1 != end ) { - if ( *it1 < *it2 ) - return true; - if ( *it2 < *it1 ) - return false; - ++it1; - ++it2; - } - - return false; -} - diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Directions.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Directions.hpp deleted file mode 100644 index 83846f127..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Directions.hpp +++ /dev/null @@ -1,302 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Directions.hpp - \brief Set of polling directions (headers) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Directions.cpp - */ -#ifndef __DIRECTIONS__ -#define __DIRECTIONS__ - -#include "Random_Pickup.hpp" -#include "Direction.hpp" -#include "OrthogonalMesh.hpp" -#include "RNG.hpp" - -namespace NOMAD { - - /// Set of polling directions. - class Directions { - - /*--------------------------------------------------------------*/ - private: - - int _nc; ///< Number of non-fixed variables. - - /// Types of the poll directions. - std::set _direction_types; - - /// Types of the secondary poll directions. - std::set _sec_poll_dir_types; - - bool _is_binary; ///< Flag equal to \c true if all variables are binary. - bool _is_categorical; ///< Flag equal to \c true if all variables are categorical. - - bool _is_orthomads; //< Flag equal to \c true if Ortho-MADS directions are used. - - // LT-MADS attributes: - NOMAD::Direction * _bl [1+2*NOMAD::L_LIMITS]; ///< Directions b(ell) (LT-MADS). - int _hat_i [1+2*NOMAD::L_LIMITS]; ///< b(ell) indexes (LT-MADS). - bool _lt_initialized; ///< Flag equal to \c true if LT-MADS has been initialized. - - const NOMAD::Display & _out; ///< Display. - - /*--------------------------------------------------------------*/ - - /// Affectation operator. - /** - \param d The right-hand side object -- \b IN. - */ - Directions & operator = ( const Directions & d ); - - /// LT-MADS initializations. - void lt_mads_init ( void ); - - /// Compute the squared norm of \c normalized(2u_t-e) for Ortho-MADS. - /** - \param x \b IN. - \param norm \b IN. - \param b \b IN. - \param new_b \b OUT. - \return The squared norm. - */ - NOMAD::Double eval_ortho_norm ( const NOMAD::Double & x , - const NOMAD::Double & norm , - const NOMAD::Point & b , - NOMAD::Point & new_b ) const; - - /// Householder transformation. - /** - - Generate \c _nc directions. - - Computes also \c H[i+nc] \c = \c -H[i] (completion to 2n directions). - \param dir The given direction -- \b IN. - \param complete_to_2n Complete or not to \c 2n directions -- \b IN. - \param H The \c _nc directions -- \b OUT. - */ - void householder ( const NOMAD::Direction & dir , - bool complete_to_2n , - NOMAD::Direction ** H ) const; - - /// Get the expression of an integer \c t in inverse base \c p. - /** - \param t \b IN. - \param p \b IN. - \return The expression of \c t in inverse base \c p. - */ - static NOMAD::Double get_phi ( int t , int p ); - - - /// Access to the LT-MADS \c b(ell) direction. - /** - \param mesh the currenet OrthogonalMesh \c ell -- \b IN. - \param dtype Direction type -- \b IN. - \param hat_i LT-MADS \c hat{i} index -- \b IN/OUT. - \return The LT-MADS \c b(ell) direction. - */ - const NOMAD::Direction * get_bl ( const NOMAD::OrthogonalMesh & mesh , - NOMAD::direction_type dtype , - int & hat_i ); - - /// Create a new LT-MADS direction. - /** - If \c hat_i \c == \c -1, a new \c b(ell) direction is created - and \c hat_i is set. - \param mesh the current OrthogonalMesh index \c ell -- \b IN. - \param dtype Direction type -- \b IN. - \param diag_i Diagonal index -- \b IN. - \param hat_i LT-MADS \c hat{i} index -- \b IN/OUT. - \param dir LT-MADS \c b(ell) direction -- \b OUT. - */ - void create_lt_direction ( const NOMAD::OrthogonalMesh & mesh , - NOMAD::direction_type dtype , - int diag_i , - int & hat_i , - NOMAD::Direction *& dir ); - - /// Permute the coordinates of a direction. - /** - \param dir The direction -- \b IN/OUT. - \param permutation_vector Permutation vector -- \b IN. - */ - void permute_coords ( NOMAD::Direction & dir , - const int * permutation_vector ) const; - - /// Compute binary directions. - /** - Only if all groups of variables are binary. - \param dirs Set of directions -- \b OUT. - */ - void compute_binary_directions ( std::list & dirs ) const; - - /*--------------------------------------------------------------*/ - - public: - - /// Constructor. - /** - \param nc Number of non-fixed variables -- \b IN. - \param direction_types Types of the poll directions -- \b IN. - \param sec_poll_dir_types Types of the secondary poll directions -- \b IN. - \param out The display -- \b IN. - */ - Directions ( int nc , - const std::set & direction_types , - const std::set & sec_poll_dir_types , - const NOMAD::Display & out ); - - /// Copy constructor. - /** - \param d The copied object -- \b IN. - */ - Directions ( const Directions & d ) - : _nc ( d._nc ) , - _direction_types ( d._direction_types ) , - _sec_poll_dir_types ( d._sec_poll_dir_types ) , - _is_binary ( d._is_binary ) , - _is_categorical ( d._is_categorical ) , - _is_orthomads ( d._is_orthomads ) , - _lt_initialized ( false ) , - _out ( d._out ) {} - - /// Destructor. - virtual ~Directions ( void ); - - /// Compute the directions for a given mesh. - /** - \param mesh The given mesh -- \b IN. - \param dirs Set of directions -- \b OUT. - \param poll Type of poll (primary or secondary) -- \b IN. - */ - void compute ( std::list & dirs , - NOMAD::poll_type poll , - const NOMAD::OrthogonalMesh & mesh ); - - /// Compute a random direction on a N-Sphere. - /** - \param random_dir -- \b OUT. - \return A boolean equal to \c true if the computation went well. - */ - bool compute_dir_on_unit_sphere ( NOMAD::Direction & random_dir ) const; - - - /// Check if Ortho-MADS directions are used. - /** - \return A boolean equal to \c true if Ortho-MADS directions are used. - */ - bool is_orthomads ( void ) const - { - return _is_orthomads; - } - - /// Check if all variables are categorical. - /** - \return A boolean equal to \c true if all variables are categorical. - */ - bool is_categorical ( void ) const - { - return _is_categorical; - } - - /// Access to the poll direction types. - /** - \return Poll direction types. - */ - const std::set & get_direction_types ( void ) const - { - return _direction_types; - } - - /// Access to the secondary poll direction types. - /** - \return Secondary poll direction types. - */ - const std::set & get_sec_poll_dir_types ( void ) const - { - return _sec_poll_dir_types; - } - - /// Reset directions for binary variables. - void set_binary ( void ); - - /// Reset directions for categorical variables. - void set_categorical ( void ); - - /// Comparison operator. - /** - \param d The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c d . - */ - bool operator < ( const Directions & d ) const; - - /// Access to the NOMAD::Display member \c _out. - /** - \return The NOMAD::Display member \c _out. - */ - const NOMAD::Display & out ( void ) const { return _out; } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Display. - /** - Uses the \c this->_out member as NOMAD::Display object. - */ - void display ( void ) const - { - display ( _out ); - } - }; - - /// Display a NOMAD::Directions object. - /** - \param out The NOMAD::Display object -- \b IN. - \param d The NOMAD::Directions object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Directions & d ) - { - d.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Display.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Display.cpp deleted file mode 100644 index 10ad631a2..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Display.cpp +++ /dev/null @@ -1,883 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Display.cpp - \brief Custom class for display (implementation) - \author Sebastien Le Digabel - \date 2010-03-30 - \see Display.hpp - */ -#include "Display.hpp" - -/*---------------------------------------------------------*/ -/* open an indented block */ -/*---------------------------------------------------------*/ -void NOMAD::Display::open_block ( const std::string & msg ) const -{ - // open braces: - if ( _newline ) - _out << _indent_str; - if ( !msg.empty() ) - _out << msg << " "; - _out << _open_brace << std::endl; - - _newline = true; - - // add a tabulation to the indentation string: - _indent_str += '\t'; -} - -/*---------------------------------------------------------*/ -/* close an indented block */ -/*---------------------------------------------------------*/ -void NOMAD::Display::close_block ( const std::string & msg ) const -{ - _newline = true; - - if ( _indent_str.empty() ) - return; - - // remove a tabulation to the indentation string: - _indent_str.erase ( 0 , 1 ); - - // close braces: - _out << _indent_str << _closed_brace << " " << msg << std::endl; -} - -/*---------------------------------------------------------*/ -/* set the display degrees */ -/*---------------------------------------------------------*/ -void NOMAD::Display::set_degrees ( NOMAD::dd_type gen_dd , - NOMAD::dd_type search_dd , - NOMAD::dd_type poll_dd , - NOMAD::dd_type iter_dd ) -{ - // max = max { gen_dd , search_dd , poll_dd , iter_dd } : - NOMAD::dd_type max = gen_dd; - if ( search_dd > gen_dd ) - max = search_dd; - if ( poll_dd > max ) - max = poll_dd; - if ( iter_dd > max ) - max = iter_dd; - - // max=0: all to 0: - if ( max == NOMAD::NO_DISPLAY ) - _gen_dd = _search_dd = _poll_dd = _iter_dd = NOMAD::NO_DISPLAY; - - // max=1: all to 1: - else if ( max == NOMAD::MINIMAL_DISPLAY ) - _gen_dd = _search_dd = _poll_dd = _iter_dd = NOMAD::MINIMAL_DISPLAY; - - // max=2: all to 2: - else if ( max == NOMAD::NORMAL_DISPLAY ) - _gen_dd = _search_dd = _poll_dd = _iter_dd = NOMAD::NORMAL_DISPLAY; - - // max=3: 0-->0, 1-->0, 2->0 and 3-->3: - else - { - _gen_dd = (gen_dd ==NOMAD::FULL_DISPLAY)? NOMAD::FULL_DISPLAY:NOMAD::NO_DISPLAY; - _search_dd = (search_dd==NOMAD::FULL_DISPLAY)? NOMAD::FULL_DISPLAY:NOMAD::NO_DISPLAY; - _poll_dd = (poll_dd ==NOMAD::FULL_DISPLAY)? NOMAD::FULL_DISPLAY:NOMAD::NO_DISPLAY; - _iter_dd = (iter_dd ==NOMAD::FULL_DISPLAY)? NOMAD::FULL_DISPLAY:NOMAD::NO_DISPLAY; - } -} - -/*---------------------------------------------------*/ -/* get the display degrees as a string (of size 4) */ -/*---------------------------------------------------*/ -void NOMAD::Display::get_display_degree ( std::string & dd ) const -{ - dd.resize ( 4 ); - dd[0] = NOMAD::Display::dd_to_char ( _gen_dd ); - dd[1] = NOMAD::Display::dd_to_char ( _search_dd ); - dd[2] = NOMAD::Display::dd_to_char ( _poll_dd ); - dd[3] = NOMAD::Display::dd_to_char ( _iter_dd ); -} - -/*---------------------------------------------*/ -/* get the display degree from a search type */ -/*---------------------------------------------*/ -NOMAD::dd_type NOMAD::Display::get_display_degree ( NOMAD::search_type search ) const -{ - if ( search == NOMAD::X0_EVAL ) - return _gen_dd; - if ( search == NOMAD::POLL || search == NOMAD::EXTENDED_POLL ) - return _poll_dd; - return _search_dd; -} - -/*------------------------------------------*/ -/* convert a dd_type into a char (static) */ -/*------------------------------------------*/ -char NOMAD::Display::dd_to_char ( NOMAD::dd_type dd ) -{ - if ( dd == NOMAD::NO_DISPLAY ) - return '0'; - if ( dd == NOMAD::MINIMAL_DISPLAY) - return '1'; - if ( dd == NOMAD::NORMAL_DISPLAY ) - return '2'; - return '3'; -} - -/*------------------------------------------*/ -/* convert a dd_type into an int (static) */ -/*------------------------------------------*/ -int NOMAD::Display::dd_to_int ( NOMAD::dd_type dd ) -{ - if ( dd == NOMAD::NO_DISPLAY ) - return 0; - if ( dd == NOMAD::MINIMAL_DISPLAY ) - return 1; - if ( dd == NOMAD::NORMAL_DISPLAY ) - return 2; - return 3; -} - -/*------------------------------------------*/ -/* convert an int into a dd_type (static) */ -/*------------------------------------------*/ -NOMAD::dd_type NOMAD::Display::int_to_dd ( int dd ) -{ - if ( dd <= 0 ) - return NOMAD::NO_DISPLAY; - if ( dd == 1 ) - return NOMAD::MINIMAL_DISPLAY; - if ( dd == 2 ) - return NOMAD::NORMAL_DISPLAY; - - return NOMAD::FULL_DISPLAY; -} - -/*---------------------------------------------------------*/ -/* display an integer with a specific width */ -/*---------------------------------------------------------*/ -void NOMAD::Display::display_int_w ( int i , int max_i ) const -{ - (*this) << std::setw ( (max_i > 0) ? - (1+int(log(static_cast(max_i))/NOMAD::LOG10)) : 1 ) - << i; -} - -/*--------------------------------------------------------*/ -/* extract display format from a string */ -/*--------------------------------------------------------*/ -/* example: s="$%5.2f" becomes s="$" and format="%5.2f" */ -/*--------------------------------------------------------*/ -void NOMAD::Display::extract_display_format ( std::string & s , std::string & format ) -{ - format.clear(); - if ( s.empty() ) - return; - size_t k = s.find("%"); - size_t n = s.size(); - if ( k < n ) - { - if ( k > 0 && s[k-1]=='\\' ) - { - std::string s1 = s.substr ( 0 , k-1 ); - std::string s2 = s.substr ( k , n-k ); - s = s1 + s2; - } - else - { - format = s.substr ( k , n-k ); - s = s.substr ( 0 , k ); - } - } -} - -/*---------------------------------------------------------*/ -/* to display a duration with a smart format */ -/* (t is in seconds and integer) */ -/*---------------------------------------------------------*/ -void NOMAD::Display::display_time ( int t ) const -{ - if ( t > 0 ) - { - int h = t / 3600; - t = t % 3600; - int m = t / 60; - t = t % 60; - if ( h > 0 ) - (*this) << h << "h "; - if ( m > 0 || h > 0) - (*this) << m << "m "; - } - else - t = 0; - (*this) << t << "s"; -} - -/*-----------------------------------------------------------------*/ -/* to display a size in memory */ -/*-----------------------------------------------------------------*/ -void NOMAD::Display::display_size_of ( float size ) const -{ - if ( size < 1024 ) - (*this) << static_cast(size) << " B"; - else if ( size < 1048576 ) - (*this) << static_cast ( 10 * size / 1024.0 ) / 10.0 << " KB"; - else if ( size < 1073741824 ) - (*this) << static_cast ( 10 * size / 1048576.0 ) / 10.0 << " MB"; - else - (*this) << static_cast ( 10 * size / 1073741824.0 ) / 10.0 << " GB"; -} - -/*-------------------------------------------------------------------*/ -/* get the display_stats_type from a string (static) */ -/*-------------------------------------------------------------------*/ -NOMAD::display_stats_type NOMAD::Display::get_display_stats_type -( const std::string & s ) -{ - int idst; - std::string ss = s , keyword; - NOMAD::toupper ( ss ); - NOMAD::display_stats_type dst = NOMAD::DS_OBJ; - while ( dst < NOMAD::DS_UNDEFINED ) - { - keyword = get_display_stats_keyword ( dst ); - if ( keyword == ss ) - return dst; - idst = dst; - ++idst; - dst = static_cast ( idst ); - } - return NOMAD::DS_UNDEFINED; -} - -/*-------------------------------------------------------------------*/ -/* to get the keyword associated with a display_stats_type */ -/* (used in Parameters::read() or Parameters::set_DISPLAY_STATS()) */ -/* (static) */ -/*-------------------------------------------------------------------*/ -std::string NOMAD::Display::get_display_stats_keyword ( NOMAD::display_stats_type dst ) -{ - std::string s; - switch ( dst ) - { - case NOMAD::DS_OBJ: - s = "OBJ"; - break; - case NOMAD::DS_MESH_INDEX: - s = "MESH_INDEX"; - break; - case NOMAD::DS_DELTA_M: - case NOMAD::DS_MESH_SIZE: - s = "MESH_SIZE"; - break; - case NOMAD::DS_DELTA_P: - case NOMAD::DS_POLL_SIZE: - s = "POLL_SIZE"; - break; - case NOMAD::DS_EVAL: - s = "EVAL"; - break; - case NOMAD::DS_SIM_BBE: - s = "SIM_BBE"; - break; - case NOMAD::DS_BBE: - s = "BBE"; - break; - case NOMAD::DS_BLK_EVA: - s = "BLK_EVA"; - break; - case NOMAD::DS_SGTE: - s = "SGTE"; - break; - case NOMAD::DS_BBO: - s = "BBO"; - break; - case NOMAD::DS_SOL: - s = "SOL"; - break; - case NOMAD::DS_VAR: - s = "VAR"; - break; - case NOMAD::DS_TIME: - s = "TIME"; - break; - case NOMAD::DS_STAT_SUM: - s = "STAT_SUM"; - break; - case NOMAD::DS_STAT_AVG: - s = "STAT_AVG"; - break; - case NOMAD::DS_UNDEFINED: - s = "undefined"; - break; - } - return s; -} - -/*-----------------------------------------------------------------*/ -/* to display a display degree */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::dd_type dd ) -{ - switch ( dd ) - { - case NOMAD::NO_DISPLAY: - out << "no display (0)"; - break; - case NOMAD::MINIMAL_DISPLAY: - out << "minimal display (1)"; - break; - case NOMAD::NORMAL_DISPLAY: - out << "normal (2)"; - break; - case NOMAD::FULL_DISPLAY: - default: - out << "full (3)"; - } - return out; -} - -/*-----------------------------------------------------*/ -/* to display a success_type */ -/*-----------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::success_type st ) -{ - switch ( st ) - { - case NOMAD::FULL_SUCCESS: - out << "dominating"; - break; - case NOMAD::PARTIAL_SUCCESS: - out << "improving"; - break; - case NOMAD::UNSUCCESSFUL: - out << "unsuccessful"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a vector of bb-input types */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , - const std::vector & bbits ) -{ - if ( bbits.empty() ) - return out; - size_t n = bbits.size()-1; - for ( size_t k = 0 ; k < n ; ++k ) - out << std::setw(8) << bbits[k] << " "; - out << std::setw(8) << bbits[n]; - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a bb-input type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::bb_input_type bi ) -{ - switch ( bi ) { - case NOMAD::CONTINUOUS: - out << "cont(R)"; - break; - case NOMAD::CATEGORICAL: - out << "cat(C)"; - break; - case NOMAD::INTEGER: - out << "int(I)"; - break; - case NOMAD::BINARY: - out << "bin(B)"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a search type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::search_type st ) -{ - switch ( st ) - { - case NOMAD::POLL: - out << "poll"; - break; - case NOMAD::EXTENDED_POLL: - out << "extended poll"; - break; - case NOMAD::SEARCH: - out << "search"; - break; - case NOMAD::CACHE_SEARCH: - out << "cache search"; - break; - case NOMAD::USER_SEARCH: - out << "user search"; - break; - case NOMAD::SPEC_SEARCH: - out << "speculative search"; - break; - case NOMAD::LH_SEARCH: - out << "LH search"; - break; - case NOMAD::LH_SEARCH_P1: - out << "LH search - Phase one"; - break; - case NOMAD::P1_SEARCH: - out << "Phase one search"; - break; - case NOMAD::MODEL_SEARCH: - out << "model search"; - break; - case NOMAD::VNS_SEARCH: - out << "VNS search"; - break; - case NOMAD::X0_EVAL: - out << "x0 evaluation"; - break; - case NOMAD::ASYNCHRONOUS: - out << "asynchronous final evaluations"; - break; - case NOMAD::UNDEFINED_SEARCH: - out << "undefined"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a model type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::model_type mt ) -{ - switch ( mt ) - { - case NOMAD::QUADRATIC_MODEL: - out << "quadratic"; - break; - case NOMAD::TGP_MODEL: - out << "TGP"; - break; - case NOMAD::NO_MODEL: - out << "no models"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a TGP mode */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::TGP_mode_type m ) -{ - switch ( m ) - { - case NOMAD::TGP_FAST: - out << "fast"; - break; - case NOMAD::TGP_PRECISE: - out << "precise"; - break; - case NOMAD::TGP_USER: - out << "user"; - break; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display an evaluation type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::eval_type et ) -{ - switch ( et ) - { - case NOMAD::TRUTH: - out << "truth"; - break; - case NOMAD::SGTE: - out << "surrogate"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display an evaluation status type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::eval_status_type est ) -{ - switch ( est ) - { - case NOMAD::EVAL_FAIL: - out << "fail"; - break; - case NOMAD::EVAL_OK: - out << "ok"; - break; - case NOMAD::EVAL_IN_PROGRESS: - out << "in progress"; - break; - case NOMAD::UNDEFINED_STATUS: - out << "undefined"; - break; - case NOMAD::EVAL_USER_REJECT: - out << "rejected"; - break; - - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a stop reason */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::stop_type st ) -{ - switch ( st ) - { - case NOMAD::DELTA_M_MIN_REACHED: - out << "min mesh size"; - break; - case NOMAD::DELTA_P_MIN_REACHED: - out << "min poll size"; - break; - case NOMAD::L_MAX_REACHED: - out << "max mesh index"; - break; - case NOMAD::L_MIN_REACHED: - out << "min mesh index"; - break; - case NOMAD::L_LIMITS_REACHED: - out << "mesh index limits"; - break; - case NOMAD::XL_LIMITS_REACHED: - out << "mesh index limits"; - break; - case NOMAD::MAX_TIME_REACHED: - out << "max time"; - break; - case NOMAD::MAX_BB_EVAL_REACHED: - out << "max number of blackbox evaluations"; - break; - case NOMAD::MAX_SGTE_EVAL_REACHED: - out << "max number of sgte evaluations"; - break; - case NOMAD::MAX_EVAL_REACHED: - out << "max number of evaluations"; - break; - case NOMAD::MAX_SIM_BB_EVAL_REACHED: - out << "max number of sim. bb evaluations"; - break; - case NOMAD::MAX_ITER_REACHED: - out << "max number of iterations"; - break; - case NOMAD::MAX_CONS_FAILED_ITER: - out << "max number of consecutive failed iterations"; - break; - case NOMAD::FEAS_REACHED: - out << "feasibility achieved"; - break; - case NOMAD::F_TARGET_REACHED: - out << "objective target reached"; - break; - case NOMAD::L_CURVE_TARGET_REACHED: - out << "L-curve target reached"; - break; - case NOMAD::P1_FAIL: - out << "phase one failed"; - break; - case NOMAD::STAT_SUM_TARGET_REACHED: - out << "stat sum target reached"; - break; - case NOMAD::X0_FAIL: - out << "problem with starting point evaluation"; - break; - case NOMAD::MESH_PREC_REACHED: - out << "mesh size reached NOMAD precision"; - break; - case NOMAD::MULTI_MAX_BB_REACHED: - out << "max number of bb evaluations"; - break; - case NOMAD::MULTI_NB_MADS_RUNS_REACHED: - out << "max number of MADS runs"; - break; - case NOMAD::MULTI_STAGNATION: - out << "stagnation of the multi-obj. algo."; - break; - case NOMAD::MULTI_NO_PARETO_PTS: - out << "initial runs cannot find Pareto points"; - break; - case NOMAD::MAX_CACHE_MEMORY_REACHED: - out << "max cache memory reached"; - break; - case NOMAD::CTRL_C: - out << "terminated by ctrl-c"; - break; - case NOMAD::USER_STOPPED: - out << "terminated by the user inside Evaluator::update_iteration()"; - break; - case NOMAD::UNKNOWN_STOP_REASON: - case NOMAD::NO_STOP: - out << "unknown"; - break; - case NOMAD::ERROR: - out << "error"; - break; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a bb_output_type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::bb_output_type bbt ) -{ - switch ( bbt ) - { - case NOMAD::OBJ: - out << "OBJ"; - break; - case NOMAD::EB: - out << "EB"; - break; - case NOMAD::PB: - out << "PB"; - break; - case NOMAD::PEB_P: - out << "PEB(P)"; - break; - case NOMAD::PEB_E: - out << "PEB(E)"; - break; - case NOMAD::FILTER: - out << "F"; - break; - case NOMAD::CNT_EVAL: - out << "CNT_EVAL"; - break; - case NOMAD::STAT_AVG: - out << "STAT_AVG"; - break; - case NOMAD::STAT_SUM: - out << "STAT_SUM"; - break; - case NOMAD::UNDEFINED_BBO: - out << "-"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a interpolation_type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , - NOMAD::interpolation_type it ) -{ - switch ( it ) - { - case NOMAD::MFN: - out << "Minimum Frobenius Norm interpolation"; - break; - case NOMAD::REGRESSION: - out << "regression"; - break; - case NOMAD::WP_REGRESSION: - out << "well-poised regression"; - break; - case NOMAD::UNDEFINED_INTERPOLATION_TYPE: - out << "undefined"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a hnorm_type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::hnorm_type hnorm ) -{ - switch ( hnorm ) - { - case NOMAD::L1: - out << "L1"; - break; - case NOMAD::L2: - out << "L2"; - break; - case NOMAD::LINF: - out << "Linf"; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a multi-obj. formulation type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::multi_formulation_type f ) -{ - switch ( f ) - { - case NOMAD::NORMALIZED: - out << "normalized"; - break; - case NOMAD::PRODUCT: - out << "product"; - break; - case NOMAD::DIST_L1: - out << "distance L1"; - break; - case NOMAD::DIST_L2: - out << "distance L2"; - break; - case NOMAD::DIST_LINF: - out << "distance Linf"; - break; - case NOMAD::UNDEFINED_FORMULATION: - out << "undefined"; - break; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a direction_type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , - NOMAD::direction_type dt ) -{ - switch ( dt ) - { - case NOMAD::ORTHO_1: - out << "Ortho-MADS 1"; - break; - case NOMAD::ORTHO_2: - out << "Ortho-MADS 2"; - break; - case NOMAD::ORTHO_NP1_QUAD: - out << "Ortho-MADS n+1 QUAD"; - break; - case NOMAD::ORTHO_NP1_NEG: - out << "Ortho-MADS n+1 NEG"; - break; - case NOMAD::DYN_ADDED: - out << "Dynamic n+1th direction"; - break; - case NOMAD::ORTHO_2N: - out << "Ortho-MADS 2n"; - break; - case NOMAD::LT_1: - out << "LT-MADS 1"; - break; - case NOMAD::LT_2: - out << "LT-MADS 2"; - break; - case NOMAD::LT_2N: - out << "LT-MADS 2n"; - break; - case NOMAD::LT_NP1: - out << "LT-MADS n+1"; - break; - case NOMAD::GPS_BINARY: - out << "GPS n, binary"; - break; - case NOMAD::GPS_2N_STATIC: - out << "GPS 2n, static"; - break; - case NOMAD::GPS_2N_RAND: - out << "GPS 2n, random"; - break; - case NOMAD::GPS_NP1_STATIC_UNIFORM: - out << "GPS n+1, static, uniform angles"; - break; - case NOMAD::GPS_NP1_STATIC: - out << "GPS n+1, static"; - break; - case NOMAD::GPS_NP1_RAND_UNIFORM: - out << "GPS n+1, random, uniform angles"; - break; - case NOMAD::GPS_NP1_RAND: - out << "GPS n+1, random"; - break; - case NOMAD::NO_DIRECTION: - out << "none"; - break; - case NOMAD::MODEL_SEARCH_DIR: - out << "model search direction"; - break; - case NOMAD::UNDEFINED_DIRECTION: - out << "undefined"; - break; - case NOMAD::PROSPECT_DIR: - out << "Prospect direction"; - break; - } - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a display_stats_type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::display_stats_type dst ) -{ - out << NOMAD::Display::get_display_stats_keyword ( dst ); - return out; -} - -/*-----------------------------------------------------------------*/ -/* to display a check_failed_type */ -/*-----------------------------------------------------------------*/ -std::ostream & NOMAD::operator << ( std::ostream & out , NOMAD::check_failed_type cf ) -{ - switch ( cf ) - { - case NOMAD::CHECK_OK: - out << "ok"; - break; - case NOMAD::LB_FAIL: - out << "lower bound"; - break; - case NOMAD::UB_FAIL: - out << "upper bound"; - break; - case NOMAD::FIX_VAR_FAIL: - out << "fixed variable"; - break; - case NOMAD::BIN_FAIL: - out << "binary variable"; - break; - case NOMAD::CAT_FAIL: - out << "categorical variable"; - break; - case NOMAD::INT_FAIL: - out << "integer variable"; - break; - } - return out; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Display.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Display.hpp deleted file mode 100644 index 930b0c442..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Display.hpp +++ /dev/null @@ -1,541 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Display.hpp - \brief Custom class for display (headers) - \author Sebastien Le Digabel - \date 2010-03-30 - \see Display.cpp -*/ -#ifndef __DISPLAY__ -#define __DISPLAY__ - -#include "utils.hpp" - -namespace NOMAD { - - /// Custom display class. - /** - - This class is used instead of \c std::ostream ojects. - - Use \c std::endl as new line character; \c '\\n' will ignore indentation. - - Do not use \c << \c flush; : it would create a new indentation. - Use method \c Display::flush() instead. - - \b Two \b examples \b for \b creating \b indented \b blocks: - - \code - using namespace NOMAD; - Display out ( std::cout ); - \endcode - - \b Example \b 1: - - \code - out << "line #1" << std::endl - << open_block() - << "line #2" << std::endl << "line #3" << std::endl - << open_block ( "begin of block 2" ) - << "line #4" << std::endl << "line #5" << std::endl - << close_block ( "end of block 2" ) - << close_block() - << std::endl; - \endcode - - \b Example \b 2: - - \code - out << "line #1" << std::endl; - out.open_block(); - out << "line #2" << std::endl << "line #3" << std::endl; - out.open_block ("begin of block 2"); - out << "line #4" << std::endl << "line #5" << std::endl; - out.close_block ("end of block 2"); - out.close_block(); - out << std::endl; - \endcode - - \b This \b displays \b twice: - - \verbatim - line #1 - { - line #2 - line #3 - begin of block 2 { - line #4 - line #5 - } end of block 2 - } - \endverbatim - */ - class Display { - - private: - - std::ostream & _out; ///< Display. - - mutable std::string _indent_str; ///< Indentation string (tabulations). - mutable bool _newline; ///< Indent or not. - - std::string _open_brace; ///< Braces of the indentation blocks. - std::string _closed_brace; ///< Defaults: "{" and "}". - - NOMAD::dd_type _gen_dd; ///< General display degree. - NOMAD::dd_type _search_dd; ///< Search display degree. - NOMAD::dd_type _poll_dd; ///< Poll display degree. - NOMAD::dd_type _iter_dd; ///< Iterative display degree. - - /// Private affectation operator. - /** - \param out The right-hand side object -- \b IN. - */ - const Display & operator = ( const Display & out ); - - public: - - /// Constructor. - /** - \param out A \c std::ostream that will be used for all displays - (can be a \c std::ofstream) - -- \b IN -- \b optional (default = \c std::cout). - */ - Display ( std::ostream & out = std::cout ) - : _out ( out ) , // can be a std::ofstream - _newline ( true ) , - _open_brace ( "{" ) , - _closed_brace ( "}" ) , - _gen_dd ( NOMAD::NORMAL_DISPLAY ) , - _search_dd ( NOMAD::NORMAL_DISPLAY ) , - _poll_dd ( NOMAD::NORMAL_DISPLAY ) , - _iter_dd ( NOMAD::NORMAL_DISPLAY ) {} - - /// Copy constructor. - /** - \param out The copied object -- \b IN. - */ - Display ( const Display & out ) - : _out ( out._out ) , - _indent_str ( out._indent_str ) , - _newline ( out._newline ) , - _open_brace ( out._open_brace ) , - _closed_brace ( out._closed_brace ) , - _gen_dd ( out._gen_dd ) , - _search_dd ( out._search_dd ) , - _poll_dd ( out._poll_dd ) , - _iter_dd ( out._iter_dd ) {} - - /// Destructor. - virtual ~Display ( void ) {} - - /// Flush. - /** - Must be used instead of \c out \c << \c std::flush. - */ - void flush ( void ) const { _out << std::flush; } - - /*---------------*/ - /* GET methods */ - /*---------------*/ - - /// Access to the indentation string. - /** - \return The indentation string. - */ - const std::string get_indent_str ( void ) const { return _indent_str; } - - /// Access to the general display degree. - /** - \return _gen_dd. - */ - NOMAD::dd_type get_gen_dd ( void ) const { return _gen_dd; } - - /// Access to the search display degree. - /** - \return _search_dd. - */ - NOMAD::dd_type get_search_dd ( void ) const { return _search_dd; } - - /// Access to the poll display degree. - /** - \return _poll_dd. - */ - NOMAD::dd_type get_poll_dd ( void ) const { return _poll_dd; } - - /// Access to the iterative display degree. - /** - \return _iter_dd. - */ - NOMAD::dd_type get_iter_dd ( void ) const { return _iter_dd; } - - /// Get the display degree for a specific search type. - /** - \param search The search type. - \return The display degree. - */ - NOMAD::dd_type get_display_degree ( NOMAD::search_type search ) const; - - /// Get the display degrees as a string of size 4. - /** - \param dd The string containing the display degrees -- \b OUT. - */ - void get_display_degree ( std::string & dd ) const; - - /*---------------*/ - /* SET methods */ - /*---------------*/ - - /// Set the indentation string. - /** - \param is The indentation string -- \b IN. - */ - void set_indent_str ( const std::string & is ) { _indent_str = is; } - - /// Set the _open_brace string. - /** - \param ob The string -- \b IN. - */ - void set_open_brace ( const std::string & ob ) { _open_brace = ob; } - - /// Set the _closed_brace string. - /** - \param cb The string -- \b IN. - */ - void set_closed_brace ( const std::string & cb ) { _closed_brace = cb; } - - /// Set the display degrees. - /** - \param gen_dd General display degree -- \b IN. - \param search_dd Search display degree -- \b IN. - \param poll_dd Poll display degree -- \b IN. - \param iter_dd Iterative display degree -- \b IN. - */ - void set_degrees ( NOMAD::dd_type gen_dd , - NOMAD::dd_type search_dd , - NOMAD::dd_type poll_dd , - NOMAD::dd_type iter_dd ); - - /// Set all the display degrees to one given display degree. - /** - \param dd The 4 display degrees -- \b IN. - */ - void set_degrees ( NOMAD::dd_type dd ) { set_degrees ( dd , dd , dd , dd ); } - - /// Open an indentation block. - /** - \param msg Message displayed as the block title - -- \b IN -- \b optional (default = empty string). - */ - void open_block ( const std::string & msg = "" ) const; - - /// Close an indentation block. - /** - \param msg Message displayed at the end of the block - -- \b IN -- \b optional (default = empty string). - */ - void close_block ( const std::string & msg = "" ) const; - - /// Operator <<. - template - const Display & operator << ( const T & ) const; - - /// Defines the \c cout type. - typedef std::basic_ostream > CoutType; - - /// Allows the use of \c out \c << \c endl (\c std::endl is used). - /** - \warning This considers also \c std::flush. - */ - typedef CoutType& (*StandardEndLine)(CoutType&); - - /// Operator << for \c std::endl. - const Display & operator << ( StandardEndLine ) const; - - /// Set the display precision. - /** - \param p The display precision -- \b IN. - */ - void precision ( int p ) const { _out.precision(p); } - - /// Get the current display precision. - /** - \return An integer for the current precision. - */ - int precision ( void ) const { return static_cast(_out.precision()); } - - /// Set the format flags (1/2). - /** - \param f The flags -- \b IN. - */ - void flags ( std::ios_base::fmtflags f ) const { _out.flags(f); } - - /// Set the format flags (2/2). - /** - \param f The flags -- \b IN. - */ - void setf ( std::ios_base::fmtflags f ) const { _out.setf(f); } - - /// Unset the format flags. - /** - \param f The flags -- \b IN. - */ - void unsetf ( std::ios_base::fmtflags f ) const { _out.unsetf(f); } - - - /// Get the current format flags. - /** - \return The format flags. - */ - std::ios_base::fmtflags flags ( void ) const { return _out.flags(); } - - /*--------------------*/ - /* type conversions */ - /*--------------------*/ - - /// Convert a NOMAD::dd_type to a character. - /** - \param dd The NOMAD::dd_type -- \b IN. - \return The character. - */ - static char dd_to_char ( NOMAD::dd_type dd ); - - /// Convert a NOMAD::dd_type to an integer. - /** - \param dd The NOMAD::dd_type -- \b IN. - \return The integer. - */ - static int dd_to_int ( NOMAD::dd_type dd ); - - /// Convert an integer to a NOMAD::dd_type. - /** - \param dd The integer -- \b IN. - \return The NOMAD::dd_type. - */ - static NOMAD::dd_type int_to_dd ( int dd ); - - /// Display a duration with a smart format. - /** - \param t Duration as an integer in seconds -- \b IN. - */ - void display_time ( int t ) const; - - /// Display a boolean with format \c yes/no. - /** - \param b The boolean -- \b IN. - */ - void display_yes_or_no ( bool b ) const { (*this) << ( (b) ? "yes" : "no" ); } - - /// Display a memory size. - /** - \param size The memory size. - */ - void display_size_of ( float size ) const; - - /// Display an integer with a specific width. - /** - \param i The integer to display -- \b IN. - \param max_i Maximal value of \c i used to determine the display width - -- \b IN -- \b optional (default = \c -1). - */ - void display_int_w ( int i , int max_i = -1 ) const; - - /// Get the keyword associated with a NOMAD::display_stats_type. - /** - \param dst The NOMAD::display_stats_type -- \b IN. - \return A string containing the keyword. - */ - static std::string get_display_stats_keyword ( NOMAD::display_stats_type dst ); - - /// Extract display format from a string. - /** - \param s The string -- \b IN/OUT. - \param format The format -- \b OUT. - */ - static void extract_display_format ( std::string & s , std::string & format ); - - /// Get the NOMAD::display_stats_type from a string. - /** - \param s The string -- \b IN. - \return The NOMAD::display_stats_type. - */ - static NOMAD::display_stats_type get_display_stats_type ( const std::string & s ); - - }; - - /*-------------------------------------------------------------------------*/ - - /// Open an indented block. - /** - Allows the use of \c out \c << \c open_block(msg). - */ - class open_block { - private: - std::string _msg; ///< Message displayed as a block title. - public: - - /// Constructor. - /** - Open an indented block. - \param msg The block title - -- \b IN -- \b optional (default = empty string). - */ - open_block ( const std::string & msg = "" ) : _msg ( msg ) {} - - /// Operator (). - const Display & operator() ( const Display & out ) const { - out.open_block ( _msg ); - return out; - } - }; - - /*-------------------------------------------------------------------------*/ - - /// Close an indented block. - /** - Allows the use of \c out \c << \c close_block(msg). - */ - class close_block { - private: - std::string _msg; ///< Message displayed at the end of a block. - public: - - /// Constructor. - /** - Close an indented block. - \param msg Message displayed at the end of a block - -- \b IN -- \b optional (default = empty string). - */ - close_block ( const std::string & msg = "" ) : _msg ( msg ) {} - - /// Operator (). - const Display & operator() ( const Display & out ) const { - out.close_block ( _msg ); - return out; - } - }; - - /*-------------------------------------------------------------*/ - /* display functions for enum types defined in 'defines.hpp' */ - /*-------------------------------------------------------------*/ - - /// Operator << for NOMAD::stop_type. - std::ostream & operator << ( std::ostream & , NOMAD::stop_type ); - - /// Operator << for NOMAD::dd_type. - std::ostream & operator << ( std::ostream & , NOMAD::dd_type ); - - /// Operator << for NOMAD::success_type. - std::ostream & operator << ( std::ostream & , NOMAD::success_type ); - - /// Operator << for NOMAD::bb_input_type. - std::ostream & operator << ( std::ostream & , NOMAD::bb_input_type ); - - /// Operator << for NOMAD::bb_output_type. - std::ostream & operator << ( std::ostream & , NOMAD::bb_output_type ); - - /// Operator << for NOMAD::interpolation_type. - std::ostream & operator << ( std::ostream & , NOMAD::interpolation_type ); - - /// Operator << for NOMAD::hnorm_type. - std::ostream & operator << ( std::ostream & , NOMAD::hnorm_type ); - - /// Operator << for NOMAD::search_type. - std::ostream & operator << ( std::ostream & , NOMAD::search_type ); - - /// Operator << for NOMAD::model_type. - std::ostream & operator << ( std::ostream & , NOMAD::model_type ); - - /// Operator << for NOMAD::TGP_mode_type. - std::ostream & operator << ( std::ostream & , NOMAD::TGP_mode_type ); - - /// Operator << for NOMAD::direction_type. - std::ostream & operator << ( std::ostream & , NOMAD::direction_type ); - - /// Operator << for NOMAD::check_failed_type. - std::ostream & operator << ( std::ostream & , NOMAD::check_failed_type ); - - /// Operator << for NOMAD::display_stats_type. - std::ostream & operator << ( std::ostream & , NOMAD::display_stats_type ); - - /// Operator << for NOMAD::eval_type. - std::ostream & operator << ( std::ostream & , NOMAD::eval_type ); - - /// Operator << for NOMAD::eval_status_type. - std::ostream & operator << ( std::ostream & , NOMAD::eval_status_type ); - - /// Operator << for NOMAD::multi_formulation_type. - std::ostream & operator << ( std::ostream & , NOMAD::multi_formulation_type ); - - /// Operator << for a vector of NOMAD::bb_intput_type. - std::ostream & operator << ( std::ostream & , - const std::vector & ); - - /// Operator <<. - template - inline const NOMAD::Display & NOMAD::Display::operator << ( const T & t ) const - { - if ( _newline ) { - _out << _indent_str; - _newline = false; - } - _out << t; - return *this; - } - - /// Allows the use of \c out \c << \c endl. - inline const NOMAD::Display & NOMAD::Display::operator << ( StandardEndLine m ) const - { - m ( _out ); // this could be a std::flush, so don't use it: instead use method flush() - _newline = true; - return *this; - } - - /// Allows the use of \c out \c << \c open_block(msg). - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::open_block & ob ) - { - return ob ( out ); - } - - /// Allows the use of \c out \c << \c close_block(msg). - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::close_block & cb ) - { - return cb ( out ); - } - -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Double.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Double.cpp deleted file mode 100644 index 78faac537..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Double.cpp +++ /dev/null @@ -1,717 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Double.cpp - \brief Custom class for double-precision reals (implementation) - \author Sebastien Le Digabel - \date 2010-04-02 - \see Double.hpp - */ -#include "Double.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -double NOMAD::Double::_epsilon = NOMAD::DEFAULT_EPSILON; -std::string NOMAD::Double::_inf_str = NOMAD::DEFAULT_INF_STR; -std::string NOMAD::Double::_undef_str = NOMAD::DEFAULT_UNDEF_STR; -#ifdef MEMORY_DEBUG -int NOMAD::Double::_cardinality = 0; -int NOMAD::Double::_max_cardinality = 0; -#endif - -/*-----------------------------------------------*/ -/* constructor 1 */ -/*-----------------------------------------------*/ -NOMAD::Double::Double ( void ) -: _value ( 0.0 ) , -_defined ( false ) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Double::_cardinality; - if ( NOMAD::Double::_cardinality > NOMAD::Double::_max_cardinality ) - ++NOMAD::Double::_max_cardinality; -#endif -} - -/*-----------------------------------------------*/ -/* constructor 2 */ -/*-----------------------------------------------*/ -NOMAD::Double::Double ( double v ) -: _value ( v ) , -_defined ( true ) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Double::_cardinality; - if (NOMAD::Double::_cardinality > NOMAD::Double::_max_cardinality) - ++NOMAD::Double::_max_cardinality; -#endif -} - -/*-----------------------------------------------*/ -/* constructor 3 */ -/*-----------------------------------------------*/ -NOMAD::Double::Double ( const NOMAD::Double & d ) -: _value ( d._value ) , -_defined ( d._defined ) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Double::_cardinality; - if (NOMAD::Double::_cardinality > NOMAD::Double::_max_cardinality) - ++NOMAD::Double::_max_cardinality; -#endif -} - -/*-----------------------------------------------*/ -/* destructor */ -/*-----------------------------------------------*/ -NOMAD::Double::~Double ( void ) -{ -#ifdef MEMORY_DEBUG - --NOMAD::Double::_cardinality; -#endif -} - -/*-----------------------------------------------*/ -/* set epsilon (static) */ -/*-----------------------------------------------*/ -void NOMAD::Double::set_epsilon ( double eps ) -{ - if ( eps <= 0.0 ) - throw NOMAD::Exception ( "Double.cpp" , __LINE__ , - "NOMAD::Double::set_epsilon(): invalid epsilon" ); - NOMAD::Double::_epsilon = eps; -} - -/*-----------------------------------------------*/ -/* get the value */ -/*-----------------------------------------------*/ -double NOMAD::Double::value ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::value(): value not defined" ); - return _value; -} - -/*------------------------------------------*/ -/* input */ -/*------------------------------------------*/ -std::istream & NOMAD::operator >> ( std::istream & in , NOMAD::Double & d ) -{ - std::string s; - in >> s; - - if ( !in.fail() && !d.atof (s) ) - in.setstate ( std::ios::failbit ); - - return in; -} - -/*-----------------------------------------------*/ -/* atof: value determined by a string */ -/*-----------------------------------------------*/ -bool NOMAD::Double::atof ( const std::string & ss ) -{ - - std::string s = ss; - NOMAD::toupper(s); - - if ( s == "-" || ss == NOMAD::Double::_undef_str ) { - _value = 0.0; - _defined = false; - return true; - } - - if ( s == "INF" || s == "+INF" || - ss == NOMAD::Double::_inf_str || - ss == ("+" + NOMAD::Double::_inf_str) ) { - _value = NOMAD::INF; - _defined = true; - return true; - } - - if ( s == "-INF" || ss == ("-" + NOMAD::Double::_inf_str) ) { - _value = -NOMAD::INF; - _defined = true; - return true; - } - - if ( s.empty() || (s.size() == 1 && !isdigit(s[0])) ) - return false; - - if ( !isdigit(s[0]) && s[0] != '+' && s[0] != '-' && s[0] != '.' ) - return false; - - size_t n = s.size(); - for ( size_t k = 1 ; k < n ; ++k ) - if ( !isdigit(s[k]) && s[k] != '.' ) { - if ( s[k] == 'E' ) { - if ( s.size() == k+1 ) - return false; - ++k; - if ( !isdigit(s[k]) && s[k] != '+' && s[k] != '-' ) - return false; - } - else - return false; - } - - *this = std::atof ( s.c_str() ); - return true; -} - -/*-------------------------------------------------*/ -/* atof from a string that can begin with 'r' to */ -/* indicate a proportion (relative value) */ -/*-------------------------------------------------*/ -bool NOMAD::Double::relative_atof ( const std::string & s , bool & relative ) -{ - if ( std::toupper(s[0]) == 'R' ) { - relative = true; - std::string ss = s; - ss.erase(ss.begin()); - if ( !atof(ss) ) - return false; - return ( *this >= 0.0 ); - } - relative = false; - return atof(s); -} - -/*-----------------------------------------------*/ -/* is the value an integer? */ -/*-----------------------------------------------*/ -bool NOMAD::Double::is_integer ( void ) const -{ - if ( !_defined ) - return false; - return ( NOMAD::Double(std::floor(_value))) == ( NOMAD::Double(std::ceil(_value)) ); -} - -/*-----------------------------------------------*/ -/* is the value binary ? */ -/*-----------------------------------------------*/ -bool NOMAD::Double::is_binary ( void ) const -{ - if ( !_defined ) - return false; - return ( NOMAD::Double(_value) == 0.0 || NOMAD::Double(_value) == 1.0 ); -} - -/*-------------------------------------*/ -/* d = d1/d2 */ -/*-------------------------------------*/ -const NOMAD::Double NOMAD::operator / ( const NOMAD::Double & d1 , - const NOMAD::Double & d2 ) -{ - if ( d2.value() == 0.0 ) - throw NOMAD::Double::Invalid_Value ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d1 / d2: division by zero" ); - return NOMAD::Double ( d1.value() / d2.value() ); -} - -/*-------------------------------------*/ -/* d1 += d2 */ -/*-------------------------------------*/ -const NOMAD::Double & NOMAD::Double::operator += ( const NOMAD::Double & d2 ) -{ - if ( !_defined || !d2._defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d1 += d2: d1 or d2 not defined" ); - _value += d2._value; - return *this; -} - -/*-------------------------------------*/ -/* d1 -= d2 */ -/*-------------------------------------*/ -const NOMAD::Double & NOMAD::Double::operator -= ( const NOMAD::Double & d2 ) -{ - if ( !_defined || !d2._defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d1 -= d2: d1 or d2 not defined" ); - _value -= d2._value; - return *this; -} - -/*-------------------------------------*/ -/* d1 *= d2 */ -/*-------------------------------------*/ -const NOMAD::Double & NOMAD::Double::operator *= ( const NOMAD::Double & d2 ) -{ - if ( !_defined || !d2._defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d1 *= d2: d1 or d2 not defined" ); - _value *= d2._value; - return *this; -} - -/*-------------------------------------*/ -/* d1 /= d2 */ -/*-------------------------------------*/ -const NOMAD::Double & NOMAD::Double::operator /= ( const NOMAD::Double & d2 ) -{ - if ( !_defined || !d2._defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d1 /= d2: d1 or d2 not defined" ); - if ( d2._value == 0.0 ) - throw Invalid_Value ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d1 /= d2: division by zero" ); - _value /= d2._value; - return *this; -} - -/*-------------------------------------*/ -/* ++d */ -/*-------------------------------------*/ -NOMAD::Double & NOMAD::Double::operator++ ( void ) -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , "NOMAD::Double: ++d: d not defined" ); - _value += 1; - return *this; -} - -/*-------------------------------------*/ -/* d++ */ -/*-------------------------------------*/ -NOMAD::Double NOMAD::Double::operator++ ( int n ) -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , "NOMAD::Double: d++: d not defined" ); - NOMAD::Double tmp = *this; - if( n <= 0 ) - n = 1; - _value += n; - return tmp; -} - -/*-------------------------------------*/ -/* --d */ -/*-------------------------------------*/ -NOMAD::Double & NOMAD::Double::operator-- ( void ) -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , "NOMAD::Double: --d: d not defined" ); - _value -= 1; - return *this; -} - -/*-------------------------------------*/ -/* d-- */ -/*-------------------------------------*/ -NOMAD::Double NOMAD::Double::operator-- ( int n ) -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double: d--: d not defined" ); - NOMAD::Double tmp = *this; - if ( n <= 0 ) - n = 1; - _value -= n; - return tmp; -} - -/*-------------------------------------*/ -/* operators = */ -/*-------------------------------------*/ -NOMAD::Double & NOMAD::Double::operator = ( const NOMAD::Double & d ) -{ - _value = d._value; - _defined = d._defined; - return *this; -} - -NOMAD::Double & NOMAD::Double::operator = ( double r ) -{ - _value = r; - _defined = true; - return *this; -} - -/*------------------------------------------*/ -/* display */ -/*------------------------------------------*/ -void NOMAD::Double::display ( const NOMAD::Display & out ) const -{ - if ( _defined ) { - if ( _value == NOMAD::INF ) - out << NOMAD::Double::_inf_str; - else if ( _value == -NOMAD::INF ) - out << "-" << NOMAD::Double::_inf_str; - else if ( std::floor(_value) == std::ceil(_value) && fabs(_value) < INT_MAX-1 ) - out << static_cast(_value); - else - out << _value; - } - else - out << NOMAD::Double::_undef_str; -} - -/*------------------------------------------*/ -/* display with format */ -/*------------------------------------------*/ -void NOMAD::Double::display ( const NOMAD::Display & out , - const std::string & format ) const -{ - // interpret the format: - // --------------------- - - // %f w=-1 prec=-1 c='f' - // %4.5f w= 4 prec= 5 c='f' - // %4f w= 4 prec= 1 c='f' - // %.5f w=-1 prec= 5 c='f' - // %.f w=-1 prec= 0 c='f' - - // c may be in 'e', 'E', 'f', 'g', 'G', 'd', or 'i' - - // e Scientific notation (mantise/exponent) using e character 3.9265e+2 - // E Scientific notation (mantise/exponent) using E character 3.9265E+2 - // f Decimal floating point 392.65 - // g Use the shorter of %e or %f 392.65 - // G Use the shorter of %E or %f 392.65 - // d or i Integer rounded value 393 - - - std::string format2 = format; - - int w = -1; - int prec = -1; - char c = 0; - - if ( !format2.empty() && format2[0]=='%' ) - { - - size_t n = format2.size(); - - c = format2[n-1]; - - if ( c!='e' && c!='E' && c!='f' && c!='g' && c!='G' && c!='d' && c!='i' ) - { - c = ( std::floor(_value) == std::ceil(_value) && fabs(_value) < INT_MAX-1 ) ? - 'd' : 'f'; - format2.push_back(c); - ++n; - } - - if ( n > 2 ) - { - - std::string sw , sprec; - - size_t k = format2.find("."); - - if ( k > 0 && k < n-1 ) - { - if ( n==3 ) - { - sprec = "0"; - } - else - { - if ( k > 1 ) - sw = format2.substr ( 1 , k-1 ); - sprec = format2.substr ( k+1 , n-k-2 ); - } - } - else - { - sw = format2.substr ( 1 , n-2 ); - } - - if ( !NOMAD::atoi ( sw , w ) ) - w = -1; - - if ( !NOMAD::atoi ( sprec , prec ) ) - prec = -1; - } - - if ( c=='d' || c=='i' ) - prec = 0; - } - - // display the value: - out << std::setw(w); - if ( _defined ) - { - if ( _value == NOMAD::INF ) - out << NOMAD::Double::_inf_str; - else if ( c=='d' || c=='i' || - ( format2.empty() && - std::floor(_value) == std::ceil(_value) && fabs(_value) < INT_MAX-1 ) ) - out << round(); - else - { - - int old_prec = out.precision(); - std::ios_base::fmtflags old_flags = out.flags(); - - if ( prec >= 0 ) - out.precision ( prec ); - - if ( c == 'f' ) - out.setf ( std::ios::fixed ); - - else if ( c == 'e' ) - { - out.unsetf ( std::ios::fixed ); - out.setf ( std::ios::scientific ); - } - - else if ( c == 'E' ) - { - out.unsetf ( std::ios::fixed ); - out.setf ( std::ios::scientific | std::ios::uppercase ); - } - - else if ( c == 'g' ) - { - std::ostringstream streamS,streamF; - streamS.precision ( prec ); - streamF.precision ( prec ); - streamF.unsetf(std::ios::scientific); - streamF.setf( std::ios::fixed ); - streamS.unsetf(std::ios::fixed); - streamS.setf( std::ios::scientific); - streamS << _value; - streamF << _value; - if (streamS.str().length() < streamF.str().length()) - out.setf(std::ios::scientific); - else - out.setf(std::ios::fixed); - - } - - else if ( c == 'G' ) - { - std::ostringstream streamS,streamF; - streamS.precision ( prec ); - streamF.precision ( prec ); - streamF.unsetf(std::ios::scientific); - streamF.setf( std::ios::fixed ); - streamS.unsetf(std::ios::fixed); - streamS.setf( std::ios::scientific); - streamS << _value ; - streamF << _value ; - if (streamS.str().length() < streamF.str().length()) - out.setf(std::ios::scientific | std::ios::uppercase ); - else - out.setf(std::ios::fixed | std::ios::uppercase ); - } - - out << _value; - - out.precision ( old_prec ); - out.flags ( old_flags ); - } - } - else - out << NOMAD::Double::_undef_str; -} - -/*------------------------------------------*/ -/* round */ -/*------------------------------------------*/ -int NOMAD::Double::round ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::round(): value not defined" ); - return static_cast(_value < 0.0 ? -std::floor(.5-_value) : std::floor(.5+_value)); -} - - -/*------------------------------------------*/ -/* Ceil */ -/*------------------------------------------*/ -const NOMAD::Double NOMAD::Double::ceil ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::ceil(): value not defined" ); - return NOMAD::Double(std::ceil(_value)); -} - -/*------------------------------------------*/ -/* Floor */ -/*------------------------------------------*/ -const NOMAD::Double NOMAD::Double::floor ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::floor(): value not defined" ); - return NOMAD::Double(std::floor(_value)); -} - -/*------------------------------------------*/ -/* abs */ -/*------------------------------------------*/ -const NOMAD::Double NOMAD::Double::abs ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::abs(): value not defined" ); - return fabs ( _value ); -} - -/*------------------------------------------*/ -/* square */ -/*------------------------------------------*/ -const NOMAD::Double NOMAD::Double::pow2 ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::pow2(): value not defined" ); - return pow ( _value , 2 ); -} - -/*------------------------------------------*/ -/* square root */ -/*------------------------------------------*/ -const NOMAD::Double NOMAD::Double::sqrt ( void ) const -{ - if ( !_defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::sqrt(): value not defined" ); - if ( *this < 0.0 ) - throw NOMAD::Double::Invalid_Value ( "Double.cpp" , __LINE__ , - "NOMAD::Double::sqrt(x): x < 0" ); - - return std::sqrt ( _value ); -} - -/*---------------------------------------------*/ -/* relative error with another NOMAD::Double */ -/*---------------------------------------------*/ -// -// This error computation is based on: -// -// A. Ziv. Relative distance–an error measure in round-off error analysis. Mathematics -// of Computation, 39(160):563–569, 1982. doi:10.1090/S0025-5718-1982-0669649-2. -// -// The error will be in [0;2] -// -// Modified: 2014-06-07, S. Le Digabel -// -const NOMAD::Double NOMAD::Double::rel_err ( const Double & x ) const -{ - if ( !_defined || !x._defined ) - throw Not_Defined ( "Double.cpp" , __LINE__ , - "NOMAD::Double::rel_err(): one of the values is not defined" ); - - // 1. test if x==y: - if ( this == &x || _value == x._value ) - return 0.0; - - double diff = fabs ( _value - x._value ); - - // 2. test if one of the values is zero: - if ( _value == 0.0 || x._value == 0.0 ) { - - // we return min{2,|x-y|} (instead of 1): - if ( diff > 2.0 ) - return 2.0; - return diff; - } - - // 3. compute the original error: - double a = fabs ( _value ); - double b = fabs ( x._value ); - double err = diff / ( (a ub ) - *this = ub; - - if ( lb._defined && *this < lb ) - *this = lb; - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Double.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Double.hpp deleted file mode 100644 index a72ee3502..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Double.hpp +++ /dev/null @@ -1,537 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Double.hpp - \brief Custom class for double-precision reals (headers) - \author Sebastien Le Digabel - \date 2010-04-02 - \see Double.cpp -*/ -#ifndef __NOMAD_DOUBLE__ -#define __NOMAD_DOUBLE__ - -#include "Exception.hpp" -#include "Display.hpp" - -namespace NOMAD { - - /// Custom class for double-precision reals. - /** - - Allows comparisons on reals with custom precision. - - Deals with undefined values. - - Use \c value() to access the true \c double value. - */ - class Double { - - private: - -#ifdef MEMORY_DEBUG - static int _cardinality; ///< Number of NOMAD::Double objects in memory. - static int _max_cardinality; ///< Max number of NOMAD::Double objects in memory. -#endif - - double _value; ///< The value of the number. - bool _defined; ///< \c true if the number has a defined value. - - static double _epsilon; ///< Desired precision on comparisons. - static std::string _inf_str; ///< Infinity string. - static std::string _undef_str; ///< Undefined value string. - - public: - - /*-------------------------------------------------------------------*/ - - /// Exception class for undefined NOMAD::Double objects. - class Not_Defined : public NOMAD::Exception { - public: - /// Constructor. - Not_Defined ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /// Exception class for divisons by zero with NOMAD::Double objects. - class Invalid_Value : public NOMAD::Exception { - public: - /// Constructor. - Invalid_Value ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /*-------------------------------------------------------------------*/ -#ifdef MEMORY_DEBUG - /// Access to the number of NOMAD::Double objects in memory. - /** - \return The number of NOMAD::Double objects in memory. - */ - static int get_cardinality ( void ) { return NOMAD::Double::_cardinality; } - - /// Access to the max number of NOMAD::Double objects in memory. - /** - \return The max number of NOMAD::Double objects in memory. - */ - static int get_max_cardinality ( void ) { return NOMAD::Double::_max_cardinality; } -#endif - - /// Constructor #1. - explicit Double ( void ); - - /// Constructor #2. - /** - From a \c double. - \param v The \c double -- \b IN. - */ - Double ( double v ); - - /// Copy constructor. - /** - \param d The copied object -- \b IN. - */ - Double ( const Double & d ); - - /// Destructor. - virtual ~Double ( void ); - - /// Function \c atof (conversion from a string to a real). - /** - The value is determined by a string. - \param s The string -- \b IN. - \return A boolean equal to \c true if the string was valid. - */ - bool atof ( const std::string & s ); - - /// Function \c atof (conversion from a string to a real) with a relative value. - /** - The value is determined by a string that may begin with \c 'r' to - indicate a proportion (relative value). - \param s The string -- \b IN. - \param relative A boolean indicating if the conversion was relative -- \b OUT. - \return A boolean equal to \c true if the string was valid. - */ - bool relative_atof ( const std::string & s , bool & relative ); - - /// Reset the Double. - void clear ( void ) { _value = 0.0; _defined = false; } - - /// Reset the Double. - void reset ( void ) { clear(); } - - /// Affectation operator #1. - /** - \param d The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Double & operator = ( const Double & d ); - - /// Affectation operator #2. - /** - \param r The right-hand side \c double -- \b IN. - \return \c *this as the result of the affectation. - */ - Double & operator = ( double r ); - - /// Access to the \c double value. - /** - \return The \c double value. - */ - double value ( void ) const; - - /// Is the value defined ? - /** - \return A boolean equal to \c true if the NOMAD::Double is defined. - */ - bool is_defined ( void ) const { return _defined; } - - /// Is the value an integer ? - /** - \return A boolean equal to \c true if the NOMAD::Double is an integer. - */ - bool is_integer ( void ) const; - - /// Is the value binary ? - /** - \return A boolean equal to \c true if the NOMAD::Double is in {0,1}. - */ - bool is_binary ( void ) const; - - /// Sizeof. - /** - The size of an object in memory. - \return An integer value for the size in bytes. - */ - int size_of ( void ) const { return sizeof(_defined) + sizeof(_value); } - - /// Access to the NOMAD::Double precision. - /** - \return A \c double for the precision. - */ - static double get_epsilon ( void ) { return Double::_epsilon; } - - /// Set the NOMAD::Double precision. - /** - \param eps The precision -- \b IN. - */ - static void set_epsilon ( double eps ); - - /// Access to the undefined value string. - /** - \return A \c std::string for the undefined value string. - */ - static std::string get_undef_str ( void ) { return Double::_undef_str; } - - /// Set the NOMAD::Double undefined value string. - /** - \param undef_str The undefined value string -- \b IN. - */ - static void set_undef_str ( const std::string & undef_str ) - { - NOMAD::Double::_undef_str = undef_str; - } - - /// Access to the infinity string. - /** - \return A \c std::string for the infinity string. - */ - static std::string get_inf_str ( void ) { return Double::_inf_str; } - - /// Set the NOMAD::Double infinity string. - /** - \param inf_str The infinity string -- \b IN. - */ - static void set_inf_str ( const std::string & inf_str ) - { - NOMAD::Double::_inf_str = inf_str; - } - - /// Rounding. - /** - \return An integer with the rounding result. - */ - int round ( void ) const; - - - /// Ceil. - /** - \return A NOMAD::double with the rounding result. - */ - const Double ceil ( void ) const; - - /// Floor. - /** - \return A NOMAD::double with the rounding result. - */ - const Double floor ( void ) const; - - - /// Absolute value. - /** - \return Another NOMAD::Double equal to max{\c -*this,\c *this}. - */ - const Double abs ( void ) const; - - /// Square. - /** - \return Another NOMAD::Double equal to \c *this \c * \c *this. - */ - const Double pow2 ( void ) const; - - /// Square root. - /** - \return Another NOMAD::Double equal to \c (*this)^0.5. - */ - const Double sqrt ( void ) const; - - /// Relative error with another NOMAD::Double. - /** - \param x The other real -- \b IN. - \return A new object with the relative error value in \c [0;1]. - */ - const Double rel_err ( const Double & x ) const; - - /// Operator \c ++ (prefix position). - /** - Allows \c ++d; - \return The NOMAD::Double plus 1. - */ - Double & operator++ ( void ); - - /// Operator \c ++ (suffix position). - /** - Allows \c d++; - \return A copy of the NOMAD::Double before incrementation. - */ - Double operator++ ( int n ); - - /// Operator \c -- (prefix position). - /** - Allows \c --d; - \return The NOMAD::Double minus 1. - */ Double & operator-- ( void ); - - /// Operator \c -- (suffix position). - /** - Allows \c d--; - \return A copy of the NOMAD::Double before decrementation. - */ Double operator-- ( int n ); - - /// Operator \c +=. - /** - Allows \c d \c += \c d1. - \param d1 The increment -- \b IN. - \return The NOMAD::Double plus \c d1. - */ - const Double & operator += ( const Double & d1 ); - - /// Operator \c -=. - /** - Allows \c d \c -= \c d1. - \param d1 The decrement -- \b IN. - \return The NOMAD::Double minus \c d1. - */ - const Double & operator -= ( const Double & d1 ); - - /// Operator \c *=. - /** - Allows \c d \c *= \c d1. - \param d1 The factor -- \b IN. - \return The NOMAD::Double times \c d1. - */ - const Double & operator *= ( const Double & d1 ); - - /// Operator \c /=. - /** - Allows \c d \c /= \c d1. Throws a NOMAD::Exception::Invalid_Value if \c d1==0. - \param d1 The denominator -- \b IN. - \return The NOMAD::Double divided by \c d1. - */ - const Double & operator /= ( const Double & d1 ); - - /// Comparison <. - /** - The same as operator \c < but with consideration of undefined values. - When comparing \c d1 and \c d2, \c (d1>. - - Can read undefined values (parameter \c UNDEF_STR with default \c "-".) - - Example: - \code - NOMAD::Double d1 , d2; - std::cout << "Enter d1 and d2: "; - std::cin >> d1 >> d2; - std::cout << "d1 and d2 are equal to " << d1 << " and " << d2 << std::endl; - \endcode - \param in A \c std::istream object (can be a file) -- \b IN/OUT. - \param d The NOMAD::Double object to be read -- \b OUT. - \return The modified \c std::istream object. - */ - std::istream & operator >> ( std::istream & in , Double & d ); - - /// Inverse operator. - /** - Allows operations such as \c d \c = \c -d. - \param d The NOMAD::Double to be inversed -- \b IN. - \return A new NOMAD::Double as the result of the operation. - */ - inline const Double operator - ( const Double & d ) - { - return NOMAD::Double (-d.value()); - } - - /// Operator \c + for two NOMAD::Double objects. - /** - Allows operations such as \c d \c = \c d1 \c + \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A third NOMAD::Double as the result of the operation. - */ - inline const Double operator + ( const Double & d1 , const Double & d2 ) - { - return NOMAD::Double ( d1.value() + d2.value() ); - } - - /// Operator \c - for two NOMAD::Double objects. - /** - Allows operations such as \c d \c = \c d1 \c - \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A third NOMAD::Double as the result of the operation. - */ - inline const Double operator - ( const Double & d1 , const Double & d2 ) - { - return NOMAD::Double (d1.value() - d2.value()); - } - - /// Operator \c * for two NOMAD::Double objects. - /** - Allows operations such as \c d \c = \c d1 \c * \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A third NOMAD::Double as the result of the operation. - */ - inline const Double operator * ( const Double & d1 , const Double & d2 ) - { - return NOMAD::Double ( d1.value() * d2.value() ); - } - - /// Operator \c / for two NOMAD::Double objects. - /** - Allows operations such as \c d \c = \c d1 \c / \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A third NOMAD::Double as the result of the operation. - */ - const Double operator / ( const Double & d1 , const Double & d2 ); - - /// Comparison operator \c ==. - /** - Allows the comparison \c d1 \c == \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A boolean equal to true if \c d1 \c == \c d2. - */ - inline bool operator == ( const Double & d1 , const Double & d2 ) - { - return fabs ( d1.value() - d2.value() ) < NOMAD::Double::get_epsilon(); - } - - /// Comparison operator \c !=. - /** - Allows the comparison \c d1 \c != \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A boolean equal to true if \c d1 \c != \c d2. - */ - inline bool operator != ( const Double & d1 , const Double & d2 ) { return !(d1==d2); } - - /// Comparison operator \c <. - /** - Allows the comparison \c d1 \c < \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A boolean equal to true if \c d1 \c < \c d2. - */ - inline bool operator < ( const Double & d1 , const Double & d2 ) - { - return d1.value() < d2.value() - NOMAD::Double::get_epsilon(); - } - - /// Comparison operator \c >. - /** - Allows the comparison \c d1 \c > \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A boolean equal to true if \c d1 \c > \c d2. - */ - inline bool operator > ( const Double & d1 , const Double & d2 ) - { - return d1.value() > d2.value() + NOMAD::Double::get_epsilon(); - } - - /// Comparison operator \c <=. - /** - Allows the comparison \c d1 \c <= \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A boolean equal to true if \c d1 \c <= \c d2. - */ - inline bool operator <= ( const Double & d1 , const Double & d2 ) { return !(d1>d2); } - - /// Comparison operator \c >=. - /** - Allows the comparison \c d1 \c >= \c d2. - \param d1 The first NOMAD::Double -- \b IN. - \param d2 The second NOMAD::Double -- \b IN. - \return A boolean equal to true if \c d1 \c >= \c d2. - */ inline bool operator >= ( const Double & d1 , const Double & d2 ) - { - return !(d1. */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Eval_Point.cpp - \brief Evaluation point (implementation) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Eval_Point.hpp - */ -#include "Cache_File_Point.hpp" -#include "Eval_Point.hpp" -#include "Slave.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -int NOMAD::Eval_Point::_current_tag = 0; -int NOMAD::Eval_Point::_current_bbe = 0; -int NOMAD::Eval_Point::_current_sgte_bbe = 0; -/*---------------------------------------------------------------------*/ -/* constructor 1 */ -/*---------------------------------------------------------------------*/ -NOMAD::Eval_Point::Eval_Point ( void ) -: _tag ( NOMAD::Eval_Point::_current_tag++ ) , -_signature ( NULL ) , -_in_cache ( false ) , -_current_run ( false ) , -_eval_type ( NOMAD::TRUTH ) , -_direction ( NULL ) , -_poll_center_type ( NOMAD::UNDEFINED_POLL_CENTER_TYPE ) , -_eval_status ( NOMAD::UNDEFINED_STATUS ) , -_EB_ok ( true ) -{ -#ifdef MODEL_STATS - _mod_use = -1; - _nY = -1; -#endif -} - -/*---------------------------------------------------------------------*/ -/* constructor 2 */ -/*---------------------------------------------------------------------*/ -NOMAD::Eval_Point::Eval_Point ( int n , int m ) -: NOMAD::Point ( n ) , -_tag ( NOMAD::Eval_Point::_current_tag++ ) , -_signature ( NULL ) , -_in_cache ( false ) , -_current_run ( false ) , -_eval_type ( NOMAD::TRUTH ) , -_direction ( NULL ) , -_poll_center_type ( NOMAD::UNDEFINED_POLL_CENTER_TYPE ) , -_eval_status ( NOMAD::UNDEFINED_STATUS ) , -_EB_ok ( true ) , -_bb_outputs ( m ) -{ -#ifdef MODEL_STATS - _mod_use = -1; - _nY = -1; -#endif -} - -/*---------------------------------------------------------------------*/ -/* constructor 3 (used for model evalaution) */ -/*---------------------------------------------------------------------*/ -NOMAD::Eval_Point::Eval_Point ( const NOMAD::Point & x , int m ) -: NOMAD::Point ( x ) , -_direction ( NULL ) , -_bb_outputs ( m ) -{ -#ifdef MODEL_STATS - _mod_use = -1; - _nY = -1; -#endif -} - - - - -/*---------------------------------------------------------------------*/ -/* constructor 4 ( used in Cache::load() ) */ -/*---------------------------------------------------------------------*/ -NOMAD::Eval_Point::Eval_Point ( const NOMAD::Cache_File_Point & x , NOMAD::eval_type et ) -: NOMAD::Point ( x.get_n() ) , -_tag ( NOMAD::Eval_Point::_current_tag++ ) , -_signature ( NULL ) , -_in_cache ( false ) , -_current_run ( false ) , -_eval_type ( et ) , -_direction ( NULL ) , -_poll_center_type ( NOMAD::UNDEFINED_POLL_CENTER_TYPE ) , -_EB_ok ( true ) , -_bb_outputs ( x.get_bb_outputs() ) -{ - int n = size(); - for ( int i = 0 ; i < n ; ++i ) - (*this)[i] = x.get_coord(i); - - switch ( x.get_eval_status() ) { - case 0: - _eval_status = NOMAD::EVAL_FAIL; - break; - case 1: - _eval_status = NOMAD::EVAL_OK; - break; - case 2: - _eval_status = NOMAD::EVAL_IN_PROGRESS; - break; - case 3: - _eval_status = NOMAD::UNDEFINED_STATUS; - break; - } - -#ifdef MODEL_STATS - _mod_use = -1; - _nY = -1; -#endif -} - - -/*---------------------------------------------------------------------*/ -/* copy constructor */ -/*---------------------------------------------------------------------*/ -NOMAD::Eval_Point::Eval_Point ( const Eval_Point & x ) -: NOMAD::Point ( x.get_n() ) , -_tag ( NOMAD::Eval_Point::_current_tag++ ) , -_signature ( x._signature ) , -_f ( x._f ) , -_h ( x._h ) , -_in_cache ( x._in_cache ) , -_current_run ( x._current_run ) , -_eval_type ( x._eval_type ) , -_direction ( NULL ) , -_poll_center_type ( x._poll_center_type ) , -_eval_status ( x._eval_status ) , -_EB_ok ( x._EB_ok ) , -_bb_outputs ( x.get_bb_outputs() ) , -_user_eval_priority ( x._user_eval_priority ) , -_rand_eval_priority ( x._rand_eval_priority ) -{ - // point coordinates: - int n = size(); - for ( int i = 0 ; i < n ; ++i ) - (*this)[i] = x[i]; - - // _direction: - if ( x._direction ) - _direction = new Direction ( *x._direction ); - -#ifdef MODEL_STATS - set_model_data ( x ); -#endif -} - -/*---------------------------------------------------------------------*/ -/* destructor */ -/*---------------------------------------------------------------------*/ -NOMAD::Eval_Point::~Eval_Point ( void ) -{ - if ( _direction ) - delete _direction; -} - -/*-------------------------------------------------------*/ -/* SET methods used to complete a default construction */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::set ( int n , int m ) -{ - reset ( n ); - _bb_outputs.reset ( m ); -} - -void NOMAD::Eval_Point::set ( const NOMAD::Point & x , int m ) -{ - NOMAD::Point::operator = ( x ); - _bb_outputs.reset ( m ); -} - -/*-------------------------------------------------------*/ -/* manually set the tag of a point */ -/* (used in parallel version so that all points have */ -/* still unique tags */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::set_tag ( int tag ) -{ - _tag = tag; - NOMAD::Eval_Point::_current_tag = tag+1; -} - -/*-------------------------------------------------------*/ -/* increment counted black box evaluations */ -/* All points have unique tags */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::increment_bbe ( void ) -{ - NOMAD::Eval_Point::_current_bbe ++; - _bbe=_current_bbe; -} - - -/*-------------------------------------------------------*/ -/* increment counted black box evaluations */ -/* All points have unique tags */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::increment_sgte_bbe ( void ) -{ - NOMAD::Eval_Point::_current_sgte_bbe ++; - _sgte_bbe=_current_sgte_bbe; -} - - -void NOMAD::Eval_Point::set_direction ( const NOMAD::Direction * dir ) -{ - delete _direction; - _direction = ( dir ) ? new NOMAD::Direction ( *dir ) : NULL; -} - -void NOMAD::Eval_Point::set_poll_center ( const NOMAD::Eval_Point * pc ) -{ - _poll_center=pc; -} - -/*-------------------------------------------------------*/ -/* set the signature */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::set_signature ( NOMAD::Signature * s ) -{ - if ( !s ) { - _signature = NULL; - return; - } - - if ( !s->is_compatible(*this) ) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "x.Eval_Point::set_signature(s): x and s are incompatible" ); - - _signature = s; -} - -/*------------------------------------------*/ -/* get the signature */ -/*------------------------------------------*/ -NOMAD::Signature * NOMAD::Eval_Point::get_signature ( void ) const -{ -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "Eval_Point::get_signature(): cannot be invoked by slave processes" ); -#endif - return _signature; -} - -/*-------------------------------------------------------*/ -/* sizeof */ -/*-------------------------------------------------------*/ -int NOMAD::Eval_Point::size_of ( void ) const -{ - return NOMAD::Point::size_of () + - _bb_outputs.size_of () + - _f.size_of () + - _h.size_of () + - _user_eval_priority.size_of() + - _rand_eval_priority.size_of() + - sizeof (_tag ) + - sizeof (NOMAD::Signature * ) + - sizeof (_current_run ) + - sizeof (_in_cache ) + - sizeof (_eval_type ) + - sizeof (_eval_status ) + - sizeof (_EB_ok ) + - sizeof (_direction ) + - ((_direction ) ? _direction->size_of() : 0); -} - -/*-------------------------------------------------------*/ -/* scaling */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::scale ( void ) -{ - if ( !_signature ) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "x.Eval_Point::scale(): x has no signature" ); - _signature->scale ( *this ); -} - -/*-------------------------------------------------------*/ -/* unscaling */ -/*-------------------------------------------------------*/ -void NOMAD::Eval_Point::unscale ( void ) -{ - if ( !_signature ) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "x.Eval_Point::unscale(): x has no signature" ); - _signature->unscale ( *this ); -} - -/*-------------------------------------------------------*/ -/* snap to bounds */ -/* returns true if the point has been modified */ -/*-------------------------------------------------------*/ -bool NOMAD::Eval_Point::snap_to_bounds ( void ) -{ - if ( !_signature ) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "x.Eval_Point::snap_to_bounds(): x has no signature" ); - return _signature->snap_to_bounds ( *this , _direction ); -} - -/*-------------------------------------------------------*/ -/* treat the periodic variables */ -/* returns true if the point has been modified */ -/*-------------------------------------------------------*/ -bool NOMAD::Eval_Point::treat_periodic_variables ( NOMAD::Direction *& new_dir ) -{ - if (!_signature) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "x.Eval_Point::treat_periodic_variables(): x has no signature" ); - - return _signature->treat_periodic_variables ( *this , _direction , new_dir ); -} - -/*--------------------------------------------------*/ -/* Eval_Point::check */ -/*--------------------------------------------------*/ -bool NOMAD::Eval_Point::check ( int m , NOMAD::check_failed_type & cf ) const -{ - if ( size() <= 0 || !_signature || m != _bb_outputs.size() ) { - std::string err = "Eval_Point::check() could not procede"; - if ( !_signature ) - err += " (no signature)"; - else if ( m != _bb_outputs.size() ) - err += " (wrong number of blackbox outputs)"; - else - err += " (point size <= 0 !)"; - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , err ); - } - - cf = NOMAD::CHECK_OK; - - const std::vector - & input_types = _signature->get_input_types(); - const NOMAD::Point & lb = _signature->get_lb(); - const NOMAD::Point & ub = _signature->get_ub(); - const NOMAD::Point & fv = _signature->get_fixed_variables(); - int n = size(); - NOMAD::bb_input_type iti; - - for ( int i = 0 ; i < n ; ++i ) - { - - const NOMAD::Double xi = (*this)[i]; - - // undefined coordinates ? - if ( !xi.is_defined() ) - throw NOMAD::Exception ( "Eval_Point.cpp" , __LINE__ , - "Eval_Point::check() could not procede (undefined coordinates)" ); - - // check the bounds: - const NOMAD::Double & lbi = lb[i]; - if ( lbi.is_defined() && xi < lbi ) - { - cf = NOMAD::LB_FAIL; - return false; - } - - const NOMAD::Double & ubi = ub[i]; - if ( ubi.is_defined() && xi > ubi ) - { - cf = NOMAD::UB_FAIL; - return false; - } - - // check the integer/categorical/binary variables: - iti = input_types[i]; - if ( iti == NOMAD::BINARY && !xi.is_binary() ) { - cf = NOMAD::BIN_FAIL; - return false; - } - if ( ( iti == NOMAD::INTEGER || iti == NOMAD::CATEGORICAL ) - && !xi.is_integer() ) { - cf = ( iti == NOMAD::INTEGER ) ? NOMAD::INT_FAIL : NOMAD::CAT_FAIL; - return false; - } - - // check the fixed-variables: - const NOMAD::Double & fvi = fv[i]; - if ( fvi.is_defined() && fvi != xi ) { - cf = NOMAD::FIX_VAR_FAIL; - return false; - } - } - return true; -} - -/*--------------------------------------------------*/ -/* display the tag */ -/*--------------------------------------------------*/ -void NOMAD::Eval_Point::display_tag ( const NOMAD::Display & out ) const -{ - out << "#"; - out.display_int_w ( _tag , NOMAD::Eval_Point::_current_tag ); -} - -/*--------------------------------------------------*/ -/* display */ -/*--------------------------------------------------*/ -void NOMAD::Eval_Point::display_eval( const NOMAD::Display & out , bool in_block ) const -{ - if ( in_block ) { - - std::ostringstream oss; - oss << "#" << _tag; - out << NOMAD::open_block ( oss.str() ) - << "x = ( "; - NOMAD::Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl - << "F(x) = [ "; - _bb_outputs.display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " ]" << std::endl; - if ( _h.is_defined() ) - out << "h = " << _h << std::endl; - if ( _f.is_defined() ) - out << "f = " << _f << std::endl; - out.close_block(); - } - else { - display_tag ( out ); - out << " x=( "; - NOMAD::Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " ) F(x)=[ "; - _bb_outputs.display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " ]"; - if ( _h.is_defined() ) - out << " h=" << _h; - if ( _f.is_defined() ) - out << " f=" << _f; - } -} - -/*--------------------------------------------------------------*/ -/* comparison operator '<': used to find and store the points */ -/* in the filter */ -/*--------------------------------------------------------------*/ -bool NOMAD::Eval_Point::operator < ( const NOMAD::Eval_Point & x ) const -{ - if ( this == &x || !is_eval_ok() || !_EB_ok ) - return false; - - double h = _h.value(); - double f = _f.value(); - double hx = x._h.value(); - double fx = x._f.value(); - - if ( h < hx ) - return ( f <= fx ); - - if ( h == hx ) - return ( f < fx ); - - return false; -} - -/*--------------------------------------------------------------*/ -/* check if there are nan's in the blackbox outputs */ -/*--------------------------------------------------------------*/ -bool NOMAD::Eval_Point::check_nan ( void ) const -{ - int m = _bb_outputs.size(); - for ( int i = 0 ; i < m ; ++i ) { - if ( _bb_outputs[i].is_defined() ) { -#ifdef WINDOWS - if ( isnan ( _bb_outputs[i].value() ) ) - return true; -#else - if ( std::isnan ( _bb_outputs[i].value() ) ) - return true; -#endif - } - } - return false; -} - -#ifdef MODEL_STATS - -/*--------------------------------------------------------------*/ -/* set model data when debugging models */ -/*--------------------------------------------------------------*/ -void NOMAD::Eval_Point::set_model_data ( const NOMAD::Eval_Point & x ) const -{ - _mod_use = x._mod_use; - _nY = x._nY; - _cond = x._cond; - _Yw = x._Yw; - _mh = x._mh; - _mf = x._mf; -} - -/*--------------------------------------------------------------*/ -/* clear model data */ -/*--------------------------------------------------------------*/ -void NOMAD::Eval_Point::clear_model_data ( void ) const -{ - _mod_use = -1; - _nY = -1; - _cond.clear(); - _Yw.clear(); - _mh.clear(); - _mf.clear(); -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Eval_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Eval_Point.hpp deleted file mode 100644 index 972d185ff..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Eval_Point.hpp +++ /dev/null @@ -1,616 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Eval_Point.hpp - \brief Evaluation point (headers) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Eval_Point.cpp - */ -#ifndef __EVAL_POINT__ -#define __EVAL_POINT__ - -#include "Parameters.hpp" -#include "Cache_File_Point.hpp" -#include "Set_Element.hpp" - -#ifdef WINDOWS -#ifndef isnan -inline bool isnan ( double x ) { return x != x; } -#endif -#endif - -namespace NOMAD { - - /// Class for the representation of an evaluation point. - /** - An evaluation point gathers the point coordinates \c x, and the blackbox - outputs at these coordinates \c f(x). - */ - class Eval_Point : public NOMAD::Point { - - private: - - static int _current_tag; ///< Current tag for all NOMAD::Eval_Point objects. - int _tag; ///< Unique tag. - - static int _current_bbe; ///< Current bbe for all NOMAD::Eval_Point objects - static int _current_sgte_bbe; ///< Current sgte_bbe for all NOMAD::Eval_Point objects . - int _bbe; /// Recorded bbe for current NOMAD::Eval_Point object - int _sgte_bbe; /// Recorded sgte_bbe for current NOMAD::Eval_Point object - int _real_time; /// Recorded time for current NOMAD::Eval_Point object - - NOMAD::Signature * _signature; ///< Signature of the point. - - /** - \c f is explicitely computed by a NOMAD::Evaluator object - and is not saved in the cache file. - */ - NOMAD::Double _f; - - /** - \c h is explicitely computed by a NOMAD::Evaluator object - and is not saved in the cache file. - */ - NOMAD::Double _h; - - /// Flag equal to \c true if this eval point is in the cache. - mutable bool _in_cache; - - /** - Flag equal to \c true if the point has been evaluated - during the current run. - */ - mutable bool _current_run; - - /// Type of the evaluation (true function or surrogate). - NOMAD::eval_type _eval_type; - - /// Direction from which the point has been constructed. - /** - May be \c NULL if no direction has been used. - */ - NOMAD::Direction * _direction; - - - /// Poll center from which the point has been constructed. - /** - May be \c NULL if no direction has been used. - */ - const NOMAD::Eval_Point * _poll_center; - - /** - Type of the poll center (feasible or not) - from which the point has been constructed. - */ - NOMAD::poll_center_type _poll_center_type; - - /// Evaluation status. - /** - Indicates if the evaluation failed, succeeded, - or is in progress. - */ - NOMAD::eval_status_type _eval_status; - - /// Flag equal to \c true if all EB constraints have been satisfied. - bool _EB_ok; - - /// Blackbox outputs. - NOMAD::Point _bb_outputs; - - /// User evaluation priority. - /** - - Decided by the user in his custom - NOMAD::Evaluator::eval_x() function, via - \c set_user_eval_priority(). - - Points with higher priorities - will be evaluated first. - */ - NOMAD::Double _user_eval_priority; - - /// Random evaluation priority. - /** - Same idea than \c _user_eval_priority - for a random ordering of trial points. - */ - NOMAD::Double _rand_eval_priority; - - /// Affectation operator. - /** - \param x The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Eval_Point & operator = ( const Eval_Point & x ); - - public: - - /// Constructor #1. - explicit Eval_Point ( void ); - - /// Constructor #2. - /** - \param n Number of variables -- \b IN. - \param m Number of blackbox outputs -- \b IN. - */ - Eval_Point ( int n , int m ); - - /// Constructor #3. - /** - \param x Coordinates of a point taken in a cache -- \b IN. - \param et Type of the evaluation (true or surrogate) -- \b IN. - */ - explicit Eval_Point ( const NOMAD::Cache_File_Point & x , - NOMAD::eval_type et ); - - - ///Constructor 4 - /** - \param x Coordinates of a point -- \b IN. - \param m Number of blackbox outputs -- \b IN. - */ - explicit Eval_Point ( const NOMAD::Point & x, int m ) ; - - - - /// Copy constructor. - /** - \param x The copied object. - */ - explicit Eval_Point ( const Eval_Point & x ); - - /// Destructor. - virtual ~Eval_Point ( void ); - - /// Check the evaluation point. - /** - \param m Number of blackbox outputs -- \b IN. - \param cf The reason for a check failure -- \b OUT. - \return A boolean equal to \c true if the point is valid. - */ - bool check ( int m , NOMAD::check_failed_type & cf ) const; - - /*---------------*/ - /* GET methods */ - /*---------------*/ - - /// Size of the point in memory. - /** - \return Size of the point in memory, in bytes. - */ - virtual int size_of ( void ) const; - - /// Access to the signature of the point. - /** - \return A pointer to the signature of the point. - */ - NOMAD::Signature * get_signature ( void ) const; - - /// Access to the number of blackbox outputs. - /** - \return Number of blackbox outputs. - */ - int get_m ( void ) const { return _bb_outputs.size(); } - - /// Access to the number of variables. - /** - \return Number of variables. - */ - int get_n ( void ) const { return size(); } - - /// Check if the evaluation at this point is valid. - /** - \return A boolean equal to \c true if the evaluation is valid. - */ - bool is_eval_ok ( void ) const { return (_eval_status == NOMAD::EVAL_OK); } - - /// Check if the evaluation at this point has been rejected by the user. - /** - \return A boolean equal to \c true if the evaluation has been rejected by the user. - */ - bool check_rejected ( void ) const { return (_eval_status == NOMAD::EVAL_USER_REJECT); } - - - /// Access to the tag of the point. - /** - \return The tag. - */ - int get_tag ( void ) const { return _tag; } - - /// Access to the bbe of the point. - /** - \return The bbe. - */ - int get_bbe ( void ) const { return _bbe; } - - /// Access to the bbe of the point. - /** - \return The sgte_bbe. - */ - int get_sgte_bbe ( void ) const { return _sgte_bbe; } - - - /// Access to the real time of the point evaluation. - /** - \return The real time. - */ - int get_real_time( void ) const { return _real_time; } - - - /// Access to the objective value \c f. - /** - \return The objective value. - */ - const NOMAD::Double & get_f ( void ) const { return _f; } - - /// Access to the feasibility value \c h. - /** - \return The feasibility value. - */ - const NOMAD::Double & get_h ( void ) const { return _h; } - - /// Access to the blackbox outputs. - /** - \return The \c m blackblack outputs. - */ - const NOMAD::Point & get_bb_outputs ( void ) const { return _bb_outputs; } - - /// Access to the direction used to construct the point. - /** - \return The direction used to construct the point; - may be \c NULL if no direction has been used. - */ - const NOMAD::Direction * get_direction ( void ) const { return _direction; } - - /// Access to the poll_center used to construct the point. - /** - \return The poll center used to construct the point; - may be \c NULL if no poll center has been used. - */ - const NOMAD::Eval_Point * get_poll_center ( void ) const { return _poll_center ; } - - - /// Check if the point has been generated during the current run. - /** - \return A boolean equal to \c true if the point has been - generated during the current run. - */ - bool get_current_run ( void ) const { return _current_run; } - - /// Check if the point is in cache. - /** - \return A boolean equal to \c true if the point is in cache. - */ - bool is_in_cache ( void ) const { return _in_cache; } - - /// Check if the point respects the EB constraints. - /** - \return A boolean equal to \c true if the point respects the EB constraints. - */ - bool is_EB_ok ( void ) const { return _EB_ok; } - - /// Access to the evaluation type. - /** - \return The evaluation type (true or surrogate). - */ - NOMAD::eval_type get_eval_type ( void ) const { return _eval_type; } - - /// Access to the poll center type. - /** - \return The poll center type (feasible or not). - */ - NOMAD::poll_center_type get_poll_center_type ( void ) const - { - return _poll_center_type; - } - - /// Access to the evaluation status. - /** - \return The evaluation status - (evaluation failed, succeeded, or is in progress). - */ - NOMAD::eval_status_type get_eval_status ( void ) const { return _eval_status; } - - /// Access to the user evaluation priority. - /** - \return The user evaluation priority. - */ - const NOMAD::Double & get_user_eval_priority ( void ) const - { - return _user_eval_priority; - } - - /// Access to the random evaluation priority. - /** - \return The random evaluation priority. - */ - const NOMAD::Double & get_rand_eval_priority ( void ) const - { - return _rand_eval_priority; - } - - /// Check the point feasibility. - /** - The point is feasible if \c h \c <= \c h_min. - \param h_min Feasibility threshold -- \b IN. - \return A boolean equal to \c true if the point is feasible. - */ - bool is_feasible ( const NOMAD::Double & h_min ) const - { - return ( _h.is_defined() && _h <= h_min ); - } - - /// Scaling. - void scale ( void ); - - /// Unscaling. - void unscale ( void ); - - /// Snap to bounds. - /** - \return A boolean equal to \c true if the snapping went well. - */ - bool snap_to_bounds ( void ); - - /// Treat the periodic variables. - /** - \param new_dir A pointer to the modified direction used to generate - this point from the poll center; may be \c NULL if no - direction has been used -- \b OUT. - \return A boolean equal to \c true if the treatment went well. - */ - bool treat_periodic_variables ( NOMAD::Direction *& new_dir ); - - /// Comparison operator. - /** - \param x Right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c x . - */ - bool operator < ( const Eval_Point & x ) const; - - /*---------------*/ - /* SET methods */ - /*---------------*/ - - /// Set the \c n and \c m. - /** - \param n Number of variables -- \b IN. - \param m Number of blackbox outputs -- \b IN. - */ - void set ( int n , int m ); - - /// Set the coordinates and \c m. - /** - \param x Coordinates of the point -- \b IN. - \param m Number of blackbox outputs -- \b IN. - */ - void set ( const NOMAD::Point & x , int m ); - - /// Set the tag. - /** - \param tag The tag -- \b IN. - */ - void set_tag ( int tag ); - - /// Set the real time. - /** - \param real_time The real time -- \b IN. - */ - void set_real_time ( int real_time ){_real_time=real_time;} - - /// increment sgte_bbe. - /** - */ - void increment_sgte_bbe (void); - - /// increment bbe. - /** - */ - void increment_bbe (void); - - /// Set the blackbox evaluation number. - /** - \param bbe the evaluation number - */ - void set_bbe (int bbe){_bbe=bbe;} - - /// Set the objective value \c f. - /** - \param f Objective value -- \b IN. - */ - void set_f ( const NOMAD::Double & f ) { _f = f; } - - /// Set the feasibility value \c h. - /** - \param h Feasibility value -- \b IN. - */ - void set_h ( const NOMAD::Double & h ) { _h = h; } - - /// Set the user evaluation priority. - /** - \param u User evaluation priority -- \b IN. - */ - void set_user_eval_priority ( const NOMAD::Double & u ) { _user_eval_priority = u; } - - /// Set the random evaluation priority. - /** - \param r Random evaluation priority -- \b IN. - */ - void set_rand_eval_priority ( const NOMAD::Double & r ) { _rand_eval_priority = r; } - - /// Set one blackbox output. - /** - \param i Index of the output to set -- \b IN. - \param v Value of the output -- \b IN. - */ - void set_bb_output ( int i , const NOMAD::Double & v ) { _bb_outputs[i]= v; } - - /// Set all blackbox outputs. - /** - \param b The \c m blackbox outputs -- \b IN. - */ - void set_bb_output ( const NOMAD::Point & b ) { _bb_outputs = b; } - - /// Set the evaluation status. - /** - \param e Evaluation status (failed, succeeded, or in progress) - -- \b IN. - */ - void set_eval_status ( const NOMAD::eval_status_type & e ) { _eval_status = e; } - - /// Set if the point respects the EB constraints. - /** - \param e A boolean equal to \c true if the point - respects the EB constraints. - */ - void set_EB_ok ( bool e ) { _EB_ok = e; } - - /// Set the evaluation type. - /** - \param e Evaluation type (true or surrogate) -- \b IN. - */ - void set_eval_type ( NOMAD::eval_type e ) { _eval_type = e; } - - /// Set the type of the poll center. - /** - \param p Type of the poll center (feasible or not) -- \b IN. - */ - void set_poll_center_type ( NOMAD::poll_center_type p ) { _poll_center_type = p; } - - /// Indicate if the point has been generated during the current run. - /** - \param c A boolean equal to \c true if the point - has been generated during the current run -- \b IN. - */ - void set_current_run ( bool c ) const { _current_run = c; } - - /// Indicate if the point is in cache. - /** - \param i A boolean equal to \c true if the point is in cache - -- \b IN. - */ - void set_in_cache ( bool i ) const { _in_cache = i; } - - - /// Set the direction used to create the point. - /** - \param d A pointer to the direction; may be \c NULL -- \b IN. - */ - void set_direction ( const NOMAD::Direction * d ); - - - /// Set the poll center used to create the point. - /** - \param d A pointer to the poll center; may be \c NULL -- \b IN. - */ - void set_poll_center ( const NOMAD::Eval_Point * d ); - - /// Set the signature. - /** - \param s A pointer to the signature -- \b IN. - */ - void set_signature ( NOMAD::Signature * s ); - - /// Check if there are nan's in the blackbox outputs: - /** - \return \c true if there is at least a nan. - */ - bool check_nan ( void ) const; - - - /// Reset the tags and bbes - /** - */ - static void reset_tags_and_bbes ( void ) {_current_tag = 0;_current_bbe = 0;_current_sgte_bbe = 0;} - -#ifdef MODEL_STATS - - private: - - mutable int _mod_use; // 1: model search; 2: model eval sort - mutable int _nY; - mutable NOMAD::Double _cond , _Yw , _mh , _mf; - - public: - - void set_mod_use ( int mod_use ) const { _mod_use = mod_use; } - void set_nY ( int nY ) const { _nY = nY; } - void set_cond ( const NOMAD::Double & cond ) const { _cond = cond; } - void set_Yw ( const NOMAD::Double & Yw ) const { _Yw = Yw; } - void set_mh ( const NOMAD::Double & mh ) const { _mh = mh; } - void set_mf ( const NOMAD::Double & mf ) const { _mf = mf; } - - int get_mod_use ( void ) const { return _mod_use; } - int get_nY ( void ) const { return _nY; } - const NOMAD::Double & get_cond ( void ) const { return _cond; } - const NOMAD::Double & get_Yw ( void ) const { return _Yw; } - const NOMAD::Double & get_mh ( void ) const { return _mh; } - const NOMAD::Double & get_mf ( void ) const { return _mf; } - - void set_model_data ( const NOMAD::Eval_Point & x ) const; - void clear_model_data ( void ) const; - -#endif - - /// Display the tag of the point. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display_tag ( const NOMAD::Display & out ) const; - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - \param in_block If \c true, the point is displayed into an indented block - -- \b IN -- \b optional (default = \c true ). - */ - virtual void display_eval ( const NOMAD::Display & out , bool in_block = true ) const; - }; - - /// Display a NOMAD::Eval_Point object. - /** - \param out The NOMAD::Display object -- \b IN. - \param x The NOMAD::Eval_Point object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Eval_Point & x ) - { - x.display_eval (out , true ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator.cpp deleted file mode 100644 index 7fa52836a..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator.cpp +++ /dev/null @@ -1,829 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Evaluator.cpp - \brief Evaluation of blackbox functions (implementation) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Evaluator.hpp - */ -#include "Evaluator.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -bool NOMAD::Evaluator::_force_quit = false; - -/*-----------------------------------------------------------------*/ -/* constructor */ -/*-----------------------------------------------------------------*/ -/* Parameters::_bb_exe is used to construct _bb_exe and _bb_nbo: */ -/* Parameters::_bb_exe can have similar blackbox names, while */ -/* . _bb_exe will have unique blackbox names */ -/* . _bb_exe includes the blackbox path */ -/*-----------------------------------------------------------------*/ -NOMAD::Evaluator::Evaluator ( const NOMAD::Parameters & p ) -: _p ( p ) , -_is_multi_obj ( false ) , -_is_model_evaluator ( false ) -{ - NOMAD::Evaluator::_force_quit = false; - - if ( _p.get_bb_exe().empty() ) - return; - - // _bbe_exe and _bb_nbo construction: - std::list::const_iterator it = _p.get_bb_exe().begin(); - _bb_exe.push_back(*it); - _bb_nbo.push_back(1); - ++it; - - std::list::const_iterator end = _p.get_bb_exe().end(); - while ( it != end ) - { - if ( *it != _bb_exe[_bb_exe.size()-1] ) - { - _bb_exe.push_back(*it); - _bb_nbo.push_back(1); - } - else - ++_bb_nbo[_bb_exe.size()-1]; - ++it; - } - - // we check that _bb_exe contains unique names and we add the problem path: - size_t k , l , n = _bb_exe.size() , nm1 = n-1; - for ( k = 0 ; k < nm1 ; ++k ) - { - for ( l = k+1 ; l < n ; ++l ) - if ( _bb_exe[k] == _bb_exe[l] ) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "problem with executable names" ); - } - - // construction of _sgte_exe: - bool has_sgte_exe = _p.has_sgte_exe(); - std::string err; - if ( has_sgte_exe ) - { - for ( k = 0 ; k < n ; ++k ) - { - - _sgte_exe.push_back ( _p.get_sgte_exe(_bb_exe[k]) ); - - if ( _sgte_exe[_sgte_exe.size()-1].empty() ) - { - err = "blackbox executable \'" + _bb_exe[k] + "\' has no surrogate"; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err ); - } - } - } - - // process blakc-box executables (check and add problem path): - for ( k = 0 ; k < n ; ++k ) - { - process_bb_exe_name ( _bb_exe[k] ); - if ( has_sgte_exe ) - process_bb_exe_name ( _sgte_exe[k] ); - } - - // blackbox names and indexes display: -#ifdef DEBUG -#ifdef USE_MPI - int rank; - MPI_Comm_rank ( MPI_COMM_WORLD, &rank); - if ( rank == 0 ) - { -#else - { -#endif - const NOMAD::Display & out = _p.out(); - if ( !_bb_exe.empty() ) - { - out << std::endl - << NOMAD::open_block ( "blackbox executables" ); - for ( k = 0 ; k < n ; ++k ) - { - out << NOMAD::open_block ( "bb #" + NOMAD::itos(k) ) - << _bb_exe[k] << std::endl - << "number of outputs=" << _bb_nbo[k] << std::endl - << NOMAD::close_block(); - } - out.close_block(); - } - if ( !_sgte_exe.empty() ) - { - out << std::endl - << NOMAD::open_block ( "surrogate executables" ); - for ( k = 0 ; k < n ; ++k ) - out << "sgte #" << static_cast(k) << ": " - << _sgte_exe[k] << std::endl; - out.close_block(); - } - } -#endif - } - - /*----------------------------------------------------------------*/ - /* process a blackbox executable name (private) */ - /*----------------------------------------------------------------*/ - void NOMAD::Evaluator::process_bb_exe_name ( std::string & bb_exe ) const - { - std::string err; - std::list bb_exe_words; - - NOMAD::get_words ( bb_exe , bb_exe_words ); - - if ( bb_exe_words.empty() ) - { - err = "problem with executable \'" + bb_exe + "\'"; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err ); - } - - std::string problem_dir = _p.get_problem_dir(); - - // bb_exe is composed of several words (it is a command): - if ( bb_exe_words.size() > 1 ) - { - - bb_exe.clear(); - - std::list::const_iterator it = bb_exe_words.begin() , - end = bb_exe_words.end(); - while (true) - { - - if ( (*it)[0] != '$' ) - { - bb_exe += "\"" + problem_dir; - bb_exe += *it + "\""; - } - else - bb_exe += it->substr ( 1 , it->size()-1 ); - - ++it; - - if ( it == end ) - break; - - bb_exe += " "; - } - } - - // bb_exe is just composed of one name (it is an executable): - else { - if ( bb_exe[0] != '$' ) - bb_exe = problem_dir + bb_exe; - else - bb_exe = bb_exe.substr ( 1 , bb_exe.size()-1 ); - if ( !NOMAD::check_exe_file ( bb_exe ) ) - { - err = "\'" + bb_exe + "\' is not a valid executable file"; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err ); - } - if ( bb_exe[0] != '$' ) - bb_exe = "\"" + bb_exe + "\""; - } - } - - /*-----------------------------------------------------------------------*/ - /* check the constraints to decide if an evaluation have to be stopped */ - /*-----------------------------------------------------------------------*/ - /* . checked when h > h_max or if a 'EB' constraint is violated */ - /* . private method */ - /*-----------------------------------------------------------------------*/ - bool NOMAD::Evaluator::interrupt_evaluations ( const NOMAD::Eval_Point & x , - const NOMAD::Double & h_max ) const - { - int nbo = _p.get_bb_nb_outputs(); - const NOMAD::Point & bbo = x.get_bb_outputs(); - const std::vector & bbot = _p.get_bb_output_type(); - NOMAD::Double h = 0.0; - bool check_h = h_max.is_defined(); - - for ( int i = 0 ; i < nbo ; ++i ) { - - if ( bbo[i].is_defined() && - ( bbot[i] == NOMAD::EB || bbot[i] == NOMAD::PEB_E ) && - bbo[i] > _p.get_h_min() ) - return true; - - if ( check_h && bbo[i].is_defined() && - (bbot[i] == NOMAD::FILTER || - bbot[i] == NOMAD::PB || - bbot[i] == NOMAD::PEB_P ) ) { - - if ( bbo[i] > _p.get_h_min() ) { - switch ( _p.get_h_norm() ) { - case NOMAD::L1: - h += bbo[i]; - break; - case NOMAD::L2: - h += bbo[i].pow2(); - break; - case NOMAD::LINF: - if ( bbo[i] > h ) - h = bbo[i]; - break; - } - - if ( _p.get_h_norm() == NOMAD::L2 ) { - if ( h > h_max.pow2() ) - return true; - } - else if ( h > h_max ) - return true; - } - } - } - return false; - } - - /*--------------------------------------------------------*/ - /* compute f(x) from the blackbox outputs of a point */ - /* (define a Multi_Obj_Evaluator to treat more than */ - /* one objective) */ - /*--------------------------------------------------------*/ - void NOMAD::Evaluator::compute_f ( NOMAD::Eval_Point & x ) const - { - if ( x.get_bb_outputs().size() != _p.get_bb_nb_outputs() ) { - std::ostringstream err; - err << "Evaluator::compute_f(x): x has a wrong number of blackbox outputs (" - << x.get_bb_outputs().size() << " != " - << _p.get_bb_nb_outputs() << ")"; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err.str() ); - } - - x.set_f ( x.get_bb_outputs()[*(_p.get_index_obj().begin())] ); - } - - /*--------------------------------------------------------*/ - /* compute h(x) from the blackbox outputs of a point */ - /* set also the flag 'EB_ok' of the point */ - /*--------------------------------------------------------*/ - void NOMAD::Evaluator::compute_h ( NOMAD::Eval_Point & x ) const - { - if ( x.get_bb_outputs().size() != _p.get_bb_nb_outputs() ) - { - std::ostringstream err; - err << "Evaluator::compute_h(x): x has a wrong number of blackbox outputs (" - << x.get_bb_outputs().size() << " != " - << _p.get_bb_nb_outputs() << ")"; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err.str() ); - } - - int nbo = _p.get_bb_nb_outputs(); - const std::vector & bbot = _p.get_bb_output_type(); - const NOMAD::Point & bbo = x.get_bb_outputs(); - NOMAD::Double h = 0.0 , bboi; - - x.set_EB_ok ( true ); - - for ( int i = 0 ; i < nbo ; ++i ) - { - - bboi = bbo[i]; - - if ( bboi.is_defined() && - (bbot[i] == NOMAD::EB || bbot[i] == NOMAD::PEB_E ) && - bboi > _p.get_h_min() ) - { - h.clear(); - x.set_h ( h ); - x.set_EB_ok ( false ); - return; - } - - if ( bboi.is_defined() && - ( bbot[i] == NOMAD::FILTER || - bbot[i] == NOMAD::PB || - bbot[i] == NOMAD::PEB_P ) ) - { - if ( bboi > _p.get_h_min() ) - { - switch ( _p.get_h_norm() ) - { - case NOMAD::L1: - h += bboi; - break; - case NOMAD::L2: - h += bboi * bboi; - break; - case NOMAD::LINF: - if ( bboi > h ) - h = bboi; - break; - } - } - } - } - - if ( _p.get_h_norm() == NOMAD::L2 ) - h = h.sqrt(); - - x.set_h ( h ); - } - - /*-------------------------------------------------------------------*/ - /* . evaluate the black boxes at a given Eval_Point */ - /* . the function returns true if the evaluation did not fail */ - /* . set count_eval=true to count the evaluation */ - /* (unless the output value CNT_EVAL is defined and set to 1 */ - /* by the blackbox) */ - /*-------------------------------------------------------------------*/ - bool NOMAD::Evaluator::eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const - { - count_eval = false; - - if ( _bb_exe.empty() || !x.is_complete() ) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "Evaluator: no BB_EXE is defined (blackbox executable names)" ); - - bool sgte = x.get_eval_type() == NOMAD::SGTE; - if ( sgte && _sgte_exe.empty() ) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "Evaluator: no SGTE_EXE is defined (surrogate executable names)" ); - - int pid = NOMAD::get_pid(); - int seed = _p.get_seed(); - std::string tmp_dir = _p.get_tmp_dir(); - - std::ostringstream oss; - oss << "." << seed; - if ( pid != seed ) - oss << "." << pid; - oss << "." << x.get_tag() << "."; - const std::string & sint = oss.str(); - - // for the parallel version: no need to include the process rank in the names - // as the point tags are unique for all the processes: each process creates - // its own points and uses Eval_Point::set_tag() - - // blackbox input file writing: - // ---------------------------- - std::string bb_input_file_name = - tmp_dir + NOMAD::BLACKBOX_INPUT_FILE_PREFIX - + sint + NOMAD::BLACKBOX_INPUT_FILE_EXT; - - std::string bb_output_file_name = - tmp_dir + NOMAD::BLACKBOX_OUTPUT_FILE_PREFIX - + sint + NOMAD::BLACKBOX_OUTPUT_FILE_EXT; - - std::ofstream fout ( bb_input_file_name.c_str() ); - if ( fout.fail() ) - { - std::string err = "could not create file blackbox input file " + bb_input_file_name + ". \n \n #### Please check that write permission are granted for the working directory. #### "; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err ); - } - - // include seed: - if ( _p.get_bb_input_include_seed() ) - fout << seed << " "; - - // include tag: - if ( _p.get_bb_input_include_tag() ) - fout << x.get_tag() << " "; - - fout.setf ( std::ios::fixed ); - fout.precision ( NOMAD::DISPLAY_PRECISION_BB ); - x.Point::display ( fout , " " , -1 , -1 ); - fout << std::endl; - - fout.close(); - - if ( fout.fail() ) - return false; - - x.set_eval_status ( NOMAD::EVAL_IN_PROGRESS ); - - std::string cmd , bb_exe; - std::ifstream fin; - bool failed; - NOMAD::Double d; - int j , nbbok; - int ibbo = 0; - - // system call to evaluate the blackbox: - // ------------------------------------- - size_t bn = _bb_exe.size(); - for ( size_t k = 0 ; k < bn ; ++k ) - { - - // executable name: - bb_exe = ( sgte ) ? _sgte_exe[k] : _bb_exe[k]; - - // system command: - cmd = bb_exe + " " + bb_input_file_name; - - // redirection ? if no, the blackbox has to create - // the output file 'bb_output_file_name': - if ( _p.get_bb_redirection() ) - cmd += " > " + bb_output_file_name; - -#ifdef DEBUG -#ifdef USE_MPI - int rank; - MPI_Comm_rank ( MPI_COMM_WORLD, &rank); - _p.out() << "command(rank=" << rank - << ") = \'" << cmd << "\'" << std::endl; -#else - _p.out() << "command=\'" << cmd << "\'" << std::endl; -#endif -#endif - - // the evaluation: - { - int signal = system ( cmd.c_str() ); - - // catch the ctrl-c signal: - if ( signal == SIGINT ) - raise ( SIGINT ); - - // other evaluation error: - failed = ( signal != 0 ); - count_eval = true; - } - - // the evaluation failed (we stop the evaluations): - if ( failed ) - { - x.set_eval_status ( NOMAD::EVAL_FAIL ); - break; - } - - // reading of the blackbox output file: - // ------------------------------------ - else - { - - // bb-output file reading: - fin.open ( bb_output_file_name.c_str() ); - - failed = false; - bool is_defined = true; - bool is_inf = false; - - // loop on the number of outputs for this blackbox: - nbbok = _bb_nbo[k]; - for ( j = 0 ; j < nbbok ; ++j ) - { - - fin >> d; - - if ( !d.is_defined() ) - { - is_defined = false; - break; - } - - if ( fin.fail() ) - { - failed = true; - break; - } - - if ( d.value() >= NOMAD::INF ) - { - is_inf = true; - break; - } - - x.set_bb_output ( ibbo++ , d ); - } - - fin.close(); - - // the evaluation failed: - if ( failed || !is_defined || is_inf ) - { - x.set_eval_status ( NOMAD::EVAL_FAIL ); - break; - } - - // stop the evaluations if h > h_max or if a 'EB' constraint is violated: - if ( k < _bb_exe.size() - 1 && interrupt_evaluations ( x , h_max ) ) - break; - } - } - - if ( x.get_eval_status() == NOMAD::EVAL_IN_PROGRESS ) - x.set_eval_status ( NOMAD::EVAL_OK ); - - // delete the blackbox input and output files: - // ------------------------------------------- - remove ( bb_input_file_name.c_str () ); - remove ( bb_output_file_name.c_str() ); - - // check the CNT_EVAL output: - // -------------------------- - int index_cnt_eval = _p.get_index_cnt_eval(); - if ( index_cnt_eval >= 0 && x.get_bb_outputs()[index_cnt_eval] == 0.0 ) - count_eval = false; - - return x.is_eval_ok(); - } - - - /*-------------------------------------------------------------------*/ - /* . evaluate the black boxes at a list of given Eval_Points */ - /*-------------------------------------------------------------------*/ - bool NOMAD::Evaluator::eval_x ( std::list & list_eval, - const NOMAD::Double & h_max , - std::list & list_count_eval) const - { - - std::list::iterator it; - std::list::iterator it_begin=list_eval.begin(); - std::list::iterator it_end=list_eval.end(); - std::list::iterator it_count=list_count_eval.begin(); - - if ( list_eval.size() !=list_count_eval.size()) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "Evaluator: inconsistent size of list" ); - - if ( _bb_exe.empty()) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "Evaluator: no BB_EXE is defined (blackbox executable names)" ); - - bool sgte = ((*it_begin)->get_eval_type() == NOMAD::SGTE); - if ( sgte && _sgte_exe.empty() ) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "Evaluator: no SGTE_EXE is defined (surrogate executable names)" ); - - - - int pid = NOMAD::get_pid(); - int seed = _p.get_seed(); - std::string tmp_dir = _p.get_tmp_dir(); - - std::ostringstream oss; - oss << "." << seed; - if ( pid != seed ) - oss << "." << pid; - - for (it=it_begin;it!=it_end;++it) - { - if (!(*it)->is_complete() ) - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , - "Evaluator: points provided for evaluations are incomplete " ); - - } - // add the tag of the first point - oss << "." << (*it_begin)->get_tag(); - - oss << "." ; - const std::string & sint = oss.str(); - - // for the parallel version: no need to include the process rank in the names - // as the point tags are unique for all the processes: each process creates - // its own points and uses Eval_Point::set_tag() - - // blackbox input file writing: - // ---------------------------- - std::string bb_input_file_name = - tmp_dir + NOMAD::BLACKBOX_INPUT_FILE_PREFIX - + sint + NOMAD::BLACKBOX_INPUT_FILE_EXT; - - std::string bb_output_file_name = - tmp_dir + NOMAD::BLACKBOX_OUTPUT_FILE_PREFIX - + sint + NOMAD::BLACKBOX_OUTPUT_FILE_EXT; - - std::ofstream fout ( bb_input_file_name.c_str() ); - if ( fout.fail() ) { - std::string err = "could not open file blackbox input file " + bb_input_file_name; - throw NOMAD::Exception ( "Evaluator.cpp" , __LINE__ , err ); - } - - - for (it=it_begin;it!=it_end;++it) - { - // include seed: - if ( _p.get_bb_input_include_seed() ) - fout << seed << " "; - - // include tag: - if ( _p.get_bb_input_include_tag() ) - fout << (*it)->get_tag() << " "; - - fout.setf ( std::ios::fixed ); - fout.precision ( NOMAD::DISPLAY_PRECISION_BB ); - (*it)->Point::display ( fout , " " , -1 , -1 ); - fout << std::endl; - } - - fout.close(); - - if ( fout.fail() ) - return false; - - for (it=it_begin;it!=it_end;++it) - (*it)->set_eval_status ( NOMAD::EVAL_IN_PROGRESS ); - - - std::string cmd , bb_exe; - std::ifstream fin; - bool failed; - NOMAD::Double d; - int j , nbbok; - int ibbo = 0; - - // system call to evaluate the blackboxes: - // ------------------------------------- - size_t bn = _bb_exe.size(); - for ( size_t k = 0 ; k < bn ; ++k ) - { - - // executable name: - bb_exe = ( sgte ) ? _sgte_exe[k] : _bb_exe[k]; - - // system command: - cmd = bb_exe + " " + bb_input_file_name; - - // redirection ? if no, the blackbox has to create - // the output file 'bb_output_file_name': - if ( _p.get_bb_redirection() ) - cmd += " > " + bb_output_file_name; - - - // the evaluation: - { - int signal = system ( cmd.c_str() ); - - // catch the ctrl-c signal: - if ( signal == SIGINT ) - raise ( SIGINT ); - - // other evaluation error: - failed = ( signal != 0 ); - } - - // the evaluation failed (we stop the evaluations): - if ( failed ) - { - it_count=list_count_eval.begin(); - for (it=it_begin;it!=it_end;++it,++it_count) - { - (*it)->set_eval_status ( NOMAD::EVAL_FAIL ); - (*it_count)=true; // - } - break; - } - - // reading of the blackbox output file: - // ------------------------------------ - else - { - - // bb-output file reading: - fin.open ( bb_output_file_name.c_str() ); - - string s; - bool is_defined,is_inf; - - bool list_all_failed_eval=true; - bool list_all_interrupt=true; - - // loop on the points - it_count=list_count_eval.begin(); - for (it=it_begin;it!=it_end;++it,++it_count) - { - failed = false; - is_defined = true; - is_inf = false; - - // loop on the number of outputs for this blackbox: - nbbok = _bb_nbo[k]; - ibbo=0; - for ( j = 0 ; j < nbbok ; ++j ) - { - - fin >> s; - - if ( fin.fail() ) - { - failed = true; - break; - } - - toupper(s); - if (s.compare("REJECT")==0) - { - *it_count=false; // Rejected points are not counted - (*it)->set_eval_status(NOMAD::EVAL_USER_REJECT); - break; - } - else - { - d.atof(s); - (*it_count)=true; - } - // - - if (s.compare("FAIL")==0) - { - failed = true; - break; - } - - - if ( !d.is_defined() ) - { - is_defined = false; - break; - } - - - if ( d.value() >= NOMAD::INF ) { - is_inf = true; - break; - } - - (*it)->set_bb_output ( ibbo++ , d ); - } - - - // the evaluation failed: - if ( failed || !is_defined || is_inf ) - { - (*it)->set_eval_status ( NOMAD::EVAL_FAIL ); - - } else - list_all_failed_eval=false; - - - // stop the evaluations if h > h_max or if a 'EB' constraint is violated: - if ( !( k < _bb_exe.size() - 1 && interrupt_evaluations ( *(*it) , h_max ) && list_all_interrupt )) - list_all_interrupt=false; - } - - fin.close(); - - if (list_all_failed_eval || list_all_interrupt) - break; - - } - } - - - // delete the blackbox input and output files: - // ------------------------------------------- - remove ( bb_input_file_name.c_str () ); - remove ( bb_output_file_name.c_str() ); - - bool at_least_one_eval_ok=false; - int index_cnt_eval = _p.get_index_cnt_eval(); - - - // update eval status and check that at least one was ok - it_count=list_count_eval.begin(); - for (it=it_begin;it!=it_end;++it,++it_count) - { - if ( (*it)->get_eval_status() == NOMAD::EVAL_IN_PROGRESS ) - (*it)->set_eval_status ( NOMAD::EVAL_OK ); - - if (!at_least_one_eval_ok && (*it)->is_eval_ok()) - at_least_one_eval_ok=true; - - // count_eval from bb_outputs: - // -------------------------- - if ( index_cnt_eval >= 0 && (*it)->get_bb_outputs()[index_cnt_eval]==0) - *it_count=false; - } - - return at_least_one_eval_ok; - } diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator.hpp deleted file mode 100644 index 53e1480b4..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator.hpp +++ /dev/null @@ -1,283 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Evaluator.hpp - \brief Evaluation of blackbox functions (headers) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Evaluator.cpp - */ -#ifndef __EVALUATOR__ -#define __EVALUATOR__ - -#include -#include "Priority_Eval_Point.hpp" -#include "Stats.hpp" -#include - -namespace NOMAD { - - // forward declarations: - class Barrier; - class Pareto_Front; - class Evaluator_Control; - - /// Evaluation of blackbox functions. - /** - This class allows the evaluation of one trial point. - */ - class Evaluator : private NOMAD::Uncopyable { - - protected: - - /// Parameters. - const NOMAD::Parameters & _p; - - /// Multi-objective flag. - /** - Identifies if a NOMAD::Evaluator object refers to - a NOMAD::Multi_Obj_Evaluator for more than one - objective function. - */ - bool _is_multi_obj; - - /// Model flag. - /** - Identifies if a NOMAD::Evaluator object refers to - a NOMAD::***_Model_Evaluator - */ - bool _is_model_evaluator; - - private: - - /// Blackbox executable names. - /** - - Not the same as Parameters::_bb_exe. - - NOMAD::Evaluator::_bb_exe is constructed from - NOMAD::Parameters::_bb_exe. - */ - std::vector _bb_exe; - - std::vector _sgte_exe; ///< Surrogate executable names. - - /// Number of outputs for each blackbox executable. - std::vector _bb_nbo; - - static bool _force_quit; ///< Flag equal to \c true if ctrl-c is pressed. - - /// Check the constraints to decide if the evaluations have to be stopped. - /** - \param x Point at which the constraints are checked -- \b IN. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \return A boolean equal to \c true if - the evaluations have to be stopped. - */ - bool interrupt_evaluations ( const NOMAD::Eval_Point & x , - const NOMAD::Double & h_max ) const; - - /// Process a blackbox executable name. - /** - \param bb_exe Executable name -- \b IN/OUT. - */ - void process_bb_exe_name ( std::string & bb_exe ) const; - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Evaluator ( const NOMAD::Parameters & p ); - - /// Destructor. - virtual ~Evaluator ( void ) {} - - /// Force quit (called by pressing ctrl-c). - static void force_quit ( void ) - { - NOMAD::Evaluator::_force_quit = true; - } - - /// Access to the \c force_quit flag. - /** - \return The \c force_quit flag. - */ - static bool get_force_quit ( void ) - { - return NOMAD::Evaluator::_force_quit; - } - - /// Access to the multi-objective flag. - /** - \return The multi-objective flag. - */ - bool is_multi_obj ( void ) const - { - return _is_multi_obj; - } - - /// Access to the model evaluator flag. - /** - \return The model evaluator flag. - */ - virtual bool is_model_evaluator ( void ) const - { - return _is_model_evaluator; - } - - /// User pre-processing of a list of points. - /** - - This virtual method is called before the evaluation of a list - of points. - - It allows the user to pre-process the points to be evaluated. - \param pts The list of points -- \b IN/OUT. - */ - virtual void list_of_points_preprocessing - ( std::set & pts ) const {} - - /// User updates after a success. - /** - This virtual method is called every time a new (full) success is made. - \param stats Stats -- \b IN. - \param x Last successful point -- \b IN. - */ - virtual void update_success ( const NOMAD::Stats & stats , - const NOMAD::Eval_Point & x ) {} - - /// User updates after an iteration. - /** - This virtual method is called every time a MADS iteration is terminated. - \param success Success of the iteration -- \b IN. - \param stats Stats -- \b IN. - \param ev_control The NOMAD::Evaluator_Control object -- \b IN. - \param true_barrier Barrier for true evaluations -- \b IN. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN. - \param pareto_front Pareto front -- \b IN. - \param stop Allows the user to stop the algorithm -- \b OUT. - */ - virtual void update_iteration ( NOMAD::success_type success , - const NOMAD::Stats & stats , - const NOMAD::Evaluator_Control & ev_control , - const NOMAD::Barrier & true_barrier , - const NOMAD::Barrier & sgte_barrier , - const NOMAD::Pareto_Front & pareto_front , - bool & stop ) {} - - /// Evaluate the blackbox functions at a given trial point (#1). - /** - - Const version. - - May be user-defined. - - Surrogate or true evaluation depending on the value of \c x.is_surrogate(). - \param x The trial point -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const; - - /// Evaluate the blackbox functions at a given trial point (#2). - /** - - Non-const version. - - Calls the const version by default. - - May be user-defined. - - Surrogate or true evaluation depending on the value of \c x.is_surrogate(). - \param x The trial point -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) - { - return static_cast(this)->eval_x ( x , h_max , count_eval ); - } - - - - /// Evaluate the blackbox functions at a given list of trial points (#1). - /** - - Const version. - - May be user-defined. - - Surrogate or true evaluation depending on the value of \c x.is_surrogate(). - \param x The list of trial points -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Number of evaluations that are counted -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( std::list &x , - const NOMAD::Double & h_max, - std::list & count_eval ) const; - - - /// Evaluate the blackbox functions at a given list of trial points (#2). - /** - - Non-Const version. - - May be user-defined. - - Surrogate or true evaluation depending on the value of \c x.is_surrogate(). - \param x The list of trial points -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Number of evaluations that are counted -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( std::list &x , - const NOMAD::Double & h_max, - std::list & count_eval ) - { - return static_cast(this)->eval_x ( x , h_max , count_eval ); - } - - - - /// Compute the objective value \c f(x) from the blackbox outputs of a point. - /** - \param x The point -- \b IN/OUT. - */ - virtual void compute_f ( NOMAD::Eval_Point & x ) const; - - /// Compute the feasibility value \c h(x) from the blackbox outputs of a point. - /** - \param x The point -- \b IN/OUT. - */ - void compute_h ( NOMAD::Eval_Point & x ) const; - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator_Control.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator_Control.cpp deleted file mode 100644 index b89bd78da..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator_Control.cpp +++ /dev/null @@ -1,3868 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Evaluator_Control.cpp - \brief Control of the blackbox evaluations (implementation) - \author Sebastien Le Digabel - \date 2010-04-15 - \see Evaluator_Control.hpp - */ -#include "Evaluator_Control.hpp" -#include "Multi_Obj_Quad_Model_Evaluator.hpp" -#include "Single_Obj_Quad_Model_Evaluator.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -bool NOMAD::Evaluator_Control::_force_quit = false; -bool NOMAD::Evaluator_Control::_force_evaluation_failure = false; - - -/*---------------------------------------------------------*/ -/* constructor */ -/*---------------------------------------------------------*/ -NOMAD::Evaluator_Control::Evaluator_Control -( const NOMAD::Parameters & p , - NOMAD::Stats & stats , - NOMAD::Evaluator * ev , // can be NULL - NOMAD::Cache * cache , // can be NULL - NOMAD::Cache * sgte_cache ) // can be NULL -: _p ( p ) , -_ev ( ev ) , -_cache ( cache ) , -_sgte_cache ( sgte_cache ) , -_model_eval_sort ( true ) , -_del_ev ( false ) , -_del_cache ( false ) , -_del_sgte_cache ( false ) , -#ifdef USE_MPI -_eval_in_progress ( NULL ) , -_nb_in_progress ( 0 ) , -_elop_tag ( 0 ) , -_slaves_elop_tags ( NULL ) , -_slave ( NULL ) , -#endif -#ifdef USE_TGP -_last_TGP_model ( NULL ) , -#endif -_stats ( stats ) , -_last_stats_tag ( -1 ) , -_last_stats_bbe ( -1 ) , -_last_history_bbe ( -1 ) -{ - NOMAD::Evaluator_Control::_force_quit = false; - - // Evaluator init: - if ( !_ev ) { - _ev = ( _p.get_index_obj().size() > 1 ) ? new NOMAD::Multi_Obj_Evaluator ( p ): - new NOMAD::Evaluator ( p ); - _del_ev = true; - } - - if ( NOMAD::Slave::is_master() ) { - -#ifdef USE_MPI - - int np = NOMAD::Slave::get_nb_processes(); - - _eval_in_progress = new NOMAD::Eval_Point * [np]; - _slaves_elop_tags = new int [np]; - for ( int i = 0 ; i < np ; ++i ) { - _eval_in_progress[i] = NULL; - _slaves_elop_tags[i] = -1; - } - - _slave = new NOMAD::Slave ( _p , _ev ); - -#endif - - const NOMAD::Display & out = _p.out(); - - // caches creation: - if ( !_cache ) { - _cache = new NOMAD::Cache ( out , NOMAD::TRUTH ); - _del_cache = true; - } - if ( !_sgte_cache ) { - _sgte_cache = new NOMAD::Cache ( out , NOMAD::SGTE ); - _del_sgte_cache = true; - } - - // caches init (we only load cache file points with m blackbox outputs): - std::string file_name; - int m = p.get_bb_nb_outputs(); - NOMAD::dd_type display_degree = out.get_gen_dd(); - - if ( !_p.get_cache_file().empty() ) { - file_name = _p.get_problem_dir() + _p.get_cache_file(); - if ( !_cache->load ( file_name , &m , display_degree == NOMAD::FULL_DISPLAY ) - && display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl - << "Warning (" << "Evaluator_Control.cpp" << ", " << __LINE__ - << "): could not load (or create) the cache file " << file_name - << std::endl << std::endl; - } - - if ( !_p.get_sgte_cache_file().empty() ) { - file_name = _p.get_problem_dir() + _p.get_sgte_cache_file(); - if ( !_sgte_cache->load ( file_name , &m , display_degree==NOMAD::FULL_DISPLAY ) && - display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY ) - out << std::endl << "Warning (" << "Evaluator_Control.cpp" << ", " << __LINE__ - << "): could not load (or create) the surrogate cache file " - << file_name << std::endl << std::endl; - } - -#ifdef MODEL_STATS - if ( _p.has_model_search() || - ( _model_eval_sort && - _p.get_model_eval_sort() != NOMAD::NO_MODEL ) ) { - out << std::endl - << "MODEL_STATS is active. Displayed model stats are:" - << std::endl - << "mode ell nY wY cond"; - if ( _p.has_constraints() ) - out << " h mh eh"; - out << " f mf ef" << std::endl - << NOMAD::open_block() - << "mode: model search (1) or model ordering (2)" << std::endl - << "ell : mesh_index" << std::endl - << "nY : cardinality of the interpolation set Y" << std::endl - << "wY : width of Y" << std::endl - << "cond: Y condition number" << std::endl; - if ( _p.has_constraints() ) - out << "h : h value" << std::endl - << "mh : model value for h" << std::endl - << "eh : relative error(%)" << std::endl; - out << "f : f value" << std::endl - << "mf : model value for f" << std::endl - << "ef : relative error(%)" << std::endl - << NOMAD::close_block() << std::endl; - } -#endif - } -} - -/*---------------------------------------------------------*/ -/* destructor */ -/*---------------------------------------------------------*/ -NOMAD::Evaluator_Control::~Evaluator_Control ( void ) -{ - if ( _del_ev ) - delete _ev; - - if ( _del_cache ) - delete _cache; - - if ( _del_sgte_cache ) - delete _sgte_cache; - - clear_eval_lop(); - -#ifdef USE_MPI - - if ( _eval_in_progress ) { - int np = NOMAD::Slave::get_nb_processes(); - for ( int i = 0 ; i < np ; ++i ) - if ( _eval_in_progress[i] && !_eval_in_progress[i]->is_in_cache() ) - delete _eval_in_progress[i]; - delete [] _eval_in_progress; - } - if ( _slaves_elop_tags ) - delete [] _slaves_elop_tags; - - delete _slave; - -#endif -} - -/*---------------------------------------------------------*/ -/* reset */ -/*---------------------------------------------------------*/ -void NOMAD::Evaluator_Control::reset ( void ) -{ - _last_stats_tag = _last_stats_bbe = -1; -#ifdef USE_TGP - _last_TGP_model = NULL; -#endif -} - -/*---------------------------------------------------------*/ -/* save the caches */ -/*---------------------------------------------------------*/ -bool NOMAD::Evaluator_Control::save_caches ( bool overwrite ) -{ - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_gen_dd(); - - bool b1 = _cache->save ( overwrite , display_degree == NOMAD::FULL_DISPLAY ); - bool b2 = _sgte_cache->save ( overwrite , display_degree == NOMAD::FULL_DISPLAY ); - - if ( !b1 && display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl << "Warning (" << "Evaluator_Control.cpp" << ", " << __LINE__ - << "): could not save the cache file " - << _p.get_problem_dir() << _p.get_cache_file() - << std::endl << std::endl; - - if ( !b2 && display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl - << "Warning (" << "Evaluator_Control.cpp" << ", " << __LINE__ - << "): could not save the surrogate cache file " - << _p.get_problem_dir() << _p.get_sgte_cache_file() - << std::endl << std::endl; - return b1 && b2; -} - -/*---------------------------------------------------------*/ -/* process an already evaluated Eval_Point (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Evaluator_Control::process_eval_point -( const NOMAD::Eval_Point & x , - NOMAD::Barrier & barrier , - NOMAD::Pareto_Front * pareto_front ) const -{ - // insertion of the Eval_Point in the barriers: - barrier.insert(x); - - if ( x.get_eval_type() == NOMAD::TRUTH || _p.get_opt_only_sgte() ) - { - - // multi-objective: - if ( pareto_front ) - { - - // insertion of the Eval_Point in the Pareto front: - if ( x.is_feasible ( _p.get_h_min() ) && - pareto_front->insert ( x ) && - _p.get_user_calls_enabled() ) - _ev->update_success ( _stats , x ); - - } - - // single-objective: call virtual method Evaluator::update_success(): - else if ( _p.get_user_calls_enabled() && - barrier.get_one_eval_succ() == NOMAD::FULL_SUCCESS ) - _ev->update_success ( _stats , x ); - } -} - -/*---------------------------------------------------------*/ -/* update barrier b1 from points in barrier b2 and treat */ -/* these points as evaluations (used in VNS search) */ -/*---------------------------------------------------------*/ -NOMAD::success_type NOMAD::Evaluator_Control::process_barrier_points -( NOMAD::Barrier & b1 , - const NOMAD::Barrier & b2 , - NOMAD::Pareto_Front * pareto_front , - NOMAD::dd_type display_degree , - NOMAD::search_type search ) const -{ - b1.reset_success(); - - NOMAD::Eval_Point * modifiable_x; - NOMAD::success_type one_eval_succ; - const NOMAD::Eval_Point * last_success = NULL; - const std::list & all_inserted = b2.get_all_inserted(); - std::list::const_iterator it , end = all_inserted.end(); - for ( it = all_inserted.begin() ; it != end ; ++it ) - { - - // insertion in barrier: - modifiable_x = &NOMAD::Cache::get_modifiable_point ( **it ); - - modifiable_x->set_direction ( NULL ); - modifiable_x->set_poll_center_type ( NOMAD::UNDEFINED_POLL_CENTER_TYPE ); - modifiable_x->set_user_eval_priority ( NOMAD::Double() ); - modifiable_x->set_rand_eval_priority ( NOMAD::Double() ); - - // process evaluation point: - process_eval_point ( **it , b1 , pareto_front ); - - one_eval_succ = b1.get_one_eval_succ(); - if ( one_eval_succ != NOMAD::UNSUCCESSFUL && one_eval_succ >= b1.get_success() ) - last_success = *it; - - } - - NOMAD::success_type success = b1.get_success(); - - // display and save only the last success: - if ( last_success && display_degree == NOMAD::FULL_DISPLAY) - display_eval_result ( *last_success , - display_degree , - search , - success , - success ); - - // barrier update: - b1.update_and_reset_success(); - - return success; -} - -/*---------------------------------------------------------*/ -/* count the output stats (STAT_SUM and STAT_AVG) */ -/* (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Evaluator_Control::count_output_stats ( const NOMAD::Eval_Point & x ) -{ - const NOMAD::Point & bbo = x.get_bb_outputs(); - int i_sum = _p.get_index_stat_sum(); - int i_avg = _p.get_index_stat_avg(); - - // STAT_SUM: - if ( i_sum >= 0 ) - _stats.update_stat_sum ( bbo[i_sum] ); - - // STAT_AVG: - if ( i_avg >= 0 ) - _stats.update_stat_avg ( bbo[i_avg] ); -} - -/*-------------------------------------------------------------------*/ -/* file displays for parameter STATS_FILE */ -/*-------------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::stats_file ( const std::string & file_name , - const NOMAD::Eval_Point * x , - bool feasible , - const NOMAD::Point * multi_obj ) const -{ - std::string fn = _p.get_problem_dir() + file_name; - std::ofstream fout ( fn.c_str() , std::ios::app ); - - if ( !fout.fail() ) - { - fout.setf ( std::ios::fixed ); - fout.precision ( NOMAD::DISPLAY_PRECISION_BB ); - display_stats ( false , fout , _p.get_stats_file() , x , feasible , multi_obj ); - } - else - { - const NOMAD::Display & out = _p.out(); - if ( out.get_gen_dd() != NOMAD::NO_DISPLAY && out.get_gen_dd() != NOMAD::MINIMAL_DISPLAY) - out << std::endl - << "Warning (" << "Evaluator_Control.cpp" << ", " << __LINE__ - << "): could not save information in stats file \'" - << file_name << "\'" << std::endl << std::endl; - } - fout.close(); -} - -/*-------------------------------------------------------------------*/ -/* display stats during Mads::run() for minimal and normal display */ -/*-------------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_stats -( bool header , - const NOMAD::Display & out , - const std::list & stats , - const NOMAD::Eval_Point * x , - bool feasible , - const NOMAD::Point * multi_obj ) const -{ - if ( stats.empty() ) - { -#ifndef R_VERSION - out << std::endl; -#endif - return; - } - - if ( header ) - { -#ifndef R_VERSION - out << std::endl; -#endif - } - - NOMAD::Double f; - const NOMAD::Point * sol = NULL; - const NOMAD::Point * bbo = NULL; - const NOMAD::Signature * signature = NULL; - int bbe = _stats.get_bb_eval(); - int real_time = _stats.get_real_time(); - int blk_bbe = _stats.get_block_eval(); - int i; - - // this integer is used for the default width display - // of the various stats on the number of evaluations: - int max_bbe = _p.get_max_bb_eval(); - if ( _p.get_max_sgte_eval() > max_bbe ) - max_bbe = _p.get_max_sgte_eval(); - if ( _p.get_max_sim_bb_eval() > max_bbe ) - max_bbe = _p.get_max_sim_bb_eval(); - if ( _p.get_max_eval() > max_bbe ) - max_bbe = _p.get_max_eval(); - - if ( x ) - { - signature = x->get_signature(); - f = (feasible) ? x->get_f() : NOMAD::INF; - sol = x; - bbo = &(x->get_bb_outputs()); - - if (bbe < _last_stats_bbe && ! multi_obj) - return; - - real_time = x->get_real_time(); - _last_stats_tag = x->get_tag(); - _last_stats_bbe = bbe; - } - - - - std::string s1 , format; - std::list::const_iterator it , end = stats.end(); - for ( it = stats.begin() ; it != end ; ++it ) - { - - if ( it->empty() ) - { -#ifndef R_VERSION - out << "\t"; -#endif - } - else { - - if ( header ) - { -#ifndef R_VERSION - s1 = *it; - NOMAD::Display::extract_display_format ( s1 , format ); - out << s1; -#endif - } - - else - { - - // get the stats type: - NOMAD::display_stats_type dst - = NOMAD::Display::get_display_stats_type ( *it ); - - // some stats types are disables in the multi-objective case: - if ( multi_obj && - ( dst == NOMAD::DS_SIM_BBE || - dst == NOMAD::DS_BBE || - dst == NOMAD::DS_SGTE || - dst == NOMAD::DS_EVAL || - dst == NOMAD::DS_TIME || - dst == NOMAD::DS_STAT_SUM || - dst == NOMAD::DS_STAT_AVG ) ) - dst = NOMAD::DS_UNDEFINED; - - // display the stats: - switch ( dst ) - { - case NOMAD::DS_UNDEFINED: - s1 = *it; - NOMAD::Display::extract_display_format ( s1 , format ); - out << s1; - break; - case NOMAD::DS_OBJ: - if ( multi_obj ) - display_stats_point ( out , stats , it , multi_obj ); - else - { -#ifdef R_VERSION - { - std::ostringstream oss; - display_stats_real ( oss , f , format ); - Rprintf ( "%s" , oss.str().c_str() ); - } -#else - display_stats_real ( out , f , format ); -#endif - format.clear(); - } - break; - case NOMAD::DS_MESH_INDEX: - { - // display_stats_int ( out , - // NOMAD::Mesh::get_mesh_index() , - // 10*L_LIMITS , - // format ); - - // format.clear(); - - if ( signature ) - { - NOMAD::Point mesh_indices=signature->get_mesh()->get_mesh_indices(); - display_stats_point ( out , stats , it , &mesh_indices ); - } - else - out << "-"; - - - break; - } - case NOMAD::DS_DELTA_M: - case NOMAD::DS_MESH_SIZE: - { - if ( signature ) - { - NOMAD::Point delta; - signature->get_mesh()->get_delta ( delta ); - display_stats_point ( out , stats , it , &delta ); - } - else - out << "-"; - } - break; - case NOMAD::DS_DELTA_P: - case NOMAD::DS_POLL_SIZE: - { - if ( signature ) - { - NOMAD::Point Delta; - signature->get_mesh()->get_Delta ( Delta ); - display_stats_point ( out , stats , it , &Delta ); - - } - else - out << "-"; - } - break; - case NOMAD::DS_SIM_BBE: - display_stats_int ( out , _stats.get_sim_bb_eval() , max_bbe , format ); - format.clear(); - break; - case NOMAD::DS_BBE: - -#ifdef R_VERSION - { - std::ostringstream oss; - display_stats_int ( oss , bbe , max_bbe , format ); - Rprintf ( "\t%s " , oss.str().c_str() ); - } -#else - { - display_stats_int ( out , bbe , max_bbe , format ); - } -#endif - format.clear(); - break; - case NOMAD::DS_BLK_EVA: - { - display_stats_int ( out , blk_bbe , max_bbe , format ); - } - format.clear(); - break; - - case NOMAD::DS_SGTE: - //display_stats_int ( out , sgte_bbe , max_bbe , format ); - display_stats_int ( out , _stats.get_sgte_eval() , max_bbe , format ); - format.clear(); - break; - case NOMAD::DS_EVAL: - display_stats_int ( out , _stats.get_eval() , max_bbe , format ); - format.clear(); - break; - case NOMAD::DS_TIME: - display_stats_int ( out , real_time , 3600 , format ); - format.clear(); - break; - case NOMAD::DS_STAT_SUM: - display_stats_real ( out , _stats.get_stat_sum() , format ); - format.clear(); - break; - case NOMAD::DS_STAT_AVG: - display_stats_real ( out , _stats.get_stat_avg() , format ); - format.clear(); - break; - case NOMAD::DS_BBO: - display_stats_point ( out , stats , it , bbo ); - break; - case NOMAD::DS_SOL: - display_stats_point ( out , stats , it , sol , signature->get_input_type() ); - break; - case NOMAD::DS_VAR: - ++it; - NOMAD::atoi ( *it , i ); - if ( sol ) - if (format.empty()) - display_stats_type ( out , (*sol)[i] , (signature->get_input_type())[i] ); - else - display_stats_real ( out , (*sol)[i] , format ); - else - out << "-"; - format.clear(); - break; - } - } - } - } - - if ( !header ) -#ifdef R_VERSION - Rprintf("\n"); -#else - out << std::endl; -#endif -} - -/*-----------------------------------------------------*/ -/* display a number with type */ -/*-----------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_stats_type -( const NOMAD::Display & out , - const NOMAD::Double & d , - const NOMAD::bb_input_type & bbType ) const -{ - - // Default based on bbType - std::string format2; - switch (bbType) - { - case NOMAD::CONTINUOUS: - format2 = "%0." + NOMAD::itos(DISPLAY_PRECISION_STD) + "g"; - break; - case NOMAD::INTEGER || NOMAD::BINARY || NOMAD::CATEGORICAL: - format2 = "%i"; - break; - default: - break; - } - d.display ( out , format2 ); - -} - -/*-----------------------------------------------------*/ -/* display a real with DISPLAY_STATS (or STATS_FILE) */ -/*-----------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_stats_real -( const NOMAD::Display & out , - const NOMAD::Double & d , - const std::string & format ) const -{ - if ( format.empty() ) - { - std::string format2 = "%0." + NOMAD::itos(DISPLAY_PRECISION_STD) + "g"; - d.display ( out , format2 ); - } - else - d.display ( out , format ); -} - - -/*---------------------------------------------------------*/ -/* display an integer with DISPLAY_STATS (or STATS_FILE) */ -/*---------------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_stats_int -( const NOMAD::Display & out , - int i , - int max_i , - const std::string & format ) const -{ - if ( format.empty() ) - out.display_int_w ( i , max_i ); - else { - NOMAD::Double d = i; - d.display ( out , format ); - } -} - -/*---------------------------------------------------------*/ -/* display a point with DISPLAY_STATS (or STATS_FILE) */ -/*---------------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_stats_point -( const NOMAD::Display & out , - const std::list & display_stats , - std::list::const_iterator & it , - const NOMAD::Point * x , - const std::vector & bbType ) const -{ - if ( x ) - { - - unsigned int n = x->size() , bbn = static_cast(bbType.size()); - - if ( bbn!=0 && n != bbn ) - throw NOMAD::Exception ( "Evaluator_Control.cpp" , __LINE__ , - "Evaluator_Control::display_stats_point(): bbType and x have different size" ); - - - // s1 is the string displayed befores and after - // one coordinate (it may include format): - std::string s1; - if ( it != display_stats.begin() ) - { - s1 = *(--it); - ++it; - } - - // extract the display format from s1: - std::string format; - if ( !s1.empty() ) - NOMAD::Display::extract_display_format ( s1 , format ); - - // s2 is the string displayed between two coordinates: - std::string s2; - ++it; - if ( it != display_stats.end() ) - s2 = *it; - else if ( s2.empty() ) - --it; - - for ( unsigned int i = 0 ; i < n ; ++i ) - { - if ( !s1.empty() && i > 0 ) - out << s1; - - if (bbn!=0 && format.empty()) - display_stats_type ( out , (*x)[i] , bbType[i]); - else - display_stats_real (out, (*x)[i] , format ); - - if ( !s1.empty() ) - out << s1; - if ( !s2.empty() && i < n-1 && s2.find("(VNS)")==std::string::npos && s2.find("(PhaseOne)")==std::string::npos && s2.find("(LH)")==std::string::npos && s2.find("(ExtendedPoll)")==std::string::npos ) - out << " " << s2; - out << " "; - } - if ( !s2.empty() && (s2.find("(VNS)")!=std::string::npos || s2.find("(PhaseOne)")!=std::string::npos || s2.find("(LH)")!=std::string::npos || s2.find("(ExtendedPoll)")!=std::string::npos)) - out << s2; - } -} - -/*------------------------------------------*/ -/* save the solution file (SOLUTION_FILE) */ -/*------------------------------------------*/ -void NOMAD::Evaluator_Control::write_solution_file ( const NOMAD::Eval_Point & x, - bool display_bimv) const -{ - const std::string & sol_file = _p.get_solution_file(); - if ( !sol_file.empty() && ( x.is_feasible ( _p.get_h_min() ) || display_bimv ) ) - write_sol_or_his_file ( _p.get_problem_dir() + sol_file , x , true , display_bimv ); -} - -/*----------------------------------------------*/ -/* save the solution file (SOLUTION_FILE) */ -/* or update the history file (HISTORY_FILE ) */ -/* (private) */ -/*----------------------------------------------*/ -void NOMAD::Evaluator_Control::write_sol_or_his_file -( const std::string & file_name , - const NOMAD::Eval_Point & x , - bool is_sol , - bool display_bimv ) const -{ - // if is_sol == true: save the solution file - // else: update the history file - bool failed = false; - std::ofstream fout; - - if ( is_sol ) - fout.open ( file_name.c_str() ); - else - fout.open ( file_name.c_str() , std::ios::app ); - - if ( !fout.fail() ) { - - fout.setf ( std::ios::fixed ); - fout.precision ( NOMAD::DISPLAY_PRECISION_BB ); - - // solution display: - if ( is_sol ) - { - if ( _p.get_bb_input_include_seed() ) - fout << _p.get_seed() << std::endl; - if ( _p.get_bb_input_include_tag() ) - fout << x.get_tag() << std::endl; - x.Point::display ( fout , "\n" , -1 , -1 ); - if (display_bimv) - fout << std::endl << "warning: best infeasible solution (min. violation)"; - fout << std::endl; - } - - // history display: - else { - x.Point::display ( fout , " " , -1 , -1 ); - fout << " "; - x.get_bb_outputs().Point::display ( fout , " " , -1 , -1 ); - fout << std::endl; - } - - if ( fout.fail() ) - failed = true; - } - else - failed = true; - - fout.close(); - - if ( failed && _p.out().get_gen_dd() != NOMAD::NO_DISPLAY && _p.out().get_gen_dd() != NOMAD::MINIMAL_DISPLAY) - _p.out() << std::endl - << "Warning (" << "Evaluator_Control.cpp" << ", " << __LINE__ - << "): could not " - << ( is_sol ? "save the current solution" : - "update the history" ) - << " in \'" - << file_name << "\'" << std::endl << std::endl; -} - - -/*---------------------------------------------------------*/ -/* display evaluation result (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_eval_result -( const NOMAD::Eval_Point & x , - NOMAD::dd_type display_degree , - NOMAD::search_type search , - NOMAD::success_type one_eval_success , - NOMAD::success_type success ) const -{ - const NOMAD::Display & out = _p.out(); - int cur_bbe; - - // surrogate evaluation: - if ( x.get_eval_type() == NOMAD::SGTE ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << "point #" << x.get_tag() << " sgte eval: "; - if ( x.is_eval_ok() ) - { - out << "h="; - if ( x.get_h().is_defined() ) - out << x.get_h(); - else - out << "inf (extr. barrier)"; - out << " f=" << x.get_f(); - } - else - out << "failed"; - out << std::endl; - } - if ( !_p.get_opt_only_sgte() ) - return; - - cur_bbe = _stats.get_sgte_eval(); - } - else - cur_bbe = _stats.get_eval(); - - const std::string & stats_file_name = _p.get_stats_file_name(); - bool feas_x = x.is_feasible ( _p.get_h_min() ); - - // update the history file: - // (contains surrogate evaluations if opt_only_sgte==true) - const std::string & his_file = _p.get_history_file(); - if ( !his_file.empty() && cur_bbe > _last_history_bbe) - { - write_sol_or_his_file ( _p.get_problem_dir() + his_file , x , false ); - _last_history_bbe = cur_bbe; - } - - // success displays: - if ( one_eval_success != NOMAD::UNSUCCESSFUL && - one_eval_success >= success ) - { - - // save the current solution in file: - write_solution_file ( x ); - - bool ds_ok = ( cur_bbe > _last_stats_bbe) && - ( _p.get_display_all_eval() || - ( one_eval_success == NOMAD::FULL_SUCCESS && feas_x ) ); - - // normal display and minimal: - if ( (display_degree == NOMAD::NORMAL_DISPLAY || display_degree == NOMAD::MINIMAL_DISPLAY ) && ds_ok ) - display_stats ( false , out , _p.get_display_stats() , &x , feas_x , NULL ); - // detailed display: - else if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << search << " " << one_eval_success - << " point " << x; - - // stats file: - if ( ds_ok && !stats_file_name.empty() ) - stats_file ( stats_file_name , &x , feas_x , NULL ); - - } - else - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << search << " " << one_eval_success - << " point #" << x.get_tag(); - if ( x.is_eval_ok() ) - out << " [ h=" << x.get_h() - << " f=" << x.get_f() << " ]" << std::endl; - else if (x.check_rejected()) - out << ": evaluation rejected by user (this may alter convergence properties!)" << std::endl; - else - out << ": evaluation failed (you may need to check the source of the problem)." << std::endl; - } - - if ( _p.get_display_all_eval() && cur_bbe > _last_stats_bbe ) - { - - if ( display_degree == NOMAD::NORMAL_DISPLAY || display_degree == NOMAD::MINIMAL_DISPLAY ) - display_stats ( false , out , _p.get_display_stats() , &x , feas_x , NULL ); - - if ( !stats_file_name.empty() ) - stats_file ( stats_file_name , &x , feas_x , NULL ); - } - } -} - - -/*-------------------------------------------*/ -/* search a point in the cache */ -/*-------------------------------------------*/ -/* . return true if the point is in cache */ -/* . private method */ -/*-------------------------------------------*/ -bool NOMAD::Evaluator_Control::cache_check -( const NOMAD::Eval_Point *& x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & count_eval , - const NOMAD::Double & h_max , - NOMAD::dd_type display_degree ) const -{ - NOMAD::eval_type x_eval_type = x->get_eval_type(); - const NOMAD::Eval_Point * cache_x = NULL; - - // first cache check: - if ( x->is_in_cache() ) - cache_x = x; - // second cache check: - else - cache_x = ( ( x->get_eval_type() == NOMAD::TRUTH ) ? - _cache : _sgte_cache )->find ( *x ); - - // cache hit: transfer some data from x to cache_x: - if ( cache_x ) - { - - if ( x_eval_type != cache_x->get_eval_type() ) - throw NOMAD::Exception ( "Evaluator_Control.cpp" , __LINE__ , - "Evaluator_Control::cache_check(): eval and cache pts have different eval_type" ); - - if ( cache_x->is_eval_ok() ) - { - - NOMAD::Eval_Point * modifiable_cache_x - = &NOMAD::Cache::get_modifiable_point ( *cache_x ); - - // if wrong number of outputs, reset cache_x._bb_outputs: - { - int m = _p.get_bb_nb_outputs(); - if ( cache_x->get_bb_outputs().size() != m ) - modifiable_cache_x->set_bb_output ( NOMAD::Point ( m ) ); - } - - modifiable_cache_x->set_signature ( x->get_signature () ); - modifiable_cache_x->set_direction ( x->get_direction () ); - // The point in cache is updated for the poll center to correspond to the new poll center of x (important for poll reduction) - modifiable_cache_x->set_poll_center ( x->get_poll_center () ); - modifiable_cache_x->set_poll_center_type ( x->get_poll_center_type () ); - modifiable_cache_x->set_user_eval_priority ( x->get_user_eval_priority() ); - modifiable_cache_x->set_rand_eval_priority ( x->get_rand_eval_priority() ); - -#ifdef MODEL_STATS - modifiable_cache_x->set_model_data ( *x ); -#endif - - // set_f, set_h, and set_EB_ok: - _ev->compute_f ( *modifiable_cache_x ); - _ev->compute_h ( *modifiable_cache_x ); - } - } - - // point in cache but evaluation is to be made again: - if ( cache_x && cache_x->is_eval_ok() && - ( !cache_x->get_f().is_defined() || - ( cache_x->is_EB_ok() && - !cache_x->get_bb_outputs().is_complete() && - cache_x->get_h().is_defined() && - cache_x->get_h() < h_max ) ) ) - { - x = cache_x; - cache_x = NULL; - } - - // point in cache: - if ( cache_x ) - { - - _stats.add_cache_hit(); - - // displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - const NOMAD::Display & out = _p.out(); - if ( cache_x->get_eval_type() == NOMAD::SGTE ) - out << "surrogate "; - out << "cache hit: #" << x->get_tag() - << " --> #" << cache_x->get_tag() << std::endl; - } - - // process the Eval_Point taken in cache: - process_eval_point ( *cache_x , - ( cache_x->get_eval_type() == NOMAD::TRUTH ) ? - true_barrier : sgte_barrier , - pareto_front ); - - // count the (simulated) bb eval ? - int index_cnt_eval = _p.get_index_cnt_eval(); - if ( index_cnt_eval >= 0 && cache_x->get_bb_outputs()[index_cnt_eval] == 0.0 ) - count_eval = false; - - x = cache_x; - - return true; - } - - return false; -} - -/*----------------------------------------------------*/ -/* eval a point (private) */ -/*----------------------------------------------------*/ -void NOMAD::Evaluator_Control::eval_point ( NOMAD::Eval_Point & x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & count_eval , - bool & stop , - NOMAD::stop_type & stop_reason , - const NOMAD::Double & h_max ) -{ - int max_bb_eval = _p.get_max_bb_eval(); - int max_sgte_eval = _p.get_max_sgte_eval(); - - // blackbox or surrogate evaluations are allowed: - if ( ( x.get_eval_type() == NOMAD::TRUTH && max_bb_eval != 0 ) || - ( x.get_eval_type() == NOMAD::SGTE && max_sgte_eval != 0 ) ) - { - - NOMAD::Eval_Point * eval_x = &NOMAD::Cache::get_modifiable_point ( x ); - - // get the signature: - NOMAD::Signature * signature = x.get_signature(); - if ( !signature ) - throw NOMAD::Exception ( "Evaluator_Control.cpp" , __LINE__ , - "Evaluator_Control::eval_point(): the point has no signature" ); - - // evaluation of the point: - // ------------------------ - bool eval_ok = true; - - NOMAD::Evaluator_Control::_force_evaluation_failure=false; - { - // 1. scaling: - bool do_scaling = signature->get_scaling().is_defined(); - if ( do_scaling ) - eval_x->scale(); - - // 2.1. evaluation: - try - { - eval_ok = _ev->eval_x ( *eval_x , h_max , count_eval ); - - } - catch ( exception & e ) - { - throw NOMAD::Exception ( "Evaluator_control.cpp" , __LINE__ , e.what() ); - } - - - - // 2.2. check the nan's: - if ( eval_ok && eval_x->check_nan() ) - eval_ok = false; - - if ( _force_evaluation_failure ) - eval_ok = false; - - // 3. unscaling: - if ( do_scaling ) - eval_x->unscale(); - } - - if ( eval_ok ) - { - - eval_x->set_eval_status ( NOMAD::EVAL_OK ); - - // set_f, set_h and set_EB_ok: - _ev->compute_f ( *eval_x ); - _ev->compute_h ( *eval_x ); - - } - else - { - eval_x->set_eval_status ( NOMAD::EVAL_FAIL ); - _stats.add_failed_eval(); - } - - // insertion in cache even if is_eval_ok == false: - if ( !x.is_in_cache() ) - { - - int size_before , size_after; - - if ( x.get_eval_type() == NOMAD::SGTE ) { - size_before = _sgte_cache->size(); - _sgte_cache->insert(x); - size_after = _sgte_cache->size(); - } - else { - size_before = _cache->size(); - _cache->insert(x); - size_after = _cache->size(); - } - - if ( size_after == size_before ) - x.set_in_cache ( false ); - } - - } - -} - - -/*----------------------------------------------------*/ -/* eval points in a list (private) */ -/*----------------------------------------------------*/ -void NOMAD::Evaluator_Control::eval_points ( std::list & list_eval , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - std::list & count_list_eval, - bool & stop , - NOMAD::stop_type & stop_reason , - const NOMAD::Double & h_max ) -{ - int max_bb_eval = _p.get_max_bb_eval(); - int max_sgte_eval = _p.get_max_sgte_eval(); - - std::list::iterator it_begin=list_eval.begin(); - - // blackbox or surrogate evaluations are allowed: - if ( ( (*it_begin)->get_eval_type() == NOMAD::TRUTH && max_bb_eval != 0 ) || - ( (*it_begin)->get_eval_type() == NOMAD::SGTE && max_sgte_eval != 0 ) ) - { - - // 1. Pre-evaluation tests and scaling - for ( std::list::iterator it=it_begin;it!=list_eval.end();++it) - { - // get the signature: - NOMAD::Signature * signature = (*it)->get_signature(); - if ( !signature ) - throw NOMAD::Exception ( "Evaluator_Control.cpp" , __LINE__ , - "Evaluator_Control::eval_points(): the point has no signature" ); - - // Scaling before evaluation of the points: - bool do_scaling = signature->get_scaling().is_defined(); - if ( do_scaling ) - (*it)->scale(); - - } - - // 2. list evaluation: - bool eval_list_ok = true; - NOMAD::Evaluator_Control::_force_evaluation_failure=false; - - try - { - _ev->eval_x ( list_eval , h_max,count_list_eval ); - } - catch ( exception & e ) - { - throw NOMAD::Exception ( "Evaluator_control.cpp" , __LINE__ , e.what() ); - } - - if ( _force_evaluation_failure ) - eval_list_ok = false; - - - // One block of evaluations is counted - if ( eval_list_ok ) - _stats.add_one_block_eval(); - - - - // 3. Post list evaluation checks and operation - std::list::iterator it_count=count_list_eval.begin(); - for ( std::list::iterator it=it_begin;it!=list_eval.end();++it,++it_count) - { - bool eval_ok=true; - bool eval_rejected=false; - - // 3.1. check the nan's and list evaluation failure: - if ( !eval_list_ok || (*it)->check_nan() ) - eval_ok = false; - - if ((*it)->check_rejected()) - { - eval_rejected=true; - eval_ok=false; - } - - // 3.2 unscaling: - if ( (*it)->get_signature()->get_scaling().is_defined() ) - (*it)->unscale(); - - - if ( eval_ok ) - { - (*it)->set_eval_status ( NOMAD::EVAL_OK ); - - // set_f, set_h and set_EB_ok: - _ev->compute_f ( *(*it) ); - _ev->compute_h ( *(*it)); - - } - else if (!eval_rejected) - { - (*it)->set_eval_status ( NOMAD::EVAL_FAIL ); - _stats.add_failed_eval(); - } // Do nothing if eval has been rejected - - // insertion in cache even if is_eval_ok == false. Exception: a point that has been rejected by user is not put in the cache. - if ( !(*it)->is_in_cache() && !eval_rejected ) - { - - int size_before , size_after; - - if ( (*it)->get_eval_type() == NOMAD::SGTE ) - { - size_before = _sgte_cache->size(); - _sgte_cache->insert(*(*it)); - size_after = _sgte_cache->size(); - } - else - { - size_before = _cache->size(); - _cache->insert(*(*it)); - size_after = _cache->size(); - } - - if ( size_after == size_before ) - (*it)->set_in_cache ( false ); - } - - - // count the output stats (STAT_SUM and STAT_AVG): - if ( (_p.check_stat_sum() || _p.check_stat_avg()) && !eval_rejected) - count_output_stats(*(*it)); - - } - } -} - - - -/*-------------------------------------------*/ -/* check stopping criteria (private) */ -/*-------------------------------------------*/ -void NOMAD::Evaluator_Control::check_stopping_criteria -( NOMAD::search_type search , - bool count_eval , - const NOMAD::Eval_Point & x , - bool & stop , - NOMAD::stop_type & stop_reason ) const -{ - // check the time: - if ( !stop && - _p.get_max_time() > 0 && - _stats.get_real_time() >= _p.get_max_time() ) - { - stop = true; - stop_reason = NOMAD::MAX_TIME_REACHED; - } - - // count an evaluation or a simulated blackbox evaluation: - if ( x.get_eval_type() == NOMAD::TRUTH ) - { - _stats.add_eval(); - if ( count_eval && !x.get_current_run() ) - _stats.add_sim_bb_eval(); - } - - - // check STAT_SUM_TARGET: - if ( !stop && - (_p.check_stat_sum() || _p.check_stat_avg())) - { - - NOMAD::Double sum_target = _p.get_stat_sum_target(); - if ( sum_target.is_defined() ) - { - NOMAD::Double sum = _stats.get_stat_sum(); - if ( sum.is_defined() && sum >= sum_target ) - { - stop = true; - stop_reason = NOMAD::STAT_SUM_TARGET_REACHED; - } - } - } - - // check the number of blackbox evaluations: - if ( !stop ) - { - int max_bb_eval = _p.get_max_bb_eval(); - int max_sgte_eval = _p.get_max_sgte_eval(); - if ( max_bb_eval > 0 && _stats.get_bb_eval() >= max_bb_eval ) - { - stop = true; - stop_reason = NOMAD::MAX_BB_EVAL_REACHED; - } - if ( max_sgte_eval > 0 && _stats.get_sgte_eval() >= max_sgte_eval ) - { - stop = true; - stop_reason = NOMAD::MAX_SGTE_EVAL_REACHED; - } - } - - // check the stopping condition MAX_EVAL: - if ( !stop && - _p.get_max_eval() > 0 && - _stats.get_eval() >= _p.get_max_eval() ) - { - stop = true; - stop_reason = NOMAD::MAX_EVAL_REACHED; - } - - // check the stopping condition MAX_SIM_BB_EVAL: - if ( !stop && - _p.get_max_sim_bb_eval() > 0 && - _stats.get_sim_bb_eval() >= _p.get_max_sim_bb_eval() ) - { - stop = true; - stop_reason = NOMAD::MAX_SIM_BB_EVAL_REACHED; - } - - // check the stopping conditions F_TARGET and FEAS_REACHED - // (for phase one: the evaluations must stop if all EB - // constraints are satisfied, but some PB constraints can - // be violated) - if ( !stop && - x.is_eval_ok() && - ( _p.get_opt_only_sgte() || - x.get_eval_type() == NOMAD::TRUTH ) ) - { - - bool feasible = x.is_feasible ( _p.get_h_min() ); - - // check FEAS_REACHED: - if ( feasible && _p.get_stop_if_feasible() ) - { - stop = true; - stop_reason = NOMAD::FEAS_REACHED; - } - - // check F_TARGET: - { - const NOMAD::Point & f_target = _p.get_f_target(); - const std::list & index_obj = _p.get_index_obj(); - std::list::const_iterator index_obj_end = index_obj.end(); - bool check_f_target = f_target.is_defined(); - int nb_to_check = (check_f_target) ? - f_target.nb_defined() : 0; - - if ( check_f_target && ( feasible || search == NOMAD::LH_SEARCH_P1 ) ) - { - const NOMAD::Point & bbo = x.get_bb_outputs(); - bool chk = true; - int k = 0; - int cnt = 0; - for ( std::list::const_iterator it = index_obj.begin(); - it != index_obj_end ; ++it , ++k ) - { - if ( bbo[*it].is_defined() && f_target[k].is_defined() ) - { - if ( f_target[k] < bbo[*it] ) - { - chk = false; - break; - } - cnt++; - } - } - - if ( chk && cnt == nb_to_check ) - { - stop = true; - stop_reason = NOMAD::F_TARGET_REACHED; - } - } - } - } -} - -/*-------------------------------------------------------*/ -/* receive an evaluation result from a slave (private) */ -/*-------------------------------------------------------*/ -#ifdef USE_MPI -void NOMAD::Evaluator_Control::receive_eval_result -( NOMAD::search_type search , - NOMAD::Eval_Point * x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - int slave_rank , - bool & stop , - NOMAD::stop_type & stop_reason ) -{ - bool eval_ok , count_eval; - - - // receive the evaluation result: - _slave->receive_eval_result ( slave_rank , x , eval_ok , count_eval ); - - // process the evaluation: - if ( eval_ok ) { - - // set_f, set_h and set_EB_ok: - _ev->compute_f ( *x ); - _ev->compute_h ( *x ); - - // process the evaluated point: - process_eval_point ( *x , - (x->get_eval_type()==NOMAD::TRUTH) ? - true_barrier : sgte_barrier , - pareto_front ); - } - else - _stats.add_failed_eval(); - - // insertion in cache even if !eval_ok: - if ( !x->is_in_cache() ) - ( ( x->get_eval_type() == NOMAD::SGTE ) ? - _sgte_cache : _cache)->insert ( *x ); - - // count the bb evaluation: - if ( count_eval ) { - if ( x->get_eval_type() == NOMAD::SGTE ) - _stats.add_sgte_eval(); - else - _stats.add_bb_eval(); - } - - // count the output stats (STAT_SUM and STAT_AVG): - if ( _p.check_stat_sum() || _p.check_stat_avg() ) { - - count_output_stats ( *x ); - - // check STAT_SUM_TARGET: - NOMAD::Double sum_target = _p.get_stat_sum_target(); - if ( sum_target.is_defined() ) { - NOMAD::Double sum = _stats.get_stat_sum(); - if ( !stop && sum.is_defined() && sum >= sum_target ) { - stop = true; - stop_reason = NOMAD::STAT_SUM_TARGET_REACHED; - } - } - } - - // check stopping criteria: - if ( !stop ) { - - int max_bb_eval = _p.get_max_bb_eval(); - int max_sgte_eval = _p.get_max_sgte_eval(); - - if ( max_bb_eval > 0 && _stats.get_bb_eval() >= max_bb_eval ) { - stop = true; - stop_reason = NOMAD::MAX_BB_EVAL_REACHED; - } - if ( max_sgte_eval > 0 && _stats.get_sgte_eval() >= max_sgte_eval ) { - stop = true; - stop_reason = NOMAD::MAX_SGTE_EVAL_REACHED; - } - } - - check_stopping_criteria ( search , count_eval , *x , stop , stop_reason ); -} -#endif - -/*----------------------------------------------------*/ -/* wait for evaluations in progress */ -/*----------------------------------------------------*/ -#ifdef USE_MPI -void NOMAD::Evaluator_Control::wait_for_evaluations -( NOMAD::search_type search , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - std::list & evaluated_pts ) -{ - if ( _nb_in_progress == 0 ) - return; - - // display degree: - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_display_degree ( search ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::open_block ( "wait for evaluations" ); - - NOMAD::Barrier & barrier = ( _p.get_opt_only_sgte() ) ? - sgte_barrier : true_barrier; - char signal; - int source; - NOMAD::Eval_Point * eval_x; - NOMAD::success_type one_eval_success; - - while ( _nb_in_progress > 0 ) - { - - source = NOMAD::Slave::receive_signal ( signal ); - eval_x = _eval_in_progress[source]; - - if ( eval_x ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "receive eval point #" << eval_x->get_tag() - << " from slave " << source << std::endl << std::endl; - - receive_eval_result ( search , - eval_x , - true_barrier , - sgte_barrier , - pareto_front , - source , - stop , - stop_reason ); - - // list of processed points: - if ( eval_x->is_in_cache() ) - evaluated_pts.push_back ( eval_x ); - - // success: - one_eval_success = barrier.get_one_eval_succ(); - success = barrier.get_success(); - - // asynchronous success count: - if ( success == NOMAD::FULL_SUCCESS && - _elop_tag != _slaves_elop_tags[source] ) - _stats.add_asynchronous_success(); - - // displays: - display_eval_result ( *eval_x , - display_degree , - search , - one_eval_success , - success ); - - if ( !_eval_in_progress[source]->is_in_cache() ) - delete _eval_in_progress[source]; - _eval_in_progress[source] = NULL; - _slaves_elop_tags[source] = -1; - --_nb_in_progress; - - // force quit (by pressing ctrl-c): - if ( !stop && ( NOMAD::Evaluator_Control::_force_quit || NOMAD::Evaluator::get_force_quit() ) ) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - break; - } - - if ( stop && ( stop_reason==NOMAD::ERROR || - stop_reason==NOMAD::UNKNOWN_STOP_REASON ) ) - break; - } - else - NOMAD::Slave::send_signal ( NOMAD::WAIT_SIGNAL , source ); - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block(); -} -#endif - -/*----------------------------------------------------------------*/ -/* check if the evaluation at this point is already in progress */ -/* (private) */ -/*----------------------------------------------------------------*/ -#ifdef USE_MPI -bool NOMAD::Evaluator_Control::already_in_progress -( const NOMAD::Eval_Point & x ) const -{ - if ( _eval_in_progress ) { - - int x_tag = x.get_tag(); - int np = NOMAD::Slave::get_nb_processes(); - - for ( int i = 0 ; i < np ; ++i ) - if ( _eval_in_progress[i] && - ( _eval_in_progress[i]->get_tag() == x_tag || - _eval_in_progress[i]->Point::operator == ( x ) ) ) - return true; - } - return false; -} -#endif - -/*----------------------------------------------------------------*/ -/* eval_list_of_points, private version (parallel version) */ -/*----------------------------------------------------------------*/ -#ifdef USE_MPI -void NOMAD::Evaluator_Control::private_eval_list_of_points -( NOMAD::search_type search , // IN : search type - NOMAD::Barrier & true_barrier , // IN/OUT : the barrier - NOMAD::Barrier & sgte_barrier , // IN/OUT : the surrogate barrier - NOMAD::Pareto_Front * pareto_front , // IN/OUT : the Pareto front - // (can be NULL) - bool & stop , // IN/OUT : stopping criterion - NOMAD::stop_type & stop_reason , // OUT : stopping reason - const NOMAD::Eval_Point *& new_feas_inc , // OUT : new feasible incumbent - const NOMAD::Eval_Point *& new_infeas_inc , // OUT : new infeas. incumbent - NOMAD::success_type & success , // OUT : type of success - std::list - & evaluated_pts ) // OUT : list of processed pts -{ - if ( stop || _eval_lop.empty() ) - { - stop_reason = NOMAD::UNKNOWN_STOP_REASON; - ++_elop_tag; - return; - } - - evaluated_pts.clear(); - - - // initial display: - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_display_degree ( search ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream msg; - msg << "list of points evaluation (" << search << ")"; - out << std::endl << NOMAD::open_block ( msg.str() ); - } - - // call the Evaluator (virtual) preprocessing of a list of points: - _ev->list_of_points_preprocessing ( _eval_lop ); - - const NOMAD::Eval_Point * old_feasible_incumbent = NULL; - const NOMAD::Eval_Point * old_infeasible_incumbent = NULL; - - // active barrier: - NOMAD::Barrier & barrier = ( _p.get_opt_only_sgte() ) ? - sgte_barrier : true_barrier; - - old_feasible_incumbent = barrier.get_best_feasible(); - old_infeasible_incumbent = barrier.get_best_infeasible(); - - NOMAD::Double f0; - if ( _p.get_opportunistic_min_f_imprvmt().is_defined() && - old_feasible_incumbent ) - f0 = old_feasible_incumbent->get_f(); - - new_feas_inc = NULL; - new_infeas_inc = NULL; - stop = false; - success = NOMAD::UNSUCCESSFUL; - stop_reason = NOMAD::NO_STOP; - - const NOMAD::Eval_Point * x; - NOMAD::check_failed_type check_failed_reason; - bool count_eval; - std::vector - to_be_evaluated; - NOMAD::success_type one_eval_success; - bool one_for_luck = false; - bool opp_stop = false; - int init_nb_eval = _stats.get_eval(); - int nb_success = 0; - int k = 0; - int nb_points = static_cast ( _eval_lop.size() ); - int max_bb_eval = _p.get_max_bb_eval(); - - // loop #1: search in cache: - // ------------------------- - std::set::iterator - it = _eval_lop.begin() , - end = _eval_lop.end(); - while ( !stop && !opp_stop && it != end ) - { - - x = it->get_point(); - - x->set_current_run ( true ); - - // displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - - // open the evaluation block: - { - std::ostringstream oss; - if ( x->get_eval_type() == NOMAD::SGTE ) - oss << "surrogate "; - oss << "evaluation " << k+1 << "/" << nb_points; - out << std::endl << NOMAD::open_block ( oss.str() ); - } - - out << std::endl << "point #" << x->get_tag() << " ( "; - x->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - if ( x->get_direction() ) - { - out << "direction : " << *x->get_direction() << std::endl; - NOMAD::Point delta; - x->get_signature()->get_mesh()->get_delta(delta); - out << "direction d : ( " << *x->get_direction()/delta << " )" << std::endl; - } - if ( x->get_signature() ) - out << "mesh indices: ( " << x->get_signature()->get_mesh()->get_mesh_indices() << " )" << std::endl; - out << std::endl; - - - - } - - // check if the evaluation at this point is already in progress: - if ( !already_in_progress ( *x ) ) - { - - // current point check (# of bb outputs, bounds, integer values, fixed-vars): - if ( x->check ( _p.get_bb_nb_outputs() , check_failed_reason ) ) - { - - count_eval = true; - - // point in cache: - if ( cache_check ( x , - true_barrier , - sgte_barrier , - pareto_front , - count_eval , - barrier.get_h_max() , - display_degree ) ) - - { - - // list of processed points: - evaluated_pts.push_back ( x ); - - // check stopping criteria: - check_stopping_criteria ( search , count_eval , *x , stop , stop_reason ); - - // success: - one_eval_success = barrier.get_one_eval_succ(); - success = barrier.get_success(); - - // displays: - display_eval_result ( *x , - display_degree , - search , - one_eval_success , - success ); - - // stop the evaluations (opportunistic strategy) ? - if ( stop_evaluations ( *x , - search , - k , - nb_points , - stop , - display_degree , - one_eval_success , - success , - init_nb_eval , - f0 , - barrier , - nb_success , - one_for_luck ) ) - { - _stats.add_interrupted_eval(); - opp_stop = true; // will break loop #1 - } - - // close the evaluation block: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block(); - } - - // point not in cache (the point is saved for loop #2): - else - { - - // blackbox or surrogate evaluations are allowed: - if ( ( x->get_eval_type() == NOMAD::TRUTH && max_bb_eval != 0 ) || - ( x->get_eval_type() == NOMAD::SGTE && _p.get_max_sgte_eval() != 0 ) ) - to_be_evaluated.push_back ( x ); - - // close the evaluation block: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block(); - } - } - - // points[k]->check() failed (close the evaluation block): - else if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "check failed (" << check_failed_reason << ")"; - out.close_block ( oss.str() ); - } - } - - // evaluation already in progress (close the evaluation block): - else if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "evaluation of point #" << x->get_tag() - << " already in progress"; - out.close_block ( oss.str() ); - } - - ++it; - ++k; - - // force quit (by pressing ctrl-c): - if ( !stop && (NOMAD::Evaluator_Control::_force_quit || NOMAD::Evaluator::get_force_quit()) ) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - } - - } // end of loop #1 - // -------------- - - // loop #2: evaluations: - // --------------------- - int nb_to_evaluate = static_cast ( to_be_evaluated.size() ); - int nb_evaluated = 0; - int cur = 0; - int source; - char signal; - NOMAD::Eval_Point * eval_x; - - while ( !stop && !opp_stop && nb_evaluated < nb_to_evaluate ) - { - - source = NOMAD::Slave::receive_signal ( signal ); - - // 2.1: send the RESULT signal, receive and process the evaluation result: - // ----------------------------------------------------------------------- - eval_x = _eval_in_progress[source]; - if ( eval_x ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "receive eval point #" << eval_x->get_tag() - << " from slave " << source << std::endl << std::endl; - - receive_eval_result ( search , - eval_x , - true_barrier , - sgte_barrier , - pareto_front , - source , - stop , - stop_reason ); - - - // list of processed points: - if ( eval_x->is_in_cache() ) - evaluated_pts.push_back ( eval_x ); - - // success: - one_eval_success = barrier.get_one_eval_succ(); - success = barrier.get_success(); - - // asynchronous success count: - if ( success == NOMAD::FULL_SUCCESS && - _elop_tag != _slaves_elop_tags[source] ) - _stats.add_asynchronous_success(); - - // displays: - display_eval_result ( *eval_x , - display_degree , - search , - one_eval_success , - success ); - - // stop the evaluations (opportunistic strategy) ? - if ( stop_evaluations ( *eval_x , - search , - nb_evaluated , - nb_to_evaluate , - stop , - display_degree , - one_eval_success , - success , - init_nb_eval , - f0 , - barrier , - nb_success , - one_for_luck ) ) - { - _stats.add_interrupted_eval(); - opp_stop = true; // will break loop #2 - } - - _eval_in_progress[source] = NULL; - _slaves_elop_tags[source] = -1; - --_nb_in_progress; - ++nb_evaluated; - } - - // 2.2: send the EVAL signal and launch a new evaluation: - // ------------------------------------------------------ - else - { - - // do not launch a new evaluation if... - - // there is no more points to be evaluated: - if ( cur == nb_to_evaluate ) - NOMAD::Slave::send_signal ( NOMAD::WAIT_SIGNAL , source ); - - // or if bbe+_nb_in_progress >= max_bb_eval: - else if ( to_be_evaluated[cur]->get_eval_type() == NOMAD::TRUTH && - max_bb_eval > 0 && - _stats.get_bb_eval() + _nb_in_progress >= max_bb_eval ) - { - stop = true; - stop_reason = NOMAD::MAX_BB_EVAL_REACHED; - NOMAD::Slave::send_signal ( NOMAD::WAIT_SIGNAL , source ); - } - - else - { - - // get the signature: - NOMAD::Signature * signature = to_be_evaluated[cur]->get_signature(); - - // there is no signature (error): - if ( !signature ) - { - stop = true; - stop_reason = NOMAD::ERROR; - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl - << "Error in Evaluator_Control::private_eval_list_of_points():" - << " the point #" << to_be_evaluated[cur]->get_tag() - << " has no signature" << std::endl << std::endl; - NOMAD::Slave::send_signal ( NOMAD::WAIT_SIGNAL , source ); - } - - else - { - - NOMAD::Slave::send_signal ( NOMAD::EVAL_SIGNAL , source ); - - eval_x = &NOMAD::Cache::get_modifiable_point ( *to_be_evaluated[cur++] ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "send eval point #" << eval_x->get_tag() - << " to slave " << source << std::endl; - - // 1. scaling: - bool do_scaling = signature->get_scaling().is_defined(); - if ( do_scaling ) - eval_x->scale(); - - // 2. send the point: - _slave->send_eval_point ( eval_x , source , barrier.get_h_max() ); - - // 3. unscaling: - if ( do_scaling ) - eval_x->unscale(); - - eval_x->set_eval_status ( NOMAD::EVAL_IN_PROGRESS ); - - _eval_in_progress[source] = eval_x; - _slaves_elop_tags[source] = _elop_tag; - ++_nb_in_progress; - } - } - } - - // force quit (by pressing ctrl-c): - if ( !stop && ( NOMAD::Evaluator_Control::_force_quit || NOMAD::Evaluator::get_force_quit() )) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - } - - } // end of loop #2 - // -------------- - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "number of evaluations in progress: " << _nb_in_progress - << std::endl << std::endl; - - // the algorithm is not asynchronous: we have - // to wait for all the evaluations in progress: - if ( !_p.get_asynchronous() ) - - wait_for_evaluations ( search , - true_barrier , - sgte_barrier , - pareto_front , - stop , - stop_reason , - success , - evaluated_pts ); - - // barriers update: - if ( !stop ) - { - true_barrier.update_and_reset_success(); - sgte_barrier.update_and_reset_success(); - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block ( "end of evaluations" ) << std::endl; - - // incumbents update: - const NOMAD::Eval_Point * bf = barrier.get_best_feasible (); - const NOMAD::Eval_Point * bi = barrier.get_best_infeasible(); - if ( bf && bf != old_feasible_incumbent ) - new_feas_inc = bf; - if ( bi && bi != old_infeasible_incumbent ) - new_infeas_inc = bi; - - // the list of eval. points is deleted (only points in the cache are kept): - clear_eval_lop(); - - // update the unique eval_lop() tag: - ++_elop_tag; - -} // end of eval_lop() parallel version - -// C. Tribes may 28, 2014 --- method for points block evaluation of a given max size -/*----------------------------------------------------------------*/ -/* eval_list_of_points, private version (scalar version) */ -/*----------------------------------------------------------------*/ -#else -void NOMAD::Evaluator_Control::private_eval_list_of_points -( NOMAD::search_type search , // IN : search type - NOMAD::Barrier & true_barrier , // IN/OUT : the barrier - NOMAD::Barrier & sgte_barrier , // IN/OUT : the surrogate barrier - NOMAD::Pareto_Front * pareto_front , // IN/OUT : the Pareto front - // (can be NULL) - bool & stop , // IN/OUT : stopping criterion - NOMAD::stop_type & stop_reason , // OUT : stopping reason - const NOMAD::Eval_Point *& new_feas_inc , // OUT : new feasible incumbent - const NOMAD::Eval_Point *& new_infeas_inc , // OUT : new infeas. incumbent - NOMAD::success_type & success , // OUT : type of success - std::list - & evaluated_pts ) // OUT : list of processed pts -{ - if ( stop || _eval_lop.empty() ) - { - stop_reason = NOMAD::UNKNOWN_STOP_REASON; - return; - } - - evaluated_pts.clear(); - - // initial display: - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_display_degree ( search ); - - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "list of points evaluation (" << search << ")"; - out << std::endl << NOMAD::open_block ( oss.str() ); - } - - // call the Evaluator (virtual) preprocessing of a list of points: - _ev->list_of_points_preprocessing ( _eval_lop ); - - const NOMAD::Eval_Point * old_feasible_incumbent = NULL; - const NOMAD::Eval_Point * old_infeasible_incumbent = NULL; - - // active barrier: - NOMAD::Barrier & barrier = ( _p.get_opt_only_sgte() ) ? sgte_barrier : true_barrier; - - old_feasible_incumbent = barrier.get_best_feasible(); - old_infeasible_incumbent = barrier.get_best_infeasible(); - - NOMAD::Double f0; - if ( _p.get_opportunistic_min_f_imprvmt().is_defined() && - old_feasible_incumbent ) - f0 = old_feasible_incumbent->get_f(); - - new_feas_inc = NULL; - new_infeas_inc = NULL; - stop = false; - success = NOMAD::UNSUCCESSFUL; - stop_reason = NOMAD::NO_STOP; - - const NOMAD::Eval_Point * x; - NOMAD::check_failed_type check_failed_reason; - bool one_for_luck = false; - bool stop_evals = false; - int init_nb_eval = _stats.get_eval(); - int nb_success = 0; - int k = 0; - int k_block = 0; - int nb_points = get_nb_eval_points(); - int block_size = _p.get_bb_max_block_size(); - int block_nb = 1; - - // main loop (on the list of points): - // ---------------------------------- - std::set::iterator it = _eval_lop.begin() , end = _eval_lop.end(); - std::list list_x,list_eval; - std::list count_list_eval; - - while ( !stop_evals && !stop && it != end ) - { - - - if ( block_size > 1 && display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "Block of evaluations (" << block_nb <<")"; - out << std::endl << NOMAD::open_block ( oss.str() ); - } - - // Creation of a block of evaluations from the list - //---------------------- - k_block=k; - bool opportunistic_success_from_cache_point=false; - while (list_eval.size()!=static_cast(block_size) && it != end && ! stop_evals) - { - - x = it->get_point(); - x->set_current_run ( true ); - - // displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - { - // open the evaluation block: - std::ostringstream oss; - oss << "submitted "; - if ( x->get_eval_type() == NOMAD::SGTE ) - oss << "surrogate "; - oss << "evaluation " << k+1 << "/" << nb_points; - out << std::endl << NOMAD::open_block ( oss.str() ); - } - - out << std::endl << "point #" << x->get_tag() << " ( "; - x->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - if ( x->get_direction() ) - { - out << "direction : " << *x->get_direction() << std::endl; - NOMAD::Point delta; - x->get_signature()->get_mesh()->get_delta(delta); - out << "direction d : ( " << *x->get_direction()/delta << " )" << std::endl; - } - if ( x->get_signature() ) - out << "mesh indices: ( " << x->get_signature()->get_mesh()->get_mesh_indices() << " )" << std::endl; - out << std::endl; - - } - - // current point check (# of bb outputs, bounds, integer values, fixed-vars): - if ( x->check ( _p.get_bb_nb_outputs() , check_failed_reason ) ) - { - bool count_eval = true; - bool has_been_in_cache=cache_check ( x , - true_barrier , - sgte_barrier , - pareto_front , - count_eval , - barrier.get_h_max() , - display_degree ); - - - // put the point in a block list for evaluation: - if ( !has_been_in_cache ) - list_eval.push_back(&NOMAD::Cache::get_modifiable_point ( *x )); - else - { - // check stopping criteria for points in cache - check_stopping_criteria ( search , count_eval , *x , stop , stop_reason ); - - // process the evaluated point: - process_eval_point ( *x , - ( x->get_eval_type() == NOMAD::TRUTH ) ? true_barrier : sgte_barrier , - pareto_front ); - - - // success: - NOMAD::success_type one_eval_success = barrier.get_one_eval_succ(); - success = barrier.get_success(); - - - opportunistic_success_from_cache_point = stop_evaluations ( *x , - search , - k , - nb_points , - stop , - display_degree , - one_eval_success , - success , - init_nb_eval , - f0 , - barrier , - nb_success , - one_for_luck ); - - - } - - if (!stop) - list_x.push_back(&NOMAD::Cache::get_modifiable_point ( *x )); - - - if ( opportunistic_success_from_cache_point ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block(); - - if ( block_size > 1 && display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block (); - - stop_evals = true; - break; - } - - - } - // points[k]->check() failed: - else if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "check failed (" << check_failed_reason << ")" << std::endl; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block(); - - - ++it; - ++k; - } - if (list_eval.size()!=0) - { - - count_list_eval.assign(list_eval.size(), false); - - if (_p.eval_points_as_block()) - { - eval_points ( list_eval , - true_barrier , - sgte_barrier , - pareto_front , - count_list_eval , - stop , - stop_reason , - barrier.get_h_max() ); - - // check stopping criteria for points NOT in cache - std::list::iterator it_eval; - } - else - { - // bool count_eval=false; - x=*(list_eval.begin()); - eval_point ( NOMAD::Cache::get_modifiable_point ( *x ) , - true_barrier , - sgte_barrier , - pareto_front , - count_list_eval.front() , - stop , - stop_reason , - barrier.get_h_max() ); - - } - - } - - // Stop evals and exit the loop - if ( stop_evals ) - break; - - // Check all the points in the evaluation block - std::list::iterator it_x,it_eval; - k=k_block; - it_eval=list_eval.begin(); - for(it_x=list_x.begin();it_x!=list_x.end();++it_x) - { - - x=(*it_x); - - // process the evaluated point: - if ( x->is_eval_ok() && x->is_in_cache() ) - process_eval_point ( *x , - ( x->get_eval_type() == NOMAD::TRUTH ) ? - true_barrier : sgte_barrier , - pareto_front ); - - - - - // success: - NOMAD::success_type one_eval_success = barrier.get_one_eval_succ(); - success = barrier.get_success(); - - // list of processed points: - if ( x->is_in_cache() ) - evaluated_pts.push_back ( x ); - else - { - // this situation may occur on very thin meshes: - // the point has not been found in the cache - // and it failed to be inserted. - one_eval_success = NOMAD::UNSUCCESSFUL; - } - - // displays: - if ( block_size > 0 && display_degree == NOMAD::FULL_DISPLAY ) - { - // open the evaluation block: - std::ostringstream oss; - if ( x->get_eval_type() == NOMAD::SGTE ) - oss << "surrogate "; - oss << "evaluation " << k+1 << "/" << nb_points; - out << std::endl << NOMAD::open_block ( oss.str() ); - out << std::endl << "point #" << x->get_tag() << std::endl; - } - - - std::list::iterator it_count=count_list_eval.begin(); - for(it_eval=list_eval.begin();it_eval!=list_eval.end();++it_eval,++it_count) - { - if ((*it_eval)==x) - { - - // count the bb evaluation: - if ( *it_count ) - { - if ( (*it_eval)->get_eval_type() == NOMAD::SGTE ) - _stats.add_sgte_eval(); - else - { - // current mads bbe evaluation - _stats.add_bb_eval(); - } - - // count the output stats (STAT_SUM and STAT_AVG): - if ( _p.check_stat_sum() || _p.check_stat_avg() ) - count_output_stats(*(*it_eval)); - } - - check_stopping_criteria ( search , *it_count ,*(*it_eval) , stop , stop_reason ); - - if ( *it_count ) - display_eval_result ( *x, display_degree, search, one_eval_success, success ); - - break; - } - } - - - - // close the evaluation block: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block (); - - // stop the evaluations (opportunistic strategy) ? - if ( !stop_evals && stop_evaluations ( *x , - search , - k , - nb_points , - stop , - display_degree , - one_eval_success , - success , - init_nb_eval , - f0 , - barrier , - nb_success , - one_for_luck ) ) - { - _stats.add_interrupted_eval(); - stop_evals = true; - } - - - ++k; - - } - - if ( block_size > 1 && display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block (); - - - // force quit (by pressing ctrl-c): - if ( !stop && ( NOMAD::Evaluator_Control::_force_quit || NOMAD::Evaluator::get_force_quit()) ) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - } - - list_x.clear(); - list_eval.clear(); - - ++block_nb; - - }// end of test for list evaluation - - // barriers update: - if ( !stop ) - { - true_barrier.update_and_reset_success(); - sgte_barrier.update_and_reset_success(); - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::close_block ( "end of evaluations" ) - << std::endl; - - // incumbents update: - const NOMAD::Eval_Point * bf = barrier.get_best_feasible (); - const NOMAD::Eval_Point * bi = barrier.get_best_infeasible(); - if ( bf && bf != old_feasible_incumbent ) - new_feas_inc = bf; - if ( bi && bi != old_infeasible_incumbent ) - new_infeas_inc = bi; - - // the list of eval. points is deleted (only points in the cache are kept): - clear_eval_lop(); - -} // end of eval_lop() scalar version - - -#endif - -/*-------------------------------------------------*/ -/* reduce the list of evaluation points */ -/*-------------------------------------------------*/ -void NOMAD::Evaluator_Control::reduce_eval_lop ( int n ) -{ - int nb_eval_pts = get_nb_eval_points(); - - if ( n < 0 || n >= nb_eval_pts ) - return; - - const NOMAD::Eval_Point * x; - std::set::iterator it = _eval_lop.end(); - for( int i=0;iget_point(); - if ( x && !x->is_in_cache() && x->get_eval_status() != NOMAD::EVAL_IN_PROGRESS ) - delete x; - } - _eval_lop.erase( it,_eval_lop.end()); -} - -/*-------------------------------------------------*/ -/* TGP model ordering (private) */ -/*-------------------------------------------------*/ -void NOMAD::Evaluator_Control::TGP_model_ordering ( NOMAD::dd_type display_degree , - bool & modified_list ) -{ - modified_list = false; - - if ( _p.get_opt_only_sgte() ) - return; - -#ifdef USE_TGP - - // display: - const NOMAD::Display & out = _p.out(); - - // model stats: - NOMAD::Model_Stats model_stats; - NOMAD::Clock clock; - -#ifdef TGP_DEBUG - out << std::endl << NOMAD::open_block ( "TGP model ordering") << std::endl; -#endif - - const std::vector & bbot = _p.get_bb_output_type(); - int i , j , n_XX = 0 , m = bbot.size(); - - // construct prediction set (XX): - // ------------------------------ - std::vector XX; - NOMAD::Point lb_XX , ub_XX; - - // save _eval_lop in XX and other_pts: - const NOMAD::Eval_Point * x; - std::list other_pts; - const NOMAD::Signature * signature = NULL; - int n = -1; - - std::set::const_iterator it , end = _eval_lop.end(); - for ( it = _eval_lop.begin() ; it != end ; ++it ) { - x = it->get_point(); - if ( n < 0 ) { - signature = x->get_signature(); - if ( !signature ) { -#ifdef TGP_DEBUG - out << NOMAD::close_block ( "failure (no signature)" ) << std::endl; -#endif - return; - } - n = signature->get_n(); - - lb_XX = ub_XX = NOMAD::Point(n); - } - - if ( x->size () == n && - x->get_m () == m && - x->get_eval_type () == NOMAD::TRUTH && - !x->get_bb_outputs().is_defined() ) { - - XX.push_back ( &NOMAD::Cache::get_modifiable_point ( *x ) ); - - for ( i = 0 ; i < n ; ++i ) { - if ( !lb_XX[i].is_defined() || (*x)[i] < lb_XX[i] ) - lb_XX[i] = (*x)[i]; - if ( !ub_XX[i].is_defined() || (*x)[i] > ub_XX[i] ) - ub_XX[i] = (*x)[i]; - } - } - else - other_pts.push_back ( x ); - } - - n_XX = XX.size(); - - if ( n_XX <= 1 ) { -#ifdef TGP_DEBUG - out << NOMAD::close_block ( "failure (size(XX) <= 1)" ) << std::endl; -#endif - return; - } - - // the TGP model: - NOMAD::TGP_Model * model; - - // Reuse the last TGP model from the TGP model search: - if ( _last_TGP_model && _p.get_model_tgp_reuse_model() ) { - - model = _last_TGP_model; - - // individual predictions for XX points: - for ( i = 0 ; i < n_XX ; ++i ) - if ( !model->predict ( *XX[i] , false ) ) // pred_outside_bnds = false - for ( j = 0 ; j < m ; ++j ) - XX[i]->set_bb_output ( j , NOMAD::Double() ); - } - - // creation of a new TGP model: - else { - - model = new NOMAD::TGP_Model ( n , bbot , out , _p.get_model_tgp_mode() ); - - NOMAD::Point center(n); - for ( i = 0 ; i < n ; ++i ) - center[i] = ( lb_XX[i] + ub_XX[i] ) / 2.0; - - // construct interpolation set (X): - // -------------------------------- - if ( !model->set_X ( *_cache , - ¢er , - _p.get_seed() , - true ) ) { // remove_fv = true - - if ( model->get_p() <= model->get_n() ) - model_stats.add_not_enough_pts(); -#ifdef TGP_DEBUG - out << NOMAD::close_block ( "failure: " + model->get_error_str() ) - << std::endl; -#endif - - delete model; - - return; - } - - int p = model->get_p(); - - // display sets X and XX: - // ---------------------- -#ifdef TGP_DEBUG - { - // max number of points displayed: - const int set_display_limit = 15; // set to -1 for no limit - - // X: - model->display_X ( out , set_display_limit ); - - // XX: - out << NOMAD::open_block ( "prediction points (XX)"); - for ( i = 0 ; i < n_XX ; ++i ) { - out << "#"; - out.display_int_w ( i , n_XX ); - out << " x=("; - XX[i]->NOMAD::Point::display ( out , " " , 15 , -1 ); - out << " )" << std::endl; - } - std::ostringstream oss; - oss << "(size=" << n_XX << ")"; - out << NOMAD::close_block ( oss.str() ) << std::endl; - } -#endif - - // TGP model construction: - // ----------------------- -#ifdef TGP_DEBUG - out << "TGP model construction ..."; - out.flush(); -#endif - - if ( !model->compute ( XX , - false , // compute_Ds2x = false - false , // compute_improv = false - false ) ) { // pred_outside_bnds = false - - model_stats.add_construction_error(); - -#ifdef TGP_DEBUG - out << "... error: " << model->get_error_str() << std::endl - << NOMAD::close_block() << std::endl; -#endif - - // reset XX outputs: - for ( i = 0 ; i < n_XX ; ++i ) - for ( j = 0 ; j < m ; ++j ) - XX[i]->set_bb_output ( j , NOMAD::Double() ); - - delete model; - - // check if ctrl-c has been pressed: - if ( NOMAD::TGP_Output_Model::get_force_quit() ) - NOMAD::Evaluator_Control::_force_quit = true; - - return; - } -#ifdef TGP_DEBUG - out << "... OK" << std::endl << std::endl; -#endif - - // update model stats: - model_stats.add_construction_time ( clock.get_CPU_time() ); - model_stats.update_nY ( p ); - model_stats.update_ES_stats ( n_XX , n_XX ); - model_stats.add_nb_truth(); - model_stats.add_nb_TGP(); - } - - // open display block for model predictions: -#ifdef TGP_DEBUG - out << NOMAD::open_block ( "TGP predictions (XX+ZZ)"); -#endif - - // clear then fill _eval_lop again: - // -------------------------------- - NOMAD::Double f_model , h_model; - const NOMAD::Double & h_min = _p.get_h_min(); - NOMAD::hnorm_type h_norm = _p.get_h_norm(); - bool snap_to_bounds = _p.get_snap_to_bounds(); - - modified_list = true; - _eval_lop.clear(); - - for ( i = 0 ; i < n_XX ; ++i ) { - - // compute model h and f values: - model->eval_hf ( XX[i]->get_bb_outputs() , - h_min , - h_norm , - h_model , - f_model ); - - // display model predictions: -#ifdef TGP_DEBUG - out << "#"; - out.display_int_w ( i , n_XX ); - out << " x=("; - XX[i]->NOMAD::Point::display ( out , " " , 15 , -1 ); - out << " ) m(x)=["; - XX[i]->get_bb_outputs().display ( out , " " , 15 , -1 ); - out << " ]"; - - if ( h_model.is_defined() && f_model.is_defined() ) - out << " hm=" << std::setw(15) << h_model - << " fm=" << std::setw(15) << f_model; - else - out << " no model value"; - out << std::endl; -#endif - - // add the evaluation point: - add_eval_point ( XX[i] , - display_degree , - snap_to_bounds , - NOMAD::Double() , - NOMAD::Double() , - f_model , - h_model ); - -#ifdef MODEL_STATS - if ( XX[i] && f_model.is_defined() && h_model.is_defined() ) { - XX[i]->set_mod_use ( 2 ); // 2 for model ordering - XX[i]->set_Yw ( model->get_Yw () ); - XX[i]->set_nY ( p ); - XX[i]->set_mh ( h_model ); - XX[i]->set_mf ( f_model ); - } -#endif - } - -#ifdef TGP_DEBUG - { - // close display block for model predictions: - std::ostringstream oss; - oss << "(size=" << n_XX << ")"; - out << NOMAD::close_block ( oss.str() ) << std::endl; - - // compute and display prediction errors: - out << NOMAD::open_block ( "prediction relative errors on X(%)" ); - model->display_X_errors ( out ); - out << NOMAD::close_block() << std::endl; - } -#endif - - // other points that have been previously discarded and have no model values: - NOMAD::Eval_Point * y; - std::list::const_iterator it2 , end2 = other_pts.end(); - for ( it2 = other_pts.begin() ; it2 != end2 ; ++it2 ) { - y = &NOMAD::Cache::get_modifiable_point (**it2); - add_eval_point ( y , - display_degree , - snap_to_bounds , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - _stats.update_model_stats ( model_stats ); - _model_ordering_stats.update ( model_stats ); - - if ( model != _last_TGP_model ) - delete model; - -#ifdef TGP_DEBUG - out << NOMAD::close_block() << std::endl; -#else - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << std::endl << "model ordering"; - if ( !modified_list ) - out << " (no modification)"; - out << std::endl; - } -#endif -#endif -} - -/*-------------------------------------------------*/ -/* model_np1_quad_epsilon (private) */ -/*-------------------------------------------------*/ -void NOMAD::Evaluator_Control::quad_model_ordering ( NOMAD::dd_type display_degree , - bool & modified_list ) -{ - const NOMAD::Display & out = _p.out(); - -#ifdef DEBUG - out << std::endl << NOMAD::open_block ( "model_np1_quad_epsilon") << std::endl; -#endif - - // save _eval_lop in pts and other_pts: - // ------------------------------------ - NOMAD::Point min , max , center , interpolation_radius; - const NOMAD::Eval_Point * y; - std::list pts , other_pts; - const NOMAD::Signature * signature = NULL; - const NOMAD::Double & radius_factor = _p.get_model_quad_radius_factor(); - NOMAD::eval_type ev_type = NOMAD::TRUTH; - int i , n = -1; - - std::set::const_iterator it , end = _eval_lop.end(); - for ( it = _eval_lop.begin() ; it != end ; ++it ) - { - y = it->get_point(); - if ( n < 0 ) - { - signature = y->get_signature(); - if ( !signature ) - { -#ifdef DEBUG - out << NOMAD::close_block ( "failure (no signature)" ) << std::endl; -#endif - modified_list = false; - return; - } - n = signature->get_n(); - ev_type = y->get_eval_type(); - min.resize ( n ); - max.resize ( n ); - center.resize ( n ); - interpolation_radius.resize ( n ); - } - - if ( y->size() == n && y->get_eval_type() == ev_type ) { - pts.push_back(y); - for ( i = 0 ; i < n ; ++i ) { - if ( !min[i].is_defined() || (*y)[i] < min[i] ) - min[i] = (*y)[i]; - if ( !max[i].is_defined() || (*y)[i] > max[i] ) - max[i] = (*y)[i]; - } - } - else - other_pts.push_back ( y ); - } - - for ( i = 0 ; i < n ; ++i ) - { - center [i] = ( min[i] + max[i] ) / 2.0; - interpolation_radius[i] = ( max[i] - min[i] ) * radius_factor / 2.0; - } - -#ifdef DEBUG - out << NOMAD::open_block ( "points used to define interpolation radius") - << "type of eval. : " << ev_type << std::endl - << "number of points: " << pts.size() << std::endl - << "min. coordinates: ( "; - min.display ( out , " " , 2 ); - out << " )" << std::endl - << "max. coordinates: ( "; - max.display ( out , " " , 2 ); - out << " )" << std::endl - << "center : ( "; - center.display ( out , " " , 2 ); - out << " )" << std::endl - << "interp. radius : ( "; - interpolation_radius.display ( out , " " , 2 ); - out << " )" << std::endl - << NOMAD::close_block() << std::endl; -#endif - - // create model: - // ------------- - NOMAD::Clock clock; - NOMAD::Model_Stats model_stats; - NOMAD::Quad_Model model ( out , - _p.get_bb_output_type() , - (ev_type==NOMAD::TRUTH) ? *_cache : *_sgte_cache , - *signature ); - - int max_Y_size = _p.get_model_quad_max_Y_size(); - int min_Y_size = _p.get_model_quad_min_Y_size(); - bool use_WP = _p.get_model_quad_use_WP (); - - // construct interpolation set Y: - model.construct_Y ( center , - interpolation_radius , - max_Y_size ); - - int nY = model.get_nY(); - -#ifdef DEBUG - out << "number of points in Y: " << nY - << " (p=" << nY-1; - if ( nY < 2 ) out << ", not enough"; - out << ")" << std::endl; -#endif - - // not enough points: - if ( nY < 2 ) - { - modified_list = false; - model_stats.add_not_enough_pts(); - } - else - { - -#ifdef DEBUG - out << std::endl; - model.display_Y ( out , "unscaled interpolation set Y" ); -#endif - - // define scaling: - model.define_scaling ( radius_factor ); - -#ifdef DEBUG - out << std::endl; - model.display_Y ( out , "scaled interpolation set Ys" ); -#endif - - // model error flag: - if ( model.get_error_flag() ) - { - model_stats.add_construction_error(); - modified_list = false; - } - else - { - // not enough points: - if ( nY < 2 || ( min_Y_size < 0 && nY <= model.get_nfree() ) ) - { - model_stats.add_not_enough_pts(); - modified_list = false; - } - // enough points and no error: - else - { - - bool cautious = _p.get_model_eval_sort_cautious(); - int nb_inside_radius = 0; - - // check that there is at least two trial points inside the trust radius - // (cautious strategy): - nb_inside_radius = 0; - std::list::const_iterator it2 , end2 = pts.end(); - if ( cautious ) - { - for ( it2 = pts.begin() ; it2 != end2 ; ++it2 ) - { - NOMAD::Point scaled_pt ( **it2 ); - model.scale ( scaled_pt ); - if ( model.is_within_trust_radius ( scaled_pt ) ) - { - if ( ++nb_inside_radius == 2 ) - break; - } - } - } - - // not enough points inside trust radius: - if ( cautious && nb_inside_radius < 2 ) - modified_list = false; - - // at least two trial points are inside trust radius: - else - { - // construct model: - // ---------------- - model.construct ( use_WP , NOMAD::SVD_EPS , NOMAD::SVD_MAX_MPN , max_Y_size ); - model_stats.add_construction_time ( clock.get_CPU_time() ); - model_stats.update_nY ( model.get_nY() ); - - // display model characteristics: -#ifdef DEBUG - out << std::endl; - model.display_model_coeffs ( out ); - out << std::endl; - model.display_Y_error ( out ); -#endif - - // count model: - if ( ev_type == NOMAD::TRUTH ) - model_stats.add_nb_truth(); - else - model_stats.add_nb_sgte(); - - switch ( model.get_interpolation_type() ) - { - case NOMAD::MFN: - model_stats.add_nb_MFN(); - break; - case NOMAD::WP_REGRESSION: - model_stats.add_nb_WP_regression(); - break; - case NOMAD::REGRESSION: - model_stats.add_nb_regression(); - break; - default: - break; - } - - // check model error flag: - const NOMAD::Double & cond = model.get_cond(); - if ( model.get_error_flag() || - !cond.is_defined() || - cond > NOMAD::SVD_MAX_COND ) - { - modified_list = false; - if ( model.get_error_flag() ) - model_stats.add_construction_error(); - else - model_stats.add_bad_cond(); - } - else - { - // clear then fill _eval_lop again: - // -------------------------------- - NOMAD::Double f_model , h_model; - NOMAD::Eval_Point * x; - bool snap_to_bounds = _p.get_snap_to_bounds(); - - modified_list = true; - _eval_lop.clear(); - - nb_inside_radius = 0; - -#ifdef DEBUG - out << std::endl << NOMAD::open_block ( "original trial points" ); -#endif - - NOMAD::Quad_Model_Evaluator *quad_model_ev=new NOMAD::Quad_Model_Evaluator(_p , model); - - for ( it2 = pts.begin() ; it2 != end2 ; ++it2 ) - { - NOMAD::Point scaled_pt ( **it2 ); - model.scale ( scaled_pt ); - - - - f_model.clear(); - h_model.clear(); - - - if ( !cautious || model.is_within_trust_radius ( scaled_pt ) ) - { - - int m = static_cast(_p.get_bb_output_type().size()); - NOMAD::Eval_Point x_eval(scaled_pt,m); - for (int i = 0 ; i < x_eval.size() ; ++i ) - x_eval[i] = scaled_pt[i].value() * 1000.0; - - bool count_eval; - - bool success=quad_model_ev->eval_x(x_eval,0.0,count_eval); - if (success) - { - _ev->compute_f(x_eval); - _ev->compute_h(x_eval); - - f_model=x_eval.get_f(); - h_model=x_eval.get_h(); - } - - ++nb_inside_radius; - } - - x = &NOMAD::Cache::get_modifiable_point (**it2); - -#ifdef DEBUG - x->display_tag ( out ); - out << ": ( "; - x->NOMAD::Point::display ( out , " " , 2 ); - out << " ) scaled: ("; - scaled_pt.NOMAD::Point::display ( out , " " , 2 ); - out << ") "; - if ( h_model.is_defined() && f_model.is_defined() ) - out << "hm=" << h_model << " fm=" << f_model; - else - out << "no model value"; - out << std::endl; -#endif - - // add the evaluation point: - add_eval_point ( x , - display_degree , - snap_to_bounds , - NOMAD::Double() , - NOMAD::Double() , - f_model , - h_model ); - -#ifdef MODEL_STATS - if ( x && f_model.is_defined() && h_model.is_defined() ) - { - x->set_mod_use ( 2 ); // 2 for model ordering - x->set_cond ( model.get_cond() ); - x->set_Yw ( model.get_Yw () ); - x->set_nY ( model.get_nY () ); - x->set_mh ( h_model ); - x->set_mf ( f_model ); - } -#endif - } - - delete quad_model_ev; - - // other points that have been previously discarded - // and have no model values: - end2 = other_pts.end(); - for ( it2 = other_pts.begin() ; it2 != end2 ; ++it2 ) - { - - x = &NOMAD::Cache::get_modifiable_point (**it2); -#ifdef DEBUG - x->display_tag ( out ); - out << ": ( "; - x->NOMAD::Point::display ( out , " " , 2 ); - out << " ) no model value" << std::endl; -#endif - add_eval_point ( x , - display_degree , - snap_to_bounds , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } -#ifdef DEBUG - out.close_block(); -#endif - } - } - model_stats.update_ES_stats ( nb_inside_radius , static_cast(pts.size()) ); - } - } - } - - _stats.update_model_stats ( model_stats ); - _model_ordering_stats.update ( model_stats ); - -#ifdef DEBUG - out << NOMAD::close_block() << std::endl; -#else - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << "model ordering"; - if ( !modified_list ) - out << " (no modification)"; - out << std::endl; - } -#endif -} - -/*----------------------------------------------------------------------------------*/ -/* evaluation of a list of points (public version that calls the private version) */ -/*----------------------------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::eval_list_of_points -( NOMAD::search_type search , // IN : search type - NOMAD::Barrier & true_barrier , // IN/OUT: truth barrier - NOMAD::Barrier & sgte_barrier , // IN/OUT: surrogate barrier - NOMAD::Pareto_Front * pareto_front , // IN/OUT: Pareto front - // (can be NULL) - bool & stop , // IN/OUT: stopping criterion - NOMAD::stop_type & stop_reason , // OUT : stopping reason - const NOMAD::Eval_Point *& new_feas_inc , // OUT : new feas. incumbent - const NOMAD::Eval_Point *& new_infeas_inc , // OUT : new infeas. incumb. - NOMAD::success_type & success , // OUT : type of success - std::list - * evaluated_pts ) // OUT : list of processed -// pts (can be NULL) -{ - - bool del_evaluated_pts = false; - if ( !evaluated_pts ) - { - evaluated_pts = new std::list; - del_evaluated_pts = true; - } - - bool sgte_eval_sort = _p.get_sgte_eval_sort() && _eval_lop.size() > 1; - bool opt_only_sgte = _p.get_opt_only_sgte (); - bool snap_to_bounds = _p.get_snap_to_bounds(); - bool modified_list = false; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_display_degree ( search ); - - // reset the success type: - true_barrier.reset_success(); - sgte_barrier.reset_success(); - - // define all points as surrogates: - if ( opt_only_sgte || sgte_eval_sort ) - { - for ( std::set::iterator it = _eval_lop.begin() ; - it != _eval_lop.end() ; ++it ) - NOMAD::Cache::get_modifiable_point(*it->get_point()).set_eval_type(NOMAD::SGTE); - } - - // use the surrogates to sort the eval. points: - if ( !opt_only_sgte && sgte_eval_sort ) - { - - // evaluate the surrogate: - private_eval_list_of_points ( search , - true_barrier , - sgte_barrier , - NULL , // Pareto front = NULL - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - *evaluated_pts ); - if ( stop ) - { - if ( del_evaluated_pts ) - delete evaluated_pts; - return; - } - - NOMAD::Eval_Point * x; - - // construct a new list of trial points that will be - // ordered using surrogate values: - std::list::const_iterator - end = evaluated_pts->end() , it2; - for ( it2 = evaluated_pts->begin() ; it2 != end ; ++it2 ) { - - // Eval_Point construction: - x = new NOMAD::Eval_Point; - x->set ( (*it2)->size() , _p.get_bb_nb_outputs() ); - x->set_signature ( (*it2)->get_signature () ); - x->set_direction ( (*it2)->get_direction () ); - x->Point::operator = ( **it2 ); - - modified_list = true; - - // add the new point to the ordered list of trial points: - add_eval_point ( x , - display_degree , - snap_to_bounds , - (*it2)->get_f() , - (*it2)->get_h() , - NOMAD::Double() , - NOMAD::Double() ); - } - } - - if ( stop ) { - if ( del_evaluated_pts ) - delete evaluated_pts; - return; - } - - // model ordering: - // --------------- - if ( !modified_list && _model_eval_sort && _eval_lop.size() > 1 ) - { - switch ( _p.get_model_eval_sort() ) { - case NOMAD::TGP_MODEL: - TGP_model_ordering ( display_degree , modified_list ); - if ( NOMAD::Evaluator_Control::_force_quit || NOMAD::Evaluator::get_force_quit() ) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - } - break; - case NOMAD::QUADRATIC_MODEL: - quad_model_ordering ( display_degree , modified_list ); - break; - case NOMAD::NO_MODEL:; - } - } - - // this test is true if ctrl-c has been pressed: - if ( stop ) { - if ( del_evaluated_pts ) - delete evaluated_pts; - return; - } - - // display the re-ordered list of trial points: - if ( modified_list && display_degree == NOMAD::FULL_DISPLAY ) { - - const NOMAD::Eval_Point * y; - - std::ostringstream oss; - oss << "re-ordered list of " << _eval_lop.size() - << " " << search << " trial points"; - - out << NOMAD::open_block ( oss.str() ) << std::endl; - - std::set::const_iterator - end = _eval_lop.end() , it; - for ( it = _eval_lop.begin() ; it != end ; ++it ) { - y = it->get_point(); - y->display_tag ( out ); - out << ": ( "; - y->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )"; - if ( y->get_direction() ) - out << " (dir " << y->get_direction()->get_index() << ")"; - out << std::endl; - } - out.close_block(); - } - - // evaluate the list of points on the 'true' function: - private_eval_list_of_points ( search , - true_barrier , - sgte_barrier , - pareto_front , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - *evaluated_pts ); - -#ifdef MODEL_STATS - display_model_stats ( *evaluated_pts ); -#endif - - if ( del_evaluated_pts ) - delete evaluated_pts; -} - -/*------------------------------------------------------------------------------------*/ -/* ordering of a list of points based on surrogate (1st) or model (2nd) evaluations */ -/*------------------------------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::ordering_lop ( NOMAD::search_type search , // IN : search type - bool & stop , // IN/OUT: stopping criterion - NOMAD::stop_type & stop_reason , // OUT : stopping reason - NOMAD::Barrier & true_barrier , // IN/OUT: truth barrier - NOMAD::Barrier & sgte_barrier // IN/OUT: surrogate barrier -) - -{ - std::list * evaluated_pts = new std::list; - - bool sgte_eval_sort = _p.get_sgte_eval_sort() && _eval_lop.size() > 1; - bool opt_only_sgte = _p.get_opt_only_sgte (); - bool snap_to_bounds = _p.get_snap_to_bounds(); - bool modified_list = false; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_display_degree ( search ); - - NOMAD::success_type success ; - const NOMAD::Eval_Point *new_feas_inc ; - const NOMAD::Eval_Point *new_infeas_inc; - - - // reset the success type: - true_barrier.reset_success(); - sgte_barrier.reset_success(); - - - // use the surrogates to sort the eval. points: - if ( !opt_only_sgte && sgte_eval_sort ) - { - - for ( std::set::iterator it = _eval_lop.begin() ; it != _eval_lop.end() ; ++it ) - NOMAD::Cache::get_modifiable_point(*it->get_point()).set_eval_type(NOMAD::SGTE); - - - // evaluate the surrogate: - private_eval_list_of_points ( search , - true_barrier , - sgte_barrier , - NULL , // Pareto front = NULL - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - *evaluated_pts ); - if ( stop ) - { - delete evaluated_pts; - return; - } - - NOMAD::Eval_Point * x; - - // construct a new list of trial points that will be - // ordered using surrogate values: - std::list::const_iterator - end = evaluated_pts->end() , it2; - for ( it2 = evaluated_pts->begin() ; it2 != end ; ++it2 ) - { - - // Eval_Point construction: - x = new NOMAD::Eval_Point; - x->set ( (*it2)->size() , _p.get_bb_nb_outputs() ); - x->set_signature ( (*it2)->get_signature () ); - x->set_direction ( (*it2)->get_direction () ); - x->set_poll_center( (*it2)->get_poll_center () ); // Poll center is needed for further testing (not needed when evaluating points) - x->set_poll_center_type ( (*it2)->get_poll_center_type () ); - x->Point::operator = ( **it2 ); - - modified_list = true; - - // add the new point to the ordered list of trial points: - add_eval_point ( x , - display_degree , - snap_to_bounds , - (*it2)->get_f() , - (*it2)->get_h() , - NOMAD::Double() , - NOMAD::Double() ); - } - } - - // model ordering: - // --------------- - if ( !modified_list && _model_eval_sort && _eval_lop.size() > 1 ) { - switch ( _p.get_model_eval_sort() ) { - case NOMAD::TGP_MODEL: - TGP_model_ordering ( display_degree , modified_list ); - break; - case NOMAD::QUADRATIC_MODEL: - quad_model_ordering ( display_degree , modified_list ); - break; - case NOMAD::NO_MODEL:; - } - } - - if ( NOMAD::Evaluator_Control::_force_quit || NOMAD::Evaluator::get_force_quit() ) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - } - - delete evaluated_pts; -} - - - -/*--------------------------------------------------------------*/ -/* return if a series of evaluations is opportunistic or not, */ -/* depending on the search type (private) */ -/*--------------------------------------------------------------*/ -bool NOMAD::Evaluator_Control::is_opportunistic ( NOMAD::search_type t ) const -{ - switch ( t ) { - case NOMAD::X0_EVAL: - return false; - case NOMAD::LH_SEARCH: - return _p.get_opportunistic_LH(); - case NOMAD::CACHE_SEARCH: - return _p.get_opportunistic_cache_search(); - default: - return _p.get_opportunistic_eval(); - } - return false; -} - -/*----------------------------------------------------------------*/ -/* stop the evaluations ? */ -/*----------------------------------------------------------------*/ -/* . check the opportunistic strategy stopping criterion */ -/* . private method */ -/*----------------------------------------------------------------*/ -bool NOMAD::Evaluator_Control::stop_evaluations -( const NOMAD::Eval_Point & x , - NOMAD::search_type search , - int k , - int nb_points , - bool stop , - NOMAD::dd_type display_degree , - NOMAD::success_type one_eval_success , - NOMAD::success_type success , - int init_nb_eval , - const NOMAD::Double & f0 , - const NOMAD::Barrier & barrier , - int & nb_success , - bool & one_for_luck ) const -{ - // opportunistic evaluation ? - bool opportunistic = is_opportunistic ( search ); - - if ( k < nb_points - 1 ) { - - if ( stop ) - return true; - - if ( opportunistic && - ( x.get_eval_type() == NOMAD::TRUTH || _p.get_opt_only_sgte() ) ) - { - - if ( one_for_luck && one_eval_success != NOMAD::FULL_SUCCESS ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - _p.out() << std::endl - << "opportunistic termination of evaluations (lucky eval)" - << std::endl; - return true; - } - - if ( success == NOMAD::FULL_SUCCESS && - check_opportunistic_criterion ( display_degree , - one_eval_success , - init_nb_eval , - f0 , - barrier , - nb_success , - one_for_luck ) ) - return true; - } - } - return false; -} - -/*-----------------------------------------------------------------*/ -/* check the opportunistic strategy stopping criterion (private) */ -/* return true to stop the evaluations */ -/* return false to continue the evaluations */ -/*-----------------------------------------------------------------*/ -bool NOMAD::Evaluator_Control::check_opportunistic_criterion -( NOMAD::dd_type display_degree , - NOMAD::success_type one_eval_success , - int init_nb_eval , - const NOMAD::Double & f0 , - const NOMAD::Barrier & barrier , - int & nb_success , - bool & one_for_luck ) const -{ - - int min_nb_success = _p.get_opportunistic_min_nb_success(); - int min_eval = _p.get_opportunistic_min_eval(); - NOMAD::Double min_f_imprvmt = _p.get_opportunistic_min_f_imprvmt(); - bool lucky_eval = _p.get_opportunistic_lucky_eval(); - const NOMAD::Display & out = _p.out(); - - // min_nb_success: - if ( min_nb_success > 0 ) - { - - if ( one_eval_success == NOMAD::FULL_SUCCESS ) - ++nb_success; - - if ( nb_success < min_nb_success ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "opport. strategy (nb_success=" << nb_success - << " < min_nb_success=" << min_nb_success - << "): continue evaluations" - << std::endl; - - return false; - } - } - - // min_eval: - if ( min_eval > 0 ) - { - - int eval = _stats.get_eval() - init_nb_eval; - - if ( eval < min_eval ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "opport. strategy (eval=" << eval - << " < min_eval=" << min_eval - << "): continue evaluations" << std::endl; - return false; - } - } - - // min_f_imprvmt: - if ( min_f_imprvmt.is_defined() ) - { - - const NOMAD::Eval_Point * bf = barrier.get_best_feasible(); - - if ( f0.is_defined() && bf ) - { - - NOMAD::Double f = bf->get_f(); - - if ( f.is_defined() ) - { - - NOMAD::Double f_imprvmt = f0.rel_err(f) * 100.0; - - if ( f_imprvmt < min_f_imprvmt ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "opport. strategy (f_improvement=" - << f_imprvmt << " < min_f_imprvmt=" << min_f_imprvmt - << "): continue evaluations" << std::endl; - - return false; - } - } - } - } - - // lucky_eval: - if ( lucky_eval && one_eval_success == NOMAD::FULL_SUCCESS ) - { - one_for_luck = true; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "opport. strategy: one more evaluation for luck" - << std::endl; - - return false; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << "opport. strategy: stop evaluations" ; - if (_p.get_bb_max_block_size() > 1) - out << " at the end of the block evaluation"; - out << std::endl; - } - - return true; -} - -/*---------------------------------------------------------------*/ -/* display the list of evaluation points (_eval_lop) */ -/*---------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_eval_lop ( NOMAD::search_type t ) const -{ - const NOMAD::Display & out = _p.out(); - int cnt = 0 , nb = static_cast(_eval_lop.size()); - - if ( nb == 0 ) { - out << std::endl << "no evaluation point" << std::endl; - return; - } - - // open indented block: - std::ostringstream oss; - if ( t != NOMAD::UNDEFINED_SEARCH ) - oss << t << " "; - oss << "evaluation point"; - if ( nb > 1 ) - oss << "s"; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - - // display the points: - std::set::const_iterator it , end = _eval_lop.end(); - for ( it = _eval_lop.begin() ; it != end ; ++it ) { - out << "point "; - out.display_int_w ( ++cnt , nb ); - out << "/" << nb << ": ( "; - it->get_point()->Point::display ( out , - " " , - 2 , - NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // close indented block: - out.close_block(); -} - -/*--------------------------------------------------------------*/ -/* add an Eval_Point to the list of points to be evaluated */ -/*--------------------------------------------------------------*/ -/* . x has to be a dynamic object */ -/* . it may be deleted into the method and be NULL after that */ -/* . the point is also snapped to bounds */ -/* . periodic variables are checked */ -/*--------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::add_eval_point( NOMAD::Eval_Point *& x , - NOMAD::dd_type display_degree , - bool snap_to_bounds , - const NOMAD::Double & f_sgte , - const NOMAD::Double & h_sgte , - const NOMAD::Double & f_model , - const NOMAD::Double & h_model ) -{ - if ( !x ) - return; - - const NOMAD::Display & out = _p.out(); - - // treat the periodic variables: - NOMAD::Direction * new_dir = NULL; - - if ( _p.has_periodic_variables() && - x->treat_periodic_variables ( new_dir ) ) - { - - if ( new_dir && new_dir->norm() == 0.0 ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "point #" << x->get_tag() - << " is flushed (||dir||==0)" - << std::endl; - - delete x; - x = NULL; - - delete new_dir; - - return; - } - } - delete new_dir; - - if ( snap_to_bounds && x->snap_to_bounds() ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << "point #" << x->get_tag() << " "; - if ( x->get_direction() && x->get_direction()->get_index() >= 0 ) - out << "(dir " << x->get_direction()->get_index() << ") "; - out << "has been snapped to bounds" << std::endl; - } - - if ( x->get_direction() && x->get_direction()->norm() == 0.0 ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "point #" << x->get_tag() - << " is flushed (||dir||==0)" - << std::endl; - delete x; - x = NULL; - - return; - } - } - - // creation of the Priority_Eval_Point: - NOMAD::Priority_Eval_Point pep ( x , _p.get_h_min() ); - - // ordering elements of Priority_Eval_Point's: - // ------------------------------------------- - - // 1. surrogate values for f and h: - pep.set_f_sgte ( f_sgte ); - pep.set_h_sgte ( h_sgte ); - - // 2. model values for f and h: - pep.set_f_model ( f_model ); - pep.set_h_model ( h_model ); - - if ( x->get_direction() ) - { - - // get the signature: - NOMAD::Signature * signature = x->get_signature(); - if ( !signature ) - throw NOMAD::Exception ( "Evaluator_Control.cpp" , __LINE__ , - "Evaluator_Control::add_eval_point(): the point has no signature" ); - - // angle with last successful directions (feasible) - const NOMAD::Direction & feas_success_dir = signature->get_feas_success_dir(); - if ( feas_success_dir.is_defined() && - x->get_poll_center_type() == NOMAD::FEASIBLE ) - pep.set_angle_success_dir ( feas_success_dir.get_angle ( *x->get_direction() ) ); - - // angle with last infeasible success direction: - const NOMAD::Direction & infeas_success_dir = signature->get_infeas_success_dir(); - if ( infeas_success_dir.is_defined() && - x->get_poll_center_type() == NOMAD::INFEASIBLE ) - pep.set_angle_success_dir ( infeas_success_dir.get_angle ( *x->get_direction() ) ); - - } - - - - // insertion of the point in _eval_lop: - // ------------------------------------ - size_t size_before = _eval_lop.size(); - - _eval_lop.insert ( pep ); - - if ( _eval_lop.size() == size_before ) - { - delete x; - x = NULL; - } -} - -#ifdef MODEL_STATS -/*------------------------------------------------------------------*/ -/* display stats on an evaluation for which a model has been used */ -/*------------------------------------------------------------------*/ -/* The displayed stats are: */ -/* */ -/* use (1:model_search, 2:model_ordering) */ -/* mesh_index */ -/* cardinality of Y */ -/* width of Y */ -/* Y condition number */ -/* h value, model for h, relative error (if constraints) */ -/* f value, model for f, relative error */ -/* */ -/*------------------------------------------------------------------*/ -void NOMAD::Evaluator_Control::display_model_stats -( const std::list & evaluated_pts ) const -{ - const NOMAD::Display & out = _p.out(); - - NOMAD::Double h , mh , eh , f , mf , ef; - - std::list::const_iterator it , end = evaluated_pts.end(); - for ( it = evaluated_pts.begin() ; it != end ; ++it ) { - if ( *it && (*it)->get_mod_use() >= 0 ) { - - if ( _p.has_constraints() ) { - h = (*it)->get_h (); - mh = (*it)->get_mh(); - } - else - h = mh = 0.0; - - f = (*it)->get_f (); - mf = (*it)->get_mf(); - - if ( h.is_defined() && mh.is_defined() && f.is_defined() && mf.is_defined() ) { - - ef = f.rel_err ( mf ) * 100.0; - - out << (*it)->get_mod_use() - << " " << std::setw(3) << NOMAD::Mesh::get_mesh_index() - << " " << std::setw(4) << (*it)->get_nY() - << " "; - - (*it)->get_Yw ().display ( out , "%12.3g" ); out << " "; - (*it)->get_cond().display ( out , "%12.3g" ); out << " "; - if ( _p.has_constraints() ) { - eh = h.rel_err ( mh ) * 100.0; - h.display ( out , "%14.3g" ); out << " "; - mh.display ( out , "%14.3g" ); out << " "; - eh.display ( out , "%14.3g" ); out << " "; - } - f.display ( out , "%14.3g" ); out << " "; - mf.display ( out , "%14.3g" ); out << " "; - ef.display ( out , "%14.3g" ); - - out << std::endl; - } - - (*it)->clear_model_data(); - } - } -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator_Control.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator_Control.hpp deleted file mode 100644 index 08f762a99..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Evaluator_Control.hpp +++ /dev/null @@ -1,773 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Evaluator_Control.hpp - \brief Control of the blackbox evaluations (headers) - \author Sebastien Le Digabel - \date 2010-04-15 - \see Evaluator_Control.cpp - */ -#ifndef __EVALUATOR_CONTROL__ -#define __EVALUATOR_CONTROL__ - -#include "Barrier.hpp" -#include "Pareto_Front.hpp" -#include "Slave.hpp" -#include "Quad_Model.hpp" - -#ifdef USE_TGP -#include "TGP_Model.hpp" -#endif - -#ifdef R_VERSION -extern "C" { -#include -} -#endif - - -namespace NOMAD { - - /// Control of the blackbox evaluations. - /** - This class allows the evaluation of a list of trial point. - */ - class Evaluator_Control : private NOMAD::Uncopyable { - - private: - - static bool _force_quit; ///< Forces NOMAD to terminate if Ctrl-C is pressed. - static bool _force_evaluation_failure; ///< Forces an evaluation failure. - - const NOMAD::Parameters & _p; ///< Parameters. - NOMAD::Evaluator * _ev; ///< The evaluator. - - NOMAD::Cache * _cache; ///< Cache for true function evaluations. - NOMAD::Cache * _sgte_cache; ///< Cache for surrogate evaluations. - - /// List of points to be evaluated. - std::set _eval_lop; - - /// Flag to enable or disable the model ordering. - bool _model_eval_sort; - - /// Flag equal to \c true if the destructor has to delete \c this->_ev. - bool _del_ev; - - /// Flag equal to \c true if the destructor has to erase the cache. - bool _del_cache; - - /// Flag equal to \c true if the destructor has to erase the cache for surrogates. - bool _del_sgte_cache; - -#ifdef USE_MPI - NOMAD::Eval_Point ** _eval_in_progress; ///< List of evaluations in progress. - int _nb_in_progress; ///< Number of evaluations in progress. - - /// Elop tag. - /** - Unique tag associated to \c this->eval_lop(). - */ - int _elop_tag; - - /// Elop tag for each slave. - /** - _slaves_elop_tags[k] corresponds to the Elop tag for slave \c k. - */ - int * _slaves_elop_tags; - - NOMAD::Slave * _slave; // Slave object for master process -#endif - -#ifdef USE_TGP - NOMAD::TGP_Model * _last_TGP_model; ///< Last TGP model from the model search. -#endif - - NOMAD::Model_Stats _model_ordering_stats; ///< Model ordering stats. - NOMAD::Stats & _stats; ///< Algorithm stats. - - /** - - Lattest tag of a point that has been written for \c display_stats - or \c stats_file. - - It is used to avoid any double display at the end of a run. - */ - mutable int _last_stats_tag; - - /// Same as \c this->_last_stats_bbe for the number of blackbox evaluations. - mutable int _last_stats_bbe; - - /// Last entry in the history file to avoid cache hits. - mutable int _last_history_bbe; - - /// Process an already evaluated Eval_Point. - /** - \param x The point -- \b IN. - \param barrier The barrier -- \b IN/OUT. - \param pareto_front The Pareto front -- \b IN/OUT - (may be NULL). - */ - void process_eval_point ( const NOMAD::Eval_Point & x , - NOMAD::Barrier & barrier , - NOMAD::Pareto_Front * pareto_front ) const; - - /// Save the solution file or update the history file. - /** - \param file_name Name of the file -- \b IN. - \param x Lattest solution -- \b IN. - \param is_sol Flag equal to \c true if the file is - a solution file; otherwise it is a history file. - \param display_bimv Display best infeasible (min. viol.) if \c true - */ - void write_sol_or_his_file ( const std::string & file_name , - const NOMAD::Eval_Point & x , - bool is_sol , - bool display_bimv=false) const; - - /// Display evaluation result. - /** - \param x Lattest evaluation -- \b IN. - \param display_degree Display degree -- \b IN. - \param search Search type -- \b IN. - \param one_eval_success Success for one evaluation -- \b IN. - \param success Success for a series of evaluations -- \b IN. - */ - void display_eval_result ( const NOMAD::Eval_Point & x , - NOMAD::dd_type display_degree , - NOMAD::search_type search , - NOMAD::success_type one_eval_success , - NOMAD::success_type success ) const; - - /// Check if evaluations have to be stopped. - /** - Checks the opportunistic strategy stopping criterion. - \param x The lattest evaluation -- \b IN. - \param search Search type -- \b IN. - \param k Evaluation index -- \b IN. - \param nb_points Number of points to evaluate -- \b IN. - \param stop \c true if the algorithm has to be stopped -- \b IN. - \param display_degree Display degree -- \b IN. - \param one_eval_success Success for one evaluation -- \b IN. - \param success Success for a series of evaluations -- \b IN. - \param init_nb_eval Initial number of evaluations -- \b IN. - \param f0 Initial value of the objective function -- \b IN - (may be undefined). - \param barrier Barrier -- \b IN. - \param nb_success Number of successes -- \b IN/OUT. - \param one_for_luck \c true if one additional evaluation is made - according to parameter \c OPPORTUNISTIC_LUCKY_EVAL - -- \b IN/OUT. - */ - bool stop_evaluations ( const NOMAD::Eval_Point & x , - NOMAD::search_type search , - int k , - int nb_points , - bool stop , - NOMAD::dd_type display_degree , - NOMAD::success_type one_eval_success , - NOMAD::success_type success , - int init_nb_eval , - const NOMAD::Double & f0 , - const NOMAD::Barrier & barrier , - int & nb_success , - bool & one_for_luck ) const; - - /// Check the opportunistic strategy stopping criterion. - /** - \param display_degree Display degree -- \b IN. - \param one_eval_success Success for one evaluation -- \b IN. - \param init_nb_eval Initial number of evaluations -- \b IN. - \param f0 Initial value of the objective function -- \b IN - (may be undefined). - \param barrier Barrier -- \b IN. - \param nb_success Number of successes -- \b IN/OUT. - \param one_for_luck \c true if one additional evaluation is made - according to parameter OPPORTUNISTIC_LUCKY_EVAL - -- \b IN/OUT. - \return A boolean equal to \c true to stop the evaluations; - Otherwise, continue the evaluations. - */ - bool check_opportunistic_criterion ( NOMAD::dd_type display_degree , - NOMAD::success_type one_eval_success , - int init_nb_eval , - const NOMAD::Double & f0 , - const NOMAD::Barrier & barrier , - int & nb_success , - bool & one_for_luck ) const; - - /// Quadratic model ordering (parameter \c MODEL_EVAL_SORT). - /** - \param display_degree Display degree -- \b IN. - \param modified_list To indicate a change in the evaluation list -- \b OUT. - */ - void quad_model_ordering ( NOMAD::dd_type display_degree , - bool & modified_list ); - - /// TGP model ordering (parameter \c MODEL_EVAL_SORT). - /** - \param display_degree Display degree -- \b IN. - \param modified_list To indicate a change in the evaluation list -- \b OUT. - */ - void TGP_model_ordering ( NOMAD::dd_type display_degree , - bool & modified_list ); - - /// Count the output stats (STAT_SUM and STAT_AVG). - /** - \param x Lattest evaluation -- \b IN. - */ - void count_output_stats ( const NOMAD::Eval_Point & x ); - - /// Search a point in the cache. - /** - \param x The point -- \b IN/OUT. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param count_eval Count or not a simulated evaluation -- \b OUT. - \param h_max Maximal feasibility value -- \b IN. - \param display_degree Display degree -- \b IN. - \return A boolean equal to \c true if the point is in cache. - */ - bool cache_check ( const NOMAD::Eval_Point *& x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & count_eval , - const NOMAD::Double & h_max , - NOMAD::dd_type display_degree ) const; - - /// Evaluate a point. - /* - \param x The point -- \b IN/OUT. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param count_eval Count or not the evaluation -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param h_max Maximal feasibility value -- \b IN. - */ - void eval_point ( NOMAD::Eval_Point & x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & count_eval , - bool & stop , - NOMAD::stop_type & stop_reason , - const NOMAD::Double & h_max ); - - - - /// Evaluate points. - /* - \param list_x The list of points -- \b IN/OUT. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param list_count_eval A list of bool for counted evaluations -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param h_max Maximal feasibility value -- \b IN. - */ - void eval_points ( std::list & list_x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - std::list & list_count_eval , - bool & stop , - NOMAD::stop_type & stop_reason , - const NOMAD::Double & h_max ); - - - - - /// Check if a search is opportunistic or not. - /** - \param t Search type -- \b IN. - \return A boolean equal to \c true if the search is opportunistic. - */ - bool is_opportunistic ( NOMAD::search_type t ) const; - - /// Check stopping criteria. - /** - \param search Search type -- \b IN. - \param count_eval Count or not the evaluation -- \b IN. - \param x Lattest evaluation -- \b IN/OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - void check_stopping_criteria ( NOMAD::search_type search , - bool count_eval , - const NOMAD::Eval_Point & x , - bool & stop , - NOMAD::stop_type & stop_reason ) const; - -#ifdef USE_MPI - - /// Receive an evaluation result from a slave. - /** - \param search Search type -- \b IN. - \param x A pointer to the evaluation -- \b OUT. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param slave_rank Slave rank -- \b IN. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - void receive_eval_result ( NOMAD::search_type search , - NOMAD::Eval_Point * x , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - int slave_rank , - bool & stop , - NOMAD::stop_type & stop_reason ); - - /// Check if the evaluation of a point is already in progress. - /** - \param x The point -- \b IN. - \return A boolean equal to \c true if the evaluation - of the point is already in progress. - */ - bool already_in_progress ( const NOMAD::Eval_Point & x ) const; - -#endif - - /// Evaluate a list of points. - /** - - "Evaluate a list of points" is abbreviated with "eval_lop". - - This method is private and is called by the public eval_lop method. - - This method is defined twice in the .cpp for scalar and parallel versions. - - The method clears the list of points \c this->_eval_lop. - \param search Search type -- \b IN. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param new_feas_inc Pointer to the new feasible incumbent -- \b OUT. - \param new_infeas_inc Pointer to the new infeasible incumbent -- \b OUT. - \param success Success for these evaluations -- \b OUT. - \param evaluated_pts List of processed points -- \b OUT. - */ - void private_eval_list_of_points - ( NOMAD::search_type search , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & stop , - NOMAD::stop_type & stop_reason , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc , - NOMAD::success_type & success , - std::list & evaluated_pts ); - - -#ifdef MODEL_STATS - /// Display stats on an evaluation for which a model has been used. - /** - \param evaluated_pts List of evaluated points -- \b IN. - */ - void display_model_stats - ( const std::list & evaluated_pts ) const; -#endif - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param stats Stats -- \b IN/OUT. - \param ev Pointer to the Evaluator -- \b IN (may be \c NULL). - \param cache Pointer to the cache -- \b IN/OUT (may be \c NULL). - \param sgte_cache Pointer to the surrogate cache -- \b IN/OUT (may be \c NULL). - */ - Evaluator_Control ( const NOMAD::Parameters & p , - NOMAD::Stats & stats , - NOMAD::Evaluator * ev , - NOMAD::Cache * cache , - NOMAD::Cache * sgte_cache ); - - /// Destructor. - virtual ~Evaluator_Control ( void ); - - /// Force quit (called by pressing Ctrl-C). - static void force_quit ( void ) - { - Evaluator_Control::_force_quit = true; - } - - /// Force evaluation failure. - static void force_evaluation_failure ( void ) - { - Evaluator_Control::_force_evaluation_failure = true; - } - - - /// Display in stats file according to parameter \c STATS_FILE. - /** - \param file_name Name of the output file -- \b IN. - \param x Pointer to the lattest evaluation -- \b IN (may be \c NULL). - \param feasible Equal to \c true if \c x is feasible -- \b IN. - \param multi_obj Pointer to several objective values -- \b IN (may be \c NULL). - */ - void stats_file ( const std::string & file_name , - const NOMAD::Eval_Point * x , - bool feasible , - const NOMAD::Point * multi_obj ) const; - - /// Display stats during NOMAD::Mads::run() for minimal and normal display. - /** - \param header Boolean equal to \c true if a header has to be displayed - -- \b IN. - \param out Display -- \b IN. - \param stats List of stats to display -- \b IN. - \param x Pointer to the lattest evaluation -- \b IN (may be \c NULL). - \param feasible Equal to \c true if \c x is feasible -- \b IN. - \param multi_obj Pointer to several objective values -- \b IN (may be \c NULL). - */ - void display_stats ( bool header , - const NOMAD::Display & out , - const std::list & stats , - const NOMAD::Eval_Point * x , - bool feasible , - const NOMAD::Point * multi_obj ) const; - - /// Display a real according to parameter \c DISPLAY_STATS. - /** - \param out Display -- \b IN. - \param d The real to display -- \b IN. - \param format The format - -- \b IN -- \b optional (default = empty string). - */ - void display_stats_real ( const NOMAD::Display & out , - const NOMAD::Double & d , - const std::string & format = "" ) const; - - /// Display a number according to its type \c DISPLAY_STATS. - /** - \param out Display -- \b IN. - \param d The number to display -- \b IN. - \param bbType The type to display -- \b IN. - */ - void display_stats_type ( const NOMAD::Display & out , - const NOMAD::Double & d , - const NOMAD::bb_input_type & bbType ) const; - - /// Display an integer according to parameter \c DISPLAY_STATS. - /** - \param out Display -- \b IN. - \param i The integer to display -- \b IN. - \param max_i Maximal value of \c i used to determine the display width - -- \b IN -- \b optional (default = \c -1). - \param format The format - -- \b IN -- \b optional (default = empty string). - */ - void display_stats_int ( const NOMAD::Display & out , - int i , - int max_i = -1 , - const std::string & format = "" ) const; - - /// Display a point according to parameter \c DISPLAY_STATS. - /** - \param out Display -- \b IN. - \param display_stats List of stats to display -- \b IN. - \param it Iterator for the list \c stats -- \b IN/OUT. - \param x Pointer to the point -- \b IN (may be \c NULL). - \param bbType Vector of input type -- \b IN -- \b optional (default = \c empty vector). - */ - void display_stats_point ( const NOMAD::Display & out , - const std::list & display_stats , - std::list::const_iterator & it , - const NOMAD::Point * x , - const std::vector & bbType = std::vector (0) ) const; - - /// Display model ordering stats ( parameter \c MODEL_EVAL_SORT ). - /** - \param out Display -- \b IN. - */ - void display_model_ordering_stats ( const NOMAD::Display & out ) const - { - out << _model_ordering_stats << std::endl; - } - - /// Save the caches. - /** - \param overwrite A boolean equal to \c true if the cache files - may be overwritten -- \b IN. - \return A boolean equal to \c true if the caches could be saved. - */ - bool save_caches ( bool overwrite ); - - /// Update the solution file. - /** - \param x The lattest solution -- \b IN. - \param display_bimv Required to display least infeasible (default=false) -- \b IN - */ - void write_solution_file ( const NOMAD::Eval_Point & x , bool display_bimv=false) const; - - /// Update a barrier from another barrier. - /** - Update barrier \c b1 from points in barrier \c b2 and treat - these points as evaluations (used in VNS search). - \param b1 First barrier -- \b IN/OUT. - \param b2 Second barrier -- \b IN. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param display_degree Display degree -- \b IN. - \param search Search type -- \b IN. - \return Success for these simulated evaluations. - */ - NOMAD::success_type process_barrier_points ( NOMAD::Barrier & b1 , - const NOMAD::Barrier & b2 , - NOMAD::Pareto_Front * pareto_front , - NOMAD::dd_type display_degree , - NOMAD::search_type search ) const; - /// Access to the cache (#1). - /** - Non-const version. - \return The cache. - */ - NOMAD::Cache & get_cache ( void ) { return *_cache; } - - /// Access to the cache (#2). - /** - Const version. - \return The cache. - */ - const NOMAD::Cache & get_cache ( void ) const { return *_cache; } - - /// Access to the surrogate cache (#1). - /** - Non-const version. - \return The surrogate cache. - */ - NOMAD::Cache & get_sgte_cache ( void ) { return *_sgte_cache; } - - /// Access to the surrogate cache (#2). - /** - Const version. - \return The surrogate cache. - */ - const NOMAD::Cache & get_sgte_cache ( void ) const { return *_sgte_cache; } - - /// Access to the evaluator. - /** - \return The evaluator. - */ - NOMAD::Evaluator * get_evaluator ( void ) const { return _ev; } - - /// Access to \c _last_stats_tag. - /** - \return \c _last_stats_tag. - */ - int get_last_stats_tag ( void ) const { return _last_stats_tag; } - - /// Access to _last_stats_bbe. - /** - \return _last_stats_bbe. - */ - int get_last_stats_bbe ( void ) const { return _last_stats_bbe; } - - /// Set the evaluator. - /** - \param e A pointer to the evaluator -- \b IN. - */ - void set_evaluator ( NOMAD::Evaluator * e ) { _ev = e; } - -#ifdef USE_TGP - /// Set the last TGP model from the model search. - /** - \param m The last TGP model -- \b IN. - */ - void set_last_TGP_model ( NOMAD::TGP_Model * m ) { _last_TGP_model = m; } -#endif - - /// Reset. - void reset ( void ); - - - /// Order eval list of points based on surrogate (1st) or model (2nd) - /** - \param search Search type -- \b IN. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - */ - void ordering_lop - ( NOMAD::search_type search , // IN : search type - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::Barrier & true_barrier , // IN/OUT: truth barrier - NOMAD::Barrier & sgte_barrier // IN/OUT: surrogate barrier - ); - - - - - /// Evaluation of a list of points (public version that calls the private version). - /** - \param search Search type -- \b IN. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param new_feas_inc Pointer to the new feasible incumbent -- \b OUT. - \param new_infeas_inc Pointer to the new infeasible incumbent -- \b OUT. - \param success Success for this series of evaluations -- \b OUT. - \param evaluated_pts List of processed points -- \b OUT. - */ - void eval_list_of_points - ( NOMAD::search_type search , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & stop , - NOMAD::stop_type & stop_reason , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc , - NOMAD::success_type & success , - std::list * evaluated_pts = NULL ); - - /// Add a point to the list of points to be evaluated. - /** - - The point has to be a dynamic object. - - It can be deleted into the method and be \c NULL after that. - - The point is also snapped to bounds. - - Periodic variables are checked. - \param x The point -- \b IN/OUT. - \param display_degree Display degree -- \b IN. - \param snap_to_bounds Boolean equal to \c true if the - point has to be snapped to bounds -- \b IN. - \param f_sgte Objective value for the surrogate -- \b IN - (may be undefined). - \param h_sgte Feasibility value for the surrogate -- \b IN - (may be undefined). - \param f_model Objective value for the model -- \b IN - (may be undefined). - \param h_model Feasibility value for the model -- \b IN - (may be undefined). - - */ - void add_eval_point ( NOMAD::Eval_Point *& x , - NOMAD::dd_type display_degree , - bool snap_to_bounds , - const NOMAD::Double & f_sgte , - const NOMAD::Double & h_sgte , - const NOMAD::Double & f_model , - const NOMAD::Double & h_model ); - - /// Display the list of evaluation points \c _eval_lop. - /** - \param t Search type -- \b IN - -- \b optional (default = NOMAD::UNDEFINED_SEARCH ). - */ - void display_eval_lop ( NOMAD::search_type t = NOMAD::UNDEFINED_SEARCH ) const; - - /// Access to the number of evaluation points. - /** - \return The number of evaluation points. - */ - int get_nb_eval_points ( void ) const - { - return static_cast ( _eval_lop.size() ); - } - - /// Access to the list of evaluation points. - /** - \return The list of evaluation points. - */ - const std::set & get_eval_lop ( void ) const - { - return _eval_lop; - } - - /// Clear the list of evaluation points. - void clear_eval_lop ( void ) { reduce_eval_lop(0); } - - /// Reduce the list of evaluation points. - /** - \param n New size of the list -- \b IN. - */ - void reduce_eval_lop ( int n ); - - /// Enable the model ordering. - void enable_model_eval_sort ( void ) { _model_eval_sort = true; } - - /// Disable the model ordering. - void disable_model_eval_sort ( void ) { _model_eval_sort = false; } - -#ifdef USE_MPI - - /// Access to the number of evaluations in progress. - /** - \return the number of evaluations in progress. - */ - int get_nb_eval_in_progress ( void ) const { return _nb_in_progress; } - - /// Wait for evaluations in progress. - /** - \param search Search type -- \b IN. - \param true_barrier Barrier for true evaluations -- \b IN/OUT. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN/OUT. - \param pareto_front A pointer to the Pareto front -- \b IN/OUT - (may be \c NULL). - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Success for these evaluations -- \b OUT. - \param evaluated_pts List of processed points -- \b OUT. - */ - void wait_for_evaluations ( NOMAD::search_type search , - NOMAD::Barrier & true_barrier , - NOMAD::Barrier & sgte_barrier , - NOMAD::Pareto_Front * pareto_front , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - std::list - & evaluated_pts ); -#endif - }; -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Exception.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Exception.cpp deleted file mode 100644 index 0ffed678c..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Exception.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Exception.cpp - \brief custom class for exceptions (implementation) - \author Sebastien Le Digabel - \date 2010-03-29 - \see Exception.hpp -*/ -#include "Exception.hpp" - -/*----------------------------------------------------------------*/ -/* NOMAD::Exception::what() */ -/*----------------------------------------------------------------*/ -const char * NOMAD::Exception::what ( void ) const throw() -{ - std::ostringstream oss; - oss << "NOMAD::Exception thrown (" << _file << ", " << _line << ")"; - if ( !_what.empty() ) - oss << " " << _what; - _what = oss.str(); - return _what.c_str(); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Exception.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Exception.hpp deleted file mode 100644 index 0ee437d37..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Exception.hpp +++ /dev/null @@ -1,95 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Exception.hpp - \brief Custom class for exceptions (headers) - \author Sebastien Le Digabel - \date 2010-03-29 - \see Exception.cpp -*/ -#ifndef __NOMAD_EXCEPTION__ -#define __NOMAD_EXCEPTION__ - -#include - -namespace NOMAD { - - /// Custom class for exceptions. - /** - NOMAD uses this type of exceptions. - It indicates the file and line number at which a throw is made. - - \b Example - - \code - throw NOMAD::Exception ( __FILE__ , __LINE__ , "an error message" ); - \endcode - */ - class Exception : public std::exception { - - private: - - mutable std::string _what; ///< Error message. - std::string _file; ///< File where the exception is thrown. - int _line; ///< Line number at which the exception is thrown. - - public: - - /// Constructor. - /** - \param file A string corresponding to the file where the - exception is thrown -- \b IN - \param line An integer corresponding to the line number - at which the exception is thrown -- \b IN. - \param msg A string corresponding to the error message -- \b IN. - */ - Exception ( const std::string & file , int line , const std::string & msg ) - : _what ( msg ) , - _file ( file ) , - _line ( line ) {} - - /// Destructor. - virtual ~Exception ( void ) throw() {} - - /// Access to the error message. - /** - \return A string with the error message. - */ - const char * what ( void ) const throw(); - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Extended_Poll.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Extended_Poll.cpp deleted file mode 100644 index 9cdd12faa..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Extended_Poll.cpp +++ /dev/null @@ -1,1255 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Extended_Poll.cpp - \brief Extended poll for categorical variables (implementation) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Extended_Poll.hpp - */ -#include "Extended_Poll.hpp" - -/*----------------------------------------------------------------*/ -/* destructor */ -/*----------------------------------------------------------------*/ -NOMAD::Extended_Poll::~Extended_Poll ( void ) -{ - std::set::const_iterator it , end = _signatures.end(); - for ( it = _signatures.begin() ; it != end ; ++it ) - delete (*it).get_signature(); - poll_reset(); -} - -/*----------------------------------------------------------------*/ -/* reset */ -/*----------------------------------------------------------------*/ -void NOMAD::Extended_Poll::reset ( void ) -{ - // successful directions: - std::set::const_iterator it , end = _signatures.end(); - for ( it = _signatures.begin() ; it != end ; ++it ) - { - (*it).get_signature()->reset_feas_success_dir(); - (*it).get_signature()->reset_infeas_success_dir(); - } - - // poll_reset: - poll_reset(); -} - -/*----------------------------------------------------------------*/ -/* poll reset: before the extended poll is launched */ -/*----------------------------------------------------------------*/ -void NOMAD::Extended_Poll::poll_reset ( void ) -{ - _poll_signatures.clear(); - std::list::const_iterator end = _extended_points.end(); - for ( std::list::iterator it = _extended_points.begin() ; - it != end ; ++it ) - if ( !(*it)->is_in_cache() ) - delete *it; - _extended_points.clear(); -} - -/*----------------------------------------------------------------*/ -/* get, check and register the extended point and its signature */ -/* created by the user in construct_extended_points() */ -/*----------------------------------------------------------------*/ -void NOMAD::Extended_Poll::add_extended_poll_point ( NOMAD::Point & ep , - NOMAD::Signature & s ) -{ - // new signature: - // -------------- - NOMAD::Signature * new_s = new NOMAD::Signature (s); - - // . 's' can be standard, but its copy 'new_s' is not - - // . a standard signature will never be inserted into _signatures, - // since standard signatures are handled and deleted by the Parameters class - - { - // signature already registered ? - NOMAD::Signature_Element se ( new_s ); - std::set::const_iterator it = _signatures.find ( se ); - - // signature already registered: - if ( it != _signatures.end() ) - { - - // success directions eventually included in new_s are not considered - // since new_s is the copy of s, which is user provided - - delete new_s; - new_s = it->get_signature(); - } - - // new signature to register: - else - _signatures.insert ( se ); - - _poll_signatures.insert ( NOMAD::Signature_Element ( new_s ) ); - } - - // new eval point: - // --------------- - NOMAD::Eval_Point * pt = new NOMAD::Eval_Point; - pt->set ( ep , _p.get_bb_nb_outputs() ); - pt->set_signature ( new_s ); - - for ( int i = 0 ; i < pt->get_n() ; ++i ) - { - if ( (pt->get_signature()->get_input_type())[i] != NOMAD::CONTINUOUS && ! (*pt)[i].is_integer() ) - - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , - "NOMAD::Extended_Poll::add_extended_points(): the categorical variables of the added point must be an integer." ); - } - - - _extended_points.push_back ( pt ); -} - -/*----------------------------------------------------------------*/ -/* check the extended poll trigger */ -/*----------------------------------------------------------------*/ -/* . return true if the extended poll has to be performed */ -/* . private method */ -/*----------------------------------------------------------------*/ -bool NOMAD::Extended_Poll::check_trigger ( const NOMAD::Eval_Point * old_bf , - const NOMAD::Eval_Point * old_bi , - const NOMAD::Eval_Point * y ) const -{ - if ( !y->is_in_cache() || - !y->is_eval_ok() || - !y->get_f().is_defined() || - !y->get_h().is_defined() ) - return false; - - // y is feasible: - // -------------- - if ( y->is_feasible ( _p.get_h_min() ) ) - { - - if ( !old_bf ) - return true; - - return check_trigger_on_f ( old_bf->get_f() , y->get_f() ); - } - - // y is infeasible: - // ---------------- - if ( !old_bf && !old_bi ) - return true; - - if ( !old_bf ) - return ( y->get_h() < old_bi->get_h() ); - - if ( !old_bi ) - return check_trigger_on_f ( old_bf->get_f() , y->get_f() ); - - if ( y->get_h() >= old_bi->get_h() ) - return false; - - // y is infeasible, and old best feasible and best infeasible solutions are - // available: the extended poll will be performed if the y point in the - // (h,f) space is below the line joining [ h(old_bf) , f(old_bf)+trigger ] - // to [ h(old_bi) , f(old_bi)+trigger ] : - const NOMAD::Double & hA = old_bf->get_h(); - NOMAD::Double fA = old_bf->get_f(); - - const NOMAD::Double & hB = old_bi->get_h(); - NOMAD::Double fB = old_bi->get_f(); - - const NOMAD::Double & hy = y->get_h(); - const NOMAD::Double & fy = y->get_f(); - - const NOMAD::Double & ept = _p.get_extended_poll_trigger(); - - if ( _p.get_relative_ept() && fA != 0.0 && fB != 0.0 && fy != 0.0 ) - { - fA = fA + fA.abs() * ept; - fB = fB + fB.abs() * ept; - } - else - { - fA = fA + ept; - fB = fB + ept; - } - - // line joining [h(A),f(A)] to [h(B),f(B)]: f=a*h+b : - NOMAD::Double a = (fA-fB) / (hA-hB); - NOMAD::Double b = fA - a * hA; - - return fy < a*hy + b; -} - -/*-------------------------------------------------------------------*/ -/* check only the f values for the extended poll trigger (private) */ -/*-------------------------------------------------------------------*/ -bool NOMAD::Extended_Poll::check_trigger_on_f ( const NOMAD::Double & old_f , - const NOMAD::Double & new_f ) const -{ - if ( new_f <= old_f ) - return true; - - // relative comparison (both values are != 0): - if ( _p.get_relative_ept() && old_f != 0.0 && new_f != 0.0 ) - return ( new_f < old_f + old_f.abs() * _p.get_extended_poll_trigger() ); - - // absolute comparison: - return ( new_f < old_f + _p.get_extended_poll_trigger() ); -} - -/*----------------------------------------------------------------*/ -/* descent from the extended poll center (private) */ -/*----------------------------------------------------------------*/ -void NOMAD::Extended_Poll::descent ( const NOMAD::Eval_Point * y , - Mads & mads , - int & nb_ext_poll_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - - - NOMAD::Stats & stats = mads.get_stats(); - bool has_sgte = _p.has_sgte(); - bool opt_only_sgte = _p.get_opt_only_sgte(); - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - - // get the signature: - NOMAD::Signature * signature = y->get_signature(); - - - // displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - - std::ostringstream oss; - oss << NOMAD::EXTENDED_POLL << " descent"; - if ( has_sgte ) - oss << " (on surrogates)"; - - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - - out << " iteration = " << stats.get_iterations() << std::endl - << " blackbox eval. = " << stats.get_bb_eval() << std::endl; - if ( has_sgte ) - out << " sgte eval. = " << stats.get_sgte_eval() << std::endl; - out << " mesh indices = (" << signature->get_mesh()->get_mesh_indices() << " )" << std::endl - << "ext. poll center = ( "; - y->Point::display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " ) f=" << y->get_f() << " h=" << y->get_h() << std::endl << std::endl; - } - - - - // create the descent parameters: - NOMAD::Parameters descent_p ( signature , _p.out() ); - set_descent_parameters ( y , stats , descent_p ); - - - // mesh indices before the descent --> restore after descent - NOMAD::Point mesh_indices = signature->get_mesh()->get_mesh_indices(); - - // limit mesh index before the descent --> restore after descent - int limit_mesh_index = signature->get_mesh()->get_limit_mesh_index(); - - - // Set mesh indices to 0 - NOMAD::Point delta( signature->get_n(), 0 ); - descent_p.get_signature()->get_mesh()->set_mesh_indices( delta ); - - // Use best_feasible or best_infeasible limit mesh index as a termination criterion for descent - const NOMAD::Eval_Point * old_bf = mads.get_best_feasible(); - const NOMAD::Eval_Point * old_bi = mads.get_best_infeasible(); - int l1=0,l2=0; - if ( old_bf ) - l1 = static_cast((old_bf->get_signature()->get_mesh()->get_min_mesh_indices())[0].value()); // index same for all variables when using categorical variable - else if ( old_bi ) - l2 = static_cast((old_bi->get_signature()->get_mesh()->get_min_mesh_indices())[0].value()); - descent_p.get_signature()->get_mesh()->set_limit_mesh_index( min( l1, l2) ); - - - - // Evaluator_Control object: - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // descent: run MADS: - // ------------------ - NOMAD::Mads EP_mads ( descent_p , - ev_control.get_evaluator () , - NULL , - &ev_control.get_cache () , - &ev_control.get_sgte_cache() ); -#ifdef DEBUG - out << std::endl << NOMAD::open_block ( "MADS run (ext. poll)" ) << std::endl; -#endif - - NOMAD::Mads::set_flag_reset_barriers ( true ); - NOMAD::Mads::set_flag_reset_mesh ( false ); - - NOMAD::stop_type st = EP_mads.run(); - - NOMAD::Mads::set_flag_reset_mesh ( true ); - -#ifdef DEBUG - out << std::endl << NOMAD::close_block ( "end of run (ext. poll)" ) << std::endl; -#endif - - // Restore mesh indices and limit mesh index (termination criterion) - signature->get_mesh()->set_mesh_indices( mesh_indices ); - signature->get_mesh()->set_limit_mesh_index( limit_mesh_index ); - - - // update stats: - const NOMAD::Stats & EP_stats = EP_mads.get_stats(); - stats.update ( EP_stats , true ); // for_search = true - stats.add_ext_poll_bb_eval ( EP_stats.get_bb_eval() ); - stats.add_ext_poll_descent (); - - // check MADS stopping criteria: - if ( st == NOMAD::CTRL_C || - st == NOMAD::ERROR || - st == NOMAD::UNKNOWN_STOP_REASON || - st == NOMAD::FEAS_REACHED || - st == NOMAD::MAX_CACHE_MEMORY_REACHED || - st == NOMAD::STAT_SUM_TARGET_REACHED || - st == NOMAD::MAX_SGTE_EVAL_REACHED || - st == NOMAD::F_TARGET_REACHED || - st == NOMAD::MAX_SIM_BB_EVAL_REACHED || - st == NOMAD::MAX_TIME_REACHED || - st == NOMAD::MAX_BB_EVAL_REACHED ) - { - stop_reason = st; - stop = true; - } - - // Pareto front: - NOMAD::Pareto_Front * pareto_front = mads.get_pareto_front(); - - // the barriers: - NOMAD::Barrier & true_barrier = mads.get_true_barrier(); - NOMAD::Barrier & sgte_barrier = mads.get_sgte_barrier(); - - // surrogate evaluations: perform at most one true evaluation: - if ( has_sgte && !opt_only_sgte ) - { - - if ( !stop ) - { - - // remember old best surrogates incumbents: - const NOMAD::Eval_Point * old_sgte_bf = sgte_barrier.get_best_feasible (); - const NOMAD::Eval_Point * old_sgte_bi = sgte_barrier.get_best_infeasible(); - - // update the surrogate barrier - // (no need to invoke Evaluator_Control::process_barrier_points() here - // since only surrogate evaluations have been made): - sgte_barrier.insert ( EP_mads.get_sgte_barrier() ); - NOMAD::success_type sgte_succ = sgte_barrier.get_success(); - sgte_barrier.update_and_reset_success(); - - // we generate only a true trial point if the - // surrogates improved the surrogate barrier: - if ( sgte_succ != NOMAD::UNSUCCESSFUL ) - { - - // choose the best surrogate point(s) where to evaluate the true function: - const NOMAD::Eval_Point * sgte_bf = sgte_barrier.get_best_feasible (); - const NOMAD::Eval_Point * sgte_bi = sgte_barrier.get_best_infeasible(); - - std::list candidates; - - if ( sgte_bf && ( !y->is_feasible(_p.get_h_min()) || sgte_bf != old_sgte_bf ) ) - candidates.push_back ( sgte_bf ); - - if ( sgte_bi && sgte_bi != old_sgte_bi ) - candidates.push_back ( sgte_bi ); - - // generate the new trial points: - NOMAD::Eval_Point * sk; - std::list::const_iterator it , end = candidates.end(); - for ( it = candidates.begin() ; it != end ; ++it ) - { - - // display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "ext. poll surrogate candidate: " << **it << std::endl; - - sk = new NOMAD::Eval_Point; - sk->set ( signature->get_n() , _p.get_bb_nb_outputs() ); - sk->set_signature ( signature ); - sk->Point::operator = ( **it ); - - // add the new point to the list of trial points: - ev_control.add_eval_point ( sk , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - // eval_list_of_points: - // -------------------- - success = NOMAD::UNSUCCESSFUL; - new_feas_inc = new_infeas_inc = NULL; - - ev_control.eval_list_of_points ( NOMAD::EXTENDED_POLL , - true_barrier , - sgte_barrier , - pareto_front , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - // number of search points (0 or 1 or 2): - nb_ext_poll_pts += static_cast ( candidates.size() ); - } - } - } - - // true evaluations (or surrogate evaluations if opt_only_sgte==true): - else - { - - const NOMAD::Barrier & active_barrier = mads.get_active_barrier(); - - // for the update of new_feas_inc and new_infeas_inc (1/2): - const NOMAD::Eval_Point * old_feasible_incumbent - = active_barrier.get_best_feasible(); - const NOMAD::Eval_Point * old_infeasible_incumbent - = active_barrier.get_best_infeasible(); - - // update barriers and process extended poll points: - NOMAD::success_type sgte_succ - = ev_control.process_barrier_points ( sgte_barrier , - EP_mads.get_sgte_barrier() , - pareto_front , - display_degree , - NOMAD::EXTENDED_POLL ); - - NOMAD::success_type true_succ - = ev_control.process_barrier_points ( true_barrier , - EP_mads.get_true_barrier() , - pareto_front , - display_degree , - NOMAD::EXTENDED_POLL ); - - // update of new_feas_inc and new_infeas_inc (2/2): - const NOMAD::Eval_Point * bf = active_barrier.get_best_feasible (); - const NOMAD::Eval_Point * bi = active_barrier.get_best_infeasible(); - if ( bf && bf != old_feasible_incumbent ) - new_feas_inc = bf; - if ( bi && bi != old_infeasible_incumbent ) - new_infeas_inc = bi; - - // number of extended poll points and success: - if ( opt_only_sgte ) - { - nb_ext_poll_pts += EP_mads.get_stats().get_sgte_eval(); - success = sgte_succ; - } - else - { - nb_ext_poll_pts += EP_mads.get_stats().get_eval(); - success = true_succ; - } - } - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of " << NOMAD::EXTENDED_POLL << " descent (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } -} - -/*----------------------------------------------------------------*/ -/* create the descent parameters (private) */ -/*----------------------------------------------------------------*/ -void NOMAD::Extended_Poll::set_descent_parameters -( const NOMAD::Eval_Point * y , - const NOMAD::Stats & stats , - NOMAD::Parameters & descent_p ) const -{ - - // extended poll center signature - // (will be the temporary standard signature): - NOMAD::Signature * epc_signature = y->get_signature(); - if ( !epc_signature ) - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , - "Extended_Poll::set_descent_parameters(): ext. poll center has no signature" ); - - // we set all the parameters: - descent_p.set_DIMENSION ( epc_signature->get_n() ); - descent_p.set_BB_INPUT_TYPE ( epc_signature->get_input_types() ); - descent_p.set_LOWER_BOUND ( epc_signature->get_lb() ); - descent_p.set_UPPER_BOUND ( epc_signature->get_ub() ); - descent_p.set_FIXED_VARIABLE ( epc_signature->get_fixed_variables() ); - descent_p.set_PERIODIC_VARIABLE ( epc_signature->get_periodic_variables() ); - descent_p.set_VARIABLE_GROUP ( epc_signature->get_var_groups() ); - descent_p.set_BB_OUTPUT_TYPE ( _p.get_bb_output_type() ); - descent_p.set_DIRECTION_TYPE ( _p.get_direction_types() ); - descent_p.set_SEC_POLL_DIR_TYPE ( _p.get_sec_poll_dir_types() ); - - - { - const std::list & bb_exe = _p.get_bb_exe(); - descent_p.set_BB_EXE ( bb_exe ); - std::list::const_iterator it , end = bb_exe.end(); - for ( it = bb_exe.begin() ; it != end ; ++it ) - descent_p.set_SGTE_EXE ( *it , _p.get_sgte_exe ( *it ) ); - } - - descent_p.set_PROBLEM_DIR ( _p.get_problem_dir() ); - descent_p.set_TMP_DIR ( _p.get_tmp_dir() ); - descent_p.set_SGTE_COST ( _p.get_sgte_cost() ); - descent_p.set_SGTE_EVAL_SORT ( _p.get_sgte_eval_sort() ); - descent_p.set_X0 ( *y ); - - bool has_sgte = _p.has_sgte(); - if ( has_sgte ) - { - descent_p.reset_f_target(); - descent_p.set_HAS_SGTE ( true ); - descent_p.set_OPT_ONLY_SGTE ( true ); - descent_p.set_STOP_IF_FEASIBLE ( false ); - descent_p.set_MODEL_SEARCH ( false ); - descent_p.set_MODEL_EVAL_SORT ( NOMAD::NO_MODEL ); - } - else - { - descent_p.set_F_TARGET ( _p.get_f_target() ); - descent_p.set_STOP_IF_FEASIBLE ( _p.get_stop_if_feasible() ); - descent_p.set_MODEL_EVAL_SORT ( _p.get_model_eval_sort()); - descent_p.set_MODEL_SEARCH (_p.has_model_search()); - - - } - - descent_p.set_LH_SEARCH ( 0 , 0 ); - - int bbe = stats.get_bb_eval(); - int sgte_eval = stats.get_sgte_eval(); - - { - int p_max_bbe = _p.get_max_bb_eval(); - if ( p_max_bbe > 0 ) - descent_p.set_MAX_BB_EVAL ( p_max_bbe - bbe ); - - int p_max_sgte_eval = _p.get_max_sgte_eval(); - if ( p_max_sgte_eval > 0 ) - descent_p.set_MAX_SGTE_EVAL ( p_max_sgte_eval - sgte_eval ); - - int p_max_eval = _p.get_max_eval(); - if ( p_max_eval > 0 ) - descent_p.set_MAX_EVAL ( p_max_eval - stats.get_eval() ); - - int p_max_sbe = _p.get_max_sim_bb_eval(); - if ( p_max_sbe > 0 ) - descent_p.set_MAX_SIM_BB_EVAL ( p_max_sbe - stats.get_sim_bb_eval() ); - - int p_max_time = _p.get_max_time(); - if ( p_max_time > 0 ) - descent_p.set_MAX_TIME ( p_max_time - stats.get_real_time() ); - - NOMAD::Double p_sst = _p.get_stat_sum_target(); - if ( p_sst.is_defined() ) - descent_p.set_STAT_SUM_TARGET ( p_sst - stats.get_stat_sum() ); - } - - descent_p.set_OPPORTUNISTIC_EVAL ( _p.get_opportunistic_eval() ); - descent_p.set_BB_INPUT_INCLUDE_SEED ( _p.get_bb_input_include_seed() ); - descent_p.set_BB_INPUT_INCLUDE_TAG ( _p.get_bb_input_include_tag() ); - descent_p.set_BB_REDIRECTION ( _p.get_bb_redirection() ); - - descent_p.set_EXTENDED_POLL_ENABLED ( false ); - descent_p.set_USER_CALLS_ENABLED ( false ); - - descent_p.set_H_MAX_0 ( _p.get_h_max_0() ); - descent_p.set_H_MIN ( _p.get_h_min() ); - descent_p.set_H_NORM ( _p.get_h_norm() ); - descent_p.set_RHO ( _p.get_rho() ); - descent_p.set_SNAP_TO_BOUNDS ( _p.get_snap_to_bounds() ); - descent_p.set_MAX_CACHE_MEMORY ( _p.get_max_cache_memory() ); - descent_p.set_SPECULATIVE_SEARCH ( _p.get_speculative_search() ); - descent_p.set_OPPORTUNISTIC_LUCKY_EVAL ( _p.get_opportunistic_lucky_eval() ); - descent_p.set_OPPORTUNISTIC_MIN_EVAL ( _p.get_opportunistic_min_eval() ); - descent_p.set_OPPORTUNISTIC_MIN_F_IMPRVMT ( _p.get_opportunistic_min_f_imprvmt() ); - descent_p.set_OPPORTUNISTIC_MIN_NB_SUCCESS ( _p.get_opportunistic_min_nb_success() ); - - if (_p.eval_points_as_block()) - descent_p.set_BB_MAX_BLOCK_SIZE( _p.get_bb_max_block_size() ); - - - descent_p.set_CACHE_FILE ( _p.get_cache_file() ); - descent_p.set_SGTE_CACHE_FILE ( _p.get_sgte_cache_file() ); - descent_p.set_CACHE_SAVE_PERIOD ( _p.get_cache_save_period() ); - - descent_p.set_ADD_SEED_TO_FILE_NAMES ( _p.get_add_seed_to_file_names() ); - - descent_p.set_DISPLAY_ALL_EVAL(_p.get_display_all_eval()); - if ( _p.out().get_poll_dd() == NOMAD::FULL_DISPLAY ) - descent_p.set_DISPLAY_DEGREE ( NOMAD::NORMAL_DISPLAY ); - else if (_p.out().get_poll_dd() == NOMAD::NORMAL_DISPLAY ) - descent_p.set_DISPLAY_DEGREE ( NOMAD::MINIMAL_DISPLAY ); - else - descent_p.set_DISPLAY_DEGREE ( _p.out().get_poll_dd()); - - // Stats style modified - if ( has_sgte ) - descent_p.set_DISPLAY_STATS ( NOMAD::itos(sgte_eval) + "+SGTE OBJ (ExtendedPoll---surrogate)" ); - else - { - std::list ds = _p.get_display_stats(); - std::list::iterator it = ds.begin(); - std::list::const_iterator end = ds.end(); - std::string s_bbe = NOMAD::itos(bbe) + "+"; - while ( it != end ) - { - if (*it == "BBE") - ds.insert ( it , s_bbe ); - ++it; - } - ds.push_back ( " (ExtendedPoll)" ); - descent_p.set_DISPLAY_STATS ( ds ); - } - - // STATS_FILE: - if ( has_sgte ) - descent_p.set_STATS_FILE ( _p.get_stats_file_name() , NOMAD::itos(sgte_eval) + "+SGTE OBJ (ExtendedPoll---surrogate)" ); - else - { - std::list sf = _p.get_stats_file(); - std::list::iterator it = sf.begin(); - std::list::const_iterator end = sf.end(); - std::string s_bbe = NOMAD::itos(bbe) + "+"; - while ( it != end ) - { - if ( *it == "BBE" ) - sf.insert ( it , s_bbe ); - ++it; - } - sf.push_back ( " (ExtendedPoll)" ); - descent_p.set_STATS_FILE ( _p.get_stats_file_name() , sf ); - } - - // Mesh: - { - const OrthogonalMesh * mesh = epc_signature->get_mesh(); - descent_p.set_MIN_MESH_SIZE ( mesh->get_min_mesh_size() ); - descent_p.set_MIN_POLL_SIZE ( mesh->get_min_poll_size() ); - descent_p.set_INITIAL_POLL_SIZE ( mesh->get_initial_poll_size() , false ); - - } - - // check the parameters: - try - { - descent_p.check ( false , // remove_history_file = false - false , // remove_solution_file = false - false ); // remove_stats_file = false - } - catch ( NOMAD::Exception & e ) - { - std::ostringstream err; - err << "-- " << e.what(); - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err.str() ); - } - -} - -/*----------------------------------------------------------------*/ -/* evaluation of an extended poll point (private) */ -/*----------------------------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Extended_Poll::eval_epp -( NOMAD::Eval_Point * y , - Mads & mads , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) const -{ - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - - // initial display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << NOMAD::open_block ( "extended poll point eval" ) << std::endl - << "extended poll point = ( "; - y->Point::display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " )" << std::endl; - } - - // add the eval point to the evaluator control: - ev_control.add_eval_point ( y , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - - // get the stats: - NOMAD::Stats & stats = mads.get_stats(); - int old_bbe = stats.get_bb_eval(); - - // eval list of points: - new_feas_inc = new_infeas_inc = NULL; - std::list evaluated_pts; - - ev_control.eval_list_of_points ( NOMAD::EXTENDED_POLL , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - &evaluated_pts ); - - // update the number of extended poll blackbox evaluations: - stats.add_ext_poll_bb_eval ( stats.get_bb_eval() - old_bbe ); - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::close_block() << std::endl; - - // return the evaluated point: - return ( evaluated_pts.size() != 1 ) ? NULL : *evaluated_pts.begin(); -} - -/*-----------------------------------------*/ -/* run the extended poll */ -/*-----------------------------------------*/ -void NOMAD::Extended_Poll::run ( Mads & mads , - int & nb_ext_poll_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - nb_ext_poll_pts = 0; - success = NOMAD::UNSUCCESSFUL; - new_feas_inc = new_infeas_inc = NULL; - - if ( stop || _extended_points.empty() ) - return; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - NOMAD::Eval_Point * cur; - - // phase 1: evaluate the extended poll points in order to sort them - // -------- (based on the surrogates or on the true function): - if ( _extended_points.size() > 1 ) - { - - bool has_sgte = _p.has_sgte(); - bool old_sgte_eval_sort = _p.get_sgte_eval_sort(); - - // phase 1 initial display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "extended poll pts sorting"; - if ( has_sgte ) - oss << " (on surrogates)"; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - if ( has_sgte ) { - _p.set_SGTE_EVAL_SORT ( false ); // this ensures that only surrogate - _p.force_check_flag(); // evaluations are performed - } - - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // loop on the extended poll points: - std::list::const_iterator end = _extended_points.end(); - for ( std::list::iterator it = _extended_points.begin() ; - it != end ; ++it ) - { - cur = *it; - - if ( has_sgte ) - cur->set_eval_type ( NOMAD::SGTE ); - - ev_control.add_eval_point ( cur , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - _extended_points.clear(); - - // get the stats: - NOMAD::Stats & stats = mads.get_stats(); - int old_bbe = stats.get_bb_eval(); - - // number of eval points: - nb_ext_poll_pts = ev_control.get_nb_eval_points(); - - // eval list of points: - new_feas_inc = new_infeas_inc = NULL; - std::list evaluated_pts; - - ev_control.eval_list_of_points ( NOMAD::EXTENDED_POLL , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - &evaluated_pts ); - if ( has_sgte ) - { - if ( !_p.get_opt_only_sgte() ) { - success = NOMAD::UNSUCCESSFUL; - new_feas_inc = new_infeas_inc = NULL; - } - _p.set_SGTE_EVAL_SORT ( old_sgte_eval_sort ); - _p.force_check_flag(); - } - - // update the number of extended poll blackbox evaluations: - stats.add_ext_poll_bb_eval ( stats.get_bb_eval() - old_bbe ); - - // sort the evaluated extended poll points: - if ( success != NOMAD::FULL_SUCCESS ) - sort_epp ( evaluated_pts ); - - // the extended poll is terminated in case of success: - if ( stop || success == NOMAD::FULL_SUCCESS || new_feas_inc || new_infeas_inc ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "end of ext poll pts sorting (success)" ) - << std::endl; - return; - } - - // phase 1 final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of ext poll pts sorting"; - if ( has_sgte ) - oss << " (on surrogates)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - - } // end of phase 1 - // -------------- - - /*--------------------------------------------------------------*/ - - // phase 2: execute the extended poll for each extended point: - // -------- - { - const NOMAD::Eval_Point * old_bf = mads.get_best_feasible(); - const NOMAD::Eval_Point * old_bi = mads.get_best_infeasible(); - const NOMAD::Eval_Point * y; - - while ( !_extended_points.empty() ) - { - - cur = *_extended_points.begin(); - - // the point has already been evaluated during - // the extended poll points sorting: - if ( cur->is_in_cache() && cur->get_eval_type() == NOMAD::TRUTH ) - y = cur; - - // the point has to be evaluated: - else - { - - y = eval_epp ( cur , - mads , - stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc ); - - ++nb_ext_poll_pts; - - // the extended poll is terminated in case of success: - if ( !y || - stop || - success == NOMAD::FULL_SUCCESS || - new_feas_inc || - new_infeas_inc ) - break; - } - - _extended_points.pop_front(); - - // perform the extended poll descent ? - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl - << "extended poll center: ( "; - y->Point::display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " )" << std::endl << std::endl - << "perform extended poll descent ..."; - } - if ( check_trigger ( old_bf , old_bi , y ) ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "... yes" << std::endl; - descent ( y , - mads , - nb_ext_poll_pts , - stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc ); - - // the extended poll is terminated in case of success: - if ( stop || success == NOMAD::FULL_SUCCESS || new_feas_inc || new_infeas_inc ) - break; - } - else if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "... no" << std::endl; - } - } // end of phase 2 - // -------------- - - // clean the extended points that have not been considered: - std::list::const_iterator end = _extended_points.end(); - for ( std::list::iterator it = _extended_points.begin() ; - it != end ; ++it ) - if ( !(*it)->is_in_cache() ) - delete *it; - _extended_points.clear(); -} - -/*----------------------------------------------------------------*/ -/* sort the extended poll points after they have been evaluated */ -/* (private) */ -/*----------------------------------------------------------------*/ -void NOMAD::Extended_Poll::sort_epp -( const std::list & evaluated_pts ) -{ - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - const NOMAD::Double & h_min = _p.get_h_min(); - std::set sorted_pts; - - // 1. loop on the evaluated points: - std::list::const_iterator it1 , end1 = evaluated_pts.end(); - for ( it1 = evaluated_pts.begin() ; it1 != end1 ; ++it1 ) - { - - // creation of a Priority_Eval_Point: - NOMAD::Priority_Eval_Point pep ( *it1 , h_min ); - - // surrogate values for f and h: - if ( (*it1)->get_eval_type() == NOMAD::SGTE ) - { - pep.set_f_sgte ( (*it1)->get_f() ); - pep.set_h_sgte ( (*it1)->get_h() ); - } - - // insertion in the sorted list of points: - sorted_pts.insert ( pep ); - } - - // 2. loop on the sorted points: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "sorted ext poll pts" ) << std::endl; - - const NOMAD::Eval_Point * cur; - NOMAD::Eval_Point * y; - int i = 0 , nb_pts = static_cast ( sorted_pts.size() ); - std::set::const_iterator - it2 , end2 = sorted_pts.end(); - - for ( it2 = sorted_pts.begin() ; it2 != end2 ; ++it2 ) - { - - // we copy y=cur an create a new Eval_Point because cur can be a surrogate - // point already in the surrogate cache - - cur = (*it2).get_point(); - - y = new NOMAD::Eval_Point; - y->set ( cur->size() , _p.get_bb_nb_outputs() ); - y->set_signature ( cur->get_signature () ); - y->set_direction ( cur->get_direction () ); - y->Point::operator = ( *cur ); - - // display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << "point #"; - out.display_int_w ( ++i , nb_pts ); - out << "/" << nb_pts << " : ( "; - y->Point::display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " )" << std::endl; - } - - // insertion in _extended_points: - _extended_points.push_back ( y ); - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::close_block() << std::endl; -} - -/*--------------------------------------------------------------------*/ -/* set the neighbors executable name for the default implementation */ -/*--------------------------------------------------------------------*/ -bool NOMAD::Extended_Poll::set_neighbors_exe ( std::string & error_str ) -{ - error_str.clear(); - - _neighbors_exe = _p.get_neighbors_exe(); - - if ( _neighbors_exe.empty() ) { - error_str = "categorical variables: parameter NEIGHBORS_EXE is undefined"; - return false; - } - - const std::string problem_dir = _p.get_problem_dir(); - - std::list neighbors_exe_words; - NOMAD::get_words ( _neighbors_exe , neighbors_exe_words ); - - // _neighbors_exe is composed of several words (it is a command): - if ( neighbors_exe_words.size() > 1 ) - { - - _neighbors_exe.clear(); - - std::list::const_iterator it = neighbors_exe_words.begin() , - end = neighbors_exe_words.end(); - while (true) { - - if ( (*it)[0] != '$' ) { - _neighbors_exe += "\"" + problem_dir; - _neighbors_exe += *it + "\""; - } - else - _neighbors_exe += it->substr ( 1 , it->size()-1 ); - - ++it; - - if ( it == end ) - break; - - _neighbors_exe += " "; - } - } - - // _neighbors_exe is just composed of one name (it is an executable): - else - { - - if ( _neighbors_exe[0] != '$' ) - _neighbors_exe = problem_dir + _neighbors_exe; - else - _neighbors_exe = _neighbors_exe.substr ( 1 , _neighbors_exe.size()-1 ); - - if ( !NOMAD::check_exe_file ( _neighbors_exe ) ) - { - error_str = "categorical variables: \'" + _neighbors_exe - + "\' is not a valid executable file"; - return false; - } - - if ( _neighbors_exe[0] != '$' ) - _neighbors_exe = "\"" + _neighbors_exe + "\""; - } - - return true; -} - -/*----------------------------------------------------------------------*/ -/* construct the extended poll points: this is the default version of */ -/* this virtual function: it calls the executable defined by the */ -/* NEIGHBORS_EXE parameter */ -/*----------------------------------------------------------------------*/ -void NOMAD::Extended_Poll::construct_extended_points ( const NOMAD::Eval_Point & xk ) -{ - if ( _neighbors_exe.empty() ) - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , - "NOMAD::Extended_Poll::construct_extended_points(): no NEIGHBORS_EXE executable (batch mode) or no subclass implementation of the method (library mode)" ); - - if ( !xk.is_complete() ) - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , - "NOMAD::Extended_Poll::construct_extended_points(): bad extended poll center"); - - NOMAD::Signature * signature = _p.get_signature(); - if ( !signature ) - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , - "NOMAD::Extended_Poll::construct_extended_points(): no signature" ); - - std::string tmp_dir = _p.get_tmp_dir(); - - std::ostringstream oss; - oss << "." << _p.get_seed() << "." << xk.get_tag() << ".neighbors."; - const std::string & sint = oss.str(); - - // input file writing: - // ------------------- - std::string input_file_name = - tmp_dir + NOMAD::BLACKBOX_INPUT_FILE_PREFIX - + sint + NOMAD::BLACKBOX_INPUT_FILE_EXT; - - std::string output_file_name = - tmp_dir + NOMAD::BLACKBOX_OUTPUT_FILE_PREFIX - + sint + NOMAD::BLACKBOX_OUTPUT_FILE_EXT; - - std::ofstream fout ( input_file_name.c_str() ); - if ( fout.fail() ) - { - remove ( input_file_name.c_str () ); - std::string err = "could not open file neighbors input file " + input_file_name; - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err ); - } - - fout.setf ( std::ios::fixed ); - fout.precision ( NOMAD::DISPLAY_PRECISION_BB ); - xk.Point::display ( fout , " " , -1 , -1 ); - fout << std::endl; - - fout.close(); - - if ( fout.fail() ) - { - remove ( input_file_name.c_str () ); - std::string err = "could not write file neighbors input file " + input_file_name; - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err ); - } - - // system call to get the neighbors: - // --------------------------------- - - std::string cmd = _neighbors_exe + " " + input_file_name + " > " + output_file_name; - -#ifdef DEBUG -#ifdef USE_MPI - int rank; - MPI_Comm_rank ( MPI_COMM_WORLD, &rank); - _p.out() << "command(rank=" << rank - << ") = \'" << cmd << "\'" << std::endl; -#else - _p.out() << "command=\'" << cmd << "\'" << std::endl; -#endif -#endif - - // the call: - if ( ( system ( cmd.c_str() ) ) != 0 ) - { - remove ( input_file_name.c_str () ); - remove ( output_file_name.c_str() ); - std::string err = "error with command " + cmd; - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err ); - } - - // reading of the output file: - // --------------------------- - - std::ifstream fin ( output_file_name.c_str() ); - - if ( fin.fail() ) - { - remove ( input_file_name.c_str () ); - remove ( output_file_name.c_str() ); - std::string err = "could not open neighbors output file " + output_file_name; - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err ); - } - - int n = xk.size(); - - while ( true ) - { - NOMAD::Point y(n); - try - { - fin >> y; - } - catch ( NOMAD::Point::Bad_Input & ) - { - if ( y.is_defined() ) { - remove ( input_file_name.c_str () ); - remove ( output_file_name.c_str() ); - std::string err = "error with neighbor in file " + output_file_name; - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err ); - } - break; - } - - if ( !y.is_complete() ) - { - remove ( input_file_name.c_str () ); - remove ( output_file_name.c_str() ); - std::string err = "error with neighbor in file " + output_file_name; - throw NOMAD::Exception ( "Extended_Poll.cpp" , __LINE__ , err ); - } - - add_extended_poll_point ( y , *signature ); - } - - fin.close(); - - // delete the input and output files: - // ---------------------------------- - remove ( input_file_name.c_str () ); - remove ( output_file_name.c_str() ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Extended_Poll.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Extended_Poll.hpp deleted file mode 100644 index ec410cab7..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Extended_Poll.hpp +++ /dev/null @@ -1,235 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Extended_Poll.hpp - \brief Extended poll for categorical variables (headers) - \author Sebastien Le Digabel - \date 2010-04-14 - \see Extended_Poll.cpp -*/ -#ifndef __EXTENDED_POLL__ -#define __EXTENDED_POLL__ - -#include "Mads.hpp" -#include "Signature_Element.hpp" - -namespace NOMAD { - - /// Generic class for the extended poll. - /** - This is an abstract class (it is not possible to create - NOMAD::Extended_Poll objects). - */ - class Extended_Poll : public NOMAD::Uncopyable { - - protected: - - /// Parameters (includes the standard signature). - NOMAD::Parameters & _p; - - /// Add an extended poll point. - /** - Get, check and register the extended point and its signature - created by the user in \c construct_extended_points(). - \param ep Extended poll point -- \b IN. - \param s Associated signature -- \b IN. - */ - void add_extended_poll_point ( NOMAD::Point & ep , NOMAD::Signature & s ); - - /*---------------------------------------------------------------------*/ - - private: - - /// Executable for getting neighbors in batch mode. - std::string _neighbors_exe; - - /// Set of signatures (does not include the standard signature). - std::set _signatures; - - /// Signatures used during one poll step. - std::set _poll_signatures; - - /// Extended points for one poll step. - std::list _extended_points; - - /*---------------------------------------------------------------------*/ - - /// Evaluation of an extended poll point. - /** - \param y The extended poll point -- \b IN/OUT. - \param mads NOMAD::Mads object invoking the poll -- \b IN/OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - \return A pointer to the evaluated point; may be \c NULL if - the evaluation failed. - */ - const NOMAD::Eval_Point * eval_epp - ( NOMAD::Eval_Point * y , - Mads & mads , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) const; - - /// Sort the evaluated extended poll points. - /** - \param evaluated_pts The list of evaluated extended poll points -- \b IN/OUT. - */ - void sort_epp ( const std::list & evaluated_pts ); - - /// Check the extended poll trigger. - /** - \param old_bf A pointer to the old best feasible point -- \b IN. - \param old_bi A pointer to the old best infeasible point -- \b IN. - \param y A pointer to the extended poll center -- \b IN. - \return A boolean equal to \c true if the extended poll has to be performed. - */ - bool check_trigger ( const NOMAD::Eval_Point * old_bf , - const NOMAD::Eval_Point * old_bi , - const NOMAD::Eval_Point * y ) const; - - /// Check only the \c f values for the extended poll trigger. - /** - \param old_f Old \c f value -- \b IN. - \param new_f New \c f value -- \b IN. - \return A boolean equal to \c true if the extended poll has to be performed. - */ - bool check_trigger_on_f ( const NOMAD::Double & old_f , - const NOMAD::Double & new_f ) const; - - /// Create the descent parameters. - /** - \param y Starting point -- \b IN. - \param stats Stats -- \b IN. - \param descent_p Descent parameters -- \b IN/OUT. - */ - void set_descent_parameters ( const NOMAD::Eval_Point * y , - const NOMAD::Stats & stats , - NOMAD::Parameters & descent_p ) const; - - /// Descent from the extended poll center. - /** - \param y Extended poll center -- \b IN. - \param mads NOMAD::Mads object invoking the poll -- \b IN/OUT. - \param nb_ext_poll_pts Number of extended poll points -- \b IN/OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - void descent ( const NOMAD::Eval_Point * y , - Mads & mads , - int & nb_ext_poll_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - - /*---------------------------------------------------------------------*/ - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Extended_Poll ( NOMAD::Parameters & p ) : _p ( p ) {} - - /// Destructor. - virtual ~Extended_Poll ( void ); - - /// Construct the extended poll points. - /** - - Has to be implemented by every NOMAD::Extended_Poll subclass. - - The extended poll points are the neighbors of \c xk where - categorical variables have different values. - - The default implementation of this method uses parameter NEIGHBORS_EXE. - \param xk Poll center. - */ - virtual void construct_extended_points ( const NOMAD::Eval_Point & xk ); - - /// Set the neighbors executable name for the default implementation. - /** - \param error_str A string containing a possible error message -- \b OUT. - \return \c true if no error. - */ - bool set_neighbors_exe ( std::string & error_str ); - - /// Reset. - void reset ( void ); - - /// Poll reset. - /** - Before the extended poll is launched. - */ - void poll_reset ( void ); - - /// Access to the poll signatures. - /** - \return The set of poll signatures. - */ - const std::set & get_poll_signatures ( void ) const - { - return _poll_signatures; - } - - /// Run the extended poll. - /** - \param mads NOMAD::Mads object invoking this poll -- \b IN/OUT. - \param nb_ext_poll_pts Number of extended poll points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - void run ( Mads & mads , - int & nb_ext_poll_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Filter_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Filter_Point.hpp deleted file mode 100644 index 281cd540d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Filter_Point.hpp +++ /dev/null @@ -1,99 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Filter_Point.hpp - \brief Point stored in the filter (headers) - \author Sebastien Le Digabel - \date 2010-04-09 -*/ -#ifndef __FILTER_POINT__ -#define __FILTER_POINT__ - -#include "Eval_Point.hpp" -#include "Set_Element.hpp" - -namespace NOMAD { - - /// Class for the representation of NOMAD::Eval_Point objects stored in the filter. - class Filter_Point : public NOMAD::Set_Element { - - private: - - /// Affectation operator. - /** - \param fp The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Filter_Point & operator = ( const Filter_Point & fp ); - - public: - - /// Constructor. - /** - \param ep A pointer to the NOMAD::Eval_Point object that - is stored in the filter -- \b IN. - */ - Filter_Point ( const NOMAD::Eval_Point * ep ) - : NOMAD::Set_Element ( ep ) {} - - /// Copy constructor. - /** - \param fp The copied object -- \b IN. - */ - explicit Filter_Point ( const Filter_Point & fp ) - : NOMAD::Set_Element ( fp.get_element() ) {} - - /// Destructor. - virtual ~Filter_Point ( void ) {} - - /// Comparison operator. - /** - \param fp The right-hand side object. - \return A boolean equal to \c true if \c *this \c < \c fp. - */ - virtual bool operator < ( const NOMAD::Set_Element & fp ) const - { - return get_element()->get_h().value() < fp.get_element()->get_h().value(); - } - - /// Access to the point. - /** - \return A pointer to the NOMAD::Eval_Point stored in the cache. - */ - const NOMAD::Eval_Point * get_point ( void ) const { return get_element(); } - }; -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/LH_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/LH_Search.cpp deleted file mode 100644 index 3614ceff7..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/LH_Search.cpp +++ /dev/null @@ -1,381 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file LH_Search.cpp - \brief Latin-Hypercube search (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see LH_Search.hpp - */ -#include "LH_Search.hpp" - -/*-----------------------------------------------------------*/ -/* MADS Latin-Hypercube (LH) search */ -/*-----------------------------------------------------------*/ -void NOMAD::LH_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - new_feas_inc = new_infeas_inc = NULL; - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - count_search = !stop; - - if ( stop ) - return; - - // initial display: - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << NOMAD::LH_SEARCH; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - // active barrier: - const NOMAD::Barrier & barrier = mads.get_active_barrier(); - - // Evaluator_Control: - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // current incumbents: - const NOMAD::Eval_Point * feas_inc = barrier.get_best_feasible (); - const NOMAD::Eval_Point * infeas_inc = barrier.get_best_infeasible(); - - // get a reference point and a signature: - const NOMAD::Eval_Point * ref = (feas_inc) ? feas_inc : infeas_inc; - NOMAD::Signature * signature = _p.get_signature(); - - // check the number of points: - int p = _initial_search ? _p.get_LH_search_p0() : _p.get_LH_search_pi(); - if ( p <= 0 ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of LH " << ( _initial_search ? "initial " : "") - << "search (number of points <= 0)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - return; - } - - // no reference point is available (we consider the standard signature): - if ( !ref ) - { - - // it is not sufficient with categorical variables: - if ( signature->has_categorical() ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of LH " << ( _initial_search ? "initial " : "") - << "search (no available reference point)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - return; - } - } - else - signature = ref->get_signature(); - - // Change Display stats style - const std::list old_ds = _p.get_display_stats(); - std::list ds = old_ds; - ds.push_back ( " (LH)" ); - _p.set_DISPLAY_STATS ( ds ); - - // check the parameters: - _p.check ( false , // remove_history_file = false - false , // remove_solution_file = false - false ); // remove_stats_file = false - - int i; - NOMAD::Eval_Point * x; - int n = signature->get_n(); - int m = _p.get_bb_nb_outputs(); - int pm1 = p-1; - - // mesh sizes: - NOMAD::Point delta_max = signature->get_mesh()->get_delta_max (); - NOMAD::Double delta_i; - NOMAD::Point delta; - if ( !_initial_search ) - signature->get_mesh()->get_delta ( delta ); - - // fixed variables: - const NOMAD::Point & fixed_variables = signature->get_fixed_variables(); - - // bb input types: - const std::vector & bbit = signature->get_input_types(); - - // bounds: - const NOMAD::Point & lb = signature->get_lb(); - const NOMAD::Point & ub = signature->get_ub(); - - // pts contains n points of dimension p: each of these points contains - // p different values for each variable: - NOMAD::Point ** pts = new NOMAD::Point * [n]; - - // creation of p search points: - for ( int k = 0 ; k < p ; ++k ) - { - - x = new NOMAD::Eval_Point ( n , m ); - x->set_signature ( signature ); - - for ( i = 0 ; i < n ; ++i ) - { - - if ( k==0 ) - { - if ( fixed_variables[i].is_defined() ) - pts[i] = new NOMAD::Point ( p , fixed_variables[i] ); - else if ( bbit[i] == NOMAD::CATEGORICAL ) - { - pts[i] = new NOMAD::Point ( p , (*ref)[i] ); - } - else - { - pts[i] = new NOMAD::Point ( p ); - - // for the initial mesh: delta is not used and there will - // be no projection on mesh: - if ( !_initial_search ) - delta_i = delta[i]; - - values_for_var_i ( p , - delta_i , - delta_max[i] , - bbit [i] , - lb [i] , - ub [i] , - *pts [i] ); - } - } - - (*x)[i] = (*pts[i])[k]; - - if ( k == pm1 ) - delete pts[i]; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << "LH point #" << x->get_tag() - << ": ( "; - x->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // add the new point to the ordered list of search trial points: - ev_control.add_eval_point ( x , - display_degree , - false , // snap_to_bounds = false - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - delete [] pts; - - nb_search_pts = ev_control.get_nb_eval_points(); - - // eval_list_of_points: - // -------------------- - new_feas_inc = new_infeas_inc = NULL; - ev_control.eval_list_of_points ( _type , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - - _p.get_display_stats(); - - // restore stats style - _p.set_DISPLAY_STATS ( old_ds ); - _p.check ( false , // remove_history_file = false - false , // remove_solution_file = false - false ); // remove_stats_file = false - - - - // final displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of LH search (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - -} - -/*-----------------------------------------------------------*/ -/* LH search: decide p values for one variable */ -/*-----------------------------------------------------------*/ -/* . if no bounds, values are scaled with the largest */ -/* delta_m value obtained so far */ -/* . private method */ -/*-----------------------------------------------------------*/ -void NOMAD::LH_Search::values_for_var_i ( int p , - const NOMAD::Double & delta_m , - const NOMAD::Double & delta_m_max , - const NOMAD::bb_input_type & bbit , - const NOMAD::Double & lb , - const NOMAD::Double & ub , - NOMAD::Point & x ) const -{ - // categorical variables have already been treated as fixed variables: - if ( bbit == NOMAD::CATEGORICAL ) - return; - - int i; - NOMAD::Double v; - NOMAD::Random_Pickup rp (p); - bool rounding = ( bbit != NOMAD::CONTINUOUS ); - bool lb_def = lb.is_defined(); - bool ub_def = ub.is_defined(); - double w = ( ( lb_def && ub_def ) ? - ub.value()-lb.value() : 1.0 ) / p; - // main loop: - for ( i = 0 ; i < p ; ++i ) - { - - // both bounds exist: - if ( lb_def && ub_def ) - v = lb + ( i + NOMAD::RNG::rand()/NOMAD::D_INT_MAX ) * w; - // one of the bounds does not exist: - else - { - - // lb exists, and ub not: mapping [0;1] --> [lb;+INF[ - if ( lb_def ) - v = lb + 10 * delta_m_max * sqrt ( - log ( NOMAD::DEFAULT_EPSILON + - ( i + NOMAD::RNG::rand()/NOMAD::D_INT_MAX ) * w ) ); - - // lb does not exist: - else - { - - // ub exists, and lb not: mapping [0;1] --> ]-INF;ub] - if ( ub_def ) - v = ub - delta_m_max * 10 * - sqrt ( -log ( NOMAD::DEFAULT_EPSILON + - ( i +NOMAD::RNG::rand()/NOMAD::D_INT_MAX ) * w ) ); - - // there are no bounds: mapping [0;1] --> ]-INF;+INF[ - else - v = (NOMAD::RNG::rand()%2 ? -1.0 : 1.0) * delta_m_max * 10 * - sqrt ( - log ( NOMAD::DEFAULT_EPSILON + - ( i + NOMAD::RNG::rand()/NOMAD::D_INT_MAX ) * w ) ); - } - } - - // rounding: - if ( rounding ) - v = v.round(); - - // projection to mesh (with ref=0): - v.project_to_mesh ( 0.0 , delta_m , lb , ub ); - - // affectation + permutation: - x[rp.pickup()] = v; - } -} - -/*---------------------------------------------------------*/ -/* simpler method used to generate a list of p LH points */ -/* (it is currently not used by the LH search) */ -/* (static) */ -/*---------------------------------------------------------*/ -bool NOMAD::LH_Search::LH_points ( int n , - int m , - int p , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - std::vector & pts ) -{ - if ( n <= 0 || - p <= 0 || - !lb.is_defined() || - !ub.is_defined() || - lb.size() != n || - ub.size() != n ) - return false; - - for ( size_t j = 0 ; j < pts.size() ; ++j ) - delete pts[j]; - pts.clear(); - - NOMAD::Eval_Point * x; - int i; - int pm1 = p-1; - NOMAD::Random_Pickup ** rps = new NOMAD::Random_Pickup *[n]; - - for ( int k = 0 ; k < p ; ++k ) - { - x = new NOMAD::Eval_Point ( n , m ); - for ( i = 0 ; i < n ; ++i ) - { - if ( k==0 ) - rps[i] = new NOMAD::Random_Pickup(p); - (*x)[i] = lb[i] + - (ub[i]-lb[i]) * - ( rps[i]->pickup() + NOMAD::RNG::rand()/(1.0+NOMAD::D_INT_MAX)) / p; - if ( k==pm1 ) - delete rps[i]; - } - pts.push_back(x); - } - - delete [] rps; - - return true; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/LH_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/LH_Search.hpp deleted file mode 100644 index aeb245b0b..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/LH_Search.hpp +++ /dev/null @@ -1,133 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file LH_Search.hpp - \brief Latin-Hypercube search (headers) - \author Sebastien Le Digabel - \date 2010-04-09 - \see LH_Search.cpp -*/ -#ifndef __LH_SEARCH__ -#define __LH_SEARCH__ - -#include "Search.hpp" -#include "Mads.hpp" -#include "RNG.hpp" - -namespace NOMAD { - - /// Class for the Latin-Hypercube search. - class LH_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - private: - - bool _initial_search; /// Initial search flag (for display only). - - /// Decide \c p values for one variable. - /** - If no bounds, values are scaled with the largest Delta^m_k value obtained so far. - \param p Number of values to decide -- \b IN. - \param delta_m Delta^m_k (for the projection to the mesh) -- \b IN. - \param delta_m_max Largest Delta^m_k value -- \b IN. - \param bbit Black-box input type -- \b IN. - \param lb Lower bound -- \b IN. - \param ub Upper bound -- \b IN. - \param x The \p values -- \b OUT. - */ - void values_for_var_i ( int p , - const NOMAD::Double & delta_m , - const NOMAD::Double & delta_m_max , - const NOMAD::bb_input_type & bbit , - const NOMAD::Double & lb , - const NOMAD::Double & ub , - NOMAD::Point & x ) const; - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param initial_search Initial search flag -- \b IN. - \param phase_one Phase one flag -- \b IN. - */ - LH_Search ( NOMAD::Parameters & p , - bool initial_search , - bool phase_one ) - : NOMAD::Search ( p , phase_one ? NOMAD::LH_SEARCH_P1 : NOMAD::LH_SEARCH ) , - _initial_search ( initial_search ) {} - - /// Destructor. - virtual ~LH_Search ( void ) {} - - /// The Latin-Hypercube search. - /** - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - - /// Simpler method used to generate a list of LH points. - /** - \param n Dimension -- \b IN. - \param m Number of outputs -- \b IN. - \param p Number of LH points -- \b IN. - \param lb Lower bounds -- \b IN. - \param ub Upper bounds -- \b IN. - \param pts LH points -- \b OUT. - \return A boolean equal to \c true if no error occured. - */ - static bool LH_points ( int n , - int m , - int p , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - std::vector & pts ); - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/L_Curve.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/L_Curve.cpp deleted file mode 100644 index 45716068d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/L_Curve.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file L_Curve.cpp - \brief L_CURVE_TARGET stopping criterion (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see L_Curve.hpp -*/ -#include "L_Curve.hpp" - -/*-----------------------------------------------*/ -/* insertion of a pair bbe/f */ -/*-----------------------------------------------*/ -void NOMAD::L_Curve::insert ( int bbe , const NOMAD::Double & f ) -{ - if ( _f.empty() ) { - _f.push_back ( f ); - _bbe.push_back (bbe); - } - else { - size_t nm1 = _bbe.size()-1; - if ( _bbe[nm1] == bbe ) - _f[nm1] = f; - else { - _f.push_back ( f ); - _bbe.push_back (bbe); - } - } -} - -/*---------------------------------------------------------------*/ -/* check the L_CURVE_TARGET stopping criterion */ -/* returns true if it detects that the target won't be reached */ -/* after bbe evaluations) */ -/*---------------------------------------------------------------*/ -bool NOMAD::L_Curve::check_stop ( int bbe ) const -{ - // we check the p last successes and approximate the L-curve - // with a line joining the extremities: - const size_t p = 7; - - if ( _f.size() >= p ) { - - size_t n = _f.size(); - - NOMAD::Double f2 = _f[n-1]; - if ( f2 <= _target ) - return false; - - size_t nmp = n-p; - int bbe1 = _bbe [ nmp ]; - NOMAD::Double f1 = _f [ nmp ]; - NOMAD::Double a = ( f2 - f1 ) / ( bbe - bbe1 ); - NOMAD::Double b = f1 - a * bbe1; - int bbe_target = static_cast ( ceil ( ( ( _target - b ) / a ).value() ) ); - - // test: if ( bbe_target > bbe+(bbe-bbe1) ) - return ( bbe_target > 2*bbe - bbe1 ); - } - return false; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/L_Curve.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/L_Curve.hpp deleted file mode 100644 index 114d2f82c..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/L_Curve.hpp +++ /dev/null @@ -1,88 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file L_Curve.hpp - \brief L_CURVE_TARGET stopping criterion (headers) - \author Sebastien Le Digabel - \date 2010-04-09 - \see L_Curve.cpp -*/ -#ifndef __L_CURVE__ -#define __L_CURVE__ - -#include "Double.hpp" -#include "Uncopyable.hpp" - -namespace NOMAD { - - /// Class implementing the L_CURVE_TARGET stopping criterion. - class L_Curve : private NOMAD::Uncopyable { - - private: - - NOMAD::Double _target; ///< L_CURVE_TARGET parameter value. - std::vector _f; ///< List of objective values. - std::vector _bbe; ///< List of numbers of evaluations. - - public: - - /// Constructor. - /** - \param target L_CURVE_TARGET parameter value -- \b IN. - */ - L_Curve ( const NOMAD::Double & target ) : _target ( target ) {} - - /// Destructor. - virtual ~L_Curve ( void ) {} - - /// Insertion of a pair \c bbe/f in the lists \c _f and \c _bbe. - /** - \param bbe A new number of evaluations -- \b IN. - \param f A new objective value -- \b IN. - */ - void insert ( int bbe , const NOMAD::Double & f ); - - /// Check the L_CURVE_TARGET stopping criterion. - /** - \param bbe An integer indicating a number of blackbox evaluations - -- \b IN. - \return A boolean equal to \c true if the method detects that - the target will not be reached after bbe evaluations. - */ - bool check_stop ( int bbe ) const; - }; -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Mads.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Mads.cpp deleted file mode 100644 index b34d123df..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Mads.cpp +++ /dev/null @@ -1,3727 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Mads.cpp - \brief MADS algorithm (implementation) - \author Sebastien Le Digabel - \date 2010-04-20 - \see Mads.hpp - */ -#include "Mads.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -bool NOMAD::Mads::_force_quit = false; -bool NOMAD::Mads::_flag_check_bimads = true; -bool NOMAD::Mads::_flag_reset_mesh = true; -bool NOMAD::Mads::_flag_reset_barriers = true; -bool NOMAD::Mads::_flag_p1_active = false; - - -/*---------------------------------------------------------*/ -/* force quit (static, called by pressing ctrl-c) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::force_quit ( int signalValue ) -{ - NOMAD::Mads::_force_quit = true; - NOMAD::Evaluator_Control::force_quit(); - NOMAD::Evaluator::force_quit(); - -#ifdef USE_TGP - NOMAD::TGP_Output_Model::force_quit(); -#endif -} - -/*---------------------------------------------------------*/ -/* access to the flags (static) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::get_flags ( bool & flag_check_bimads , - bool & flag_reset_mesh , - bool & flag_reset_barriers , - bool & flag_p1_active ) -{ - flag_check_bimads = _flag_check_bimads; - flag_reset_mesh = _flag_reset_mesh; - flag_reset_barriers = _flag_reset_barriers; - flag_p1_active = _flag_p1_active; -} - -/*---------------------------------------------------------*/ -/* initializations */ -/*---------------------------------------------------------*/ -/* . only to be invoked by constructors */ -/* . private method */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::init ( void ) -{ - - NOMAD::Mads::_force_quit = false; - - if ( !NOMAD::Slave::is_master() ) - return; - - // Mads::force_quit() will be called if ctrl-c is pressed: - signal ( SIGINT , NOMAD::Mads::force_quit ); -#ifndef WINDOWS - signal ( SIGPIPE , NOMAD::Mads::force_quit ); // (ctrl-c during a "| more") -#endif -#ifdef USE_MPI - signal ( SIGTERM , NOMAD::Mads::force_quit ); -#endif - - // model searches initialization: - if ( _p.has_model_search() ) { -#ifdef USE_TGP - if ( _p.get_model_search(1) == NOMAD::TGP_MODEL ) - _model_search1 = new TGP_Model_Search ( _p ); -#endif - if ( _p.get_model_search(1) == NOMAD::QUADRATIC_MODEL ) - _model_search1 = new Quad_Model_Search ( _p ); -#ifdef USE_TGP - if ( _p.get_model_search(2) == NOMAD::TGP_MODEL ) - _model_search2 = new TGP_Model_Search ( _p ); -#endif - if ( _p.get_model_search(2) == NOMAD::QUADRATIC_MODEL ) - _model_search2 = new Quad_Model_Search ( _p ); - } - -#ifdef USE_TGP - _ev_control.set_last_TGP_model ( NULL ); -#endif - - // VNS search initialization: - if ( _p.get_VNS_search() ) - _VNS_search = new VNS_Search ( _p ); - - // cache search initialization: - if ( _p.get_cache_search() ) - _cache_search = new Cache_Search ( _p ); - - // Orthogonal mesh initialization - _mesh->reset(); - - -} - -/*---------------------------------------------------------*/ -/* destructor */ -/*---------------------------------------------------------*/ -NOMAD::Mads::~Mads ( void ) -{ - delete _pareto_front; - delete _model_search1; - delete _model_search2; - delete _VNS_search; - delete _cache_search; - delete _L_curve; - - if ( _extended_poll && !_user_ext_poll) - delete _extended_poll; -} - -/*-------------------------------------------------------------*/ -/* reset */ -/*-------------------------------------------------------------*/ -/* default values for parameters: keep_barriers = false */ -/* keep_stats = false */ -/*-------------------------------------------------------------*/ -void NOMAD::Mads::reset ( bool keep_barriers , bool keep_stats ) -{ - // evaluator control: -#ifdef USE_TGP - _ev_control.set_last_TGP_model ( NULL ); -#endif - - // user search: - _user_search = NULL; - - // model search #1: - if ( _p.get_model_search(1) != NOMAD::NO_MODEL ) - { - if ( _model_search1 ) - _model_search1->reset(); - else { - if ( _p.get_model_search(1) == NOMAD::TGP_MODEL ) - { -#ifdef USE_TGP - _model_search1 = new TGP_Model_Search ( _p ) ; -#endif - } - else - _model_search1 = new Quad_Model_Search ( _p ); - } - } - else - { - delete _model_search1; - _model_search1 = NULL; - } - - // model search #2: - if ( _p.get_model_search(2) != NOMAD::NO_MODEL ) - { - if ( _model_search2 ) - _model_search2->reset(); - else - { - if ( _p.get_model_search(2) == NOMAD::TGP_MODEL ) - { -#ifdef USE_TGP - _model_search2 = new TGP_Model_Search ( _p ) ; -#endif - } - else - _model_search2 = new Quad_Model_Search ( _p ); - } - } - else - { - delete _model_search2; - _model_search2 = NULL; - } - - // VNS search: - if ( _p.get_VNS_search() ) - { - if ( _VNS_search ) - _VNS_search->reset(); - else - _VNS_search = new VNS_Search ( _p ); - } - else { - delete _VNS_search; - _VNS_search = NULL; - } - - // cache search: - if ( _p.get_cache_search() ) - { - if ( _cache_search ) - _cache_search->reset(); - else - _cache_search = new Cache_Search ( _p ); - } - else - { - delete _cache_search; - _cache_search = NULL; - } - - // barriers: - _flag_reset_barriers = !keep_barriers; - if ( _flag_reset_barriers ) - { - _true_barrier.reset(); - _sgte_barrier.reset(); - } - - // stats: - if ( !keep_stats ) - _stats.reset(); - - - _mesh->reset(); - -} - -/*---------------------------------------------------------*/ -/* algorithm execution (single-objective) */ -/*---------------------------------------------------------*/ -NOMAD::stop_type NOMAD::Mads::run ( void ) -{ - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_gen_dd(); - NOMAD::stop_type stop_reason = NOMAD::UNKNOWN_STOP_REASON; - -#ifdef USE_MPI - - if ( NOMAD::Slave::get_nb_processes() < 2 ) - { - out << NOMAD::open_block("ERROR:") << "Incorrect command to run with MPI." << std::endl - << "Usage: mpirun -np p exeName" << std::endl ; - out << NOMAD::close_block(); - return stop_reason; - } - - - // init the slaves: - bool stop_slaves_here = false; - - if ( NOMAD::Slave::is_master() ) - { - if ( !NOMAD::Slave::are_running() ) - { - NOMAD::Slave::init_slaves ( out ); - stop_slaves_here = true; - } - } - else - { - NOMAD::Slave s ( _p , _ev_control.get_evaluator() ); - s.run(); - return stop_reason; - } - -#endif - - try - { - - // check an extended poll if there are categorical - // variables and disable extended poll otherwise: - if ( _p.get_signature()->has_categorical() ) - { - - if ( _user_ext_poll && !_extended_poll ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "categorical variables: user extended poll object is NULL" ); - - if ( _p.get_extended_poll_enabled() && !_user_ext_poll ) - { - if (!_extended_poll) - _extended_poll = new NOMAD::Extended_Poll ( _p ); // extended poll created only once with the signatures of _p - - std::string error_str; - if ( !_extended_poll->set_neighbors_exe ( error_str ) ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , error_str ); - } - } - else if ( _extended_poll ) - { - if ( !_user_ext_poll ) - delete _extended_poll; - _extended_poll = NULL; - } - - // check if Mads::run() has been called for multi-objective: - if ( NOMAD::Mads::_flag_check_bimads && _p.get_nb_obj() > 1 ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::run() called for multi-objective instead of Mads::multi_run()" ); - -#ifndef R_VERSION - if ( display_degree == NOMAD::NORMAL_DISPLAY || display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "MADS run" ); - - if ( display_degree == NOMAD::NORMAL_DISPLAY ) { - _ev_control.display_stats ( true , - out , - _p.get_display_stats() , - NULL , - false , - NULL ); - out << std::endl << std::endl; - } -#endif - - // barriers init: - if ( _flag_reset_barriers ) - { - _true_barrier.reset(); - _sgte_barrier.reset(); - } - - // evaluator control init: - _ev_control.reset(); - - // reset the extended poll: - if ( _extended_poll && _p.get_extended_poll_enabled() ) - _extended_poll->reset(); - - // mesh init/reset: - if ( _flag_reset_mesh ) - _mesh->reset(); - - NOMAD::success_type success , last_success; - int nb_search_pts; - bool count_search; - bool stop = false; - const NOMAD::Eval_Point * new_feas_inc = NULL; - const NOMAD::Eval_Point * new_infeas_inc = NULL; - - stop_reason = NOMAD::NO_STOP; - - // x0 eval: - eval_x0 ( stop , stop_reason ); - - // phase one: if no feasible starting point: - bool phase_one_done = false; - if (stop && - stop_reason == NOMAD::X0_FAIL && - _p.has_EB_constraints() && - ( _stats.get_eval() > 0 || ( _p.get_opt_only_sgte() && _stats.get_sgte_eval() > 0 ) ) ) - { - - phase_one_done = true; - Phase_One_Search p1s ( _p ); - p1s.search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - - _mesh->reset(); - - } - - // initial Latin-Hypercube (LH) search: - if ( !stop && !phase_one_done && _p.get_LH_search_p0() > 0 ) - { - - LH_Search lh ( _p , true , _flag_p1_active ); - int nb_search_pts; - - lh.search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_LH_success(); - - if ( count_search ) - _stats.add_nb_LH_searches(); - - _stats.add_LH_pts ( nb_search_pts ); - } - - // no iterations allowed: - if ( !stop && _p.get_max_iterations() == 0 ) - { - stop = true; - stop_reason = NOMAD::MAX_ITER_REACHED; - } - - // L_curve initialization: - delete _L_curve; - _L_curve = NULL; - const NOMAD::Double L_curve_target = _p.get_L_curve_target(); - if ( L_curve_target.is_defined() ) - { - _L_curve = new NOMAD::L_Curve ( L_curve_target ); - const NOMAD::Eval_Point * best_feasible = get_best_feasible(); - if ( best_feasible ) - _L_curve->insert ( _stats.get_bb_eval() , best_feasible->get_f() ); - } - - int max_cfi = _p.get_max_consecutive_failed_iterations(); - int nb_cfi = 0; - - success = last_success = NOMAD::UNSUCCESSFUL; - - // MADS iterations: - while ( !stop ) - { - - iteration ( stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc ); - - if ( success == NOMAD::UNSUCCESSFUL && last_success == NOMAD::UNSUCCESSFUL ) - ++nb_cfi; - else - nb_cfi = (success == NOMAD::UNSUCCESSFUL) ? 1 : 0; - - last_success = success; - - // check the consecutive number of failed iterations: - if ( max_cfi > 0 && nb_cfi > max_cfi ) - { - stop = true; - stop_reason = NOMAD::MAX_CONS_FAILED_ITER; - } - - } - - // parallel version: -#ifdef USE_MPI - - // asynchronous mode: wait for the evaluations in progress: - if ( _p.get_asynchronous() ) - { - std::list evaluated_pts; - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - evaluated_pts ); - } - - // update stats: - _stats.set_MPI_data_size ( NOMAD::Slave::get_data_sent() + - NOMAD::Slave::get_data_rcvd() ); - -#endif - - // final cache save (overwrite=true): - _ev_control.save_caches ( true ); - - // final displays: - const NOMAD::Eval_Point * bf = get_best_feasible(); - bool write_stats = bf && - ( bf->get_tag() != _ev_control.get_last_stats_tag() || - _stats.get_bb_eval() != _ev_control.get_last_stats_bbe() ); - - const std::string & stats_file_name = _p.get_stats_file_name(); - - if ( !stats_file_name.empty() ) - { - if ( write_stats && !_p.get_display_all_eval() ) - { - _ev_control.stats_file ( stats_file_name , bf , true , NULL ); - } - if ( !bf && display_degree > NOMAD::MINIMAL_DISPLAY ) - { - std::ofstream fout ( (_p.get_problem_dir() + stats_file_name).c_str() ); - if ( fout.fail() ) - { - out << std::endl - << "Warning (" << "Mads.cpp" << ", " << __LINE__ - << "): could not save information in stats file \'" - << stats_file_name << "\'" << std::endl << std::endl; - } - else - fout << "no feasible solution has been found after " - << _stats.get_bb_eval() << " evaluations" - << std::endl; - fout.close(); - } - - } - - if ( display_degree > NOMAD::MINIMAL_DISPLAY) - { - - // final stats: - if ( display_degree == NOMAD::NORMAL_DISPLAY && bf && write_stats && !_p.get_display_all_eval() ) - _ev_control.display_stats ( false, - out, - _p.get_display_stats() , - bf , - true , - NULL ); -#ifndef R_VERSION - std::ostringstream msg; - msg << "end of run (" << stop_reason << ")"; - out << std::endl << NOMAD::close_block ( msg.str() ); -#endif - } - - // mono-objective final displays: - if ( _p.get_nb_obj() == 1 ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "NOMAD final display" ); - -#ifndef R_VERSION - display(); -#endif - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block(); - } - - } // end of the try block - - catch ( std::exception & e ) - { - -#ifdef USE_MPI - if ( NOMAD::Slave::are_running() ) - NOMAD::Slave::stop_slaves ( out ); -#endif - - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , e.what() ); - } - - // stop the slaves: -#ifdef USE_MPI - if ( NOMAD::Slave::are_running() && stop_slaves_here ) - NOMAD::Slave::stop_slaves ( out ); -#endif - - return stop_reason; -} - -/*----------------------------------------------------------------------*/ -/* launch a single optimization for multi-objective optimization */ -/*----------------------------------------------------------------------*/ -/* . the display_degree is given as a parameter since it corresponds */ -/* to the original iterative display degree before all degrees have */ -/* been set to zero */ -/* . private method */ -/*----------------------------------------------------------------------*/ -void NOMAD::Mads::multi_launch_single_opt -( NOMAD::dd_type display_degree , - int mads_runs , - int overall_bbe , - NOMAD::Multi_Obj_Evaluator & ev , - int & stagnation_cnt , - NOMAD::Stats & multi_stats , - bool & stop , - NOMAD::stop_type & stop_reason ) -{ - // max number of bb evaluations for one MADS run: - int max_bbe = _p.get_max_bb_eval(); - - // size of the Pareto front before the MADS run: - int tmp = _pareto_front->size(); - - // current MADS run: - int cur_mads_run = multi_stats.get_mads_runs(); - - // displays: - const NOMAD::Display & out = _p.out(); - - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - { - out << "MADS run " << std::setw(2) << cur_mads_run + 1; - if ( mads_runs > 0 ) - out << "/" << mads_runs; - out << " ..."; - } - - // run single-objective MADS (it also updates the Pareto front): - NOMAD::Mads::set_flag_check_bimads ( false ); - NOMAD::stop_type single_run_stop_reason = run(); - NOMAD::Mads::set_flag_check_bimads ( true ); - - if ( single_run_stop_reason == NOMAD::CTRL_C || - single_run_stop_reason == NOMAD::ERROR || - single_run_stop_reason == NOMAD::UNKNOWN_STOP_REASON || - single_run_stop_reason == NOMAD::X0_FAIL || - single_run_stop_reason == NOMAD::F_TARGET_REACHED || - single_run_stop_reason == NOMAD::P1_FAIL ) - { - stop = true; - stop_reason = single_run_stop_reason; - } - - // update MULTI-MADS stats from MADS stats: - multi_stats.update ( _stats , false ); // for_search = false - multi_stats.add_mads_run(); - - int nb_new_pts = _pareto_front->size() - tmp; - int global_bbe = multi_stats.get_bb_eval(); - - // displays: - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - { - - // display basic stats on the terminated run: - out << "... OK [bb eval=" << std::setw(3) << _stats.get_bb_eval() - << "] [overall bb eval=" << std::setw(5) << global_bbe - << "] [# dominant pts=" << std::setw(4) << _pareto_front->size() - << "] [# new pts=" << std::setw(4) << nb_new_pts << "]"; - - // display f1, f2, and f: - const NOMAD::Eval_Point * bf = get_best_feasible(); - if ( bf ) - { - - const NOMAD::Point & bbo = bf->get_bb_outputs(); - - out << " [f1=" << bbo[ev.get_i1()] - << " f2=" << bbo[ev.get_i2()]; - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << " f=" << bf->get_f(); - out << "]"; - } - out << std::endl; - } - - if ( _stats.get_bb_eval() == 0 && nb_new_pts == 0 ) - ++stagnation_cnt; - else - stagnation_cnt = 0; - - // stop ? - if ( !stop ) - { - - // test the number of MADS runs: - if ( mads_runs > 0 ) - { - if ( multi_stats.get_mads_runs() >= mads_runs ) - { - stop = true; - stop_reason = NOMAD::MULTI_NB_MADS_RUNS_REACHED; - } - } - - // test if no new Pareto point has been generated for 50*n MADS runs: - else - { - if ( stagnation_cnt > 50 * _p.get_nb_free_variables() ) - { - stop = true; - stop_reason = NOMAD::MULTI_STAGNATION; - } - } - } - - if ( overall_bbe >= 0 && global_bbe >= overall_bbe ) - { - stop = true; - stop_reason = NOMAD::MULTI_MAX_BB_REACHED; - } - - bool user_calls_enabled = _p.get_user_calls_enabled(); - - if ( !stop ) - { - - // ell is the mesh index on which the last run terminated: - // int ell = NOMAD::Mesh::get_mesh_index(); - - // reset MADS: - reset(); - - // this strategy deciding the initial mesh size - // was used with versions < 3.4 - // if ( cur_mads_run > 1 ) - // _p.set_INITIAL_MESH_INDEX ( (ell > 5) ? 5 : ell ); - - // modify MAX_BB_EVAL for single runs (in order to have - // less than overall_bbe blackbox evaluations): - if ( overall_bbe >= 0 && global_bbe + max_bbe > overall_bbe ) - _p.set_MAX_BB_EVAL ( overall_bbe - global_bbe ); - } - - // set the number of MADS runs for the general Stats object: - _stats.set_mads_runs ( multi_stats.get_mads_runs() ); - - // call the user-defined function Multi_Obj_Evaluator::update_mads_run(): - if ( user_calls_enabled ) - ev.update_mads_run ( _stats , - _ev_control , - _true_barrier , - _sgte_barrier , - *_pareto_front ); -} - -/*--------------------------------------------------------------------------*/ -/* compute and set the minimal poll size for multi-objective optimization */ -/* (private) */ -/*--------------------------------------------------------------------------*/ -void NOMAD::Mads::multi_set_min_poll_size ( const NOMAD::Point & lb , - const NOMAD::Point & ub , - const NOMAD::Point & Delta_0 , - NOMAD::Double delta_j ) -{ - - delta_j /= sqrt ( _mesh->get_update_basis() ); - - int n = Delta_0.size(); - NOMAD::Point Delta_min (n); - - for ( int i = 0 ; i < n ; ++i ) - { - - // set a relative value: - if ( lb[i].is_defined() && ub[i].is_defined() ) - Delta_min[i] = delta_j * ( ub[i] - lb[i] ); - - // set an absolute value: - else - Delta_min[i] = delta_j; - - // compare to Delta_0: - if ( Delta_min[i] > Delta_0[i] ) - Delta_min[i] = Delta_0[i]; - } - - _p.set_MIN_POLL_SIZE ( Delta_min ); -} - -/*---------------------------------------------------------*/ -/* algorithm execution (multi) */ -/*---------------------------------------------------------*/ -NOMAD::stop_type NOMAD::Mads::multi_run ( void ) -{ - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_gen_dd(); - NOMAD::stop_type stop_reason = NOMAD::UNKNOWN_STOP_REASON; - - // init the slaves: - -#ifdef USE_MPI - - if ( NOMAD::Slave::get_nb_processes() < 2 ) - { - out << NOMAD::open_block("ERROR:") << "Incorrect command to run with MPI." << std::endl - << "Usage: mpirun -np p exeName" << std::endl ; - out << NOMAD::close_block(); - return stop_reason; - } - - bool stop_slaves_here = false; - - if ( NOMAD::Slave::is_master() ) - { - if ( !NOMAD::Slave::are_running() ) - { - NOMAD::Slave::init_slaves ( out ); - stop_slaves_here = true; - } - } - else - { - NOMAD::Slave s ( _p , _ev_control.get_evaluator() ); - s.run(); - return stop_reason; - } - -#endif - - try { - - // objective indexes: - NOMAD::Multi_Obj_Evaluator::set_obj_indexes ( _p.get_index_obj() ); - - // bounds: - const NOMAD::Point & lb = _p.get_lb(); - const NOMAD::Point & ub = _p.get_ub(); - - // MULTI-MADS stopping criteria: - int mads_runs = _p.get_multi_nb_mads_runs(); // max number of MADS runs - int overall_bbe = _p.get_multi_overall_bb_eval(); // max number of total bb eval. - bool use_delta_crit = _p.get_multi_use_delta_crit(); // use the delta term. crit. - int stagnation_cnt = 0; - - if ( mads_runs == 0 ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::multi_run(): parameter MULTI_NB_MADS_RUNS is not positive" ); - - if ( _p.get_nb_obj() != 2 ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::multi_run(): NOMAD current version handles a maximum of two objectives" ); - - // remember cache save period: - int old_csp = _p.get_cache_save_period(); - - // remember L_CURVE_TARGET: - NOMAD::Double old_lct = _p.get_L_curve_target(); - - // remember solution file: - std::string old_sol_file = _p.get_solution_file(); - - // remember the original LH search parameters: - int lh_p0 = _p.get_LH_search_p0(); - int lh_pi = _p.get_LH_search_pi(); - - // remember the original minimal poll size: - const NOMAD::Point original_min_poll_size = _p.get_min_poll_size(); - - // remember display degrees: - NOMAD::dd_type iter_dd = out.get_iter_dd(); - std::string old_dd; - out.get_display_degree ( old_dd ); - - // save list of starting points: - std::string x0_cache_file = _p.get_x0_cache_file(); - std::vector x0s; - { - const std::vector & x0s_tmp = _p.get_x0s(); - size_t nx0 = x0s_tmp.size() , k; - for ( k = 0 ; k < nx0 ; ++k ) - x0s.push_back ( new Point ( *x0s_tmp[k] ) ); - } - - NOMAD::Point Delta_0 = _mesh->get_initial_poll_size (); - - - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl << NOMAD::open_block ( "multi-MADS run" ) << std::endl; - - bool stop = false; - stop_reason = NOMAD::NO_STOP; - - // MULTI-MADS stats: - NOMAD::Stats multi_stats ( _stats ); - - // access to the evaluator (downcast to a Multi_Obj_Evaluator): - NOMAD::Multi_Obj_Evaluator * ev = - static_cast ( _ev_control.get_evaluator() ); - if ( !ev->is_multi_obj() ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::multi_run(): associated Evaluator object is not a Multi_Obj_Evaluator" ); - - // parameters modifications: - // ------------------------- - - // STATS_FILE: - const std::string old_stats_file_name = _p.get_stats_file_name(); - const std::list old_stats_file = _p.get_stats_file(); - _p.reset_stats_file(); - - // MAX_BB_EVAL: - int max_bbe = _p.get_max_bb_eval(); - if ( overall_bbe >= 0 && ( max_bbe < 0 || overall_bbe < max_bbe ) ) - _p.set_MAX_BB_EVAL ( overall_bbe ); - - // disable display: - _p.set_DISPLAY_DEGREE ( NOMAD::NO_DISPLAY ); - - // disable solution file: - _p.set_SOLUTION_FILE ( "" ); - - // disable CACHE_SAVE_PERIOD: - _p.set_CACHE_SAVE_PERIOD ( -1 ); - - // disable L_CURVE_TARGET: - _p.set_L_CURVE_TARGET ( NOMAD::Double() ); - - // LH_SEARCH and MAX_BB_EVAL adjustment: - if ( lh_p0 > 0 ) - { - _p.set_LH_SEARCH ( lh_p0 , 0 ); - if ( max_bbe >= 0 ) - { - int bbe = max_bbe + lh_p0; - if ( overall_bbe >= 0 && bbe > overall_bbe ) - bbe = overall_bbe; - _p.set_MAX_BB_EVAL ( bbe ); - } - } - - // parameters validation: - _p.check ( true , // remove_history_file = true - true , // remove_solution_file = true - true ); // remove_stats_file = true - - // Pareto front initialization: - delete _pareto_front; - _pareto_front = new NOMAD::Pareto_Front; - - // initial optimizations ( minimize f1(x) or f2(x) ): - // -------------------------------------------------- - const NOMAD::Eval_Point * best_f2; - int i; - - for ( i = 0 ; i < 2 ; ++i ) - { - - if ( stop ) - break; - - // minimize f2: - if ( i == 1 ) - { - - // new starting point: - best_f2 = _pareto_front->get_best_f2(); - if ( best_f2 ) - { - _p.set_EXTERN_SIGNATURE ( best_f2->get_signature() ); - _p.reset_X0(); - _p.set_X0 ( *best_f2 ); - } - - // LH_SEARCH: - if ( lh_pi > 0 ) - _p.set_LH_SEARCH ( lh_pi , 0 ); - else if ( lh_p0 > 0 ) - _p.set_LH_SEARCH ( 0 , 0 ); - - // MAX_BB_EVAL: - if ( max_bbe >= 0 ) - { - int bbe = max_bbe + ( (lh_pi > 0 ) ? lh_pi : 0 ); - if ( overall_bbe >= 0 ) - { - if ( bbe > overall_bbe ) - bbe = overall_bbe; - int global_bbe = multi_stats.get_bb_eval(); - if ( global_bbe + bbe > overall_bbe ) - bbe = overall_bbe - global_bbe; - } - _p.set_MAX_BB_EVAL ( bbe ); - } - - if ( _p.to_be_checked() ) - _p.check ( false , // remove_history_file = false - true , // remove_solution_file = true - true ); // remove_stats_file = true - - // Signature has changed and the pointer to the mesh must be updated - _mesh=_p.get_signature()->get_mesh(); - - } - - // set weights/reference: - ev->set_weights ( 1-i , i ); - ev->set_ref ( NULL ); - - // launch the single optimization: - multi_launch_single_opt ( iter_dd , - mads_runs , - overall_bbe , - *ev , - stagnation_cnt , - multi_stats , - stop , - stop_reason ); - } - - const NOMAD::Point * ref; - const NOMAD::Pareto_Point * xj; - NOMAD::Double delta_j; - - // the LH search is disabled: - _p.set_LH_SEARCH ( 0 , 0 ); - - // MAX_BB_EVAL reset: - if ( max_bbe > 0 && ( lh_p0 > 0 || lh_pi > 0 ) ) - { - int bbe = max_bbe; - if ( overall_bbe >= 0 ) - { - if ( bbe > overall_bbe ) - bbe = overall_bbe; - - int global_bbe = multi_stats.get_bb_eval(); - if ( global_bbe + bbe > overall_bbe ) - bbe = overall_bbe - global_bbe; - } - _p.set_MAX_BB_EVAL ( bbe ); - } - - // MULTI-MADS main loop: - // --------------------- - const NOMAD::Eval_Point * x0_tmp; - - while ( !stop ) - { - - // get the reference point from the Pareto front: - ref = _pareto_front->get_ref ( xj , delta_j ); - - if ( !xj ) - { - stop = true; - stop_reason = NOMAD::MULTI_NO_PARETO_PTS; - break; - } - - // use delta as stopping criterion: - if ( use_delta_crit ) - { - if ( delta_j.is_defined() && delta_j > 0.0 ) - multi_set_min_poll_size ( lb , ub , Delta_0 , delta_j ); - else - _p.set_MIN_POLL_SIZE ( original_min_poll_size ); - } - - // new starting point: - x0_tmp = xj->get_element(); - _p.set_EXTERN_SIGNATURE ( x0_tmp->get_signature() ); - _p.reset_X0(); - _p.set_X0 ( *x0_tmp ); - - _p.check ( false , // remove_history_file = false - true , // remove_solution_file = true - true ); // remove_stats_file = true - - // a reference point has been found: optimization - // with reference-based function: - if ( ref ) - { - - // set reference: - ev->set_ref ( ref ); - - // launch the single optimization: - multi_launch_single_opt ( iter_dd , - mads_runs , - overall_bbe , - *ev , - stagnation_cnt , - multi_stats , - stop , - stop_reason ); - - delete ref; - ev->set_ref ( NULL ); - } - - // no reference available: two optimizations ( f1(x) and f2(x) ): - else - { - - // for the stagnation check: - const NOMAD::Eval_Point * pp_before; - int stagnation_cnt_before , overall_bbe_before; - bool check_1 = false; - - // loop on f1 and f2: - for ( i = 0 ; i < 2 ; ++i ) - { - - if ( stop ) - break; - - // minimize f2: - if ( i == 1 ) - { - - // new starting point: - best_f2 = _pareto_front->get_best_f2(); - if ( best_f2 ) - { - _p.set_EXTERN_SIGNATURE ( best_f2->get_signature() ); - _p.reset_X0(); - _p.set_X0 ( *best_f2 ); - } - else - _p.set_X0 ( *x0_tmp ); - - _p.check ( false , // remove_history_file = false - true , // remove_solution_file = true - true ); // remove_stats_file = true - } - - // set weights/reference: - ev->set_weights ( 1-i , i ); - ev->set_ref ( NULL ); - - stagnation_cnt_before = stagnation_cnt; - overall_bbe_before = overall_bbe; - pp_before = ( _pareto_front->size() == 1 ) ? - _pareto_front->begin() : NULL; - - // launch the single optimization: - multi_launch_single_opt ( iter_dd , - mads_runs , - overall_bbe , - *ev , - stagnation_cnt , - multi_stats , - stop , - stop_reason ); - - // stagnation check: - if ( stagnation_cnt > stagnation_cnt_before && - overall_bbe == overall_bbe_before && - _pareto_front->size() == 1 && - _pareto_front->begin() == pp_before ) - { - - if ( i == 0 ) - check_1 = true; - else if ( check_1 ) - { - stop = true; - stop_reason = NOMAD::MULTI_STAGNATION; - } - } - } - } - - } // end of MULTI-MADS main loop - // --------------------------- - - - // parameters re-initialization and final displays: - if ( ! _p.get_signature()->has_categorical() ) // Dimension may change when categorical variables are present. This may pose problem for the check. Hence we add a test -> when categorical variables are present, the parameters are not set back to their initial state at the end of the multi-objective optimization. - { - _p.reset_X0(); - size_t nx0 = x0s.size(); - if ( nx0 > 0 ) - { - for ( size_t k = 0 ; k < nx0 ; ++k ) - { - _p.set_X0 ( *x0s[k] ); - delete x0s[k]; - } - } - else if ( !x0_cache_file.empty() ) - _p.set_X0 ( x0_cache_file ); - - if ( use_delta_crit ) - _p.set_MIN_POLL_SIZE ( original_min_poll_size ); - - } - _p.set_MAX_BB_EVAL ( max_bbe ); - _p.set_DISPLAY_DEGREE ( old_dd ); - _p.set_STATS_FILE ( old_stats_file_name , old_stats_file ); - _p.set_SOLUTION_FILE ( old_sol_file ); - _p.set_LH_SEARCH ( lh_p0 , lh_pi ); - _p.set_CACHE_SAVE_PERIOD ( old_csp ); - _p.set_L_CURVE_TARGET ( old_lct ); - - - _p.check ( false , // remove_history_file = false - true , // remove_solution_file = true - true ); // remove_stats_file = true - - // reset MADS stats from MULTI-MADS stats: - _stats = multi_stats; - - // final cache save (overwrite=true): - _ev_control.save_caches ( true ); - -#ifndef R_VERSION - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - { - std::ostringstream msg; - msg << "end of run (" << stop_reason << ")"; - out << std::endl << NOMAD::close_block ( msg.str() ) << std::endl; - } -#endif - - - // multi-objective final displays: - if ( _p.get_nb_obj() > 1 ) - { - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.open_block ( "NOMAD final display" ); - - display(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block(); - } - - } // end of the try block - - catch ( std::exception & e ) - { - -#ifdef USE_MPI - if ( NOMAD::Slave::are_running() ) - NOMAD::Slave::stop_slaves ( out ); -#endif - - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , e.what() ); - } - - // stop the slaves: -#ifdef USE_MPI - if ( NOMAD::Slave::are_running() && stop_slaves_here ) - NOMAD::Slave::stop_slaves ( out ); -#endif - - return stop_reason; -} - -/*---------------------------------------------------------*/ -/* one MADS iteration (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::iteration ( bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - - bool forbid_poll_size_stop = false; - - // force quit (by pressing ctrl-c): - if ( !stop && NOMAD::Mads::_force_quit ) - { - stop = true; - stop_reason = NOMAD::CTRL_C; - return; - } - - // poll center selection: - ( ( _p.get_opt_only_sgte() ) ? - _sgte_barrier : _true_barrier ).select_poll_center ( success ); - - // displays: - const NOMAD::Display & out = _p.out(); - if ( out.get_iter_dd() == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::open_block ( "MADS iteration " - + NOMAD::itos ( _stats.get_iterations() ) ) - << std::endl; - display_iteration_begin(); - - // SEARCH: - // ------- - search ( stop , stop_reason , success , new_feas_inc , new_infeas_inc ); - - // POLL: - // ----- - if ( success != NOMAD::FULL_SUCCESS ) - poll ( stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc , - forbid_poll_size_stop ); - - // UPDATES: - // -------- - - NOMAD::Point old_r=_mesh->get_mesh_indices(); - - if ( !stop ) - { - // OrthogonalMesh update using success status and direction of success (when present) - if ( new_feas_inc ) - { - _mesh=new_feas_inc->get_signature()->get_mesh(); - _mesh->update ( success, new_feas_inc->get_direction() ); - } - else if ( new_infeas_inc ) - { - _mesh=new_infeas_inc->get_signature()->get_mesh(); - _mesh->update ( success, new_infeas_inc->get_direction()); - } - else - _mesh->update ( success ); - - // check the min mesh/poll sizes stopping criteria - _mesh->check_min_mesh_sizes( stop , stop_reason ); - - // if the Delta_k^p stopping criterion is met with integer variables, - // the last set of directions must have a minimal coordinate of 1; - // otherwise the stopping criterion is disabled at this iteration: - if ( forbid_poll_size_stop && stop && stop_reason == NOMAD::DELTA_P_MIN_REACHED ) - { - stop = false; - stop_reason = NOMAD::NO_STOP; - } - - // display: - if ( _p.out().get_iter_dd() == NOMAD::FULL_DISPLAY ) - { - - _p.out() << std::endl << NOMAD::open_block ( "OrthogonalMesh update" ) - << "previous mesh indices: ( " << old_r << " )" << std::endl - << "new mesh indices : ( " << _mesh->get_mesh_indices() << " )" << std::endl - << NOMAD::close_block() << std::endl; - } - - // periodic cache save (overwrite=false): - if ( _p.get_cache_save_period() > 0 && - _stats.get_iterations()%_p.get_cache_save_period() == - _p.get_cache_save_period() - 1 ) - _ev_control.save_caches ( false ); - } - - // number of iterations: - _stats.add_iteration(); - if ( !stop && - _p.get_max_iterations() > 0 && - _stats.get_iterations() >= _p.get_max_iterations() ) - { - stop = true; - stop_reason = NOMAD::MAX_ITER_REACHED; - } - - // max cache memory: - if ( !stop && - _p.get_max_cache_memory() > 0.0 && - _ev_control.get_cache().size_of() > 1048576*_p.get_max_cache_memory() ) - { - stop = true; - stop_reason = NOMAD::MAX_CACHE_MEMORY_REACHED; - } - - // L_CURVE_TARGET stopping criterion: - if ( _L_curve && !stop ) - { - int bbe = _stats.get_bb_eval(); - if ( success == NOMAD::FULL_SUCCESS ) - { - if ( new_feas_inc ) - _L_curve->insert ( bbe , new_feas_inc->get_f() ); - } - else if ( success == NOMAD::UNSUCCESSFUL && _L_curve->check_stop ( bbe ) ) - { - stop = true; - stop_reason = NOMAD::L_CURVE_TARGET_REACHED; - } - } - - // call the user-defined function Evaluator::update_iteration(): - if ( _p.get_user_calls_enabled() ) - { - bool stop_before = stop; - - - NOMAD::Pareto_Front * pf = ( ( _pareto_front ) ? _pareto_front:(new NOMAD::Pareto_Front) ); - - _ev_control.get_evaluator()->update_iteration ( success , - _stats , - _ev_control , - _true_barrier , - _sgte_barrier , - *pf , - stop ); - - if ( ! _pareto_front ) - delete pf; - - - if ( !stop_before && stop ) - stop_reason = NOMAD::USER_STOPPED; - } - - // if the algorithms stops, we set the mesh index to the value - // it had before the mesh update: - if ( stop ) - { - _mesh->set_mesh_indices( old_r ); - } - - // displays at the end of an iteration: - display_iteration_end ( stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc ); - - - - // displays: - if ( out.get_iter_dd() == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "end of iteration " - + NOMAD::itos ( _stats.get_iterations()-1 ) ); -} - -/*---------------------------------------------------------*/ -/* the poll (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::poll ( bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc , - bool & forbid_poll_size_stop ) -{ - forbid_poll_size_stop = false; - - if ( stop ) - return; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - - success = NOMAD::UNSUCCESSFUL; - new_feas_inc = NULL; - new_infeas_inc = NULL; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "MADS poll" ) << std::endl; - - - const NOMAD::Eval_Point * x; - size_t offset = 0; - - std::vector signatures; - - const NOMAD::Barrier & barrier = get_active_barrier(); - std::list::const_iterator it , end; - - - // poll centers: - const NOMAD::Eval_Point * poll_centers[2] , * poll_center; - poll_centers[0] = barrier.get_poll_center(); - poll_centers[1] = (_p.use_sec_poll_center()) ? - barrier.get_sec_poll_center() : NULL; - - if ( !poll_centers[0] && !poll_centers[1] ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::poll(): could not get a poll center" ); - - - // Keep original directions + reduction in reducedPollDirs - std::list *dirs=new std::list[2]; - std::list *reducedPollDirs=new std::list[2]; - std::list::iterator itDir; - - - // loop on the two poll centers for creation of evaluation point - // ----------------------------- - NOMAD::poll_type i_pc = NOMAD::PRIMARY; - poll_center = poll_centers[NOMAD::PRIMARY]; - - bool reducePollToNDir=false; - - while ( true ) - { - if ( poll_center ) - { - // add the poll center signature - signatures.push_back(poll_center->get_signature()); - - // Creation of the poll directions - set_poll_directions ( dirs[i_pc] , i_pc , offset , *poll_center , stop , stop_reason ); - - // Reduction is applied only to achieve ortho n+1 - reducePollToNDir=dirs_have_orthomads_np1(dirs[i_pc]); - - // creation of the poll trial points in the evaluator control: - if (reducePollToNDir) - { - - // Keep poll directions unchanged (store directions even those that will be snaped to bounds) - reducedPollDirs[i_pc].assign(dirs[i_pc].begin(),dirs[i_pc].end()); - - _ev_control_for_sorting.clear_eval_lop(); - - - // Sort the directions only if mesh is not finest - if ( ! _mesh->is_finest() ) - { - - // 1st sorting of points based on feas. or infeas. success direction. IMPORTANT removes out of bounds -> this justifies to proceede in two steps - set_poll_trial_points(dirs[i_pc],offset,*poll_center,stop,stop_reason,true); - if (stop) - { - delete[] dirs; - delete[] reducedPollDirs; - return; - } - -#ifdef USE_MPI - // asynchronous mode: wait for truth evaluations in progress: - if ( _p.get_asynchronous() ) - { - std::list eval_pts; - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - eval_pts ); - } -#endif - - // 2nd sorting of points based on model and surrogate if available - _ev_control_for_sorting.ordering_lop( NOMAD::POLL,stop,stop_reason,_true_barrier,_sgte_barrier ); - if (stop) - { - delete[] dirs; - delete[] reducedPollDirs; - return; - } - } - - - - // reduce the number of poll direction using dir indices from ev_control_for_sorting and original poll directions (reducedPollDirs) - bool hasBeenReduced=set_reduced_poll_to_n_directions(reducedPollDirs[i_pc],*poll_center); - - - // if hasBeenReduced than reassign dirs for setting poll trial points (reduced) - // else original dirs are considered - if (hasBeenReduced) - dirs[i_pc].assign(reducedPollDirs[i_pc].begin(),reducedPollDirs[i_pc].end()); - - } - - set_poll_trial_points(dirs[i_pc],offset,*poll_center,stop,stop_reason,false); - offset = dirs[i_pc].size(); - - if (!reducePollToNDir) - { - // 2nd sorting of points based on model and surrogate if available - _ev_control.ordering_lop( NOMAD::POLL,stop,stop_reason,_true_barrier,_sgte_barrier ); - } - - - } - - if (stop) - { - delete[] dirs; - delete[] reducedPollDirs; - return; - } - - // loop increment: - if ( i_pc == NOMAD::PRIMARY) - { - i_pc = NOMAD::SECONDARY; - poll_center = poll_centers[NOMAD::SECONDARY]; - } - else - break; - } - - - // display the re-ordered list of poll trial points: - if ( display_degree == NOMAD::FULL_DISPLAY && !stop ) - { - const std::set & poll_pts = _ev_control.get_eval_lop(); - if (!reducePollToNDir) - out << std::endl << NOMAD::open_block ( "re-ordered list of " - + NOMAD::itos ( poll_pts.size() ) - + " poll trial points." ); - else - out << std::endl << NOMAD::open_block ( "re-ordered and reduced (dynamic directions maybe added after evaluations) list of " - + NOMAD::itos ( poll_pts.size() ) - + " poll trial points" ); - - std::set::const_iterator end2 = poll_pts.end() , it2; - for ( it2 = poll_pts.begin() ; it2 != end2 ; ++it2 ) - { - x = it2->get_point(); - x->display_tag ( out ); - out << " : ( "; - x->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )"; - if ( x->get_direction() ) - out << " (dir " << x->get_direction()->get_index() << ")"; - out << std::endl; - } - out.close_block(); - } - - - _stats.add_poll_pts ( _ev_control.get_nb_eval_points() ); - - // the directions are checked to satisfy a minimum - // poll size with integer variables: - check_directions ( forbid_poll_size_stop ); - - // eval_list_of_points (poll): - // --------------------------- - std::list *evaluated_pts=new std::list; - _ev_control.eval_list_of_points ( NOMAD::POLL , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - evaluated_pts ); - - - // If ortho mads n+1, complete poll with additional evaluations obtained dynamically - if (!stop && success !=NOMAD::FULL_SUCCESS && _p.has_dynamic_direction()) - { - _ev_control.reset(); - - // loop again on the two poll centers to obtain dynamic direction - // --------------------------------------------------------------------------- - i_pc = NOMAD::PRIMARY; - poll_center = poll_centers[NOMAD::PRIMARY]; - offset=0; - while ( true ) - { - if ( poll_center && NOMAD::Mads::dirs_have_orthomads_np1(reducedPollDirs[i_pc])) - { - std::list dyn_dirs; - -#ifdef USE_MPI - // asynchronous mode: wait for the evaluations in progress: - if ( _p.get_asynchronous() ) - { - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - *evaluated_pts ); - } -#endif - - bool hasNewDynDir=get_dynamic_directions (reducedPollDirs[i_pc], - dyn_dirs, - *poll_center); - - - // Set new poll points obtained dynamically - if (hasNewDynDir) - { - set_poll_trial_points(dyn_dirs, - offset, - *poll_center, - stop, - stop_reason, - false); - - if (stop) - { - delete evaluated_pts; - delete[] dirs; - delete[] reducedPollDirs; - return; - } - } - offset = dyn_dirs.size(); - } - // loop increment: - if ( i_pc == NOMAD::PRIMARY ) - { - i_pc = NOMAD::SECONDARY; - poll_center = poll_centers[NOMAD::SECONDARY]; - } - else - break; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - const std::set & poll_pts = _ev_control.get_eval_lop(); - out << std::endl << NOMAD::open_block ( "re-ordered and complete (dynamic directions added) list of " - + NOMAD::itos ( poll_pts.size() ) - + " poll trial points" ); - - std::set::const_iterator end2 = poll_pts.end() , it2; - for ( it2 = poll_pts.begin() ; it2 != end2 ; ++it2 ) { - x = it2->get_point(); - x->display_tag ( out ); - out << " : ( "; - x->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )"; - if ( x->get_direction() ) - out << " (dir " << x->get_direction()->get_index() << ")"; - out << std::endl; - } - out.close_block(); - } - - - - - // Eval additional point(s) : - // --------------------------- - _ev_control.eval_list_of_points ( NOMAD::POLL , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - if (success==NOMAD::FULL_SUCCESS) - _stats.add_nb_success_dyn_dir(); - - } - - delete evaluated_pts; - delete[] dirs; - delete[] reducedPollDirs; - - - // extended poll for categorical variables: - // ---------------------------------------- - if ( !stop && - _extended_poll && - success != NOMAD::FULL_SUCCESS && - _p.get_extended_poll_enabled() ) { - - // display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "MADS extended poll" ) << std::endl; - -#ifdef USE_MPI - // asynchronous mode: wait for the evaluations in progress: - if ( _p.get_asynchronous() ) { - std::list evaluated_pts; - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - evaluated_pts ); - } -#endif - - // reset the extended poll object: - _extended_poll->poll_reset(); - - // call the user defined method changing the categorical variables - // (this creates the list of extended poll points): - _extended_poll->construct_extended_points ( *barrier.get_poll_center() ); - - // add the signatures in use to the list of poll signatures: - { - const std::set & - tmp = _extended_poll->get_poll_signatures(); - std::set::const_iterator it , end = tmp.end(); - for ( it = tmp.begin() ; it != end ; ++it ) - signatures.push_back ( it->get_signature() ); - } - - // execute the extended poll: - int nb_ext_poll_pts; - _extended_poll->run ( *this , - nb_ext_poll_pts , - stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc ); - - // stats updates: - _stats.add_ext_poll_pts ( nb_ext_poll_pts ); - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_ext_poll_succ(); - _stats.add_nb_ext_polls(); - - // display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::close_block ( "end of extended poll" ) << std::endl; - } - - // stats updates: - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_poll_success(); - - _stats.add_nb_poll_searches(); - - // success directions (feasible and infeasible): - update_success_directions ( new_feas_inc , true ); - update_success_directions ( new_infeas_inc , false ); - -#ifdef DEBUG - if ( !new_feas_inc && !new_infeas_inc ) - out << "No new feasible or infeasible incumbent" << std::endl << std::endl; -#endif - - // check the PEB constraints: if we have a new best infeasible - // incumbent from another infeasible incumbent - // ( active_barrier.check_PEB_constraints() ): - if ( _p.get_barrier_type() == NOMAD::PEB_P && new_infeas_inc && - new_infeas_inc->get_poll_center_type() == NOMAD::INFEASIBLE ) - ( ( _p.get_opt_only_sgte() ) ? _sgte_barrier : _true_barrier ).check_PEB_constraints( *new_infeas_inc , display_degree==NOMAD::FULL_DISPLAY ); - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block ( "end of poll" ); -} - -/*---------------------------------------------------------*/ -/* Reduction to n directions for each direction group */ -/* of a poll center. (private) */ -/* return false if not enough directions provided/returned */ -/*---------------------------------------------------------*/ -// A direction group corresponds to a variable group having directions. -// A variable group of categorical variables does not possess directions. -bool NOMAD::Mads::set_reduced_poll_to_n_directions(std::list & dirs, - const NOMAD::Eval_Point & poll_center) -{ - // get the number of free variables using the signature (because of extended poll and changing signature) - NOMAD::Signature * cur_signature = poll_center.get_signature(); - size_t n = cur_signature->get_n()-cur_signature->get_nb_fixed_variables() ; - - // No direction for categorical variables - size_t n_cat = cur_signature->get_n_categorical(); - - // Verify that enough directions for reduction are provided - if ( dirs.size()::iterator itDirs; - size_t maxDirGroupIndex=0; - size_t dgi; - for (itDirs=dirs.begin();itDirs!=dirs.end() ; ++itDirs) - { - dgi=(*itDirs).get_dir_group_index(); - if (dgi>maxDirGroupIndex) maxDirGroupIndex=dgi; - } - - std::list TmpDirs(dirs); - dirs.clear(); - - // Loop on each direction group - for (dgi=0;dgi<=maxDirGroupIndex;++dgi) - { - - // Get all poll directions with a given direction group index + Get a vector of unique indices for those directions - std::vector pollDirs; - std::vector pollDirIndices; - bool containsOrthoMads=false; - for (itDirs=TmpDirs.begin();itDirs!=TmpDirs.end() ; ++itDirs) - { - if ((*itDirs).get_dir_group_index()==static_cast(dgi)) - { - pollDirs.push_back(*itDirs); - pollDirIndices.push_back((*itDirs).get_index()); - if (!containsOrthoMads) - containsOrthoMads=NOMAD::dir_is_orthomads((*itDirs).get_type()); - } - } - - - std::list sortedDirs; - std::list::iterator itSortedDirs; - // Sort the directions only if mesh is not finest - if ( !_mesh->is_finest() ) - { - - const std::set & LOP=_ev_control_for_sorting.get_eval_lop(); - - if ( LOP.size()==0 ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::set_reduced_poll_to_n_directions(): the _ev_control_for_sorting does not have a list of evaluation points." ); - - - // Get all directions from ev_control ordered lop (list of evaluation points) with a given direction group index and given poll center - // Get a set of unique indices of those directions - std::list sortedDirIndices; - std::set indices; - std::list::iterator itSortedDirIndices; - std::set::const_iterator citLOP; - for (citLOP=LOP.begin();citLOP!=LOP.end();++citLOP) - { - const NOMAD::Eval_Point *eval_point=(*citLOP).get_point(); - if (eval_point->get_direction()->get_dir_group_index()==static_cast(dgi) && - *(eval_point->get_poll_center())==poll_center) - { - int index=eval_point->get_direction()->get_index(); - if ( indices.size() == 0 || indices.find(index) == indices.end() ) // if the index is already in indices no need to add it in sortedDirIndices to avoid duplicate. - sortedDirIndices.push_back(index); - indices.insert(index); // If the index is already in the set IT IS NOT INSERTED --> set of unique sort integers - - } - - } - - if ( sortedDirIndices.size()==0 ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::set_reduced_poll_to_n_directions(): no directions with proper group index available from _ev_control_for_sorting!" ); - - // A direction from _ev_control may have been suppressed if it does not satisfy bound constraint and is not snapped to bounds - // --> complete sorted direction with remaining directions in poll dirs - // - // 2 - Add poll directions (from tmpDirs) in the same order as sorted direction indices (from ev_control) - std::vector::iterator itPollDirIndices; - std::vector::iterator itPollDirs=pollDirs.begin(); - size_t pos; - for ( itSortedDirIndices = sortedDirIndices.begin() ; itSortedDirIndices != sortedDirIndices.end() ; ++itSortedDirIndices) - { - itPollDirIndices=find(pollDirIndices.begin(),pollDirIndices.end(),*itSortedDirIndices); - if ( itPollDirIndices!=pollDirIndices.end() ) - { - pos=distance(pollDirIndices.begin(),itPollDirIndices); - itPollDirs=pollDirs.begin(); - std::advance(itPollDirs,pos); - sortedDirs.push_back(*itPollDirs); - } - } - // 3 - complete with remaining pollDirs directions - if ( sortedDirs.size() != pollDirs.size() ) - { - itPollDirs=pollDirs.begin(); - for ( itPollDirIndices = pollDirIndices.begin() ; itPollDirIndices != pollDirIndices.end() ; ++itPollDirIndices,++itPollDirs) - { - itSortedDirIndices=find(sortedDirIndices.begin(),sortedDirIndices.end(),*itPollDirIndices); - if ( itSortedDirIndices == sortedDirIndices.end() ) - // Handle the case where poll direction not in sorted directions --> put it at the end - sortedDirs.push_back(*itPollDirs); - } - } - - } - else - sortedDirs.assign(pollDirs.begin(),pollDirs.end()); - - // Make a spanning set of directions (this is slightly different Ortho n+1 paper but still we have the garantee that Dk grows asymptotically dense because D^o_k has not been sorted if mesh_index_is_max) - // Sequentially add sorted directions that increase the rank in two situations: - // - If mesh is not finest -> consider all directions for adding -> n directions - // - If mesh is finest but some ORTHO MADS directions are present -> only consider ortho mads dir for adding -> n directions - // - Else, all directions are considered -> more than n directions - // See paper Ortho n+1 paper for details - size_t currentRank=get_rank_from_dirs(dirs); - for (itSortedDirs=sortedDirs.begin();itSortedDirs!=sortedDirs.end();++itSortedDirs) - { - dirs.push_back(*itSortedDirs); - if ( !_mesh->is_finest() || ( _mesh->is_finest() && containsOrthoMads)) - { - size_t rank=get_rank_from_dirs(dirs); - if (rank>currentRank && rank<=n-n_cat && NOMAD::dir_is_orthomads((*itSortedDirs).get_type())) - currentRank++; - else - dirs.pop_back(); - } - } - - - } - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - if ( dirs.size()!=n-n_cat ) - { - if (display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << NOMAD::open_block ( "The number of reduced directions is lower than n-n_categorical: "); - out << dirs.size() << ". No reduction is performed." << std::endl; - out << NOMAD::close_block(); - } - return false; - } - return true; -} - -/*----------------------------------------------------------------*/ -/* Get the rank from a list of directions (private) */ -/*----------------------------------------------------------------*/ -int NOMAD::Mads::get_rank_from_dirs(const std::list & dirs) -{ - if (dirs.size()==0) - return 0; - - std::list::const_iterator it=dirs.begin(); - size_t m=(*it).size(); - size_t n=dirs.size(); - - double ** M = new double *[m]; - for (size_t i=0 ; i(i)].value() ; - ++it; - } - } - - int rank=NOMAD::get_rank(M,m,n); - - for (size_t i = 0 ; i < m ; ++i ) - { - delete[] M[i]; - } - delete[] M; - return rank; - -} - -/*---------------------------------------------------------------------------------------*/ -/* compute a prospect point by optimizing quadratic models of obj(s) and constraints */ -/* (private) */ -/*---------------------------------------------------------------------------------------*/ -bool NOMAD::Mads::optimize_quad_model ( const NOMAD::Eval_Point & poll_center , - const std::list & dirs , - NOMAD::Point & prospect_point ) -{ - const NOMAD::Display & out = _p.out(); - - // surrogate or truth model evaluations: - NOMAD::eval_type ev_type = - ( _p.get_opt_only_sgte() ) ? NOMAD::SGTE : NOMAD::TRUTH; - - // active cache: - const NOMAD::Cache & cache = get_cache(); - - NOMAD::Point delta,Delta; - NOMAD::Signature * signature=poll_center.get_signature(); - _mesh->get_delta ( delta ); - _mesh->get_Delta ( Delta ); - - // compute the interpolation radius: points in Y must be at - // a max distance of ms_radius_factor times Delta^k: - NOMAD::Point interpolation_radius = Delta; - interpolation_radius *= _p.get_model_quad_radius_factor(); - - - // Epsilon for quad model hypercube scaling - NOMAD::Double epsilon = _p.get_model_np1_quad_epsilon(); - -#ifdef DEBUG - out << std::endl << NOMAD::open_block ( "Quadratic model for (n+1)th prospect point") << std::endl - << "model construction for " << ev_type << std::endl - << "nbr of cache pts: " << cache.size() << std::endl - << "mesh indices : ( " << _mesh->get_mesh_indices () << " )" << std::endl - << "poll center : ( " << poll_center << " )" << std::endl - << "poll size : ( " << Delta << " )" << std::endl - << "interpol. radius: ( " << interpolation_radius << " )" << std::endl - << "epsilon hypercube: ( " << epsilon << " )" << std::endl;; -#endif - - - // creation of the model for all bb outputs: - std::vector bbot = _p.get_bb_output_type(); - NOMAD::Quad_Model model ( out , bbot , cache , *signature ); - NOMAD::Model_Stats tmp_stats; - NOMAD::Clock clock; - - // flag to detect model or optimization errors: - bool error = true; - - // construct interpolation set Y: - int min_Y_size = _p.get_model_quad_min_Y_size(); - int max_Y_size = _p.get_model_quad_max_Y_size(); - - model.construct_Y ( poll_center , interpolation_radius , max_Y_size ); - - int nY = model.get_nY(); - -#ifdef DEBUG - out << std::endl << "number of points in Y: " << nY; - if ( nY < 2 || ( min_Y_size < 0 && nY <= model.get_nfree() ) ) - out << " (not enough)"; - out << std::endl; -#endif - - if ( nY < 2 || ( min_Y_size < 0 && nY <= model.get_nfree() ) ) - tmp_stats.add_not_enough_pts(); - else - { -#ifdef DEBUG - out << std::endl; - model.display_Y ( out , "unscaled interpolation set Y" ); -#endif - - // define scaling with rotation: obtain an hypercube [0,1]^n formed by truncated directions - model.define_scaling_by_directions ( dirs, delta ,epsilon); - -#ifdef DEBUG - out << std::endl; - model.display_Y ( out , "scaled interpolation set Ys" ); -#endif - - // error check: - if ( model.get_error_flag() ) - tmp_stats.add_construction_error(); - - // no model error: - else { - - // construct model: - model.construct ( _p.get_model_quad_use_WP() , NOMAD::SVD_EPS , NOMAD::SVD_MAX_MPN , max_Y_size ); - tmp_stats.add_construction_time ( clock.get_CPU_time() ); - tmp_stats.update_nY ( model.get_nY() ); - - // display model characteristics: -#ifdef DEBUG - out << std::endl; - model.display_model_coeffs ( out ); - out << std::endl; - model.display_Y_error ( out ); -#endif - - - // count model: - if ( ev_type == NOMAD::TRUTH ) - tmp_stats.add_nb_truth(); - else - tmp_stats.add_nb_sgte(); - - switch ( model.get_interpolation_type() ) - { - case NOMAD::MFN: - tmp_stats.add_nb_MFN(); - break; - case NOMAD::WP_REGRESSION: - tmp_stats.add_nb_WP_regression(); - break; - case NOMAD::REGRESSION: - tmp_stats.add_nb_regression(); - break; - default: - break; - } - - // check model error flag: - const NOMAD::Double & cond = model.get_cond(); - if ( model.get_error_flag() || - !cond.is_defined() || - cond > NOMAD::SVD_MAX_COND ) - { - if ( model.get_error_flag() ) - tmp_stats.add_construction_error(); - else - tmp_stats.add_bad_cond(); - } - else - { - int n = model.get_n(); - std::string error_str; - int i; - - // initial displays: - if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "Quad model optimization for prospect point"; - out << std::endl << NOMAD::open_block ( oss.str() ); - } - - // parameters creation: - NOMAD::Parameters model_param ( out ); - - // number of variables: - model_param.set_DIMENSION ( n ); - - // blackbox outputs: - model_param.set_BB_OUTPUT_TYPE ( bbot ); - - // barrier parameters: - model_param.set_H_MIN ( _p.get_h_min () ); - model_param.set_H_NORM ( _p.get_h_norm() ); - - // starting points: - model_param.set_X0 ( NOMAD::Point ( n , 500.0 ) ); - - // fixed variables: - for ( i = 0 ; i < n ; ++i ) - if ( model.variable_is_fixed(i) || _p.variable_is_fixed(i) ) - model_param.set_FIXED_VARIABLE(i); - - // no model search and no model ordering: - model_param.set_MODEL_SEARCH ( false ); - model_param.set_MODEL_EVAL_SORT ( false ); - model_param.set_DIRECTION_TYPE (NOMAD::ORTHO_2N); // use 2N for model search rather than the default Ortho n+1 - - // display: - model_param.set_DISPLAY_DEGREE ( NOMAD::NO_DISPLAY ); - - // mesh: use isotropic mesh - model_param.set_ANISOTROPIC_MESH ( false ); - model_param.set_MESH_UPDATE_BASIS ( 4.0 ); - model_param.set_MESH_COARSENING_EXPONENT ( 1 ); - model_param.set_MESH_REFINING_EXPONENT ( -1 ); - model_param.set_INITIAL_MESH_INDEX ( 0 ); - model_param.set_INITIAL_MESH_SIZE ( NOMAD::Point ( n , 100.0 ) ); - - // maximum number of evaluations: - model_param.set_MAX_BB_EVAL ( 50000 ); - - model_param.set_SNAP_TO_BOUNDS ( true ); - - // disable user calls: - model_param.set_USER_CALLS_ENABLED ( false ); - - // set flags: - bool flag_check_bimads , flag_reset_mesh , flag_reset_barriers , flag_p1_active; - NOMAD::Mads::get_flags ( flag_check_bimads , - flag_reset_mesh , - flag_reset_barriers , - flag_p1_active ); - - NOMAD::Mads::set_flag_check_bimads (false ); - NOMAD::Mads::set_flag_reset_mesh ( true ); - NOMAD::Mads::set_flag_reset_barriers ( true ); - NOMAD::Mads::set_flag_p1_active ( false ); - - // bounds to optimize away from n first direction - // Bound are consistent with model evaluator: x in [0;1000] for optimziation -> x in [-1;1] for model evaluation - NOMAD::Point lb ( n , 0.0 ); - NOMAD::Point ub ( n , 1000.0 ); - model_param.set_LOWER_BOUND ( lb ); - model_param.set_UPPER_BOUND ( ub ); - - try - { - - // parameters validation: - model_param.check(); - - // model evaluator creation: - NOMAD::Evaluator *ev; - if (model_param.get_nb_obj()==2) - ev =new NOMAD::Multi_Obj_Quad_Model_Evaluator( model_param , model ); - else - ev=new NOMAD::Single_Obj_Quad_Model_Evaluator( model_param , model ); - - // algorithm creation and execution: - NOMAD::Mads mads ( model_param , ev ); - - NOMAD::Phase_One_Evaluator * p1ev=NULL; - if ( model_param.get_nb_obj() >= 2 && ! flag_check_bimads ) - { - p1ev = new NOMAD::Phase_One_Evaluator ( model_param , *ev ); - mads.get_evaluator_control().set_evaluator ( p1ev ); - } - NOMAD::stop_type st = mads.run(); - - - delete ev; - if (p1ev) - delete p1ev; - - // reset flags: - NOMAD::Mads::set_flag_check_bimads ( flag_check_bimads ); - NOMAD::Mads::set_flag_reset_mesh ( flag_reset_mesh ); - NOMAD::Mads::set_flag_reset_barriers ( flag_reset_barriers ); - NOMAD::Mads::set_flag_p1_active ( flag_p1_active ); - - // check the stopping criterion: - if ( st == NOMAD::CTRL_C || st == NOMAD::MAX_CACHE_MEMORY_REACHED ) { - std::ostringstream oss; - oss << "quad model optimization for prospect point: " << st; - error_str = oss.str(); - error = true; - } - - // display solution: - if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - { - NOMAD::Display out_tmp = out; - out_tmp.set_degrees ( NOMAD::NORMAL_DISPLAY ); - out_tmp.open_block("Optimization results"); - mads.display ( out_tmp ); - } - - // get the solution(s): - const NOMAD::Eval_Point * best_feas = mads.get_best_feasible (); - const NOMAD::Eval_Point * best_infeas = mads.get_best_infeasible(); - - - if ( best_infeas ) - { - prospect_point = *best_infeas; - prospect_point *= 0.001; - model.unscale ( prospect_point ); - - if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - { - out << "best infeasible point before unscaling: ( "; - prospect_point.NOMAD::Point::display ( out ); - out << " )" << std::endl; - } - - - } - else if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - out << "no infeasible solution" << std::endl; - - - if ( best_feas ) - { - prospect_point = *best_feas; - prospect_point *= 0.001; - model.unscale ( prospect_point ); - if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - { - out << "best feasible point after unscaling : ( "; - prospect_point.NOMAD::Point::display ( out ); - out << " )" << std::endl; - } - - } - else if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - out << "no feasible solution" << std::endl; - - - if ( !prospect_point.is_defined() ) - { - error = true; - error_str = "optimization error: no solution"; - } - else - error=false; - } - catch ( std::exception & e ) - { - error = true; - error_str = std::string ( "optimization error: " ) + e.what(); - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , error_str ); - } - } - } - } - - // update the stats: - _stats.update_model_stats ( tmp_stats ); - - if ( _p.get_display_degree() == NOMAD::FULL_DISPLAY ) - { - out << std::endl << "Prospect point. from quad. model: "; - if ( !error) - out << "( " << prospect_point << " )" << std::endl; - else - out << "failure" << std::endl; - - out << NOMAD::close_block() << std::endl; - } - -#ifdef DEBUG - out << NOMAD::close_block() << std::endl; -#endif - - return !error; -} - - -/*----------------------------------------------------------------*/ -/* set the poll directions based on signatures (private) */ -/*----------------------------------------------------------------*/ -void NOMAD::Mads::set_poll_directions ( std::list & dirs , - NOMAD::poll_type i_pc , - size_t offset , - const NOMAD::Eval_Point & poll_center , - bool & stop , - NOMAD::stop_type & stop_reason ) -{ - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - - std::list::const_iterator it , end; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - if ( i_pc == NOMAD::SECONDARY ) - out << "secondary "; - out << "poll center: ( "; - poll_center.Point::display ( out, " ", 2, NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // get the poll center's signature: - NOMAD::Signature * cur_signature = poll_center.get_signature(); - - if ( !cur_signature ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::poll(): could not get the poll center's signature" ); - - int n = cur_signature->get_n(); - - if ( n != poll_center.size() ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::poll(): the poll center has an incompatible signature" ); - - // get directions from the signature: - cur_signature->get_directions ( dirs , - i_pc , - poll_center ); - - - - size_t k = 0; - for ( it = dirs.begin() ; it != dirs.end() ; ++it, ++k ) - it->set_index ( static_cast(offset + k) ); - - - - if ( !stop && dirs.empty() ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "Mads::poll(): could not get directions: stop" - << std::endl << NOMAD::close_block() << std::endl; - stop = true; - stop_reason = NOMAD::MESH_PREC_REACHED; - return; - - } - - - // displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - end = dirs.end(); - - int nb_dirs = static_cast(dirs.size()); - - out << std::endl - << NOMAD::open_block ( "poll directions (include mesh size parameter)" ); - for ( it = dirs.begin() ; it != end ; ++it ) - { - out << "dir "; - out.display_int_w ( (*it).get_index() , nb_dirs ); - out << " : " << *it << std::endl; - } - out.close_block(); - } -} - - -/*----------------------------------------------------------------------------------*/ -/* check if a set of directions includes one Ortho-MADS N+1 direction (private) */ -/* (true if at least one direction in the set is of type Ortho-MADS N+1) */ -/*----------------------------------------------------------------------------------*/ -bool NOMAD::Mads::dirs_have_orthomads_np1( const std::list & dirs) -{ - std::list::const_iterator it , end = dirs.end(); - for ( it = dirs.begin() ; it != end ; ++it ) - if ( (*it).get_type()==NOMAD::ORTHO_NP1_QUAD || - (*it).get_type()==NOMAD::ORTHO_NP1_NEG) - return true; - return false; -} - - -/*-------------------------------------------------------------------------*/ -/* check if a dir needs to be obtained from model optimization (private) */ -/* (true if all directions in the set are of type Ortho-MADS N+1 QUAD) */ -/*-------------------------------------------------------------------------*/ -bool NOMAD::Mads::dir_from_model_opt( const std::list & dirs) -{ - std::list::const_iterator it , end = dirs.end(); - for ( it = dirs.begin() ; it != end ; ++it ) - if ( (*it).get_type()!=NOMAD::ORTHO_NP1_QUAD ) - return false; - return true; -} - - - -/*----------------------------------------------------------------*/ -/* set the poll trial points based on poll directions (private) */ -/*----------------------------------------------------------------*/ -void NOMAD::Mads::set_poll_trial_points (std::list &dirs, - size_t offset, - const NOMAD::Eval_Point & poll_center, - bool & stop, - NOMAD::stop_type &stop_reason, - bool sorting) -{ - NOMAD::Signature * cur_signature=poll_center.get_signature(); - NOMAD::poll_center_type pc_type=( poll_center.is_feasible ( _p.get_h_min() ) ) ? NOMAD::FEASIBLE : NOMAD::INFEASIBLE; - - int n = cur_signature->get_n(); - int m = _p.get_bb_nb_outputs(); - const std::vector & bbit = _p.get_bb_input_type(); - - std::list::const_iterator it; - - const NOMAD::Direction * dir; - NOMAD::Eval_Point * pt; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - - int k=0; - for ( it = dirs.begin() ; it != dirs.end() ; ++it ) - { - dir = &(*it); - pt = new NOMAD::Eval_Point ( n , m ); - - // pt = poll_center + dir: with a particular case for binary variables - // equal to 1 with dir=1: the variables are set to 0 (1+1=0 in binary): - for (int i = 0 ; i < n ; ++i ) - (*pt)[i] = ( bbit[i]==NOMAD::BINARY && (*dir)[i]==1.0 && (poll_center)[i]==1.0 ) ? 0.0 : (*pt)[i] = (poll_center)[i] + (*dir)[i]; - - if ( pt->Point::operator == ( poll_center ) ) - delete pt; - else - { - pt->set_signature ( cur_signature ); - pt->set_direction ( dir ); - pt->set_poll_center_type ( pc_type ); - pt->set_poll_center ( &poll_center ); - - // random direction? - if ( NOMAD::dir_is_random ( dir->get_type() ) ) - { - int nb_dirs = static_cast(dirs.size()); - NOMAD::Random_Pickup rp ( nb_dirs ); - pt->set_rand_eval_priority ( rp.pickup() ); - } - - if (!sorting) - _ev_control.add_eval_point ( pt , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - else - { - _ev_control_for_sorting.add_eval_point ( pt , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - ++k; - } - } - - if ( k==0 ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "Mads::poll(): could not generate poll trial points: stop" - << std::endl << NOMAD::close_block() << std::endl; - stop = true; - stop_reason = NOMAD::MESH_PREC_REACHED; - } - - - return; -} - - -/*-------------------------------------------------------------*/ -/* compute the poll directions dynamically (private) */ -/*-------------------------------------------------------------*/ -bool NOMAD::Mads::get_dynamic_directions (const std::list & dirs, - std::list & newDirs, - const NOMAD::Eval_Point & poll_center ) -{ - - const NOMAD::Signature * cur_signature=poll_center.get_signature(); - // get the number of free variables using the signature (because of extended poll and changing signature) - size_t n = cur_signature->get_n()-cur_signature->get_nb_fixed_variables(); - size_t n_cat = cur_signature->get_n_categorical(); - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_poll_dd(); - - // Dynamic completion only if sufficient directions provided: (n-n_cat)->(n-n_cat)+1 - if ( dirs.size() < n-n_cat ) - return false; - - - // Get the maximum number of direction groups - std::list::const_iterator itDir; - int maxDirGroupIndex=0; - int dgi; - for (itDir=dirs.begin();itDir!=dirs.end() ; ++itDir) - { - dgi=(*itDir).get_dir_group_index(); - if (dgi>maxDirGroupIndex) - maxDirGroupIndex=dgi; - } - - // Loop on each direction group to obtain a new direction - for (dgi=0;dgi<=maxDirGroupIndex;++dgi) - { - int maxIndex=0; - - // 1 - Search directions having the same direction group index - std::list rDirs; - std::list::iterator it_fv; - for (itDir=dirs.begin();itDir!=dirs.end() ; ++itDir) - { - if ((*itDir).get_index()>maxIndex) - maxIndex=(*itDir).get_index(); - if ((*itDir).get_dir_group_index()==dgi) - rDirs.push_back(*itDir); - } - - // 2 - add a dynamic direction from a quad model optimization or sum of direction negatives - NOMAD::Direction dyn_dir=get_single_dynamic_direction(rDirs,poll_center); - if ( dyn_dir.get_type()==NOMAD::DYN_ADDED ) - { - dyn_dir.set_index(maxIndex+1); - newDirs.push_back(dyn_dir); - } - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl; - if ( newDirs.size()!= 0 ) - out << NOMAD::open_block ( "Added (n+1)th poll direction(s) (include mesh size parameter)" ); - else - out << NOMAD::open_block ( "Cannot generate a (n+1)th poll direction" ); - - for ( itDir = newDirs.begin() ; itDir != newDirs.end() ; ++itDir ) - { - out << "dir "; - out.display_int_w ( (*itDir).get_index() , static_cast(newDirs.size()) ); - out << " : " << *itDir << std::endl; - } - out.close_block(); - out << std::endl; - - } - - if ( newDirs.size()==0 ) - return false; - - - return true; -} - - - -/*------------------------------------------------------------------------------*/ -/* get a single dynamic direction from incomplete poll */ -/* directions by optimization of a quad model or sum of negative (private) */ -/*------------------------------------------------------------------------------*/ -/* The new direction calculation is described in paper from */ -/* Audet, Ianni, Le Digabel and Tribes : Reducing the number of */ -/* function evaluations in Mesh Adaptive Direct Search Algorithms*/ -/*----------------------------------------------------------------*/ -NOMAD::Direction NOMAD::Mads::get_single_dynamic_direction (const std::list & dirs, - const NOMAD::Eval_Point & poll_center) -{ - const NOMAD::Signature * cur_signature=poll_center.get_signature(); - int n=cur_signature->get_n(); - - NOMAD::Direction Vb1( n , 0.0 ,NOMAD::UNDEFINED_DIRECTION); - - - std::vector alpha; - NOMAD::Double f_pc=(poll_center.is_feasible(_p.get_h_min())) ? poll_center.get_f():poll_center.get_h(); - NOMAD::Double lambda=0; - std::list::const_iterator itDir; - - // -sum(d^i) - for (itDir=dirs.begin();itDir!=dirs.end();++itDir) - { - for (int i=0; i & input_types=cur_signature->get_input_types(); - - - NOMAD::Point delta,Delta; - _mesh->get_delta ( delta ); - _mesh->get_Delta ( Delta ); - bool isZero=true; - for (int i=0; i rounding towards mesh node. - if (input_types[i]==NOMAD::CONTINUOUS) - { - if ((vb1/dm).round()>=(v/dm).round()) - V[i] = (v/dm).ceil()*dm; - else - V[i] = (v/dm).floor()*dm; - } - // Integer variables: - else if ( input_types[i] == NOMAD::INTEGER ) - { - if ( v >= dp/3.0 ) - V[i] = v.ceil(); - else if ( v <= -dp/3.0 ) - V[i] = v.floor(); - else - V[i] = v.round(); - } - // binary variables: - else if ( input_types[i] == NOMAD::BINARY ) - { - if ( v != 0.0 ) V[i] = 1.0; - } - // categorical variables: set direction=0: - else if ( input_types[i] == NOMAD::CATEGORICAL ) - V[i] = 0.0; - - if (V[i]!=0) - isZero=false; - } - - if (isZero) - { - NOMAD::Direction Vzero( n , 0.0 ,NOMAD::UNDEFINED_DIRECTION); - return Vzero; - } - else - return V; -} - - -/*----------------------------------------------------------------*/ -/* check the directions after the poll step (private) */ -/*----------------------------------------------------------------*/ -/* ensures that the last set of poll directions is small enough */ -/* with integer variables */ -/*----------------------------------------------------------------*/ -void NOMAD::Mads::check_directions ( bool & forbid_poll_size_stop ) -{ - if ( !_p.get_min_poll_size_defined() ) - { - - NOMAD::Double v , min; - const NOMAD::Point * dir; - int i , n; - - const NOMAD::Signature * signature; - - const std::set & poll_pts = _ev_control.get_eval_lop(); - std::set::const_iterator end = poll_pts.end() , it; - for ( it = poll_pts.begin() ; it != end ; ++it ) - { - - signature = it->get_point()->get_signature(); - - if ( signature ) - { - - dir = it->get_point()->get_direction(); - - if ( dir ) - { - - n = dir->size(); - - if ( n == signature->get_n() ) - { - - const std::vector & bbit - = signature->get_input_types(); - - for ( i = 0 ; i < n ; ++i ) - { - if ( bbit[i] == NOMAD::INTEGER ) - { - v = (*dir)[i].abs(); - if ( v.is_defined() && v > 0.0 && ( !min.is_defined() || v < min ) ) - min = v; - } - } - } - } - } - } - - if ( min.is_defined() && min > 1.0 ) - forbid_poll_size_stop = true; - } -} - -/*---------------------------------------------------------*/ -/* update of the success directions, after the poll */ -/* (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::update_success_directions ( const NOMAD::Eval_Point * new_inc , - bool feasible ) const -{ - if ( new_inc && new_inc->get_direction() ) - { - - const NOMAD::Direction * dir = new_inc->get_direction(); - NOMAD::Signature * signature = new_inc->get_signature(); - - - if ( !signature ) - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , - "Mads::update_success_directions(): new incumbent has no signature" ); - - if ( feasible ) - new_inc->get_signature()->set_feas_success_dir ( *dir ); - else - new_inc->get_signature()->set_infeas_success_dir ( *dir ); - - } -} - - -/*---------------------------------------------------------*/ -/* the search (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::search ( bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - int nb_search_pts; - bool count_search; - int mads_iteration = _stats.get_iterations(); - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - NOMAD::success_type last_it_success = success; - success = NOMAD::UNSUCCESSFUL; - - // first display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "MADS search" ); - - // 1. speculative search: - if ( _p.get_speculative_search() ) - { - if ( new_feas_inc || new_infeas_inc ) - { - Speculative_Search ss ( _p ); - - ss.search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_spec_success(); - if ( count_search ) - _stats.add_nb_spec_searches(); - _stats.add_spec_pts ( nb_search_pts ); - } - } - - // 2. user search: - if ( success != NOMAD::FULL_SUCCESS && _user_search ) - { - - // initial user search display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << NOMAD::USER_SEARCH; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - // the search: - _user_search->search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - // update stats: - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_usr_srch_success(); - if ( count_search ) - _stats.add_nb_usr_searches(); - _stats.add_usr_srch_pts ( nb_search_pts ); - - // final user search display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of " << NOMAD::USER_SEARCH << " (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - } - - // 3. cache search: - if ( success != NOMAD::FULL_SUCCESS && _p.get_cache_search() ) - { - - // the search: - _cache_search->search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - // update stats: - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_CS_success(); - if ( count_search ) - _stats.add_nb_cache_searches(); - _stats.add_CS_pts ( nb_search_pts ); - } - - // 4. Model Searches (stats are updated inside the searches): - if ( success != NOMAD::FULL_SUCCESS && _p.has_model_search() ) - { - -#ifdef USE_MPI - // asynchronous mode: wait for the evaluations in progress: - if ( _p.get_asynchronous() ) - { - std::list evaluated_pts; - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - evaluated_pts ); - } -#endif - - // model search #1: - _model_search1->search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - // save the TGP model for the model ordering: - if ( _p.get_model_search(1) == NOMAD::TGP_MODEL ) - { -#ifdef USE_TGP - _ev_control.set_last_TGP_model - ( static_cast(_model_search1)->get_model() ); -#endif - } - // model search #2: - if ( success != NOMAD::FULL_SUCCESS && _model_search2 ) - { - -#ifdef USE_MPI - // asynchronous mode: wait for the evaluations in progress: - if ( _p.get_asynchronous() ) - { - std::list evaluated_pts; - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - evaluated_pts ); - } -#endif - _model_search2->search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - // save the TGP model for the model ordering: - if ( _p.get_model_search(2) == NOMAD::TGP_MODEL ) - { -#ifdef USE_TGP - _ev_control.set_last_TGP_model - ( static_cast(_model_search2)->get_model() ); -#endif - } - } - } - - // 5. VNS search: - if ( _p.get_VNS_search() && - success != NOMAD::FULL_SUCCESS && - last_it_success == NOMAD::UNSUCCESSFUL && - _mesh->is_finer_than_initial() && - _stats.get_iterations() > 0 ) - { - - // check the VNS_trigger criterion: - int bbe = _stats.get_bb_eval(); - if ( bbe==0 || - _stats.get_VNS_bb_eval() / static_cast(bbe) < _p.get_VNS_trigger() ) - { - -#ifdef USE_MPI - // asynchronous mode: wait for the evaluations in progress: - if ( _p.get_asynchronous() ) - { - std::list evaluated_pts; - _ev_control.wait_for_evaluations ( NOMAD::ASYNCHRONOUS , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - success , - evaluated_pts ); - } -#endif - - _VNS_search->search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_VNS_success(); - - if ( count_search ) - _stats.add_nb_VNS_searches(); - - _stats.add_VNS_pts ( nb_search_pts ); - } - } - - // 6. Latin-Hypercube (LH) search: - if ( success != NOMAD::FULL_SUCCESS && _p.get_LH_search_pi() > 0 ) - { - - // for the first iteration: do not perform the - // search if there was an initial LH search: - if ( mads_iteration > 0 || _p.get_LH_search_p0() <= 0 ) { - - LH_Search lh ( _p , false , _flag_p1_active ); - - lh.search ( *this , - nb_search_pts , - stop , - stop_reason , - success , - count_search , - new_feas_inc , - new_infeas_inc ); - - if ( success == NOMAD::FULL_SUCCESS ) - _stats.add_LH_success(); - - if ( count_search ) - _stats.add_nb_LH_searches(); - - _stats.add_LH_pts ( nb_search_pts ); - } - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block ( "end of search" ); -} - -/*---------------------------------------------------------*/ -/* x0 eval (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::eval_x0 ( bool & stop , - NOMAD::stop_type & stop_reason ) -{ - const std::vector & x0s = _p.get_x0s(); - const std::string & x0_cache_file = _p.get_x0_cache_file(); - if ( x0s.empty() && x0_cache_file.empty() ) - return; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_gen_dd(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "starting point evaluation" ); - - NOMAD::Eval_Point * pt; - size_t k; - int m = _p.get_bb_nb_outputs(); - int n = _p.get_dimension(); - std::ostringstream err; - - // x0s from vector Parameters::_x0s: - // --------------------------------- - size_t x0s_size = x0s.size(); - for ( k = 0 ; k < x0s_size ; ++k ) - { - - // the current starting point has to be in dimension n: - if ( x0s[k]->size() != n ) - { - err << "starting point ( " << *x0s[k] << " ) is not of dimension " << n; - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , err.str() ); - } - - // creation of the Eval_Point: - pt = new NOMAD::Eval_Point; - pt->set ( *x0s[k] , m ); - pt->set_signature ( _p.get_signature() ); - - _ev_control.add_eval_point ( pt , - display_degree , - false , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - // x0 from a cache file: - // --------------------- - if ( !x0_cache_file.empty() ) - { - - NOMAD::Cache & cache = _ev_control.get_cache(); - const NOMAD::Eval_Point * x; - - // another cache file (this file won't be modified): - if ( x0_cache_file != _p.get_cache_file() ) - { - - NOMAD::Cache x0_cache ( out , ( _p.get_opt_only_sgte() ) ? NOMAD::SGTE : NOMAD::TRUTH ); - std::string file_name = _p.get_problem_dir() + x0_cache_file; - - if ( !x0_cache.load ( file_name , NULL , display_degree==NOMAD::FULL_DISPLAY ) ) - { - err << "could not load (or create) the cache file " << file_name; - throw NOMAD::Exception ( "Mads.cpp" , __LINE__ , err.str() ); - } - - // we copy all the temporary cache points - // into the list of points to be evaluated: - x = x0_cache.begin(); - while ( x ) - { - - pt = new NOMAD::Eval_Point; - pt->set ( *x , m ); - - if ( x->get_signature() ) - pt->set_signature ( x->get_signature() ); - else if ( x->size() == n ) - pt->set_signature ( _p.get_signature() ); - - if ( pt->get_signature() ) - _ev_control.add_eval_point ( pt , - display_degree , - false , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - else - { - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl << "Warning (" << "Mads.cpp" << ", " << __LINE__ - << "): could not use the starting point " << *pt - << " (no signature)" << std::endl << std::endl; - delete pt; - } - - x = x0_cache.next(); - } - - // insertion of this temporary cache in the algorithm's cache: - cache.insert ( x0_cache ); - } - - // x0 cache file and the algorithm's cache file are the same: - else { - - x = cache.begin(); - while ( x ) { - pt = &NOMAD::Cache::get_modifiable_point ( *x ); - - if ( x->get_signature() ) - pt->set_signature ( x->get_signature() ); - else if ( x->size() == n ) - pt->set_signature ( _p.get_signature() ); - - if ( pt->get_signature() ) - _ev_control.add_eval_point ( pt , - display_degree , - false , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - else { - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl << "Warning (" << "Mads.cpp" << ", " << __LINE__ - << "): could not use the starting point " << *pt - << "(no signature)" << std::endl; - } - x = cache.next(); - } - } - } - - // display of all starting points: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - - const std::set & pts = _ev_control.get_eval_lop(); - - // one starting point: - if ( pts.size() == 1 ) { - out << std::endl << "x0 eval point: ( "; - pts.begin()->get_point()->Point::display ( out , - " " , - 2 , - NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // several starting points: - else - _ev_control.display_eval_lop ( NOMAD::X0_EVAL ); - } - - NOMAD::success_type success; - const NOMAD::Eval_Point * new_feas_inc = NULL; - const NOMAD::Eval_Point * new_infeas_inc = NULL; - - // eval_list_of_points (x0): - // ------------------------- - _ev_control.eval_list_of_points ( NOMAD::X0_EVAL , - _true_barrier , - _sgte_barrier , - _pareto_front , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - if ( !stop && - ( success == NOMAD::UNSUCCESSFUL || - (!new_feas_inc && !new_infeas_inc ) || - ( _p.get_barrier_type() == NOMAD::EB && - !get_active_barrier().get_best_feasible() ) ) ) { - stop = true; - stop_reason = NOMAD::X0_FAIL; - } - - - // displays: - display_iteration_end ( stop , - stop_reason , - success , - new_feas_inc , - new_infeas_inc ); - - // stop the algorithm if no iterations are allowed: - if ( !stop && _p.get_max_iterations() == 0 ) - { - stop = true; - stop_reason = NOMAD::MAX_ITER_REACHED; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::close_block ( "end of starting point evaluation" ); -} - -/*---------------------------------------------------------*/ -/* display the Pareto front */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::display_pareto_front ( void ) const -{ - if ( !_pareto_front ) - return; - - const std::string & stats_file_name = _p.get_stats_file_name(); - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_gen_dd(); - - // loop on the Pareto points: - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl << NOMAD::open_block ( "Pareto front" ) << std::endl; - - const NOMAD::Eval_Point * cur = _pareto_front->begin(); - while ( cur ) - { - - if ( cur->is_eval_ok() && cur->is_feasible ( _p.get_h_min() ) ) - { - - const std::list & index_obj = _p.get_index_obj(); - std::list::const_iterator it , end = index_obj.end(); - const NOMAD::Point & bbo = cur->get_bb_outputs(); - int i = 0; - NOMAD::Point multi_obj ( static_cast(index_obj.size()) ); - - for ( it = index_obj.begin() ; it != end ; ++it ) - multi_obj[i++] = bbo[*it]; - - if ( !stats_file_name.empty() ) - _ev_control.stats_file ( stats_file_name , cur , true , &multi_obj ); - - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY && !_p.get_display_stats().empty() ) - _ev_control.display_stats ( false , - out , - _p.get_display_stats() , - cur , - true , - &multi_obj ); - } - cur = _pareto_front->next(); - } - - if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << NOMAD::close_block(); - - // other stats: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - - out << std::endl << "number of pts : " << _pareto_front->size() << std::endl; - - NOMAD::Double delta , surf; - _pareto_front->get_delta_surf ( delta , surf , - _p.get_multi_f_bounds() ); // f1_min, f1_max, - // f2_min, f2_max - out << "delta_j : " << delta << std::endl - << "surf : "; - if ( surf.is_defined() ) - out << 100*surf << "%" << std::endl; - else - out << NOMAD::Double() - << " (define valid MULTI_F_BOUNDS values to access this output)" - << std::endl; - } - else if ( display_degree != NOMAD::NO_DISPLAY && display_degree != NOMAD::MINIMAL_DISPLAY) - out << std::endl << "number of Pareto points: " << _pareto_front->size() - << std::endl; -} - -/*---------------------------------------------------------*/ -/* MADS display */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::display ( const NOMAD::Display & out ) const -{ - NOMAD::dd_type display_degree = out.get_gen_dd(); - - if ( !NOMAD::Slave::is_master() ) - return; - - // 0. no display: - // -------------- - if ( display_degree == NOMAD::NO_DISPLAY || display_degree == NOMAD::MINIMAL_DISPLAY) - { - - // there may be a pareto front to write as a stats file: - if ( _pareto_front && - !_pareto_front->empty() && - !_p.get_stats_file_name().empty() ) - display_pareto_front(); - - return; - } - - // incumbents: - const NOMAD::Eval_Point * bf = get_best_feasible(); - const NOMAD::Eval_Point * bi = get_best_infeasible(); - const NOMAD::Eval_Point *bimv = get_best_infeasible_min_viol(); - - // save the solution file: - if ( bf ) - _ev_control.write_solution_file ( *bf , false); - else if (bimv) - _ev_control.write_solution_file ( *bimv , true ); - - - - // 1. detailed display: - // -------------------- - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - - // cache: - out << std::endl - << NOMAD::open_block ( "cache" ) - << ( _p.get_opt_only_sgte() ? _ev_control.get_sgte_cache() : _ev_control.get_cache() ) - << NOMAD::close_block(); - - // constraints: - if ( _p.has_constraints() ) - out << std::endl - << NOMAD::open_block ( "constraints handling") << std::endl - << get_active_barrier() - << NOMAD::close_block(); - - // Pareto front: - if ( _pareto_front ) - { - if ( _pareto_front->empty() ) - out << std::endl << "Pareto front empty" << std::endl; - else - display_pareto_front(); - } - - // stats: - out << std::endl - << NOMAD::open_block ( "stats" ) - << _stats - << NOMAD::close_block(); - - // model stats: -#ifdef DEBUG - display_model_stats ( out ); -#endif - - // miscellaneous: - if ( !_pareto_front ) - { - out << std::endl - << NOMAD::open_block ( "miscellaneous" ) - << "mesh indices : min= (" - << _mesh->get_min_mesh_indices() << " ), max = (" - << _mesh->get_max_mesh_indices() << " ), last= ( " - << _mesh->get_mesh_indices() << " ) " << std::endl; - - if ( bimv ) - { - out << "best infeasible solution (min. violation): ( "; - bimv->Point::display ( out , " " , -1 , -1 ); - out << " ) h=" << bimv->get_h() - << " f=" << bimv->get_f() << std::endl; - } - - out << "best feasible solution : "; - - if ( bf ) - { - out << "( "; - bf->Point::display ( out , " " , -1 , -1 ); - out << " ) h=" << bf->get_h() - << " f=" << bf->get_f() << std::endl; - } - else - out << "no feasible solution has been found" << std::endl; - - - out.close_block(); - } - } - - // 2. normal display: - // ------------------ - else - { - - // blackbox evaluations: - out << std::endl - << "blackbox evaluations : " << _stats.get_bb_eval() << std::endl; - - // output stats: - if ( _stats.get_stat_sum().is_defined() ) - out << "stat sum : " << _stats.get_stat_sum() << std::endl; - if ( _stats.get_stat_avg().is_defined() ) - out << "stat avg : " << _stats.get_stat_avg() << std::endl; - - // Pareto front (multi-objective optimization): - if ( _pareto_front ) - { - out << "number of MADS runs : " << _stats.get_mads_runs() << std::endl; - if ( _pareto_front->empty() ) - out << "Pareto front : empty" << std::endl; - else - display_pareto_front(); - } - - // single-objective optimization (display of best solutions): - else - { - - if ( !bf && !bi ) - out << "no solution" << std::endl; - else - { - if ( bimv ) - { - out << "best infeasible solution (min. violation): ( "; - bimv->Point::display ( out , " " , -1 , -1 ); - out << " ) h=" << bimv->get_h() - << " f=" << bimv->get_f() << std::endl; - } - - out << "best feasible solution : "; - - if ( bf ) - { - out << "( "; - bf->Point::display ( out , " " , -1 , -1 ); - out << " ) h=" << bf->get_h() - << " f=" << bf->get_f() << std::endl; - } - else - out << "no feasible solution has been found" << std::endl; - - } - } - out.close_block(); - } -} - -/*---------------------------------------------------------*/ -/* display model stats */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::display_model_stats ( const NOMAD::Display & out ) const -{ - if ( _model_search1 ) - out << std::endl << NOMAD::open_block ( "model search #1 stats" ) - << *_model_search1 << NOMAD::close_block(); - if ( _model_search2 ) - out << std::endl << NOMAD::open_block ( "model search #2 stats" ) - << *_model_search2 << NOMAD::close_block(); - if ( _p.get_model_eval_sort() != NOMAD::NO_MODEL ) { - out << std::endl << NOMAD::open_block ( "model ordering stats" ); - _ev_control.display_model_ordering_stats ( out ); - out << NOMAD::close_block(); - } -} - -/*---------------------------------------------------------*/ -/* display mesh and poll sizes for a given signature and */ -/* the current mesh index (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::display_deltas ( const NOMAD::Signature & s ) const -{ - NOMAD::Point delta,Delta; - - _mesh->get_delta(delta); - _mesh->get_Delta(Delta); - if (delta.is_defined() && Delta.is_defined()) - _p.out() << "mesh size : ( " << delta << " )" << std::endl - << "poll size : ( " << Delta << " )" << std::endl - << "mesh indices : ( " << _mesh->get_mesh_indices() << " )" << std::endl; - -} - -/*-------------------------------------------------------*/ -/* displays at the beginning of an iteration (private) */ -/*-------------------------------------------------------*/ -void NOMAD::Mads::display_iteration_begin ( void ) const -{ - const NOMAD::Display & out = _p.out(); - if ( out.get_iter_dd() != NOMAD::FULL_DISPLAY ) - return; - - // incumbents: - const NOMAD::Eval_Point * bf = get_best_feasible(); - const NOMAD::Eval_Point * bi = get_best_infeasible(); - const NOMAD::Signature * s1 = NULL; - - out << "blackbox evaluations : " << _stats.get_bb_eval() << std::endl; -#ifdef USE_MPI - if ( _p.get_asynchronous() ) - out << "eval. in progress : " << _ev_control.get_nb_eval_in_progress() - << std::endl; -#endif - out << "best feas. solution : "; - if ( bf ) { - out << "( "; - bf->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " ) h=" << bf->get_h() - << " f=" << bf->get_f() - << std::endl; - } - else - out << "none" << std::endl; - out << "best infeas. solution: "; - if ( bi ) { - out << "( "; - bi->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " ) h=" << bi->get_h() - << " f=" << bi->get_f() - << std::endl; - } - else - out << "none" << std::endl; - - out << "poll center : "; - const NOMAD::Eval_Point * poll_center = get_active_barrier().get_poll_center(); - if ( poll_center ) { - out << "( "; - poll_center->Point::display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - - s1 = poll_center->get_signature(); - if (s1) - display_deltas ( *s1 ); - } - else - out << "none" << std::endl; - - const NOMAD::Eval_Point * sec_poll_center - = get_active_barrier().get_sec_poll_center(); - - if ( sec_poll_center ) { - out << "sec. poll center : ( "; - sec_poll_center->Point::display ( out , - " " , - 2 , - NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - const NOMAD::Signature * s2 = sec_poll_center->get_signature(); - if ( s2 && (!s1 || s1 != s2) ) - display_deltas ( *s2 ); - } - out << "h_max : " - << get_active_barrier().get_h_max() << std::endl; -} - -/*---------------------------------------------------------*/ -/* displays at the end of an iteration (private) */ -/*---------------------------------------------------------*/ -void NOMAD::Mads::display_iteration_end -( bool stop , - NOMAD::stop_type stop_reason , - NOMAD::success_type success , - const NOMAD::Eval_Point * new_feas_inc , - const NOMAD::Eval_Point * new_infeas_inc ) const -{ - const NOMAD::Display & out = _p.out(); - - if ( out.get_iter_dd() != NOMAD::FULL_DISPLAY ) - return; - - out << std::endl - << "terminate MADS : "; - out.display_yes_or_no ( stop ); - out << std::endl; - if ( stop ) { - out << "termination cause : " << stop_reason; - if ( stop_reason==NOMAD::X0_FAIL && - !_flag_p1_active && - _p.has_EB_constraints() ) - out << " (phase one will be performed)"; - out << std::endl; - } - out << "iteration status : " << success << std::endl; - out << "new feas. incumbent : "; - if ( new_feas_inc ) - out << *new_feas_inc; - else - out << "none" << std::endl; - out << "new infeas. incumbent: "; - if ( new_infeas_inc ) - out << *new_infeas_inc; - else - out << "none" << std::endl; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Mads.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Mads.hpp deleted file mode 100644 index 29c68a37d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Mads.hpp +++ /dev/null @@ -1,610 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Mads.hpp - \brief MADS algorithm (headers) - \author Sebastien Le Digabel - \date 2010-04-20 - \see Mads.cpp - */ -#ifndef __MADS__ -#define __MADS__ - -#include "Quad_Model_Search.hpp" -#include "Speculative_Search.hpp" -#include "LH_Search.hpp" -#include "VNS_Search.hpp" -#include "Cache_Search.hpp" -#include "Phase_One_Search.hpp" -#include "L_Curve.hpp" -#include "Extended_Poll.hpp" - -#include "XMesh.hpp" -#include "SMesh.hpp" - -#ifdef USE_TGP -#include "TGP_Model_Search.hpp" -#endif - -namespace NOMAD { - - // forward declaration of Extended_Poll: - class Extended_Poll; - - /// The MADS algorithm. - class Mads : private NOMAD::Uncopyable { - - private: - - static bool _force_quit; ///< Forces NOMAD to terminate if Ctrl-C is pressed. - - NOMAD::Parameters & _p; ///< Parameters. - NOMAD::Stats _stats; ///< Statistics. - NOMAD::Evaluator_Control _ev_control; ///< Evaluator control. - NOMAD::Evaluator_Control _ev_control_for_sorting; ///< Evaluator control. - NOMAD::Barrier _true_barrier; ///< Barrier for true function evaluations. - NOMAD::Barrier _sgte_barrier; ///< Barrier for surrogate evaluations. - - NOMAD::OrthogonalMesh * _mesh; ///< Access to the OrthogonalMesh - - /// Pareto front for multi-objective optimization. - NOMAD::Pareto_Front * _pareto_front; - - /// User search defined with NOMAD::Mads::set_user_search(). - NOMAD::Search * _user_search; - - NOMAD::Search * _model_search1; ///< Model search #1. - NOMAD::Search * _model_search2; ///< Model search #2. - - NOMAD::Search * _VNS_search; ///< VNS search. - NOMAD::Search * _cache_search; ///< Cache search. - NOMAD::L_Curve * _L_curve; ///< L-curve target. - NOMAD::Extended_Poll * _extended_poll; ///< Extended poll for categorical variables. - bool _user_ext_poll; ///< Flag for user-defined extended poll. - - // MADS flags (these are not parameters as users do not modify them): - - static bool _flag_check_bimads; ///< Flag for the multi-objective test in \c run(). - static bool _flag_reset_mesh; ///< Reset or not the mesh before a MADS run. - static bool _flag_reset_barriers; ///< Reset or not the barriers before a MADS run. - static bool _flag_p1_active; ///< Flag equal to \c true if phase one is active. - - /*-----------------------------------------------------------------------------*/ - - /// Initializations. - void init ( void ); - - /// Starting point evaluation. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - void eval_x0 ( bool & stop , NOMAD::stop_type & stop_reason ); - - /// One MADS iteration. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Success for this iteration -- \b OUT. - \param new_feas_inc Pointer to the new feasible incumbent -- \b OUT. - \param new_infeas_inc Pointer to the new infeasible incumbent -- \b OUT. - */ - void iteration ( bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - - /// The search step. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Success for this step -- \b OUT. - \param new_feas_inc Pointer to the new feasible incumbent -- \b OUT. - \param new_infeas_inc Pointer to the new infeasible incumbent -- \b OUT. - */ - void search ( bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - - /// The poll step. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Success for this step -- \b OUT. - \param new_feas_inc Pointer to the new feasible incumbent -- \b OUT. - \param new_infeas_inc Pointer to the new infeasible incumbent -- \b OUT. - \param forbid_poll_size_stop Boolean used to check if the min poll - size stopping criterion has to be - disabled for integer variables -- \b OUT. - */ - void poll ( bool & stop, - NOMAD::stop_type & stop_reason, - NOMAD::success_type & success, - const NOMAD::Eval_Point *& new_feas_inc, - const NOMAD::Eval_Point *& new_infeas_inc, - bool & forbid_poll_size_stop ); - - /// Sets the poll trial points from poll direction, poll center and mesh size - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param dirs List of directions for the poll -- \b IN. - \param poll_center the poll center (can be null) -- \b IN. - \param offset Dir index offset for primary and sec. poll center -- \b IN. - \param sorting If true than the points are for sorting -- \b IN. - */ - void set_poll_trial_points ( std::list & dirs, - size_t offset, - const NOMAD::Eval_Point & poll_center, - bool & stop, - NOMAD::stop_type &stop_reason, - bool sorting); - - - /// Compute a prospect point by optimization on quadratic models. - /** - \param poll_center The poll center -- \b IN. - \param dirs The directions that delimit the hypercube for optimization -- \b IN. - \param prospect_point The prospect point -- \b OUT. - \return A flag equal to \c true if the prospect direction has been computed. - */ - bool optimize_quad_model ( const NOMAD::Eval_Point & poll_center , - const std::list & dirs , - NOMAD::Point & prospect_point ) ; - - - /// Sets the poll directions from signature, poll center and mesh size - /** - \param dirs List of directions for the poll -- \b OUT. - \param i_pc Poll type -- \b IN. - \param offset Dir index offset for primary and sec. poll center -- \b IN. - \param poll_center The poll center -- \b IN. - \param stop Stop flag, true if cannot get direction -- \b IN/OUT. - \param stop_reason Stop type -- \b OUT. - */ - void set_poll_directions ( std::list & dirs , - NOMAD::poll_type i_pc , - size_t offset , - const NOMAD::Eval_Point & poll_center , - bool & stop , - NOMAD::stop_type & stop_reason ); - - /// Reduce the number of poll directions -> n - /** - \param dirs List of directions for the poll -- \b IN/OUT. - \param poll_center the poll center -- \b IN. - \return success for this step. - */ - bool set_reduced_poll_to_n_directions(std::list & dirs, - const NOMAD::Eval_Point & poll_center); - - /// Compute the rank of a list of directions - /** - \param dirs List of directions for the poll -- \b IN/OUT. - \return rank>0 of the dirs if successfull or 0 if rank cannot be evaluated - */ - int get_rank_from_dirs(const std::list & dirs); - - - /// Check the directions after the poll step. - /** - \param forbid_poll_size_stop Boolean equal to \c true if - the \c MIN_POLL_SIZE parameter is valid for - the last set of poll directions -- \b OUT. - */ - void check_directions ( bool & forbid_poll_size_stop ); - - /// Update of the success directions. - /** - - Occurs after the poll. - \param new_inc Pointer to the new incumbent -- \b IN (may be \c NULL). - \param feasible Flag equal to \c true if the incumbent is feasible -- \b IN. - */ - void update_success_directions ( const NOMAD::Eval_Point * new_inc , - bool feasible ) const; - - /// Launch a single-objective MADS run for multi-objective optimization. - /** - \param display_degree Display degree -- \b IN. - \param mads_runs Total number of MADS runs to execute -- \b IN. - \param overall_bbe Global maximum number of blackbox evaluations -- \b IN. - \param ev Evaluator for multi-objective -- \b IN/OUT. - \param stagnation_cnt Counter to detect a stagnation -- \b IN/OUT. - \param multi_stats Stats for multi-objective -- \b IN/OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - void multi_launch_single_opt ( NOMAD::dd_type display_degree , - int mads_runs , - int overall_bbe , - NOMAD::Multi_Obj_Evaluator & ev , - int & stagnation_cnt , - NOMAD::Stats & multi_stats , - bool & stop , - NOMAD::stop_type & stop_reason ); - - /// Compute and set the minimal poll size for multi-objective optimization. - /** - \param lb Lower bounds -- \b IN. - \param ub Upper bounds -- \b IN. - \param delta_p_0 Initial poll size -- \b IN. - \param delta_j Delta criterion for multi-objective -- \b IN/OUT. - */ - void multi_set_min_poll_size ( const NOMAD::Point & lb , - const NOMAD::Point & ub , - const NOMAD::Point & delta_p_0 , - NOMAD::Double delta_j ); - - // Display mesh and poll sizes for a given signature. - /** - \param s The signature -- \b IN. - */ - void display_deltas ( const NOMAD::Signature & s ) const; - - /// Displays at the beginning of an iteration. - void display_iteration_begin ( void ) const; - - /// Displays at the end of an iteration. - /** - \param stop Stop flag -- \b IN. - \param stop_reason Stop reason -- \b IN. - \param success Iteration success -- \b IN. - \param new_feas_inc Pointer to the new feasible incumbent -- \b IN. - \param new_infeas_inc Pointer to the new infeasible incumbent -- \b IN. - */ - void display_iteration_end ( bool stop , - NOMAD::stop_type stop_reason , - NOMAD::success_type success , - const NOMAD::Eval_Point * new_feas_inc , - const NOMAD::Eval_Point * new_infeas_inc ) const; - - - /// Determine dynamic directions from a set of directions. - /** - - The computed opposite directions already include Delta^k_m. - \param dirs List of existing directions (no snap to bounds) -- \b IN. - \param newDirs New dynamic directions -- \b OUT. - \param poll_center Poll center -- \b IN. - \return true if new dynamic direction generated false otherwise - */ - bool get_dynamic_directions (const std::list & dirs, - std::list & newDirs, - const NOMAD::Eval_Point & poll_center) ; - - - - /// Check if a set of directions include Ortho-MADS N+1 direction. - /** - \param dirs List of directions -- \b IN. - \return A boolean equal to \c true if at - least one direction in the set is - of type Ortho-MADS N+1. - */ - bool dirs_have_orthomads_np1 ( const std::list & dirs ); - - - /// Check if a dir needs to be obtained from model optimization - /** - \param dirs List of directions -- \b IN. - \return A boolean equal to \c true if all directions are of type Ortho-MADS N+1 QUAD. - */ - bool dir_from_model_opt( const std::list & dirs); - - - /// get a single direction using quad model optimization or sum of negatives - /** - \param dirs Reduced poll directions (no snap to bounds) -- \b IN. - \param poll_center Poll center -- \b IN. - \return new direction - */ - NOMAD::Direction get_single_dynamic_direction (const std::list & dirs, - const NOMAD::Eval_Point & poll_center) ; - - - /*-----------------------------------------------------------------------------*/ - - public: - - /// Constructor #1. - /** - - Basic version. - \param p Parameters -- \b IN. - \param ev A pointer to the evaluator -- \b IN - -- \b optional (default = \c NULL). - */ - Mads ( NOMAD::Parameters & p , NOMAD::Evaluator * ev = NULL ) - : _p ( p ) , - _stats ( p.get_sgte_cost() ) , - _ev_control ( p , _stats , ev , NULL , NULL ) , - _ev_control_for_sorting( p , _stats , _ev_control.get_evaluator() , &(_ev_control.get_cache()) , &(_ev_control.get_sgte_cache()) ) , - _true_barrier ( p , NOMAD::TRUTH ) , - _sgte_barrier ( p , NOMAD::SGTE ) , - _mesh ( p.get_signature()->get_mesh() ) , - _pareto_front ( NULL ) , - _user_search ( NULL ) , - _model_search1 ( NULL ) , - _model_search2 ( NULL ) , - _VNS_search ( NULL ) , - _cache_search ( NULL ) , - _L_curve ( NULL ) , - _extended_poll ( NULL ) , - _user_ext_poll ( false ) { init(); } - - /// Constructor #2. - /** - - Advanced version. - \param p Parameters -- \b IN. - \param ev A pointer to the evaluator -- \b IN (may be \c NULL). - \param extended_poll A pointer to a NOMAD::Extended_Poll object - -- \b IN (may be \c NULL). - \param cache A pointer to a cache -- \b IN (may be \c NULL). - \param sgte_cache A pointer to a cache for surrogates - -- \b IN (may be \c NULL). - */ - Mads ( NOMAD::Parameters & p , - NOMAD::Evaluator * ev , // may be NULL - NOMAD::Extended_Poll * extended_poll , // may be NULL - NOMAD::Cache * cache , // may be NULL - NOMAD::Cache * sgte_cache ) // may be NULL - : _p ( p ) , - _stats ( p.get_sgte_cost() ) , - _ev_control ( p , _stats , ev , cache , sgte_cache ) , - _ev_control_for_sorting( p , _stats , _ev_control.get_evaluator() , cache , sgte_cache ) , - _true_barrier ( p , NOMAD::TRUTH ) , - _sgte_barrier ( p , NOMAD::SGTE ) , - _mesh ( p.get_signature()->get_mesh() ) , - _pareto_front ( NULL ) , - _user_search ( NULL ) , - _model_search1 ( NULL ) , - _model_search2 ( NULL ) , - _VNS_search ( NULL ) , - _cache_search ( NULL ) , - _L_curve ( NULL ) , - _extended_poll ( extended_poll ) , - _user_ext_poll ( (extended_poll!=NULL) ) { init(); } - - /// Destructor. - virtual ~Mads ( void ); - - /// Algorithm execution for single-objective. - /** - \return Stop reason. - */ - NOMAD::stop_type run ( void ); - - /// Algorithm execution for multi-objective. - /** - \return Stop reason. - */ - NOMAD::stop_type multi_run ( void ); - - /// Force quit. - /** - Called by pressing Ctrl-C. - \param signalValue Signal value -- \b IN. - */ - static void force_quit ( int signalValue ); - - /// Reset. - /** - - Also resets the user search. - \param keep_barriers A boolean equal to \c true if NOMAD::Barrier objects - have to be reseted - -- \b IN -- \b optional (default = \c false). - \param keep_stats A boolean equal to \c true if the stats object - has to be reseted - -- \b IN -- \b optional (default = \c false). - */ - void reset ( bool keep_barriers = false , bool keep_stats = false ); - - /// Set user search. - /** - \param us A pointer to the user search -- \b IN. - */ - void set_user_search ( NOMAD::Search * us ) { _user_search = us; } - - /// Set an extern Pareto front. - /** - \param pf A pointer to a Pareto front -- \b IN. - */ - void set_pareto_front ( NOMAD::Pareto_Front * pf ) { _pareto_front = pf; } - - /// Set the flag for the multi-objective test. - /** - \param fcb The flag for the multi-objective test -- \b IN. - */ - static void set_flag_check_bimads ( bool fcb ) { _flag_check_bimads = fcb; } - - /// Set the flag \c _flag_reset_mesh. - /** - \param frm The flag -- \b IN. - */ - static void set_flag_reset_mesh ( bool frm ) { _flag_reset_mesh = frm; } - - /// Set the flag \c _flag_reset_barriers. - /** - \param frb The flag -- \b IN. - */ - static void set_flag_reset_barriers ( bool frb ) { _flag_reset_barriers = frb; } - - /// Set the flag \c _flag_p1_active -- \b IN. - /** - \param fpa The flag. - */ - static void set_flag_p1_active ( bool fpa ) { _flag_p1_active = fpa; } - - /// Access to the flags. - /** - \param flag_check_bimads Multi-objective flag -- \b OUT. - \param flag_reset_mesh Mesh reset flag -- \b OUT. - \param flag_reset_barriers Reset barriers flag -- \b OUT. - \param flag_p1_active Phase one flag -- \b OUT. - */ - static void get_flags ( bool & flag_check_bimads , - bool & flag_reset_mesh , - bool & flag_reset_barriers , - bool & flag_p1_active ); - - /// Access to the stats. - /** - \return The stats. - */ - NOMAD::Stats & get_stats ( void ) { return _stats; } - - /// Access to the evaluator control. - /** - \return The evaluator control. - */ - NOMAD::Evaluator_Control & get_evaluator_control ( void ) { return _ev_control; } - - /// Access to the barrier for true function evaluations. - /** - \return The barrier for the true function evaluations. - */ - NOMAD::Barrier & get_true_barrier ( void ) { return _true_barrier; } - - /// Access to the barrier for surrogate evaluations. - /** - \return The barrier for the surrogates. - */ - NOMAD::Barrier & get_sgte_barrier ( void ) { return _sgte_barrier; } - - /// Access to the NOMAD::Extended_Poll object. - /** - \return A pointer to \c _extended_poll. - */ - NOMAD::Extended_Poll * get_extended_poll ( void ) const { return _extended_poll; } - - - - /// Access to the Pareto front. - /** - \return A pointer to the Pareto front. - */ - NOMAD::Pareto_Front * get_pareto_front ( void ) const { return _pareto_front; } - - /// Access to the active cache (truth or surrogate). - /** - \return The active cache. - */ - const NOMAD::Cache & get_cache ( void ) const - { - return ( _p.get_opt_only_sgte() ) ? - _ev_control.get_sgte_cache() : _ev_control.get_cache(); - } - - /// Access to the active barrier (truth or surrogate). - /** - \return The active barrier. - */ - const NOMAD::Barrier & get_active_barrier ( void ) const - { - return ( _p.get_opt_only_sgte() ) ? _sgte_barrier : _true_barrier; - } - - /// Access to the best feasible point. - /** - \return A pointer to the best feasible point; - \return \c NULL if there is no feasible point. - */ - const NOMAD::Eval_Point * get_best_feasible ( void ) const - { - return get_active_barrier().get_best_feasible(); - } - - /// Access to the best infeasible point. - /** - \return A pointer to the best infeasible point; - \return \c NULL if there is no infeasible point. - */ - const NOMAD::Eval_Point * get_best_infeasible( void ) const - { - return get_active_barrier().get_best_infeasible(); - } - - /// Access to the best infeasible point with minimun constraint violation. - /** - \return A pointer to the best infeasible point with min. viol.; - \return \c NULL if there is no infeasible point. - */ - const NOMAD::Eval_Point * get_best_infeasible_min_viol ( void ) const - { - return get_active_barrier().get_best_infeasible_min_viol(); - } - - /// Display model stats. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display_model_stats ( const NOMAD::Display & out ) const; - - /// Display the Pareto front. - /** - Displays the front at the standard output or in a stats file. - */ - void display_pareto_front ( void ) const; - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Display. - /** - Uses the NOMAD::Display object of the NOMAD::Parameters class. - */ - void display ( void ) const { display ( _p.out() ); } - }; - - /// Display a NOMAD::Mads object. - /** - \param out The NOMAD::Display object -- \b IN. - \param m The NOMAD::Mads object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Mads & m ) - { - m.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Sorted_Point.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Sorted_Point.cpp deleted file mode 100644 index 21725595c..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Sorted_Point.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Model_Sorted_Point.cpp - \brief Interpolation point with distance to model center (implementation) - \author Sebastien Le Digabel - \date 2010-11-15 - \see Model_Sorted_Point.hpp -*/ -#include "Model_Sorted_Point.hpp" - -/*---------------------------------------------------------*/ -/* constructor */ -/*---------------------------------------------------------*/ -NOMAD::Model_Sorted_Point::Model_Sorted_Point -( NOMAD::Point * x , const NOMAD::Point & center ) : _x(x) -{ - int i , n = center.size(); - if ( x && x->size() == n ) { - _dist = 0.0; - for ( i = 0 ; i < n ; ++i ) - if ( (*x)[i].is_defined() && center[i].is_defined() ) { - _dist += ( (*x)[i] - center[i] ).pow2(); - } - else { - _dist.clear(); - break; - } - } -} - -/*---------------------------------------------------------*/ -/* affectation operator */ -/*---------------------------------------------------------*/ -NOMAD::Model_Sorted_Point & NOMAD::Model_Sorted_Point::operator = -( const NOMAD::Model_Sorted_Point & x ) -{ - _x = x._x; - _dist = x._dist; - return *this; -} - -/*---------------------------------------------------------*/ -/* comparison operator */ -/*---------------------------------------------------------*/ -bool NOMAD::Model_Sorted_Point::operator < -( const Model_Sorted_Point & x ) const -{ - if ( _dist.is_defined() ) { - if ( !x._dist.is_defined() ) - return true; - return _dist < x._dist; - } - return false; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Sorted_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Sorted_Point.hpp deleted file mode 100644 index 4238fc399..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Sorted_Point.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Model_Sorted_Point.hpp - \brief Interpolation point with distance to model center (headers) - \author Sebastien Le Digabel - \date 2010-11-15 - \see Model_Sorted_Point.cpp -*/ -#ifndef __MODEL_SORTED_POINT__ -#define __MODEL_SORTED_POINT__ - -#include "Point.hpp" - -namespace NOMAD { - - /// Class used to order interpolation points. - class Model_Sorted_Point { - - private: - - NOMAD::Point * _x; ///< The point. - NOMAD::Double _dist; ///< Distance to center. - - public: - - /// Constructor 1/2. - /** - \param x Interpolaton point -- \b IN. - \param center Model center -- \b IN. - */ - Model_Sorted_Point ( NOMAD::Point * x , const NOMAD::Point & center ); - - /// Constructor 2/2. - /** - \param x Interpolaton point -- \b IN. - \param dist Custom distance with center -- \b IN. - */ - Model_Sorted_Point ( NOMAD::Point * x , const NOMAD::Double & dist ) - : _x ( x ) , _dist ( dist ) {} - - /// Copy constructor. - /** - \param x The copied object -- \b IN. - */ - Model_Sorted_Point ( const Model_Sorted_Point & x ) - : _x ( x._x ) , _dist ( x._dist ) {} - - /// Affectation operator. - /** - \param x The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - Model_Sorted_Point & operator = ( const Model_Sorted_Point & x ); - - /// Destructor. - virtual ~Model_Sorted_Point ( void ) {} - - /// Comparison operator. - /** - \param x The right-hand side object -- \b IN. - \return \c true if the current interpolation point is closer to the center. - */ - bool operator < ( const Model_Sorted_Point & x ) const; - - /// Access to the interpolation point. - /** - \return The interpolation point. - */ - NOMAD::Point * get_point ( void ) const { return _x; } - - /// Access to the distance. - /** - \return The distance - */ - const NOMAD::Double & get_dist ( void ) const { return _dist; } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Stats.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Stats.cpp deleted file mode 100644 index 5486d5433..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Stats.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Model_Stats.cpp - \brief Model stats (implementation) - \author Sebastien Le Digabel - \date 2010-09-24 - \see Model_Stats.hpp -*/ -#include "Model_Stats.hpp" - -/*---------------------------------------------------------*/ -/* affectation operator */ -/*---------------------------------------------------------*/ -NOMAD::Model_Stats & NOMAD::Model_Stats::operator = ( const NOMAD::Model_Stats & s ) -{ - _nb_truth = s._nb_truth; - _nb_sgte = s._nb_sgte; - _nb_MFN = s._nb_MFN; - _nb_WP_regression = s._nb_WP_regression; - _nb_regression = s._nb_regression; - _nb_TGP = s._nb_TGP; - _not_enough_pts = s._not_enough_pts; - _nb_Y_sets = s._nb_Y_sets; - _sum_nY = s._sum_nY; - _min_nY = s._min_nY; - _max_nY = s._max_nY; - _construction_error = s._construction_error; - _construction_time = s._construction_time; - _optimization_time = s._optimization_time; - _bad_cond = s._bad_cond; - _MS_nb_searches = s._MS_nb_searches; - _MS_pts = s._MS_pts; - _MS_success = s._MS_success; - _MS_bb_eval = s._MS_bb_eval; - _MS_sgte_eval = s._MS_sgte_eval; - _MS_cache_hits = s._MS_cache_hits; - _MS_rejected = s._MS_rejected; - _MS_max_search_pts = s._MS_max_search_pts; - _MS_nb_opt = s._MS_nb_opt; - _MS_opt_error = s._MS_nb_opt; - _MS_avg_model_eval = s._MS_avg_model_eval; - _MS_max_model_eval = s._MS_max_model_eval; - _MS_max_bbe = s._MS_max_bbe; - _ES_nb_inside_radius = s._ES_nb_inside_radius; - _ES_nb_pts = s._ES_nb_pts; - - return *this; -} - -/*---------------------------------------------------------*/ -/* reset the stats */ -/*---------------------------------------------------------*/ -void NOMAD::Model_Stats::reset ( void ) -{ - _nb_truth = - _nb_sgte = - _nb_MFN = - _nb_WP_regression = - _nb_regression = - _nb_TGP = - _not_enough_pts = - _construction_error = - _bad_cond = - _MS_nb_searches = - _MS_pts = - _MS_success = - _MS_bb_eval = - _MS_sgte_eval = - _MS_cache_hits = - _MS_rejected = - _MS_max_search_pts = - _MS_nb_opt = - _MS_opt_error = - _MS_avg_model_eval = - _MS_max_model_eval = - _MS_max_bbe = - _ES_nb_inside_radius = - _ES_nb_pts = - _nb_Y_sets = 0; - - _min_nY = INT_MAX; - _sum_nY = 0.0; - - _max_nY = -1; - _construction_time = - _optimization_time = 0.0; -} - -/*-------------------------------------------------------*/ -/* update stats from another NOMAD::Model_Stats object */ -/*-------------------------------------------------------*/ -void NOMAD::Model_Stats::update ( const NOMAD::Model_Stats & s ) -{ - _nb_truth += s._nb_truth; - _nb_sgte += s._nb_sgte; - _nb_MFN += s._nb_MFN; - _nb_WP_regression += s._nb_WP_regression; - _nb_regression += s._nb_regression; - _nb_TGP += s._nb_TGP; - _not_enough_pts += s._not_enough_pts; - _construction_error += s._construction_error; - _construction_time += s._construction_time; - _optimization_time += s._optimization_time; - _bad_cond += s._bad_cond; - _MS_nb_searches += s._MS_nb_searches; - _MS_pts += s._MS_pts; - _MS_success += s._MS_success; - _MS_bb_eval += s._MS_bb_eval; - _MS_sgte_eval += s._MS_sgte_eval; - _MS_cache_hits += s._MS_cache_hits; - _MS_rejected += s._MS_rejected; - _MS_opt_error += s._MS_opt_error; - _MS_max_bbe += s._MS_max_bbe; - _ES_nb_inside_radius += s._ES_nb_inside_radius; - _ES_nb_pts += s._ES_nb_pts; - _nb_Y_sets += s._nb_Y_sets; - _sum_nY += s._sum_nY; - - _min_nY = ( _min_nY < s._min_nY ) ? - _min_nY : s._min_nY; - - _max_nY = ( _max_nY > s._max_nY ) ? - _max_nY : s._max_nY; - - _MS_max_model_eval = ( _MS_max_model_eval > s._MS_max_model_eval ) ? - _MS_max_model_eval : s._MS_max_model_eval; - - _MS_max_search_pts = ( _MS_max_search_pts > s._MS_max_search_pts ) ? - _MS_max_search_pts : s._MS_max_search_pts; - - if ( _MS_nb_opt + s._MS_nb_opt == 0 ) - _MS_avg_model_eval = 0; - else - _MS_avg_model_eval = ( _MS_avg_model_eval* _MS_nb_opt + - s._MS_avg_model_eval*s._MS_nb_opt ) / - ( _MS_nb_opt + s._MS_nb_opt ); - - _MS_nb_opt += s._MS_nb_opt; -} - -/*----------------------------------------------------*/ -/* update stats on |Y| */ -/*----------------------------------------------------*/ -void NOMAD::Model_Stats::update_nY ( int nY ) -{ - ++_nb_Y_sets; - _sum_nY += nY; - if ( nY > _max_nY ) - _max_nY = nY; - if ( nY < _min_nY ) - _min_nY = nY; -} - -/*----------------------------------------------------*/ -/* update _MS_max_search_pts */ -/*----------------------------------------------------*/ -void NOMAD::Model_Stats::update_MS_max_search_pts ( int sp ) -{ - if ( sp > _MS_max_search_pts ) - _MS_max_search_pts = sp; -} - -/*-----------------------------------------------------------------------*/ -/* update stats _MS_nb_opt, _MS_max_model_eval, and _MS_avg_model_eval */ -/*-----------------------------------------------------------------------*/ -void NOMAD::Model_Stats::update_MS_model_opt ( int eval ) -{ - if ( eval > _MS_max_model_eval ) - _MS_max_model_eval = eval; - ++_MS_nb_opt; - _MS_avg_model_eval = ( (_MS_avg_model_eval*(_MS_nb_opt-1)) + eval ) / _MS_nb_opt; -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Model_Stats::display ( const NOMAD::Display & out ) const -{ - out << "number of models built : " << get_nb_models() << std::endl; - if ( _nb_sgte > 0 ) - out << "number of truth models : " << _nb_truth << std::endl - << "number of surrogate models : " << _nb_sgte << std::endl; - out << "number of MFN interpolations : " << _nb_MFN << std::endl - << "number of WP regressions : " << _nb_WP_regression << std::endl - << "number of quadr. regressions : " << _nb_regression << std::endl - << "number of TGP models : " << _nb_TGP << std::endl - << "number of construction errors: " << _construction_error << std::endl - << "number of bad cond numbers : " << _bad_cond << std::endl - << "number of too small Y sets : " << _not_enough_pts << std::endl - << "min Y size : "; - if ( _min_nY != INT_MAX ) - out << _min_nY; - else - out << "-"; - out << std::endl - << "max Y size : "; - if ( _max_nY != -1 ) - out << _max_nY; - else - out << "-"; - out << std::endl - << "avg Y size : "; - if ( get_avg_nY() != 0.0 ) - out << get_avg_nY(); - else - out << "-"; - out << std::endl - << "construction CPU time (s) : " << _construction_time << std::endl; - if ( _MS_nb_searches > 0 ) { - out << NOMAD::open_block ( "model searches" ) - << "number of searches : " << _MS_nb_searches << std::endl - << "number of search successes : " << _MS_success << std::endl - << "number of search points : " << _MS_pts << std::endl - << "number of blackbox evaluations : " << _MS_bb_eval << std::endl; - if ( _MS_sgte_eval > 0 ) - out << "number of sgte evaluations : " << _MS_sgte_eval << std::endl; - out << "number of cache hits : " << _MS_cache_hits << std::endl - << "number of rejected candidates : " << _MS_rejected << std::endl - << "max number of trial points : " << _MS_max_search_pts << std::endl - << "number of optimizations : " << _MS_nb_opt << std::endl - << "number of optimization errors : " << _MS_opt_error << std::endl - << "number of max_bbe stops : " << _MS_max_bbe << std::endl - << "max number of model evaluations : " << _MS_max_model_eval << std::endl - << "average number of model evaluations: " << _MS_avg_model_eval << std::endl - << "optimization CPU time (s) : " << _optimization_time << std::endl - << NOMAD::close_block(); - } - - if ( _ES_nb_pts > 0 ) { - out << NOMAD::open_block ( "model ordering" ) - << "number of points considered : " << _ES_nb_pts << std::endl - << "number of points inside radius: " << _ES_nb_inside_radius - << " ("; - NOMAD::Double(_ES_nb_inside_radius*100.0/_ES_nb_pts).display ( out , "%.0f" ); - out << "%)" << std::endl - << NOMAD::close_block(); - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Stats.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Stats.hpp deleted file mode 100644 index 75eb815ae..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Model_Stats.hpp +++ /dev/null @@ -1,365 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Model_Stats.hpp - \brief Model stats (headers) - \author Sebastien Le Digabel - \date 2010-09-24 - \see Model_Stats.cpp -*/ -#ifndef __MODEL_STATS__ -#define __MODEL_STATS__ - -#include "Double.hpp" - -namespace NOMAD { - - /// Model stats. - class Model_Stats { - - private: - - int _nb_truth; ///< Number of truth models. - int _nb_sgte; ///< Number of surrogate models. - int _nb_MFN; ///< Number of quadr. MFN models. - int _nb_WP_regression; ///< Number of quadr. well-poised regressions models. - int _nb_regression; ///< Number of quadr. regression_max_nY models. - int _nb_TGP; ///< Number of TGP models. - int _not_enough_pts; ///< Number of too small \c Y sets. - int _nb_Y_sets; ///< Number of \c Y sets. - float _sum_nY; ///< Total number of \c Y points. - int _min_nY; ///< Minimal \c Y size. - int _max_nY; ///< Maximal \c Y size. - int _construction_error; ///< Number of construction errors. - double _construction_time; ///< Models construction CPU time. - double _optimization_time; ///< Models optimization CPU time. - - /// Number of times that \c cond exceeded \c SVD_MAX_COND. - int _bad_cond; - - // model search (MS): - int _MS_nb_searches; ///< Number of searches. - int _MS_pts; ///< Number of search points. - int _MS_success; ///< Number of search successes. - int _MS_bb_eval; ///< Number of search blackbox evaluations. - int _MS_sgte_eval; ///< Number of search surrogate evaluations. - int _MS_cache_hits; ///< Number of search cache hits. - int _MS_rejected; ///< Number of rejected trial points. - int _MS_max_search_pts; ///< Max number of trial points for one search. - int _MS_nb_opt; ///< Number of optimizations. - int _MS_opt_error; ///< Number of optimization errors. - int _MS_avg_model_eval; ///< Avg number of evaluations for a model opt. - int _MS_max_model_eval; ///< Max number of evaluations for a model opt. - int _MS_max_bbe; ///< Number of times model eval. reached limit. - - // eval sort (ES): - int _ES_nb_inside_radius; ///< Total number of points inside radius. - int _ES_nb_pts; ///< Total number of points. - -public: - - /// Constructor. - explicit Model_Stats ( void ) { reset(); } - - /// Copy constructor. - /** - \param s The copied object -- \b IN. - */ - explicit Model_Stats ( const Model_Stats & s ) - : _nb_truth ( s._nb_truth ) , - _nb_sgte ( s._nb_sgte ) , - _nb_MFN ( s._nb_MFN ) , - _nb_WP_regression ( s._nb_WP_regression ) , - _nb_regression ( s._nb_regression ) , - _nb_TGP ( s._nb_TGP ) , - _not_enough_pts ( s._not_enough_pts ) , - _nb_Y_sets ( s._nb_Y_sets ) , - _sum_nY ( s._sum_nY ) , - _min_nY ( s._min_nY ) , - _max_nY ( s._max_nY ) , - _construction_error ( s._construction_error ) , - _construction_time ( s._construction_time ) , - _optimization_time ( s._optimization_time ) , - _bad_cond ( s._bad_cond ) , - _MS_nb_searches ( s._MS_nb_searches ) , - _MS_pts ( s._MS_pts ) , - _MS_success ( s._MS_success ) , - _MS_bb_eval ( s._MS_bb_eval ) , - _MS_sgte_eval ( s._MS_sgte_eval ) , - _MS_cache_hits ( s._MS_cache_hits ) , - _MS_rejected ( s._MS_rejected ) , - _MS_max_search_pts ( s._MS_max_search_pts ) , - _MS_nb_opt ( s._MS_nb_opt ) , - _MS_opt_error ( s._MS_opt_error ) , - _MS_avg_model_eval ( s._MS_avg_model_eval ) , - _MS_max_model_eval ( s._MS_max_model_eval ) , - _MS_max_bbe ( s._MS_max_bbe ) , - _ES_nb_inside_radius ( s._ES_nb_inside_radius ) , - _ES_nb_pts ( s._ES_nb_pts ) {} - - /// Affectation operator. - /** - \param s The right-hand side object -- \b IN. - */ - Model_Stats & operator = ( const Model_Stats & s ); - - /// Destructor. - virtual ~Model_Stats ( void ) {} - - /// Reset the stats. - void reset ( void ); - - /// Update stats from another NOMAD::Model_Stats object. - /** - \param s The other NOMAD::Model_Stats object -- \b IN. - */ - void update ( const Model_Stats & s ); - - /// Update stats on the size of interpolation set \c Y. - /** - \param nY Size of an interpolation set \c Y -- \b IN. - */ - void update_nY ( int nY ); - - /// Update stat \c _MS_max_search_pts. - /** - \param sp Number of trial points for a model search -- \b IN. - */ - void update_MS_max_search_pts ( int sp ); - - /// Update stats \c _MS_nb_opt, \c _MS_max_model_eval, and \c _MS_avg_model_eval. - /** - \param eval Number of model evaluations during one model optimization -- \b IN. - */ - void update_MS_model_opt ( int eval ); - - /// Update model ordering stats. - /** - \param nb_inside_radius Number of points inside radius -- \b IN. - \param nb_pts Number of points -- \b IN. - */ - void update_ES_stats ( int nb_inside_radius , int nb_pts ) - { - _ES_nb_inside_radius += nb_inside_radius; - _ES_nb_pts += nb_pts; - } - - /// Add a real to stat \c _construction_time. - /** - \param t Time -- \b IN. - */ - void add_construction_time ( double t ) { _construction_time += t; } - - /// Add a real to stat \c _optimization_time. - /** - \param t Time -- \b IN. - */ - void add_optimization_time ( double t ) { _optimization_time += t; } - - /// Add \c 1 to stat \c _nb_truth. - void add_nb_truth ( void ) { ++_nb_truth; } - - /// Add \c 1 to stat \c _nb_sgte. - void add_nb_sgte ( void ) { ++_nb_sgte; } - - /// Add \c 1 to stat \c _nb_MFN. - void add_nb_MFN ( void ) { ++_nb_MFN; } - - /// Add \c 1 to stat \c _nb_WP_regression. - void add_nb_WP_regression ( void ) { ++_nb_WP_regression; } - - /// Add \c 1 to stat \c _nb_regression. - void add_nb_regression ( void ) { ++_nb_regression; } - - /// Add \c 1 to stat \c _nb_TGP. - void add_nb_TGP ( void ) { ++_nb_TGP; } - - /// Add \c 1 to stat \c _not_enough_pts. - void add_not_enough_pts ( void ) { ++_not_enough_pts; } - - /// Add \c 1 to stat \c _construction_error. - void add_construction_error ( void ) { ++_construction_error; } - - /// Add \c 1 to stat \c _bad_cond. - void add_bad_cond ( void ) { ++_bad_cond; } - - /// Add \c 1 to stat \c _MS_nb_searches. - void add_MS_nb_searches ( void ) { ++_MS_nb_searches; } - - /// Add \c 1 to stat \c _MS_success. - void add_MS_success ( void ) { ++_MS_success; } - - /// Add \c 1 to stat \c _MS_opt_error. - void add_MS_opt_error ( void ) { ++_MS_opt_error; } - - /// Add \c 1 to stat \c _MS_max_bbe. - void add_MS_max_bbe ( void ) { ++_MS_max_bbe; } - - /// Add \c 1 to stat \c _MS_rejected. - void add_MS_rejected ( void ) { ++_MS_rejected; } - - /// Add an integer to stat \c _MS_pts. - /** - \param i The integer -- \b IN. - */ - void add_MS_pts ( int i ) { _MS_pts += i; } - - /// Add an integer to stat \c _MS_bb_eval. - /** - \param i The integer -- \b IN. - */ - void add_MS_bb_eval ( int i ) { _MS_bb_eval += i; } - - /// Add an integer to stat \c _MS_sgte_eval. - /** - \param i The integer -- \b IN. - */ - void add_MS_sgte_eval ( int i ) { _MS_sgte_eval += i; } - - /// Add an integer to stat \c _MS_cache_hits. - /** - \param i The integer -- \b IN. - */ - void add_MS_cache_hits ( int i ) { _MS_cache_hits += i; } - - /// Access to the number of model searches. - /* - \return The number of model searches. - **/ - int get_MS_nb_searches ( void ) const { return _MS_nb_searches; } - - /// Access to the number of model optimizations. - /* - \return The number of model optimizations. - **/ - int get_MS_nb_opt ( void ) const { return _MS_nb_opt; } - - /// Access to the number of model search points. - /* - \return The number of model search points. - **/ - int get_MS_pts ( void ) const { return _MS_pts; } - - /// Access to the number of model blackbox evaluations. - /* - \return The number of model blackbox evaluations. - **/ - int get_MS_bb_eval ( void ) const { return _MS_bb_eval; } - - /// Access to the number of model search surrogate evaluations. - /* - \return The number of model search surrogate evaluations. - **/ - int get_MS_sgte_eval ( void ) const { return _MS_sgte_eval; } - - /// Access to the number of model search successes. - /* - \return The number of model search successes. - **/ - int get_MS_success ( void ) const { return _MS_success; } - - /// Access to the number of models. - /* - \return The number of models. - **/ - int get_nb_models ( void ) const { return _nb_truth + _nb_sgte; } - - /// Access to stat \c _min_nY. - /** - \return The stat \c _min_nY. - */ - int get_min_nY ( void ) const { return _min_nY; } - - /// Access to stat \c _max_nY. - /** - \return The stat \c _max_nY. - */ - int get_max_nY ( void ) const { return _max_nY; } - - /// Access to the average size of interpolation sets. - /** - \return The average size of interpolation sets. - */ - float get_avg_nY ( void ) const - { - return ( _nb_Y_sets == 0 ) ? 0 : _sum_nY / _nb_Y_sets; - } - - /// Access to stat \c _nb_MFN. - /** - \return \c The stat _nb_MFN. - */ - int get_nb_MFN ( void ) const { return _nb_MFN; } - - /// Access to stat \c _nb_WP_regression. - /** - \return \c The stat _nb_WP_regression. - */ - int get_nb_WP_regression ( void ) const { return _nb_WP_regression; } - - /// Access to stat \c _nb_regression. - /** - \return \c The stat _nb_regression. - */ - int get_nb_regression ( void ) const { return _nb_regression; } - - /// Access to stat \c _nb_TGP. - /** - \return \c The stat _nb_TGP. - */ - int get_nb_TGP ( void ) const { return _nb_TGP; } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::Model_Stats object. - /** - \param out The NOMAD::Display object -- \b IN. - \param s The NOMAD::Model_Stats object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Model_Stats & s ) { - s.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Evaluator.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Evaluator.cpp deleted file mode 100644 index aa6ffe155..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Evaluator.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Multi_Obj_Evaluator.cpp - \brief NOMAD::Evaluator subclass for multiobjective optimization (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Multi_Obj_Evaluator.hpp -*/ -#include "Multi_Obj_Evaluator.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -int NOMAD::Multi_Obj_Evaluator::_i1 = -1; -int NOMAD::Multi_Obj_Evaluator::_i2 = -1; - -/*---------------------------------------*/ -/* initialization of objective indexes */ -/* (static) */ -/*---------------------------------------*/ -void NOMAD::Multi_Obj_Evaluator::set_obj_indexes ( const std::list & index_obj ) -{ - if ( index_obj.size() != 2 ) - throw NOMAD::Exception ( "Multi_Obj_Evaluator.cpp" , __LINE__ , - "Multi_Obj_Evaluator defined with a number of indexes different than two" ); - - std::list::const_iterator it = index_obj.begin(); - - NOMAD::Multi_Obj_Evaluator::_i1 = *it; - it++; - NOMAD::Multi_Obj_Evaluator::_i2 = *it; -} - -/*-------------------------------------------------------------*/ -/* computation of f, taking into account the two objectives, */ -/* with weights _w1 and _w2 */ -/*-------------------------------------------------------------*/ -void NOMAD::Multi_Obj_Evaluator::compute_f ( NOMAD::Eval_Point & x ) const -{ - if ( _i1 < 0 || _i2 < 0 ) - throw NOMAD::Exception ( "Multi_Obj_Evaluator.cpp" , __LINE__ , - "Multi_Obj_Evaluator::compute_f(): no objective indexes defined" ); - - int obj_index [2]; - obj_index[0] = _i1; - obj_index[1] = _i2; - - const NOMAD::Point & bbo = x.get_bb_outputs(); - - // a reference is available: - if ( _ref ) - { - - NOMAD::multi_formulation_type mft = _p.get_multi_formulation(); - - if ( mft == NOMAD::UNDEFINED_FORMULATION ) - throw NOMAD::Exception ( "Multi_Obj_Evaluator.cpp" , __LINE__ , - "Multi_Obj_Evaluator::compute_f(): no formulation type is defined" ); - - // normalized formulation: - if ( mft == NOMAD::NORMALIZED || mft == NOMAD::DIST_LINF ) { - - // f1 - r1: - NOMAD::Double d = bbo[obj_index[0]] - (*_ref)[0]; - - // f2 - r2: - NOMAD::Double f2mr2 = bbo[obj_index[1]] - (*_ref)[1]; - - // we take the max: - if ( f2mr2 > d ) - d = f2mr2; - - x.set_f ( d ); - } - - // product formulation: - else if ( mft == NOMAD::PRODUCT ) { - - NOMAD::Double prod = 1.0 , ri , fi; - - for ( int i = 0 ; i < 2 ; ++i ) { - - ri = (*_ref)[i]; - fi = bbo[obj_index[i]]; - - if ( fi > ri ) { - prod = 0.0; - break; - } - prod = prod * (ri-fi).pow2(); - } - - x.set_f ( -prod ); - } - - // distance formulation: - else { - - NOMAD::Double d; - NOMAD::Double r1mf1 = (*_ref)[0] - bbo[obj_index[0]]; - NOMAD::Double r2mf2 = (*_ref)[1] - bbo[obj_index[1]]; - - if ( r1mf1 >= 0.0 && r2mf2 >= 0.0 ) { - d = r1mf1.pow2(); - NOMAD::Double tmp = r2mf2.pow2(); - if ( tmp < d ) - d = tmp; - d = -d; - } - else if ( r1mf1 <= 0.0 && r2mf2 <= 0.0 ) { - - // with L2 norm: - if ( mft == NOMAD::DIST_L2 ) - d = r1mf1.pow2() + r2mf2.pow2(); - - // with L1 norm: - else - d = (r1mf1.abs() + r2mf2.abs()).pow2(); - - // Linf norm: treated as NORMALIZED - } - else if ( r1mf1 > 0.0 ) - d = r2mf2.pow2(); - else - d = r1mf1.pow2(); - - x.set_f ( d ); - } - } - - // no reference is available (use weights): - else - x.set_f ( _w1 * bbo[obj_index[0]] + _w2 * bbo[obj_index[1]] ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Evaluator.hpp deleted file mode 100644 index 3ddb3feb0..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Evaluator.hpp +++ /dev/null @@ -1,140 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Multi_Obj_Evaluator.hpp - \brief NOMAD::Evaluator subclass for multiobjective optimization (headers) - \author Sebastien Le Digabel - \date 2010-04-20 - \see Multi_Obj_Evaluator.cpp -*/ -#ifndef __MULTI_OBJ_EVALUATOR__ -#define __MULTI_OBJ_EVALUATOR__ - -#include "Phase_One_Evaluator.hpp" - -namespace NOMAD { - - /// NOMAD::Evaluator subclass for multiobjective optimization. - /** - Version for two objective functions. - */ - class Multi_Obj_Evaluator : public NOMAD::Evaluator { - - private: - - static int _i1; ///< Index of the first objective. - static int _i2; ///< Index of the second objective. - - NOMAD::Double _w1; ///< Weight on the first objective function. - NOMAD::Double _w2; ///< Weight on the second objective function. - - const NOMAD::Point * _ref; ///< Reference point. - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Multi_Obj_Evaluator ( const NOMAD::Parameters & p ) - : NOMAD::Evaluator ( p ) , - _w1 ( 1.0 ) , - _w2 ( 0.0 ) , - _ref ( NULL ) { _is_multi_obj = true; } - - /// Destructor. - virtual ~Multi_Obj_Evaluator ( void ) {} - - /// Initialization of objective indexes. - /** - \param index_obj List of objective indexes -- \b IN. - */ - static void set_obj_indexes ( const std::list & index_obj ); - - /// Updates after a MADS run. - /** - This virtual method is called every time a MADS run is terminated. - \param stats Stats -- \b IN. - \param ev_control Evaluator control -- \b IN. - \param true_barrier Barrier for true functions -- \b IN. - \param sgte_barrier Barrier for surrogate functions -- \b IN. - \param pareto_front Pareto front -- \b IN. - */ - virtual void update_mads_run ( const NOMAD::Stats & stats , - const NOMAD::Evaluator_Control & ev_control , - const NOMAD::Barrier & true_barrier , - const NOMAD::Barrier & sgte_barrier , - const NOMAD::Pareto_Front & pareto_front ) {} - - /// Compute \c f(x) from the blackbox outputs of a point. - /** - - Bi-objective version. - - Computation of \c f taking into account the two objectives - with a reformulation based on a reference point, or - with weights when no reference is available. - \param x The evaluation point -- \b IN/OUT. - */ - virtual void compute_f ( NOMAD::Eval_Point & x ) const; - - /// Get the index of the first objective function. - /** - \return The index of the first objective function. - */ - static int get_i1 ( void ) { return _i1; } - - /// Get the index of the second objective function. - /** - \return The index of the second objective function. - */ - static int get_i2 ( void ) { return _i2; } - - /// Set the weights. - /** - \param w1 Weight on the first objective function -- \b IN. - \param w2 Weight on the second objective function -- \b IN. - */ - void set_weights ( const NOMAD::Double & w1 , - const NOMAD::Double & w2 ) { _w1 = w1; _w2 = w2; } - - /// Set the reference point. - /** - \param ref A pointer to the reference point -- \b IN. - */ - void set_ref ( const NOMAD::Point * ref ) { _ref = ref; } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Quad_Model_Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Quad_Model_Evaluator.hpp deleted file mode 100644 index 7dab90477..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Multi_Obj_Quad_Model_Evaluator.hpp +++ /dev/null @@ -1,84 +0,0 @@ - -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version (3.7.0.beta)*/ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Multi_Obj_Quad_Model_Evaluator.hpp - \brief NOMAD::Mulit_Obj_Evaluator subclass for quadratic model optimization (headers) - \author Christophe Tribes - \date 2014-06-19 - \see Multi_Obj_Quad_Model_Evaluator.cpp - */ -#ifndef __MULTI_OBJ_QUAD_MODEL_EVALUATOR__ -#define __MULTI_OBJ_QUAD_MODEL_EVALUATOR__ - -#include "Quad_Model_Evaluator.hpp" -#include "Multi_Obj_Evaluator.hpp" - -namespace NOMAD { - - /// Bi-objective NOMAD::Evaluator subclass for quadratic model. - class Multi_Obj_Quad_Model_Evaluator : public NOMAD::Quad_Model_Evaluator, public NOMAD::Multi_Obj_Evaluator { - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param model Model -- \b IN. - */ - Multi_Obj_Quad_Model_Evaluator ( const NOMAD::Parameters & p , - const NOMAD::Quad_Model & model ) : NOMAD::Quad_Model_Evaluator(p,model),NOMAD::Multi_Obj_Evaluator(p) {_is_model_evaluator=true;} - - /// Destructor. - virtual ~Multi_Obj_Quad_Model_Evaluator ( void ){;} - - - /// Evaluate the blackboxes quad model at a given trial point - /** - \param x point to evaluate -- \b IN/OUT. - \param h_max h_max for barrier -- \b IN. - \param count_eval Count eval if true -- \b IN. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const {return Quad_Model_Evaluator::eval_x(x,h_max,count_eval);} - - - }; -} - -#endif - diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/OrthogonalMesh.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/OrthogonalMesh.cpp deleted file mode 100644 index c07e2ae94..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/OrthogonalMesh.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file OrthogonalMesh.hpp - \brief implementation - \author Christophe Tribes - \date 2014-06-19 - \see SMesh.cpp XMesh.cpp - */ - -#include "OrthogonalMesh.hpp" - -/// Constructor (called only by derived objects). -NOMAD::OrthogonalMesh::OrthogonalMesh (const NOMAD::Point & Delta_0 , - const NOMAD::Point & Delta_min , - const NOMAD::Point & delta_min , - const NOMAD::Point & fixed_variables , - NOMAD::Double update_basis, - int coarsening_step, - int refining_step, - int limit_mesh_index ) : -_delta_0 ( Delta_0 ), -_Delta_0 ( Delta_0 ), -_Delta_min ( Delta_min ), -_delta_min ( delta_min ), -_update_basis ( update_basis ), -_coarsening_step ( coarsening_step ), -_refining_step ( refining_step ), -_limit_mesh_index ( limit_mesh_index ) -{ - bool chkMesh = delta_min.is_defined(); - bool chkPoll = Delta_min.is_defined(); - _n = Delta_0.size(); - - _n_free_variables = _n - fixed_variables.nb_defined(); - - // The delta_0 are obtained from the Delta_0 - _delta_0*=pow(_n_free_variables,-0.5); - - if ( !_Delta_0.is_complete() ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , - "NOMAD::OrthogonalMesh::OrthogonalMesh(): delta_0 has undefined values" ); - - if ( chkMesh && delta_min.size() != _n ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , - "NOMAD::OrthogonalMesh::OrthogonalMesh(): delta_0 and delta_min have different sizes" ); - - if ( chkPoll && Delta_min.size() != _n ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , - "NOMAD::OrthogonalMesh::OrthogonalMesh(): Delta_0 and Delta_min have different sizes" ); - - - std::string error; - for ( int k = 0 ; k < _n ; ++k ) - { - // we check that Delta_min <= Delta_0 and that delta_min <= delta_0: - if ( chkMesh && - _delta_min[k].is_defined() && - _delta_0[k] < _delta_min[k] ) - { - error = "NOMAD::OrthogonalMesh::OrthogonalMesh(): delta_0 < delta_min"; - break; - } - if ( chkPoll && - _Delta_min[k].is_defined() && - _Delta_0[k] < _Delta_min[k] ) - { - error = "NOMAD::OrthogonalMesh::OrthogonalMesh(): Delta_0 < Delta_min"; - break; - } - - } - - if ( !error.empty() ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , error ); -} - - - -bool NOMAD::OrthogonalMesh::is_finer_than_initial (void) const -{ - NOMAD::Point delta; - get_delta(delta); - - for (int i =0; i < _n ; ++i ) - if ( delta[i] >= _delta_0[i] ) - return false; - - return true; -} - - - -/// Manually set the min mesh size per coordinate. -void NOMAD::OrthogonalMesh::set_min_mesh_sizes ( const NOMAD::Point & delta_min ) -{ - - // If delta_min undefined than _delta_min->undefined - if ( ! delta_min.is_defined() ) - { - _delta_min.clear(); - return; - } - - // If delta_min defined test that everything is consistent - if ( delta_min.size() != _n ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::OrthogonalMesh::set_delta_min() delta_min has dimension different than mesh dimension" ); - - if ( !delta_min.is_complete() ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , - "NOMAD::OrthogonalMesh::set_delta_min(): delta_min has some defined and undefined values" ); - - std::string error; - for ( int k = 0 ; k < _n ; ++k ) - { - - // we check that Delta_min <= Delta_0 and that delta_min <= delta_0: - if ( delta_min[k].is_defined() && - _delta_0[k] < delta_min[k] ) - { - error = "NOMAD::OrthogonalMesh::set_delta_min(): delta_0 < delta_min"; - break; - } - if ( delta_min[k].is_defined() && - _Delta_0[k] < delta_min[k] ) - { - error = "NOMAD::OrthogonalMesh::set_delta_min(): Delta_0 < delta_min"; - break; - } - - } - - if ( !error.empty() ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , error ); - - _delta_min=delta_min; - -} - - - -/*-----------------------------------------------------------*/ -/* set delta_0 */ -/*-----------------------------------------------------------*/ -void NOMAD::OrthogonalMesh::set_delta_0 ( const NOMAD::Point & d ) -{ - - if ( d.size() != _delta_0.size() ) - throw NOMAD::Exception ( "OrthogonalMesh.hpp" , __LINE__ , - "NOMAD::OrthogonalMesh::set_delta_0(): dimension of provided delta_0 must be consistent with their previous dimension" ); - - _delta_0=d; -} - -/*-----------------------------------------------------------*/ -/* set Delta_0 */ -/*-----------------------------------------------------------*/ -void NOMAD::OrthogonalMesh::set_Delta_0 ( const NOMAD::Point & d ) -{ - - if ( d.size() != _Delta_0.size() ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::set_Delta_0(): dimension of provided Delta_0 must be consistent with their previous dimension" ); - - _Delta_0=d; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/OrthogonalMesh.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/OrthogonalMesh.hpp deleted file mode 100644 index 1d31dd259..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/OrthogonalMesh.hpp +++ /dev/null @@ -1,377 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file OrthogonalMesh.hpp - \brief Virtual class for the MADS orthogonal meshes (headers) - \author Christophe Tribes - \date 2010-04-06 - \see Mesh.cpp XMesh.cpp -*/ -#ifndef __ORTHOGONALMESH__ -#define __ORTHOGONALMESH__ - -#include "Point.hpp" -#include "Direction.hpp" - -namespace NOMAD { - - /// Virtual class for the MADS orthogonal meshes. - /** - - An orthogonal mesh in NOMAD is defined with the basic orthogonal directions the - mesh size parameter delta^k. - - The poll size parameter Delta^k is not used to define the mesh but - to define the poll trial points. - - At each MADS iteration the mesh is updated. - - Mesh and poll size parameters are stored as NOMAD::Point objects. - */ - class OrthogonalMesh { - - /*--------------------------------------------------------------*/ - private: - - - /*--------------------------------------------------------------*/ - - /// Private affectation operator. - /** - \param m The right-hand side object -- \b IN. - */ - const OrthogonalMesh & operator = ( const OrthogonalMesh & m ); - - - /*--------------------------------------------------------------*/ - protected: - - - NOMAD::Point _delta_0; - NOMAD::Point _Delta_0; - NOMAD::Point _Delta_min; - NOMAD::Point _delta_min; - - NOMAD::Double _update_basis; - int _coarsening_step; - int _refining_step ; - - int _n; - int _n_free_variables; - - int _limit_mesh_index; // Limit max or min of the mesh index for fine mesh (SMesh->max, XMesh->min) - - /// Constructor (called only by derived objects). - /** - \param Delta_0 Initial poll size Delta_0 -- \b IN. - \param Delta_min Minimal poll size Delta_min (may be undefined) -- \b IN. - \param delta_min Minimal mesh size delta_min (may be undefined) -- \b IN. - \param fixed_variables Fixed variables -- \b IN. - \param update_basis Mesh/poll update basis (tau) -- \b IN. - \param coarsening_step Mesh/poll coarsening exponent (w+) -- \b IN. - \param refining_step Mesh/poll refining exponent (w-) -- \b IN. - \param limit_mesh_index Limit mesh index to trigger stopping criterion -- \b IN. - */ - OrthogonalMesh (const NOMAD::Point & Delta_0 , - const NOMAD::Point & Delta_min , - const NOMAD::Point & delta_min , - const NOMAD::Point & fixed_variables , - NOMAD::Double update_basis, - int coarsening_step, - int refining_step, - int limit_mesh_index ) ; - - - /// Copy constructor (called only by derived objects). - /** - \param m The copied object -- \b IN. - */ - OrthogonalMesh ( const OrthogonalMesh & m ) - : _delta_0 ( m._delta_0 ), - _Delta_0 ( m._Delta_0 ), - _Delta_min ( m._Delta_min ), - _delta_min ( m._delta_min ), - _update_basis ( m._update_basis ), - _coarsening_step ( m._coarsening_step ), - _refining_step ( m._refining_step ), - _n ( m._n ), - _n_free_variables ( m._n_free_variables ), - _limit_mesh_index ( m._limit_mesh_index){} - - - /*--------------------------------------------------------------*/ - public: - - - /// Destructor. - virtual ~OrthogonalMesh ( void ){;} - - - /// Update the Mesh (poll and mesh sizes). - /** - \param success Type of success of the iteration -- \b IN. - \param dir Direction of the iteration (optional) -- \b IN. - */ - virtual void update ( NOMAD::success_type success, const NOMAD::Direction * dir=NULL) = 0; - - - /// Update the provided mesh indices (the Mesh is unchanged). - /** - \param success Type of success of the iteration -- \b IN. - \param mesh_indices Provided mesh indices for update -- \b IN/OUT. - \param dir Direction of the iteration (optional) -- \b IN. - */ - virtual void update ( NOMAD::success_type success, NOMAD::Point & mesh_indices, const NOMAD::Direction * dir=NULL ) const = 0; - - - - /// Reset the Mesh to its original sizes (poll and mesh sizes). - virtual void reset ( void ) = 0; - - - /// Access to the initial mesh size. - /** - \return A NOMAD::Point for the initial mesh size. - */ - const NOMAD::Point & get_initial_mesh_size ( void ) const { return _delta_0; } - - /// Access to the initial poll size. - /** - \return A NOMAD::Point for the initial poll size. - */ - const NOMAD::Point & get_initial_poll_size ( void ) const { return _Delta_0; } - - - /// Access to the minimal mesh size. - /** - \return A NOMAD::Point for the minimal mesh size. - */ - const NOMAD::Point & get_min_mesh_size ( void ) const { return _delta_min; } - - - /// Access to the minimal poll size. - /** - \return A NOMAD::Point for the minimal poll size. - */ - const NOMAD::Point & get_min_poll_size ( void ) const { return _Delta_min; } - - - /// Test if mesh is finest so far. - /** - \return True if mesh is the finest so far, False otherwise. - */ - virtual bool is_finest(void) const = 0; - - - /// Test if current mesh is finer than initial mesh (used by VNS search). - /** - \return True if mesh size is smaller than initial mesh size for all components. - */ - bool is_finer_than_initial (void) const; - - - /// Access to the mesh/poll update basis tau. - /** - \return A double with the update basis tau. - */ - double get_update_basis ( void ) const { return _update_basis.value(); } - - - /// Access to the mesh ratio after a success - /** - \return A point with the ratio for each coordinate - */ - virtual NOMAD::Point get_mesh_ratio_if_success( void ) const = 0; - - - /// Access to the number of variables. - /** - \return An integer with the number of variables. - */ - int get_n ( void ) const { return _n; } - - - /// Access to the number of free variables. - /** - \return An integer with the number of free variables. - */ - int get_n_free_variables ( void ) const { return _n_free_variables; } - - - /// Access to the mesh size parameter delta^k. - /** - \return delta The mesh size parameter delta^k -- \b OUT. - */ - NOMAD::Point get_delta ( void ) const - { - NOMAD::Point delta; - get_delta(delta); - return delta; - } - - /// Access to the mesh size parameter delta^k. - /** - \param delta The mesh size parameter delta^k -- \b OUT. - \return A boolean equal to \c true if all values are - strictly inferior than the associated minimal - mesh size delta_min - (stopping criterion MIN_MESH_SIZE). - */ - virtual bool get_delta ( NOMAD::Point & delta ) const = 0; - - /// Access to the largest mesh size. - /** - \return The largest mesh size -- \b OUT. - */ - virtual NOMAD::Point get_delta_max ( void ) const = 0; - - - /// Access to the poll size parameter Delta^k. - /** - \return Delta The poll size parameter Delta^k -- \b OUT. - */ - NOMAD::Point get_Delta ( void ) - { - NOMAD::Point Delta; - get_Delta(Delta); - return Delta; - } - - /// Access to the poll size parameter Delta^k. - /** - \param Delta The poll size parameter Delta^k -- \b OUT. - \return A boolean equal to \c true if all values are - strictly inferior than the associated minimal - mesh size delta_min - (stopping criterion MIN_POLL_SIZE). - */ - virtual bool get_Delta ( NOMAD::Point & Delta ) const = 0 ; - - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - virtual void display ( const NOMAD::Display & out ) const = 0; - - /// Check the stopping conditions on the minimal poll and mesh sizes. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - virtual void check_min_mesh_sizes ( bool & stop , - NOMAD::stop_type & stop_reason ) const = 0; - - /// Access to the mesh indices per coordinate. - /** - \return A point with the mesh index for each coordinate. - */ - virtual const NOMAD::Point get_mesh_indices ( void ) const = 0; - - /// Manually set the mesh indices per coordinate (virtual). - /** - \param r The mesh index per coordinate -- \b IN. - */ - virtual void set_mesh_indices ( const NOMAD::Point & r ) =0 ; - - /// Manually set the min mesh size per coordinate. - /** - \param delta_min The min mesh sizes per coordinate (can be undefined) -- \b IN. - */ - void set_min_mesh_sizes ( const NOMAD::Point & delta_min ); - - /// Manually set intial mesh size per coordinate. - /** - \param d The initial mesh sizes per coordinate -- \b IN. - */ - void set_delta_0 ( const NOMAD::Point & d ); - - /// Manually set intial poll size per coordinate. - /** - \param d The initial poll sizes per coordinate -- \b IN. - */ - void set_Delta_0 ( const NOMAD::Point & d ); - - - /// Access to the min mesh indices reached so far. - /** - \return A point with the mesh index for each coordinate. - */ - virtual const NOMAD::Point get_min_mesh_indices ( void ) const = 0; - - /// Access to the max mesh indices reached so far. - /** - \return A point with the mesh index for each coordinate. - */ - virtual const NOMAD::Point get_max_mesh_indices ( void ) const = 0; - - - /// Access to the limit mesh index. - /** - \return An integer with the limit mesh index. - */ - int get_limit_mesh_index ( void ) const { return _limit_mesh_index;} - - - /// Manually set the limit mesh index. - /** - \param limit_mesh_index The limit mesh index. - */ - virtual void set_limit_mesh_index ( int limit_mesh_index ) = 0; - - - /// Scale and project the ith component of a vector on the mesh - /** - \param i The vector component number -- \b IN. - \param l The vector component value -- \b IN. - \return The ith component of a vector after mesh scaling and projection - */ - virtual NOMAD::Double scale_and_project(int i, NOMAD::Double l) const = 0 ; - - - }; - - /// Display a NOMAD::OrthogonalMesh object. - /** - \param out The NOMAD::Display object -- \b IN. - \param m The NOMAD::OrthogonalMesh object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::OrthogonalMesh & m ) - { - m.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entries.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entries.cpp deleted file mode 100644 index b2d6e7aca..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entries.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Parameter_Entries.cpp - \brief Parameter entries (implementation) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Parameter_Entries.hpp -*/ -#include "Parameter_Entries.hpp" - -/*--------------------------------------------*/ -/* destructor */ -/*--------------------------------------------*/ -NOMAD::Parameter_Entries::~Parameter_Entries ( void ) -{ - std::multiset::iterator - end = _entries.end() , it; - for ( it = _entries.begin() ; it != end ; ++it) - delete *it; -} - -/*--------------------------------------------*/ -/* finds a specific entry in the set */ -/*--------------------------------------------*/ -NOMAD::Parameter_Entry * NOMAD::Parameter_Entries::find ( const std::string & name ) const -{ - NOMAD::Parameter_Entry p (name); - std::multiset::const_iterator - it = _entries.find ( &p ); - if ( it != _entries.end() ) - return (*it); - return NULL; -} - -/*----------------------------------------*/ -/* inserts an entry into the set */ -/*----------------------------------------*/ -void NOMAD::Parameter_Entries::insert ( NOMAD::Parameter_Entry * entry ) -{ - NOMAD::Parameter_Entry * cur = find ( entry->get_name() ); - if ( cur ) { - entry->set_unique ( false ); - cur->set_unique ( false ); - while ( cur->get_next() ) - cur = cur->get_next(); - cur->set_next ( entry ); - } - _entries.insert ( entry ); -} - -/*----------------------------------------*/ -/* find a non-interpreted entry */ -/*----------------------------------------*/ -NOMAD::Parameter_Entry * NOMAD::Parameter_Entries::find_non_interpreted ( void ) const -{ - std::multiset::const_iterator - end = _entries.end() , it; - for ( it = _entries.begin() ; it != end ; ++it ) - if ( !(*it)->has_been_interpreted() ) - return *it; - return NULL; -} - -/*--------------------------------------------*/ -/* display */ -/*--------------------------------------------*/ -void NOMAD::Parameter_Entries::display ( const NOMAD::Display & out ) const -{ - std::multiset::const_iterator - end = _entries.end() , it; - for ( it = _entries.begin() ; it != end ; ++it ) - out << **it << std::endl; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entries.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entries.hpp deleted file mode 100644 index 13f782f46..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entries.hpp +++ /dev/null @@ -1,113 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Parameter_Entries.hpp - \brief Parameter entries (headers) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Parameter_Entries.cpp -*/ -#ifndef __PARAMETER_ENTRIES__ -#define __PARAMETER_ENTRIES__ - -#include "Parameter_Entry.hpp" - -namespace NOMAD { - - /// Parameter entries. - /** - - Objects of this class store NOMAD::Parameter_Entry objects. - - One NOMAD::Parameter_Entries object summarizes an entire parameters file. - */ - class Parameter_Entries : private NOMAD::Uncopyable { - - private: - - /// List of NOMAD::Parameter_Entry objects (the entries). - std::multiset _entries; - - public: - - /// Constructor. - explicit Parameter_Entries ( void ) {} - - /// Destructor. - virtual ~Parameter_Entries ( void ); - - /// Find a specific entry in a set. - /** - \param name The name of the wanted NOMAD::Parameter_Entry object -- \b IN. - \return A pointer to the NOMAD::Parameter_Entry object if it - has been found in the list of entries, - or \c NULL otherwise. - */ - NOMAD::Parameter_Entry * find ( const std::string & name ) const; - - /// Insert a new entry in the list of entries. - /** - \param entry A pointer to the new NOMAD::Parameter_Entry object -- \b IN. - */ - void insert ( NOMAD::Parameter_Entry * entry ); - - /// Find a non-interpreted entry. - /** - \return A pointer to the first NOMAD::Parameter_Entry that has not been - interpreted so far, - or \c NULL if all entries have already been interpreted. - */ - NOMAD::Parameter_Entry * find_non_interpreted ( void ) const; - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::Parameter_Entries object. - /** - \param out The NOMAD::Display object -- \b IN. - \param e The NOMAD::Parameter_Entries object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Parameter_Entries & e ) - { - e.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.cpp deleted file mode 100644 index 094af4939..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Parameter_Entry.cpp - \brief Parameter entry (implementation) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Parameter_Entry.hpp -*/ -#include "Parameter_Entry.hpp" - -/*-----------------------------------*/ -/* . constructor (from a string) */ -/* . ignores all entries after '#' */ -/*-----------------------------------*/ -NOMAD::Parameter_Entry::Parameter_Entry ( const std::string & entry , - bool remove_comments ) - : _ok ( false ) , - _unique ( true ) , - _next ( NULL ) , - _has_been_interpreted ( false ) -{ - int i , idst; - std::string s; - std::istringstream in ( entry ); - in >> _name; - - if (_name.size()==0) - return; - - if ( remove_comments && _name[0] == '#' ) - _name.clear(); - else { - - NOMAD::toupper ( _name ); - - bool stats_file_name_read = false; - - while ( true ) { - in >> s; - - if ( in.fail() ) - break; - - // comment: - if ( remove_comments && s[0]=='#' ) - break; - - // string with quotes: - bool had_quotes = false; - if ( s[0] == '\"' || s[0] == '\'' ) { - - had_quotes = true; - char quote = s[0]; - - s.erase ( s.begin() ); - - if ( s[s.size()-1] == quote ) - s.resize ( s.size() - 1 ); - - else { - std::string ss; - getline ( in , ss , quote ); - - if ( in.fail() || !in.good()) { - _ok = false; - return; - } - - s = s + ss; - } - } - - // DISPLAY_STATS or STATS_FILE: - if ( _name == "STATS_FILE" && !stats_file_name_read ) - stats_file_name_read = true; - - else if ( _name == "DISPLAY_STATS" || _name == "STATS_FILE" ) { - - if ( had_quotes ) { - _ok = false; - return; - } - - std::string keyword , ss = s; - bool interpreted = false; - NOMAD::toupper ( ss ); - - NOMAD::display_stats_type dst = NOMAD::DS_OBJ; - while ( dst < NOMAD::DS_UNDEFINED ) { - - keyword = NOMAD::Display::get_display_stats_keyword (dst); - - i = static_cast ( ss.rfind ( keyword , ss.size()-1 ) ); - - if ( i >= 0 ) { - std::string s1 = s.substr ( 0 , i ); - std::string s2 = s.substr ( i+keyword.size() ); - if ( !s1.empty() ) - _values.push_back ( s1 ); - _values.push_back ( keyword ); - if ( !s2.empty() ) - _values.push_back ( s2 ); - _values.push_back ( std::string() ); - interpreted = true; - break; - } - - // loop increment: - idst = dst; - ++idst; - dst = static_cast ( idst ); - } - - if ( !interpreted ) { - _values.push_back ( s ); - _values.push_back ( std::string() ); - } - - continue; - } - - // vector: - if ( s.size() > 1 && ( s[0] == '[' || s[0] == '(' ) ) { - _values.push_back ( s[0]=='[' ? "[" : "(" ); - s.erase(s.begin()); - } - int sm1 = static_cast(s.size()) - 1; - char c = s[sm1]; - if ( s.size() > 1 && ( c == ']' || c == ')' ) ) { - s.resize(sm1); - _values.push_back (s); - _values.push_back ( c==']' ? "]" : ")" ); - continue; - } - - // other values: - _values.push_back ( s ); - } - - if ( !_values.empty() ) - _ok = true; - } -} - -/*------------------------------*/ -/* display */ -/*------------------------------*/ -void NOMAD::Parameter_Entry::display ( const NOMAD::Display & out ) const -{ - if ( _ok ) { - out << _name << ": "; - std::list::const_iterator end = _values.end(); - for ( std::list::const_iterator it = _values.begin() ; it != end ; ++it ) - out << "[" << *it << "] "; - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.hpp deleted file mode 100644 index 7a5cb40d6..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameter_Entry.hpp +++ /dev/null @@ -1,199 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Parameter_Entry.hpp - \brief Parameter entry (headers) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Parameter_Entry.cpp -*/ -#ifndef __PARAMETER_ENTRY__ -#define __PARAMETER_ENTRY__ - -#include "Display.hpp" -#include "Uncopyable.hpp" - -namespace NOMAD { - - /// Parameter entry. - /** - - Describes the data relative to a parameter in a parameters file. - - Objets of this class are stored in a NOMAD::Parameter_Entries object. - */ - class Parameter_Entry : private NOMAD::Uncopyable { - - private: - - std::string _name; ///< Name of the parameter. - std::list _values; ///< List of values for the parameter. - bool _ok; ///< If the parameter is valid. - bool _unique; ///< If the parameter is unique. - Parameter_Entry * _next; ///< Acces to the next parameter. - - /// If the parameter has been interpreted. - bool _has_been_interpreted; - - public: - - /// Constructor. - /** - Ignores all entries after \c '#'. - \param entry A string describing the parameter entry -- \b IN. - \param remove_comments A boolean equal to \c true if entries after - \c '#' are ignored -- \b IN - -- \b optional (default = \c true). - */ - Parameter_Entry ( const std::string & entry , bool remove_comments = true ); - - /// Destructor. - virtual ~Parameter_Entry ( void ) {} - - /*---------------*/ - /* GET methods */ - /*---------------*/ - - /// Access to the name of the parameter. - /** - \return The name. - */ - const std::string & get_name ( void ) const { return _name; } - - /// Access to the parameter values. - /** - \return The parameter values as a list of strings. - */ - const std::list & get_values ( void ) const { return _values; } - - /// Access to the number of values of the parameter. - /** - \return The number of values. - */ - int get_nb_values ( void ) const { return static_cast(_values.size()); } - - /// Access to the \c _ok flag. - /** - This flag is equal to \c true if the parameter entry is well defined. - \return A boolean equal to \c true if the parameter is valid. - */ - bool is_ok ( void ) const { return _ok; } - - /// Access to the \c _unique flag. - /** - This flag is decided when a parameters file is read. - \return A boolean equal to \c true if the parameter is unique - in a parameters file. - */ - bool is_unique ( void ) const { return _unique; } - - /// Access to another NOMAD::Parameter_Entry. - /** - NOMAD::Parameter_Entry objects are stored in a NOMAD::Parameter_Entries - object. The link between elements is assumed by the \c _next member - returned by this function. - \return A pointer to the next entry. - */ - Parameter_Entry * get_next ( void ) const { return _next; } - - /// Access to the \c _has_been_interpreted flag. - /** - \return A boolean equal to \c true if the parameter has already - been interpreted. - */ - bool has_been_interpreted ( void ) const { return _has_been_interpreted; } - - /*---------------*/ - /* SET methods */ - /*---------------*/ - - /// Set the \c _next pointer. - /** - \param p A pointer to the next NOMAD::Parameter_Entry to be inserted -- \b IN. - */ - void set_next ( Parameter_Entry * p ) { _next = p; } - - /// Set the \c _unique flag. - /** - \param u Value of the flag -- \b IN. - */ - void set_unique ( bool u ) { _unique = u; } - - /// Set the \c _has_been_interpreted flag. to \c true. - void set_has_been_interpreted ( void ) { _has_been_interpreted = true; } - - /// Comparison with another entry. - /** - The comparison is based on the parameter name. - \param p The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c this->_name \c < \c p._name. - */ - bool operator < ( const Parameter_Entry & p ) const { return _name < p._name; } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Allows the comparison of two NOMAD::Parameter_Entry objects. - struct Parameter_Entry_Comp { - /// Comparison of two NOMAD::Parameter_Entry objects. - /** - \param p1 Pointer to the first NOMAD::Parameter_Entry -- \b IN. - \param p2 Pointer to the second NOMAD::Parameter_Entry -- \b IN. - \return A boolean equal to \c true if \c *p1 \c < \c *p2. - */ - bool operator() ( const Parameter_Entry * p1 , const Parameter_Entry * p2 ) const - { - return (*p1 < *p2); - } - }; - - /// Display a NOMAD::Parameter_Entry object. - /** - \param out The NOMAD::Display object -- \b IN. - \param e The NOMAD::Parameter_Entry object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Parameter_Entry & e ) - { - e.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameters.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameters.cpp deleted file mode 100644 index 8a53582c1..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameters.cpp +++ /dev/null @@ -1,9938 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Parameters.cpp - \brief NOMAD parameters (implementation) - \author Sebastien Le Digabel - \date 2010-04-20 - \see Parameters.hpp - */ -#include "Parameters.hpp" -#include "Slave.hpp" -#include "XMesh.hpp" -#include "SMesh.hpp" - -bool NOMAD::Parameters::_warning_has_been_displayed=false; - -/*----------------------------------------*/ -/* destructor */ -/*----------------------------------------*/ -NOMAD::Parameters::~Parameters ( void ) -{ - delete _std_signature; - delete_x0s(); - reset_variable_groups(); -} - -/*----------------------------------------*/ -/* initializations (private) */ -/*----------------------------------------*/ -void NOMAD::Parameters::init ( void ) -{ - // miscellaneous and algorithm parameters: - _to_be_checked = true; - _seed = 0; - // _seed = NOMAD::get_pid(); - _max_eval = -1; - _max_sim_bb_eval = -1; - _max_bb_eval = -1; - _max_bbe_decided = false; - _max_time = -1; - _max_iterations = -1; - _max_cons_failed_it = -1; - _max_cache_memory = 2000; - _cache_save_period = 25; - _snap_to_bounds = true; - _stop_if_feasible = false; - _user_calls_enabled = true; - _asynchronous = true; - _stat_sum_target.clear(); - _L_curve_target.clear(); - _cache_file.clear(); - _problem_dir.clear(); - _tmp_dir.clear(); - - // F_TARGET: - reset_f_target(); - - // output files: - _add_seed_to_file_names = true; - _solution_file.clear(); - _history_file.clear(); - - // NOMAD::Double static members: - set_EPSILON ( NOMAD::DEFAULT_EPSILON ); - set_UNDEF_STR ( NOMAD::DEFAULT_UNDEF_STR ); - set_INF_STR ( NOMAD::DEFAULT_INF_STR ); - - // Mesh: - _anisotropic_mesh = true; - _use_smesh = false; - _mesh_update_basis = 4; - _poll_update_basis = 2; - _mesh_coarsening_exponent = 1; - _mesh_refining_exponent =-1; - _initial_mesh_index = 0; - _min_poll_size_defined = false; - _initial_mesh_size.clear(); - _initial_poll_size.clear(); - _min_mesh_size.clear(); - _min_poll_size.clear(); - - // Directions: - reset_directions ( ); - - // X0: - reset_X0(); - - // signature: - delete _std_signature; - _std_signature = NULL; - - // variables: - _dimension = -1; - _nb_free_variables = -1; - _extended_poll_trigger = 0.1; - _relative_ept = true; - _extended_poll_enabled = true; - _bb_input_include_tag = false; - _bb_input_include_seed = false; - _bb_redirection = true; - _bb_input_type.clear(); - _neighbors_exe.clear(); - reset_bounds(); - reset_scaling(); - reset_fixed_variables(); - reset_periodic_variables(); - reset_variable_groups(); - - // Barrier: - _rho = 0.1; - _h_min = 0.0; - _h_max_0 = NOMAD::INF; - _h_norm = NOMAD::L2; - _has_constraints = false; - _has_EB_constraints = false; - _has_filter_constraints = false; - _barrier_type = NOMAD::EB; - - // outputs: - _index_obj.clear(); - _bb_exe.clear(); - _bb_output_type.clear(); - _index_cnt_eval = -1; - _index_stat_sum = -1; - _index_stat_avg = -1; - - // surrogate: - _sgte_exe.clear(); - _sgte_cache_file.clear(); - _sgte_eval_sort = true; - _has_sgte = false; - _opt_only_sgte = false; - _sgte_cost = -1; - _sgte_max_eval = -1; - - // MULTI-MADS: - _multi_nb_mads_runs = -1; - _multi_overall_bb_eval = -1; - _multi_use_delta_crit = false; - _multi_formulation = NOMAD::UNDEFINED_FORMULATION; - _multi_f_bounds.reset(); - - // model is not disabled - _disable_models=false; - - // sort is not disabled - _disable_eval_sort=false; - - - // model search parameters: - _model_params.search1 = NOMAD::QUADRATIC_MODEL; - _model_params.search2 = NOMAD::NO_MODEL; - - _model_params.search_proj_to_mesh = true; - _model_params.search_optimistic = true; - _model_params.search_max_trial_pts = 10; - - // model ordering parameters: - _model_params.eval_sort = NOMAD::QUADRATIC_MODEL; - _model_params.eval_sort_cautious = true; - - // quadratic model parameters: - _model_params.quad_radius_factor = 2.0; - _model_params.quad_use_WP = false; - _model_params.quad_min_Y_size = -1; - _model_params.quad_max_Y_size = 500; - _model_params.model_np1_quad_epsilon =0.01; - - // TGP model parameters: - _model_params.tgp_mode = NOMAD::TGP_FAST; - _model_params.tgp_reuse_model = true; - - // other searches: - _VNS_trigger.clear(); - _speculative_search = true; - _VNS_search = false; - _LH_search_p0 = -1; - _LH_search_pi = -1; - _opportunistic_LH = true; - _opp_LH_is_defined = false; - _cache_search = false; - _opportunistic_cache_search = false; - _opp_CS_is_defined = false; - - // opportunistic strategy: - _bb_max_block_size = 1; - _eval_points_as_block = false; - _opportunistic_eval = true; - _opportunistic_min_nb_success = -1; - _opportunistic_min_eval = -1; - _opportunistic_lucky_eval = false; - _opportunistic_min_f_imprvmt.clear(); - - // display: - _out.set_degrees ( NOMAD::NORMAL_DISPLAY ); -#ifdef DEBUG - set_POINT_DISPLAY_LIMIT ( -1 ); -#else - set_POINT_DISPLAY_LIMIT ( NOMAD::DEFAULT_POINT_DISPLAY_LIMIT ); -#endif - - _out.set_open_brace ( "{" ); - _out.set_closed_brace ( "}" ); - - _display_stats.clear(); - reset_stats_file(); - - _display_all_eval = false; -} - -/*------------------------------------------------------------------*/ -/* delete the list of x0 points: std::vector _x0s */ -/* (private) */ -/*------------------------------------------------------------------*/ -void NOMAD::Parameters::delete_x0s ( void ) -{ - size_t x0n = _x0s.size(); - for ( size_t i = 0 ; i < x0n ; ++i ) - delete _x0s[i]; - _x0s.clear(); -} - -/*----------------------------------------*/ -/* reset parameter X0 */ -/*----------------------------------------*/ -void NOMAD::Parameters::reset_X0 ( void ) -{ - _to_be_checked = true; - delete_x0s(); - _x0_cache_file.clear(); -} - -/*----------------------------------------*/ -/* reset the directions */ -/*----------------------------------------*/ -void NOMAD::Parameters::reset_directions ( void ) -{ - _to_be_checked = true; - _direction_types.clear(); - _sec_poll_dir_types.clear(); -} - -/*--------------------------------------------*/ -/* check the display and file stats */ -/*--------------------------------------------*/ -bool NOMAD::Parameters::check_display_stats -( const std::list & stats ) const -{ - int var_index; - std::list::const_iterator it , end = stats.end(); - for ( it = stats.begin() ; it != end ; ++it ) { - if ( !it->empty() && - NOMAD::Display::get_display_stats_type(*it) == NOMAD::DS_VAR ) { - ++it; - if ( !NOMAD::atoi ( *it , var_index ) || - var_index < 0 || - var_index >= _dimension ) { - return false; - } - } - } - return true; -} - -/*--------------------------------------------*/ -/* check a directory name (static, private) */ -/*--------------------------------------------*/ -bool NOMAD::Parameters::check_directory ( std::string & s ) -{ - // step 1: remove spaces at the begining: - size_t i = 0 , ns = s.size(); - while ( i < ns && s[i] == ' ' ) - ++i; - std::string ss; - while ( i < ns ) - ss.push_back(s[i++]); - if ( ss.empty() ) - return false; - s = ss; - - // step 2: replace '/' or '\' with DIR_SEP: - i = 0; - ns = s.size(); - while ( i < ns ) { - if ( s[i] == '/' || s[i] == '\\' ) - s[i] = NOMAD::DIR_SEP; - ++i; - } - - // step 3: add DIR_SEP at the end: - if ( i >= 1 ) { - if (s[i-1] != NOMAD::DIR_SEP) { - s += NOMAD::DIR_SEP; - } - } - else { - s = "."; - s.push_back ( NOMAD::DIR_SEP ); - } - - return true; -} - -/*---------------------------------------------------------------*/ -/* interpretation of the Parameter_Entry for PERIODIC_VARIABLE */ -/* (private) */ -/*---------------------------------------------------------------*/ -void NOMAD::Parameters::interpret_periodic_var -( const NOMAD::Parameter_Entries & entries ) -{ - int i , j , k; - std::list::const_iterator it , end; - NOMAD::Parameter_Entry * pe = entries.find ( "PERIODIC_VARIABLE" ); - - while ( pe ) { - - // just one variable index (can be '*' or a range of indexes 'i-j'): - if ( pe->get_nb_values() == 1 ) { - - it = pe->get_values().begin(); - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE" ); - - for ( k = i ; k <= j ; ++k ) - set_PERIODIC_VARIABLE (k); - } - - // list of variable indexes: - else { - end = pe->get_values().end(); - for ( it = pe->get_values().begin() ; it != end ; ++it ) { - if ( !NOMAD::atoi ( *it , i ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE" ); - set_PERIODIC_VARIABLE (i); - } - } - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } -} - -/*------------------------------------------------------------*/ -/* interpretation of the Parameter_Entry for VARIABLE_GROUP */ -/* (private) */ -/*------------------------------------------------------------*/ -void NOMAD::Parameters::interpret_var_groups ( const NOMAD::Parameter_Entries & entries ) -{ - int i , j , k; - std::set var_indexes; - std::list::const_iterator it , end; - NOMAD::Parameter_Entry * pe = entries.find ( "VARIABLE_GROUP" ); - - while ( pe ) { - - // just one variable index (can be '*' or a range of indexes 'i-j'): - if ( pe->get_nb_values() == 1 ) { - - it = pe->get_values().begin(); - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP" ); - - for ( k = j ; k >= i ; --k ) - var_indexes.insert(k); - } - - // list of variable indexes: - else { - end = pe->get_values().end(); - for ( it = pe->get_values().begin() ; it != end ; ++it ) { - if ( !NOMAD::atoi ( *it , i ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP" ); - var_indexes.insert(i); - } - } - - set_VARIABLE_GROUP ( var_indexes , - _direction_types , - _sec_poll_dir_types ); - - var_indexes.clear(); - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } -} - -/*------------------------------------------------------*/ -/* interpretation of the Parameter_Entry for bounds, */ -/* fixed variables, and scaling (BFVS) */ -/* (param_name = "LOWER_BOUND" or "UPPER_BOUND" */ -/* "FIXED_VARIABLE" or "SCALING" ) */ -/* (private) */ -/*------------------------------------------------------*/ -void NOMAD::Parameters::interpret_BFVS ( const NOMAD::Parameter_Entries & entries , - const std::string & param_name ) -{ - // param_name == LOWER_BOUND or UPPER_BOUND or FIXED_VARIABLE: - if ( param_name != "LOWER_BOUND" && - param_name != "UPPER_BOUND" && - param_name != "FIXED_VARIABLE" && - param_name != "SCALING" ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "wrong use of Parameters::interpret_BFVS()" ); - - NOMAD::Parameter_Entry * pe = entries.find ( param_name ); - std::list::const_iterator it; - int i, j, k; - NOMAD::Double v; - std::string err; - std::string file_name; - std::ifstream fin; - - while ( pe ) - { - - // file name or just one index: - if ( pe->get_nb_values() == 1 ) - { - - // special case for FIXED_VARIABLE without value - // (the value will be taken from x0, if unique): - if ( isdigit ( (*pe->get_values().begin())[0] ) || - *pe->get_values().begin() == "*" ) - { - - if ( param_name[0] != 'F' ) - { - err = "invalid parameter: " + param_name - + " - only one argument, which is not a file name"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - if ( _x0s.size() != 1 || !_x0_cache_file.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "FIXED_VARIABLE with only a variable index and no unique x0" ); - - if ( !NOMAD::string_to_index_range ( *pe->get_values().begin() , - i , - j , - &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE" ); - - for ( k = i ; k <= j ; ++k ) - set_FIXED_VARIABLE ( k , (*_x0s[0])[k] ); - } - - - // file name: - else { - - file_name = _problem_dir + *pe->get_values().begin(); - - fin.open ( file_name.c_str() ); - - if ( fin.fail() ) - { - err = "invalid parameter: " + param_name + - " - could not open file \'" + file_name + "\'"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - try { - switch ( param_name[0] ) { - case 'L': - _lb.reset ( _dimension ); - fin >> _lb; - break; - case 'U': - _ub.reset ( _dimension ); - fin >> _ub; - break; - case 'F': - _fixed_variables.reset ( _dimension ); - fin >> _fixed_variables; - break; - case 'S': - _scaling.reset ( _dimension ); - fin >> _scaling; - } - } - catch ( NOMAD::Point::Bad_Input & ) { - err = "invalid parameter: " + param_name + - " - could not read file \'" + file_name + "\'"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - fin.close(); - } - } - - // vector form: all values on one row: - else if ( pe->get_nb_values() == _dimension + 2 ) { - - if ( !pe->is_unique() ) { - err = "invalid parameter: " + param_name + - " - has been given in vector form with [] or () and is not unique"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - it = pe->get_values().begin(); - - if ( *it != "[" && *it != "(" ) { - err = "invalid parameter: " + param_name + - " - error in vector form with () or []"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - ++it; - for ( k = 0 ; k < _dimension ; ++k ) { - if ( !v.atof(*it) ) { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - ++it; - switch ( param_name[0] ) { - case 'L': set_LOWER_BOUND ( k , v ); - break; - case 'U': set_UPPER_BOUND ( k , v ); - break; - case 'F': set_FIXED_VARIABLE ( k , v ); - break; - case 'S': set_SCALING ( k , v ); - } - } - - if ( *it != "]" && *it != ")" ) { - err = "invalid parameter: " + param_name + - " - error in vector form with () or []"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - } - - // indexed values: - else { - - if ( pe->get_nb_values() != 2 ) { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - it = pe->get_values().begin(); - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - ++it; - if ( !v.atof(*it) ) { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - for ( k = j ; k >= i ; --k ) - switch (param_name[0]) { - case 'L': set_LOWER_BOUND ( k, v ); - break; - case 'U': set_UPPER_BOUND ( k, v ); - break; - case 'F': set_FIXED_VARIABLE ( k, v ); - break; - case 'S': set_SCALING ( k, v ); - } - } - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } -} - -/*----------------------------------------------------------------*/ -/* interpretation of the Parameter_Entry for F_TARGET (private) */ -/*----------------------------------------------------------------*/ -void NOMAD::Parameters::interpret_f_target ( const NOMAD::Parameter_Entries & entries ) -{ - NOMAD::Double d; - std::list::const_iterator it; - NOMAD::Parameter_Entry * pe = entries.find ( "F_TARGET" ); - - if ( pe ) - { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: F_TARGET not unique" ); - - it = pe->get_values().begin(); - - int nb_values = pe->get_nb_values(); - - // just one value: single-objective optimization: - if ( nb_values == 1 ) - { - - if ( !d.atof ( *it ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: F_TARGET" ); - set_F_TARGET (d); - } - - // vector form: multi-objective optimization: - else - { - - nb_values -= 2; - - NOMAD::Point f_target ( nb_values ); - - if ( *it != "[" && *it != "(" ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: F_TARGET - error in vector form with () or []" ); - - ++it; - - for ( int k = 0 ; k < nb_values ; ++k ) - { - - if ( !d.atof ( *it ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: F_TARGET" ); - ++it; - - f_target[k] = d; - } - - if ( *it != "]" && *it != ")" ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: F_TARGET - error in vector form with () or []" ); - - set_F_TARGET ( f_target ); - } - pe->set_has_been_interpreted(); - } -} - -/*-------------------------------------------------------------*/ -/* interpretation of the Parameter_Entry for mesh/poll sizes */ -/* (private) */ -/*-------------------------------------------------------------*/ -void NOMAD::Parameters::interpret_mesh_sizes -( const NOMAD::Parameter_Entries & entries , - const std::string & param_name ) -{ - // param_name == "INITIAL_MESH_SIZE" or "INITIAL_MESH_SIZE" or "MIN_MESH_SIZE" or "MIN_POLL_SIZE": - if ( param_name != "INITIAL_POLL_SIZE" && - param_name != "INITIAL_MESH_SIZE" && - param_name != "MIN_MESH_SIZE" && - param_name != "MIN_POLL_SIZE" ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "wrong use of Parameters::interpret_mesh_sizes()" ); - - int i , j , k; - NOMAD::Double v; - bool relative; - std::string err; - std::list::const_iterator it; - NOMAD::Parameter_Entry * pe = entries.find ( param_name ); - - while ( pe ) - { - - // just one value: - if ( pe->get_nb_values() == 1 ) - { - - if ( !pe->is_unique() ) - { - err = "invalid parameter: " + param_name - + " - has been given with just one value and is not unique"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - if ( !v.relative_atof ( *pe->get_values().begin() , relative ) ) - { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - if ( param_name[0] == 'I' && param_name[8] =='M') - set_INITIAL_MESH_SIZE ( v , relative ); - else if ( param_name[0] == 'I' && param_name[8] =='P') - set_INITIAL_POLL_SIZE ( v , relative ); - else if ( param_name[4] == 'M' ) - set_MIN_MESH_SIZE ( v , relative ); - else - set_MIN_POLL_SIZE ( v , relative ); - } - - // indexed form: - else if ( pe->get_nb_values() == 2 ) - { - - it = pe->get_values().begin(); - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - ++it; - - if ( !v.relative_atof( *it , relative ) ) - { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - for ( k = i ; k <= j ; ++k ) - { - if ( param_name[0] == 'I' && param_name[8] =='M') - set_INITIAL_MESH_SIZE ( k , v , relative ); - else if ( param_name[0] == 'I' && param_name[8] =='P') - set_INITIAL_POLL_SIZE ( k , v , relative ); - else if ( param_name[4] == 'M' ) - set_MIN_MESH_SIZE ( k , v , relative ); - else - set_MIN_POLL_SIZE ( k , v , relative ); - } - } - - // vector form: all values on one row: - else if ( pe->get_nb_values() == _dimension + 2 ) - { - - if ( !pe->is_unique() ) { - err = "invalid parameter: " + param_name - + " - has been given in vector form with [] or () and is not unique"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - it = pe->get_values().begin(); - - if ( *it != "[" && *it != "(" ) - { - err = "invalid parameter: " + param_name + - " - error in vector form with () or []"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - ++it; - for ( k = 0 ; k < _dimension ; ++k ) - { - if ( !v.relative_atof ( *it , relative ) ) - { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - ++it; - if ( param_name[0] == 'I' && param_name[8] =='M' ) - set_INITIAL_MESH_SIZE ( k , v , relative ); - if ( param_name[0] == 'I' && param_name[8] =='P' ) - set_INITIAL_POLL_SIZE ( k , v , relative ); - else if ( param_name[4] == 'M' ) - set_MIN_MESH_SIZE ( k , v , relative ); - else - set_MIN_POLL_SIZE ( k , v , relative ); - } - - if ( *it != "]" && *it != ")" ) - { - err = "invalid parameter: " + param_name + - " - error in vector form with () or []"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - } - - else - { - err = "invalid parameter: " + param_name; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } -} - -/*---------------------------------------------------------------------------------*/ -/* interpretation of the Parameter_Entry for BB_INPUT_TYPE (private) */ -/*---------------------------------------------------------------------------------*/ -/* BB_INPUT_TYPE [ t1 t2 ... tn ] # blackbox input types (one type/variable) */ -/* or BB_INPUT_TYPE i t # ti in { R , C , B , I } */ -/* # or { Real , Cat , Bin , Int } */ -/* or BB_INPUT_TYPE i-j t */ -/*---------------------------------------------------------------------------------*/ -void NOMAD::Parameters::interpret_bb_input_type -( const NOMAD::Parameter_Entries & entries ) -{ - int i , j , k; - NOMAD::bb_input_type bbit; - std::list::const_iterator it; - NOMAD::Parameter_Entry * pe = entries.find ( "BB_INPUT_TYPE" ); - - while ( pe ) { - - // indexed form: - if ( pe->get_nb_values() == 2 ) { - - it = pe->get_values().begin(); - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE" ); - ++it; - if ( !NOMAD::string_to_bb_input_type ( *it , bbit ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE" ); - - for ( k = i ; k <= j ; ++k ) - set_BB_INPUT_TYPE ( k , bbit ); - } - - // vector form: all values on one row: - else if ( pe->get_nb_values() == _dimension + 2 ) { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - std::string ( "invalid parameter: BB_INPUT_TYPE " ) - + " - has been given in vector form with [] or () and is not unique" ); - - it = pe->get_values().begin(); - - if ( *it != "[" && *it != "(" ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE - error in vector form with () or []" ); - - ++it; - for ( k = 0 ; k < _dimension ; ++k ) { - if ( !NOMAD::string_to_bb_input_type ( *it , bbit ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE" ); - ++it; - set_BB_INPUT_TYPE ( k , bbit ); - } - - if ( *it != "]" && *it != ")" ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE - error in vector form with () ot []" ); - } - - else - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE" ); - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } -} - -/*------------------------------------------------*/ -/* interpretation of the Parameter_Entry for x0 */ -/* (private) */ -/*------------------------------------------------*/ -void NOMAD::Parameters::interpret_x0 ( const NOMAD::Parameter_Entries & entries ) -{ - NOMAD::Parameter_Entry * pe = entries.find ( "X0" ); - std::list::const_iterator it; - int i , j , k , l; - NOMAD::Double v; - NOMAD::Point tmp_x0; - std::vector indexes; - - while ( pe ) { - - tmp_x0.reset ( _dimension ); - - // File name: - if ( pe->get_nb_values() == 1 ) - set_X0 ( *pe->get_values().begin() ); - - // Vector form: all values on one row: - else if ( pe->get_nb_values() == _dimension + 2 ) { - - it = pe->get_values().begin(); - - if ( *it != "[" && *it != "(" ) { - - // particular case with n=1 and 3 entry values: - // example: X0 1 0 4.0 (first coordinate of the 2nd x0 point put to 4.0) - if ( _dimension == 1 ) { - - it = pe->get_values().begin(); - - if ( !NOMAD::atoi ( *it , l ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0" ); - - i = static_cast ( indexes.size() ); - if ( l > i ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0" ); - else if ( l == i ) { - l = static_cast ( _x0s.size() ); - indexes.push_back ( l ); - set_X0 ( tmp_x0 ); - } - else - l = indexes[l]; - - ++it; - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0" ); - - if ( i != 0 && j != 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0" ); - - ++it; - if ( !v.atof(*it) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0" ); - - (*_x0s[l])[0] = v; - } - - else - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0 - error in vector form with () or []" ); - } - - else { - - ++it; - for ( k = 0 ; k < _dimension ; ++k ) { - if ( !v.atof(*it) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0" ); - ++it; - tmp_x0[k] = v; - } - - if ( *it != "]" && *it != ")" ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: X0 - error in vector form with () or []" ); - - set_X0 ( tmp_x0 ); - } - } - - // indexed values without x0 index (must be unique) - // (example: X0 0-5 1.0): - else if ( pe->get_nb_values() == 2 ) { - - it = pe->get_values().begin(); - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - ++it; - if ( !v.atof(*it) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - - if ( indexes.empty() ) { - l = static_cast ( _x0s.size() ); - indexes.push_back ( l ); - set_X0 ( tmp_x0 ); - } - else - l = indexes[0]; - - for ( k = j ; k >= i ; --k ) - (*_x0s[l])[k] = v; - } - - // indexed values with x0 index - // example: X0 0 0-5 1.0 --> first x0 point - // X0 1 0-5 2.0 --> 2nd x0 point - else { - - if ( pe->get_nb_values() != 3 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - - it = pe->get_values().begin(); - - if ( !NOMAD::atoi ( *it , l ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - - i = static_cast ( indexes.size() ); - if ( l > i ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - else if ( l == i ) { - l = static_cast ( _x0s.size() ); - indexes.push_back ( l ); - set_X0 ( tmp_x0 ); - } - else - l = indexes[l]; - - ++it; - if ( !NOMAD::string_to_index_range ( *it , i , j , &_dimension ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - - ++it; - if ( !v.atof(*it) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: X0" ); - - for ( k = j ; k >= i ; --k ) - (*_x0s[l])[k] = v; - - } - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } -} - -/*----------------------------------------*/ -/* read a parameters file */ -/*----------------------------------------*/ -void NOMAD::Parameters::read ( const std::string & param_file ) -{ - // parameters will have to be checked: - _to_be_checked = true; - - // PROBLEM_DIR: - // ------------ - _problem_dir.clear(); - size_t k = param_file.find_last_of ( NOMAD::DIR_SEP ); - if ( k < param_file.size() ) - _problem_dir = param_file.substr (0,k) + NOMAD::DIR_SEP; - else - _problem_dir = std::string(".") + NOMAD::DIR_SEP; - - // open the parameters file: - std::string err = "could not open parameters file \'" + param_file + "\'"; - std::ifstream fin; - if ( NOMAD::check_read_file ( param_file ) ) { - fin.open ( param_file.c_str() ); - if ( !fin.fail() ) - err.clear(); - } - if ( !err.empty() ) { - fin.close(); - throw NOMAD::Exception ( "Parameters.cpp" , __LINE__ , err ); - } - - // the set of entries: - NOMAD::Parameter_Entries entries; - - // the file is read: fill the set 'entries' of Parameter_Entry: - NOMAD::Parameter_Entry * pe; - std::string s; - - while ( fin.good() && !fin.eof() ) - { - - s.clear(); - - getline ( fin , s ); - - if ( !fin.fail() && !s.empty() ) - { - pe = new NOMAD::Parameter_Entry ( s ); - if ( pe->is_ok() ) - entries.insert ( pe ); // pe will be deleted by ~Parameter_Entries() - else - { - if ( ( pe->get_name() != "" && pe->get_nb_values() == 0 ) || - pe->get_name() == "STATS_FILE" ) - { - err = "invalid parameter: " + pe->get_name(); - delete pe; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - delete pe; - } - } - } - - // the file is closed: - fin.close(); - - // entries display: -#ifdef DEBUG - if ( NOMAD::Slave::is_master() ) - _out << std::endl - << NOMAD::open_block ( "parsing of \'" + param_file + "\'" ) - << entries - << NOMAD::close_block(); -#endif - - read(entries); -} - -/*----------------------------------------*/ -/* read a parameters file */ -/*----------------------------------------*/ -void NOMAD::Parameters::read ( const NOMAD::Parameter_Entries & entries ) -{ - - // interpret and set the entries using SET methods: - std::list::const_iterator it , end; - int i , j , m; - NOMAD::Double d; - NOMAD::Parameter_Entry * pe; - std::string s; - std::string err ; - - /*----------------------------------------------*/ - - // EPSILON: - // -------- - { - pe = entries.find ( "EPSILON" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EPSILON not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EPSILON" ); - set_EPSILON (d); - pe->set_has_been_interpreted(); - } - } - - // UNDEF_STR: - // ---------- - pe = entries.find ( "UNDEF_STR" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: UNDEF_STR not unique" ); - set_UNDEF_STR ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - - // INF_STR: - // -------- - pe = entries.find ( "INF_STR" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INF_STR not unique" ); - set_INF_STR ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - - // ANISOTROPIC_MESH - //------------------- - { - pe = entries.find ( "ANISOTROPIC_MESH" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ANISOTROPIC_MESH not unique" ); - - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ANISOTROPIC_MESH" ); - set_ANISOTROPIC_MESH ( i == 1 ); - pe->set_has_been_interpreted(); - - } - } - - // POLL_UPDATE_BASIS: - // ------------------ - { - pe = entries.find ( "POLL_UPDATE_BASIS" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: POLL_UPDATE_BASIS not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: POLL_UPDATE_BASIS" ); - set_POLL_UPDATE_BASIS (d); - pe->set_has_been_interpreted(); - } - } - - - - // MESH_UPDATE_BASIS: - // ------------------ - { - pe = entries.find ( "MESH_UPDATE_BASIS" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_UPDATE_BASIS not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_UPDATE_BASIS" ); - set_MESH_UPDATE_BASIS (d); - pe->set_has_been_interpreted(); - } - } - - // INITIAL_MESH_INDEX: - // ------------------- - { - pe = entries.find ( "INITIAL_MESH_INDEX" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_INDEX not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_INDEX" ); - pe->set_has_been_interpreted(); - set_INITIAL_MESH_INDEX (i); - } - } - - // MESH_REFINING_EXPONENT: - // ----------------------- - { - pe = entries.find ( "MESH_REFINING_EXPONENT" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_REFINING_EXPONENT not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_REFINING_EXPONENT" ); - pe->set_has_been_interpreted(); - set_MESH_REFINING_EXPONENT (i); - } - } - - // MESH_COARSENING_EXPONENT: - // ------------------------- - { - pe = entries.find ( "MESH_COARSENING_EXPONENT" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_COARSENING_EXPONENT not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_COARSENING_EXPONENT" ); - pe->set_has_been_interpreted(); - set_MESH_COARSENING_EXPONENT (i); - } - } - - // USE_SMESH: - // --------------- - { - pe = entries.find ( "USE_SMESH" ); - if ( pe ) - { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: USE_SMESH not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: USE_SMESH" ); - set_USE_SMESH ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - - // POINT_DISPLAY_LIMIT: - // -------------------- - { - pe = entries.find ( "POINT_DISPLAY_LIMIT" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: POINT_DISPLAY_LIMIT not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: POINT_DISPLAY_LIMIT" ); - set_POINT_DISPLAY_LIMIT (i); - pe->set_has_been_interpreted(); - } - } - - // DIMENSION: - // ---------- - { - pe = entries.find ( "DIMENSION" ); - - if ( !pe ) { - if ( !pe && _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIMENSION not defined" ); - } - else { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIMENSION not unique" ); - - int dim; - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), dim) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIMENSION" ); - - pe->set_has_been_interpreted(); - - set_DIMENSION ( dim ); - } - } - - // SNAP_TO_BOUNDS: - // --------------- - { - pe = entries.find ( "SNAP_TO_BOUNDS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SNAP_TO_BOUNDS not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SNAP_TO_BOUNDS" ); - set_SNAP_TO_BOUNDS ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // MULTI-MADS: - // ----------- - { - // MULTI_OVERALL_BB_EVAL: - pe = entries.find ( "MULTI_OVERALL_BB_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_OVERALL_BB_EVAL not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_OVERALL_BB_EVAL" ); - pe->set_has_been_interpreted(); - set_MULTI_OVERALL_BB_EVAL (i); - } - - // MULTI_NB_MADS_RUNS: - pe = entries.find ( "MULTI_NB_MADS_RUNS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_NB_MADS_RUNS not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_NB_MADS_RUNS" ); - pe->set_has_been_interpreted(); - set_MULTI_NB_MADS_RUNS (i); - } - - // MULTI_USE_DELTA_CRIT: - pe = entries.find ( "MULTI_USE_DELTA_CRIT" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_USE_DELTA_CRIT not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_USE_DELTA_CRIT" ); - pe->set_has_been_interpreted(); - set_MULTI_USE_DELTA_CRIT ( i == 1 ); - } - - // MULTI_F_BOUNDS (f1_min, f2_min, f2_min, f2_max): - pe = entries.find ( "MULTI_F_BOUNDS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_F_BOUNDS not unique" ); - if ( pe->get_nb_values() != 4 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_F_BOUNDS" ); - NOMAD::Point mfb ( 4 ); - it = pe->get_values().begin(); - for ( i = 0 ; i < 4 ; ++i ) { - if ( !d.atof ( *it ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_F_BOUNDS" ); - mfb[i] = d; - ++it; - } - pe->set_has_been_interpreted(); - set_MULTI_F_BOUNDS ( mfb ); - } - - // MULTI_FORMULATION: - // ------------------ - { - pe = entries.find ( "MULTI_FORMULATION" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_FORMULATION not unique" ); - NOMAD::multi_formulation_type mft; - if ( pe->get_nb_values() != 1 || - !NOMAD::string_to_multi_formulation_type - ( *(pe->get_values().begin()) , mft ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Invalid parameter: MULTI_FORMULATION_TYPE" ); - pe->set_has_been_interpreted(); - set_MULTI_FORMULATION ( mft ); - } - } - } - - // Models - // -------------- - { - - - // Disable models when explicitely requested - pe = entries.find ( "DISABLE" ); - while ( pe ) - { - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISABLE" ); - - std::string smt = *(pe->get_values().begin()); - NOMAD::toupper(smt); - if ( smt == "MODELS" ) - set_DISABLE_MODELS(); - else if ( smt == "EVAL_SORT" ) - set_DISABLE_EVAL_SORT(); - else - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Invalid parameter: DISABLE MODELS. Only MODELS argument is accepted!" ); - - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } - - - - // MODEL_SEARCH (can be entered one time or twice): - int i_model_search = 1; - bool b_model_search = false; - pe = entries.find ( "MODEL_SEARCH" ); - - while ( pe ) { - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH" ); - if ( i_model_search == 3 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH (cannot be entered more than twice" ); - - NOMAD::model_type mt; - std::string smt = *(pe->get_values().begin()); - int imt = NOMAD::string_to_bool ( smt ); - - // entered as a boolean: - if ( imt == 0 || imt == 1 ) { - if ( b_model_search || i_model_search == 2 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH (boolean argument can only be used once)" ); - b_model_search = true; - set_MODEL_SEARCH ( imt == 1 ); - } - - // entered as a model type: - else { - - if ( !NOMAD::string_to_model_type ( smt , mt ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH" ); - - set_MODEL_SEARCH ( i_model_search , mt ); - } - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - ++i_model_search; - } - - // MODEL_SEARCH_OPTIMISTIC: - { - pe = entries.find ( "MODEL_SEARCH_OPTIMISTIC" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_OPTIMISTIC not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_OPTIMISTIC" ); - set_MODEL_SEARCH_OPTIMISTIC ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // MODEL_SEARCH_PROJ_TO_MESH: - { - pe = entries.find ( "MODEL_SEARCH_PROJ_TO_MESH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_PROJ_TO_MESH not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_PROJ_TO_MESH" ); - set_MODEL_SEARCH_PROJ_TO_MESH ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // MODEL_QUAD_RADIUS_FACTOR: - { - pe = entries.find ( "MODEL_QUAD_RADIUS_FACTOR" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_RADIUS_FACTOR not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_RADIUS_FACTOR" ); - pe->set_has_been_interpreted(); - set_MODEL_QUAD_RADIUS_FACTOR ( d ); - } - } - - // MODEL_QUAD_USE_WP: - { - pe = entries.find ( "MODEL_QUAD_USE_WP" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_USE_WP not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_USE_WP" ); - set_MODEL_QUAD_USE_WP ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // MODEL_QUAD_MAX_Y_SIZE: - { - pe = entries.find ( "MODEL_QUAD_MAX_Y_SIZE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_MAX_Y_SIZE not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_MAX_Y_SIZE" ); - pe->set_has_been_interpreted(); - set_MODEL_QUAD_MAX_Y_SIZE (i); - } - } - - // MODEL_QUAD_MIN_Y_SIZE: - { - pe = entries.find ( "MODEL_QUAD_MIN_Y_SIZE" ); - if ( pe ) { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_MIN_Y_SIZE not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_MIN_Y_SIZE" ); - - s = *(pe->get_values().begin()); - NOMAD::toupper(s); - - if ( s == "N+1" ) - i = -1; - else if ( !NOMAD::atoi ( s , i ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_MIN_Y_SIZE" ); - - pe->set_has_been_interpreted(); - set_MODEL_QUAD_MIN_Y_SIZE (i); - } - } - - - // MODEL_QUAD_HYPERCUBE_LOWER_LIM: - { - pe = entries.find ( "MODEL_NP1_QUAD_EPSILON" ); - if ( pe ) { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_NP1_QUAD_EPSILON not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_NP1_QUAD_EPSILON" ); - - s = *(pe->get_values().begin()); - NOMAD::toupper(s); - NOMAD::Double d; - if ( !d.atof ( s) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_NP1_QUAD_EPSILON" ); - - pe->set_has_been_interpreted(); - set_MODEL_NP1_QUAD_EPSILON (d); - } - } - - // MODEL_TGP_MODE: - { - pe = entries.find ( "MODEL_TGP_MODE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_TGP_MODE not unique" ); - - NOMAD::TGP_mode_type m; - if ( pe->get_nb_values() != 1 || - !NOMAD::string_to_TGP_mode_type ( *(pe->get_values().begin()) , m ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Invalid parameter: MODEL_TGP_MODE" ); - pe->set_has_been_interpreted(); - set_MODEL_TGP_MODE ( m ); - } - } - - // MODEL_TGP_REUSE_MODEL: - { - pe = entries.find ( "MODEL_TGP_REUSE_MODEL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_TGP_REUSE_MODEL not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_TGP_REUSE_MODEL" ); - set_MODEL_TGP_REUSE_MODEL ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // MODEL_SEARCH_MAX_TRIAL_PTS: - { - pe = entries.find ( "MODEL_SEARCH_MAX_TRIAL_PTS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_MAX_TRIAL_PTS not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_MAX_TRIAL_PTS" ); - pe->set_has_been_interpreted(); - set_MODEL_SEARCH_MAX_TRIAL_PTS (i); - } - } - - // MODEL_EVAL_SORT: - { - pe = entries.find ( "MODEL_EVAL_SORT" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_EVAL_SORT not unique" ); - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_EVAL_SORT" ); - - NOMAD::model_type mt; - std::string smt = *(pe->get_values().begin()); - int imt = NOMAD::string_to_bool ( smt ); - - // entered as a boolean: - if ( imt == 0 || imt == 1 ) - set_MODEL_EVAL_SORT ( imt == 1 ); - - // entered as a model type: - else { - - if ( !NOMAD::string_to_model_type ( smt , mt ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_EVAL_SORT" ); - set_MODEL_EVAL_SORT ( mt ); - } - - pe->set_has_been_interpreted(); - } - } - - // MODEL_EVAL_SORT_CAUTIOUS: - { - pe = entries.find ( "MODEL_EVAL_SORT_CAUTIOUS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_EVAL_SORT_CAUTIOUS not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_EVAL_SORT_CAUTIOUS" ); - set_MODEL_EVAL_SORT_CAUTIOUS ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - } - - // SPECULATIVE_SEARCH: - // ------------------- - { - pe = entries.find ( "SPECULATIVE_SEARCH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SPECULATIVE_SEARCH not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SPECULATIVE_SEARCH" ); - set_SPECULATIVE_SEARCH ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // VNS_SEARCH: - // ----------- - { - pe = entries.find ( "VNS_SEARCH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VNS_SEARCH not unique" ); - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VNS_SEARCH" ); - - s = *(pe->get_values().begin()); - i = NOMAD::string_to_bool ( s ); - - // entered as a real: - if ( i == -1 || s == "1" ) { - if ( !d.atof ( s ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VNS_SEARCH" ); - set_VNS_SEARCH ( d ); - } - // entered as a boolean: - else - set_VNS_SEARCH ( i == 1 ); - - pe->set_has_been_interpreted(); - } - } - - // CACHE_SEARCH: - // ------------- - { - pe = entries.find ( "CACHE_SEARCH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_SEARCH not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_SEARCH" ); - set_CACHE_SEARCH ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // LH_SEARCH: - // ---------- - { - pe = entries.find ( "LH_SEARCH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LH_SEARCH not unique" ); - if ( pe->get_nb_values() != 2 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LH_SEARCH" ); - it = pe->get_values().begin(); - - if ( !NOMAD::atoi (*it++ , i) || i < 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LH_SEARCH" ); - - if ( !NOMAD::atoi (*it , j) || j < 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LH_SEARCH" ); - - set_LH_SEARCH ( i , j ); - pe->set_has_been_interpreted(); - } - - // OPPORTUNISTIC_LH: - // ----------------- - { - pe = entries.find ( "OPPORTUNISTIC_LH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_LH not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_LH" ); - set_OPPORTUNISTIC_LH ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - } - - // OPPORTUNISTIC_CACHE_SEARCH: - // --------------------------- - { - pe = entries.find ( "OPPORTUNISTIC_CACHE_SEARCH" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_CACHE_SEARCH not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_CACHE_SEARCH" ); - set_OPPORTUNISTIC_CACHE_SEARCH ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // opportunistic strategy: - // ----------------------- - { - - // BB_MAX_BLOCK_SIZE - pe = entries.find ( "BB_MAX_BLOCK_SIZE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_MAX_BLOCK_SIZE not unique" ); - - it = pe->get_values().begin(); - - if ( !NOMAD::atoi (*it++ , i) || i <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_MAX_BLOCK_SIZE" ); - set_BB_MAX_BLOCK_SIZE (i); - - pe->set_has_been_interpreted(); - } - - - // OPPORTUNISTIC_EVAL: - pe = entries.find ( "OPPORTUNISTIC_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_EVAL not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_EVAL" ); - set_OPPORTUNISTIC_EVAL ( i == 1 ); - pe->set_has_been_interpreted(); - } - - // OPPORTUNISTIC_MIN_NB_SUCCESS: - pe = entries.find ( "OPPORTUNISTIC_MIN_NB_SUCCESS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_MIN_NB_SUCCESS not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_MIN_NB_SUCCESS" ); - pe->set_has_been_interpreted(); - set_OPPORTUNISTIC_MIN_NB_SUCCESS (i); - } - - // OPPORTUNISTIC_MIN_EVAL: - pe = entries.find ( "OPPORTUNISTIC_MIN_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_MIN_EVAL not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_MIN_EVAL" ); - pe->set_has_been_interpreted(); - set_OPPORTUNISTIC_MIN_EVAL (i); - } - - // OPPORTUNISTIC_MIN_F_IMPRVMT: - pe = entries.find ( "OPPORTUNISTIC_MIN_F_IMPRVMT" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_MIN_F_IMPRVMT not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_MIN_F_IMPRVMT" ); - pe->set_has_been_interpreted(); - set_OPPORTUNISTIC_MIN_F_IMPRVMT ( d ); - } - - // OPPORTUNISTIC_LUCKY_EVAL: - pe = entries.find ( "OPPORTUNISTIC_LUCKY_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_LUCKY_EVAL not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPPORTUNISTIC_LUCKY_EVAL" ); - set_OPPORTUNISTIC_LUCKY_EVAL ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // Directions (DIRECTION_TYPE and SEC_POLL_DIR_TYPE): - // -------------------------------------------------- - { - NOMAD::direction_type dt; - - - pe = entries.find ( "DIRECTION_TYPE" ); - while ( pe ) { - - if ( !NOMAD::strings_to_direction_type ( pe->get_values() , dt ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIRECTION_TYPE" ); - set_DIRECTION_TYPE ( dt ); - - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } - - pe = entries.find ( "SEC_POLL_DIR_TYPE" ); - while ( pe ) { - if ( !NOMAD::strings_to_direction_type ( pe->get_values() , dt ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SEC_POLL_DIR_TYPE" ); - set_SEC_POLL_DIR_TYPE ( dt ); - - pe->set_has_been_interpreted(); - pe = pe->get_next(); - } - } - - - // MAX_ITERATIONS: - // --------------- - { - pe = entries.find ( "MAX_ITERATIONS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_ITERATIONS not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_ITERATIONS" ); - pe->set_has_been_interpreted(); - set_MAX_ITERATIONS (i); - } - } - - // MAX_CONSECUTIVE_FAILED_ITERATIONS: - // ---------------------------------- - { - pe = entries.find ( "MAX_CONSECUTIVE_FAILED_ITERATIONS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_CONSECUTIVE_FAILED_ITERATIONS not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_CONSECUTIVE_FAILED_ITERATIONS" ); - pe->set_has_been_interpreted(); - set_MAX_CONSECUTIVE_FAILED_ITERATIONS (static_cast(d.value())); - } - } - - // MAX_CACHE_MEMORY: - // ----------------- - { - pe = entries.find ( "MAX_CACHE_MEMORY" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_CACHE_MEMORY not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_CACHE_MEMORY" ); - pe->set_has_been_interpreted(); - set_MAX_CACHE_MEMORY (static_cast(d.value())); - } - } - - // MAX_EVAL: - // --------- - { - pe = entries.find ( "MAX_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_EVAL not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_EVAL" ); - pe->set_has_been_interpreted(); - set_MAX_EVAL (i); - } - } - - // MAX_BB_EVAL: - // ------------ - { - pe = entries.find ( "MAX_BB_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_BB_EVAL not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_BB_EVAL" ); - pe->set_has_been_interpreted(); - set_MAX_BB_EVAL (i); - } - } - - // MAX_SIM_BB_EVAL: - // ---------------- - { - pe = entries.find ( "MAX_SIM_BB_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_SIM_BB_EVAL not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_SIM_BB_EVAL" ); - pe->set_has_been_interpreted(); - set_MAX_SIM_BB_EVAL (i); - } - } - - // MAX_SGTE_EVAL: - // -------------- - { - pe = entries.find ( "MAX_SGTE_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_SGTE_EVAL not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_SGTE_EVAL" ); - pe->set_has_been_interpreted(); - set_MAX_SGTE_EVAL (i); - } - } - - // MAX_TIME: - // --------- - { - pe = entries.find ( "MAX_TIME" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_TIME not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()), i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MAX_TIME" ); - - pe->set_has_been_interpreted(); - set_MAX_TIME (i); - } - } - - // STAT_SUM_TARGET: - // ---------------- - { - pe = entries.find ( "STAT_SUM_TARGET" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STAT_SUM_TARGET not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STAT_SUM_TARGET" ); - pe->set_has_been_interpreted(); - set_STAT_SUM_TARGET ( d ); - } - } - - // L_CURVE_TARGET: - // --------------- - { - pe = entries.find ( "L_CURVE_TARGET" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: L_CURVE_TARGET not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: L_CURVE_TARGET" ); - pe->set_has_been_interpreted(); - set_L_CURVE_TARGET ( d ); - } - } - - // EXTENDED_POLL_TRIGGER: - // ---------------------- - { - pe = entries.find ( "EXTENDED_POLL_TRIGGER" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EXTENDED_POLL_TRIGGER not unique" ); - - bool rel; - - if ( pe->get_nb_values() != 1 || - !d.relative_atof ( *(pe->get_values().begin()) , rel ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EXTENDED_POLL_TRIGGER" ); - - pe->set_has_been_interpreted(); - set_EXTENDED_POLL_TRIGGER ( d , rel ); - } - } - - // EXTENDED_POLL_ENABLED: - // ---------------------- - { - pe = entries.find ( "EXTENDED_POLL_ENABLED" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EXTENDED_POLL_ENABLED not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EXTENDED_POLL_ENABLED" ); - set_EXTENDED_POLL_ENABLED ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // USER_CALLS_ENABLED: - // ------------------- - { - pe = entries.find ( "USER_CALLS_ENABLED" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: USER_CALLS_ENABLED not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: USER_CALLS_ENABLED" ); - set_USER_CALLS_ENABLED ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // ASYNCHRONOUS: - // ------------- - { - pe = entries.find ( "ASYNCHRONOUS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ASYNCHRONOUS not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ASYNCHRONOUS" ); - set_ASYNCHRONOUS ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // RHO: - // ---- - { - pe = entries.find ( "RHO" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: RHO not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: RHO" ); - pe->set_has_been_interpreted(); - set_RHO(d); - } - } - - // H_MIN: - // ------ - { - pe = entries.find ( "H_MIN" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: H_MIN not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: H_MIN" ); - pe->set_has_been_interpreted(); - set_H_MIN(d); - } - } - - // H_MAX_0: - // -------- - { - pe = entries.find ( "H_MAX_0" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: H_MAX_0 not unique" ); - if ( pe->get_nb_values() != 1 || !d.atof ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Invalid parameter: H_MAX_0" ); - pe->set_has_been_interpreted(); - set_H_MAX_0(d); - } - } - - // H_NORM: - // ------- - { - pe = entries.find ( "H_NORM" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: H_NORM not unique" ); - NOMAD::hnorm_type hn = NOMAD::L2; - if ( pe->get_nb_values() != 1 || - !NOMAD::string_to_hnorm_type ( *(pe->get_values().begin()) , hn ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Invalid parameter: H_NORM" ); - pe->set_has_been_interpreted(); - set_H_NORM ( hn ); - } - } - - // TMP_DIR: - // -------- - { - _tmp_dir.clear(); - pe = entries.find ( "TMP_DIR" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: TMP_DIR not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: TMP_DIR" ); - - set_TMP_DIR ( *(pe->get_values().begin()) ); - - pe->set_has_been_interpreted(); - } - } - - // ADD_SEED_TO_FILE_NAMES: - // ----------------------- - { - pe = entries.find ( "ADD_SEED_TO_FILE_NAMES" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ADD_SEED_TO_FILE_NAMES not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ADD_SEED_TO_FILE_NAMES" ); - - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: ADD_SEED_TO_FILE_NAMES" ); - set_ADD_SEED_TO_FILE_NAMES ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // SOLUTION_FILE: - // -------------- - { - _solution_file.clear(); - pe = entries.find ( "SOLUTION_FILE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SOLUTION_FILE not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SOLUTION_FILE" ); - set_SOLUTION_FILE ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - } - - // HISTORY_FILE: - // ------------- - { - _history_file.clear(); - pe = entries.find ( "HISTORY_FILE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: HISTORY_FILE not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: HISTORY_FILE" ); - set_HISTORY_FILE ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - } - - // STATS_FILE: - // ----------- - { - pe = entries.find ( "STATS_FILE" ); - if ( pe ) { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STATS_FILE not unique" ); - - end = pe->get_values().end(); - it = pe->get_values().begin(); - std::string file_name = *it; - ++it; - - std::list ls; - if (it!=end) - { - while ( it != end ) { - ls.push_back(*it); - ++it; - } - ls.resize(ls.size()-1); - } - - set_STATS_FILE ( file_name , ls ); - pe->set_has_been_interpreted(); - } - } - - // CACHE FILE: - // ----------- - { - _cache_file.clear(); - pe = entries.find ( "CACHE_FILE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_FILE not unique" ); - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_FILE" ); - set_CACHE_FILE ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - } - - // SGTE_CACHE FILE: - // ---------------- - { - _sgte_cache_file.clear(); - pe = entries.find ( "SGTE_CACHE_FILE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_CACHE_FILE not unique" ); - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_CACHE_FILE" ); - set_SGTE_CACHE_FILE ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - } - - - // CACHE_SAVE_PERIOD: - // ------------------ - { - pe = entries.find ( "CACHE_SAVE_PERIOD" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_SAVE_PERIOD not unique" ); - if ( pe->get_nb_values() != 1 || !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_SAVE_PERIOD" ); - set_CACHE_SAVE_PERIOD (i); - pe->set_has_been_interpreted(); - } - } - - // SGTE_COST: - // ---------- - { - pe = entries.find ( "SGTE_COST" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_COST not unique" ); - if ( pe->get_nb_values() != 1 || - !NOMAD::atoi (*(pe->get_values().begin()) , i) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_COST" ); - set_SGTE_COST (i); - pe->set_has_been_interpreted(); - } - } - - // X0: - // --- - interpret_x0 ( entries ); - - // FIXED_VARIABLE: - // --------------- - interpret_BFVS ( entries , "FIXED_VARIABLE"); - - // LOWER_BOUND: - // ------------ - interpret_BFVS ( entries , "LOWER_BOUND"); - - // UPPER_BOUND: - // ------------ - interpret_BFVS ( entries , "UPPER_BOUND"); - - // SCALING: - // -------- - interpret_BFVS ( entries , "SCALING" ); - - // BB_INPUT_TYPE: - // -------------- - interpret_bb_input_type ( entries ); - - // F_TARGET: - // --------- - interpret_f_target ( entries ); - - // STOP_IF_FEASIBLE: - // ----------------- - pe = entries.find ( "STOP_IF_FEASIBLE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STOP_IF_FEASIBLE not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STOP_IF_FEASIBLE" ); - pe->set_has_been_interpreted(); - set_STOP_IF_FEASIBLE ( i == 1 ); - } - - // BB_INPUT_INCLUDE_TAG: - // --------------------- - { - pe = entries.find ( "BB_INPUT_INCLUDE_TAG" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_INCLUDE_TAG not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_INCLUDE_TAG" ); - set_BB_INPUT_INCLUDE_TAG ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // BB_INPUT_INCLUDE_SEED: - // ---------------------- - { - pe = entries.find ( "BB_INPUT_INCLUDE_SEED" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_INCLUDE_SEED not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_INCLUDE_SEED" ); - set_BB_INPUT_INCLUDE_SEED ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - // BB_REDIRECTION: - // --------------- - { - pe = entries.find ( "BB_REDIRECTION" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_REDIRECTION not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_REDIRECTION" ); - set_BB_REDIRECTION ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // INITIAL_POLL_SIZE, INITIAL_MESH_SIZE, MIN_MESH_SIZE, and MIN_POLL_SIZE: - // ---------------------------------------------------- - interpret_mesh_sizes ( entries , "INITIAL_MESH_SIZE" ); - interpret_mesh_sizes ( entries , "INITIAL_POLL_SIZE" ); - interpret_mesh_sizes ( entries , "MIN_MESH_SIZE" ); - interpret_mesh_sizes ( entries , "MIN_POLL_SIZE" ); - - // BB_OUTPUT_TYPE: - // --------------- - { - pe = entries.find ( "BB_OUTPUT_TYPE" ); - - if ( !pe ) { - if ( _bb_output_type.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE not defined" ); - } - else { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE not unique" ); - - m = pe->get_nb_values(); - - if ( m <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE" ); - - NOMAD::bb_output_type cur; - std::list bbot; - i = 0; - end = pe->get_values().end(); - for ( it = pe->get_values().begin() ; it != end ; ++it ) { - if ( !NOMAD::string_to_bb_output_type ( *it , cur ) ) { - err = "invalid parameter: BB_OUTPUT_TYPE (" + pe->get_name(); - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - bbot.push_back (cur); - } - - set_BB_OUTPUT_TYPE ( bbot ); - - pe->set_has_been_interpreted(); - } - } - - // NEIGHBORS_EXE: - // -------------- - { - _neighbors_exe.clear(); - pe = entries.find ( "NEIGHBORS_EXE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: NEIGHBORS_EXE not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: NEIGHBORS_EXE" ); - set_NEIGHBORS_EXE ( *(pe->get_values().begin()) ); - pe->set_has_been_interpreted(); - } - } - - // BB_EXE: - // ------- - { - pe = entries.find ( "BB_EXE" ); - if ( pe ) { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE not unique" ); - - m = pe->get_nb_values(); - - if ( m == 1 ) - set_BB_EXE ( *pe->get_values().begin() ); - - else { - - if ( m != static_cast(_bb_output_type.size()) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: number of BB_EXE (>1) and corresponding BB_OUTPUT_TYPE must be the same." ); - - std::list bbexe; - end = pe->get_values().end(); - for ( it = pe->get_values().begin() ; it != end ; ++it ) - bbexe.push_back (*it); - - set_BB_EXE ( bbexe ); - } - - pe->set_has_been_interpreted(); - } - } - - // SGTE_EXE: - // --------- - { - pe = entries.find ( "SGTE_EXE" ); - if ( pe ) { - - std::string bb_exe_name , sgte_name; - - if ( pe->get_nb_values() == 1 ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EXE (with one arguement) not unique" ); - sgte_name = *pe->get_values().begin(); - } - - else if ( pe->get_nb_values() == 2 ) { - bb_exe_name = *pe->get_values().begin(); - sgte_name = *(++pe->get_values().begin()); - } - - else - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EXE" ); - - set_SGTE_EXE ( bb_exe_name , sgte_name ); - pe->set_has_been_interpreted(); - } - } - - // SGTE_EVAL_SORT: - // --------------- - { - pe = entries.find ( "SGTE_EVAL_SORT" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EVAL_SORT not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EVAL_SORT" ); - set_SGTE_EVAL_SORT ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // HAS_SGTE: - // --------- - { - pe = entries.find ( "HAS_SGTE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: HAS_SGTE not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: HAS_SGTE" ); - set_HAS_SGTE ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // OPT_ONLY_SGTE: - // -------------- - { - pe = entries.find ( "OPT_ONLY_SGTE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPT_ONLY_SGTE not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPT_ONLY_SGTE" ); - set_OPT_ONLY_SGTE ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // DISPLAY_DEGREE: - // --------------- - { - pe = entries.find ( "DISPLAY_DEGREE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISPLAY_DEGREE not unique" ); - if ( pe->get_nb_values() != 1 || - !set_DISPLAY_DEGREE ( *(pe->get_values().begin()) ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISPLAY_DEGREE" ); - pe->set_has_been_interpreted(); - } - } - - // OPEN_BRACE: - // ----------- - { - pe = entries.find ( "OPEN_BRACE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPEN_BRACE not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPEN_BRACE" ); - - set_OPEN_BRACE ( *(pe->get_values().begin()) ); - - pe->set_has_been_interpreted(); - } - } - - // CLOSED_BRACE: - // ------------- - { - pe = entries.find ( "CLOSED_BRACE" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CLOSED_BRACE not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CLOSED_BRACE" ); - - set_CLOSED_BRACE ( *(pe->get_values().begin()) ); - - pe->set_has_been_interpreted(); - } - } - - // DISPLAY_STATS: - { - pe = entries.find ( "DISPLAY_STATS" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISPLAY_STATS not unique" ); - std::list ls; - end = pe->get_values().end(); - for ( it = pe->get_values().begin() ; it != end ; ++it ) - ls.push_back ( *it ); - ls.resize ( ls.size()-1 ); - set_DISPLAY_STATS ( ls ); - pe->set_has_been_interpreted(); - } - } - - // DISPLAY_ALL_EVAL: - // ----------------- - { - pe = entries.find ( "DISPLAY_ALL_EVAL" ); - if ( pe ) { - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISPLAY_ALL_EVAL not unique" ); - i = NOMAD::string_to_bool ( *(pe->get_values().begin() ) ); - if ( pe->get_nb_values() != 1 || i == -1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISPLAY_ALL_EVAL" ); - set_DISPLAY_ALL_EVAL ( i == 1 ); - pe->set_has_been_interpreted(); - } - } - - // SEED: - // ----- - { - pe = entries.find ( "SEED" ); - - if ( pe ) - { - - if ( !pe->is_unique() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SEED not unique" ); - - if ( pe->get_nb_values() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SEED" ); - - s = *(pe->get_values().begin()); - NOMAD::toupper(s); - - - if ( s == "DIFF" ) - i = -1; - else if ( !NOMAD::atoi ( s , i ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SEED" ); - set_SEED(i); - pe->set_has_been_interpreted(); - - - } - } - - // VARIABLE_GROUP: - // --------------- - interpret_var_groups ( entries ); - - // PERIODIC_VARIABLE: - // ------------------ - interpret_periodic_var ( entries ); - - /*----------------------------------------------*/ - - // check the non-interpreted parameters: - pe = entries.find_non_interpreted(); - if ( pe ) { - err = "invalid parameter: " + pe->get_name() + " - unknown"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - // user must check the parameters with Parameters::check() -} - -/*---------------------------------------*/ -/* display */ -/*---------------------------------------*/ -void NOMAD::Parameters::display ( const NOMAD::Display & out ) const -{ - std::list::const_iterator it; - - if ( _to_be_checked ) { - out << "parameters not checked" << std::endl; - return; - } - - // problem directory: - if ( !_problem_dir.empty() ) { - out << "problem directory : " << _problem_dir << std::endl; - if ( _tmp_dir != _problem_dir ) - out << "tmp directory : " << _tmp_dir << std::endl; - } - - // dimension: - out << "dimension : n=" << _dimension << std::endl; - - // bounds: - if ( _lb.is_defined() ) { - out << "lower bounds : ( "; - _lb.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - if ( _ub.is_defined() ) { - out << "upper bounds : ( "; - _ub.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // scaling: - if ( _scaling.is_defined() ) { - out << "scaling : ( "; - _scaling.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // fixed variables: - if ( _fixed_variables.is_defined() ) { - out << "fixed variables : ( "; - _fixed_variables.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // back-box input types: - if ( _bb_input_include_tag ) - out << "blackbox input files : include tag" << std::endl; - if ( _bb_input_include_seed ) - out << "blackbox input files : include seed" << std::endl; - - out << "blackbox input types : "; - if ( get_signature()->all_continuous() ) - out << "all variables are continuous (R)" << std::endl; - else - out << "( " << _bb_input_type << " )" << std::endl; - - // extended poll trigger: - if ( get_signature()->has_categorical() ) { - if ( _extended_poll_enabled ) { - out << "extended poll trigger: " << _extended_poll_trigger; - if ( _relative_ept ) - out << " (relative)"; - if ( !_neighbors_exe.empty() ) - out << std::endl << "neighbors executable : " << _neighbors_exe; - } - else - out << "extended poll is disabled"; - out << std::endl; - } - - // periodic variables: - if ( !_periodic_variables.empty() ) { - out << "periodic variables : { "; - for ( size_t k = 0 ; k < _periodic_variables.size() ; ++k ) - if ( _periodic_variables[k] ) - out << k << " "; - out << "}" << std::endl; - } - - // variable groups: - if ( _var_groups.size() > 1 ) { - int i = 0; - out.open_block ( "variable groups" ); - std::set::const_iterator - it2 , end2 = _var_groups.end(); - for ( it2 = _var_groups.begin() ; it2 != end2 ; ++it2 ) - out << NOMAD::open_block ( "group #" + NOMAD::itos ( i++ ) ) - << **it2 << NOMAD::close_block(); - out.close_block(); - } - - // blackbox outputs: - { - bool display_bb_exe = !_bb_exe.empty(); - bool display_sgte_exe = !_sgte_exe.empty(); - int m = static_cast(_bb_output_type.size()); - int w = 1+int(log(static_cast(m))/NOMAD::LOG10); - it = _bb_exe.begin(); - - out.open_block ( "blackbox outputs (m=" + NOMAD::itos ( m ) + ")" ); - for ( int i = 0 ; i < m ; ++i ) { - out << "#" << std::setw(w) << i << " " << std::setw(12) << _bb_output_type[i]; - if ( display_bb_exe ) { - out << "\t" << *it; - if ( display_sgte_exe ) - out << "\t" << get_sgte_exe(*it); - ++it; - } - out << std::endl; - } - out.close_block(); - } - - // signature (standard or extern): - out << "signature : " - << ( (_std_signature) ? "standard" : "extern" ) << std::endl; - - // BB_REDIRECTION: - if ( !_bb_redirection ) { - out << "blackbox output redirection : "; - out.display_yes_or_no ( _bb_redirection ); - out << std::endl; - } - - // surrogate: - { - out << "has surrogate : "; - out.display_yes_or_no ( _has_sgte ); - out << std::endl; - if ( _has_sgte ) { - - // OPT_ONLY_SGTE: - if ( _opt_only_sgte ) { - out << "minimize only with surrogate : "; - out.display_yes_or_no ( _opt_only_sgte ); - out << std::endl; - } - - // SGTE_EVAL_SORT: - out << "sort trial points with surrogate: "; - out.display_yes_or_no ( _sgte_eval_sort ); - out << std::endl; - - // SGTE_COST: - out << "surrogate cost : "; - if ( _sgte_cost > 0 ) - out << _sgte_cost - << " surrogate evaluations count as one bb evaluation" << std::endl; - else - out << "none" << std::endl; - } - } - - // MULTI-MADS: - if ( get_nb_obj() > 1 ) { - out << "multi-MADS : [overall bb eval="; - if ( _multi_overall_bb_eval >= 0 ) - out << _multi_overall_bb_eval; - else - out << "-"; - out << "] [nb MADS runs="; - if ( _multi_nb_mads_runs >= 0 ) - out << _multi_nb_mads_runs; - else - out << "-"; - out << "] [use delta crit="; - out.display_yes_or_no ( _multi_use_delta_crit ); - out << "]" << std::endl - << " [formulation=" - << _multi_formulation << "]"; - if ( _multi_f_bounds.is_defined() ) { - out << " [f_bounds="; - _multi_f_bounds.display ( out , "," , -1 , -1 ); - out << "]"; - } - out << std::endl; - } - - // barrier: - if ( _has_constraints ) { - - out << "barrier type : "; - switch ( _barrier_type ) { - case NOMAD::EB: - out << "extreme" << std::endl; - break; - case NOMAD::PEB_P: - case NOMAD::PB: - out << "progressive" << std::endl; - out << "prog. barrier trigger : " << _rho << std::endl; - break; - default: - out << "filter" << std::endl; - } - out << "barrier h_min : " << _h_min << std::endl - << "barrier initial h_max : " << _h_max_0 << std::endl; - } - if ( _has_filter_constraints ) - out << "barrier h_norm : " << _h_norm << std::endl; - - // ADD_SEED_TO_FILE_NAMES: - out << "add seed to output file names : "; - out.display_yes_or_no ( _add_seed_to_file_names ); - out << std::endl; - - // SOLUTION_FILE: - out << "solution file : "; - if ( !_solution_file.empty() ) - out << _solution_file << std::endl; - else - out << "none" << std::endl; - - // HISTORY_FILE: - out << "history file : "; - if ( !_history_file.empty() ) - out << _history_file << std::endl; - else - out << "none" << std::endl; - - // STATS_FILE: - out << "stats file : "; - if ( !_stats_file_name.empty() ) { - out << "(" << _stats_file_name << ") "; - std::list::const_iterator end = _stats_file.end(); - for ( it = _stats_file.begin() ; it != end ; ++it ) { - if ( it->empty() ) - out << " "; - else - out << *it; - } - out << std::endl; - } - else - out << "none" << std::endl; - - // CACHE_FILE: - out << "cache file : "; - if ( !_cache_file.empty() ) { - out << _cache_file << std::endl; - out << "cache save period : "; - if ( _cache_save_period <= 0 ) - out << "never"; - else if ( _cache_save_period == 1 ) - out << "every iteration"; - else - out << "every " << _cache_save_period << " iterations"; - out << std::endl; - } - else - out << "none" << std::endl; - - // surrogate cache file: - if ( !_sgte_cache_file.empty() ) - out << "surrogate cache file : " - << _sgte_cache_file << std::endl; - - // X0: - if ( _x0s.empty() && _x0_cache_file.empty() ) - out << "x0 : points in \'" - << _cache_file << "\'" << std::endl; - else { - bool first = true; - if ( !_x0_cache_file.empty() ) { - if ( first ) { - out << "x0 : "; - first = false; - } - else - out << " : "; - out << _x0_cache_file; - if ( _x0_cache_file != _cache_file ) - out << " (read only)"; - out << std::endl; - } - if ( !_x0s.empty() ) { - size_t x0n = _x0s.size(); - for ( size_t k = 0 ; k < x0n ; ++k ) { - if ( first ) { - out << "x0 : "; - first = false; - } - else - out << " : "; - out << "( "; - _x0s[k]->display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - } - } - - // directions: - { - std::set::const_iterator it , end = _direction_types.end(); - if ( _direction_types.size() == 1 ) - out << "directions : " - << *_direction_types.begin() << std::endl; - else { - out << NOMAD::open_block ( "directions" ); - for ( it = _direction_types.begin() ; it != end ; ++it ) - out << *it << std::endl; - out.close_block(); - } - if ( _barrier_type == NOMAD::PB || _barrier_type == NOMAD::PEB_P ) { - if ( _sec_poll_dir_types.empty() ) - out << "sec. poll dir. type: no secondary poll" << std::endl; - else { - if ( _sec_poll_dir_types.size() == 1 ) - out << "sec. poll dir. type: " - << *_sec_poll_dir_types.begin() << std::endl; - else { - end = _sec_poll_dir_types.end(); - out << NOMAD::open_block ( "sec. poll dir. types" ); - for ( it = _sec_poll_dir_types.begin() ; it != end ; ++it ) - out << *it << std::endl; - out.close_block(); - } - } - } - - } - - // mesh: - { - if ( get_use_smesh() ) - { - out << NOMAD::open_block ( "smesh (isotropic)" ); - out << "mesh update basis : " << std::setw(3) << _mesh_update_basis << std::endl; - } - else - { - if ( get_anisotropic_mesh() ) - out << NOMAD::open_block ( "xmesh (anisotropic)" ); - else - out << NOMAD::open_block ( "xmesh (isotropic)" ); - out << "poll update basis : " << std::setw(3) << _poll_update_basis << std::endl; - } - out << "coarsening exponent : " << std::setw(3) << _mesh_coarsening_exponent - << std::endl - << "refining exponent : " << std::setw(3) << _mesh_refining_exponent - << std::endl - << "initial mesh index : " << std::setw(3) << _initial_mesh_index << std::endl; - out << "initial mesh size : ( "; - _initial_mesh_size.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - out << "initial poll size : ( "; - _initial_poll_size.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - if ( _min_mesh_size.is_defined() ) { - out << "min mesh size : ( "; - _min_mesh_size.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - if ( _min_poll_size.is_defined() ) { - out << "min poll size : ( "; - _min_poll_size.display ( out , " " , 4 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - out.close_block(); - } - - // ASYNCHRONOUS: -#ifdef USE_MPI - out << "asynchronous : "; - out.display_yes_or_no ( _asynchronous ); - out << std::endl; -#endif - - // USER_CALLS_ENABLED: - if ( !_user_calls_enabled ) - out << "user calls : disabled" << std::endl; - - // SNAP_TO_BOUNDS: - out << "snap to bounds : "; - out.display_yes_or_no ( _snap_to_bounds ); - out << std::endl; - - // opportunistic strategy: - { - out << "opportunistic evaluations : "; - out.display_yes_or_no ( _opportunistic_eval ); - out << std::endl; - if ( _opportunistic_eval ) { - if ( _opportunistic_min_nb_success > 0 ) - out << "opportunistic min nb success : " - << _opportunistic_min_nb_success << std::endl; - if ( _opportunistic_min_eval > 0 ) - out << "opportunistic min nb eval : " - << _opportunistic_min_eval << std::endl; - if ( _opportunistic_min_f_imprvmt.is_defined() ) - out << "opportunistic min obj improvement: " - << _opportunistic_min_f_imprvmt << "%" - << std::endl; - if ( _opportunistic_lucky_eval ) - out << "opportunistic lucky eval : " - << _opportunistic_lucky_eval << std::endl; - } - } - - // models: - if (_disable_models) - { - out << NOMAD::open_block ( "models" ); - out << "models usage has been forcefully disabled: " - << std::endl << NOMAD::close_block(); - } - else - { - if ( _model_params.search1 != NOMAD::NO_MODEL || - _model_params.eval_sort != NOMAD::NO_MODEL ) - { - out << NOMAD::open_block ( "models" ); - if ( _model_params.search1 != NOMAD::NO_MODEL ) - { - out << NOMAD::open_block ( "model search" ); - if ( _model_params.search2 == NOMAD::NO_MODEL ) - out << "models type : " << _model_params.search1 << std::endl; - else - out << "models types : " - << _model_params.search1 << " and " - << _model_params.search2 << std::endl; - out << "project to mesh: "; - out.display_yes_or_no ( _model_params.search_proj_to_mesh ); - out << std::endl - << "optimistic : "; - out.display_yes_or_no ( _model_params.search_optimistic ); - out << std::endl - << "max trial pts : " << _model_params.search_max_trial_pts - << std::endl << NOMAD::close_block(); - } - else - out << "no model search" << std::endl; - - // model ordering: - if ( _model_params.eval_sort != NOMAD::NO_MODEL ) { - if ( _model_params.eval_sort == NOMAD::QUADRATIC_MODEL ) { - out << NOMAD::open_block ( "model ordering" ) - << "models type : " << _model_params.eval_sort - << std::endl << "cautious model ordering: "; - out.display_yes_or_no ( _model_params.eval_sort_cautious ); - out << std::endl << NOMAD::close_block(); - } - else - out << "model ordering: " << _model_params.eval_sort << std::endl; - } - else - out << "no model ordering" << std::endl; - - - if ( has_direction_type(NOMAD::ORTHO_NP1_QUAD) ) - { - out << NOMAD::open_block ( "Quad model (n+1)th dynamic direction for Ortho N+1" ) - << "models type : QUADRATIC " - << std::endl << "cautious model ordering: "; - out.display_yes_or_no ( _model_params.eval_sort_cautious ); - out << std::endl << "quad model epsilon for ortho n+1: " - << _model_params.model_np1_quad_epsilon << std::endl; - out << std::endl << NOMAD::close_block(); - } - - // quadratic model parameters: - if ( _model_params.eval_sort == NOMAD::QUADRATIC_MODEL || - _model_params.search1 == NOMAD::QUADRATIC_MODEL || - _model_params.search2 == NOMAD::QUADRATIC_MODEL ) { - out << NOMAD::open_block ( "quadratic model parameters" ) - << "radius factor: " << _model_params.quad_radius_factor << std::endl - << "use WP : "; - out.display_yes_or_no ( _model_params.quad_use_WP ); - out << std::endl << "min Y size : "; - if ( _model_params.quad_min_Y_size < 0 ) - out << "n+1"; - else - out << _model_params.quad_min_Y_size; - out << std::endl - << "max Y size : " << _model_params.quad_max_Y_size - << std::endl << NOMAD::close_block(); - } - - // TGP model parameters: - if ( _model_params.eval_sort == NOMAD::TGP_MODEL || - _model_params.search1 == NOMAD::TGP_MODEL || - _model_params.search2 == NOMAD::TGP_MODEL ) { - out << NOMAD::open_block ( "TGP model parameters" ) - << "mode : " << _model_params.tgp_mode << std::endl - << "reuse model: " << _model_params.tgp_reuse_model << std::endl - << NOMAD::close_block(); - } - out.close_block(); - } - else { - out << "use models : "; - out.display_yes_or_no ( false ); - out << std::endl; - } - } - - // SPECULATIVE_SEARCH: - out << "speculative search : "; - out.display_yes_or_no ( _speculative_search ); - out << std::endl; - - // VNS_SEARCH: - out << "VNS search : "; - out.display_yes_or_no ( _VNS_search ); - if ( _VNS_search ) - out << " [trigger=" << _VNS_trigger << "]"; - out << std::endl; - - // LH_SEARCH: - out << "Latin-Hypercube (LH) search : "; - if ( _LH_search_p0 > 0 || _LH_search_pi > 0 ) { - out << "#init:" << _LH_search_p0 - << ", #iter:" << _LH_search_pi - << ", opport:"; - out.display_yes_or_no ( _opportunistic_LH ); - } - else - out.display_yes_or_no ( false ); - out << std::endl; - - // CACHE_SEARCH: - out << "cache search : "; - if ( _cache_search ) { - out.display_yes_or_no ( true ); - out << ", opport:"; - out.display_yes_or_no ( _opportunistic_cache_search ); - } - else - out.display_yes_or_no ( false ); - out << std::endl; - - // random seed / unique tag / run id: - out << "random seed / run id : " << _seed << std::endl; - - // EPSILON: - out << "epsilon : " - << NOMAD::Double::get_epsilon() << std::endl; - - // UNDEF_STR: - out << "undefined string : " - << NOMAD::Double::get_undef_str() << std::endl; - - // INF_STR: - out << "infinity string : " - << NOMAD::Double::get_inf_str() << std::endl; - - // DISPLAY_DEGREEs: - out << NOMAD::open_block ( "display degrees" ) - << "general : " << _out.get_gen_dd() << std::endl - << "search : " << _out.get_search_dd() << std::endl - << "poll : " << _out.get_poll_dd() << std::endl - << "iterative: " << _out.get_iter_dd() << std::endl - << NOMAD::close_block(); - - // DISPLAY_STATS: - out << "display stats : "; - std::list::const_iterator end = _display_stats.end(); - for ( it = _display_stats.begin() ; it != end ; ++it ) { - if ( it->empty() ) - out << " "; - else - out << *it; - } - out << std::endl; - - // DISPLAY_ALL_EVAL: - out << "display all evaluations : "; - out.display_yes_or_no ( _display_all_eval ); - out << std::endl; - - // POINT_DISPLAY_LIMIT: - out << "point display limit : "; - if ( NOMAD::Point::get_display_limit() > 0 ) - out << NOMAD::Point::get_display_limit() << std::endl; - else - out << "no limit" << std::endl; - - // MAX_EVAL: - if ( _max_eval > 0 ) - out << "max eval. (bb+cache) : " << _max_eval << std::endl; - - // MAX_BB_EVAL: - if ( _max_bb_eval >= 0 ) { - out << "max number of blackbox eval. : " << _max_bb_eval; - if ( _max_bb_eval == 0 ) - out << " (no blackbox eval. allowed)"; - out << std::endl; - } - - // MAX_SIM_BB_EVAL: - if ( _max_sim_bb_eval >= 0 ) - out << "max simulated blackbox eval. : " << _max_sim_bb_eval << std::endl; - - // MAX_SGTE_EVAL: - if ( _sgte_max_eval >= 0 ) { - out << "max surrogate eval. : " << _sgte_max_eval; - if ( _sgte_max_eval == 0 ) - out << " (no surrogate eval. allowed)"; - out << std::endl; - } - - // MAX_ITERATIONS: - if ( _max_iterations >= 0 ) { - out << "max iterations : " << _max_iterations; - if ( _max_iterations == 0 ) - out << " (no iterations allowed)"; - out << std::endl; - } - - // MAX_CONSECUTIVE_FAILED_ITERATIONS: - if ( _max_cons_failed_it > 0 ) - out << "max consecutive failed it. : " << _max_cons_failed_it << std::endl; - - // MAX_CACHE_MEMORY: - if ( _max_cache_memory > 0 ) - out << "max cache memory : " << _max_cache_memory - << " MB" << std::endl; - - // MAX_TIME: - if ( _max_time > 0 ) - out << "max wall-clock time : " << _max_time << "s" << std::endl; - - // F_TARGET: - if ( _f_target.is_defined() ) { - out << "objective target : "; - if ( _f_target.size() > 1 ) { - out << "( "; - _f_target.display ( out , " " , 4 , -1 ); - out << " )" << std::endl; - } - else - out << _f_target[0] << std::endl; - } - - // STAT_SUM_TARGET: - if ( _stat_sum_target.is_defined() ) - out << "stat sum target : " - << _stat_sum_target << std::endl; - - // L_CURVE_TARGET: - if ( _L_curve_target.is_defined() ) - out << "L-curve target : " - << _L_curve_target << std::endl; - - // STOP_IF_FEASIBLE: - if ( _stop_if_feasible ) { - out << "stop if feasible : "; - out.display_yes_or_no ( _stop_if_feasible ); - out << std::endl; - } -} - -/*---------------------------------------*/ -/* reset stats file */ -/*---------------------------------------*/ -void NOMAD::Parameters::reset_stats_file ( void ) -{ - _stats_file.clear(); - _stats_file_name.clear(); -} - -/*---------------------------------------*/ -/* reset variable groups */ -/*---------------------------------------*/ - -// 1/2 (private): -void NOMAD::Parameters::reset_variable_groups -( std::set & vg ) const -{ - std::set::const_iterator end = vg.end() , it; - for ( it = vg.begin() ; it != end ; ++it ) - delete *it; - vg.clear(); -} - -// 2/2 (public): -void NOMAD::Parameters::reset_variable_groups ( void ) -{ - _to_be_checked = true; - reset_variable_groups ( _var_groups ); - reset_variable_groups ( _user_var_groups ); -} - -/*---------------------------------------*/ -/* reset fixed variables */ -/*---------------------------------------*/ -void NOMAD::Parameters::reset_fixed_variables ( void ) -{ - _to_be_checked = true; - _fixed_variables.clear(); -} - -/*---------------------------------------*/ -/* reset periodic variables */ -/*---------------------------------------*/ -void NOMAD::Parameters::reset_periodic_variables ( void ) -{ - _to_be_checked = true; - _periodic_variables.clear(); -} - -/*---------------------------------------*/ -/* reset bounds */ -/*---------------------------------------*/ -void NOMAD::Parameters::reset_bounds ( void ) -{ - _to_be_checked = true; - _lb.clear(); - _ub.clear(); -} - -/*---------------------------------------*/ -/* reset scaling */ -/*---------------------------------------*/ -void NOMAD::Parameters::reset_scaling ( void ) -{ - _to_be_checked = true; - _scaling.clear(); -} - -/*----------------------------------------*/ -/* check the parameters */ -/*----------------------------------------*/ -void NOMAD::Parameters::check ( bool remove_history_file , - bool remove_solution_file , - bool remove_stats_file ) -{ - if ( !_to_be_checked ) - return; - - int i; - - /*--------------------------------------------------*/ - /* display degree and NOMAD::Point::display_limit */ - /*--------------------------------------------------*/ - { - -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - _out.set_degrees ( NOMAD::NO_DISPLAY ); -#endif - -#ifdef DEBUG -#ifdef USE_MPI - if ( NOMAD::Slave::is_master() ) -#endif - _out.set_degrees ( NOMAD::FULL_DISPLAY ); -#endif - - if ( _out.get_gen_dd() == NOMAD::FULL_DISPLAY ) - set_POINT_DISPLAY_LIMIT ( -1 ); - } - - /*----------------------------*/ - /* DIMENSION */ - /*----------------------------*/ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIMENSION" ); - if ( _dimension > NOMAD::MAX_DIMENSION ) - { - std::ostringstream oss; - oss << "invalid parameter: DIMENSION (must be <= " - << NOMAD::MAX_DIMENSION << ")"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , oss.str() ); - } - - /*----------------------------*/ - /* BB_INPUT_TYPE */ - /*----------------------------*/ - if ( static_cast(_bb_input_type.size()) != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE" ); - - - /*----------------------------*/ - /* BOUNDS */ - /*----------------------------*/ - { - if ( _lb.size() > _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LOWER_BOUND" ); - if ( _lb.size() < _dimension ) - _lb.resize ( _dimension ); - - if ( _ub.size() > _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: UPPER_BOUND" ); - if ( _ub.size() < _dimension ) - _ub.resize ( _dimension ); - - for ( i = 0 ; i < _dimension ; ++i ) - { - if ( _lb[i].is_defined() && _ub[i].is_defined() ) - { - if ( _lb[i] > _ub[i] ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LOWER_BOUND or UPPER_BOUND" ); - if ( _lb[i] == _ub[i] ) - set_FIXED_VARIABLE ( i , _lb[i] ); - - } - // Check that x0s are within bounds when defined - if(_lb[i].is_defined()) - { - std::vector::iterator it; - for(it=_x0s.begin();it<_x0s.end();it++) - { - // Compare values only if dimension is the same - if ( (*it)->size()==_lb.size() && (**it)[i] < _lb[i] ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: x0 < LOWER_BOUND " ); - } - } - if(_ub[i].is_defined()) - { - std::vector::iterator it; - for(it=_x0s.begin();it<_x0s.end();it++) - { - // Compare values only if dimension is the same - if ( (*it)->size()==_ub.size() && (**it)[i] > _ub[i] ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: x0 > UPPER_BOUND " ); - } - } - // integer, binary, and categorical variables: - if ( _bb_input_type[i] != NOMAD::CONTINUOUS ) - { - - // binary variables: - if ( _bb_input_type[i] == NOMAD::BINARY ) - { - _lb[i] = 0.0; - _ub[i] = 1.0; - } - // integer and categorical variables: - else - { - if ( _lb[i].is_defined() ) - _lb[i] = ceil(_lb[i].value()); - if ( _ub[i].is_defined() ) - _ub[i] = floor(_ub[i].value()); - } - } - } - } - - - /*----------------------------*/ - /* FIXED_VARIABLES */ - /*----------------------------*/ - if ( _fixed_variables.size() > _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE" ); - - if ( _fixed_variables.size() < _dimension ) - _fixed_variables.resize ( _dimension ); - - int nb_fixed = 0; - for ( i = 0; i < _dimension; ++i ) - if ( _fixed_variables[i].is_defined() ) - { - ++nb_fixed; - if ( (_lb[i].is_defined() && _fixed_variables[i] < _lb[i]) || - (_ub[i].is_defined() && _fixed_variables[i] > _ub[i]) || - ( (_bb_input_type[i] == NOMAD::INTEGER || - _bb_input_type[i] == NOMAD::CATEGORICAL ) - && !_fixed_variables[i].is_integer() ) || - ( _bb_input_type[i] == NOMAD::BINARY && !_fixed_variables[i].is_binary() ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE" ); - } - - if ( nb_fixed == _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE - all variables are fixed" ); - - _nb_free_variables = _dimension - nb_fixed; - - /*----------------------------*/ - /* Poll and Mesh */ - /*----------------------------*/ - { - - if ( _use_smesh && _anisotropic_mesh ) - { - _anisotropic_mesh=false; - if ( !_warning_has_been_displayed ) - _out << NOMAD::open_block("Warning:") - << "Anisotropic mesh is disabled when using smesh." << std::endl - << NOMAD::close_block(); - } - - - // mesh sizes: - if ( _initial_mesh_size.size() != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_SIZE must have same dimension as problem" ); - - // poll sizes - if ( _initial_poll_size.size() != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_POLL_SIZE must have same dimension as problem" ); - - if ( _initial_mesh_size.is_defined() && _initial_poll_size.is_defined() ) - { - if ( !_warning_has_been_displayed ) - _out << NOMAD::open_block("Warning:") - << "Initial mesh size and initial poll size are provided. Only the initial poll size will be considered." << std::endl - << NOMAD::close_block(); - _initial_mesh_size.clear(); - _initial_mesh_size.reset ( _dimension ); - } - - - // initial mesh size or poll size: - // -------------------------------- - bool use_x0 = !_x0s.empty() && _x0s[0]->size() == _dimension; - for ( i = 0 ; i < _dimension ; ++i ) - { - - // continuous variables: - // --------------------- - if ( _bb_input_type[i] == NOMAD::CONTINUOUS ) - { - - // Determine _initial_mesh_size from _initial_poll_size (this will disappear in future version) - if ( _initial_mesh_size[i].is_defined() ) - _initial_poll_size[i]=_initial_mesh_size[i]*pow(_dimension,0.5); - - // default value for initial mesh size - if ( !_initial_poll_size[i].is_defined() ) - { - - if (_lb[i].is_defined() && _ub[i].is_defined()) - { - set_INITIAL_POLL_SIZE ( i , 0.1 , true ); - if ( _lb[i] == _ub[i] ) - set_INITIAL_POLL_SIZE (i, 1 ,false); - - } - else if ( _lb[i].is_defined() && use_x0 && (*_x0s[0])[i].is_defined() && _lb[i]!=(*_x0s[0])[i]) - { - _initial_poll_size[i] = ((*_x0s[0])[i]-_lb[i])/10.0; // Case x0 < lb tested elsewhere - } - else if ( _ub[i].is_defined()&& use_x0 && (*_x0s[0])[i].is_defined() && _ub[i]!=(*_x0s[0])[i]) - { - _initial_poll_size[i] = (_ub[i]-(*_x0s[0])[i])/10.0; // Case x0 > ub tested elsewhere - } - else - { - if ( use_x0 && (*_x0s[0])[i].is_defined() && (*_x0s[0])[i].abs() > NOMAD::Double::get_epsilon()*10.0 ) - _initial_poll_size[i] = (*_x0s[0])[i].abs()/10.0; - else - { - _initial_poll_size[i] = 1.0; - - if (_out.get_gen_dd()>=NOMAD::NORMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "Initial mesh size for variable " << i << " has been arbitrarily fixed to 1." << std::endl - << " In the absence of bounds and initial values different than zero," << std::endl - << " it is recommended to explicitely provide this parameter." << std::endl - << NOMAD::close_block(); - } - } - } - else if ( !_fixed_variables[i].is_defined() && - ( _initial_poll_size[i].value() < NOMAD::Double::get_epsilon() || - _initial_poll_size[i].value() <= 0.0 ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_SIZE" ); - } - // binary/categorical variables: - // ----------------------------- - else if ( _bb_input_type[i] == NOMAD::BINARY || - _bb_input_type[i] == NOMAD::CATEGORICAL ) - { - // mesh and poll sizes not used for binary and categorical - // but set to prevent warning when creating signature - _initial_mesh_size[i] = 1.0; - _initial_poll_size[i] = 1.0; - } - // integer variables: - // ------------------ - else - { - // Determine mesh size from poll size - if ( _initial_poll_size[i].is_defined() ) - _initial_mesh_size[i]=_initial_poll_size[i]*pow(_dimension,-0.5); - - - if ( _initial_mesh_size[i].is_defined() ) - { - _initial_mesh_size[i]=_initial_mesh_size[i].round(); - if ( _initial_mesh_size[i] < 1.0 ) - _initial_mesh_size[i] = 1.0; - - } - else // that is no initial_mesh_size and no initial_poll_size - { - - // default value for initial mesh size - // (r0.1 if there are bounds + rounding to nearest integer not zero, 1.0 otherwise): - if ( !_lb[i].is_defined() || !_ub[i].is_defined() ) - _initial_mesh_size[i] = 1.0; - else - { - set_INITIAL_POLL_SIZE ( i , 0.1 , true ); - _initial_mesh_size[i]=_initial_poll_size[i]*pow(_dimension,-0.5); - _initial_mesh_size[i]=_initial_mesh_size[i].round(); - if ( _initial_mesh_size[i] < 1.0 ) - _initial_mesh_size[i] = 1.0; - - } - } - _initial_poll_size[i]=_initial_mesh_size[i]*pow(_dimension,0.5); - - } - // Determine _initial_mesh_size from _initial_poll_size (this will disappear in future version) - if ( !_initial_mesh_size[i].is_defined() ) - _initial_mesh_size[i]=_initial_poll_size[i]*pow(_dimension,-0.5); - - } - - // min mesh size \delta_min: - if ( _min_mesh_size.is_defined() ) - { - - if ( _min_mesh_size.size() != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_MESH_SIZE" ); - - for ( i = 0 ; i < _dimension ; ++i ) - if ( _min_mesh_size[i].is_defined() && - (_min_mesh_size[i].value() < NOMAD::Double::get_epsilon() || - _min_mesh_size[i].value() <= 0.0 ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameters: MIN_MESH_SIZE" ); - } - - // min poll size \Delta^p_min: - if ( _min_poll_size.is_defined() ) - { - - _min_poll_size_defined = true; - - if ( _min_poll_size.size() != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_POLL_SIZE" ); - - for ( i = 0 ; i < _dimension ; ++i ) - { - // continuous variables: - if ( _bb_input_type[i] == NOMAD::CONTINUOUS ) - { - if ( _min_poll_size[i].is_defined() && - (_min_poll_size[i].value() < NOMAD::Double::get_epsilon() || - _min_poll_size[i].value() <= 0.0 ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameters: MIN_POLL_SIZE" ); - } - - // integer and binary variables: - else if ( _bb_input_type[i] != NOMAD::CATEGORICAL ) - { - if ( _min_poll_size[i].is_defined() ) - { - if ( _min_poll_size[i] < 1.0 ) - _min_poll_size[i] = 1.0; - } - else - _min_poll_size[i] = 1.0; - } - } - } - - // default min poll size for non-continuous variables: - else - { - - _min_poll_size_defined = false; - - _min_poll_size = NOMAD::Point ( _dimension ); - for ( i = 0 ; i < _dimension ; ++i ) - if ( _bb_input_type[i] == NOMAD::INTEGER ) - _min_poll_size[i] = 1.0; - } - - // default value for _mesh_update_basis (tau): - if ( _mesh_update_basis <= 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameters: MESH_UPDATE_BASIS (must be >1)" ); - - if ( _poll_update_basis <= 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameters: POLL_UPDATE_BASIS (must be >1)" ); - } - - - int nb_obj = static_cast(_index_obj.size()); - - /*----------------------------*/ - /* DISPLAY_STATS */ - /*----------------------------*/ - if ( _display_stats.empty() ) - { - std::list ls; - if ( nb_obj == 1 ) - { - ls.push_back ( NOMAD::Display::get_display_stats_keyword ( NOMAD::DS_BBE ) ); - ls.push_back ( std::string() ); - } - ls.push_back ( NOMAD::Display::get_display_stats_keyword ( NOMAD::DS_OBJ ) ); - set_DISPLAY_STATS ( ls ); - } - - else if ( !check_display_stats ( _display_stats ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DISPLAY_STATS" ); - - /*----------------------------*/ - /* STATS_FILE */ - /*----------------------------*/ - if ( !_stats_file_name.empty() ) - { - if ( _stats_file.empty() ) - { - std::list ls; - ls.push_back ( NOMAD::Display::get_display_stats_keyword ( NOMAD::DS_BBE ) ); - ls.push_back ( std::string() ); - ls.push_back ( NOMAD::Display::get_display_stats_keyword ( NOMAD::DS_OBJ ) ); - set_STATS_FILE ( _stats_file_name , ls ); - } - else if ( !check_display_stats ( _stats_file ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STATS_FILE" ); - } - - /*----------------------------*/ - /* SCALING */ - /*----------------------------*/ - if ( _scaling.size() > _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SCALING" ); - - if ( _scaling.size() < _dimension ) - _scaling.resize ( _dimension ); - - for ( i = 0; i < _dimension; ++i ) - if ( _scaling[i].is_defined() && _scaling[i] == 0.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SCALING (zero value)" ); - - /*---------------------------*/ - /* blackbox outputs */ - /*---------------------------*/ - if ( _bb_output_type.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE" ); - if ( _bb_output_type.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE - undefined" ); - - size_t m = _bb_output_type.size(); - - if ( !_bb_exe.empty() && m != _bb_exe.size() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE: wrong number of blackbox executable names" ); - - // surrogate: - if ( !_sgte_exe.empty() ) - { - - _has_sgte = true; - - if ( _bb_exe.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EXE - no BB_EXE is defined" ); - - std::map::const_iterator it; - std::map::const_iterator end = _sgte_exe.end(); - std::list::const_iterator bb_exe_begin = _bb_exe.begin(); - std::list::const_iterator bb_exe_end = _bb_exe.end(); - - // an empty string in _sgte_exe means that there is a unique - // blackbox with the associated surrogate - // (SGTE_EXE parameter with only one argument): - it = _sgte_exe.find(""); - if ( it != end ) { - if ( _sgte_exe.size() != 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EXE - impossible to interpret with one argument" ); - - std::string bb_exe_name = *bb_exe_begin; - std::list::const_iterator it2 = ++bb_exe_begin; - while ( it2 != bb_exe_end ) { - if ( *it2 != bb_exe_name ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: unique SGTE_EXE without unique blackbox executable" ); - ++it2; - } - - std::string sgte_name = it->second; - - _sgte_exe.clear(); - _sgte_exe[bb_exe_name] = sgte_name; - } - else - for ( it = _sgte_exe.begin() ; it != end ; ++it ) - if ( find ( bb_exe_begin , bb_exe_end , it->first ) == bb_exe_end ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_EXE" ); - } - else if ( !_has_sgte ) - { - _sgte_eval_sort = false; - _sgte_cost = -1; - - if ( _opt_only_sgte ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: OPT_ONLY_SGTE" ); - } - - if ( _opt_only_sgte ) - _sgte_eval_sort = false; - - size_t k; - - // CNT_EVAL, _STAT_SUM_ and _STAT_AVG_ checks (each one have to be unique): - _index_cnt_eval = _index_stat_sum = _index_stat_avg = -1; - for ( k = 0 ; k < m ; ++k ) - { - if ( _bb_output_type[k] == NOMAD::STAT_SUM ) - { - if ( _index_stat_sum >= 0 ) - { - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE: more than one STAT_SUM output" ); - } - _index_stat_sum = static_cast(k); - } - else if ( _bb_output_type[k] == NOMAD::STAT_AVG ) - { - if ( _index_stat_avg >= 0 ) - { - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE: more than one STAT_AVG output" ); - } - _index_stat_avg = static_cast(k); - } - else if ( _bb_output_type[k] == NOMAD::CNT_EVAL ) - { - if ( _index_cnt_eval >= 0 ) - { - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE: more than one CNT_EVAL output" ); - } - _index_cnt_eval = static_cast(k); - } - } - - // F_TARGET: - if ( _f_target.is_defined() && nb_obj != _f_target.size() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: F_TARGET of bad dimension" ); - - /*----------------------------*/ - /* directions */ - /*----------------------------*/ - bool use_ortho_mads = false; - - { - bool use_mads = false; - bool use_ortho_mads_only = true; - std::set::const_iterator it , end = _direction_types.end(); - - // default value for primary poll directions: - if ( _direction_types.empty() ) - { - set_DIRECTION_TYPE ( NOMAD::ORTHO_NP1_QUAD ); // Default setting that maybe changed if models are disabled - use_mads = true; - use_ortho_mads = true; - use_ortho_mads_only = true; // OrthoMads (2n or n+1) not mixed with LT or GPS - } - else - for ( it = _direction_types.begin() ; it != end ; ++it ) - { - if ( NOMAD::dir_is_mads ( *it ) ) - use_mads = true; - if ( NOMAD::dir_is_orthomads ( *it ) ) - use_ortho_mads = true; - if ( ! NOMAD::dir_is_orthomads ( *it ) ) - use_ortho_mads_only = false; - - } - - if ( ! use_ortho_mads_only && _anisotropic_mesh ) - { - _anisotropic_mesh=false; - if ( !_warning_has_been_displayed ) - _out << NOMAD::open_block("Warning:") - << "Anisotropic mesh is disabled for direction types other than OrthoMads." << std::endl - << NOMAD::close_block(); - } - - - - - // default value for secondary poll directions: - if ( _barrier_type == NOMAD::PB || _barrier_type == NOMAD::PEB_P ) - { - - if ( _sec_poll_dir_types.empty() ) - { - if ( use_mads ) - { - if ( _direction_types.size() == 1 ) - { - NOMAD::direction_type dt = *(_direction_types.begin()); - if ( dt == NOMAD::ORTHO_1 || dt == NOMAD::ORTHO_2 ) - set_SEC_POLL_DIR_TYPE ( NOMAD::ORTHO_1 ); - else if ( dt == NOMAD::LT_1 || dt == NOMAD::LT_2 ) - set_SEC_POLL_DIR_TYPE ( NOMAD::LT_1 ); - else - set_SEC_POLL_DIR_TYPE ( (use_ortho_mads) ? NOMAD::ORTHO_2 : NOMAD::LT_2 ); - } - else - set_SEC_POLL_DIR_TYPE ( (use_ortho_mads) ? NOMAD::ORTHO_2 : NOMAD::LT_2 ); - } - else - set_SEC_POLL_DIR_TYPE ( NOMAD::GPS_NP1_STATIC ); - } - - else - { - bool old_uom = use_ortho_mads; - bool old_um = use_mads; - end = _sec_poll_dir_types.end(); - for ( it = _sec_poll_dir_types.begin() ; it != end ; ++it ) - { - if ( *it == NOMAD::NO_DIRECTION ) - { - _sec_poll_dir_types.clear(); - use_ortho_mads = old_uom; - use_mads = old_um; - break; - } - if ( NOMAD::dir_is_orthomads (*it) ) - use_ortho_mads = true; - if ( NOMAD::dir_is_mads ( *it ) ) - use_mads = true; - } - } - } - else - _sec_poll_dir_types.clear(); - - /*----------------------------*/ - /* SPECULATIVE_SEARCH */ - /*----------------------------*/ - if ( !use_mads ) - _speculative_search = false; - } - - /*----------------------------*/ - /* periodic variables */ - /*----------------------------*/ - if ( !_periodic_variables.empty() ) { - - // check the size: - if ( _dimension != static_cast(_periodic_variables.size()) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE - bad size" ); - - // check the bounds: - for ( int k = 0 ; k < _dimension ; ++k ) - if ( _periodic_variables[k] ) { - if ( !_lb[k].is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE - lower bound not defined" ); - if ( !_ub[k].is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE - upper bound not defined" ); - } - } - - - /*---------------------------*/ - /* model parameters */ - /*---------------------------*/ - { - - // disable models upon request - if ( _disable_models) - { - _model_params.search1 = _model_params.search2 = _model_params.eval_sort = NOMAD::NO_MODEL; - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - { - _out << NOMAD::open_block("Warning:") - << "Model use is forcefully disabled." << std::endl - << NOMAD::close_block(); - - if (has_direction_type(NOMAD::ORTHO_NP1_QUAD)) - { - _out << NOMAD::open_block("Warning:") - << "Model use is disabled for direction type. Direction types ORTHO N+1 QUAD are changed to ORTHO N+1 NEG." << std::endl - << NOMAD::close_block(); - } - } - set_DIRECTION_TYPE_NO_MODEL(); - - } - - // disable models when requested or for more than 50 variables, - // for categorical variables and for surrogate optimization: - bool has_categorical=false; - bool has_binary=false; - for ( i = 0 ; i < _dimension ; ++i ) - { - if ( !_fixed_variables[i].is_defined() && _bb_input_type[i] == NOMAD::CATEGORICAL ) - { - has_categorical=true; - } - if ( !_fixed_variables[i].is_defined() && _bb_input_type[i] == NOMAD::BINARY ) - { - has_binary=true; - } - } - - if ( _nb_free_variables >= 50 || has_categorical || _opt_only_sgte ) - { - _model_params.search1 = _model_params.search2 = _model_params.eval_sort = NOMAD::NO_MODEL; - set_DIRECTION_TYPE_NO_MODEL(); - - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - { - if ( _opt_only_sgte) - _out << NOMAD::open_block("Warning:") - << "Model use is disabled when setting the option OPT_ONLY_SGTE to yes." << std::endl; - if ( has_categorical) - _out << NOMAD::open_block("Warning:") - << "Model use is disabled for problem with categorical variables." << std::endl - << NOMAD::close_block(); - if ( _nb_free_variables >= 50) - _out << NOMAD::open_block("Warning:") - << "Model use is disabled for problem with dimension greater than 50." << std::endl - << NOMAD::close_block(); - } - } - - - // disable PEB constraints when categorical variables are present - if ( has_categorical && _barrier_type == NOMAD::PEB_P) - { - - change_PEB_to_PB(); - - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "PEB constraints are disabled when using categorical variables. To continue, PEB constraints have been replaced by PB constraints." << std::endl - << NOMAD::close_block(); - - } - - if ( ( has_categorical || has_binary ) && _anisotropic_mesh ) - { - _anisotropic_mesh=false; - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "Default anisotropic mesh is disabled with categorical and binary variables." << std::endl - << NOMAD::close_block(); - - } - - // disable model use in parallel mode: -#ifdef USE_MPI - _model_params.search1 = _model_params.search2 = _model_params.eval_sort = NOMAD::NO_MODEL; - set_DIRECTION_TYPE_NO_MODEL(); - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "Model use is disabled in parallel mode (MPI)." << std::endl - << NOMAD::close_block(); - - - if ((has_direction_type(NOMAD::ORTHO_NP1_QUAD) || has_direction_type(NOMAD::ORTHO_NP1_NEG)) && _asynchronous) - { - set_ASYNCHRONOUS(false); - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "Asynchronous mode is disabled in parallel mode (MPI) when dynamic directions (ortho n+1) are used." << std::endl - << NOMAD::close_block(); - } -#endif - - // other checks: - if ( ( _model_params.search1 == NOMAD::NO_MODEL && - _model_params.search2 != NOMAD::NO_MODEL ) || - ( _model_params.search1 != NOMAD::NO_MODEL && - _model_params.search1 == _model_params.search2 ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH (conflict with the two types of search)" ); - - if ( _model_params.quad_radius_factor <= 0.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_RADIUS_FACTOR (must be > 0)" ); - - if ( _model_params.quad_min_Y_size < 0 ) - _model_params.quad_min_Y_size = -1; - else if ( _model_params.quad_min_Y_size < 2 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_QUAD_MIN_Y_SIZE (must be in {'N+1',-1,2,3,...})" ); - - if ( _model_params.model_np1_quad_epsilon <= 0.0 || _model_params.model_np1_quad_epsilon >= 1.0) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_NP1_QUAD_EPSILON (must be > 0 and < 1)" ); - - if ( _model_params.quad_max_Y_size <= _nb_free_variables ) - _model_params.quad_max_Y_size = _nb_free_variables + 1; - - if ( _model_params.search_max_trial_pts < 1 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH_MAX_TRIAL_PTS (must be >= 1)" ); - } - - /*----------------------------*/ - /* EVAL SORT */ - /*----------------------------*/ - if (_disable_eval_sort) - { - - _model_params.eval_sort = NOMAD::NO_MODEL; - _sgte_eval_sort = false; - NOMAD::Priority_Eval_Point::set_lexicographic_order(true); - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "Eval sort is forcefully disabled (using models, surrogates, user eval priority, etc.). Only lexicographic order is used." << std::endl - << NOMAD::close_block(); - - } - else - NOMAD::Priority_Eval_Point::set_lexicographic_order(false); - - - /*----------------------------*/ - /* variable groups */ - /*----------------------------*/ - { - - // reset variable groups: - reset_variable_groups ( _var_groups ); - - std::vector in_group ( _dimension ); - for ( i = 0 ; i < _dimension ; ++i ) - in_group[i] = false; - - NOMAD::Variable_Group * vg; - std::set direction_types , sec_poll_dir_types; - - // 1. user groups: - std::set::const_iterator - end = _user_var_groups.end() , it; - - bool mod; - for ( it = _user_var_groups.begin() ; it != end ; ++it ) - { - - if ( !(*it)->check ( _fixed_variables , _bb_input_type , &in_group, mod ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP" ); - - direction_types = (*it)->get_direction_types(); - sec_poll_dir_types = (*it)->get_sec_poll_dir_types(); - - if ( direction_types.empty() ) - direction_types = _direction_types; - - if ( sec_poll_dir_types.empty() ) - sec_poll_dir_types = _sec_poll_dir_types; - - vg = new NOMAD::Variable_Group ( (*it)->get_var_indexes() , - direction_types , - sec_poll_dir_types , - _out ); - - _var_groups.insert ( vg ); - } - - - // 2. 'automatic' groups for other variables: - std::set vi_cbi; // list of cont./bin./int. variables - std::set vi_cat; // list of categorical variables - - for ( i = 0 ; i < _dimension ; ++i ) - { - if ( !in_group[i] && !_fixed_variables[i].is_defined() ) { - if ( _bb_input_type[i] != NOMAD::CATEGORICAL ) - vi_cbi.insert(i); - else - vi_cat.insert(i); - } - } - - // creation of a group for cont./bin./int. variables: - if ( !vi_cbi.empty() ) - { - vg = new NOMAD::Variable_Group ( vi_cbi , - _direction_types , - _sec_poll_dir_types , - _out ); - - _var_groups.insert ( vg ); - } - - // creation of a group for categorical variables: - if ( !vi_cat.empty() ) - { - vg = new NOMAD::Variable_Group ( vi_cat , - _direction_types , - _sec_poll_dir_types , - _out ); - _var_groups.insert ( vg ); - } - } - - /*----------------------------*/ - /* TMP_DIR */ - /*----------------------------*/ - { - if ( _tmp_dir.empty() ) - _tmp_dir = _problem_dir; - - // check the directory: - if ( !_tmp_dir.empty() && !NOMAD::check_read_file ( _tmp_dir ) ) - { - std::string err = "invalid parameter: TMP_DIR: cannot access \'" + _tmp_dir + "\'"; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - } - - /*------------------------------------------------------*/ - /* SOLUTION_FILE, HISTORY_FILE and STATS_FILE */ - /* (depending on the value of ADD_SEED_TO_FILE_NAMES, */ - /* the seed is added the file names) */ - /*------------------------------------------------------*/ - if ( _add_seed_to_file_names ) - { - - std::string s_seed = NOMAD::itos(_seed); - int n_seed = static_cast(s_seed.size()); - - add_seed_to_file_name ( n_seed , s_seed , _solution_file ); - add_seed_to_file_name ( n_seed , s_seed , _history_file ); - add_seed_to_file_name ( n_seed , s_seed , _stats_file_name ); - } - - // remove old history, solution, and stats files: - std::string old_file; - if ( remove_history_file && !_history_file.empty() ) - { - old_file = _problem_dir + _history_file; - remove ( old_file.c_str() ); - } - if ( remove_stats_file && !_stats_file_name.empty() ) - { - old_file = _problem_dir + _stats_file_name; - remove ( old_file.c_str() ); - } - if ( remove_solution_file && !_solution_file.empty() ) - { - old_file = _problem_dir + _solution_file; - remove ( old_file.c_str() ); - } - - /*----------------------------*/ - /* opportunistic strategy */ - /*----------------------------*/ - if ( !_opportunistic_eval ) - { - _model_params.eval_sort = NOMAD::NO_MODEL; - _sgte_eval_sort = false; - _opportunistic_lucky_eval = false; - _opportunistic_min_nb_success = -1; - _opportunistic_min_eval = -1; - _opportunistic_min_f_imprvmt.clear(); - } - - // opportunistic default strategy for LH search: - // single-objective: the default is taken the same as OPPORTUNISTIC_EVAL - // multi-objective : the default is 'no' - if ( !_opp_LH_is_defined ) - _opportunistic_LH = ( nb_obj > 1 ) ? false : _opportunistic_eval; - - // opportunistic default strategy for cache search - // (the same as OPPORTUNISTIC_EVAL): - if ( !_opp_CS_is_defined ) - _opportunistic_cache_search = false; - - if (_bb_max_block_size<=0) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::check(): invalid block size for list evaluation (>0)" ); - - if (_out.get_gen_dd()>NOMAD::MINIMAL_DISPLAY && !_warning_has_been_displayed && _bb_max_block_size > 1 && (_max_bb_eval>0 || _max_sim_bb_eval>0 || _max_eval>0)) - _out << NOMAD::open_block("Warning:") - << "The maximum number of evaluations may be exceeded when BB_MAX_BLOCK_SIZE>1." << std::endl - << NOMAD::close_block(); - - -#ifdef USE_MPI - if (_bb_max_block_size >1) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::check(): List evaluation by block of size > 1 are not allowed when using MPI." ); -#endif - - /*----------------------------*/ - /* MULTI-MADS */ - /*----------------------------*/ - if ( nb_obj > 1 ) - { - - if ( _multi_formulation == NOMAD::UNDEFINED_FORMULATION ) - _multi_formulation = ( _VNS_search ) ? NOMAD::DIST_L2 : NOMAD::PRODUCT; - - if ( _multi_nb_mads_runs < 0 ) - { - - if ( _multi_overall_bb_eval < 0 ) - { - _multi_nb_mads_runs = 30; - if ( !_max_bbe_decided ) - { - _max_bb_eval = 25 * _nb_free_variables; - - if ( _LH_search_p0 < 0 ) - _LH_search_p0 = _max_bb_eval; - } - } - else if ( !_max_bbe_decided ) - { - _max_bb_eval = static_cast - ( ceil ( sqrt ( 1.0 * _nb_free_variables * _multi_overall_bb_eval ) ) ); - - if ( _LH_search_p0 < 0 ) - _LH_search_p0 = _max_bb_eval; - } - } - else if ( _multi_overall_bb_eval > 0 && !_max_bbe_decided ) - { - _max_bb_eval = _multi_overall_bb_eval / _multi_nb_mads_runs; - if ( _multi_nb_mads_runs * _max_bb_eval < _multi_overall_bb_eval ) - ++_max_bb_eval; - } - } - - /*----------------------------------*/ - /* signature (standard or extern) */ - /*----------------------------------*/ - NOMAD::Signature * new_s = new NOMAD::Signature ( _dimension , - _bb_input_type , - _lb , - _ub , - _use_smesh , - _anisotropic_mesh , - _initial_poll_size, - _min_poll_size, - _min_mesh_size, - _mesh_update_basis, - _poll_update_basis, - _mesh_coarsening_exponent, - _mesh_refining_exponent, - _initial_mesh_index, - _scaling , - _fixed_variables , - _periodic_variables , - _var_groups ); - - // extern signature: - if ( _extern_signature ) - { - - bool fail = ( *new_s != *_extern_signature ); - delete new_s; - if ( fail ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::check(): incompatible extern signature" ); - } - - // standard signature: - else - { - if ( _std_signature ) - { - delete new_s; - - _std_signature->reset ( _dimension , - _bb_input_type , - _lb , - _ub , - _scaling , - _fixed_variables , - _periodic_variables , - _var_groups ); - } - else - { - _std_signature = new_s; - _std_signature->set_std(); - } - } - - bool has_categorical - = ( (_std_signature) ? _std_signature : _extern_signature )->has_categorical(); - - - /*----------------------------*/ - /* X0 */ - /*----------------------------*/ - { - if ( _x0s.empty() && _x0_cache_file.empty() ) { - if ( _LH_search_p0 <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::check(): no starting point" ); - else if ( has_categorical ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::check(): no starting point with categorical variables" ); - } - - size_t x0n = _x0s.size(); - for ( size_t k = 0 ; k < x0n ; ++k ) - { - if ( !_x0s[k]->is_complete() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: x0 with missing coordinates" ); - - // check that x0 is consistent with input type - for ( i = 0 ; i < _dimension ; ++i ) - { - const NOMAD::Double xi = (*_x0s[k])[i]; - if ( _bb_input_type[i] != NOMAD::CONTINUOUS && ! xi.is_integer() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: x0 with variables values inconistent with their type (integer, binary, categorical." ); - - } - - } - - - // avoid _x0_cache_file == _sgte_cache_file : - if ( !_opt_only_sgte && - !_x0_cache_file.empty() && - !_sgte_cache_file.empty() && - _x0_cache_file == _sgte_cache_file ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: x0 and sgte cache file are the same" ); - } - - - /*----------------------*/ - - _to_be_checked = false; - _warning_has_been_displayed=true; -} - -/*-----------------------------------------------------------------*/ -/* add seed to a file name: file_name.ext --> file_name.seed.ext */ -/* (static, private) */ -/*-----------------------------------------------------------------*/ -void NOMAD::Parameters::add_seed_to_file_name ( int n_seed , - const std::string & s_seed , - std::string & file_name ) -{ - int n_pn = static_cast(file_name.size()); - - if ( n_pn == 0 ) - return; - - int k = static_cast(file_name.find_last_of(".")); - std::string ext = ""; - std::string fic = file_name; - - if ( k >= 0 && k < n_pn ) { - fic = file_name.substr ( 0 , k ); - ext = file_name.substr ( k , n_pn-k ); - n_pn = k; - } - - if ( n_pn <= n_seed+1 || - fic.substr ( n_pn-n_seed , n_pn-1 ) != s_seed ) - file_name = fic + "." + s_seed + ext; -} - -/*----------------------------------------*/ -/* GET methods */ -/*----------------------------------------*/ - -// get_signature: -NOMAD::Signature * NOMAD::Parameters::get_signature ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_signature(), Parameters::check() must be invoked" ); - if ( !_std_signature && !_extern_signature ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_signature(), no signature is set" ); - return (_std_signature) ? _std_signature : _extern_signature; -} - -// get_dimension: -int NOMAD::Parameters::get_dimension ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_dimension(), Parameters::check() must be invoked" ); - return _dimension; -} - -// get_nb_free_variables: -int NOMAD::Parameters::get_nb_free_variables ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_nb_free_variables(), Parameters::check() must be invoked" ); - return _nb_free_variables; -} - -// get_add_seed_to_file_names: -bool NOMAD::Parameters::get_add_seed_to_file_names ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_add_seed_to_file_names(), Parameters::check() must be invoked" ); - return _add_seed_to_file_names; -} - -// get_snap_to_bounds: -bool NOMAD::Parameters::get_snap_to_bounds ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_snap_to_bounds(), Parameters::check() must be invoked" ); - return _snap_to_bounds; -} - -// get_speculative_search: -bool NOMAD::Parameters::get_speculative_search ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_speculative_search(), Parameters::check() must be invoked" ); - return _speculative_search; -} - -// get_cache_search: -bool NOMAD::Parameters::get_cache_search ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_cache_search(), Parameters::check() must be invoked" ); - return _cache_search; -} - -// access to all the models parameters: -void NOMAD::Parameters::get_model_parameters ( NOMAD::model_params_type & mp ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_parameters(), Parameters::check() must be invoked" ); - mp = _model_params; -} - -// get_model_search: -NOMAD::model_type NOMAD::Parameters::get_model_search ( int i ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_search(), Parameters::check() must be invoked" ); - - if ( i != 1 && i != 2 ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_search(i), i must be 1 or 2" ); - - return ( i == 1 ) ? _model_params.search1 : _model_params.search2; -} - -// has_model_search: -bool NOMAD::Parameters::has_model_search ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_model_search(), Parameters::check() must be invoked" ); - return _model_params.search1 != NOMAD::NO_MODEL; -} - -// get_model_search_optimistic: -bool NOMAD::Parameters::get_model_search_optimistic ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_search_optimistic(), Parameters::check() must be invoked" ); - return _model_params.search_optimistic; -} - -// get_model_search_proj_to_mesh: -bool NOMAD::Parameters::get_model_search_proj_to_mesh ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_search_proj_to_mesh(), Parameters::check() must be invoked" ); - return _model_params.search_proj_to_mesh; -} - -// get_model_quad_radius_factor: -const NOMAD::Double & NOMAD::Parameters::get_model_quad_radius_factor ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_quad_radius_factor(), Parameters::check() must be invoked" ); - return _model_params.quad_radius_factor; -} - -// get_model_quad_use_WP: -bool NOMAD::Parameters::get_model_quad_use_WP ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_quad_use_WP(), Parameters::check() must be invoked" ); - return _model_params.quad_use_WP; -} - -// get_model_quad_max_Y_size: -int NOMAD::Parameters::get_model_quad_max_Y_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_quad_max_Y_size(), Parameters::check() must be invoked" ); - return _model_params.quad_max_Y_size; -} - -// get_model_np1_quad_epsilon: -const NOMAD::Double & NOMAD::Parameters::get_model_np1_quad_epsilon ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_np1_quad_epsilon(), Parameters::check() must be invoked" ); - return _model_params.model_np1_quad_epsilon; -} - - -// get_model_quad_min_Y_size: -int NOMAD::Parameters::get_model_quad_min_Y_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_quad_min_Y_size(), Parameters::check() must be invoked" ); - return _model_params.quad_min_Y_size; -} - -// get_model_tgp_mode: -NOMAD::TGP_mode_type NOMAD::Parameters::get_model_tgp_mode ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_tgp_mode(), Parameters::check() must be invoked" ); - return _model_params.tgp_mode; -} - -// get_model_tgp_reuse_model: -bool NOMAD::Parameters::get_model_tgp_reuse_model ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_tgp_reuse_model(), Parameters::check() must be invoked" ); - return _model_params.tgp_reuse_model; -} - -// get_model_search_max_trial_pts: -int NOMAD::Parameters::get_model_search_max_trial_pts ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_search_max_trial_pts(), Parameters::check() must be invoked" ); - return _model_params.search_max_trial_pts; -} - -// get_model_eval_sort: -NOMAD::model_type NOMAD::Parameters::get_model_eval_sort ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_eval_sort(), Parameters::check() must be invoked" ); - return _model_params.eval_sort; -} - - - -// get_model_eval_sort_cautious: -bool NOMAD::Parameters::get_model_eval_sort_cautious ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_model_eval_sort_cautious(), Parameters::check() must be invoked" ); - return _model_params.eval_sort_cautious; -} - -// get_VNS_search: -bool NOMAD::Parameters::get_VNS_search ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_VNS_search(), Parameters::check() must be invoked" ); - return _VNS_search; -} - -// get_VNS_trigger: -const NOMAD::Double & NOMAD::Parameters::get_VNS_trigger ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_VNS_trigger(), Parameters::check() must be invoked" ); - return _VNS_trigger; -} - -// get_LH_search_p0: -int NOMAD::Parameters::get_LH_search_p0 ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_LH_search_p0(), Parameters::check() must be invoked" ); - return _LH_search_p0; -} - -// get_LH_search_p0: -int NOMAD::Parameters::get_LH_search_pi ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_LH_search_pi(), Parameters::check() must be invoked" ); - return _LH_search_pi; -} - -// get_direction_types: -const std::set & -NOMAD::Parameters::get_direction_types ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_direction_types(), Parameters::check() must be invoked" ); - return _direction_types; -} - -// get_sec_poll_dir_types: -const std::set & -NOMAD::Parameters::get_sec_poll_dir_types ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_sec_poll_dir_types(), Parameters::check() must be invoked" ); - return _sec_poll_dir_types; -} - -// check if there are Ortho-MADS directions: -bool NOMAD::Parameters::has_orthomads_directions ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_orthomads_directions(), Parameters::check() must be invoked" ); - bool use_ortho_mads = NOMAD::dirs_have_orthomads ( _direction_types ); - if ( !use_ortho_mads ) - use_ortho_mads = NOMAD::dirs_have_orthomads ( _sec_poll_dir_types ); - return use_ortho_mads; -} - - -// check if there are dynamic directions to complete the (n+1)th direction: -bool NOMAD::Parameters::has_dynamic_direction ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_dynamic_direction(), Parameters::check() must be invoked" ); - - return (has_direction_type(NOMAD::ORTHO_NP1_QUAD) || has_direction_type(NOMAD::ORTHO_NP1_NEG)); -} - -// check that a given direction type is present (private) -bool NOMAD::Parameters::has_direction_type ( NOMAD::direction_type dt ) const -{ - std::set::const_iterator it , end = _direction_types.end(); - for ( it = _direction_types.begin() ; it != end ; ++it ) - if ( (*it)==dt) - return true; - return false; -} - - -// anisotropic mesh : -bool NOMAD::Parameters::get_anisotropic_mesh ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_anisotropic_mesh, Parameters::check() must be invoked" ); - return _anisotropic_mesh; -} - - -// smesh: -bool NOMAD::Parameters::get_use_smesh ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_use_smesh, Parameters::check() must be invoked" ); - return _use_smesh; -} - - -// get_mesh_update_basis: -const NOMAD::Double & NOMAD::Parameters::get_mesh_update_basis ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_mesh_update_basis(), Parameters::check() must be invoked" ); - return _mesh_update_basis; -} - -// get_poll_update_basis: -const NOMAD::Double & NOMAD::Parameters::get_poll_update_basis ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_poll_update_basis(), Parameters::check() must be invoked" ); - return _poll_update_basis; -} - -// get_mesh_coarsening_exponent: -int NOMAD::Parameters::get_mesh_coarsening_exponent ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_mesh_coarsening_exponent(), Parameters::check() must be invoked" ); - return _mesh_coarsening_exponent; -} - -// get_mesh_refining_exponent: -int NOMAD::Parameters::get_mesh_refining_exponent ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_mesh_refining_exponent(), Parameters::check() must be invoked" ); - return _mesh_refining_exponent; -} - -// get_initial_mesh_index: -int NOMAD::Parameters::get_initial_mesh_index ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_initial_mesh_index(), Parameters::check() must be invoked" ); - return _initial_mesh_index; -} - -// get_initial_mesh_size: -const NOMAD::Point & NOMAD::Parameters::get_initial_mesh_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_initial_mesh_size(), Parameters::check() must be invoked" ); - return _initial_mesh_size; -} - -// get_initial_poll_size: -const NOMAD::Point & NOMAD::Parameters::get_initial_poll_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_initial_poll_size(), Parameters::check() must be invoked" ); - return _initial_poll_size; -} - -// get_min_mesh_size: -const NOMAD::Point & NOMAD::Parameters::get_min_mesh_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_min_mesh_size(), Parameters::check() must be invoked" ); - return _min_mesh_size; -} - -// get_min_poll_size: -const NOMAD::Point & NOMAD::Parameters::get_min_poll_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_min_poll_size(), Parameters::check() must be invoked" ); - return _min_poll_size; -} - -// get_min_poll_size_defined: -bool NOMAD::Parameters::get_min_poll_size_defined ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_min_poll_size_defined(), Parameters::check() must be invoked" ); - return _min_poll_size_defined; -} - -// get_neighbors_exe: -const std::string & NOMAD::Parameters::get_neighbors_exe ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_neighbors_exe(), Parameters::check() must be invoked" ); - return _neighbors_exe; -} - -// get_extended_poll_trigger: -const NOMAD::Double & NOMAD::Parameters::get_extended_poll_trigger ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_extended_poll_trigger(), Parameters::check() must be invoked" ); - return _extended_poll_trigger; -} - -// get_relative_ept: -bool NOMAD::Parameters::get_relative_ept ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_relative_ept(), Parameters::check() must be invoked" ); - return _relative_ept; -} - -// get_extended_poll_enabled: -bool NOMAD::Parameters::get_extended_poll_enabled ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_extended_poll_enabled(), Parameters::check() must be invoked" ); - return _extended_poll_enabled; -} - -// get_user_calls_enabled: -bool NOMAD::Parameters::get_user_calls_enabled ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_user_calls_enabled(), Parameters::check() must be invoked" ); - return _user_calls_enabled; -} - -// get_asynchronous: -bool NOMAD::Parameters::get_asynchronous ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_asynchronous(), Parameters::check() must be invoked" ); - return _asynchronous; -} - -// get_x0s: -const std::vector & NOMAD::Parameters::get_x0s ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_x0s(), Parameters::check() must be invoked" ); - return _x0s; -} - -// get_x0_cache_file: -const std::string & NOMAD::Parameters::get_x0_cache_file ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_x0_cache_file(), Parameters::check() must be invoked" ); - return _x0_cache_file; -} - -// get_lb: -const NOMAD::Point & NOMAD::Parameters::get_lb ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_lb(), Parameters::check() must be invoked" ); - return _lb; -} - -// get_ub: -const NOMAD::Point & NOMAD::Parameters::get_ub ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_ub(), Parameters::check() must be invoked" ); - return _ub; -} - -// get_scaling: -const NOMAD::Point & NOMAD::Parameters::get_scaling ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_scaling(), Parameters::check() must be invoked" ); - return _scaling; -} - -// get_fixed_variables: -const NOMAD::Point & NOMAD::Parameters::get_fixed_variables ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_fixed_variables(), Parameters::check() must be invoked" ); - return _fixed_variables; -} - -// variable_is_fixed: -bool NOMAD::Parameters::variable_is_fixed ( int index ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::variable_is_fixed(), Parameters::check() must be invoked" ); - if ( index < 0 || index >= _fixed_variables.size() ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::variable_is_fixed(), bad variable index" ); - return _fixed_variables[index].is_defined(); -} - -// get_bb_nb_outputs: -int NOMAD::Parameters::get_bb_nb_outputs ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_nb_outputs(), Parameters::check() must be invoked" ); - return static_cast(_bb_output_type.size()); -} - -// get_bb_exe: -const std::list & NOMAD::Parameters::get_bb_exe ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_exe(), Parameters::check() must be invoked" ); - return _bb_exe; -} - -// get_sgte_eval_sort: -bool NOMAD::Parameters::get_sgte_eval_sort ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_sgte_eval_sort(), Parameters::check() must be invoked" ); - return _sgte_eval_sort; -} - -// has_sgte: -bool NOMAD::Parameters::has_sgte ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_sgte(), Parameters::check() must be invoked" ); - return _has_sgte; -} - -// get_opt_only_sgte: -bool NOMAD::Parameters::get_opt_only_sgte ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opt_only_sgte(), Parameters::check() must be invoked" ); - return _opt_only_sgte; -} - -// has_sgte_exe: -bool NOMAD::Parameters::has_sgte_exe ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_sgte_exe(), Parameters::check() must be invoked" ); - return !_sgte_exe.empty(); -} - -// get_sgte_cost: -int NOMAD::Parameters::get_sgte_cost ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_sgte_cost(), Parameters::check() must be invoked" ); - return _sgte_cost; -} - -// get_sgte_exe (returns an empty string if bb_exe has no surrogate): -std::string NOMAD::Parameters::get_sgte_exe ( const std::string & bb_exe ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_sgte_exe(), Parameters::check() must be invoked" ); - std::map::const_iterator it = _sgte_exe.find(bb_exe); - std::string s; - if ( it != _sgte_exe.end() ) - s = it->second; - return s; -} - -// get_index_obj: -const std::list & NOMAD::Parameters::get_index_obj ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_index_obj(), Parameters::check() must be invoked" ); - return _index_obj; -} - -// get_nb_obj: -int NOMAD::Parameters::get_nb_obj ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_nb_obj(), Parameters::check() must be invoked" ); - return static_cast(_index_obj.size()); -} - -// get_bb_input_include_tag: -bool NOMAD::Parameters::get_bb_input_include_tag ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_input_include_tag(), Parameters::check() must be invoked" ); - return _bb_input_include_tag; -} - -// get_bb_input_include_seed: -bool NOMAD::Parameters::get_bb_input_include_seed ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_input_include_seed(), Parameters::check() must be invoked" ); - return _bb_input_include_seed; -} - -// get_bb_redirection: -bool NOMAD::Parameters::get_bb_redirection ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_redirection(), Parameters::check() must be invoked" ); - return _bb_redirection; -} - -// get_bb_input_type: -const std::vector & -NOMAD::Parameters::get_bb_input_type ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_input_type(), Parameters::check() must be invoked" ); - return _bb_input_type; -} - -// get_bb_output_type: -const std::vector & -NOMAD::Parameters::get_bb_output_type ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_output_type(), Parameters::check() must be invoked" ); - return _bb_output_type; -} - -// get_seed: -int NOMAD::Parameters::get_seed ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_seed(), Parameters::check() must be invoked" ); - return _seed; -} - -// get_display_all_eval: -bool NOMAD::Parameters::get_display_all_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_display_all_eval(), Parameters::check() must be invoked" ); - return _display_all_eval; -} - -// get_display_stats: -const std::list & NOMAD::Parameters::get_display_stats ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_display_stats(), Parameters::check() must be invoked" ); - return _display_stats; -} - -// get_stats_file_name: -const std::string & NOMAD::Parameters::get_stats_file_name ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_stats_file_name(), Parameters::check() must be invoked" ); - return _stats_file_name; -} - -// get_stats_file: -const std::list & NOMAD::Parameters::get_stats_file ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_stats_file(), Parameters::check() must be invoked" ); - return _stats_file; -} - -// get_point_display_limit: -int NOMAD::Parameters::get_point_display_limit ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_point_display_limit(), Parameters::check() must be invoked" ); - return NOMAD::Point::get_display_limit(); -} - -// out (ex get_display()): -const NOMAD::Display & NOMAD::Parameters::out ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::out(), Parameters::check() must be invoked" ); - return _out; -} - -// get_display_degree 1/2: -void NOMAD::Parameters::get_display_degree ( std::string & d ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_display_degree(), Parameters::check() must be invoked" ); - _out.get_display_degree ( d ); -} - -// get_display_degree 2/2: -int NOMAD::Parameters::get_display_degree ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_display_degree(), Parameters::check() must be invoked" ); - return _out.get_gen_dd(); -} - -// get_max_eval: -int NOMAD::Parameters::get_max_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_eval(), Parameters::check() must be invoked" ); - return _max_eval; -} - -// get_max_bb_eval: -int NOMAD::Parameters::get_max_bb_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_bb_eval(), Parameters::check() must be invoked" ); - return _max_bb_eval; -} - -// get_max_sim_bb_eval: -int NOMAD::Parameters::get_max_sim_bb_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_sim_bb_eval(), Parameters::check() must be invoked" ); - return _max_sim_bb_eval; -} - -// get_max_sgte_eval: -int NOMAD::Parameters::get_max_sgte_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_sgte_eval(), Parameters::check() must be invoked" ); - return _sgte_max_eval; -} - -// get_max_time: -int NOMAD::Parameters::get_max_time ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_time(), Parameters::check() must be invoked" ); - return _max_time; -} - -// get_max_iterations: -int NOMAD::Parameters::get_max_iterations ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_iterations(), Parameters::check() must be invoked" ); - return _max_iterations; -} - -// get_max_consecutive_failed_iterations: -int NOMAD::Parameters::get_max_consecutive_failed_iterations ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_consecutive_failed_iterations(), Parameters::check() must be invoked" ); - return _max_cons_failed_it; -} - -// get_max_cache_memory: -float NOMAD::Parameters::get_max_cache_memory ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_max_cache_memory(), Parameters::check() must be invoked" ); - return _max_cache_memory; -} - -// get_cache_save_period: -int NOMAD::Parameters::get_cache_save_period ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_cache_save_period(), Parameters::check() must be invoked" ); - return _cache_save_period; -} - -// get_stop_if_feasible: -bool NOMAD::Parameters::get_stop_if_feasible ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_stop_if_feasible(), Parameters::check() must be invoked" ); - return _stop_if_feasible; -} - -// get_f_target: -const NOMAD::Point & NOMAD::Parameters::get_f_target ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_f_target(), Parameters::check() must be invoked" ); - return _f_target; -} - -// get_stat_sum_target: -const NOMAD::Double & NOMAD::Parameters::get_stat_sum_target ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_stat_sum_target(), Parameters::check() must be invoked" ); - return _stat_sum_target; -} - -// get_L_curve_target: -const NOMAD::Double & NOMAD::Parameters::get_L_curve_target ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_L_curve_target(), Parameters::check() must be invoked" ); - return _L_curve_target; -} - -// get_problem_dir: -const std::string & NOMAD::Parameters::get_problem_dir ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_problem_dir(), Parameters::check() must be invoked" ); - return _problem_dir; -} - -// get_tmp_dir: -const std::string & NOMAD::Parameters::get_tmp_dir ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_tmp_dir(), Parameters::check() must be invoked" ); - return _tmp_dir; -} - -// get_solution_file: -const std::string & NOMAD::Parameters::get_solution_file ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_solution_file(), Parameters::check() must be invoked" ); - return _solution_file; -} - -// get_history_file: -const std::string & NOMAD::Parameters::get_history_file ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_history_file(), Parameters::check() must be invoked" ); - return _history_file; -} - -// get_cache_file: -const std::string & NOMAD::Parameters::get_cache_file ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_cache_file(), Parameters::check() must be invoked" ); - return _cache_file; -} - -// get_sgte_cache_file: -const std::string & NOMAD::Parameters::get_sgte_cache_file ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_sgte_cache_file(), Parameters::check() must be invoked" ); - return _sgte_cache_file; -} - -// get_rho: -const NOMAD::Double & NOMAD::Parameters::get_rho ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_rho(), Parameters::check() must be invoked" ); - return _rho; -} - -// get_h_min: -const NOMAD::Double & NOMAD::Parameters::get_h_min ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_h_min(), Parameters::check() must be invoked" ); - return _h_min; -} - -// get_h_max_0: -const NOMAD::Double & NOMAD::Parameters::get_h_max_0 ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_h_max_0(), Parameters::check() must be invoked" ); - return _h_max_0; -} - -// get_h_norm: -NOMAD::hnorm_type NOMAD::Parameters::get_h_norm ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_h_norm(), Parameters::check() must be invoked" ); - return _h_norm; -} - -// use_sec_poll_center: -bool NOMAD::Parameters::use_sec_poll_center ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::use_second_poll_center(), Parameters::check() must be invoked" ); - return _barrier_type == NOMAD::PB || _barrier_type == NOMAD::PEB_P; -} - -// get_barrier_type: -NOMAD::bb_output_type NOMAD::Parameters::get_barrier_type ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_filter_type(), Parameters::check() must be invoked" ); - return _barrier_type; -} - -// has_constraints: -bool NOMAD::Parameters::has_constraints ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_constraints(), Parameters::check() must be invoked" ); - return _has_constraints; -} - -// has_EB_constraints: -bool NOMAD::Parameters::has_EB_constraints ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::has_EB_constraints(), Parameters::check() must be invoked" ); - return _has_EB_constraints; -} - -// get_multi_nb_mads_runs: -int NOMAD::Parameters::get_multi_nb_mads_runs ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_multi_nb_mads_runs(), Parameters::check() must be invoked" ); - return _multi_nb_mads_runs; -} - -// get_multi_overall_bb_eval: -int NOMAD::Parameters::get_multi_overall_bb_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_multi_overall_bb_eval(), Parameters::check() must be invoked" ); - return _multi_overall_bb_eval; -} - -// get_multi_use_delta_crit: -bool NOMAD::Parameters::get_multi_use_delta_crit ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_multi_use_delta_crit(), Parameters::check() must be invoked" ); - return _multi_use_delta_crit; -} - -// get_multi_f_bounds: -const NOMAD::Point & NOMAD::Parameters::get_multi_f_bounds ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_multi_f_bounds(), Parameters::check() must be invoked" ); - return _multi_f_bounds; -} - -// get_multi_formulation: -NOMAD::multi_formulation_type NOMAD::Parameters::get_multi_formulation ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_multi_formulation(), Parameters::check() must be invoked" ); - return _multi_formulation; -} - -// get_opportunistic_cache_search: -bool NOMAD::Parameters::get_opportunistic_cache_search ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_cache_search(), Parameters::check() must be invoked" ); - return _opportunistic_cache_search; -} - -// get_opportunistic_LH: -bool NOMAD::Parameters::get_opportunistic_LH ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_LH(), Parameters::check() must be invoked" ); - return _opportunistic_LH; -} - -// get_opportunistic_eval: -bool NOMAD::Parameters::get_opportunistic_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_eval(), Parameters::check() must be invoked" ); - return _opportunistic_eval; -} - -// get_opportunistic_min_nb_success -int NOMAD::Parameters::get_opportunistic_min_nb_success ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_min_nb_success(), Parameters::check() must be invoked"); - return _opportunistic_min_nb_success; -} - -// get_opportunistic_min_eval -int NOMAD::Parameters::get_opportunistic_min_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_min_eval(), Parameters::check() must be invoked" ); - return _opportunistic_min_eval; -} - -// get_bb_max_block_size -int NOMAD::Parameters::get_bb_max_block_size ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_bb_max_block_size(), Parameters::check() must be invoked" ); - return _bb_max_block_size; -} - - -// get_opportunistic_min_f_imprvmt -const NOMAD::Double & NOMAD::Parameters::get_opportunistic_min_f_imprvmt ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_min_f_imprvmt(), Parameters::check() must be invoked" ); - return _opportunistic_min_f_imprvmt; -} - -// get_opportunistic_lucky_eval: -bool NOMAD::Parameters::get_opportunistic_lucky_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_opportunistic_lucky_eval(), Parameters::check() must be invoked" ); - return _opportunistic_lucky_eval; -} - -// check_stat_sum: -bool NOMAD::Parameters::check_stat_sum ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::check_stat_sum(), Parameters::check() must be invoked" ); - return ( _index_stat_sum >= 0 ); -} - -// check_stat_avg: -bool NOMAD::Parameters::check_stat_avg ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::check_stat_avg(), Parameters::check() must be invoked" ); - return ( _index_stat_avg >= 0 ); -} - -// get_index_stat_sum: -int NOMAD::Parameters::get_index_stat_sum ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_index_stat_sum(), Parameters::check() must be invoked" ); - return _index_stat_sum; -} - -// get_index_stat_avg: -int NOMAD::Parameters::get_index_stat_avg ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_index_stat_avg(), Parameters::check() must be invoked" ); - return _index_stat_avg; -} - -// get_index_cnt_eval: -int NOMAD::Parameters::get_index_cnt_eval ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_index_cnt_eval(), Parameters::check() must be invoked" ); - return _index_cnt_eval; -} - -// get_periodic_variables: -const std::vector & NOMAD::Parameters::get_periodic_variables ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_periodic_variables(), Parameters::check() must be invoked" ); - return _periodic_variables; -} - -// get_variable_groups: -const std::set & -NOMAD::Parameters::get_variable_groups ( void ) const -{ - if ( _to_be_checked ) - throw Bad_Access ( "Parameters.cpp" , __LINE__ , - "Parameters::get_variable_groups(), Parameters::check() must be invoked" ); - return _var_groups; -} - -/*----------------------------------------*/ -/* SET methods */ -/*----------------------------------------*/ - -// set_POINT_DISPLAY_LIMIT: -void NOMAD::Parameters::set_POINT_DISPLAY_LIMIT ( int dl ) -{ - NOMAD::Point::set_display_limit ( dl ); -} - -// set_DIMENSION: -bool NOMAD::Parameters::set_DIMENSION ( int dim ) -{ - if ( _dimension > 0 ) { - _dimension = -1; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIMENSION - defined twice" ); - return false; - } - - _to_be_checked = true; - _dimension = dim; - if ( _dimension <= 0 ) { - _dimension = -1; - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIMENSION" ); - return false; - } - - // all variables are initially considered continuous: - _bb_input_type.resize ( _dimension ); - for ( int i = 0 ; i < _dimension ; ++i ) - _bb_input_type[i] = NOMAD::CONTINUOUS; - - // resize of _initial_mesh_size: - _initial_mesh_size.reset ( _dimension ); - _initial_poll_size.reset ( _dimension ); - - return true; -} - -// set_EXTERN_SIGNATURE (set a new extern signature and -// delete the standard signature): -void NOMAD::Parameters::set_EXTERN_SIGNATURE ( NOMAD::Signature * s ) -{ - if ( _std_signature && s == _std_signature ) - return; - - // standard signature: - delete _std_signature; - _std_signature = NULL; - _extern_signature = s; - - // dimension: - _dimension = -1; - set_DIMENSION ( s->get_n() ); - - // input types: - set_BB_INPUT_TYPE ( s->get_input_types() ); - - // bounds: - set_LOWER_BOUND ( s->get_lb() ); - set_UPPER_BOUND ( s->get_ub() ); - - // scaling: - set_SCALING ( s->get_scaling() ); - - // fixed variables: - set_FIXED_VARIABLE ( s->get_fixed_variables() ); - - // periodic variables: - set_PERIODIC_VARIABLE ( s->get_periodic_variables() ); - - // variable groups: - reset_variable_groups(); - set_VARIABLE_GROUP ( s->get_var_groups() ); - - _to_be_checked = true; -} - -// set_SNAP_TO_BOUNDS: -void NOMAD::Parameters::set_SNAP_TO_BOUNDS ( bool stb ) -{ - _to_be_checked = true; - _snap_to_bounds = stb; -} - -// set_SPECULATIVE_SEARCH: -void NOMAD::Parameters::set_SPECULATIVE_SEARCH ( bool ss ) -{ - _to_be_checked = true; - _speculative_search = ss; -} - -// set_CACHE_SEARCH: -void NOMAD::Parameters::set_CACHE_SEARCH ( bool s ) -{ - _to_be_checked = true; - _cache_search = s; -} - -// Disable use of models -void NOMAD::Parameters::set_DISABLE_MODELS ( void ) -{ - _disable_models=true; -} - -// Disable use of models -void NOMAD::Parameters::set_DISABLE_EVAL_SORT ( void ) -{ - _disable_eval_sort=true; -} - -// set all the models parameters: -void NOMAD::Parameters::set_model_parameters ( const NOMAD::model_params_type & mp ) -{ - _to_be_checked = true; - set_MODEL_SEARCH ( 1 , mp.search1 ); - set_MODEL_SEARCH ( 2 , mp.search2 ); - set_MODEL_EVAL_SORT ( mp.eval_sort ); - set_MODEL_SEARCH_OPTIMISTIC ( mp.search_optimistic ); - set_MODEL_SEARCH_PROJ_TO_MESH ( mp.search_proj_to_mesh ); - set_MODEL_SEARCH_MAX_TRIAL_PTS ( mp.search_max_trial_pts ); - set_MODEL_EVAL_SORT_CAUTIOUS ( mp.eval_sort_cautious ); - set_MODEL_QUAD_RADIUS_FACTOR ( mp.quad_radius_factor ); - set_MODEL_QUAD_USE_WP ( mp.quad_use_WP ); - set_MODEL_QUAD_MIN_Y_SIZE ( mp.quad_min_Y_size ); - set_MODEL_QUAD_MAX_Y_SIZE ( mp.quad_max_Y_size ); - set_MODEL_TGP_MODE ( mp.tgp_mode ); - set_MODEL_TGP_REUSE_MODEL ( mp.tgp_reuse_model ); -} - -// set_MODEL_SEARCH (1/3): -void NOMAD::Parameters::set_MODEL_SEARCH ( int i , NOMAD::model_type ms ) -{ - _to_be_checked = true; - -#ifndef USE_TGP - if ( ms == NOMAD::TGP_MODEL ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_SEARCH: this version has not been compiled for TGP" ); -#endif - - if ( i != 1 && i != 2 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "NOMAD::Parameters::set_MODEL_SEARCH(i,m): bad value for argument i (must be 1 or 2)" ); - - if ( i == 1 ) { - if ( _model_params.search2 != NOMAD::NO_MODEL ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "NOMAD::Parameters::set_MODEL_SEARCH(1,m): already a second model search" ); - - _model_params.search1 = ms; - } - else { - - if ( _model_params.search1 == NOMAD::NO_MODEL && ms != NOMAD::NO_MODEL ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "NOMAD::Parameters::set_MODEL_SEARCH(2,m): no first model search" ); - - if ( _model_params.search1 != NOMAD::NO_MODEL && _model_params.search1 == ms ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "NOMAD::Parameters::set_MODEL_SEARCH(2,m): second model search of the same type" ); - - _model_params.search2 = ms; - } -} - -// set_MODEL_SEARCH (2/3): -void NOMAD::Parameters::set_MODEL_SEARCH ( bool ms ) -{ - if ( ms ) { - set_MODEL_SEARCH ( 1 , NOMAD::QUADRATIC_MODEL ); - set_MODEL_SEARCH ( 2 , NOMAD::NO_MODEL ); - } - else { - set_MODEL_SEARCH ( 1 , NOMAD::NO_MODEL ); - set_MODEL_SEARCH ( 2 , NOMAD::NO_MODEL ); - } -} - -// set_MODEL_SEARCH (3/3): -void NOMAD::Parameters::set_MODEL_SEARCH ( NOMAD::model_type ms ) -{ - set_MODEL_SEARCH ( 1 , ms ); - set_MODEL_SEARCH ( 2 , NOMAD::NO_MODEL ); -} - - -// set_MODEL_EVAL_SORT (1/2): -void NOMAD::Parameters::set_MODEL_EVAL_SORT ( NOMAD::model_type mes ) -{ -#ifndef USE_TGP - if ( mes == NOMAD::TGP_MODEL ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_EVAL_SORT: this version has not been compiled for TGP" ); -#endif - _to_be_checked = true; - _model_params.eval_sort = mes; -} - -// set_MODEL_EVAL_SORT (2/2): -void NOMAD::Parameters::set_MODEL_EVAL_SORT ( bool mes ) -{ - if ( mes ) - set_MODEL_EVAL_SORT ( NOMAD::QUADRATIC_MODEL ); - else - set_MODEL_EVAL_SORT ( NOMAD::NO_MODEL ); -} - - -// set_MODEL_SEARCH_OPTIMISTIC: -void NOMAD::Parameters::set_MODEL_SEARCH_OPTIMISTIC ( bool mso ) -{ - _to_be_checked = true; - _model_params.search_optimistic = mso; -} - -// set_MODEL_SEARCH_PROJ_TO_MESH: -void NOMAD::Parameters::set_MODEL_SEARCH_PROJ_TO_MESH ( bool ptm ) -{ - _to_be_checked = true; - _model_params.search_proj_to_mesh = ptm; -} - -// set_MODEL_QUAD_RADIUS_FACTOR: -void NOMAD::Parameters::set_MODEL_QUAD_RADIUS_FACTOR ( const NOMAD::Double & r ) -{ - _to_be_checked = true; - _model_params.quad_radius_factor = r; -} - -// set_MODEL_QUAD_USE_WP: -void NOMAD::Parameters::set_MODEL_QUAD_USE_WP ( bool uwp ) -{ - _to_be_checked = true; - _model_params.quad_use_WP = uwp; -} - -// set_MODEL_QUAD_MAX_Y_SIZE: -void NOMAD::Parameters::set_MODEL_QUAD_MAX_Y_SIZE ( int s ) -{ - _to_be_checked = true; - _model_params.quad_max_Y_size = s; -} - -// set_MODEL_QUAD_MIN_Y_SIZE: -void NOMAD::Parameters::set_MODEL_QUAD_MIN_Y_SIZE ( int s ) -{ - _to_be_checked = true; - _model_params.quad_min_Y_size = (s < 0) ? -1 : s; -} - -// set_MODEL_QUAD_HYPERCUBE_LOWER_LIM: -void NOMAD::Parameters::set_MODEL_NP1_QUAD_EPSILON ( const NOMAD::Double & d ) -{ - _to_be_checked = true; - _model_params.model_np1_quad_epsilon = d; -} - - - -// set_MODEL_TGP_MODE: -void NOMAD::Parameters::set_MODEL_TGP_MODE ( NOMAD::TGP_mode_type m ) -{ - if ( m == NOMAD::TGP_USER ) { - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MODEL_TGP_MODE: the TGP user mode is only a debugging option" ); - } - - _to_be_checked = true; - _model_params.tgp_mode = m; -} - -// set_MODEL_TGP_REUSE_MODEL: -void NOMAD::Parameters::set_MODEL_TGP_REUSE_MODEL ( bool rm ) -{ - _to_be_checked = true; - _model_params.tgp_reuse_model = rm; -} - -// set_MODEL_SEARCH_MAX_TRIAL_PTS: -void NOMAD::Parameters::set_MODEL_SEARCH_MAX_TRIAL_PTS ( int s ) -{ - _to_be_checked = true; - _model_params.search_max_trial_pts = s; -} - -// set_MODEL_EVAL_SORT_CAUTIOUS: -void NOMAD::Parameters::set_MODEL_EVAL_SORT_CAUTIOUS ( bool mesc ) -{ - _to_be_checked = true; - _model_params.eval_sort_cautious = mesc; -} - -// set_VNS_SEARCH (1/2): -void NOMAD::Parameters::set_VNS_SEARCH ( bool s ) -{ - _to_be_checked = true; - _VNS_search = s; - _VNS_trigger = ( s ) ? 0.75 : NOMAD::Double(); -} - -// set_VNS_SEARCH (2/2): -void NOMAD::Parameters::set_VNS_SEARCH ( const NOMAD::Double & trigger ) -{ - _to_be_checked = true; - if ( !trigger.is_defined() ) { - _VNS_search = false; - return; - } - - if ( trigger < 0.0 || trigger > 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VNS_SEARCH: must be in [0;1]" ); - - _VNS_search = ( trigger > 0.0 ); - _VNS_trigger = trigger; -} - -// set_LH_SEARCH: -void NOMAD::Parameters::set_LH_SEARCH ( int p0 , int pi ) -{ - _to_be_checked = true; - _LH_search_p0 = (p0 <= 0 ) ? 0 : p0; - _LH_search_pi = (pi <= 0 ) ? 0 : pi; -} - -// set_DIRECTION_TYPE (1/2): -void NOMAD::Parameters::set_DIRECTION_TYPE ( NOMAD::direction_type dt ) -{ - _to_be_checked = true; - if ( dt == NOMAD::UNDEFINED_DIRECTION || - dt == NOMAD::NO_DIRECTION || - dt == NOMAD::MODEL_SEARCH_DIR ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: DIRECTION_TYPE" ); - _direction_types.insert ( dt ); -} - -// set_DIRECTION_TYPE (2/2): -void NOMAD::Parameters::set_DIRECTION_TYPE ( const std::set & dt ) -{ - std::set::const_iterator it , end = dt.end(); - for ( it = dt.begin() ; it != end ; ++it ) - set_DIRECTION_TYPE ( *it ); -} - -void NOMAD::Parameters::set_DIRECTION_TYPE_NO_MODEL ( void ) -{ - std::set::iterator it=_direction_types.find(NOMAD::ORTHO_NP1_QUAD); - std::set::iterator end = _direction_types.end(); - while (it != end) - { - _direction_types.erase(it); - _direction_types.insert(NOMAD::ORTHO_NP1_NEG); - it=_direction_types.find(NOMAD::ORTHO_NP1_QUAD); - } -} - - -// set_SEC_POLL_DIR_TYPE (1/2): -void NOMAD::Parameters::set_SEC_POLL_DIR_TYPE ( NOMAD::direction_type dt ) -{ - _to_be_checked = true; - if ( dt == NOMAD::UNDEFINED_DIRECTION || dt == NOMAD::MODEL_SEARCH_DIR ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SEC_POLL_DIR_TYPE" ); - _sec_poll_dir_types.insert ( dt ); -} - -// set_SEC_POLL_DIR_TYPE (2/2): -void NOMAD::Parameters::set_SEC_POLL_DIR_TYPE -( const std::set & dt ) { - std::set::const_iterator it , end = dt.end(); - for ( it = dt.begin() ; it != end ; ++it ) - set_SEC_POLL_DIR_TYPE ( *it ); -} - - -// set_RHO: -void NOMAD::Parameters::set_RHO ( const NOMAD::Double & rho ) -{ - if ( !rho.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: RHO" ); - _to_be_checked = true; - _rho = rho; -} - -// set_H_MIN: -void NOMAD::Parameters::set_H_MIN ( const NOMAD::Double & h_min ) -{ - if ( !h_min.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , "invalid parameter: H_MIN" ); - _to_be_checked = true; - _h_min = h_min; -} - -// set_H_MAX_0: -void NOMAD::Parameters::set_H_MAX_0 ( const NOMAD::Double & h_max ) -{ - _to_be_checked = true; - _h_max_0 = ( h_max.is_defined() ) ? h_max : NOMAD::INF; -} - -// set_H_NORM: -void NOMAD::Parameters::set_H_NORM ( NOMAD::hnorm_type h_norm ) -{ - _to_be_checked = true; - _h_norm = h_norm; -} - -// set_SCALING (1/2): -void NOMAD::Parameters::set_SCALING ( int index , const NOMAD::Double & value ) -{ - _to_be_checked = true; - if ( index < 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SCALING" ); - if ( index >= _scaling.size() ) - _scaling.resize ( index + 1 ); - - _scaling[index] = value; -} - -// set_SCALING (2/2): -void NOMAD::Parameters::set_SCALING ( const NOMAD::Point & s ) -{ - _to_be_checked = true; - _scaling = s; -} - -// set_FIXED_VARIABLE (1/3): -void NOMAD::Parameters::set_FIXED_VARIABLE ( int index , const NOMAD::Double & value ) -{ - _to_be_checked = true; - if ( index < 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE" ); - if ( index >= _fixed_variables.size() ) - _fixed_variables.resize ( index + 1 ); - - _fixed_variables[index] = value; -} - -// set_FIXED_VARIABLE (2/3): -void NOMAD::Parameters::set_FIXED_VARIABLE ( int index ) -{ - _to_be_checked = true; - if ( index < 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE (index < 0)" ); - if ( _x0s.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE (no starting point defined)" ); - - if ( index >= _x0s[0]->size() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: FIXED_VARIABLE (incompatible starting point)" ); - - if ( index >= _fixed_variables.size() ) - _fixed_variables.resize ( index + 1 ); - - _fixed_variables[index] = (*_x0s[0])[index]; -} - -// set_FIXED_VARIABLE (2/3): -void NOMAD::Parameters::set_FIXED_VARIABLE ( const NOMAD::Point & fv ) -{ - _to_be_checked = true; - _fixed_variables = fv; -} - -// set_LOWER_BOUND (1/2): -void NOMAD::Parameters::set_LOWER_BOUND ( int index, const NOMAD::Double & value ) -{ - _to_be_checked = true; - if (index < 0) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: LOWER_BOUND" ); - if ( index >= _lb.size() ) - _lb.resize(index+1); - if ( !_lb[index].is_defined() || value > _lb[index] ) - _lb[index] = value; -} - -// set_LOWER_BOUND (2/2): -void NOMAD::Parameters::set_LOWER_BOUND ( const NOMAD::Point & lb ) -{ - _to_be_checked = true; - _lb = lb; -} - -// set_UPPER_BOUND (1/2): -void NOMAD::Parameters::set_UPPER_BOUND ( int index, const NOMAD::Double & value ) -{ - _to_be_checked = true; - if (index < 0) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: UPPER_BOUND" ); - if ( index >= _ub.size() ) - _ub.resize (index + 1); - if ( !_ub[index].is_defined() || value < _ub[index] ) - _ub[index] = value; -} - -// set_UPPER_BOUND (2/2): -void NOMAD::Parameters::set_UPPER_BOUND ( const NOMAD::Point & ub ) -{ - _to_be_checked = true; - _ub = ub; -} - -// set_SGTE_COST: -void NOMAD::Parameters::set_SGTE_COST ( int c ) -{ - _to_be_checked = true; - _sgte_cost = ( c > 0 ) ? c : -1; -} - -// set_SGTE_EVAL_SORT: -void NOMAD::Parameters::set_SGTE_EVAL_SORT ( bool ses ) -{ - _to_be_checked = true; - _sgte_eval_sort = ses; -} - -// set_HAS_SGTET: -void NOMAD::Parameters::set_HAS_SGTE ( bool hs ) -{ - _to_be_checked = true; - _has_sgte = hs; -} - -// set_OPT_ONLY_SGTE: -void NOMAD::Parameters::set_OPT_ONLY_SGTE ( bool oos ) -{ - _to_be_checked = true; - _opt_only_sgte = oos; -} - -// set_SGTE_EXE: -void NOMAD::Parameters::set_SGTE_EXE ( const std::string & bb_exe , - const std::string & sgte_exe ) -{ - _to_be_checked = true; - _sgte_exe[bb_exe] = sgte_exe; -} - -// set_BB_EXE (1/3): -void NOMAD::Parameters::set_BB_EXE ( const std::string & bbexe ) -{ - _to_be_checked = true; - if ( _bb_output_type.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE - BB_OUTPUT_TYPE must be defined first" ); - _bb_exe.clear(); - size_t nk = _bb_output_type.size(); - for ( size_t k = 0 ; k < nk ; ++k ) - _bb_exe.push_back ( bbexe ); -} - -// set_BB_EXE (2/3): -void NOMAD::Parameters::set_BB_EXE ( int m , const std::string * bbexe ) -{ - _to_be_checked = true; - - if ( m <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE" ); - - if ( m != static_cast(_bb_output_type.size()) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE - number of names or BB_OUTPUT_TYPE undefined" ); - - size_t nk = _bb_output_type.size(); - for ( size_t k = 0 ; k < nk ; ++k ) - _bb_exe.push_back ( bbexe[k] ); -} - -// set_BB_EXE (3/3): -void NOMAD::Parameters::set_BB_EXE ( const std::list & bbexe ) -{ - _to_be_checked = true; - if ( !bbexe.empty() && bbexe.size() != _bb_output_type.size() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_EXE - number of names or BB_OUTPUT_TYPE undefined" ); - _bb_exe = bbexe; -} - -// set_BB_INPUT_INCLUDE_TAG: -void NOMAD::Parameters::set_BB_INPUT_INCLUDE_TAG ( bool bbiit ) -{ - _to_be_checked = true; - _bb_input_include_tag = bbiit; -} - -// set_BB_INPUT_INCLUDE_SEED: -void NOMAD::Parameters::set_BB_INPUT_INCLUDE_SEED ( bool bbiis ) -{ - _to_be_checked = true; - _bb_input_include_seed = bbiis; -} - -// set_BB_REDIRECTION: -void NOMAD::Parameters::set_BB_REDIRECTION ( bool bbr ) -{ - _to_be_checked = true; - _bb_redirection = bbr; -} - -// set_BB_INPUT_TYPE (1/3): -void NOMAD::Parameters::set_BB_INPUT_TYPE ( int index , NOMAD::bb_input_type bbit ) -{ - _to_be_checked = true; - if ( index < 0 || index >= _dimension || - static_cast(_bb_input_type.size()) != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_INPUT_TYPE" ); - _bb_input_type[index] = bbit; -} - -// set_BB_INPUT_TYPE (2/3): -void NOMAD::Parameters::set_BB_INPUT_TYPE -( const std::vector & bbit ) -{ - int n = static_cast(bbit.size()); - for ( int i = 0 ; i < n ; ++i ) - set_BB_INPUT_TYPE ( i , bbit[i] ); -} - -// set_BB_INPUT_TYPE (3/3): -void NOMAD::Parameters::set_BB_INPUT_TYPE -( const std::list & bbit ) -{ - int i = 0; - std::list::const_iterator it , end = bbit.end(); - for ( it = bbit.begin() ; it != end ; ++it , ++i ) - set_BB_INPUT_TYPE ( i , *it ); -} - -// reset_PEB_changes: -void NOMAD::Parameters::reset_PEB_changes ( void ) const -{ - size_t nk = _bb_output_type.size(); - for ( size_t k = 0 ; k < nk ; ++k ) - if ( _bb_output_type[k] == NOMAD::PEB_E ) - _bb_output_type[k] = NOMAD::PEB_P; -} - -// change PEB to PB constraints -void NOMAD::Parameters::change_PEB_to_PB ( void ) -{ - size_t nk = _bb_output_type.size(); - for ( size_t k = 0 ; k < nk ; ++k ) - if ( _bb_output_type[k] == NOMAD::PEB_P || _bb_output_type[k] == NOMAD::PEB_E ) - { - _bb_output_type[k] = NOMAD::PB; - _barrier_type = NOMAD::PB; - } -} - - - -// change_PEB_constraint_status: -void NOMAD::Parameters::change_PEB_constraint_status ( int index ) const -{ - if ( index < 0 || - index >= static_cast(_bb_output_type.size()) || - _bb_output_type[index] != NOMAD::PEB_P ) - throw NOMAD::Exception ( "Parameters.cpp" , __LINE__ , - "error in Parameters::change_PEB_constraint_status(i): bad i" ); - _bb_output_type[index] = NOMAD::PEB_E; -} - -// set_BB_OUTPUT_TYPE (1/2): -void NOMAD::Parameters::set_BB_OUTPUT_TYPE -( const std::list & bbot ) -{ - int i = 0; - std::vector bbot_vector ( bbot.size() ); - std::list::const_iterator end = bbot.end() , it; - for ( it = bbot.begin() ; it != end ; ++it ) - bbot_vector[i++] = *it; - set_BB_OUTPUT_TYPE ( bbot_vector ); -} - -// set_BB_OUTPUT_TYPE (2/2): -void NOMAD::Parameters::set_BB_OUTPUT_TYPE -( const std::vector & bbot ) -{ - _to_be_checked = true; - - _barrier_type = NOMAD::EB; - _has_constraints = false; - _has_EB_constraints = false; - _has_filter_constraints = false; - - _bb_output_type.clear(); - - int m = static_cast(bbot.size()); - - if ( m <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE" ); - if ( !_bb_output_type.empty() && - m != static_cast(_bb_output_type.size()) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE - number of types" ); - - _bb_output_type.resize (m); - - bool filter_used = false; - bool pb_used = false; - bool peb_used = false; - - _index_obj.clear(); - - for ( int i = 0 ; i < m ; ++i ) - { - - _bb_output_type[i] = bbot[i]; - - switch ( bbot[i] ) - { - - case NOMAD::OBJ: - _index_obj.push_back(i); - break; - - case NOMAD::EB: - _has_constraints = true; - _has_EB_constraints = true; - break; - - case NOMAD::FILTER: - _has_constraints = true; - _has_filter_constraints = true; - filter_used = true; - break; - - case NOMAD::PB: - _has_constraints = true; - _has_filter_constraints = true; - pb_used = true; - break; - - case NOMAD::PEB_P: - case NOMAD::PEB_E: - _has_constraints = true; - _has_filter_constraints = true; - pb_used = true; - peb_used = true; - _bb_output_type[i] = NOMAD::PEB_P; - break; - default: - break; - } - } - - if ( _index_obj.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE - OBJ not given" ); - if ( filter_used && pb_used ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: BB_OUTPUT_TYPE - F and PB/PEB used together" ); - - if ( filter_used ) - _barrier_type = NOMAD::FILTER; - else if ( pb_used ) - _barrier_type = (peb_used) ? NOMAD::PEB_P : NOMAD::PB; -} - -// set_PROBLEM_DIR: -void NOMAD::Parameters::set_PROBLEM_DIR ( const std::string & dir ) -{ - _to_be_checked = true; - _problem_dir = dir; - if ( !_problem_dir.empty() && !NOMAD::Parameters::check_directory ( _problem_dir ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PROBLEM_DIR" ); -} - -// set_TMP_DIR: -void NOMAD::Parameters::set_TMP_DIR ( const std::string & dir ) -{ - _to_be_checked = true; - _tmp_dir = dir; - if ( !_tmp_dir.empty() && !NOMAD::Parameters::check_directory ( _tmp_dir ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: TMP_DIR" ); -} - -// set_ADD_SEED_TO_FILE_NAMES: -void NOMAD::Parameters::set_ADD_SEED_TO_FILE_NAMES ( bool astfn ) -{ - _to_be_checked = true; - _add_seed_to_file_names = astfn; -} - -// set_SOLUTION_FILE: -void NOMAD::Parameters::set_SOLUTION_FILE ( const std::string & sf ) -{ - _to_be_checked = true; - _solution_file = sf; - if ( sf.empty() ) - return; - if ( !NOMAD::Parameters::check_directory ( _solution_file ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SOLUTION_FILE" ); - _solution_file.resize ( _solution_file.size()-1 ); -} - -// set_HISTORY_FILE: -void NOMAD::Parameters::set_HISTORY_FILE ( const std::string & hf ) -{ - _to_be_checked = true; - _history_file = hf; - if ( hf.empty() ) - return; - if ( !NOMAD::Parameters::check_directory ( _history_file ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: HISTORY_FILE" ); - _history_file.resize ( _history_file.size()-1 ); -} - -// set_CACHE_FILE: -void NOMAD::Parameters::set_CACHE_FILE ( const std::string & cf ) -{ - _to_be_checked = true; - _cache_file = cf; - if ( cf.empty() ) - return; - if ( !NOMAD::Parameters::check_directory ( _cache_file ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: CACHE_FILE" ); - _cache_file.resize ( _cache_file.size()-1 ); -} - -// set_SGTE_CACHE_FILE: -void NOMAD::Parameters::set_SGTE_CACHE_FILE ( const std::string & cf ) -{ - _to_be_checked = true; - _sgte_cache_file = cf; - if ( cf.empty() ) - return; - if ( !NOMAD::Parameters::check_directory ( _sgte_cache_file ) ) { - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: SGTE_CACHE_FILE"); - } - _sgte_cache_file.resize ( _sgte_cache_file.size()-1 ); -} - -// set_X0: -// add a new point in the list of starting points: -void NOMAD::Parameters::set_X0 ( const NOMAD::Point & x0 ) -{ - _to_be_checked = true; - _x0s.push_back ( new NOMAD::Point ( x0 ) ); -} - -// indicate a x0 file or a cache file containing starting points: -void NOMAD::Parameters::set_X0 ( const std::string & file_name ) -{ - _to_be_checked = true; - - if ( file_name.empty() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::set_X0(file_name): file_name is empty" ); - - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "Parameters::set_X0() has been used before setting DIMENSION" ); - - NOMAD::Point tmp_x0 ( _dimension ); - std::string complete_file_name = _problem_dir + file_name; - std::ifstream fin ( complete_file_name.c_str() ); - - if ( fin.fail() ) { - std::string err = "invalid parameter: X0 - could not open file \'" - + complete_file_name + "\'"; - fin.close(); - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , err ); - } - - bool flag = true; - try { - fin >> tmp_x0; - } - catch ( NOMAD::Point::Bad_Input & ) { - flag = false; - - // we suppose that the file name corresponds to a cache file: - _x0_cache_file = file_name; - } - - while ( flag ) { - - set_X0 ( tmp_x0 ); - - // other starting points in the file ? - flag = true; - try { - fin >> tmp_x0; - } - catch ( NOMAD::Point::Bad_Input & ) { - flag = false; - } - } - - fin.close(); -} - -// set_DISPLAY_ALL_EVAL: -void NOMAD::Parameters::set_DISPLAY_ALL_EVAL ( bool dae ) -{ - _to_be_checked = true; - _display_all_eval = dae; -} - -// set_DISPLAY_STATS (1/2): -void NOMAD::Parameters::set_DISPLAY_STATS ( const std::list & ls ) -{ - _display_stats.clear(); - _display_stats = ls; -} - -// set_DISPLAY_STATS (2/2): -void NOMAD::Parameters::set_DISPLAY_STATS ( const std::string & stats ) -{ - if ( stats.empty() ) { - _display_stats.clear(); - return; - } - - NOMAD::Parameter_Entry pe ( "DISPLAY_STATS " + stats , false ); - - std::list::const_iterator end = pe.get_values().end() , - it = pe.get_values().begin(); - std::list ls; - - while ( it != end ) { - ls.push_back ( *it ); - ++it; - } - - ls.resize ( ls.size()-1 ); - - set_DISPLAY_STATS ( ls ); -} - -// set_STATS_FILE (1/2): -void NOMAD::Parameters::set_STATS_FILE ( const std::string & file_name , - const std::list & ls ) -{ - if ( file_name.empty() ) { - reset_stats_file(); - return; - } - - _to_be_checked = true; - _stats_file = ls; - _stats_file_name = file_name; - - if ( !NOMAD::Parameters::check_directory ( _stats_file_name ) ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: STATS_FILE" ); - - _stats_file_name.resize ( _stats_file_name.size()-1 ); -} - -// set_STATS_FILE (2/2): -void NOMAD::Parameters::set_STATS_FILE ( const std::string & file_name , - const std::string & stats ) -{ - NOMAD::Parameter_Entry pe ( "STATS_FILE " + file_name + " " + stats , false ); - std::list::const_iterator end = pe.get_values().end() , - it = pe.get_values().begin(); - std::list ls; - ++it; - while ( it != end ) { - ls.push_back(*it); - ++it; - } - - ls.resize ( ls.size()-1 ); - - set_STATS_FILE ( file_name , ls ); -} - -// set_DISPLAY_DEGREE (1/3) - (accepts also dd_type arguments): -bool NOMAD::Parameters::set_DISPLAY_DEGREE ( int dd ) -{ -#ifndef DEBUG - return set_DISPLAY_DEGREE ( NOMAD::itos(dd) ); -#endif - return true; -} - -// set_DISPLAY_DEGREE (2/3): -bool NOMAD::Parameters::set_DISPLAY_DEGREE ( const std::string & dd ) -{ -#ifndef DEBUG - { - std::string ddu = dd; - NOMAD::toupper ( ddu ); - - if ( ddu == "NO" || ddu == "NO_DISPLAY" ) { - set_DISPLAY_DEGREE ( 0 , 0 , 0 , 0 ); - return true; - } - else if ( ddu == "MIN" || ddu == "MINIMAL" || ddu == "MINIMAL_DISPLAY" ) { - set_DISPLAY_DEGREE ( 1 , 1 , 1 , 1 ); - return true; - } - - else if ( ddu == "NORMAL" || ddu == "NORMAL_DISPLAY" ) { - set_DISPLAY_DEGREE ( 2 , 2 , 2 , 2 ); - return true; - } - - else if ( ddu == "FULL" || ddu == "FULL_DISPLAY" ) { - set_DISPLAY_DEGREE ( 3 , 3 , 3 , 3 ); - return true; - } - } - - if ( dd.size() == 1 ) { - int i; - if ( !NOMAD::atoi ( dd[0] , i ) ) - return false; - _out.set_degrees ( NOMAD::Display::int_to_dd(i) ); - return true; - } - - if ( dd.size() != 4 ) - return false; - - // 1. general display: - int gdd; - if ( !NOMAD::atoi ( dd[0] , gdd ) ) - return false; - - // 2. search display: - int sdd; - if ( !NOMAD::atoi ( dd[1] , sdd ) ) - return false; - - // 3. poll display: - int pdd; - if ( !NOMAD::atoi ( dd[2] , pdd ) ) - return false; - - // 4. iterative display: - int idd; - if ( !NOMAD::atoi ( dd[3] , idd ) ) - return false; - - set_DISPLAY_DEGREE ( gdd , sdd , pdd , idd ); - -#endif - return true; -} - -// set_DISPLAY_DEGREE (3/3): -void NOMAD::Parameters::set_DISPLAY_DEGREE ( int gen_dd , - int search_dd , - int poll_dd , - int iter_dd ) -{ -#ifndef DEBUG - _out.set_degrees ( NOMAD::Display::int_to_dd ( gen_dd ) , - NOMAD::Display::int_to_dd ( search_dd ) , - NOMAD::Display::int_to_dd ( poll_dd ) , - NOMAD::Display::int_to_dd ( iter_dd ) ); -#endif -} - -// set_OPEN_BRACE: -void NOMAD::Parameters::set_OPEN_BRACE ( const std::string & ob ) -{ - _to_be_checked = true; - _out.set_open_brace ( ob ); -} - -// set_CLOSED_BRACE: -void NOMAD::Parameters::set_CLOSED_BRACE ( const std::string & cb ) -{ - _to_be_checked = true; - _out.set_closed_brace ( cb ); -} - -// set_SEED: -void NOMAD::Parameters::set_SEED ( int t ) -{ - _to_be_checked = true; - _seed = ( t < 0 ) ? NOMAD::get_pid() : t; - - if ( t < 0 && t!=-1 && _out.get_gen_dd()>=NOMAD::NORMAL_DISPLAY && !_warning_has_been_displayed) - _out << NOMAD::open_block("Warning:") - << "Seed should be in the interval [0;INT_MAX] U {-1}. The seed is set to the process id!" << std::endl - << NOMAD::close_block(); - - // The RNG seed is set here when explicit set is required otherwise default RNG seed is used - NOMAD::RNG::set_seed(_seed); - -} - -// set_MAX_EVAL: -void NOMAD::Parameters::set_MAX_EVAL ( int e ) -{ - _to_be_checked = true; - _max_eval = ( e <= 0 ) ? -1 : e; -} - -// set_MAX_BB_EVAL: -void NOMAD::Parameters::set_MAX_BB_EVAL ( int bbe ) -{ - _to_be_checked = true; - _max_bbe_decided = true; - _max_bb_eval = ( bbe < 0 ) ? -1 : bbe; -} - -// set_MAX_SIM_BB_EVAL: -void NOMAD::Parameters::set_MAX_SIM_BB_EVAL ( int bbe ) -{ - _to_be_checked = true; - _max_sim_bb_eval = ( bbe <= 0 ) ? -1 : bbe; -} - -// set_MAX_SGTE_EVAL: -void NOMAD::Parameters::set_MAX_SGTE_EVAL ( int bbe ) -{ - _to_be_checked = true; - _sgte_max_eval = ( bbe < 0 ) ? -1 : bbe; -} - -// set_MAX_TIME: -void NOMAD::Parameters::set_MAX_TIME ( int t ) -{ - _to_be_checked = true; - _max_time = ( t <= 0 ) ? -1 : t; -} - -// set_MAX_ITERATIONS: -void NOMAD::Parameters::set_MAX_ITERATIONS ( int it ) -{ - _to_be_checked = true; - _max_iterations = ( it < 0 ) ? -1 : it; -} - -// set_MAX_CONSECUTIVE_FAILED_ITERATIONS: -void NOMAD::Parameters::set_MAX_CONSECUTIVE_FAILED_ITERATIONS ( int it ) -{ - _to_be_checked = true; - _max_cons_failed_it = ( it <= 0 ) ? -1 : it; -} - -// set_MAX_CACHE_MEMORY:: -void NOMAD::Parameters::set_MAX_CACHE_MEMORY ( float mcm ) -{ - _to_be_checked = true; - _max_cache_memory = ( mcm < 0.0 ) ? -1 : mcm; -} - -// set_CACHE_SAVE_PERIOD: -void NOMAD::Parameters::set_CACHE_SAVE_PERIOD ( int csp ) -{ - _to_be_checked = true; - _cache_save_period = ( csp <= 0 ) ? -1 : csp; -} - -// set_STOP_IF_FEASIBLE: -void NOMAD::Parameters::set_STOP_IF_FEASIBLE ( bool sif ) -{ - _to_be_checked = true; - _stop_if_feasible = sif; -} - -// set_F_TARGET (1/2): -void NOMAD::Parameters::set_F_TARGET ( const NOMAD::Double & f_target ) -{ - _to_be_checked = true; - _f_target = NOMAD::Point ( 1 , f_target ); -} - -// set_F_TARGET (2/2): -void NOMAD::Parameters::set_F_TARGET ( const NOMAD::Point & f_target ) -{ - _to_be_checked = true; - _f_target = f_target; -} - -// set_STAT_SUM_TARGET: -void NOMAD::Parameters::set_STAT_SUM_TARGET ( const NOMAD::Double & sst ) -{ - _to_be_checked = true; - _stat_sum_target = sst; -} - -// set_L_CURVE_TARGET: -void NOMAD::Parameters::set_L_CURVE_TARGET ( const NOMAD::Double & lct ) -{ - _to_be_checked = true; - _L_curve_target = lct; -} - -// set_ANISOTROPIC_MESH: -void NOMAD::Parameters::set_ANISOTROPIC_MESH ( bool anis ) -{ - _to_be_checked = true; - _anisotropic_mesh = anis; -} - - -// set_USE_SMESH: -void NOMAD::Parameters::set_USE_SMESH ( bool use_smesh ) -{ - _to_be_checked = true; - _use_smesh = use_smesh; -} - - - -// set_MESH_UPDATE_BASIS: -void NOMAD::Parameters::set_MESH_UPDATE_BASIS ( const NOMAD::Double & mub ) -{ - if ( !mub.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_UPDATE_BASIS" ); - _to_be_checked = true; - _mesh_update_basis = mub; -} - -// set_POLL_UPDATE_BASIS: -void NOMAD::Parameters::set_POLL_UPDATE_BASIS ( const NOMAD::Double & pub ) -{ - if ( !pub.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: POLL_UPDATE_BASIS" ); - _to_be_checked = true; - _poll_update_basis = pub; -} - - -// set_INITIAL_MESH_INDEX: -void NOMAD::Parameters::set_INITIAL_MESH_INDEX ( int ell_0 ) -{ - _to_be_checked = true; - if ( ell_0 > NOMAD::L_LIMITS ) - ell_0 = NOMAD::L_LIMITS; - else if ( ell_0 < - NOMAD::L_LIMITS ) - ell_0 = -NOMAD::L_LIMITS; - _initial_mesh_index = ell_0; -} - -// set_MESH_COARSENING_EXPONENT: -void NOMAD::Parameters::set_MESH_COARSENING_EXPONENT ( int mce ) -{ - _to_be_checked = true; - if ( mce < 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_COARSENING_EXPONENT"); - _mesh_coarsening_exponent = mce; -} - -// set_MESH_REFINING_EXPONENT: -void NOMAD::Parameters::set_MESH_REFINING_EXPONENT ( int mre ) -{ - _to_be_checked = true; - if ( mre >= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MESH_REFINING_EXPONENT"); - _mesh_refining_exponent = mre; -} - -// set_INITIAL_MESH_SIZE (1/3): -void NOMAD::Parameters::set_INITIAL_MESH_SIZE ( int index , - const NOMAD::Double & d , - bool relative ) -{ - if ( index < 0 || index >= _initial_mesh_size.size() || !d.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_SIZE" ); - _to_be_checked = true; - - if ( relative ) - { - - if ( !_lb.is_defined() || !_ub.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_SIZE - bounds not defined" ); - - if ( !_lb[index].is_defined() || !_ub[index].is_defined() || - d <= 0.0 || d > 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_SIZE - relative value" ); - - NOMAD::Double d2 = d; - d2 *= _ub[index] - _lb[index]; - _initial_mesh_size[index] = d2; - } - else - _initial_mesh_size[index] = d; -} - -// set_INITIAL_MESH_SIZE (2/3): -void NOMAD::Parameters::set_INITIAL_MESH_SIZE ( const NOMAD::Point & delta_m_0 , - bool relative ) -{ - _to_be_checked = true; - if ( relative ) - { - int nd = delta_m_0.size(); - for ( int i = 0 ; i < nd ; ++i ) - set_INITIAL_MESH_SIZE ( i , delta_m_0[i] , true ); - } - else - _initial_mesh_size = delta_m_0; -} - -// set_INITIAL_MESH_SIZE (3/3): -void NOMAD::Parameters::set_INITIAL_MESH_SIZE ( const NOMAD::Double & d , bool relative ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_MESH_SIZE - undefined dimension" ); - _to_be_checked = true; - if ( relative ) - for ( int i = 0 ; i < _dimension ; ++i ) - set_INITIAL_MESH_SIZE ( i , d , true ); - else - _initial_mesh_size = NOMAD::Point ( _dimension , d ); -} - -// set_INITIAL_POLL_SIZE (1/3): -void NOMAD::Parameters::set_INITIAL_POLL_SIZE ( int index , - const NOMAD::Double & d , - bool relative ) -{ - if ( index < 0 || index >= _initial_poll_size.size() || !d.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_POLL_SIZE" ); - _to_be_checked = true; - - if ( relative ) - { - - if ( !_lb.is_defined() || !_ub.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_POLL_SIZE - bounds not defined" ); - - if ( !_lb[index].is_defined() || !_ub[index].is_defined() || - d <= 0.0 || d > 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_POLL_SIZE - relative value" ); - - NOMAD::Double d2 = d; - d2 *= _ub[index] - _lb[index]; - _initial_poll_size[index] = d2; - } - else - _initial_poll_size[index] = d; -} - -// set_INITIAL_POLL_SIZE (2/3): -void NOMAD::Parameters::set_INITIAL_POLL_SIZE ( const NOMAD::Point & delta_m_0 , - bool relative ) -{ - _to_be_checked = true; - if ( relative ) - { - int nd = delta_m_0.size(); - for ( int i = 0 ; i < nd ; ++i ) - set_INITIAL_POLL_SIZE ( i , delta_m_0[i] , true ); - } - else - _initial_poll_size = delta_m_0; -} - -// set_INITIAL_POLL_SIZE (3/3): -void NOMAD::Parameters::set_INITIAL_POLL_SIZE ( const NOMAD::Double & d , bool relative ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: INITIAL_POLL_SIZE - undefined dimension" ); - _to_be_checked = true; - if ( relative ) - for ( int i = 0 ; i < _dimension ; ++i ) - set_INITIAL_POLL_SIZE ( i , d , true ); - else - _initial_poll_size = NOMAD::Point ( _dimension , d ); -} - - - -// set_MIN_MESH_SIZE (1/3): -void NOMAD::Parameters::set_MIN_MESH_SIZE ( int index , - const NOMAD::Double & d , - bool relative ) -{ - if (_dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_MESH_SIZE - undefined dimension" ); - - if ( !_min_mesh_size.is_defined() ) - _min_mesh_size = NOMAD::Point ( _dimension ); - - if ( index < 0 || index >= _min_mesh_size.size() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_MESH_SIZE" ); - _to_be_checked = true; - if ( relative ) - { - - if ( !_lb.is_defined() || !_ub.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_MESH_SIZE - bounds not defined" ); - - if ( !_lb[index].is_defined() || !_ub[index].is_defined() || - !d.is_defined() || d <= 0.0 || d > 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_MESH_SIZE - relative value" ); - NOMAD::Double d2 = d; - d2 *= _ub[index] - _lb[index]; - _min_mesh_size[index] = d2; - } - else - _min_mesh_size[index] = d; -} - -// set_MIN_MESH_SIZE (2/3): -void NOMAD::Parameters::set_MIN_MESH_SIZE ( const NOMAD::Point & delta_p_min , - bool relative ) -{ - _to_be_checked = true; - if ( relative ) - { - int nd = delta_p_min.size(); - for ( int i = 0 ; i < nd ; ++i ) - set_MIN_MESH_SIZE ( i , delta_p_min[i] , true ); - } - else - _min_mesh_size = delta_p_min; -} - -// set_MIN_MESH_SIZE (3/3): -void NOMAD::Parameters::set_MIN_MESH_SIZE ( const NOMAD::Double & d , bool relative ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_MESH_SIZE - undefined dimension" ); - _to_be_checked = true; - if ( relative ) - for ( int i = 0 ; i < _dimension ; ++i ) - set_MIN_MESH_SIZE ( i , d , true ); - else - _min_mesh_size = NOMAD::Point ( _dimension , d ); -} - -// set_MIN_POLL_SIZE (1/3): -void NOMAD::Parameters::set_MIN_POLL_SIZE ( int index , - const NOMAD::Double & d , - bool relative ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_POLL_SIZE - undefined dimension" ); - - if ( !_min_poll_size.is_defined() ) - _min_poll_size = NOMAD::Point ( _dimension ); - - if ( index < 0 || index >= _min_poll_size.size() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_POLL_SIZE" ); - _to_be_checked = true; - if ( relative ) { - if ( !_lb[index].is_defined() || !_ub[index].is_defined() || - !d.is_defined() || d <= 0.0 || d > 1.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_POLL_SIZE - relative value" ); - _min_poll_size[index] = d * ( _ub[index] - _lb[index] ); - } - else - _min_poll_size[index] = d; -} - -// set_MIN_POLL_SIZE (2/3): -void NOMAD::Parameters::set_MIN_POLL_SIZE ( const NOMAD::Point & delta_p_min , - bool relative ) -{ - _to_be_checked = true; - if ( relative ) { - int nd = delta_p_min.size(); - for ( int i = 0 ; i < nd ; ++i ) - set_MIN_POLL_SIZE ( i , delta_p_min[i] , true ); - } - else - _min_poll_size = delta_p_min; -} - -// set_MIN_POLL_SIZE (3/3): -void NOMAD::Parameters::set_MIN_POLL_SIZE ( const NOMAD::Double & d , bool relative ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MIN_POLL_SIZE - undefined dimension" ); - _to_be_checked = true; - if ( relative ) - for ( int i = 0 ; i < _dimension ; ++i ) - set_MIN_POLL_SIZE ( i , d , true ); - else - _min_poll_size = NOMAD::Point ( _dimension , d ); -} - -// set_NEIGHBORS_EXE: -void NOMAD::Parameters::set_NEIGHBORS_EXE ( const std::string & ne ) -{ - _to_be_checked = true; - _neighbors_exe = ne; -} - -// set_EXTENDED_POLL_TRIGGER: -void NOMAD::Parameters::set_EXTENDED_POLL_TRIGGER ( const NOMAD::Double & ept , - bool relative ) -{ - _to_be_checked = true; - - if ( !ept.is_defined() ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EXTENDED_POLL_TRIGGER (undefined)" ); - - if ( ept <= 0.0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: EXTENDED_POLL_TRIGGER: must be strictly positive" ); - - _extended_poll_trigger = ept; - _relative_ept = relative; -} - -// set_EXTENDED_POLL_ENABLED: -void NOMAD::Parameters::set_EXTENDED_POLL_ENABLED ( bool epe ) -{ - _to_be_checked = true; - _extended_poll_enabled = epe; -} - -// set_USER_CALLS_ENABLED: -void NOMAD::Parameters::set_USER_CALLS_ENABLED ( bool uce ) -{ - _to_be_checked = true; - _user_calls_enabled = uce; -} - -// set_ASYNCHRONOUS: -void NOMAD::Parameters::set_ASYNCHRONOUS ( bool a ) -{ - _to_be_checked = true; - _asynchronous = a; -} - -// set_MULTI_NB_MADS_RUNS: -void NOMAD::Parameters::set_MULTI_NB_MADS_RUNS ( int i ) -{ - if ( i == 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_NB_MADS_RUNS - has been set to zero" ); - - _to_be_checked = true; - _multi_nb_mads_runs = ( i < 0 ) ? -1 : i; -} - -// set_MULTI_OVERALL_BB_EVAL: -void NOMAD::Parameters::set_MULTI_OVERALL_BB_EVAL ( int i ) -{ - _to_be_checked = true; - _multi_overall_bb_eval = ( i < 0 ) ? -1 : i; -} - -// set_MULTI_USE_DELTA_CRIT: -void NOMAD::Parameters::set_MULTI_USE_DELTA_CRIT ( bool b ) -{ - _to_be_checked = true; - _multi_use_delta_crit = b; -} - -// set_MULTI_F_BOUNDS: -void NOMAD::Parameters::set_MULTI_F_BOUNDS ( const NOMAD::Point & p ) -{ - _to_be_checked = true; - if ( p.size() != 4 || p[0] >= p[1] || p[2] >= p[3] ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: MULTI_F_BOUNDS" ); - _multi_f_bounds = p; -} - -// set_MULTI_FORMULATION: -void NOMAD::Parameters::set_MULTI_FORMULATION ( NOMAD::multi_formulation_type mft ) -{ - _to_be_checked = true; - _multi_formulation = mft; -} - -void NOMAD::Parameters::set_BB_MAX_BLOCK_SIZE ( int max_block_size ) -{ - _to_be_checked = true; - _bb_max_block_size = max_block_size; - - if ( _bb_max_block_size > 1 ) - _eval_points_as_block=true; - - -} - - - -// set_OPPORTUNISTIC_LH: -void NOMAD::Parameters::set_OPPORTUNISTIC_LH ( bool opp ) -{ - _to_be_checked = true; - _opportunistic_LH = opp; - _opp_LH_is_defined = true; -} - -// set_OPPORTUNISTIC_CACHE_SEARCH: -void NOMAD::Parameters::set_OPPORTUNISTIC_CACHE_SEARCH ( bool opp ) -{ - _to_be_checked = true; - _opportunistic_cache_search = opp; - _opp_CS_is_defined = true; -} - -// set_OPPORTUNISTIC_EVAL: -void NOMAD::Parameters::set_OPPORTUNISTIC_EVAL ( bool oe ) -{ - _to_be_checked = true; - _opportunistic_eval = oe; -} - -// set_OPPORTUNISTIC_MIN_NB_SUCCESS: -void NOMAD::Parameters::set_OPPORTUNISTIC_MIN_NB_SUCCESS ( int mns ) -{ - _to_be_checked = true; - if ( mns <= 0 ) - mns = -1; - _opportunistic_min_nb_success = mns; -} - -// set_OPPORTUNISTIC_MIN_EVAL: -void NOMAD::Parameters::set_OPPORTUNISTIC_MIN_EVAL ( int me ) -{ - _to_be_checked = true; - if ( me <= 0 ) - me = -1; - _opportunistic_min_eval = me; -} - -// set_OPPORTUNISTIC_MIN_F_IMPRVMT: -void NOMAD::Parameters::set_OPPORTUNISTIC_MIN_F_IMPRVMT ( const NOMAD::Double & mfi ) -{ - _to_be_checked = true; - if ( !mfi.is_defined() || mfi <= 0.0 ) - _opportunistic_min_f_imprvmt.clear(); - else - _opportunistic_min_f_imprvmt = mfi; -} - -// set_OPPORTUNISTIC_LUCKY_EVAL: -void NOMAD::Parameters::set_OPPORTUNISTIC_LUCKY_EVAL ( bool le ) -{ - _to_be_checked = true; - _opportunistic_lucky_eval = le; -} - -// set_PERIODIC_VARIABLE (1/2): -void NOMAD::Parameters::set_PERIODIC_VARIABLE ( int index ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE - undefined dimension" ); - - if ( index < 0 || index >= _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: PERIODIC_VARIABLE - bad variable index" ); - - if ( _periodic_variables.empty() ) - for ( int i = 0 ; i < _dimension ; ++i ) - _periodic_variables.push_back ( false ); - - _periodic_variables[index] = true; - _to_be_checked = true; -} - -// set_PERIODIC_VARIABLE (2/2): -void NOMAD::Parameters::set_PERIODIC_VARIABLE ( const std::vector & pv ) -{ - _to_be_checked = true; - _periodic_variables = pv; -} - -// set_VARIABLE_GROUP (1/3): -void NOMAD::Parameters::set_VARIABLE_GROUP ( const std::set & var_indexes ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP - undefined dimension" ); - - if ( _bb_input_type.empty() || - static_cast(_bb_input_type.size()) != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP - undefined blackbox input types" ); - - _to_be_checked = true; - - std::set empty; - - _user_var_groups.insert ( new NOMAD::Variable_Group ( var_indexes , - empty , - empty , - _out ) ); -} - -// set_VARIABLE_GROUP (2/3): -void NOMAD::Parameters::set_VARIABLE_GROUP -( const std::set & var_indexes , - const std::set & direction_types , - const std::set & sec_poll_dir_types ) -{ - if ( _dimension <= 0 ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP - undefined dimension" ); - - if ( _bb_input_type.empty() || - static_cast(_bb_input_type.size()) != _dimension ) - throw Invalid_Parameter ( "Parameters.cpp" , __LINE__ , - "invalid parameter: VARIABLE_GROUP - undefined blackbox input types" ); - - _to_be_checked = true; - - std::set dt = direction_types; - if ( dt.empty() ) - dt.insert ( NOMAD::ORTHO_NP1_QUAD ); - - _user_var_groups.insert ( new NOMAD::Variable_Group ( var_indexes , - dt , - sec_poll_dir_types , - _out ) ); -} - -// set_VARIABLE_GROUP (3/3): -void NOMAD::Parameters::set_VARIABLE_GROUP -( const std::list & vg ) -{ - - std::list::const_iterator it , end = vg.end(); - for ( it = vg.begin() ; it != end ; ++it ) - set_VARIABLE_GROUP ( (*it)->get_var_indexes () , - (*it)->get_direction_types () , - (*it)->get_sec_poll_dir_types() - ); - -} - -/*-----------------------------------------------*/ -/* help (display parameter descriptions) - 1/3 */ -/*-----------------------------------------------*/ -void NOMAD::Parameters::help ( const std::string & param_name,bool developer ) const -{ - std::list ls; - ls.push_back ( param_name ); - help ( ls,developer); -} - -/*-----------------------------------------------*/ -/* help (display parameter descriptions) - 2/3 */ -/*-----------------------------------------------*/ -void NOMAD::Parameters::help ( int argc , char ** argv , bool developer ) const -{ - std::list ls; - if ( argc <= 2 ) - ls.push_back ( "ALL" ); - else - for ( int i = 2 ; i < argc ; ++i ) - ls.push_back ( argv[i] ); - help(ls,developer); -} - -/*-----------------------------------------------*/ -/* help (display parameter descriptions) - 3/3 */ -/*-----------------------------------------------*/ -void NOMAD::Parameters::help ( const std::list & pnames,bool developer ) const -{ -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - return; -#endif - - // initial display: - _out << std::endl - << NOMAD::open_block ( "NOMAD - help on parameters - see more details in " - + NOMAD::USER_GUIDE_FILE ); - - std::list param_names = pnames; - NOMAD::toupper ( param_names ); - - bool chk = false; - bool display_all = false; - - if ( NOMAD::string_match ( "ALL", param_names) || NOMAD::string_match( "PARAMS", param_names ) || - NOMAD::string_match ( "PARAMETER", param_names) || NOMAD::string_match ( "PARAM", param_names) || - NOMAD::string_match ( "NOMAD" , param_names ) || NOMAD::string_match ( "EVERYTHING", param_names) ) - display_all = true; - - - const char registered_key_basic[]="2N ANGLES AVG BARRIER BASIC BASIC BB_EXE BB_INPUT_TYPE BB_OUTPUT_TYPE BI-MADS BI-OBJECTIVES BIMADS \ - BINARY BIOBJECTIVES BLACK-BOXES BLACKBOXES BOUNDS CACHE BBEVAL CACHE_FILE CNT_EVAL CONSTRAINTS CONTINUOUS COUNT DEBUG DELTA_0 DIMENSION \ - DIRECTION_TYPE DIRECTION_TYPES DIRECTIONS DIRECTIONS_TYPES DIRECTORY DISPLAY_ALL_EVAL DISPLAY_DEGREES DISPLAY_STATS EVALUATIONS \ - EXECUTABLE F_TARGET FILES FILTER FORMAT GPS h(x) HISTORY_FILE INITIAL_MESH_SIZE INTEGER LATEX LATIN-HYPERCUBE LB LH_SEARCH LOWER_BOUND \ - LT LT-MADS LTMADS MADS MAX_BB_EVAL MAX_TIME MAXIMUM MINIMIZE MODEL MODELS MULTI-OBJECTIVE MULTIOBJECTIVES N+1 NUMBER OPTIMIZE ORTHO \ - ORTHO-MADS ORTHOMADS OUTPUTS PATH PB PEB POINT POLL PROGRESSIVE-BARRIER RANDOM SAMPLING SCREEN SCREEN SOLUTION_FILE STARTING STATIC \ - STATS STATS_FILE STOPPING SUM TEMPORARY TERMINATES TERMINATION TMP_DIR UB UNIFORM UPPER_BOUNDS VARIABLES X0"; - - const char registered_key_advanced[]="ADD_SEED_TO_FILE_NAMES ADVANCED ANISOTROPIC_MESH ASYNCHRONOUS BB_INPUT_INCLUDE_SEED BB_INPUT_INCLUDE_TAG \ - BB_REDIRECTION BBEVAL BI-MADS BI-OBJECTIVES BIMADS BIOBJECTIVES BLACK-BOXES BLACKBOXES BLOCKS BOUNDS CACHE CACHE_FILE CACHE_SAVE_PERIOD \ - CACHE_SEARCH CATEGORICAL CLOSED_BRACES CONSTRAINTS CYCLIC DELTA DETERMINISTIC DIRECTIONS DISABLE DISABLE_EVAL_SORT DISABLE_MODEL DISABLE_MODELS \ - DISPLAY ELL ELL_0 BB_MAX_BLOCK_SIZE EVALUATIONS EXECUTABLE EXTENDED_POLL EXTENDED_POLL_DISABLED EXTENDED_POLL_ENABLED EXTENDED_POLL_TRIGGER FEASIBILITY \ - FILES FILTER FIXED_VARIABLE FROBENIUS GLOBAL GROUPS H_MAX_0 H_MIN H_NORM HAS_SGTE HMAX HMAX_0 HMIN INDENTATION INF_STR \ - INFINITY INTERPOLATION ITERATIONS L_0 L_INF L0 L1 L2 LATIN-HYPERCUBE LB LIBRARY LINF LT-MADS LTMADS MADS \ - MAX_CACHE_MEMORY MAX_CONSECUTIVE_FAILED_ITERATIONS MAX_EVAL MAX_ITERATIONS MAX_SGTE_EVAL MAX_SIM_BB_EVAL MAXIMUM \ - MB MEGA-BYTES MEGABYTES MESH MESH_COARSENING_EXPONENT MESH_REFINING_EXPONENT MESH_UPDATE_BASIS META-HEURISTICS METAHEURISTICS MFN \ - MIN_MESH_SIZE MIN_POLL_SIZE MINIMUM MIXED MODEL MODEL_EVAL_SORT MODEL_ORDERING MODEL_SEARCH MODEL_SEARCH_OPTIMISTIC MODELS MPI \ - MULTI_F_BOUNDS MULTI_NB_MADS_RUNS MULTI_OVERALL_BB_EVAL MULTI-OBJECTIVES MULTIOBJECTIVES MVP N+1 NEIGHBORHOOD NEIGHBORHOODS NEIGHBORS_EXE \ - NEIGHBOURHOODS NEIGHBOURS NUMBER OPEN_BRACES OPPORTUNISTIC_CACHE_SEARCH OPPORTUNISTIC_EVAL OPPORTUNISTIC_LH OPPORTUNISTIC_MIN_EVAL \ - OPTIMISTIC ORTHO ORTHO-MADS ORTHOGONAL ORTHOMADS OUTPUT OUTPUTS PARALLELISM PARETO PB PEB PERIODIC_VARIABLE PMADS POINT_DISPLAY_LIMIT \ - POLL POLL_UPDATE_BASIS PRECISION PROGRESSIVE-BARRIER PROJECTION PSD-MADS PSDMADS QUAD QUADRATIC RAM RANDOM REALS REGRESSION RHO SAMPLING SCALE SCALING \ - SEARCH SEED SGTE_CACHE_FILE SGTE_COST SGTE_EVAL_SORT SGTE_EXE SGTE_ORDERING SGTES SIMULATED SNAP_TO_BOUNDS SPECULATIVE_SEARCH \ - STAT_SUM_TARGET STATS STOP_IF_FEASIBLE SUCCESSES SURF SURROGATES TABULATIONS TAU TERMINATES TERMINATION TGP TGPMODEL_SEARCH TRIGGER \ - UB UNDEF_STR UNDEFINED USER_CALLS_DISABLED USER_CALLS_ENABLED VARIABLE_GROUP VARIABLES VNS_SEARCH W- W+"; - - const char registered_key_developer[]="BI-MADS BI-OBJECTIVES BIMADS BIOBJECTIVES BLACK-BOXES BLACK-BOXES COMPARISONS DEVELOPER \ - DIRECTIONS EPSILON EVALUATIONS FROBENIUS INITIAL_MESH_INDEX IMPROVEMENT INTERPOLATION L_CURVE_TARGET MADS MFN MODEL MODEL_EVAL_SORT_CAUTIOUS MODEL_ORDERING \ - MODEL_QUAD_MAX_Y_SIZE MODEL_QUAD_MIN_Y_SIZE MODEL_QUAD_RADIUS_FACTOR MODEL_QUAD_USE_WP MODEL_SEARCH MODEL_SEARCH_MAX_TRIAL_PTS \ - MODEL_SEARCH_PROJ_TO_MESH MODEL_TGP_MODE MODEL_TGP_REUSE_MODEL MODELS MULTI_FORMULATION MULTI_USE_DELTA_CRITERION MULTI-OBJECTIVES \ - MULTIOBJECTIVES N+1 NP1 OBJECTIVE OPPORTUNISTIC_LUCKY_EVAL OPPORTUNISTIC_MIN_F_IMPRVMT OPPORTUNISTIC_MIN_NB_SUCCESSES OPT_ONLY_SGTES \ - ORTHO PARETO PB PEB POLL PRECISION PROGRESSIVE-BARRIER PROJECTION QUAD QUADRATIC REALS REGRESSION SEC_POLL_DIR_TYPES SGTES STOPPING \ - SUCCESSES SURROGATES TERMINATES TERMINATION TGP USE_SMESH WELL-POISEDNESS"; - - - if ( display_all || NOMAD::string_find ( registered_key_basic, param_names ) ) - { - _out << "--------------------------------------------------------------" << endl; - _out << "-----------------------BASIC PARAMETERS-----------------------" << endl; - _out << "--------------------------------------------------------------" << endl; - } - - - // BB_EXE: - // ------- - if ( display_all || NOMAD::string_find ( "BB_EXE BASIC BLACK-BOXES BLACKBOXES \ - EXECUTABLE FILES BI-OBJECTIVES \ - BIOBJECTIVES MULTIOBJECTIVES \ - BIMADS BI-MADS \ - MULTI-OBJECTIVES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_EXE (basic)" ) << std::endl - << ". blackbox executable names" << std::endl - << ". list of strings" << std::endl - << ". no default, required (except in library mode)" << std::endl - << ". several executables can be used" << std::endl - << ". one executable can give several outputs" << std::endl - << ". use \' or \", and \'$\', to specify names or" << std::endl - << " commands with spaces" << std::endl - << ". when the \'$\' character is put in first" << std::endl - << " position of a string, it is considered" << std::endl - << " as global and no path will be added" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "BB_EXE bb.exe" << std::endl - << "BB_EXE bb1.exe bb2.exe" << std::endl - << "BB_EXE \'$nice bb.exe\'" << std::endl - << "BB_EXE \'$python bb.py\'" << std::endl - << NOMAD::close_block() - << NOMAD::close_block(); - chk = true; - } - - // BB_INPUT_TYPE: - // -------------- - if ( display_all || NOMAD::string_find ( "BB_INPUT_TYPE BLACK-BOXES BLACKBOXES \ - BASIC VARIABLES CONTINUOUS \ - INTEGER BINARY" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_INPUT_TYPE (basic)" ) << std::endl - << ". blackbox input types" << std::endl - << ". list of types for each variable" << std::endl - << ". " << NOMAD::open_block ( "available types" ) - << "B: binary" << std::endl - << "C: categorical" << std::endl - << "I: integer" << std::endl - << "R: continuous" << std::endl - << NOMAD::close_block() - << ". default: * R (all continuous)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "BB_INPUT_TYPE ( R I B ) # for all 3 variables" << std::endl - << "BB_INPUT_TYPE 1-3 B # variables 1 to 3 are binary" << std::endl - << "BB_INPUT_TYPE 0 I # first variable is integer" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // BB_OUTPUT_TYPE: - // --------------- - if ( display_all || NOMAD::string_find ( "BB_OUTPUT_TYPE BASIC CONSTRAINTS \ - BLACK-BOXES BLACKBOXES \ - BARRIER STATS BI-OBJECTIVES h(x) \ - PB PEB FILTER STATS SUM AVG CNT_EVAL \ - COUNT PROGRESSIVE-BARRIER \ - MULTI-OBJECTIVE MINIMIZE \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS \ - OPTIMIZE" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_OUTPUT_TYPE (basic)" ) << std::endl - << ". blackbox output types" << std::endl - << ". list of types for each blackbox output" << std::endl - << ". " << NOMAD::open_block ( "available types" ) << std::endl - << "OBJ : objective value to minimize" << std::endl - << " (define twice for bi-objective)" << std::endl - << "CSTR or PB: constraint <= 0 treated with" << std::endl - << " Progressive Barrier (PB)" << std::endl - << "EB : constraint <= 0 treated with" << std::endl - << " Extreme Barrier (EB)" << std::endl - << "PEB : constraint <= 0 treated with" << std::endl - << " hybrid PB/EB" << std::endl - << "F : constraint <= 0 treated with Filter" << std::endl - << "CNT_EVAL : 0 or 1 output: count or not the" << std::endl - << " evaluation" << std::endl - << "STAT_AVG : NOMAD will compute the average" << std::endl - << " value for this output" << std::endl - << "STAT_SUM : the same for the sum" << std::endl - << "NOTHING : the output is ignored" << std::endl - << "- : same as \'NOTHING\'" << std::endl - << NOMAD::close_block() - << ". STAT_SUM and STAT_AVG outputs have to be unique;" << std::endl - << " they are updated at every new blackbox evaluation" << std::endl - << ". no default, required" << std::endl - << ". see user guide for blackbox output formats" << std::endl - << ". equality constraints are not natively supported" << std::endl - << ". see parameters LOWER_BOUND and UPPER_BOUND for" << std::endl - << " bound constraints" << std::endl - << ". " << NOMAD::open_block ( "examples" ) << std::endl - << "BB_EXE bb.exe # these two lines define" << std::endl - << "BB_OUTPUT_TYPE OBJ EB EB # that bb.exe outputs" << std::endl - << " # three values" << std::endl - << std::endl - << "BB_EXE bb1.exe bb2.exe bb2.exe # bb1.exe outputs the" << std::endl - << "BB_OUTPUT_TYPE OBJ EB EB # objective and bb2.exe" << std::endl - << " # two constraints" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - - // CACHE_FILE: - // ----------- - if ( display_all || NOMAD::string_find ( "CACHE_FILE BASIC \ - FILES OUTPUTS" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "CACHE_FILE (basic)" ) << std::endl - << ". cache file; if the specified file" << std::endl - << " does not exist, it will be created" << std::endl - << ". argument: one string" << std::endl - << ". no default" << std::endl - << ". points already in the file will be" << std::endl - << " tagged as true evaluations" << std::endl - << ". example: CACHE_FILE cache.bin" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // DIMENSION: - // ---------- - if ( display_all || NOMAD::string_find ( "DIMENSION BASIC VARIABLES" , - param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "DIMENSION (basic)" ) << std::endl - << ". number of variables" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default, required" << std::endl - << ". example: DIMENSION 3" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // DIRECTION_TYPE: - // --------------- - if ( display_all || NOMAD::string_find ( "DIRECTION_TYPES BASIC DIRECTION_TYPE DIRECTIONS_TYPES \ - BASIC ORTHO LT GPS \ - MADS DIRECTIONS 2N N+1 POLL MODEL MODELS \ - ORTHOMADS ORTHO-MADS LTMADS LT-MADS \ - RANDOM STATIC UNIFORM ANGLES" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "DIRECTION_TYPE (basic)" ) << std::endl - << ". types of directions used in the poll step" << std::endl - << ". arguments: direction types (see user" << std::endl - << " guide for available types)" << std::endl - << ". default: ORTHO (OrthoMADS n+1 (QUAD model used for " << std::endl - << " (n+1)th dir)." << std::endl - << ". several direction types can be defined" << std::endl - << " at the same time (one direction per line)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) << std::endl - << "DIRECTION_TYPE ORTHO 1 # OrthoMADS, 1" << std::endl - << "DIRECTION_TYPE ORTHO 2 # OrthoMADS, 2" << std::endl - << "DIRECTION_TYPE ORTHO N+1 # OrthoMADS, n+1" << std::endl - << " # (QUAD model used"<< std::endl - << " # for (n+1)th dir)"<< std::endl - << "DIRECTION_TYPE ORTHO N+1 QUAD # OrthoMADS, n+1" << std::endl - << " # (QUAD model used"<< std::endl - << " # for (n+1)th dir)"<< std::endl - << "DIRECTION_TYPE ORTHO N+1 NEG # OrthoMADS, n+1" << std::endl - << " # ((n+1)th dir = " << std::endl - << " # negative sum of" << std::endl - << " # n first dirs)" << std::endl - << "DIRECTION_TYPE ORTHO # OrthoMADS, n+1 QUAD " << std::endl - << "DIRECTION_TYPE ORTHO 2N # OrthoMADS, 2n" << std::endl - << "DIRECTION_TYPE LT 1 # LT-MADS, 1" << std::endl - << "DIRECTION_TYPE LT 2 # LT-MADS, 2" << std::endl - << "DIRECTION_TYPE LT N+1 # LT-MADS, n+1" << std::endl - << "DIRECTION_TYPE LT # LT-MADS, 2n" << std::endl - << "DIRECTION_TYPE LT 2N # LT-MADS, 2n" << std::endl - << "DIRECTION_TYPE GPS BINARY or BIN # GPS, bin var" << std::endl - << "DIRECTION_TYPE GPS N+1 # GPS, n+1," << std::endl - << " # static" << std::endl - << "DIRECTION_TYPE GPS N+1 STATIC # GPS, n+1," << std::endl - << " # static" << std::endl - << "DIRECTION_TYPE GPS N+1 STATIC UNIFORM # GPS, n+1," << std::endl - << " # static, unif" << std::endl - << "DIRECTION_TYPE GPS N+1 RAND # GPS, n+1," << std::endl - << " # rand" << std::endl - << "DIRECTION_TYPE GPS N+1 RAND UNIFORM # GPS, n+1," << std::endl - << " # rand, unif" << std::endl - << "DIRECTION_TYPE GPS # GPS, 2n," << std::endl - << " # static" << std::endl - << "DIRECTION_TYPE GPS 2N # GPS, 2n," << std::endl - << " # static" << std::endl - << "DIRECTION_TYPE GPS 2N STATIC # GPS, 2n," << std::endl - << " # static" << std::endl - << "DIRECTION_TYPE GPS 2N RAND # GPS, 2n," << std::endl - << " # rand" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // DISPLAY_ALL_EVAL: - // ----------------- - if ( display_all || NOMAD::string_find ( "DISPLAY_ALL_EVAL DISPLAY_STATS \ - STATS_FILE BASIC" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "DISPLAY_ALL_EVAL (basic)" ) << std::endl - << ". if \'yes\', more points are displayed with" << std::endl - << " parameters DISPLAY_STATS and STATS_FILE" << std::endl - << ". points of the phase one with EB constraints" << std::endl - << " are not displayed" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: DISPLAY_ALL_EVAL yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // DISPLAY_DEGREE: - // --------------- - if ( display_all || NOMAD::string_find ( "DISPLAY_DEGREES OUTPUTS \ - SCREEN DEBUG BASIC" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "DISPLAY_DEGREE (basic)" ) << std::endl - << ". " << NOMAD::open_block ( "display degree" ) - << "0: no display" << std::endl - << "1: minimal display" << std::endl - << "2: normal display" << std::endl - << "3: full display" << std::endl - << NOMAD::close_block() - << ". argument: one integer in {0, 1, 2, 3} (basic)" << std::endl - << " or one string in {\'NO\', \'NO_DISPLAY\', \'MIN\'," << std::endl - << " \'MINIMAL\', \'MINIMAL_DISPLAY\' ,\'NORMAL\'," - << std::endl - << " \'NORMAL_DISPLAY\', \'FULL\'," << std::endl - << " \'FULL_DISPLAY\'}" << std::endl - << " or one string composed of 4 integers each in" << std::endl - << " { 0, 1, 2 ,3} (advanced)" << std::endl - << ". default: 2" << std::endl - << ". " - << NOMAD::open_block("advanced use with 4 digits (see user guide for details)") - << "#1 general display degree (before and after" << std::endl - << " all iterations)" << std::endl - << "#2 search display degree (during searches)" << std::endl - << "#3 poll display degree (during polls)" << std::endl - << "#4 iterative display degree (other displays at" << std::endl - << " each iteration)" << std::endl - << NOMAD::close_block() << ". " << NOMAD::open_block ( "examples" ) - << "DISPLAY_DEGREE 2 # basic : normal display" << std::endl - << "DISPLAY_DEGREE 0030 # advanced: display only" << std::endl - << " # poll info" << std::endl - << NOMAD::close_block() - << NOMAD::close_block(); - chk = true; - } - - // DISPLAY_STATS: - // --------------- - if ( display_all || NOMAD::string_find ( "DISPLAY_STATS OUTPUTS LATEX FORMAT \ - SCREEN DEBUG BASIC" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "DISPLAY_STATS (basic)" ) << std::endl - << ". format of the outputs displayed at each success" << std::endl - << " (single-objective)" << std::endl - << ". format of the final Pareto front" << std::endl - << " (multi-objective)" << std::endl - << ". displays more points with DISPLAY_ALL_EVAL=true" << std::endl - << ". arguments: list of strings possibly including" << std::endl - << " the following keywords:" << std::endl - << " BBE : blackbox evaluations" << std::endl - << " BBO : blackbox outputs" << std::endl - << " BLK_EVA : number of blocks of evaluations" << std::endl - << " EVAL : evaluations (includes cache hits)" << std::endl - << " MESH_INDEX: mesh index" << std::endl - << " MESH_SIZE : mesh size delta_k^m" << std::endl - << " OBJ : objective function value" << std::endl - << " POLL_SIZE : poll size delta_k^p" << std::endl - << " SIM_BBE : simulated blackbox evaluations" << std::endl - << " SGTE : surrogate evaluations" << std::endl - << " SOL : current feasible iterate" << std::endl - << " STAT_SUM : value of stat SUM" << std::endl - << " STAT_AVG : value of stat AVG" << std::endl - << " TIME : real time in seconds" << std::endl - << " VARi : value of variable i" << std::endl - << " (0 for the first variable)" << std::endl - << ". all outputs may be formatted using C style" << std::endl - << " (%f, %e, %E, %g, %G, %i, %d with the possibility" << std::endl - << " to specify the display width and the precision)" << std::endl - << " example: %5.2Ef displays f in 5 columns and 2 decimals" << std::endl - << " in scientific notation" << std::endl - << ". do not use quotes" << std::endl - << ". the \'%\' character may be explicitely indicated with \'\\%\'" - << std::endl - << ". see details in user guide" << std::endl - << ". defaults: BBE OBJ (single-objective)" << std::endl - << " OBJ (multi-objective)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "DISPLAY_STATS TIME f=OBJ" << std::endl - << "DISPLAY_STATS %5.2obj" << std::endl - << "# for LaTeX tables:" << std::endl - << "DISPLAY_STATS $BBE$ & ( $%12.5SOL, ) & $OBJ$ \\\\" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // F_TARGET: - // --------- - if ( display_all || NOMAD::string_find ( "F_TARGET BASIC BLACK-BOXES BLACKBOXES \ - BI-OBJECTIVES STOPPING \ - MULTI-OBJECTIVES \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "F_TARGET (basic)" ) << std::endl - << ". NOMAD terminates if fi <= F_TARGET[i] for" << std::endl - << " all objectives i" << std::endl - << ". arguments: one or two reals (single or bi-obj.)" << std::endl - << ". no default" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "F_TARGET 0.0 # single-objective" << std::endl - << "F_TARGET ( 0.0 0.0 ) # bi-objective" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - - // HISTORY_FILE: - // ------------- - if ( display_all || NOMAD::string_find ( "HISTORY_FILE BASIC \ - FILES OUTPUTS" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "HISTORY_FILE (basic)" ) << std::endl - << ". history file: contains all trial points" << std::endl - << ". does not include multiple evaluations" << std::endl - << ". argument: one string" << std::endl - << ". no default" << std::endl - << ". the seed is added to the file name" << std::endl - << " if ADD_SEED_TO_FILE_NAMES=\'yes\'" << std::endl - << ". example: HISTORY_FILE his.txt" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // INITIAL_MESH_SIZE: - // ------------------ - if ( display_all || NOMAD::string_find ( "INITIAL_MESH_SIZE BASIC MADS \ - DELTA_0 " , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "INITIAL_MESH_SIZE (basic)" ) << std::endl - << ". initial mesh size" << std::endl - << ". arguments: one or DIMENSION positive real(s)" << std::endl - << ". no default" << std::endl - << ". NOMAD uses one mesh size per variable." << std::endl - << ". values can be given with \'r\' to indicate a proportion of" << std::endl - << " the bounds range (bounds have to be defined for the" << std::endl - << " corresponding variables)" << std::endl - << ". initial poll size is determined from initial mesh size" << std::endl - << " when provided, but providing both is not allowed. " << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "INITIAL_MESH_SIZE 1.0 # for all variables" << std::endl - << "INITIAL_MESH_SIZE ( 3 - r0.1 ) # for all variables" << std::endl - << " # (default considered" << std::endl - << " # for 2nd variable)" << std::endl - << "INITIAL_MESH_SIZE 1 0.5 # for var. 1 only" << std::endl - << "INITIAL_MESH_SIZE 2-4 r0.25 # for var. 2 to 4" << std::endl - << NOMAD::close_block() - << NOMAD::close_block(); - chk = true; - } - - - // INITIAL_POLL_SIZE: - // ------------------ - if ( display_all || NOMAD::string_find ( "INITIAL_POLL_SIZE BASIC MADS \ - DELTA_0 " , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "INITIAL_POLL_SIZE (basic)" ) << std::endl - << ". initial poll size" << std::endl - << ". arguments: one or DIMENSION positive real(s)" << std::endl - << ". defaults: r0.1 if bounds are defined (10% of the range)," << std::endl - << " |x0|/10 otherwise (if x0!=0)" << std::endl - << ". NOMAD uses one poll size per variable to achieve scaling" << std::endl - << ". values can be given with \'r\' to indicate a proportion of" << std::endl - << " the bounds range (bounds have to be defined for the" << std::endl - << " corresponding variables)." << std::endl - << ". the initial mesh size is determined from initial poll size" << std::endl - << " when provided, but providing both is not allowed. " << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "INITIAL_POLL_SIZE 1.0 # for all variables" << std::endl - << "INITIAL_POLL_SIZE ( 3 - r0.1 ) # for all variables" << std::endl - << " # (default considered" << std::endl - << " # for 2nd variable)" << std::endl - << "INITIAL_POLL_SIZE 1 0.5 # for var. 1 only" << std::endl - << "INITIAL_POLL_SIZE 2-4 r0.25 # for var. 2 to 4" << std::endl - << NOMAD::close_block() - << NOMAD::close_block(); - chk = true; - } - - - // LH_SEARCH: - // ---------- - if ( display_all || NOMAD::string_find ( "LH_SEARCH LATIN-HYPERCUBE \ - SAMPLING BASIC" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "LH_SEARCH (basic)" ) << std::endl - << ". Latin-Hypercube sampling (search)" << std::endl - << ". arguments: two nonnegative integers p0 and pi" << std::endl - << ". defaults: no search for single-objective" << std::endl - << " or one initial search for bi-objective" << std::endl - << " (see user guide)" << std::endl - << ". p0: number of initial LH search points" << std::endl - << " (or in first MADS run for bi-obj.)" << std::endl - << ". pi: LH search points at each iteration" << std::endl - << " (or in 2nd MADS run for bi-obj.)" << std::endl - << ". the search can be opportunistic or not" << std::endl - << " (see parameter OPPORTUNISTIC_LH)" << std::endl - << ". example: LH_SEARCH 100 0" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // LOWER_BOUND: - // ------------ - if ( display_all || NOMAD::string_find ( "LOWER_BOUND BASIC LB BOUNDS FILES" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "LOWER_BOUND (basic)" ) << std::endl - << ". lower bounds for each variable" << std::endl - << ". no default" << std::endl - << ". can be defined by various methods (see user guide)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "LOWER_BOUND * 0.0 # all variables are nonnegative" << std::endl - << "LOWER_BOUND 0-2 0.0 # the 3 first var. are nonnegative" << std::endl - << "LOWER_BOUND 0 0.0 # the first var. is nonnegative" << std::endl - << "LOWER_BOUND lb.txt # bounds are defined in \'lb.txt\'" << std::endl - << " # containing DIMENSION values" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // MAX_BB_EVAL: - // ------------ - if ( display_all || NOMAD::string_find ( "MAX_BB_EVAL BASIC BLACK-BOXES BLACKBOXES \ - MAXIMUM CACHE BBEVAL \ - NUMBER EVALUATIONS STOPPING \ - BI-0BJECTIVE MULTI-OBJECTIVE \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_BB_EVAL (basic)" ) << std::endl - << ". maximum number of blackbox evaluations" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default" << std::endl - << ". doesn\'t consider evaluations taken in the" << std::endl - << " cache (cache hits)" << std::endl - << ". in bi-objective mode: max number of blackbox" << std::endl - << " evaluations for each MADS run" << std::endl - << ". example: MAX_BB_EVAL 1000" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MAX_TIME: - // --------- - if ( display_all || NOMAD::string_find ( "MAX_TIME BASIC BLACK-BOXES BLACKBOXES \ - MAXIMUM WALL-CLOCK REAL \ - STOPPING TERMINATION \ - TERMINATES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_TIME (basic)" ) << std::endl - << ". maximum wall-clock time in seconds" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default" << std::endl - << ". example: MAX_TIME 3600 # one hour max" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // SOLUTION_FILE: - // -------------- - if ( display_all || NOMAD::string_find ( "SOLUTION_FILE BASIC \ - FILES OUTPUTS" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SOLUTION_FILE (basic)" ) << std::endl - << ". file containing the solution" << std::endl - << ". argument: one string" << std::endl - << ". no default" << std::endl - << ". the seed is added to the file name if" << std::endl - << " ADD_SEED_TO_FILE_NAMES=\'yes\'" << std::endl - << ". example: SOLUTION_FILE sol.txt" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // STATS_FILE: - // ----------- - if ( display_all || NOMAD::string_find ( "STATS_FILE BASIC \ - FILES OUTPUTS DISPLAY_STATS" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "STATS_FILE (basic)" ) << std::endl - << ". file containing all successes with the same format" << std::endl - << " than DISPLAY_STATS" << std::endl - << ". displays more points with DISPLAY_ALL_EVAL=true" << std::endl - << ". arguments: one string (file name) and one" << std::endl - << " list of strings (stats)" << std::endl - << ". no default" << std::endl - << ". the seed is added to the file name if" << std::endl - << " ADD_SEED_TO_FILE_NAMES=\'yes\'" << std::endl - << ". example: STATS_FILE log.txt BBE SOL f=%.2EOBJ" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // TMP_DIR: - // -------- - if ( display_all || NOMAD::string_find ( "TMP_DIR BASIC PATH TEMPORARY \ - DIRECTORY FILES \ - BLACK-BOXES BLACKBOXES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "TMP_DIR (basic)" ) << std::endl - << ". temporary directory for blackbox input/output files" << std::endl - << ". argument: one string indicating a directory" << std::endl - << ". default: problem directory" << std::endl - << ". improved performance with a local temporary directory" << std::endl - << ". example: TMP_DIR /tmp" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // UPPER_BOUND: - // ------------ - if ( display_all || NOMAD::string_find ( "UPPER_BOUND BASIC UB BOUNDS" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "UPPER_BOUND (basic)" ) << std::endl - << ". upper bounds for each variable" << std::endl - << ". same logic as parameter LOWER_BOUND" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // X0: - // --- - if ( display_all || NOMAD::string_find ( "X0 STARTING POINT BASIC \ - VARIABLES \ - LH LATIN-HYPERCUBE \ - CACHE FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "X0 (basic)" ) << std::endl - << ". starting point(s)" << std::endl - << ". arguments: text file name," << std::endl - << " or cache file name," << std::endl - << " or DIMENSION reals," << std::endl - << " or indexed values" << std::endl - << ". default: best point from a cache file or from" << std::endl - << " an initial LH search" << std::endl - << ". do not use a surrogate cache file" << std::endl - << " (even if OPT_ONLY_SGTE=\'yes\')" << std::endl - << ". more than one starting point can be defined (all points" << std::endl - << " are evaluated: x0 evaluations are not opportunistic)" << std:: endl - << ". a text file can describe more than one point" << std::endl - << ". may be infeasible, but can only violate PB, F, or PEB" << std::endl - << " constraints" << std::endl - << ". cannot be outside bounds" << std::endl - << ". must respect fixed variables (param. FIXED_VARIABLE)" << std::endl - << ". " << NOMAD::open_block ("examples") << std::endl - << "X0 x0.txt # text file with a multiple" << std::endl - << " # of DIMENSION values" << std::endl << std::endl - << "X0 * 0.0 # first starting point" << std::endl - << "X0 1 * 1.0 # second starting point" << std::endl << std::endl - << "X0 ( 0 1 2 ) # if DIMENSION=3" << std::endl << std::endl - << "see other examples in user guide" << std::endl - << NOMAD::close_block() - << NOMAD::close_block(); - chk = true; - } - - - if ( display_all || NOMAD::string_find ( registered_key_advanced , param_names ) ) - { - _out << "--------------------------------------------------------------" << endl; - _out << "---------------------ADVANCED PARAMETERS----------------------" << endl; - _out << "--------------------------------------------------------------" << endl; - } - - // ADD_SEED_TO_FILE_NAMES: - // ----------------------- - if ( display_all || NOMAD::string_find ( "ADD_SEED_TO_FILE_NAMES OUTPUTS \ - ADVANCED FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "ADD_SEED_TO_FILE_NAMES (advanced)" ) << std::endl - << ". if \'yes\', the seed is added to the name of" << std::endl - << " output files (HISTORY_FILE, SOLUTION_FILE," << std::endl - << " and STATS_FILE)" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: ADD_SEED_TO_FILE_NAMES no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // ANISOTROPIC_MESH: - // ------------- - if ( display_all || NOMAD::string_find ( "ANISOTROPIC MESH SCALING" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "ANISOTROPIC_MESH (advanced)" ) << std::endl - << ". use anisotropic mesh for generating directions" << std::endl - << ". if \'yes\', the mesh size is scaled dynamically" << std::endl - << ". based on direction of success." << std::endl - << ". This option is compatible with Ortho Mads " << std::endl - << ". directions only " << std::endl - << ". default: \'yes\'" << std::endl - << ". example: ANISOTROPIC_MESH no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // ASYNCHRONOUS: - // ------------- - if ( display_all || NOMAD::string_find ( "ASYNCHRONOUS PARALLELISM MPI \ - ADVANCED PMADS" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "ASYNCHRONOUS (advanced)" ) << std::endl - << ". asynchronous strategy for the parallel version" << std::endl - << ". if \'yes\', there can be evaluations in progress" << std::endl - << " after an iteration has ended" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: ASYNCHRONOUS no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // BB_INPUT_INCLUDE_SEED: - // ---------------------- - if ( display_all || NOMAD::string_find ( "BB_INPUT_INCLUDE_SEED BLACK-BOXES \ - BLACKBOXES \ - ADVANCED FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_INPUT_INCLUDE_SEED (advanced)" ) << std::endl - << ". if \'yes\', the seed (\'SEED\') of the current" << std::endl - << " execution is put as the first entry in" << std::endl - << " all blackbox input files" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: BB_INPUT_INCLUDE_SEED yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // BB_INPUT_INCLUDE_TAG: - // --------------------- - if ( display_all || NOMAD::string_find ( "BB_INPUT_INCLUDE_TAG \ - BLACK-BOXES BLACKBOXES \ - ADVANCED FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_INPUT_INCLUDE_TAG (advanced)" ) << std::endl - << ". if \'yes\', the tag of a point is put as the first" << std::endl - << " entry in all blackbox input files (second" << std::endl - << " entry if BB_INPUT_INCLUDE_SEED=\'yes\')" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: BB_INPUT_INCLUDE_TAG yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // BB_REDIRECTION: - // --------------- - if ( display_all || NOMAD::string_find ( "BB_REDIRECTION BLACK-BOXES BLACKBOXES \ - ADVANCED OUTPUT FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_REDIRECTION (advanced)" ) << std::endl - << ". if NOMAD uses a redirection (\'>\') to" << std::endl - << " create blackbox output files" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". if \'no\', the blackbox has to manage its" << std::endl - << " own output files (see user guide)" << std::endl - << ". example: BB_INPUT_INCLUDE_TAG yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // CACHE_SAVE_PERIOD: - // ------------------ - if ( display_all || NOMAD::string_find ( "CACHE_SAVE_PERIOD OUTPUTS \ - ITERATIONS ADVANCED FILES" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "CACHE_SAVE_PERIOD (advanced)" ) << std::endl - << ". period (iterations) at which the cache file is saved" << std::endl - << " (if CACHE_FILE is defined; disabled for bi-objective)" << std::endl - << ". argument: one nonnegative integer" << std::endl - << ". default: 25" << std::endl - << ". example: CACHE_SAVE_PERIOD 10" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // CACHE_SEARCH: - // ------------- - if ( display_all || NOMAD::string_find ( "CACHE_SEARCH ADVANCED\ - CACHE_FILE SGTE_CACHE_FILE" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "CACHE_SEARCH (advanced)" ) << std::endl - << ". enable or disable the cache search" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". the search looks in the cache between iterations" << std::endl - << ". this can be useful when a non-empty initial cache" << std::endl - << " file is provided or with an extern cache that" << std::endl - << " the user updates independently" << std::endl - << ". example: CACHE_SEARCH yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // CLOSED_BRACE: - // ------------- - if ( display_all || NOMAD::string_find ( "CLOSED_BRACES INDENTATION TABULATIONS \ - BLOCKS ADVANCED DISPLAY" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "CLOSED_BRACE (advanced)" ) << std::endl - << ". string displayed at the end of indented" << std::endl - << " blocks in full display mode" << std::endl - << ". argument: one string" << std::endl - << ". default: \'}\'" << std::endl - << ". example: CLOSED_BRACE End" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // DISABLE MODELS / EVAL_SORT - //----------- - if ( display_all || NOMAD::string_find ( "MODEL DISABLE MODELS DISABLE_MODELS \ - MODEL_EVAL_SORT ADVANCED \ - EVAL_SORT \ - ORTHO N+1 QUAD QUADRATIC MODEL_SEARCH TGP " , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "DISABLE (advanced)" ) << std::endl - << ". this parameter is used to forcefully disable a feature." << std::endl - << ". argument: MODELS or EVAL_SORT" << std::endl - << ". # DISABLE MODELS is equivalent to set: " << std::endl - << " MODEL_EVAL_SORT no " << std::endl - << " MODEL_SEARCH no " << std::endl - << " DIRECTION_TYPE ORTHO N+1 NEG " << std::endl - << " # WARNING: extra settings of MODEL_EVAL_SORT," << std::endl - << " MODEL_SEARCH and DIRECTION_TYPE ORTHO N+1 QUAD" << std::endl - << " will be ignored " << std::endl - << ". # DISABLE EVAL_SORT: ordering by lexicographic order only. " << std::endl - << " # WARNING: setting of MODEL_EVAL_SORT," << std::endl - << " SURROGATE_EVAL_SORT and user priority " << std::endl - << " will be ignored" << std::endl - << ". default: no default" << std::endl - - << NOMAD::close_block(); - chk = true; - } - - // BB_MAX_BLOCK_SIZE - //----------- - if ( display_all || NOMAD::string_find ( "EVAL LIST MAX BLOCK SIZE BB BLACKBOX \ - BLACK-BOX OPPORTUNIST OPPORTUNISTIC PARALLEL", - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "BB_MAX_BLOCK_SIZE (advanced)" ) << std::endl - << ". maximum size of a block of evaluations send to the blackbox" << std::endl - << " executable at once. Blackbox executable can manage parallel" << std::endl - << " evaluations on its own. Opportunistic strategies may apply after" << std::endl - << " each block of evaluations." << std::endl - << " Depending on the algorithm phase, the blackbox executable will" << std::endl - << " receive at most BB_MAX_BLOCK_SIZE points to evaluate." << std::endl - << " When this parameter is greater than one, the number of evaluations"<< std::endl - << " may exceed the MAX_BB_EVAL stopping criterion." << std::endl - << ". argument: integer > 0" << std::endl - << ". example: BB_MAX_BLOCK_SIZE 3," << std::endl - << " The blackbox executable receives blocks of" << std::endl - << " at most 3 points for evaluation." << std::endl - << ". default: 1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // EXTENDED_POLL_ENABLED: - // ---------------------- - if ( display_all || NOMAD::string_find ( "EXTENDED_POLL_ENABLED \ - EXTENDED_POLL_DISABLED \ - MIXED MVP CATEGORICAL \ - ADVANCED" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "EXTENDED_POLL_ENABLED (advanced)" ) << std::endl - << ". if \'no\', the extended poll for categorical" << std::endl - << " variables is disabled" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". the extended poll uses the surrogate" << std::endl - << " if HAS_SGTE or SGTE_EXE is defined" << std::endl - << ". example: EXTENDED_POLL_ENABLED yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // EXTENDED_POLL_TRIGGER: - // ---------------------- - if ( display_all || NOMAD::string_find ( "EXTENDED_POLL_TRIGGER ADVANCED \ - MIXED MVP CATEGORICAL" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "EXTENDED_POLL_TRIGGER (advanced)" ) << std::endl - << ". extended poll trigger for categorical variables" << std::endl - << ". argument: one positive real (can be relative)" << std::endl - << ". an extended poll around the extended poll point y" << std::endl - << " constructed from an iterate xk is performed if" << std::endl - << " f(y) < f(xk)+trigger or f(y) < f(xk)+|f(x_k)|*trigger" << std::endl - << " (relative value)" << std::endl - << ". see details in user guide" << std::endl - << ". default: r0.1" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "EXTENDED_POLL_TRIGGER 10.0 # ext poll trigger of 10" << std::endl - << "EXTENDED_POLL_TRIGGER r0.2 # ext poll trigger of 20%" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - - // FIXED_VARIABLE: - // --------------- - if ( display_all || NOMAD::string_find ( "FIXED_VARIABLE VARIABLES ADVANCED \ - FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "FIXED_VARIABLE (advanced)" ) << std::endl - << ". fix some variables to some specific values" << std::endl - << ". arguments: variable indexes and values" << std::endl - << ". no default" << std::endl - << ". values are optional if at least one starting point" << std::endl - << " is defined" << std::endl - << ". can be given by a text file containing DIMENSION" << std::endl - << " entrie (use \'-\' for free variables)" << std::endl - << ". variables inside groups defined by VARIABLE_GROUP" << std::endl - << " cannot be fixed" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "FIXED_VARIABLE ( 0.0 - 0.0 ) # variables 0 and 2 are fixed" << std::endl - << "FIXED_VARIABLE fixed.txt # with a file" << std::endl - << "FIXED_VARIABLE 0-1 3.14 # 2 first variables fixed" << std::endl - << " # to 3.14" << std::endl - << "FIXED_VARIABLE 0 # first variable fixed to" << std::endl - << " # its X0 value" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // H_MAX_0: - // -------- - if ( display_all || NOMAD::string_find ( "H_MAX_0 HMAX_0 HMAX ADVANCED \ - CONSTRAINTS PB FILTER PEB \ - L1 L2 LINF L_INF \ - FEASIBILITY \ - PROGRESSIVE-BARRIER" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "H_MAX_0 (advanced)" ) << std::endl - << ". initial value of h_max (for PB and" << std::endl - << " F constraints handling strategies)" << std::endl - << ". argument: one positive real" << std::endl - << ". default: 1E+20" << std::endl - << ". points x such that h(x) > h_max are" << std::endl - << " rejected (h measures the feasibility)" << std::endl - << ". example: H_MAX_0 100.0" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // H_MIN: - // ------ - if ( display_all || NOMAD::string_find ( "H_MIN HMIN ADVANCED \ - CONSTRAINTS PB FILTER PEB \ - L1 L2 LINF L_INF \ - FEASIBILITY \ - PROGRESSIVE-BARRIER" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "H_MIN (advanced)" ) << std::endl - << ". value of h_min; x is feasible if h(x) <= h_min" << std::endl - << " (h measures the feasibility)" << std::endl - << ". argument: one positive real" << std::endl - << ". default: 0.0" << std::endl - << ". example: H_MIN 1E-5" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // H_NORM: - // ------- - if ( display_all || NOMAD::string_find ( "H_NORM ADVANCED \ - CONSTRAINTS PB FILTER PEB \ - L1 L2 LINF L_INF \ - FEASIBILITY \ - PROGRESSIVE-BARRIER" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "H_NORM (advanced)" ) << std::endl - << ". norm used by the F and PB constraints handling" << std::endl - << " strategies to compute h(x) (h measures the" << std::endl - << " feasibility)" << std::endl - << ". argument: one string in {\'L1\', \'L2\', \'Linf\'}" << std::endl - << ". default: \'L2\'" << std::endl - << ". example: H_NORM Linf" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // HAS_SGTE: - // --------- - if ( display_all || NOMAD::string_find ( "HAS_SGTE SGTE_EXE ADVANCED SURROGATES \ - BLACK-BOXES BLACKBOXES \ - SGTES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "HAS_SGTE (advanced)" ) << std::endl - << ". to indicate that the problem has a surrogate" << std::endl - << ". argument: one boolean (\'yes\' or \'no\') " << std::endl - << ". default: \'no\' if parameter SGTE_EXE is undefined," << std::endl - << " \'yes\' otherwise" << std::endl - << ". this parameter is not necessary in batch" << std::endl - << " mode, but essential in library mode when" << std::endl - << " no surrogate executable is provided" << std::endl - << ". example: HAS_SGTE yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // INF_STR: - // -------- - if ( display_all || NOMAD::string_find ( "INF_STR ADVANCED \ - INFINITY DISPLAY REALS" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "INF_STR (advanced)" ) << std::endl - << ". string used to display infinity" << std::endl - << ". argument: one string" << std::endl - << ". default: \"inf\"" << std::endl - << ". example: INF_STR Infinity" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MAX_CACHE_MEMORY: - // ----------------- - if ( display_all || NOMAD::string_find ( "MAX_CACHE_MEMORY ADVANCED \ - MAXIMUM RAM STOPPING \ - MB MEGA-BYTES MEGABYTES \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_CACHE_MEMORY (advanced)" ) << std::endl - << ". the program terminates as soon as the cache" << std::endl - << " reaches this memory limit" << std::endl - << ". argument: one positive integer (expressed in MB)" << std::endl - << ". default: 2000" << std::endl - << ". example: MAX_CACHE_MEMORY 1024 # limit of 1GB cache" << std::endl - << " # occupation" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MAX_CONSECUTIVE_FAILED_ITERATIONS: - // ---------------------------------- - if ( display_all || NOMAD::string_find ( "MAX_CONSECUTIVE_FAILED_ITERATIONS ADVANCED \ - TERMINATION STOPPING TERMINATES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_CONSECUTIVE_FAILED_ITERATIONS (advanced)" ) << std::endl - << ". maximum number of consecutive failed iterations" << std::endl - << ". arguments: one positive integer" << std::endl - << ". no default" << std::endl - << ". example: MAX_CONSECUTIVE_FAILED_ITERATIONS 5" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MAX_EVAL: - // --------- - if ( display_all || NOMAD::string_find ( "MAX_EVAL ADVANCED BLACK-BOXES BLACKBOXES \ - MAXIMUM CACHE BBEVAL \ - NUMBER EVALUATIONS STOPPING \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_EVAL (advanced)" ) << std::endl - << ". maximum number of evaluations" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default" << std::endl - << ". includes evaluations taken in" << std::endl - << " the cache (cache hits)" << std::endl - << ". example: MAX_EVAL 1000" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MAX_ITERATIONS: - // --------------- - if ( display_all || NOMAD::string_find ( "MAX_ITERATIONS ADVANCED \ - MAXIMUM MADS \ - NUMBER STOPPING \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_ITERATIONS (advanced)" ) << std::endl - << ". maximum number of MADS iterations" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default" << std::endl - << ". example: MAX_ITERATIONS 20" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MAX_SGTE_EVAL: - // -------------- - if ( display_all || NOMAD::string_find ( "MAX_SGTE_EVAL ADVANCED BLACK-BOXES \ - BLACKBOXES \ - MAXIMUM SURROGATES BBEVAL SGTES \ - NUMBER EVALUATIONS STOPPING \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_SGTE_EVAL (advanced)" ) << std::endl - << ". maximum number of surrogate evaluations" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default" << std::endl - << ". example: MAX_SGTE_EVAL 10000" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MAX_SIM_BB_EVAL: - // ---------------- - if ( display_all || NOMAD::string_find ( "MAX_SIM_BB_EVAL ADVANCED \ - BLACK-BOXES BLACKBOXES BBEVAL \ - MAXIMUM CACHE SIMULATED \ - NUMBER EVALUATIONS STOPPING \ - TERMINATES TERMINATION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MAX_SIM_BB_EVAL (advanced)" ) << std::endl - << ". maximum number of simulated blackbox evaluations" << std::endl - << ". argument: one positive integer" << std::endl - << ". no default" << std::endl - << ". the same as MAX_BB_EVAL except that it considers" << std::endl - << " initial cache hits (cache points that come from" << std::endl - << " a cache file)" << std::endl - << ". simulates the number of blackbox evaluations" << std::endl - << " when no cache file is used" << std::endl - << ". example: MAX_SIM_BB_EVAL 1000" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MESH_COARSENING_EXPONENT: - // ------------------------- - if ( display_all || NOMAD::string_find ( "MESH_COARSENING_EXPONENT ADVANCED \ - MADS W+ \\DELTA" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MESH_COARSENING_EXPONENT (advanced)" ) << std::endl - << ". mesh coarsening exponent w^+ used to update the mesh" << std::endl - << " after successes (\\Delta^m_{k+1}=\\tau^{w^+}\\Delta^m_k)" << std::endl - << ". argument: one nonnegative integer" << std::endl - << ". default: 1" << std::endl - << ". example: MESH_COARSENING_EXPONENT 0 # the mesh size is" << std::endl - << " # not increased" << std::endl - << " # after successes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MESH_REFINING_EXPONENT: - // ----------------------- - if ( display_all || NOMAD::string_find ( "MESH_REFINING_EXPONENT ADVANCED \ - MADS W- \\DELTA" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MESH_REFINING_EXPONENT (advanced)" ) << std::endl - << ". mesh refining exponent w^- used to update the mesh" << std::endl - << " after failures (\\Delta^m_{k+1} = \\tau^{w^-}\\Delta^m_k)" << std::endl - << ". argument: one negative" << std::endl - << ". default: -1" << std::endl - << ". example: MESH_REFINING_EXPONENT -2" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MESH_UPDATE_BASIS: - // ------------------ - if ( display_all || NOMAD::string_find ( "MESH_UPDATE_BASIS ADVANCED \ - MADS \\TAU \\DELTA" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MESH_UPDATE_BASIS (advanced)" ) << std::endl - << ". mesh update basis \\tau used to update the" << std::endl - << " mesh (\\Delta^m_{k+1} = \\tau^w\\Delta^m_k)" << std::endl - << ". argument: one positive real > 1" << std::endl - << ". default: 4.0" << std::endl - << ". example: MESH_UPDATE_BASIS 2.0" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MIN_MESH_SIZE: - // -------------- - if ( display_all || NOMAD::string_find ( "MIN_MESH_SIZE ADVANCED \ - \\DELTA MINIMUM TERMINATION \ - STOPPING TERMINATES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MIN_MESH_SIZE (advanced)" ) << std::endl - << ". minimum mesh size" << std::endl - << ". arguments: same logic as INITIAL_MESH_SIZE" << std::endl - << " (\'r\' can be used)" << std::endl - << ". no default" << std::endl - << ". example: MIN_MESH_SIZE r1E-5" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MIN_POLL_SIZE: - // -------------- - if ( display_all || NOMAD::string_find ( "MIN_POLL_SIZE MESH ADVANCED \ - \\DELTA^P MINIMUM TERMINATION \ - STOPPING TERMINATES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MIN_POLL_SIZE (advanced)" ) << std::endl - << ". minimum poll size" << std::endl - << ". arguments: same logic as INITIAL_MESH_SIZE" << std::endl - << " (\'r\' can be used)" << std::endl - << ". default: 1.0 for integer or binary variables, no default otherwise" - << std::endl - << ". example: MIN_POLL_SIZE r1E-5" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MODEL_EVAL_SORT: - // ---------------- - if ( display_all || NOMAD::string_find ( "MODEL_ORDERING MODEL_EVAL_SORT ADVANCED \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC \ - TGP" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_EVAL_SORT (advanced)" ) << std::endl - << ". if models are used to sort the trial points" << std::endl - << ". disabled for more than 50 variables" << std::endl - << ". disabled with categorical variables" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << " or one string in {\'QUADRATIC\', \'TGP\'}" << std::endl - << ". default: \'QUADRATIC\'" << std::endl - << ". examples: MODEL_EVAL_SORT quadratic" << std::endl - << " MODEL_EVAL_SORT yes # quadratic is used" << std::endl - << " MODEL_EVAL_SORT no # no MES" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MODEL_SEARCH: - // ------------- - if ( display_all || NOMAD::string_find ( "MODEL_SEARCH ADVANCED CATEGORICAL \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC PARALLEL \ - TGP" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_SEARCH (advanced)" ) << std::endl - << ". model search (MS)" << std::endl - << ". can be entered twice in order to define two searches" << std::endl - << ". disabled for more than 50 variables" << std::endl - << ". disabled with categorical variables" << std::endl - << ". disabled in parallel mode" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << " or one string in {\'QUADRATIC\', \'TGP\'}" << std::endl - << ". default: \'QUADRATIC\'" << std::endl - << ". example: MODEL_SEARCH QUADRATIC" << std::endl - << " MODEL_SEARCH TGP" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // MODEL_SEARCH_OPTIMISTIC: - // ------------------------ - if ( display_all || NOMAD::string_find ( "MODEL_SEARCH_OPTIMISTIC ADVANCED \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC \ - TGP" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_SEARCH_OPTIMISTIC (advanced)" ) << std::endl - << ". model search (MS) is optimistic or not" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: MODEL_SEARCH_OPTIMISTIC no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MULTI_F_BOUNDS: - // --------------- - if ( display_all || NOMAD::string_find ( "MULTI_F_BOUNDS ADVANCED PARETO \ - BI-OBJECTIVES MULTI-OBJECTIVES \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS SURF" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MULTI_F_BOUNDS (advanced)" ) << std::endl - << ". multi-objective optimization: bounds on the two" << std::endl - << " objective functions" << std::endl - << ". arguments: 4 reals: f1_min f1_max f2_min f2_max" << std::endl - << ". default: none" << std::endl - << ". these values are used to display the \'surf\' statistics" << std::endl - << " on Pareto fronts (useful to compare different Pareto" << std::endl - << " fronts)" << std::endl - << ". \'surf\' will not be displayed with invalid values (for example" - << std::endl - << " if a dominant point has a f2 value greater than f2_max)" << std::endl - << ". example: MULTI_F_BOUNDS 0 10 0 10" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MULTI_NB_MADS_RUNS: - // ------------------- - if ( display_all || NOMAD::string_find ( "MULTI_NB_MADS_RUNS ADVANCED \ - BI-OBJECTIVES MULTI-OBJECTIVES \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS \ - NUMBER" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MULTI_NB_MADS_RUNS (advanced)" ) << std::endl - << ". multi-objective optimization:" << std::endl - << " number of MADS runs" << std::endl - << ". argument: one positive integer" << std::endl - << ". default: see user guide" << std::endl - << ". example: MULTI_NB_MADS_RUNS 30" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MULTI_OVERALL_BB_EVAL: - // --------------------- - if ( display_all || NOMAD::string_find ( "MULTI_OVERALL_BB_EVAL ADVANCED \ - BI-OBJECTIVES MULTI-OBJECTIVES \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS \ - NUMBER BLACK-BOXES BLACKBOXES BBEVAL \ - EVALUATIONS TERMINATION \ - STOPPING TERMINATES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "MULTI_OVERALL_BB_EVAL (advanced)" ) << std::endl - << ". multi-objective optimization: maximum" << std::endl - << " number of blackbox evaluations" << std::endl - << ". argument: one positive integer" << std::endl - << ". default: see user guide" << std::endl - << ". example: MULTI_OVERALL_BB_EVAL 1000" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // NEIGHBORS_EXE: - // -------------- - if ( display_all || NOMAD::string_find ( "NEIGHBORS_EXE NEIGHBOURS \ - NEIGHBORHOODS NEIGHBOURHOODS \ - EXTENDED_POLL \ - MIXED MVP CATEGORICAL \ - ADVANCED" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "NEIGHBORS_EXE (advanced)" ) << std::endl - << ". to indicate a neighborhood executable for categorical" << std::endl - << " variables in batch mode" << std::endl - << ". arguments: one string" << std::endl - << ". no default" << std::endl - << ". the executable must take a file with the coordinates of" << std::endl - << " a point as argument and displays a list of neighbors" << std::endl - << ". the number of variables must be the same" << std::endl - << ". when the \'$\' character is put in first position of a" << std::endl - << " string, it is considered as global and no path is added" << std::endl - << ". see user guide for details" << std::endl - << ". example: NEIGHBORS_EXE neighbors.exe" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPEN_BRACE: - // ----------- - if ( display_all || NOMAD::string_find ( "OPEN_BRACES INDENTATION TABULATIONS \ - BLOCKS ADVANCED DISPLAY" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "OPEN_BRACE (advanced)" ) << std::endl - << ". string displayed at the beginning of indented" << std::endl - << " blocks in full display mode" << std::endl - << ". argument: one string" << std::endl - << ". default: \'{\'" << std::endl - << ". example: OPEN_BRACE Begin" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPPORTUNISTIC_CACHE_SEARCH: - // --------------------------- - if ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_CACHE_SEARCH ADVANCED \ - BLACK-BOXES BLACKBOXES EVALUATIONS \ - SUCCESSES CACHE SEARCH" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_CACHE_SEARCH (advanced)" ) << std::endl - << ". opportunistic strategy for cache search" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: OPPORTUNISTIC_CACHE_SEARCH yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPPORTUNISTIC_EVAL: - // ------------------- - if ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_EVAL ADVANCED \ - BLACK-BOXES BLACKBOXES EVALUATIONS \ - SUCCESSES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_EVAL (advanced)" ) << std::endl - << ". opportunistic strategy (terminate a list of" << std::endl - << " evaluations after successes)" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". type \'nomad -h opportunistic\' to see advanced options" << std::endl - << ". example: OPPORTUNISTIC_EVAL no # complete evaluations" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // OPPORTUNISTIC_LH: - // ----------------- - if ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_LH ADVANCED \ - BLACK-BOXES BLACKBOXES EVALUATIONS \ - SUCCESSES LATIN-HYPERCUBE SEARCH" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_LH (advanced)" ) << std::endl - << ". opportunistic strategy for Latin-Hypercube search" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: same value as OPPORTUNISTIC_EVAL" << std::endl - << ". example: OPPORTUNISTIC_LH no # complete evaluations" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // OPPORTUNISTIC_MIN_EVAL: - // ----------------------- - if ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_MIN_EVAL ADVANCED \ - BLACK-BOXES BLACKBOXES EVALUATIONS \ - SUCCESSES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_MIN_EVAL (advanced)" ) << std::endl - << ". advanced parameter for the opportunistic" << std::endl - << " strategy (see user guide)" << std::endl - << ". argument: one nonnegative integer" << std::endl - << ". no default" << std::endl - << ". example: OPPORTUNISTIC_MIN_EVAL 3" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // PERIODIC_VARIABLE: - // ------------------ - if ( display_all || NOMAD::string_find ( "PERIODIC_VARIABLE VARIABLES ADVANCED \ - BOUNDS LB UB CYCLIC MADS" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "PERIODIC_VARIABLE (advanced)" ) << std::endl - << ". specify that some variables are periodic" << std::endl - << ". arguments: variable indexes" << std::endl - << ". no default" << std::endl - << ". bounds must be defined for these variables" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "PERIODIC_VARIABLE * # all variables are periodic" << std::endl - << "PERIODIC_VARIABLE 0-1 # 2 first var. are periodic" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // POINT_DISPLAY_LIMIT: - // -------------------- - if ( display_all || NOMAD::string_find ( "POINT_DISPLAY_LIMIT OUTPUTS \ - ADVANCED PRECISION" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "POINT_DISPLAY_LIMIT (advanced)" ) << std::endl - << ". maximum number of point coordinates" << std::endl - << " that are displayed" << std::endl - << ". argument: one positive integer" << std::endl - << ". default: 20" << std::endl - << ". example: POINT_DISPLAY_LIMIT 10" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // POLL_UPDATE_BASIS: - // ------------------ - if ( display_all || NOMAD::string_find ( "POLL_UPDATE_BASIS ADVANCED \ - MADS ANISOTROPIC MESH \\TAU \\DELTA" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "POLL_UPDATE_BASIS (advanced)" ) << std::endl - << ". poll update basis \\tau used to update the" << std::endl - << " poll (\\Delta^{k+1} = \\tau^w\\Delta^k)" << std::endl - << ". argument: one positive real > 1" << std::endl - << ". default: 2.0" << std::endl - << ". example: POLL_UPDATE_BASIS 1.5" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // RHO: - // ---- - if ( display_all || NOMAD::string_find ( "RHO ADVANCED MADS CONSTRAINTS \ - PROGRESSIVE-BARRIER PB PEB \ - FILTER TRIGGER" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "RHO (advanced)" ) << std::endl - << ". rho parameter of the progressive barrier" << std::endl - << ". argument: one nonnegative real" << std::endl - << ". default: 0.1" << std::endl - << ". example: RHO 0.5" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // SCALING: - // -------- - if ( display_all || NOMAD::string_find ( "SCALING SCALE ADVANCED \ - FILES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SCALING (advanced)" ) << std::endl - << ". variable scaling" << std::endl - << ". arguments: variable indexes and values" << std::endl - << ". no default" << std::endl - << ". variables are multiplied by these values: they are scaled" << std::endl - << " before an evaluation and the call to Evaluator::eval_x()," << std::endl - << " and unscaled after the evaluation" << std::endl - << ". all NOMAD outputs (including files) display unscaled values" << std::endl - << ". all variable-related parameters (bounds, starting points," << std::endl - << " fixed variables) must be specified without scaling" << std::endl - << ". can be given by a text file containing DIMENSION entries" << std::endl - << " (use \'-\' for unscaled variables)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "SCALING ( 0.1 - 100 ) # variables 0 and 2 are scaled" << std::endl - << "SCALING scaling.txt # with a file" << std::endl - << "SCALING 0-1 10.0 # 2 first variables scaled" << std::endl - << " # by factor 10" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - - // SEED: - // ----- - if ( display_all || NOMAD::string_find ( "SEED ADVANCED \ - RANDOM FILES ORTHOMADS LT-MADS LTMADS \ - LATIN-HYPERCUBE LH TGP \ - SAMPLING SEARCH" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SEED (advanced)" ) << std::endl - << ". random seed" << std::endl - << ". argument: one integer in [0," << UINT32_MAX << "] U {-1} or the string \'DIFF\'" << std::endl - << ". default: \'" << NOMAD::RNG::get_seed() << "\'" << std::endl - << ". the default value is used for each run if" << std::endl - << " the parameter is not provided. " << std::endl - << ". if '-1' or \'DIFF\' is entered " << std::endl - << " the seed is different for each run (PID is used)." << std::endl - << ". the seed is used in the output file names" << std::endl - << ". the seed affects the randomness of " << std::endl - << " Ortho-MADS and LT-MADS directions," << std::endl - << " Latin-Hypercube search, and TGP search." << std::endl - << ". example: SEED 123456" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // SGTE_CACHE_FILE: - // ---------------- - if ( display_all || NOMAD::string_find ( "SGTE_CACHE_FILE ADVANCED \ - SURROGATES SGTES \ - FILES OUTPUTS" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SGTE_CACHE_FILE (advanced)" ) << std::endl - << ". surrogate cache file; cannot be the same" << std::endl - << " as CACHE_FILE" << std::endl - << ". argument: one string" << std::endl - << ". no default" << std::endl - << ". points already in the file will be tagged" << std::endl - << " as surrogate evaluations" << std::endl - << ". example: SGTE_CACHE_FILE sgte_cache.bin" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // SGTE_COST: - // ---------- - if ( display_all || NOMAD::string_find ( "SGTE_COST SURROGATES SGTES ADVANCED \ - BLACK-BOXES BLACKBOXES" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "SGTE_COST (advanced)" ) << std::endl - << ". cost of the surrogate function relatively" << std::endl - << " to the true function" << std::endl - << ". argument: one nonnegative integer" << std::endl - << ". default: infinity (no surrogate cost)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "SGTE_COST 3 # three surrogate evaluations" << std::endl - << " # count as one blackbox" << std::endl - << " # evaluation (the surrogate" << std::endl - << " # is three times faster)" << std::endl - << "SGTE_COST -1 # set to infinity" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // SGTE_EVAL_SORT: - // --------------- - if ( display_all || NOMAD::string_find ( "SGTE_EVAL_SORT ADVANCED SURROGATES \ - SGTE_ORDERING SGTES BLACK-BOXES \ - BLACKBOXES" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SGTE_EVAL_SORT (advanced)" ) << std::endl - << ". if surrogate is used to sort the trial points" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: SGTE_EVAL_SORT NO" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // SGTE_EXE: - // ---------- - if ( display_all || NOMAD::string_find ( "SGTE_EXE HAS_SGTE ADVANCED SURROGATES \ - SGTES BLACK-BOXES BLACKBOXES \ - FILES EXECUTABLE" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SGTE_EXE (advanced)" ) << std::endl - << ". to indicate a surrogate executable" << std::endl - << ". arguments: one or two strings" << std::endl - << ". no default" << std::endl - << ". surrogate(s) and blackbox(es) must have the same" << std::endl - << " number of outputs" << std::endl - << ". if surrogates are used, every blackbox executable" << std::endl - << " must have a surrogate" - << std::endl - << ". automatically sets HAS_SGTE to \'yes\'" << std::endl - << ". " << NOMAD::open_block ( "examples" ) << std::endl - << "SGTE_EXE b1.exe s1.exe # \'s1.exe\' is a surrogate" << std::endl - << " # for \'b1.exe\'" << std::endl << std::endl - << "SGTE_EXE sgte.exe # only if one blackbox" << std::endl - << " # executable is used" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // SNAP_TO_BOUNDS: - // --------------- - if ( display_all || NOMAD::string_find ( "SNAP_TO_BOUNDS PROJECTION \ - ADVANCED" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "SNAP_TO_BOUNDS (advanced)" ) << std::endl - << ". if \'yes\', snap to bounds points generated" << std::endl - << " outside boundaries" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: SNAP_TO_BOUNDS no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // SPECULATIVE_SEARCH: - // ------------------- - if ( display_all || NOMAD::string_find ( "SPECULATIVE_SEARCH MADS OPTIMISTIC \ - ADVANCED" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "SPECULATIVE_SEARCH (advanced)" ) << std::endl - << ". MADS speculative_search (optimistic strategy)" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: SPECULATIVE_SEARCH no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // STAT_SUM_TARGET: - // ---------------- - if ( display_all || NOMAD::string_find ( "STAT_SUM_TARGET ADVANCED TERMINATION \ - STOPPING TERMINATES STATS" , param_names ) ) - { - _out << std::endl - << NOMAD::open_block ( "STAT_SUM_TARGET (advanced)" ) << std::endl - << ". MADS terminates if STAT_SUM reaches the value of this" << std::endl - << " parameter (STAT_SUM is one of the possible outputs" << std::endl - << " defined in BB_OUTPUT_TYPE)" << std::endl - << ". argument: one real" << std::endl - << ". no default" << std::endl - << ". example: STAT_SUM_TARGET 100.0" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // STOP_IF_FEASIBLE: - // ----------------- - if ( display_all || NOMAD::string_find ( "STOP_IF_FEASIBLE ADVANCED \ - TERMINATES TERMINATION STOPPING" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "STOP_IF_FEASIBLE (advanced)" ) << std::endl - << ". the algorithm terminates if it generates" << std::endl - << " a feasible solution" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: STOP_IF_FEASIBLE yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // UNDEF_STR: - // ---------- - if ( display_all || NOMAD::string_find ( "UNDEF_STR ADVANCED \ - UNDEFINED DISPLAY REALS" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "UNDEF_STR (advanced)" ) << std::endl - << ". string used to display undefined real values" << std::endl - << ". argument: one string" << std::endl - << ". default: \"-\"" << std::endl - << ". example: UNDEF_STR Undefined" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // USER_CALLS_ENABLED: - // ------------------- - if ( display_all || NOMAD::string_find ( "USER_CALLS_ENABLED USER_CALLS_DISABLED \ - ADVANCED LIBRARY" , - param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "USER_CALLS_ENABLED (advanced)" ) << std::endl - << ". if \'no\', the automatic calls to user" << std::endl - << " functions are disabled" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: USER_CALLS_ENABLED yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // VARIABLE_GROUP: - // -------------- - if ( display_all || NOMAD::string_find ( "VARIABLE_GROUP GROUPS PSD-MADS PSDMADS \ - VARIABLES ADVANCED" , param_names ) ) { - _out << std::endl - << NOMAD::open_block ( "VARIABLE_GROUP (advanced)" ) << std::endl - << ". defines groups of variables" << std::endl - << ". MADS directions are applied separately for" << std::endl - << " each group" << std::endl - << ". also used by PSD-MADS (not yet implemented)" << std::endl - << ". groups cannot include fixed variables" << std::endl - << ". arguments: variable indexes" << std::endl - << ". default groups are created for different types" << std::endl - << " of variables" << std::endl - << ". no other default" << std::endl - << ". advanced options only available in library mode" << std::endl - << " (see user guide)" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "VARIABLE_GROUP 2-5" << std::endl - << "VARIABLE_GROUP 0 1 3" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - - // VNS_SEARCH: - // ----------- - if ( display_all || NOMAD::string_find ( "VNS_SEARCH NEIGHBORHOOD \ - METAHEURISTICS META-HEURISTICS \ - GLOBAL ADVANCED \ - TRIGGER" , - param_names ) ) { - - if ( !NOMAD::string_find ( "RHO" , param_names ) ) { - - _out << std::endl - << NOMAD::open_block ( "VNS_SEARCH (advanced)" ) << std::endl - << ". Variable Neighborhood Search (VNS) search" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << " or one real in [0;1] for the VNS trigger" << std::endl - << ". default: \'no\' (same as 0.0)" << std::endl - << ". the VNS trigger is the maximum desired ratio of" << std::endl - << " VNS blackbox evaluations over the total number" << std::endl - << " of blackbox evaluations" << std::endl - << ". the VNS search is never executed with a null trigger" << std::endl - << " while a value of 1 allows the search at every" << std::endl - << " iteration" << std::endl - << ". if VNS_SEARCH=\'yes\', the default value of 0.75 is" << std::endl - << " taken for the trigger" << std::endl - << ". VNS search uses the surrogate if HAS_SGTE or" << std::endl - << " SGTE_EXE is defined" << std::endl - << ". " << NOMAD::open_block ( "examples" ) - << "VNS_SEARCH yes # VNS trigger of 75%" << std::endl - << "VNS_SEARCH 0.5 # VNS trigger of 50%" << std::endl - << NOMAD::close_block() << NOMAD::close_block(); - chk = true; - } - } - - - - // last display: - if ( !chk && !developer) { - - std::string pname = ( pnames.size() == 1 ) ? - ("\'" + *pnames.begin() + "\'") : - "the specified list of parameter names"; - - _out << std::endl << "no help available for " << pname << std::endl - << "help example: \'nomad -h mesh\' displays help on the mesh parameters" - << std::endl; - } - - if (developer && NOMAD::string_find(registered_key_developer,param_names)) - { - _out << "--------------------------------------------------------------" << endl; - _out << "---------------------DEVELOPER PARAMETERS---------------------" << endl; - _out << "--------------------------------------------------------------" << endl; - } - - // EPSILON: - // -------- - if ( developer && (display_all || NOMAD::string_find ( "EPSILON DEVELOPPER \ - PRECISION REALS COMPARISONS" , - param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "EPSILON (developer)" ) << std::endl - << ". precision on reals" << std::endl - << ". argument: one positive real" << std::endl - << ". default: 1E-13" << std::endl - << ". example: EPSILON 1E-8" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // INITIAL_MESH_INDEX: - // ------------------- - if ( developer && ( display_all || NOMAD::string_find ( "INITIAL_MESH_INDEX DEVELOPER SMESH \ - \\DELTA MADS L0 L_0 \\ELL_0" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "INITIAL_MESH_INDEX (developer)" ) << std::endl - << ". initial mesh index for SMesh \\ell_0" << std::endl - << ". argument: one integer (can be negative)" << std::endl - << ". default: 0" << std::endl - << ". example: INITIAL_MESH_INDEX -1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // L_CURVE_TARGET: - // --------------- - if ( developer && ( display_all || NOMAD::string_find ( "L_CURVE_TARGET DEVELOPER TERMINATION \ - STOPPING TERMINATES" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "L_CURVE_TARGET (developer)" ) << std::endl - << ". MADS terminates if it detects that the objective will" << std::endl - << " not reach this value (based on an approximation" << std::endl - << " of the L-shaped curve obj_value v.s. bb_eval)" << std::endl - << ". argument: one real" << std::endl - << ". no default" << std::endl - << ". example: L_CURVE_TARGET 10.0" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - - // MODEL_EVAL_SORT_CAUTIOUS: - // ------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "MODEL_ORDERING MODEL_EVAL_SORT_CAUTIOUS \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS DEVELOPER \ - QUADRATIC TGP" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_EVAL_SORT_CAUTIOUS (developer)" ) << std::endl - << ". if the model ordering strategy is cautious, meaning" << std::endl - << " that models are evaluated only within a trust radius" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: MODEL_EVAL_SORT_CAUTIOUS no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_QUAD_MAX_Y_SIZE: - // ---------------------- - if ( developer && ( display_all || NOMAD::string_find ( "MODEL_QUAD_MAX_Y_SIZE MODEL_SEARCH DEVELOPER \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_QUAD_MAX_Y_SIZE (developer)" ) << std::endl - << ". Sup. limit on the size of interp. set Y for quadr. models" << std::endl - << ". arguments: one integer greater than the number of variables" << std::endl - << ". default: 500" << std::endl - << ". example: MODEL_QUAD_MAX_Y_SIZE 10" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_QUAD_MIN_Y_SIZE: - // ---------------------- - if ( developer && (display_all || NOMAD::string_find ( "MODEL_QUAD_MIN_Y_SIZE MODEL_SEARCH DEVELOPER \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_QUAD_MIN_Y_SIZE (developer)" ) << std::endl - << ". Inf. limit on the size of interp. set Y for quadr. models" << std::endl - << ". arguments: one integer > 1 or the string \'N+1\'" << std::endl - << ". default: N+1" << std::endl - << ". examples: MODEL_QUAD_MIN_Y_SIZE N+1" << std::endl - << " MODEL_QUAD_MIN_Y_SIZE -1 # same as N+1" << std::endl - << " MODEL_QUAD_MIN_Y_SIZE 2" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_QUAD_RADIUS_FACTOR: - // ------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "MODEL_QUAD_RADIUS_FACTOR MODEL_SEARCH \ - DEVELOPER MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_QUAD_RADIUS_FACTOR (developer)" ) << std::endl - << ". quadratic model search radius factor (see user guide)" << std::endl - << ". arguments: one strictly positive real" << std::endl - << ". default: 2.0" << std::endl - << ". example: MODEL_QUAD_RADIUS_FACTOR 1.0" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_SEARCH_MAX_TRIAL_PTS: - // --------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "MODEL_SEARCH_MAX_TRIAL_PTS \ - DEVELOPER MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC \ - TGP" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_SEARCH_MAX_TRIAL_PTS (developer)" ) << std::endl - << ". limit on the number of trial points for one model search" << std::endl - << ". arguments: one integer greater than or equal to 1" << std::endl - << ". the quadratic model search will not generate more than 4 points" << std::endl - << ". default: 10" << std::endl - << ". example: MODEL_SEARCH_MAX_TRIAL_PTS 1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_SEARCH_PROJ_TO_MESH: - // -------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "MODEL_SEARCH_PROJ_TO_MESH DEVELOPER \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC PROJECTION \ - TGP" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_SEARCH_PROJ_TO_MESH (developer)" ) << std::endl - << ". if model search trial points are projected to the mesh" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: MODEL_SEARCH_PROJ_TO_MESH no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_QUAD_USE_WP: - // ------------------ - if ( developer && ( display_all || NOMAD::string_find ( "MODEL_QUAD_USE_WP DEVELOPER \ - WELL-POISEDNESS \ - MODELS INTERPOLATION REGRESSION \ - MFN FROBENIUS QUADRATIC" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "MODEL_QUAD_USE_WP (developer)" ) << std::endl - << ". enable the strategy to maintain WP with quadr. models" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: MODEL_QUAD_USE_WP yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MODEL_NP1_QUAD_EPSILON : - // --------------- - if ( developer && (display_all || NOMAD::string_find ( "MODEL MODELS NP1 QUAD EPSILON \ - ORTHO N+1 QUAD DEVELOPER" , - param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "MODEL_NP1_QUAD_EPSILON (developer)" ) << std::endl - << ". with the direction type ORTHO N+1 QUAD selected the" << std::endl - << " (n+1)-th direction is determined within a truncated " << std::endl - << " unit hypercube ]epsilon;1[^n defined by the first " << std::endl - << " n-th directions. The truncation is on lower limit " << std::endl - << " and is defined with a single argument (epsilon)." << std::endl - << ". argument: real in ]0;1[" << std::endl - << ". default: 0.01" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MODEL_TGP_MODE: - // --------------- - if ( developer && (display_all || NOMAD::string_find ( "MODEL_TGP_MODE MODEL_SEARCH DEVELOPER \ - MODELS INTERPOLATION REGRESSION \ - TGP" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MODEL_TGP_MODE (developer)" ) << std::endl - << ". TGP mode (fast or precise)" << std::endl - << ". arguments: one string in {\'FAST\', \'PRECISE\'}" << std::endl - << ". default: \'FAST\'" << std::endl - << ". example: MODEL_TGP_MODE PRECISE" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MODEL_TGP_REUSE_MODEL: - // ---------------------- - if (developer && ( display_all || NOMAD::string_find ( "MODEL_TGP_REUSE_MODEL DEVELOPER \ - MODELS INTERPOLATION REGRESSION \ - TGP" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "MODEL_TGP_REUSE_MODEL (developer)" ) << std::endl - << ". enable to use the last model from the TGP search for" << std::endl - << " the TGP model eval sort strategy." << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'yes\'" << std::endl - << ". example: MODEL_TGP_REUSE_MODEL no" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // MULTI_FORMULATION: - // ----------------- - if ( developer && (display_all || NOMAD::string_find ( "MULTI_FORMULATION DEVELOPER PARETO \ - BI-OBJECTIVES MULTI-OBJECTIVES\ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS" , - param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "MULTI_FORMULATION (developer)" ) << std::endl - << ". multi-objective optimization: single-objective reformulation" - << std::endl - << ". argument: one string in {\'NORMALIZED\', \'PRODUCT\', \'DIST_L1\'," - << std::endl - << " \'DIST_L2\', \'DIST_LINF\'}" << std::endl - << " (\'NORMALIZED\' and \'DIST_LINF\' are equivalent)" << std::endl - << ". default: \'PRODUCT\' or \'DIST_L2\' if VNS_SEARCH is set to \'yes\'" - << std::endl - << ". example: MULTI_FORMULATION DIST_L1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // MULTI_USE_DELTA_CRIT: - // --------------------- - if ( developer && ( display_all || NOMAD::string_find ( "MULTI_USE_DELTA_CRITERION DEVELOPER PARETO \ - BIOBJECTIVES MULTIOBJECTIVES \ - BI-MADS BIMADS \ - BI-OBJECTIVES MULTI-OBJECTIVES" , - param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "MULTI_USE_DELTA_CRIT (developer)" ) << std::endl - << ". multi-objective optimization: use the delta criterion" << std::endl - << " (can result in a better distributed Pareto front)" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: MULTI_USE_DELTA_CRIT yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPPORTUNISTIC_LUCKY_EVAL: - // ------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_LUCKY_EVAL DEVELOPER \ - BLACK-BOXES BLACKBOXES EVALUATIONS \ - SUCCESSES" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_LUCKY_EVAL (developer)" ) << std::endl - << ". developer parameter for the opportunistic" << std::endl - << " strategy" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". default: \'no\'" << std::endl - << ". example: OPPORTUNISTIC_LUCKY_EVAL yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPPORTUNISTIC_MIN_F_IMPRVMT: - // ---------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_MIN_F_IMPRVMT DEVELOPER \ - OBJECTIVE \ - BLACK-BOXES BLACKBOXES EVALUATIONS \ - SUCCESSES IMPROVEMENT" , param_names ) ) ) { - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_MIN_F_IMPRVMT (developer)" ) << std::endl - << ". advanced parameter for the opportunistic" << std::endl - << " strategy (see user guide)" << std::endl - << ". argument: one real" << std::endl - << ". no default" << std::endl - << ". example: OPPORTUNISTIC_MIN_F_IMPRVMT 0.1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPPORTUNISTIC_MIN_NB_SUCCESS: - // ----------------------------- - if ( developer && ( display_all || NOMAD::string_find ( "OPPORTUNISTIC_MIN_NB_SUCCESSES DEVELOPER \ - BLACK-BOXES BLACKBOXES \ - EVALUATIONS" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "OPPORTUNISTIC_MIN_NB_SUCCESS (developer)" ) << std::endl - << ". advanced parameter for the opportunistic" << std::endl - << " strategy (see user guide)" << std::endl - << ". argument: one nonnegative integer" << std::endl - << ". no default" << std::endl - << ". example: OPPORTUNISTIC_MIN_NB_SUCCESS 2" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // OPT_ONLY_SGTE: - // -------------- - if (developer && ( display_all || NOMAD::string_find ( "OPT_ONLY_SGTES DEVELOPER SURROGATES \ - BLACK-BOXES BLACKBOXES \ - SGTES" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "OPT_ONLY_SGTE (developer)" ) << std::endl - << ". NOMAD will only minimize the surrogate" << std::endl - << ". argument: one boolean (\'yes\' or \'no\')" << std::endl - << ". SGTE_EXE or HAS_SGTE must be defined" << std::endl - << ". default: \'no\'" << std::endl - << ". example: OPT_ONLY_SGTE yes" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // SEC_POLL_DIR_TYPES: - // ------------------- - if ( developer && ( display_all || NOMAD::string_find ( "SEC_POLL_DIR_TYPES DEVELOPER MADS \ - POLL DIRECTIONS PB PEB \ - PROGRESSIVE-BARRIER" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "SEC_POLL_DIR_TYPES (developer)" ) << std::endl - << ". types of directions for the secondary poll" << std::endl - << ". arguments: same logic as DIRECTION_TYPE" << std::endl - << ". default: see user guide" << std::endl - << ". example: SEC_POLL_DIR_TYPES ORTHO 1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - // USE_SMESH: - // ------------------- - if ( developer && ( display_all || NOMAD::string_find ( "USE_SMESH SMESH MESH \ - ANISO" , param_names ) ) ){ - _out << std::endl - << NOMAD::open_block ( "USE_SMESH (developer)" ) << std::endl - << ". forces the use of the standard mesh (older version of mesh)" << std::endl - << ". default: no" << std::endl - << ". example: USE_SMESH 1" << std::endl - << NOMAD::close_block(); - chk = true; - } - - - // last display: - if ( !chk && developer) { - - std::string pname = ( pnames.size() == 1 ) ? - ("\'" + *pnames.begin() + "\'") : - "the specified list of parameter names"; - - _out << std::endl << "no help available for " << pname << std::endl - << "Developer help example: \'nomad -d mesh\' displays developer " << std::endl - << " help on the mesh parameters." << std::endl - << std::endl; - } - - - _out.close_block(); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameters.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameters.hpp deleted file mode 100644 index 5bf5a7e6b..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Parameters.hpp +++ /dev/null @@ -1,2601 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Parameters.hpp - \brief NOMAD Parameters (headers) - \author Sebastien Le Digabel - \date 2010-04-21 - \see Parameters.cpp - */ -#ifndef __PARAMETERS__ -#define __PARAMETERS__ - -#include -#include -#include -#include -#include "Parameter_Entries.hpp" -#include "Signature.hpp" - -namespace NOMAD { - - /// Structure to represent the models parameters. - struct model_params_type { - - NOMAD::model_type search1; ///< First model search (MS) type. - NOMAD::model_type search2; ///< Second model search (MS) type. - - NOMAD::model_type eval_sort; ///< Use models to sort trial pts (MES). - - bool search_optimistic; ///< If the MS is optimistic or not. - bool search_proj_to_mesh; ///< Model solution projected or not to mesh. - int search_max_trial_pts; ///< Limit on the number of MS trial pts. - bool eval_sort_cautious; ///< Cautious strategy for MES. - - NOMAD::Double quad_radius_factor; ///< Quadratic model radius factor \c r. - bool quad_use_WP; ///< Use or not a well-poisedness strategy. - int quad_min_Y_size; ///< Limit inf on the size of \c Y. - int quad_max_Y_size; ///< Limit sup on the size of \c Y. - NOMAD::Double model_np1_quad_epsilon;///< Ortho n+1 quadratic model epsilon (scaling used for (n+1)th dynamic direction with Ortho n+1) - - NOMAD::TGP_mode_type tgp_mode; ///< TGP mode (fast or precise). - bool tgp_reuse_model; ///< Use the model from MS for the MES. - }; - - /// Class for the NOMAD parameters. - class Parameters : private NOMAD::Uncopyable { - - private: - - bool _to_be_checked; ///< Access control to the parameters. - static bool _warning_has_been_displayed; - NOMAD::Display _out; ///< Display. - - /*----------------------------------------------------------------------*/ - - /// Initializations. - void init ( void ); - - /// Interpretation of the entries for the starting point. - /** - \param entries Parameter entries -- \b IN. - */ - void interpret_x0 ( const NOMAD::Parameter_Entries & entries ); - - /// Interpretation of the entries for mesh and poll sizes. - /** - \param entries Parameter entries -- \b IN. - \param param_name Parameter name -- \b IN. - */ - void interpret_mesh_sizes ( const NOMAD::Parameter_Entries & entries , - const std::string & param_name ); - - /// Interpretation of the entries for bounds and fixed variables. - /** - \c BFVS stands for "Bounds and Fixed VariableS". - \param entries Parameter entries -- \b IN. - \param param_name Parameter name -- \b IN. - */ - void interpret_BFVS ( const NOMAD::Parameter_Entries & entries , - const std::string & param_name ); - - /// Interpretation of the entries for parameter \c BB_INPUT_TYPE. - /** - \param entries Parameter entries -- \b IN. - */ - void interpret_bb_input_type ( const NOMAD::Parameter_Entries & entries ); - - /// Interpretation of the entries for parameter \c PERIODIC_VARIABLE. - /** - \param entries Parameter entries -- \b IN. - */ - void interpret_periodic_var ( const NOMAD::Parameter_Entries & entries ); - - /// Interpretation of the entries for parameter \c VARIABLE_GROUP. - /** - \param entries Parameter entries -- \b IN. - */ - void interpret_var_groups ( const NOMAD::Parameter_Entries & entries ); - - // Interpretation of the entries for parameter \c F_TARGET. - /** - \param entries Parameter entries -- \b IN. - */ - void interpret_f_target ( const NOMAD::Parameter_Entries & entries ); - - /// Delete the list of starting points. - void delete_x0s ( void ); - - /// Check a directory name. - /** - \param dir Directory name -- \b IN. - \return A boolean equal to \c true if the directory is valid. - */ - static bool check_directory ( std::string & dir ); - - /// Add a seed to a file name. - /** - - Transforms \c file_name.ext into \c file_name.seed.ext. - \param n_seed Length of the seed \c s_seed -- \b IN. - \param s_seed A string representating the seed -- \b IN. - \param file_name File name -- \b IN/OUT. - */ - static void add_seed_to_file_name ( int n_seed , - const std::string & s_seed , - std::string & file_name ); - - - - /// Check if a specified direction type is set. - /** - \param dt The specified direction type -- \b IN. - \return true if the specified direction type is used. - */ - bool has_direction_type(NOMAD::direction_type dt) const; - - - /*----------------------------------------------------------------------*/ - - public: - - /// Exception class for an invalid parameter. - class Invalid_Parameter : public NOMAD::Exception { - public: - /// Constructor. - Invalid_Parameter ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /// Exception class for a bad access. - class Bad_Access : public NOMAD::Exception { - public: - /// Constructor. - Bad_Access ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /*----------------------------------------------------------------------*/ - - /// Constructor #1. - /** - \param out Display -- \b IN. - */ - explicit Parameters ( const NOMAD::Display & out ) - : _out ( out ) , - _std_signature ( NULL ) , - _extern_signature ( NULL ) { init(); } - - /// Constructor #2. - /** - From an extern signature. - \param extern_signature A pointer to the extern signature -- \b IN. - \param out Display -- \b IN. - */ - explicit Parameters ( NOMAD::Signature * extern_signature , - const NOMAD::Display & out ) - : _out ( out ) , - _std_signature ( NULL ) , - _extern_signature ( extern_signature ) { init(); } - - /// Destructor. - virtual ~Parameters ( void ); - - /// Display parameter help. - /** - - Help option obtained with command \c nomad \c -h. - - A list of parameters is given as the program arguments. - \param argc Number of command line arguments -- \b IN. - \param argv The command line arguments -- \b IN. - \param developer Bool to request developer help (defaut=false) -- \b IN. - */ - void help ( int argc , char ** argv , bool developer=false) const; - - /// Display parameter help. - /** - For a specific parameter. - \param param_name Name of the parameter -- \b IN. - \param developer Bool to request developer help (defaut=false) -- \b IN. - */ - void help ( const std::string & param_name, bool developer=false ) const; - - /// Display parameter help. - /** - For a list of parameters. - \param param_names_list List of parameter names -- \b IN. - \param developer Bool to request developer help (defaut=false) -- \b IN. - */ - void help ( const std::list & param_names_list , bool developer=false) const; - - /// Reset. - void reset ( void ) { init(); } - - /// Read parameters from a file. 1/2 - /** - \param param_file Name of the parameters file -- \b IN. - */ - void read ( const std::string & param_file ); - - /// Read parameters from a Parameter_Entries 2/2 - /** - \param entries -- \b IN. - */ - void read ( const NOMAD::Parameter_Entries & entries ); - - - /// Check the parameters. - /** - \param remove_history_file A boolean equal to \c true if the history file - has to be deleted - -- \b IN -- \b optional (default = \c true). - \param remove_solution_file A boolean equal to \c true if the solution file - has to be deleted - -- \b IN -- \b optional (default = \c true). - \param remove_stats_file A boolean equal to \c true if the stats file - has to be deleted - -- \b IN -- \b optional (default = \c true). - */ - void check ( bool remove_history_file = true , - bool remove_solution_file = true , - bool remove_stats_file = true ); - - /// Force the check flag to be satisfied. - /** - This advanced function should be used with care. - */ - void force_check_flag ( void ) { _to_be_checked = false; } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Display. - /** - Uses \c this->_out as NOMAD::Display object. - */ - void display ( void ) const { display ( _out ); } - - /*--------------------------------------------------------------*/ - /* Attributes and methods listed by categories */ - /*--------------------------------------------------------------*/ - - // Algorithm and miscellaneous parameters: - // --------------------------------------- - private: - std::string _problem_dir; ///< Problem directory. - std::string _tmp_dir; ///< Temporary directory. - int _seed; ///< Seed. - int _max_eval; ///< Maximum number of evaluations. - int _max_bb_eval; ///< Maximum number of blackbox evaluations. - - std::list _display_stats; ///< Stats keywords for \c DISPLAY_STATS. - bool _display_all_eval; ///< Parameter \c DISPLAY_ALL_EVAL - - /// Equal to \c true if \c _max_bb_eval has been entered. - bool _max_bbe_decided; - - /// Maximum number of simulated evaluations. - int _max_sim_bb_eval; - - int _max_time; ///< Maximum time. - int _max_iterations; ///< Maximum number of iterations. - int _max_cons_failed_it; ///< Maximum number of consecutive failed iterations. - float _max_cache_memory; ///< Maximum cache memory. - bool _stop_if_feasible; ///< Stop if a feasible solution is found. - NOMAD::Point _f_target; ///< Target for the objective function. - NOMAD::Double _stat_sum_target; ///< Target for the STAT_SUM stat. - NOMAD::Double _L_curve_target; ///< Target for the L_CURVE criterion. - bool _snap_to_bounds; ///< Snap or not the points to the bounds. - bool _user_calls_enabled; ///< Enable calls to user functions. - bool _asynchronous; ///< Asynchronous version for parallelism. - - public: - - /// Test to know if parameters have to be checked. - /** - \return A boolean equal to \c true if parameters have - to be checked with function NOMAD::Parameters::check(). - */ - bool to_be_checked ( void ) const { return _to_be_checked; } - - /// Access to the display degrees. - /** - - Use NOMAD::Parameters::out().get_X_dd() - to access other specific display degrees. - - \see Display.hpp. - \param d The 4 display degrees as a string -- \b OUT. - */ - void get_display_degree ( std::string & d ) const; - - /// Access to the display degree. - /** - \return General display degree. - */ - int get_display_degree ( void ) const; - - /// Access to display. - /** - \return The NOMAD::Display object. - */ - const NOMAD::Display & out ( void ) const; - - /// Access to the \c DISPLAY_STATS parameter. - /** - \return The \c DISPLAY_STATS parameter. - */ - const std::list & get_display_stats ( void ) const; - - /// Access to the \c DISPLAY_ALL_EVAL parameter. - /** - \return The \c DISPLAY_ALL_EVAL parameter. - */ - bool get_display_all_eval ( void ) const; - - /// Access to the \c POINT_DISPLAY_LIMIT parameter. - /** - \return The \c POINT_DISPLAY_LIMIT parameter. - */ - int get_point_display_limit ( void ) const; - - /// Access to the seed. - /** - \return The seed. - */ - int get_seed ( void ) const; - - /// Access to the maximum number of evaluations. - /** - \return The maximum number of evaluations. - */ - int get_max_eval ( void ) const; - - /// Access to the \c MAX_SIM_BB_EVAL parameter. - /** - \return The \c MAX_SIM_BB_EVAL parameter. - */ - int get_max_sim_bb_eval ( void ) const; - - /// Access to the \c MAX_BB_EVAL parameter. - /** - \return The \c MAX_BB_EVAL parameter. - */ - int get_max_bb_eval ( void ) const; - - /// Access to the \c MAX_TIME parameter. - /** - \return The \c MAX_TIME parameter. - */ - int get_max_time ( void ) const; - - /// Access to the maximum number of iterations. - /** - \return The maximum number of iterations. - */ - int get_max_iterations ( void ) const; - - /// Access to the maximum number of consecutive failed iterations. - /** - \return The maximum number of consecutive failed iterations. - */ - int get_max_consecutive_failed_iterations ( void ) const; - - /// Access to the maximum cache memory. - /** - \return The maximum cache memory. - */ - float get_max_cache_memory ( void ) const; - - /// Access to the \c STOP_IF_FEASIBLE parameter. - /** - \return The \c STOP_IF_FEASIBLE parameter. - */ - bool get_stop_if_feasible ( void ) const; - - /// Access to the \c F_TARGET parameter. - /** - \return The \c F_TARGET parameter. - */ - const NOMAD::Point & get_f_target ( void ) const; - - /// Access to the \c STAT_SUM_TARGET parameter. - /** - \return The \c STAT_SUM_TARGET parameter. - */ - const NOMAD::Double & get_stat_sum_target ( void ) const; - - /// Access to the \c L_CURVE_TARGET parameter. - /** - \return The \c L_CURVE_TARGET parameter. - */ - const NOMAD::Double & get_L_curve_target ( void ) const; - - /// Access to the problem directory. - /** - \return The problem directory. - */ - const std::string & get_problem_dir ( void ) const; - - /// Access to the temporary directory. - /** - \return The temporary directory. - */ - const std::string & get_tmp_dir ( void ) const; - - /// Access to the \c SNAP_TO_BOUNDS parameter. - /** - \return The \c SNAP_TO_BOUNDS parameter. - */ - bool get_snap_to_bounds ( void ) const; - - /// Access to the \c USER_CALLS_ENABLED parameter. - /** - \return The \c USER_CALLS_ENABLED parameter. - */ - bool get_user_calls_enabled ( void ) const; - - /// Access to the \c ASYNCHRONOUS parameter. - /** - \return The \c ASYNCHRONOUS parameter. - */ - bool get_asynchronous ( void ) const; - - /// Set the \c POINT_DISPLAY_LIMIT parameter. - /** - \param dl The \c POINT_DISPLAY_LIMIT parameter -- \b IN. - */ - void set_POINT_DISPLAY_LIMIT ( int dl ); - - /// Set the \c DISPLAY_STATS parameter. - /** - - From a list of strings. - \param ds The \c DISPLAY_STATS parameter -- \b IN. - */ - void set_DISPLAY_STATS ( const std::list & ds ); - - /// Set the \c DISPLAY_STATS parameter. - /** - - From a string. - \param ds The \c DISPLAY_STATS parameter -- \b IN. - */ - void set_DISPLAY_STATS ( const std::string & ds ); - - /// Set the \c DISPLAY_ALL_EVAL parameter. - /** - \param dae The \c DISPLAY_ALL_EVAL parameter -- \b IN. - */ - void set_DISPLAY_ALL_EVAL ( bool dae ); - - /// Set the display degree. - /** - - Accepts also NOMAD::dd_type arguments. - \param dd Display degree -- \b IN. - \return \c true if the operation succeeded. - */ - bool set_DISPLAY_DEGREE ( int dd ); - - /// Set the display degrees. - /** - - From a string with the 4 degrees. - \param dd Display degree -- \b IN. - \return \c true if the operation succeeded. - */ - bool set_DISPLAY_DEGREE ( const std::string & dd ); - - /// Set the display degrees. - /* - \param gen_dd General display degree -- \b IN. - \param search_dd Search display degree -- \b IN. - \param poll_dd Poll display degree -- \b IN. - \param iter_dd Iterative display degree -- \b IN. - */ - void set_DISPLAY_DEGREE ( int gen_dd , - int search_dd , - int poll_dd , - int iter_dd ); - - /// Set the \c OPEN_BRACE parameter. - /** - \param s The \c OPEN_BRACE parameter -- \b IN. - */ - void set_OPEN_BRACE ( const std::string & s ); - - /// Set the \c CLOSED_BRACE parameter. - /** - \param s The \c CLOSED_BRACE parameter -- \b IN. - */ - void set_CLOSED_BRACE ( const std::string & s ); - - /// Set the seed. - /** - \param seed The seed -- \b IN. - */ - void set_SEED ( int seed ); - - /// Set the \c MAX_EVAL parameter. - /** - \param me The \c MAX_EVAL parameter -- \b IN. - */ - void set_MAX_EVAL ( int me ); - - /// Set the \c MAX_SIM_BB_EVAL parameter. - /** - \param msbe The \c MAX_SIM_BB_EVAL parameter -- \b IN. - */ - void set_MAX_SIM_BB_EVAL ( int msbe ); - - /// Set the \c MAX_BB_EVAL parameter. - /** - \param bbe The \c MAX_BB_EVAL parameter -- \b IN. - */ - void set_MAX_BB_EVAL ( int bbe ); - - /// Set the \c MAX_TIME parameter. - /** - \param mt The \c MAX_TIME parameter -- \b IN. - */ - void set_MAX_TIME ( int mt ); - - /// Set the \c MAX_ITERATIONS parameter. - /** - \param mi The \c MAX_ITERATIONS parameter -- \b IN. - */ - void set_MAX_ITERATIONS ( int mi ); - - /// Set the \c MAX_CONSECUTIVE_FAILED_ITERATIONS parameter. - /** - \param mcsi The \c MAX_CONSECUTIVE_FAILED_ITERATIONS parameter -- \b IN. - */ - void set_MAX_CONSECUTIVE_FAILED_ITERATIONS ( int mcsi ); - - /// Set the \c MAX_CACHE_MEMORY parameter. - /** - \param mcm The \c MAX_CACHE_MEMORY parameter -- \b IN. - */ - void set_MAX_CACHE_MEMORY ( float mcm ); - - /// Set the \c STOP_IF_FEASIBLE parameter. - /** - \param sif The \c STOP_IF_FEASIBLE parameter -- \b IN. - */ - void set_STOP_IF_FEASIBLE ( bool sif ); - - /// Set the \c STAT_SUM_TARGET parameter. - /** - \param target The \c STAT_SUM_TARGET parameter -- \b IN. - */ - void set_STAT_SUM_TARGET ( const NOMAD::Double & target ); - - /// Set the \c L_CURVE_TARGET parameter. - /** - \param target The \c L_CURVE_TARGET parameter -- \b IN. - */ - void set_L_CURVE_TARGET ( const NOMAD::Double & target ); - - /// Set the \c PROBLEM_DIR parameter. - /** - \param dir The \c PROBLEM_DIR parameter -- \b IN. - */ - void set_PROBLEM_DIR ( const std::string & dir ); - - /// Set the \c TMP_DIR parameter. - /** - \param dir The \c TMP_DIR parameter -- \b IN. - */ - void set_TMP_DIR ( const std::string & dir ); - - /// Set the \c SNAP_TO_BOUNDS parameter. - /** - \param stb The \c SNAP_TO_BOUNDS parameter -- \b IN. - */ - void set_SNAP_TO_BOUNDS ( bool stb ); - - /// Set the \c USER_CALLS_ENABLED parameter. - /** - \param uce The \c USER_CALLS_ENABLED parameter -- \b IN. - */ - void set_USER_CALLS_ENABLED ( bool uce ); - - /// Set the \c ASYNCHRONOUS parameter. - /** - \param as The \c ASYNCHRONOUS parameter -- \b IN. - */ - void set_ASYNCHRONOUS ( bool as ); - - /// Set the \c F_TARGET parameter. - /** - - Multi-objective version. - \param target The \c F_TARGET parameter -- \b IN. - */ - void set_F_TARGET ( const NOMAD::Point & target ); - - /// Set the F_TARGET \c parameter. - /** - - Single-objective version. - \param target The \c F_TARGET parameter -- \b IN. - */ - void set_F_TARGET ( const NOMAD::Double & target ); - - /// Reset the \c F_TARGET parameter. - void reset_f_target ( void ) { _f_target.clear(); } - - /// Set the \c EPSILON parameter. - /** - \param eps The \c EPSILON parameter -- \b IN. - */ - void set_EPSILON ( const NOMAD::Double & eps ) - { - NOMAD::Double::set_epsilon ( eps.value() ); - } - - /// Set the \c UNDEF_STR parameter. - /** - \param undef_str The \c UNDEF_STR parameter -- \b IN. - */ - void set_UNDEF_STR ( const std::string & undef_str ) - { - NOMAD::Double::set_undef_str ( undef_str ); - } - - /// Set the \c INF_STR parameter. - /** - \param inf_str The \c INF_STR parameter -- \b IN. - */ - void set_INF_STR ( const std::string & inf_str ) - { - NOMAD::Double::set_inf_str ( inf_str ); - } - - /// Access to the \c EPSILON parameter. - /** - \return The \c EPSILON parameter. - */ - const NOMAD::Double get_epsilon ( void ) const - { - return NOMAD::Double::get_epsilon(); - } - - /// Access to the \c UNDEF_STR parameter. - /** - \return The \c UNDEF_STR parameter. - */ - const std::string get_undef_str ( void ) const - { - return NOMAD::Double::get_undef_str(); - } - - /// Access to the \c INF_STR parameter. - /** - \return The \c INF_STR parameter. - */ - const std::string get_inf_str ( void ) const - { - return NOMAD::Double::get_inf_str(); - } - - // Output files: - // ------------- - private: - - /// List of stats for parameter \c STATS_FILE. - std::list _stats_file; - - /// Name of the stats file. - std::string _stats_file_name; - - /// Parameter \c ADD_SEED_TO_FILE_NAME. - bool _add_seed_to_file_names; - - std::string _solution_file; ///< Parameter \c SOLUTION_FILE. - std::string _history_file; ///< Parameter \c HISTORY_FILE. - std::string _cache_file; ///< Parameter \c CACHE_FILE. - int _cache_save_period; ///< Parameter \c CACHE_SAVE_PERIOD. - - public: - - /// Access to the list of stats for the \c STATS_FILE parameter. - /** - \return The list of stats. - */ - const std::list & get_stats_file ( void ) const; - - /// Access to the name of the stats file. - /** - \return The name of the stats file. - */ - const std::string & get_stats_file_name ( void ) const; - - /// Access to the \c SOLUTION_FILE parameter. - /** - \return The \c SOLUTION_FILE parameter. - */ - const std::string & get_solution_file ( void ) const; - - /// Access to the \c HISTORY_FILE parameter. - /** - \return The \c HISTORY_FILE parameter. - */ - const std::string & get_history_file ( void ) const; - - /// Access to the \c CACHE_FILE parameter. - /** - \return The \c CACHE_FILE parameter. - */ - const std::string & get_cache_file ( void ) const; - - /// Access to the \c CACHE_SAVE_PERIOD parameter. - /** - \return The \c CACHE_SAVE_PERIOD parameter. - */ - int get_cache_save_period ( void ) const; - - /// Access to the \c ADD_SEED_TO_FILE_NAME parameter. - /** - \return The \c ADD_SEED_TO_FILE_NAME parameter. - */ - bool get_add_seed_to_file_names ( void ) const; - - /// Reset the \c STATS_FILE parameter. - void reset_stats_file ( void ); - - /// Set the \c STATS_FILE parameter. - /** - \param file_name Name of the stats file -- \b IN. - \param stats List of stats -- \b IN. - */ - void set_STATS_FILE ( const std::string & file_name , - const std::list & stats ); - - /// Set the \c STATS_FILE parameter. - /** - \param file_name Name of the stats file -- \b IN. - \param stats The stats -- \b IN. - */ - void set_STATS_FILE ( const std::string & file_name , - const std::string & stats ); - - /// Set the \c ADD_SEED_TO_FILE_NAME parameter. - /** - \param astfn The \c ADD_SEED_TO_FILE_NAME parameter -- \b IN. - */ - void set_ADD_SEED_TO_FILE_NAMES ( bool astfn ); - - /// Set the \c SOLUTION_FILE parameter. - /** - \param sf The \c SOLUTION_FILE parameter -- \b IN. - */ - void set_SOLUTION_FILE ( const std::string & sf ); - - /// Set the \c HISTORY_FILE parameter. - /** - \param hf The \c HISTORY_FILE parameter -- \b IN. - */ - void set_HISTORY_FILE ( const std::string & hf ); - - /// Set the \c CACHE_FILE parameter. - /** - \param cf The \c CACHE_FILE parameter -- \b IN. - */ - void set_CACHE_FILE ( const std::string & cf ); - - /// Set the \c CACHE_SAVE_PERIOD parameter. - /** - \param csp The \c CACHE_SAVE_PERIOD parameter -- \b IN. - */ - void set_CACHE_SAVE_PERIOD ( int csp ); - - // Searches: - // --------- - private: - - /// Speculative search (MADS search). - bool _speculative_search; - - bool _disable_models; ///< Models disablement - - NOMAD::model_params_type _model_params; ///< Models parameters. - - // VNS search parameters: - bool _VNS_search; ///< Flag for the VNS search. - NOMAD::Double _VNS_trigger; ///< VNS trigger. - - // Latin-Hypercube (LH) search: - int _LH_search_p0; ///< Number of initial LH search points. - int _LH_search_pi; ///< LH search points at each iteration. - bool _opportunistic_LH; ///< Parameter \c OPPORTUNISTIC_LH. - bool _opp_LH_is_defined; ///< A boolean equal to \c true if a LH has been defined. - - bool _cache_search; ///< Cache search. - bool _opportunistic_cache_search; ///< Parameter \c OPPORTUNISTIC_CACHE_SEARCH. - - /// A boolean equal to \c true if \c OPPORTUNISTIC_CACHE_SEARCH has been defined. - bool _opp_CS_is_defined; - - public: - - /// Access to the \c SPECULATIVE_SEARCH parameter. - /** - \return The \c SPECULATIVE_SEARCH parameter. - */ - bool get_speculative_search ( void ) const; - - /// Check if a model search is specified. - /** - \return A boolean equal to \c true if a model search is defined. - */ - bool has_model_search ( void ) const; - - /// Access to the \c MODEL_SEARCH parameter. - /** - \param i Index of the model search (1 or 2) -- \b IN. - \return The \c MODEL_SEARCH parameter. - */ - NOMAD::model_type get_model_search ( int i ) const; - - /// Access to the \c MODEL_SEARCH_OPTIMISTIC parameter. - /** - \return The \c MODEL_SEARCH_OPTIMISTIC parameter. - */ - bool get_model_search_optimistic ( void ) const; - - /// Access to the \c MODEL_SEARCH_PROJ_TO_MESH parameter. - /** - \return The \c MODEL_SEARCH_PROJ_TO_MESH parameter. - */ - bool get_model_search_proj_to_mesh ( void ) const; - - /// Access to the \c MODEL_QUAD_RADIUS_FACTOR parameter. - /** - \return The \c MODEL_QUAD_RADIUS_FACTOR parameter. - */ - const NOMAD::Double & get_model_quad_radius_factor ( void ) const; - - /// Access to the \c MODEL_NP1_QUAD_EPSILON parameter. - /** - \return The \c MODEL_NP1_QUAD_EPSILON parameter. - */ - const NOMAD::Double & get_model_np1_quad_epsilon ( void ) const; - - - /// Access to the \c MODEL_QUAD_USE_WP parameter. - /** - \return The \c MODEL_QUAD_USE_WP parameter. - */ - bool get_model_quad_use_WP ( void ) const; - - /// Access to the \c MODEL_QUAD_MAX_Y_SIZE parameter. - /** - \return The \c MODEL_QUAD_MAX_Y_SIZE parameter. - */ - int get_model_quad_max_Y_size ( void ) const; - - /// Access to the \c MODEL_QUAD_MIN_Y_SIZE parameter. - /** - \return The \c MODEL_QUAD_MIN_Y_SIZE parameter. - */ - int get_model_quad_min_Y_size ( void ) const; - - /// Access to the \c MODEL_TGP_MODE parameter. - /** - \return The \c MODEL_TGP_MODE parameter. - */ - NOMAD::TGP_mode_type get_model_tgp_mode ( void ) const; - - /// Access to the \c MODEL_TGP_REUSE_MODEL parameter. - /** - \return The \c MODEL_TGP_REUSE_MODEL parameter. - */ - bool get_model_tgp_reuse_model ( void ) const; - - /// Access to the \c MODEL_SEARCH_MAX_TRIAL_PTS parameter. - /** - \return The \c MODEL_SEARCH_MAX_TRIAL_PTS parameter. - */ - int get_model_search_max_trial_pts ( void ) const; - - /// Access to the \c MODEL_EVAL_SORT parameter. - /** - \return The \c MODEL_EVAL_SORT parameter. - */ - NOMAD::model_type get_model_eval_sort ( void ) const; - - /// Access to the \c MODEL_EVAL_SORT_CAUTIOUS parameter. - /** - \return The \c MODEL_EVAL_SORT_CAUTIOUS parameter. - */ - bool get_model_eval_sort_cautious ( void ) const; - - - /// Access to all the models parameters. - /** - \param mp The models parameters -- \b OUT. - */ - void get_model_parameters ( NOMAD::model_params_type & mp ) const; - - /// Access to the \c VNS_SEARCH parameter. - /** - \return The \c VNS_SEARCH parameter. - */ - bool get_VNS_search ( void ) const; - - /// Access to the VNS trigger. - /** - \return The VNS trigger. - */ - const NOMAD::Double & get_VNS_trigger ( void ) const; - - /// Access to the number of initial LH search points. - /** - \return The number of initial LH search points. - */ - int get_LH_search_p0 ( void ) const; - - /// Access to the number of LH search points at each iteration. - /** - \return The number of LH search points at each iteration. - */ - int get_LH_search_pi ( void ) const; - - /// Access to the \c OPPORTUNISTIC_LH parameter. - /** - \return The \c OPPORTUNISTIC_LH parameter. - */ - bool get_opportunistic_LH ( void ) const; - - /// Access to the \c CACHE_SEARCH parameter. - /** - \return The \c CACHE_SEARCH parameter. - */ - bool get_cache_search ( void ) const; - - /// Access to the \c OPPORTUNISTIC_CACHE_SEARCH parameter. - /** - \return The \c OPPORTUNISTIC_CACHE_SEARCH parameter. - */ - bool get_opportunistic_cache_search ( void ) const; - - /// Set the \c SPECULATIVE_SEARCH parameter. - /** - \param ss The \c SPECULATIVE_SEARCH parameter -- \b IN. - */ - void set_SPECULATIVE_SEARCH ( bool ss ); - - /// Disable use of models. - /** - */ - void set_DISABLE_MODELS ( void ); - - /// Disable use of sort (lexicographic order used). - /** - */ - void set_DISABLE_EVAL_SORT ( void ); - - /// Set all the models parameters. - /** - \param mp The models parameters -- \b IN. - */ - void set_model_parameters ( const NOMAD::model_params_type & mp ); - - /// Set the \c MODEL_SEARCH parameter (1/3). - /** - \param i Index of the model search (1 or 2) -- \b IN. - \param ms The \c MODEL_SEARCH parameter -- \b IN. - */ - void set_MODEL_SEARCH ( int i , NOMAD::model_type ms ); - - /// Set the \c MODEL_SEARCH parameter (2/3). - /** - \param ms The \c MODEL_SEARCH parameter -- \b IN. - */ - void set_MODEL_SEARCH ( bool ms ); - - /// Set the \c MODEL_SEARCH parameter (3/3). - /** - \param mod_type The \c MODEL_SEARCH parameter -- \b IN. - */ - void set_MODEL_SEARCH ( NOMAD::model_type mod_type ); - - /// Set the \c MODEL_SEARCH_OPTIMISTIC parameter. - /** - \param mso The \c MODEL_SEARCH_OPTIMISTIC parameter -- \b IN. - */ - void set_MODEL_SEARCH_OPTIMISTIC ( bool mso ); - - /// Set the \c MODEL_SEARCH_PROJ_TO_MESH parameter. - /** - \param ptm The \c MODEL_SEARCH_PROJ_TO_MESH parameter -- \b IN. - */ - void set_MODEL_SEARCH_PROJ_TO_MESH ( bool ptm ); - - /// Set the \c MODEL_QUAD_RADIUS_FACTOR parameter. - /** - \param r The \c MODEL_QUAD_RADIUS_FACTOR parameter -- \b IN. - */ - void set_MODEL_QUAD_RADIUS_FACTOR ( const NOMAD::Double & r ); - - /// Set the \c MODEL_QUAD_USE_WP parameter. - /** - \param uwp The \c MODEL_QUAD_USE_WP parameter -- \b IN. - */ - void set_MODEL_QUAD_USE_WP ( bool uwp ); - - /// Set the \c MODEL_QUAD_MAX_Y_SIZE parameter. - /** - \param s The \c MODEL_QUAD_MAX_Y_SIZE parameter -- \b IN. - */ - void set_MODEL_QUAD_MAX_Y_SIZE ( int s ); - - /// Set the \c MODEL_QUAD_MIN_Y_SIZE parameter. - /** - \param s The \c MODEL_QUAD_MIN_Y_SIZE parameter -- \b IN. - */ - void set_MODEL_QUAD_MIN_Y_SIZE ( int s ); - - /// Set the \c MODEL_NP1_QUAD_EPSILON parameter. - /** - \param r The \c MODEL_NP1_QUAD_EPSILON parameter -- \b IN. - */ - void set_MODEL_NP1_QUAD_EPSILON ( const NOMAD::Double & r ); - - /// Set the \c MODEL_TGP_MODE parameter. - /** - \param m The \c MODEL_TGP_MODE parameter -- \b IN. - */ - void set_MODEL_TGP_MODE ( NOMAD::TGP_mode_type m ); - - /// Set the \c MODEL_TGP_REUSE_MODEL parameter. - /** - \param rm The \c MODEL_TGP_REUSE_MODEL parameter -- \b IN. - */ - void set_MODEL_TGP_REUSE_MODEL ( bool rm ); - - /// Set the \c MODEL_SEARCH_MAX_TRIAL_PTS parameter. - /** - \param s The \c MODEL_SEARCH_MAX_TRIAL_PTS parameter -- \b IN. - */ - void set_MODEL_SEARCH_MAX_TRIAL_PTS ( int s ); - - /// Set the \c MODEL_EVAL_SORT parameter (1/2). - /** - \param mes The \c MODEL_EVAL_SORT parameter -- \b IN. - */ - void set_MODEL_EVAL_SORT ( NOMAD::model_type mes ); - - /// Set the \c MODEL_EVAL_SORT parameter (2/2). - /** - \param mes The \c MODEL_EVAL_SORT parameter -- \b IN. - */ - void set_MODEL_EVAL_SORT ( bool mes ); - - - /// Set the \c MODEL_EVAL_SORT_CAUTIOUS parameter. - /** - \param mesc The \c MODEL_EVAL_SORT_CAUTIOUS parameter -- \b IN. - */ - void set_MODEL_EVAL_SORT_CAUTIOUS ( bool mesc ); - - /// Set the \c VNS_SEARCH parameter. - /** - \param vns The \c VNS_SEARCH parameter -- \b IN. - */ - void set_VNS_SEARCH ( bool vns ); - - /// Set the \c VNS_SEARCH parameter. - /** - \param trigger The VNS trigger -- \b IN. - */ - void set_VNS_SEARCH ( const NOMAD::Double & trigger ); - - /// Set the \c LH_SEARCH parameter. - /** - \param p0 Number of initial LH search points -- \b IN. - \param pi LH search points at each iteration -- \b IN. - */ - void set_LH_SEARCH ( int p0 , int pi ); - - /// Set the \c OPPORTUNISTIC_LH parameter. - /** - \param olh The \c OPPORTUNISTIC_LH parameter -- \b IN. - */ - void set_OPPORTUNISTIC_LH ( bool olh ); - - /// Set the \c CACHE_SEARCH parameter. - /** - \param cs The \c CACHE_SEARCH parameter -- \b IN. - */ - void set_CACHE_SEARCH ( bool cs ); - - /// Set the \c OPPORTUNISTIC_CACHE_SEARCH parameter. - /** - \param ocs The \c OPPORTUNISTIC_CACHE_SEARCH parameter -- \b IN. - */ - void set_OPPORTUNISTIC_CACHE_SEARCH ( bool ocs ); - - // Mesh: - // ----- - private: - - bool _use_smesh; ///< Use smesh (default xmesh) - bool _anisotropic_mesh; ///< Anisotropic mesh (xmesh only, i.e. _use_smesh=false) - NOMAD::Double _mesh_update_basis; ///< Mesh update basis (tau). - NOMAD::Double _poll_update_basis; ///< Poll update basis (beta). - int _mesh_coarsening_exponent; ///< Mesh coarsening exponent. - int _mesh_refining_exponent; ///< Mesh refining exponent. - int _initial_mesh_index; ///< Initial mesh index (ell_0). - NOMAD::Point _initial_mesh_size; ///< Initial (absolute) mesh size (delta^0). - NOMAD::Point _min_mesh_size; ///< Minimal (absolute) mesh size (delta_min). - NOMAD::Point _initial_poll_size; ///< Initial (absolute) poll size (delta^0). - NOMAD::Point _min_poll_size; ///< Minimal (absolute) poll size (Delta_min). - - bool _min_poll_size_defined; ///< \c true if _min_poll_size is user-defined. - - public: - - /// Access to the \c ANISOTROPIC_MESH parameter. - /** - \return The \c ANISOTROPIC_MESH parameter -- \b IN. - */ - bool get_anisotropic_mesh ( void ) const; - - /// Access to the \c USE_SMESH parameter. - /** - \return The \c USE_SMESH parameter -- \b IN. - */ - bool get_use_smesh ( void ) const; - - - - /// Access to the \c POLL_UPDATE_BASIS parameter. - /** - \return The \c POLL_UPDATE_BASIS parameter. - */ - const NOMAD::Double & get_poll_update_basis ( void ) const; - - - /// Access to the \c MESH_UPDATE_BASIS parameter. - /** - \return The \c MESH_UPDATE_BASIS parameter. - */ - const NOMAD::Double & get_mesh_update_basis ( void ) const; - - /// Access to the \c MESH_COARSENING_EXPONENT parameter. - /** - \return The \c MESH_COARSENING_EXPONENT parameter. - */ - int get_mesh_coarsening_exponent ( void ) const; - - /// Access to the \c MESH_REFINING_EXPONENT parameter. - /** - \return The \c MESH_REFINING_EXPONENT parameter. - */ - int get_mesh_refining_exponent ( void ) const; - - /// Access to the \c INITIAL_MESH_INDEX parameter. - /** - \return The \c INITIAL_MESH_INDEX parameter. - */ - int get_initial_mesh_index ( void ) const; - - - /// Access to the \c INITIAL_MESH_SIZE parameter. - /** - \return The \c INITIAL_MESH_SIZE parameter. - */ - const NOMAD::Point & get_initial_mesh_size ( void ) const; - - /// Access to the \c INITIAL_POLL_SIZE parameter. - /** - \return The \c INITIAL_POLL_SIZE parameter. - */ - const NOMAD::Point & get_initial_poll_size ( void ) const; - - /// Access to the \c MIN_MESH_SIZE parameter. - /** - \return The \c MIN_MESH_SIZE parameter. - */ - const NOMAD::Point & get_min_mesh_size ( void ) const; - - /// Access to the \c MIN_POLL_SIZE parameter. - /** - \return The \c MIN_POLL_SIZE parameter. - */ - const NOMAD::Point & get_min_poll_size ( void ) const; - - /// Access to \c _min_poll_size_defined. - /** - \return A boolean equal to \c true if the \c MIN_POLL_SIZE parameter - has been user-defined. - */ - bool get_min_poll_size_defined ( void ) const; - - /// Set the \c ANISOTROPIC_MESH parameter. - /** - \param anis The \c ANISOTROPIC_MESH parameter -- \b IN. - */ - void set_ANISOTROPIC_MESH ( bool anis ); - - /// Set the \c USE_SMESH parameter. - /** - \param use_smesh The \c USE_SMESH parameter -- \b IN. - */ - void set_USE_SMESH ( bool use_smesh ); - - - /// Set the \c MESH_UPDATE_BASIS parameter. - /** - \param tau The \c MESH_UPDATE_BASIS parameter -- \b IN. - */ - void set_MESH_UPDATE_BASIS ( const NOMAD::Double & tau ); - - /// Set the \c POLL_UPDATE_BASIS parameter. - /** - \param r The \c POLL_UPDATE_BASIS parameter -- \b IN. - */ - void set_POLL_UPDATE_BASIS ( const NOMAD::Double & r ); - - - /// Set the \c INITIAL_MESH_INDEX parameter. - /** - \param ell_0 The \c INITIAL_MESH_INDEX parameter -- \b IN. - */ - void set_INITIAL_MESH_INDEX ( int ell_0 ); - - /// Set the \c MESH_REFINING_EXPONENT parameter. - /** - \param mre The \c MESH_REFINING_EXPONENT parameter -- \b IN. - */ - void set_MESH_REFINING_EXPONENT ( int mre ); - - /// Set the \c MESH_COARSENING_EXPONENT parameter. - /** - \param mce The \c MESH_COARSENING_EXPONENT parameter -- \b IN. - */ - void set_MESH_COARSENING_EXPONENT ( int mce ); - - /// Set the \c MIN_MESH_SIZE parameter. - /** - \param mms Minimum mesh size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_MIN_MESH_SIZE ( const NOMAD::Double & mms , bool relative = false ); - - /// Set the \c MIN_MESH_SIZE parameter. - /** - \param index Index of a variable -- \b IN. - \param mms Minimum mesh size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_MIN_MESH_SIZE ( int index , - const NOMAD::Double & mms , - bool relative = false ); - - /// Set the \c MIN_MESH_SIZE parameter. - /** - \param mms Minimum mesh size -- \b IN. - \param relative Indicated as relative values - -- \b IN -- \b optional (default = \c false). - */ - void set_MIN_MESH_SIZE ( const NOMAD::Point & mms , bool relative = false ); - - /// Set the \c MIN_POLL_SIZE parameter. - /** - \param mps Minimum poll size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_MIN_POLL_SIZE ( const NOMAD::Double & mps , bool relative = false ); - - /// Set the \c MIN_POLL_SIZE parameter. - /** - \param index Index of a variable -- \b IN. - \param mps Minimum poll size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_MIN_POLL_SIZE ( int index , - const NOMAD::Double & mps , - bool relative = false ); - - /// Set the \c MIN_POLL_SIZE parameter. - /** - \param mps Minimum poll size -- \b IN. - \param relative Indicated as relative values - -- \b IN -- \b optional (default = \c false). - */ - void set_MIN_POLL_SIZE ( const NOMAD::Point & mps , bool relative = false ); - - /// Set the \c INITIAL_MESH_SIZE parameter. - /** - \param ims Initial mesh size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_INITIAL_MESH_SIZE ( const NOMAD::Double & ims , bool relative = false ); - - /// Set the \c INITIAL_MESH_SIZE parameter. - /** - \param index Index of a variable -- \b IN. - \param ims Initial mesh size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_INITIAL_MESH_SIZE ( int index , - const NOMAD::Double & ims , - bool relative = false ); - - /// Set the \c INITIAL_MESH_SIZE parameter. - /** - \param ims Initial mesh size -- \b IN. - \param relative Indicated as relative values - -- \b IN -- \b optional (default = \c false). - */ - void set_INITIAL_MESH_SIZE ( const NOMAD::Point & ims , bool relative = false ); - - - /// Set the \c INITIAL_POLL_SIZE parameter. - /** - \param ims Initial poll size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_INITIAL_POLL_SIZE ( const NOMAD::Double & ims , bool relative = false ); - - /// Set the \c INITIAL_POLL_SIZE parameter. - /** - \param index Index of a variable -- \b IN. - \param ims Initial poll size -- \b IN. - \param relative Indicated as a relative value - -- \b IN -- \b optional (default = \c false). - */ - void set_INITIAL_POLL_SIZE ( int index , - const NOMAD::Double & ims , - bool relative = false ); - - /// Set the \c INITIAL_POLL_SIZE parameter. - /** - \param ims Initial poll size -- \b IN. - \param relative Indicated as relative values - -- \b IN -- \b optional (default = \c false). - */ - void set_INITIAL_POLL_SIZE ( const NOMAD::Point & ims , bool relative = false ); - - - - // Directions: - // ----------- - private: - - /// Types of poll directions. - std::set _direction_types; - - /// Types of directions for the secondary poll. - std::set _sec_poll_dir_types; - - /// Change direction types to prevent using models for finding the (n+1)th direction - /// Apply if ORTHO N+1 QUAD -> ORTHO N+1 NEG. - void set_DIRECTION_TYPE_NO_MODEL ( void ); - - - public: - - /// Access to the list of poll direction types. - /** - \return The list of poll direction types. - */ - const std::set & get_direction_types ( void ) const; - - /// Access to the list of secondary poll direction types. - /** - \return The list of secondary poll direction types. - */ - const std::set & get_sec_poll_dir_types ( void ) const; - - - /// Check if there are Ortho-MADS directions. - /** - \return A boolean equal to \c true if there is at least one - Ortho-MADS direction in the list of poll directions - or in the list of secondary poll directions. - */ - bool has_orthomads_directions ( void ) const; - - - /// Check if a direction type that required dynamic completion for the (n+1)th direction. - /** - \return true if a dynamic completion is required. - */ - bool has_dynamic_direction(void) const; - - - /// Reset the directions. - void reset_directions ( void ); - - - /// Add a new direction type. - /** - \param dt The new direction type -- \b IN. - */ - void set_DIRECTION_TYPE ( NOMAD::direction_type dt ); - - /// Add a set of new direction types. - /** - \param dt The set of new direction types -- \b IN. - */ - void set_DIRECTION_TYPE ( const std::set & dt ); - - - /// Add a new direction type for the secondary poll. - /** - \param dt The new direction type -- \b IN. - */ - void set_SEC_POLL_DIR_TYPE ( NOMAD::direction_type dt ); - - /// Add a set of new direction types for the secondary poll. - /** - \param dt The set of new direction types -- \b IN. - */ - void set_SEC_POLL_DIR_TYPE ( const std::set & dt ); - - /// Enables use of quad model to determine prospect direction - /// for Ortho n+1 direction type - /** - \param qmpd boolean -- \b IN. - */ - void set_QUAD_MODEL_PROSPECT_DIR ( bool qmpd ) ; - - // Starting point(s): - // ------------------ - private: - - std::vector _x0s; ///< List of starting points. - std::string _x0_cache_file; ///< Cache file containing starting points. - - public: - - /// Add a new point in the list of starting points. - /** - \param x0 The new point -- \b IN. - */ - void set_X0 ( const NOMAD::Point & x0 ); - - /// Indicate a cache file containing starting points. - /** - \param file_name Name of the cache file -- \b IN. - */ - void set_X0 ( const std::string & file_name ); - - /// Reset all string points. - void reset_X0 ( void ); - - /// Access to the list of starting points. - /** - \return The list of starting points. - */ - const std::vector & get_x0s ( void ) const; - - /// Access to the name of a cache file containing starting points. - /** - \return The file name. - */ - const std::string & get_x0_cache_file ( void ) const; - - // Signature: standard or extern (only one is != NULL): - // ---------------------------------------------------- - private: - - /// Standard signature. - /** - Created and deleted by the Parameters class. - */ - NOMAD::Signature * _std_signature; - - /// Extern signature. - /** - Created and deleted outside the class. - */ - NOMAD::Signature * _extern_signature; - - public: - - /// Access to the signature. - /** - \return The one non-NULL signature. - */ - NOMAD::Signature * get_signature ( void ) const; - - /// Set a new extern signature. - /** - Deletes the standard signature. - \param s A pointer to the extern signature -- \b IN. - */ - void set_EXTERN_SIGNATURE ( NOMAD::Signature * s ); - - // Dimension: - // ---------- - private: - - /// Dimension. - /** - - Number of variables. - - Parameter \c DIMENSION. - */ - int _dimension; - - public: - - /// Access to the dimension. - /** - \return The dimension. - */ - int get_dimension ( void ) const; - - /// Set the dimension. - /** - \param n The dimension -- \b IN. - \return \c true if the operation succeeded. - */ - bool set_DIMENSION ( int n ); - - // Fixed variables: - // ---------------- - private: - - /// Fixed variables. - /** - - This point is of dimension \c n (parameter \c DIMENSION). - - Undefined values correspond to free variables. - */ - NOMAD::Point _fixed_variables; - - /// Number of free variables. - int _nb_free_variables; - - public: - - /// Access to the number of free variables. - /** - \return The number of free variables. - */ - int get_nb_free_variables ( void ) const; - - /// Access to the fixed variables. - /** - \return The fixed variables. - */ - const NOMAD::Point & get_fixed_variable ( void ) const - { - return get_fixed_variables(); - } - - /// Access to the fixed variables. - /** - \return The fixed variables. - */ - const NOMAD::Point & get_fixed_variables ( void ) const; - - /// Test if a variable is fixed. - /** - \param i Index of the variable -- \b IN. - \return A boolean equal to \c true if the variable \c i is fixed. - */ - bool variable_is_fixed ( int i ) const; - - /// Reset the fixed variables. - /** - This frees all the variables. - */ - void reset_fixed_variables ( void ); - - /// Fix one variable. - /** - \param i Index of the variable -- \b IN. - \param value Value of the fixed variable -- \b IN. - */ - void set_FIXED_VARIABLE ( int i , const NOMAD::Double & value ); - - /// Fix one variable. - /** - The value of the variable is based on the starting point. - \param i Index of the variable -- \b IN. - */ - void set_FIXED_VARIABLE ( int i ); - - /// Fix a series of variables. - /** - \param fv The fixed variables; This point is of dimension \c n; - free variables correspond to undefined values -- \b IN. - */ - void set_FIXED_VARIABLE ( const NOMAD::Point & fv ); - - /// Free a variable. - /** - \param i Index of the variable -- \b IN. - */ - void set_FREE_VARIABLE ( int i ) { set_FIXED_VARIABLE ( i , NOMAD::Double() ); } - - // Periodic variables: - // ------------------- - - /// Periodic variables. - /** - - This vector is of size \c n. - - \c _periodic_variables[i] is equal to \c true if - the variable \c i is periodic. - */ - std::vector _periodic_variables; - - /// Access to the periodic variables. - /** - \return The periodic variables - */ - const std::vector & get_periodic_variable ( void ) const - { - return get_periodic_variables(); - } - - /// Access to the periodic variables. - /** - \return The periodic variables - */ - const std::vector & get_periodic_variables ( void ) const; - - /// Check if there is periodic variables. - /** - \return A boolean equal to \c true if there is periodic variables. - */ - bool has_periodic_variables ( void ) const - { - return !_periodic_variables.empty(); - } - - /// Reset periodic variables. - void reset_periodic_variables ( void ); - - /// Set one variable to be periodic. - /** - \param i Index of the variable -- \b IN. - */ - void set_PERIODIC_VARIABLE ( int i ); - - /// Set a series of variables to be periodic. - /** - \param pv Vector of size \c n indicating the - periodic variables -- \b IN. - */ - void set_PERIODIC_VARIABLE ( const std::vector & pv ); - - // Categorical variables: - // ---------------------- - private: - - /// Extended poll trigger. - /** - - Must be strictly positive. - - May be relative. - */ - NOMAD::Double _extended_poll_trigger; - - /// Equal to \c true if the extended poll trigger is relative. - bool _relative_ept; - - /// Equal to \c true if the extended poll is enabled. - bool _extended_poll_enabled; - - /// Neighborhood executable for using batch mode with categorical variables. - std::string _neighbors_exe; - - public: - - /// Access to the extended poll trigger. - /** - \return The extended poll trigger. - */ - const NOMAD::Double & get_extended_poll_trigger ( void ) const; - - /// Check if the extended poll trigger is relative. - /** - \return A boolean equal to \c true if the extended poll trigger is relative. - */ - bool get_relative_ept ( void ) const; - - /// Check if the extended poll is enabled. - /** - \return A boolean equal to \c true if the extended poll is enabled. - */ - bool get_extended_poll_enabled ( void ) const; - - /// Access to the neighborhood executable. - /** - \return The neighborhood executable. - */ - const std::string & get_neighbors_exe ( void ) const; - - /// Set the extended poll trigger. - /** - \param ept The extended poll trigger -- \b IN. - \param rel A boolean equal to \c true if the extended poll - trigger is relative -- \b IN. - */ - void set_EXTENDED_POLL_TRIGGER ( const NOMAD::Double & ept , bool rel ); - - /// Enable or disable the extended poll. - /** - \param epe A boolean equal to \c true if the extended poll is enabled -- \b IN. - */ - void set_EXTENDED_POLL_ENABLED ( bool epe ); - - /// Set the neighborhood executable. - /** - \param ne The neighborhood executable. - */ - void set_NEIGHBORS_EXE ( const std::string & ne ); - - // Groups of variables: - // -------------------- - private: - - /// Groups of variables. - std::set _var_groups; - - /// User groups of variables. - std::set _user_var_groups; - - /// Reset a group of variables. - /** - \param g Group to reset; may be \c _var_groups or \c _user_var_groups - -- \b IN/OUT. - */ - void reset_variable_groups - ( std::set & g ) const; - - public: - - /// Reset groups of variables. - void reset_variable_groups ( void ); - - /// Access to the groups of variables. - /** - \return The groups of variables. - */ - const std::set & - get_variable_groups ( void ) const; - - /// Set one group of variables. - /** - Basic version. - \param var_indexes Indexes of the variables of the group -- \b IN. - */ - void set_VARIABLE_GROUP ( const std::set & var_indexes ); - - /// Set one group of variables. - /** - Advanced version. - \param var_indexes Indexes of the variables of the group -- \b IN. - \param prim_poll_dir_types Types of the poll directions -- \b IN. - \param sec_poll_dir_types Types of the secondary poll directions -- \b IN. - */ - void set_VARIABLE_GROUP - ( const std::set & var_indexes , - const std::set & prim_poll_dir_types , - const std::set & sec_poll_dir_types ); - - /// Set several groups of variables. - /** - \param vg A list of groups of variables -- \b IN. - */ - void set_VARIABLE_GROUP ( const std::list & vg ); - - // Bounds and scaling: - // ------------------- - private: - - NOMAD::Point _lb; ///< Lower bounds. - NOMAD::Point _ub; ///< Upper bounds. - NOMAD::Point _scaling; ///< Scaling. - - public: - - /// Access to the lower bounds. - /** - \return The lower bounds. - */ - const NOMAD::Point & get_lb ( void ) const; - - /// Access to the upper bounds. - /** - \return The upper bounds. - */ - const NOMAD::Point & get_ub ( void ) const; - - /// Access to the lower bounds. - /** - \return The lower bounds. - */ - const NOMAD::Point & get_lower_bound ( void ) const { return get_lb(); } - - /// Access to the upper bounds. - /** - \return The upper bounds. - */ - const NOMAD::Point & get_upper_bound ( void ) const { return get_ub(); } - - /// Access to the scaling. - /** - \return The scaling. - */ - const NOMAD::Point & get_scaling ( void ) const; - - /// Reset the bounds. - void reset_bounds ( void ); - - /// Reset the scaling. - void reset_scaling ( void ); - - /// Set one lower bound. - /** - \param i Index of the variable -- \b IN. - \param lb Lower bound -- \b IN. - */ - void set_LOWER_BOUND ( int i , const NOMAD::Double & lb ); - - /// Set all lower bounds. - /** - Use undefined values for variables without bounds. - \param lb Lower bounds -- \b IN. - */ - void set_LOWER_BOUND ( const NOMAD::Point & lb ); - - /// Set one upper bound. - /** - \param i Index of the variable -- \b IN. - \param ub Upper bound -- \b IN. - */ - void set_UPPER_BOUND ( int i , const NOMAD::Double & ub ); - - /// Set all upper bounds. - /** - Use undefined values for variables without bounds. - \param ub Upper bounds -- \b IN. - */ - void set_UPPER_BOUND ( const NOMAD::Point & ub ); - - /// Set the scaling of one variable. - /** - \param i Index of the variable -- \b IN. - \param s Scaling -- \b IN. - */ - void set_SCALING ( int i , const NOMAD::Double & s ); - - /// Set the scaling for all variables. - /** - Use undefined values for variables scaling. - \param s Scaling -- \b IN. - */ - void set_SCALING ( const NOMAD::Point & s ); - - // Blackboxes (inputs and outputs): - // -------------------------------- - private: - - /// Blackbox input types. - std::vector _bb_input_type; - - /// Parameter \c BB_INPUT_INCLUDE_TAG. - bool _bb_input_include_tag; - - /// Parameter \c BB_INPUT_INCLUDE_SEED. - bool _bb_input_include_seed; - - /// Blackbox output types. - /** - May be modified during the algorithm (PEB constraints). - */ - mutable std::vector _bb_output_type; - - /// List of blackbox executables. - std::list _bb_exe; - - /// List of objective indexes. - std::list _index_obj; - - /// Index for the output \c STAT_SUM. - int _index_stat_sum; - - /// Index for the output \c STAT_AVG. - int _index_stat_avg; - - /// Index for the output \c CNT_EVAL. - /** - - \c 0 or \c 1. - - \c CNT_EVAL indicates if a blackbox evaluation has to be counted. - */ - int _index_cnt_eval; - - /// Parameter \c BB_REDIRECTION. - bool _bb_redirection; - - public: - - /// Access to the number of blackbox outputs. - /** - \return The number of blackbox outputs. - */ - int get_bb_nb_outputs ( void ) const; - - /// Access to the \c BB_INPUT_INCLUDE_TAG parameter. - /** - \return The \c BB_INPUT_INCLUDE_TAG parameter. - */ - bool get_bb_input_include_tag ( void ) const; - - /// Access to the \c BB_INPUT_INCLUDE_SEED parameter. - /** - \return The \c BB_INPUT_INCLUDE_SEED parameter. - */ - bool get_bb_input_include_seed ( void ) const; - - /// Access to the blackbox input types. - /** - \return The blackbox input types. - */ - const std::vector & get_bb_input_type ( void ) const; - - /// Access to the blackbox output types. - /** - \return The blackbox output types. - */ - const std::vector & get_bb_output_type ( void ) const; - - /// Access to the objective indexes. - /** - \return The list of objective indexes. - */ - const std::list & get_index_obj ( void ) const; - - /// Access to the number of objective functions. - /** - \return The number of objective functions. - */ - int get_nb_obj ( void ) const; - - /// Check the display and file stats. - /** - \param stats The stats -- \b IN. - \return A booleam equal to \c true if the stats are valid. - */ - bool check_display_stats ( const std::list & stats ) const; - - /// Check if there is a \c STAT_SUM output. - /** - \return A boolean equal to \c true if there a \c STAT_SUM output. - */ - bool check_stat_sum ( void ) const; - - /// Check if there is a \c STAT_AVG output. - /** - \return A boolean equal to \c true if there is a \c STAT_AVG output. - */ - bool check_stat_avg ( void ) const; - - /// Access the index of output \c CNT_EVAL output. - /** - \return Index of the \c CNT_EVAL output. - \return \c -1 if there is no \c CNT_EVAL output. - */ - int get_index_cnt_eval ( void ) const; - - /// Access the index of output \c STAT_SUM output. - /** - \return Index of the \c STAT_SUM output. - \return \c -1 if there is no \c STAT_SUM output. - */ - int get_index_stat_sum ( void ) const; - - /// Access the index of output \c STAT_AVG output. - /** - \return Index of the \c STAT_AVG output. - \return \c -1 if there is no \c STAT_AVG output. - */ - int get_index_stat_avg ( void ) const; - - /// Access to the list of blackbox executables. - /** - \return The list of blackbox executables. - */ - const std::list & get_bb_exe ( void ) const; - - /// Access to the \c BB_REDIRECTION parameter. - /** - \return The \c BB_REDIRECTION parameter. - */ - bool get_bb_redirection ( void ) const; - - /// Set the \c BB_INPUT_INCLUDE_TAG parameter. - /** - \param bbiit The \c BB_INPUT_INCLUDE_TAG parameter -- \b IN. - */ - void set_BB_INPUT_INCLUDE_TAG ( bool bbiit ); - - /// Set the \c BB_INPUT_INCLUDE_SEED parameter. - /** - \param bbiis The \c BB_INPUT_INCLUDE_SEED parameter -- \b IN. - */ - void set_BB_INPUT_INCLUDE_SEED ( bool bbiis ); - - /// Set the blackbox input type of one variable. - /** - \param index Index of the variable -- \b IN. - \param bbit Type of the variable -- \b IN. - */ - void set_BB_INPUT_TYPE ( int index , NOMAD::bb_input_type bbit ); - - /// Set the blackbox input types of all variables. - /** - \param bbit Types of the variables -- \b IN. - */ - void set_BB_INPUT_TYPE ( const std::vector & bbit ); - - /// Set the blackbox input types of all variables. - /** - \param bbit Types of the variables -- \b IN. - */ - void set_BB_INPUT_TYPE ( const std::list & bbit ); - - /// Set the blackbox output types. - /** - \param bbot Blackbox output types -- \b IN. - */ - void set_BB_OUTPUT_TYPE ( const std::list & bbot ); - - /// Set the blackbox output types. - /** - \param bbot Blackbox output types -- \b IN. - */ - void set_BB_OUTPUT_TYPE ( const std::vector & bbot ); - - /// Set a list of blackbox executable names. - /** - Must correspond to the blackbox output types. - \param bbexe The list of blackbox executable names -- \b IN. - */ - void set_BB_EXE ( const std::list & bbexe ); - - /// Set a list of blackbox executable names. - /** - \param m Number of blackbox outputs and size of \c bbexe -- \b IN. - \param bbexe The list of blackbox executable names -- \b IN. - */ - void set_BB_EXE ( int m , const std::string * bbexe ); - - /// Set a unique blackbox executable name. - /** - \param bbexe The blackbox executable name -- \b IN. - */ - void set_BB_EXE ( const std::string & bbexe ); - - /// Set the \c BB_REDIRECTION parameter. - /** - \param bbr The \c BB_REDIRECTION parameter -- \b IN. - */ - void set_BB_REDIRECTION ( bool bbr ); - - /// Reset the PEB statuses. - /** - Set all outputs at NOMAD::PEB_E (PEB constraint in "extreme" status) - to NOMAD::PEB_P (PEB constraint in "progressive" status). - */ - void reset_PEB_changes ( void ) const; - - /// Change constraints from PEB to PB. - /** - Set all outputs at NOMAD::PEB to NOMAD::PB - */ - void change_PEB_to_PB ( void ); - - /// Change the status of one PEB constraint. - /** - The status is changed from - NOMAD::PEB_P (PEB constraint in "progressive" status) - to NOMAD::PEB_E (PEB constraint in "extreme" status). - \param index Index of the PEB constraint. - */ - void change_PEB_constraint_status ( int index ) const; - - // Surrogates: - // ----------- - private: - - /// Surrogate executables. - /** - \c _sgte_exe[bb_exe] corresponds to the surrogate associated - with the blackbox true executable \c bb_exe. - */ - std::map _sgte_exe; - - bool _disable_eval_sort; ///< Sort disablement - - /// Flag equal to \c true if surrogates are used to sort evaluation points. - bool _sgte_eval_sort; - - /// Flag equal to \c true if the problem has a surrogate. - bool _has_sgte; - - /// Flag equal to \c true if NOMAD considers only surrogates. - bool _opt_only_sgte; - - /// Surrogate cost. - /** - Number of surrogate evaluations counting as one blackbox evaluation. - */ - int _sgte_cost; - - /// Maximum number of surrogate evaluations. - int _sgte_max_eval; - - /// Surrogate cache file. - std::string _sgte_cache_file; - - public: - - /// Access to the surrogate associated with a truth executable. - /** - \param bb_exe The truth executable -- \b IN. - \return The surrogate executable name. - \return An empty string if \c bb_exe has no surrogate. - */ - std::string get_sgte_exe ( const std::string & bb_exe ) const; - - /// Access to the \c SGTE_EVAL_SORT parameter. - /** - \return The \c SGTE_EVAL_SORT parameter. - */ - bool get_sgte_eval_sort ( void ) const; - - /// Access to the \c SGTE_COST parameter. - /** - \return The \c SGTE_COST parameter. - */ - int get_sgte_cost ( void ) const; - - /// Access to the \c MAX_SGTE_EVAL parameter. - /** - \return The \c MAX_SGTE_EVAL parameter. - */ - int get_max_sgte_eval ( void ) const; - - /// Access to the \c SGTE_CACHE_FILE parameter. - /** - \return The \c SGTE_CACHE_FILE parameter. - */ - const std::string & get_sgte_cache_file ( void ) const; - - /// Access to the \c HAS_SGTEparameter. - /** - \return The \c HAS_SGTEparameter. - */ - bool has_sgte ( void ) const; - - /// Access to the \c OPT_ONLY_SGTE parameter. - /** - \return The \c OPT_ONLY_SGTE parameter. - */ - bool get_opt_only_sgte ( void ) const; - - /// Check if a surrogate executable has been defined. - /** - \return A boolean equal to \c true if - a surrogate executable has been defined. - */ - bool has_sgte_exe ( void ) const; - - /// Set the \c SGTE_EXE parameter. - /** - \param bb_exe Truth executable -- \b IN. - \param sgte_exe Associated surrogate executable -- \b IN. - */ - void set_SGTE_EXE ( const std::string & bb_exe , const std::string & sgte_exe ); - - /// Set the \c SGTE_EVAL_SORT parameter. - /** - \param ses The \c SGTE_EVAL_SORT parameter -- \b IN. - */ - void set_SGTE_EVAL_SORT ( bool ses ); - - /// Set the \c HAS_SGTE parameter. - /** - \param hs The \c HAS_SGTE parameter -- \b IN. - */ - void set_HAS_SGTE ( bool hs ); - - /// Set the \c OPT_ONLY_SGTE parameter. - /** - \param oos The \c OPT_ONLY_SGTE parameter -- \b IN. - */ - void set_OPT_ONLY_SGTE ( bool oos ); - - /// Set the \c SGTE_COST parameter. - /** - \param sc The \c SGTE_COST parameter -- \b IN. - */ - void set_SGTE_COST ( int sc ); - - /// Set the \c MAX_SGTE_EVAL parameter. - /** - \param mse The \c MAX_SGTE_EVAL parameter -- \b IN. - */ - void set_MAX_SGTE_EVAL ( int mse ); - - /// Set the \c SGTE_CACHE_FILE parameter. - /** - \param scf The \c SGTE_CACHE_FILE parameter -- \b IN. - */ - void set_SGTE_CACHE_FILE ( const std::string & scf ); - - // Barrier: - // -------- - private: - NOMAD::Double _h_min; ///< Value of \c h_min. - NOMAD::Double _h_max_0; ///< Initial value of \c h_max. - NOMAD::Double _rho; ///< Rho parameter of the progressive barrier. - NOMAD::hnorm_type _h_norm; ///< Norm used to compute the feasibility function \c h. - - /// Flag equal to \c true if there are constraints. - bool _has_constraints; - - /// Flag equal to \c true if there are filter or progressive barrier constraints. - bool _has_filter_constraints; - - /// Flag equal to \c true if there are extreme barrier constraints. - bool _has_EB_constraints; - - /// Type of the barrier. - /** - May be NOMAD::FILTER, NOMAD::PB, NOMAD::PEB_P, or NOMAD::EB. - */ - NOMAD::bb_output_type _barrier_type; - - public: - - /// Access to the \c H_MIN parameter. - /** - \return The \c H_MIN parameter. - */ - const NOMAD::Double & get_h_min ( void ) const; - - /// Access to the \c H_MAX_0 parameter. - /** - \return The \c H_MAX_0 parameter. - */ - const NOMAD::Double & get_h_max_0 ( void ) const; - - /// Access to the \c RHO parameter. - /** - \return The \c RHO parameter. - */ - const NOMAD::Double & get_rho ( void ) const; - - /// Access to the \c H_NORM parameter. - /** - \return The \c H_NORM parameter. - */ - NOMAD::hnorm_type get_h_norm ( void ) const; - - /// Access to the type of barrier. - /** - \return The type of barrier. - */ - NOMAD::bb_output_type get_barrier_type ( void ) const; - - /// Check if there are constraints. - /** - \return A boolean equal to \c true if there are constraints. - */ - bool has_constraints ( void ) const; - - /// Check if there are extreme barrier constraints. - /** - \return A boolean equal to \c true if there are extreme barrier constraints. - */ - bool has_EB_constraints ( void ) const; - - /// Check if the progressive barrier (PB) is used. - /** - \return A boolean equal to \c true if the PB is used. - */ - bool use_sec_poll_center ( void ) const; - - /// Set the \c H_MIN parameter. - /** - \param h_min The \c H_MIN parameter -- \b IN. - */ - void set_H_MIN ( const NOMAD::Double & h_min ); - - /// Set the \c H_MAX_0 parameter. - /** - \param h_max The \c H_MAX_0 parameter -- \b IN. - */ - void set_H_MAX_0 ( const NOMAD::Double & h_max ); - - /// Set the \c RHO parameter. - /** - \param rho The \c RHO parameter -- \b IN. - */ - void set_RHO ( const NOMAD::Double & rho ); - - /// Set the \c H_NORM parameter. - /** - \param h_norm The \c H_NORM parameter -- \b IN. - */ - void set_H_NORM ( NOMAD::hnorm_type h_norm ); - - // MULTI-MADS parameters: - // ---------------------- - private: - - /// Number of MADS runs in Multi-MADS. - int _multi_nb_mads_runs; - - /// Maximum number of blackbox evaluations in Multi-MADS. - int _multi_overall_bb_eval; - - /// Flag equal to \c true if the delta criterion is used in Multi-MADS. - bool _multi_use_delta_crit; - - /// Bounds on the objective necessary for the display of the \c surf stat. - NOMAD::Point _multi_f_bounds; - - /// Multi-MADS reformulation. - /** - May be NOMAD::NORMALIZED, NOMAD::PRODUCT, - NOMAD::DIST_L1, NOMAD::DIST_L2, or NOMAD::DIST_LINF. - */ - NOMAD::multi_formulation_type _multi_formulation; - - public: - - /// Access to the \c MULTI_NB_MADS_RUNS parameter. - /** - \return The \c MULTI_NB_MADS_RUNS parameter. - */ - int get_multi_nb_mads_runs ( void ) const; - - /// Access to the \c MULTI_OVERALL_BB_EVAL parameter. - /** - \return The \c MULTI_OVERALL_BB_EVAL parameter. - */ - int get_multi_overall_bb_eval ( void ) const; - - /// Access to the \c MULTI_USE_DELTA_CRIT parameter. - /** - \return The \c MULTI_USE_DELTA_CRIT parameter. - */ - bool get_multi_use_delta_crit ( void ) const; - - /// Access to the \c MULTI_F_BOUNDS parameter. - /** - \return The \c MULTI_F_BOUNDS parameter. - */ - const NOMAD::Point & get_multi_f_bounds ( void ) const; - - /// Access to the \c MULTI_FORMULATION parameter. - /** - \return The \c MULTI_FORMULATION parameter. - */ - NOMAD::multi_formulation_type get_multi_formulation ( void ) const; - - /// Set the \c MULTI_NB_MADS_RUNS parameter. - /** - \param mads_runs The \c MULTI_NB_MADS_RUNS parameter -- \b IN. - */ - void set_MULTI_NB_MADS_RUNS ( int mads_runs ); - - /// Set the \c MULTI_OVERALL_BB_EVAL parameter. - /** - \param bbe The \c MULTI_OVERALL_BB_EVAL parameter -- \b IN. - */ - void set_MULTI_OVERALL_BB_EVAL ( int bbe ); - - /// Set the \c MULTI_USE_DELTA_CRIT parameter. - /** - \param udc The \c MULTI_USE_DELTA_CRIT parameter -- \b IN. - */ - void set_MULTI_USE_DELTA_CRIT ( bool udc ); - - /// Set the \c MULTI_F_BOUNDS parameter. - /** - \param mfb The \c MULTI_F_BOUNDS parameter -- \b IN. - */ - void set_MULTI_F_BOUNDS ( const NOMAD::Point & mfb ); - - /// Set the \c MULTI_FORMULATION parameter. - /** - \param mf The \c MULTI_FORMULATION parameter -- \b IN. - */ - void set_MULTI_FORMULATION ( NOMAD::multi_formulation_type mf ); - - // Opportunistic strategy parameters: - // ---------------------------------- - private: - - /// Flag equal to \c true if the opportunistic strategy is enabled. - bool _opportunistic_eval; - - /// Minimum number of successes. - /** - Parameter \c OPPORTUNISTIC_MIN_NB_SUCCESS. - */ - int _opportunistic_min_nb_success; - - /// Minimum number of evaluations. - /** - Parameter \c OPPORTUNISTIC_MIN_EVAL. - */ - int _opportunistic_min_eval; - - /// Minimum (relative) percentage of feasible objective improvement. - /** - Parameter \c OPPORTUNISTIC_MIN_F_IMPRVMT. - */ - NOMAD::Double _opportunistic_min_f_imprvmt; - - /// Flag equal to \c true if the lucky evaluation is enabled. - /** - Do one more eval "for luck". - */ - bool _opportunistic_lucky_eval; - - - /// Max block size for list evaluation - /** - Parameter \c BB_MAX_BLOCK_SIZE. - */ - int _bb_max_block_size; - - /// Block of points evaluation - /** - Parameter \c EVAL_POINTS_AS_BLOCK. - */ - bool _eval_points_as_block; - - public: - - /// Access to the \c OPPORTUNISTIC_EVAL parameter. - /** - \return The \c OPPORTUNISTIC_EVAL parameter - */ - bool get_opportunistic_eval ( void ) const; - - /// Access to the \c OPPORTUNISTIC_MIN_NB_SUCCESS parameter. - /** - \return The \c OPPORTUNISTIC_MIN_NB_SUCCESS parameter. - */ - int get_opportunistic_min_nb_success ( void ) const; - - /// Access to the \c OPPORTUNISTIC_MIN_EVAL parameter. - /** - \return The \c OPPORTUNISTIC_MIN_EVAL parameter. - */ - int get_opportunistic_min_eval ( void ) const; - - /// Access to the \c OPPORTUNISTIC_MIN_F_IMPRVMT parameter. - /** - \return The \c OPPORTUNISTIC_MIN_F_IMPRVMT parameter. - */ - const NOMAD::Double & get_opportunistic_min_f_imprvmt ( void ) const; - - /// Access to the \c OPPORTUNISTIC_LUCKY_EVAL parameter. - /** - \return The \c OPPORTUNISTIC_LUCKY_EVAL parameter. - */ - bool get_opportunistic_lucky_eval ( void ) const; - - /// Access to the \c BB_MAX_BLOCK_SIZE parameter - /** - \return the \c BB_MAX_BLOCK_SIZE parameter - */ - int get_bb_max_block_size ( void ) const ; - - /// Set the \c BB_MAX_BLOCK_SIZE parameter. - /** - \param bb_block_size The \c BB_MAX_BLOCK_SIZE parameter -- \b IN. - */ - void set_BB_MAX_BLOCK_SIZE ( int bb_block_size ); - - /// Access to the \c EVAL_POINTS_AS_BLOCK parameter - /** - \return true if points are evaluated as a block (number of elements >=1) - */ - bool eval_points_as_block() const {return _eval_points_as_block;} - - - /// Set the \c OPPORTUNISTIC_EVAL parameter. - /** - \param opp_eval The \c OPPORTUNISTIC_EVAL parameter -- \b IN. - */ - void set_OPPORTUNISTIC_EVAL ( bool opp_eval ); - - /// Set the \c OPPORTUNISTIC_MIN_NB_SUCCESS parameter. - /** - \param opp_min_nb_succ The \c OPPORTUNISTIC_MIN_NB_SUCCESS parameter -- \b IN. - */ - void set_OPPORTUNISTIC_MIN_NB_SUCCESS ( int opp_min_nb_succ ); - - /// Set the \c OPPORTUNISTIC_MIN_EVAL parameter. - /** - \param opp_min_eval The \c OPPORTUNISTIC_MIN_EVAL parameter -- \b IN. - */ - void set_OPPORTUNISTIC_MIN_EVAL ( int opp_min_eval ); - - /// Set the \c OPPORTUNISTIC_MIN_F_IMPRVMT parameter. - /** - \param opp_min_f_imprvt The \c OPPORTUNISTIC_MIN_F_IMPRVMT parameter -- \b IN. - */ - void set_OPPORTUNISTIC_MIN_F_IMPRVMT ( const NOMAD::Double & opp_min_f_imprvt ); - - /// Set the \c OPPORTUNISTIC_LUCKY_EVAL parameter. - /** - \param opp_lucky_eval The \c OPPORTUNISTIC_LUCKY_EVAL parameter -- \b IN. - */ - void set_OPPORTUNISTIC_LUCKY_EVAL ( bool opp_lucky_eval ); - - - - - }; - - /*----------------------------------------------------------------------*/ - - /// Display a NOMAD::Parameters object. - /** - \param out The NOMAD::Display object -- \b IN. - \param p The NOMAD::Parameters object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Parameters & p ) - { - p.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Front.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Front.cpp deleted file mode 100644 index dd133e111..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Front.cpp +++ /dev/null @@ -1,439 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Pareto_Front.cpp - \brief Pareto front (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Pareto_Front.hpp -*/ -#include "Pareto_Front.hpp" - -/*------------------------------------------------------*/ -/* insertion of a point */ -/* (returns true if the point is a new Pareto point) */ -/*------------------------------------------------------*/ -bool NOMAD::Pareto_Front::insert ( const NOMAD::Eval_Point & x ) -{ - - NOMAD::Pareto_Point pp ( &x ); - - if ( _pareto_pts.empty() ) { - _pareto_pts.insert (pp); - return true; - } - - bool insert = false; - - std::set::iterator it = _pareto_pts.begin(); - while ( it != _pareto_pts.end() ) { - if ( pp.dominates (*it) ) { - _pareto_pts.erase(it++); - insert = true; - - continue; - } - ++it; - } - - if ( !insert ) { - insert = true; - std::set::iterator end = _pareto_pts.end(); - for ( it = _pareto_pts.begin() ; it != end ; ++it ) { - if ( it->dominates (pp) ) { - insert = false; - break; - } - } - } - - if ( insert ) { - _pareto_pts.insert ( pp ); - return true; - } - return false; -} - -/*-------------------------------------------------------*/ -/* get the point that minimizes f2(x) */ -/* (this is simply the last point of the Pareto front) */ -/*-------------------------------------------------------*/ -const NOMAD::Eval_Point * NOMAD::Pareto_Front::get_best_f2 ( void ) const -{ - if ( _pareto_pts.empty() ) - return NULL; - - std::set::const_iterator it = _pareto_pts.end(); - --it; - - return it->get_element(); -} - -/*------------------------------------------------------*/ -/* get the reference point */ -/*------------------------------------------------------*/ -NOMAD::Point * NOMAD::Pareto_Front::get_ref ( const NOMAD::Pareto_Point *& xj , - NOMAD::Double & delta_j ) const -{ - xj = NULL; - delta_j.clear(); - - int p = static_cast(_pareto_pts.size()); - - // no points in the front: - if ( p == 0 ) - return NULL; - - // just one point in the front: - if ( p == 1 ) { - xj = &(*_pareto_pts.begin()); - delta_j = 1.0 / ( xj->get_w() + 1 ); // delta=1.0 - return NULL; - } - - std::set::const_iterator it = _pareto_pts.begin(); - NOMAD::Point * ref = new NOMAD::Point ( 2 ); - - NOMAD::Double f1xm1; // f_1 ( x_{j-1} ) - NOMAD::Double f1x; // f_1 ( x_j ) - NOMAD::Double f1xp1; // f_1 ( x_{j+1} ) - - NOMAD::Double f2xm1; // f_2 ( x_{j-1} ) - NOMAD::Double f2x; // f_2 ( x_j ) - NOMAD::Double f2xp1; // f_2 ( x_{j+1} ) - - // two points in the front: - if ( p == 2 ) { - - f1xm1 = it->get_f1(); - f2xm1 = it->get_f2(); - - ++it; - xj = &(*it); - - f1x = xj->get_f1(); - f2x = xj->get_f2(); - - delta_j = ( (f1x-f1xm1).pow2() + (f2x-f2xm1).pow2() ) / ( xj->get_w() + 1.0 ); - - const_cast(xj)->update_w(); - - (*ref)[0] = f1x; - (*ref)[1] = f2xm1; - - return ref; - } - - // more than two points in the front: - std::set::const_iterator end = _pareto_pts.end(); - - const NOMAD::Pareto_Point * prev , * cur , * next; - - NOMAD::Double delta; - - prev = &(*it); - ++it; - - while ( true ) { - - cur = &(*it); - - ++it; - if ( it == end ) - break; - - next = &(*it); - - f1xm1 = prev->get_f1(); - f2xm1 = prev->get_f2(); - - f1x = cur->get_f1(); - f2x = cur->get_f2(); - - f1xp1 = next->get_f1(); - f2xp1 = next->get_f2(); - - delta = ( (f1x-f1xm1).pow2() + (f2x-f2xm1).pow2() + - (f1x-f1xp1).pow2() + (f2x-f2xp1).pow2() ) / ( cur->get_w() + 1.0 ); - - if ( !delta_j.is_defined() || delta > delta_j ) { - xj = cur; - delta_j = delta; - (*ref)[0] = f1xp1; - (*ref)[1] = f2xm1; - } - - prev = cur; - } - - const_cast(xj)->update_w(); - - return ref; -} - -/*------------------------------------------------------*/ -/* compute delta and surf */ -/*------------------------------------------------------*/ -void NOMAD::Pareto_Front::get_delta_surf ( NOMAD::Double & delta_j , - NOMAD::Double & surf , - const NOMAD::Point & f_bounds ) const -{ - bool def = f_bounds.is_complete(); - NOMAD::Double f1_min , f1_max , f2_min , f2_max; - - if ( def ) { - - if ( f_bounds.size() == 4 ) { - - f1_min = f_bounds[0]; - f1_max = f_bounds[1]; - f2_min = f_bounds[2]; - f2_max = f_bounds[3]; - - if ( f1_min >= f1_max || f2_min >= f2_max ) { - f1_min.clear(); - f1_max.clear(); - f2_min.clear(); - f2_max.clear(); - def = false; - } - } - else - def = false; - } - - delta_j.clear(); - surf.clear(); - - int p = static_cast ( _pareto_pts.size() ); - - // no point in the front: - if ( p == 0 ) { - if ( def ) - surf = 1.0; - return; - } - - const NOMAD::Pareto_Point * xj; - NOMAD::Double f1x; // f_1 ( x_j ) - NOMAD::Double f2x; // f_2 ( x_j ) - - NOMAD::Double surf_frame = (def) ? - ( f2_max - f2_min ) * ( f1_max - f1_min ) - : NOMAD::Double(); - - // just one point in the front: - if ( p == 1 ) { - xj = &(*_pareto_pts.begin()); - delta_j = 1.0 / ( xj->get_w() + 1 ); // delta=1.0 - f1x = xj->get_f1(); - f2x = xj->get_f2(); - - if ( !def || f1x > f1_max || f1x < f1_min || f2x > f2_max || f2x < f2_min ) - return; - - surf = ( ( f2_max - f2_min ) * ( f1x - f1_min ) - + ( f2x - f2_min ) * ( f1_max - f1x ) ) / surf_frame; - - return; - } - - std::set::const_iterator it = _pareto_pts.begin(); - - NOMAD::Double f1xm1; // f_1 ( x_{j-1} ) - NOMAD::Double f1xp1; // f_1 ( x_{j+1} ) - - NOMAD::Double f2xm1; // f_2 ( x_{j-1} ) - NOMAD::Double f2xp1; // f_2 ( x_{j+1} ) - - // two points in the front: - if ( p == 2 ) { - - f1xm1 = it->get_f1(); - f2xm1 = it->get_f2(); - - if ( def && ( f1xm1 < f1_min || - f1xm1 > f1_max || - f2xm1 < f2_min || - f2xm1 > f2_max ) ) - def = false; - - ++it; - xj = &(*it); - - f1x = xj->get_f1(); - f2x = xj->get_f2(); - - if ( def && ( f1x < f1_min || - f1x > f1_max || - f2x < f2_min || - f2x > f2_max ) ) - def = false; - - delta_j = ( (f1x-f1xm1).pow2() + (f2x-f2xm1).pow2() ) / ( xj->get_w() + 1.0 ); - - if ( def ) - surf = ( ( f2xm1 - f2_min ) * ( f1x - f1xm1 ) - + ( f2_max - f2_min ) * ( f1xm1 - f1_min ) - + ( f2x - f2_min ) * ( f1_max - f1x ) ) / surf_frame; - - return; - } - - // more than two points in the front: - std::set::const_iterator end = _pareto_pts.end(); - - const NOMAD::Pareto_Point * prev , * cur , * next; - - NOMAD::Double delta; - - prev = &(*it); - f1xm1 = prev->get_f1(); - f2xm1 = prev->get_f2(); - - ++it; - - cur = &(*it); - f1x = cur->get_f1(); - - if ( def && ( f1xm1 < f1_min || - f1xm1 > f1_max || - f2xm1 < f2_min || - f2xm1 > f2_max || - f1x < f1_min || - f1x > f1_max ) ) - def = false; - - if ( def ) - surf = ( f2xm1 - f2_min ) * ( f1x - f1xm1 ) - + ( f2_max - f2_min ) * ( f1xm1 - f1_min ); - - while ( true ) { - - cur = &(*it); - - ++it; - if ( it == end ) - break; - - next = &(*it); - - f1xm1 = prev->get_f1(); - f2xm1 = prev->get_f2(); - - f1x = cur->get_f1(); - f2x = cur->get_f2(); - - f1xp1 = next->get_f1(); - f2xp1 = next->get_f2(); - - - if ( def && - ( f1xm1 < f1_min || f1xm1 > f1_max || f2xm1 < f2_min || f2xm1 > f2_max || - f1x < f1_min || f1x > f1_max || f2x < f2_min || f2x > f2_max || - f1xp1 < f1_min || f1xp1 > f1_max || f2xp1 < f2_min || f2xp1 > f2_max ) ) - def = false; - - delta = ( (f1x-f1xm1).pow2() + (f2x-f2xm1).pow2() + - (f1x-f1xp1).pow2() + (f2x-f2xp1).pow2() ) / ( cur->get_w() + 1.0 ); - - if ( !delta_j.is_defined() || delta > delta_j ) - delta_j = delta; - - if ( def ) - surf += ( f2x - f2_min ) * ( f1xp1 - f1x ); - - prev = cur; - } - - if ( def ) { - surf += ( f2xp1 - f2_min ) * ( f1_max - f1xp1 ); - surf = surf / surf_frame; - } - else - surf.clear(); -} - -/*------------------------------------------------------*/ -/* display the Pareto points */ -/*------------------------------------------------------*/ -void NOMAD::Pareto_Front::display ( const NOMAD::Display & out ) const -{ - size_t nb = _pareto_pts.size(); - int cnt = 0; - std::set::const_iterator it , end = _pareto_pts.end(); - for ( it = _pareto_pts.begin() ; it != end ; ++it ) { - out << "#"; - out.display_int_w ( cnt++ , static_cast(nb) ); - out << " "; - it->display ( out ); - out << std::endl; - } -} - -/*------------------------------------------------------------------*/ -/* . begin() and next() methods, to browse the front */ -/* */ -/* . example: */ -/* */ -/* const Eval_Point * cur = pareto_front.begin(); */ -/* while (cur) { */ -/* ... */ -/* cur = pareto_front.next(); */ -/* } */ -/*------------------------------------------------------------------*/ - -// begin(): -// -------- -const NOMAD::Eval_Point * NOMAD::Pareto_Front::begin ( void ) const -{ - if ( _pareto_pts.empty() ) - return NULL; - _it = _pareto_pts.begin(); - return _it->get_element(); -} - -// next(): (supposes that begin() has been called) -// ------- -const NOMAD::Eval_Point * NOMAD::Pareto_Front::next ( void ) const -{ - if ( _pareto_pts.empty() ) - return NULL; - ++_it; - if ( _it == _pareto_pts.end() ) - return NULL; - return _it->get_element(); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Front.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Front.hpp deleted file mode 100644 index ec5b3d418..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Front.hpp +++ /dev/null @@ -1,166 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Pareto_Front.hpp - \brief Pareto front (headers) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Pareto_Front.cpp -*/ -#ifndef __PARETO_FRONT__ -#define __PARETO_FRONT__ - -#include "Pareto_Point.hpp" - -namespace NOMAD { - - /// Pareto front for two objective functions. - /** - Browse the front with the following instructions: - \code - const Eval_Point * cur = pareto_front.begin(); - while ( cur ) { - ... - cur = pareto_front.next(); - } - \endcode - */ - class Pareto_Front : private NOMAD::Uncopyable { - - private: - - /// The set of Pareto points. - std::set _pareto_pts; - - /// Iterator to browse the front with begin() and next(). - mutable std::set::const_iterator _it; - - public: - - /// Constructor. - Pareto_Front ( void ) {} - - /// Destructor. - virtual ~Pareto_Front ( void ) {} - - /// Access to the first Pareto point. - /** - Used to initialize a loop on the Pareto points. - \return A pointer to the first Pareto point and \c NULL if the front - is empty. - */ - const NOMAD::Eval_Point * begin ( void ) const; - - /// Access to the next Pareto point. - /** - Used to increment a loop on the Pareto points. - \return A pointer to the next Pareto point and \c NULL if - the current point is the last point in the front. - */ - const NOMAD::Eval_Point * next ( void ) const; - - /// Access to the number of Pareto points. - /** - \return The number of Pareto points. - */ - int size ( void ) const { return static_cast(_pareto_pts.size()); } - - /// Check if the front is empty. - /** - \return A boolean equal to \c true if the front is empty. - */ - bool empty ( void ) const { return _pareto_pts.empty(); } - - /// Computation and access to the reference point. - /** - \param xj A pointer to the reference point; Is equal to \c NULL if - no reference exists -- \b OUT. - \param delta_j The \c delta stats measuring the front repartition -- \b OUT. - \return A pointer to the reference point and - \c NULL if there is no reference point. - */ - NOMAD::Point * get_ref ( const NOMAD::Pareto_Point *& xj , - NOMAD::Double & delta_j ) const; - - /// Access to the Pareto point minimizing f2(x). - /** - \return A pointer to the Pareto point minimizing f2 and - \c NULL if such a point does not exist. - */ - const NOMAD::Eval_Point * get_best_f2 ( void ) const; - - /// Compute the stats \c delta and \c surf. - /** - - \c delta measures the front repartition (lower is best). - - \c surf measures the front quality (lower is best). - \param delta_j The \c delta stat -- \b OUT. - \param surf The \c surf stat -- \b OUT. - \param f_bounds NOMAD::Point with 4 values (f1_min, f1_max, f2_min, and f2_max) - defining bounds for f1 and f2 for the computation - of the \c surf stat -- \b IN. - */ - void get_delta_surf ( NOMAD::Double & delta_j , - NOMAD::Double & surf , - const NOMAD::Point & f_bounds ) const; - - /// Insertion of a point in the Pareto front. - /** - \param x The point to be inserted -- \b IN. - \return A boolean equal to \c true if the point is a new Pareto point. - */ - bool insert ( const NOMAD::Eval_Point & x ); - - /// Display the Pareto points. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::Pareto_Front object. - /** - \param out The NOMAD::Display object -- \b IN. - \param pf The NOMAD::Pareto_Front object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Pareto_Front & pf ) { - pf.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Point.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Point.cpp deleted file mode 100644 index a28cae0c1..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Point.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Pareto_Point.cpp - \brief Pareto point (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Pareto_Point.hpp -*/ -#include "Pareto_Point.hpp" - -/*--------------------------------------------------------*/ -/* comparison operator: */ -/* . supposes that argument fp is a Pareto_Point */ -/* . used for the insertion in a set (the Pareto front) */ -/* . we compare f1(x) and f1(y) */ -/*--------------------------------------------------------*/ -bool NOMAD::Pareto_Point::operator < -( const NOMAD::Set_Element & fp ) const -{ - if ( this == &fp || get_element() == fp.get_element() ) - return false; - - int i1 = NOMAD::Multi_Obj_Evaluator::get_i1(); - - return get_element()->get_bb_outputs()[i1].value() < - fp.get_element()->get_bb_outputs()[i1].value(); -} - -/*---------------------------------------------------------------*/ -/* dominance notion: */ -/* . used for the comparison (dominance) of two Pareto points, */ -/* before they are inserted into the Pareto front */ -/*---------------------------------------------------------------*/ -bool NOMAD::Pareto_Point::dominates ( const NOMAD::Pareto_Point & pp ) const -{ - if ( this == &pp || get_element() == pp.get_element() ) - return false; - - int i1 = NOMAD::Multi_Obj_Evaluator::get_i1(); - int i2 = NOMAD::Multi_Obj_Evaluator::get_i2(); - - // we compare F(x)=[f1(x),f2(x)] and F(y)=[f1(y),f2(y)]: - double f1x = get_element()->get_bb_outputs ()[i1].value(); - double f2x = get_element()->get_bb_outputs ()[i2].value(); - double f1y = pp.get_element()->get_bb_outputs()[i1].value(); - double f2y = pp.get_element()->get_bb_outputs()[i2].value(); - - if ( f1x < f1y ) - return f2x <= f2y; - - if ( f1x == f1y ) - return ( f2x < f2y ); - - return false; -} - -/*---------------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------------*/ -void NOMAD::Pareto_Point::display ( const NOMAD::Display & out ) const -{ - const NOMAD::Point & bbo = get_element()->get_bb_outputs(); - int w = 13; - - out << "x=( "; - get_element()->NOMAD::Point::display ( out , " " , w , -1 ); - out << " ) F(x)=[ "; - bbo.Point::display ( out , " " , w , -1 ); - out << " ] [ f1(x) f2(x) ]=[ " - << std::setw(w) << bbo[NOMAD::Multi_Obj_Evaluator::get_i1()] << " " - << std::setw(w) << bbo[NOMAD::Multi_Obj_Evaluator::get_i2()] << " ]"; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Point.hpp deleted file mode 100644 index cdfc87dd9..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Pareto_Point.hpp +++ /dev/null @@ -1,155 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Pareto_Point.hpp - \brief Pareto point (headers) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Pareto_Point.cpp -*/ -#ifndef __PARETO_POINT__ -#define __PARETO_POINT__ - -#include "Multi_Obj_Evaluator.hpp" - -namespace NOMAD { - - /// Pareto point for two objective functions. - class Pareto_Point : public NOMAD::Set_Element { - - private: - - int _w; ///< Weight. - - /// Affectation operator. - /** - \param p The right-hand side object -- \b IN. - */ - Pareto_Point & operator = ( const Pareto_Point & p ); - - public: - - /// Constructor. - /** - \param ep A pointer to an evaluation point -- \b IN. - */ - Pareto_Point ( const NOMAD::Eval_Point * ep ) - : NOMAD::Set_Element ( ep ) , - _w ( 0 ) {} - - /// Copy constructor. - /** - \param pp The copied object -- \b IN. - */ - explicit Pareto_Point ( const Pareto_Point & pp ) - : NOMAD::Set_Element ( pp.get_element() ) , - _w ( 0 ) {} - - /// Destructor. - virtual ~Pareto_Point ( void ) {} - - /// Update the weight. - /** - A more evolved formula than \c ++w is used in order - to avoid stagnation with large number of evaluations. - */ - void update_w ( void ) { _w = 2 * _w + 2; } - - /// Access to the weight. - /** - \return The weight. - */ - int get_w ( void ) const { return _w; } - - /// Access to the value of the first objective function. - /** - \return The value of the first objective function. - */ - const NOMAD::Double & get_f1 ( void ) const - { - return get_element()->get_bb_outputs()[NOMAD::Multi_Obj_Evaluator::get_i1()]; - } - - /// Access to the value of the second objective function. - /** - \return The value of the second objective function. - */ - const NOMAD::Double & get_f2 ( void ) const - { - return get_element()->get_bb_outputs()[NOMAD::Multi_Obj_Evaluator::get_i2()]; - } - - /// Comparison operator. - /** - - Supposes that \c y is a Pareto point. - - Used for the insertion in a set (the Pareto front). - - \c f1(*this) and \c f1(y) are compared. - \param y The right-hand side of the comparison -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c y. - */ - virtual bool operator < ( const NOMAD::Set_Element & y ) const; - - /// Dominance operator. - /** - Used for the comparison (dominance) of two Pareto points - before they are inserted into the Pareto front. - \param y The right-hand side of the comparison -- \b IN. - \return A boolean equal to \c true if \c *this dominates \c y. - */ - bool dominates ( const Pareto_Point & y ) const; - - /// Display the Pareto point. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::Pareto_Point object. - /** - \param out The NOMAD::Display object -- \b IN. - \param pp The NOMAD::Pareto_Point object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Pareto_Point & pp ) - { - pp.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Evaluator.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Evaluator.cpp deleted file mode 100644 index 577cbb2df..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Evaluator.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Phase_One_Evaluator.cpp - \brief NOMAD::Evaluator subclass for the phase one (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Phase_One_Evaluator.hpp - */ -#include "Phase_One_Evaluator.hpp" - -/*------------------------------------------------------------------*/ -/* compute f(x) from the blackbox outputs of a point */ -/* (special objective for MADS phase 1) */ -/*------------------------------------------------------------------*/ -void NOMAD::Phase_One_Evaluator::compute_f ( NOMAD::Eval_Point & x ) const -{ - if ( x.get_bb_outputs().size() != _p.get_bb_nb_outputs() ) - { - std::ostringstream err; - err << "Phase_One_Evaluator::compute_f(x): " - << "x has a wrong number of blackbox outputs (" - << x.get_bb_outputs().size() << " != " << _p.get_bb_nb_outputs() << ")"; - throw NOMAD::Exception ( "Phase_One_Evaluator.cpp" , __LINE__ , err.str() ); - } - - // objective value for MADS phase 1: the squared sum of all EB constraint violations - // (each EB constraint has been previously transformed into OBJ values): - const std::list & index_obj = _p.get_index_obj(); - const std::list::const_iterator end = index_obj.end(); - const NOMAD::Point & bbo = x.get_bb_outputs(); - NOMAD::Double h_min = _p.get_h_min(); - NOMAD::Double sum = 0.0; - NOMAD::Double v; - - for ( std::list::const_iterator it = index_obj.begin() ; it != end ; ++it ) - { - v = bbo[*it]; - if ( v > h_min ) - sum += v.pow2(); - } - - x.set_f ( sum ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Evaluator.hpp deleted file mode 100644 index 2c01b9f00..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Evaluator.hpp +++ /dev/null @@ -1,166 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Phase_One_Evaluator.hpp - \brief NOMAD::Evaluator subclass for the phase one (headers) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Phase_One_Evaluator.cpp - */ -#ifndef __PHASE_ONE_EVALUATOR__ -#define __PHASE_ONE_EVALUATOR__ - -#include "Evaluator.hpp" - -namespace NOMAD { - - /// NOMAD::Evaluator subclass for the phase one. - class Phase_One_Evaluator : public NOMAD::Evaluator { - - private: - - NOMAD::Evaluator & _basic_ev; ///< The original evaluator. - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param ev Original evaluator -- \b IN. - */ - Phase_One_Evaluator ( const NOMAD::Parameters & p , NOMAD::Evaluator & ev ) - : NOMAD::Evaluator ( p ) , - _basic_ev ( ev ) {} - - /// Destructor. - virtual ~Phase_One_Evaluator ( void ) {} - - /// User updates after a success. - /** - This virtual method is called every time a new (full) success is made. - \param s Stats -- \b IN. - \param x Successful point -- \b IN. - */ - virtual void update_success ( const NOMAD::Stats & s , const NOMAD::Eval_Point & x ) - { - _basic_ev.update_success ( s , x ); - } - - /// Evaluate the blackboxes at a given trial point. - /** - \param x The trial point -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const - { - return _basic_ev.eval_x ( x , h_max , count_eval ); - } - - - /// Evaluate the blackboxes at a given list of trial points. - /** - \param list_x The list of trial points -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param list_count_eval Flags indicating if the evaluations have to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( std::list & list_x , - const NOMAD::Double & h_max , - std::list & list_count_eval ) const - { - return _basic_ev.eval_x ( list_x , h_max , list_count_eval ); - } - - - /// User preprocessing of points before evaluations. - /** - This method is called before the evaluation of a list of points. - \param pts List of points to preprocess -- \b IN/OUT. - */ - virtual void list_of_points_preprocessing - ( std::set & pts ) const - { - _basic_ev.list_of_points_preprocessing ( pts ); - } - - - /// Access to the model evaluator flag. - /** - \return The model evaluator flag. - */ - virtual bool is_model_evaluator ( void ) const - { - return _basic_ev.is_model_evaluator(); - } - - /// User updates after an iteration. - /** - This virtual method is called every time a MADS iteration is terminated. - \param success Success of the iteration -- \b IN. - \param stats Stats -- \b IN. - \param ev_control The NOMAD::Evaluator_Control object -- \b IN. - \param true_barrier Barrier for true evaluations -- \b IN. - \param sgte_barrier Barrier for surrogate evaluations -- \b IN. - \param pareto_front Pareto front -- \b IN. - \param stop Allows the user to stop the algorithm -- \b OUT. - */ - virtual void update_iteration ( NOMAD::success_type success , - const NOMAD::Stats & stats , - const NOMAD::Evaluator_Control & ev_control , - const NOMAD::Barrier & true_barrier , - const NOMAD::Barrier & sgte_barrier , - const NOMAD::Pareto_Front & pareto_front , - bool & stop ) {} - - - - /// Objective computation. - /** - - Compute \c f(x) from the blackbox outputs of a point. - - Special objective for MADS phase one. - \param x The trial point -- \b IN/OUT. - */ - virtual void compute_f ( NOMAD::Eval_Point & x ) const; - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Search.cpp deleted file mode 100644 index 1cd2281bf..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Search.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Phase_One_Search.cpp - \brief NOMAD::Search subclass for the phase one (implementation) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Phase_One_Search.hpp - */ -#include "Phase_One_Search.hpp" - -/*-------------------------------------------------------------*/ -/* phase one search */ -/* (try to satisfy EB constraints) */ -/*-------------------------------------------------------------*/ -void NOMAD::Phase_One_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - new_feas_inc = new_infeas_inc = NULL; - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - stop = false; - count_search = true; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - - // initial display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << NOMAD::P1_SEARCH; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - // stats: - NOMAD::Stats & stats = mads.get_stats(); - - // counters: - int old_bbe = stats.get_bb_eval(); - int old_it = stats.get_iterations(); - - // Evaluator_Control: - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // save and modify parameters: - std::string old_display_degree; - _p.out().get_display_degree ( old_display_degree ); - const std::list old_ds = _p.get_display_stats(); - NOMAD::Double old_VNS_trigger = _p.get_VNS_trigger(); - const std::string old_stats_file_name = _p.get_stats_file_name(); - const std::string old_sol_file = _p.get_solution_file(); - const std::list old_stats_file = _p.get_stats_file(); - const NOMAD::Point old_f_target = _p.get_f_target(); - NOMAD::Double old_lct = _p.get_L_curve_target(); - bool old_sif = _p.get_stop_if_feasible(); - const std::vector old_bbot = _p.get_bb_output_type(); - std::vector p1_bbot = old_bbot; - - - if ( display_degree == NOMAD::NORMAL_DISPLAY) // Normal display -> minimal display for Phase one - _p.set_DISPLAY_DEGREE( NOMAD::MINIMAL_DISPLAY); - else if (display_degree == NOMAD::FULL_DISPLAY) - _p.set_DISPLAY_DEGREE( NOMAD::FULL_DISPLAY);// Full display -> full display for Phase one - - - - int m = static_cast ( old_bbot.size() ); - int cnt = 0; - for ( int i = 0 ; i < m ; ++i ) - { - if ( old_bbot[i] == NOMAD::EB ) - { - p1_bbot[i] = NOMAD::OBJ; - ++cnt; - } - else if ( old_bbot[i] == NOMAD::OBJ ) - p1_bbot[i] = NOMAD::UNDEFINED_BBO; - } - - if ( cnt == 0 ) { - stop = true; - stop_reason = NOMAD::P1_FAIL; - return; - } - - _p.set_F_TARGET ( NOMAD::Point ( cnt , 0.0 ) ); - _p.set_L_CURVE_TARGET ( NOMAD::Double() ); - _p.set_STOP_IF_FEASIBLE ( false ); - _p.set_VNS_SEARCH ( false ); - _p.set_BB_OUTPUT_TYPE ( p1_bbot ); - _p.set_SOLUTION_FILE ( "" ); - _p.reset_stats_file(); - - // DISPLAY_STATS and STATS_FILE - { - std::list ds = old_ds; - std::list sf = old_stats_file; - ds.push_back ( " (PhaseOne)" ); - _p.set_DISPLAY_STATS ( ds ); - sf.push_back ( " (PhaseOne)" ); - _p.set_STATS_FILE ( old_stats_file_name , sf ); - - } - - _p.check ( false , // remove_history_file = false - true , // remove_solution_file = true - false ); // remove_stats_file = false - - // modify evaluator: - NOMAD::Evaluator * old_ev = ev_control.get_evaluator(); - NOMAD::Phase_One_Evaluator * p1ev = new NOMAD::Phase_One_Evaluator ( _p , *old_ev ); - ev_control.set_evaluator ( p1ev ); - - // disable the Pareto front: - NOMAD::Pareto_Front * old_pareto_front = mads.get_pareto_front(); - mads.set_pareto_front ( NULL ); - - int old_eval = stats.get_eval(); - - // run MADS with modified parameters: - // ---------------------------------- - - // C. Tribes march 2014 ---- these flags are mads static and must be put back to their original value after running mads (see below) - // get flags: - bool flag_check_bimads , flag_reset_mesh , flag_reset_barriers , flag_p1_active; - NOMAD::Mads::get_flags ( flag_check_bimads , - flag_reset_mesh , - flag_reset_barriers , - flag_p1_active ); - - - // set flags: - NOMAD::Mads::set_flag_check_bimads ( false ); - NOMAD::Mads::set_flag_reset_mesh ( false ); - NOMAD::Mads::set_flag_p1_active ( true ); - NOMAD::Mads::set_flag_reset_barriers ( true ); - - // run: - stop_reason = mads.run(); - - // reset stopping condition: - if ( stop_reason == NOMAD::F_TARGET_REACHED ) - { - - // stop if feasible: - if ( old_sif ) - { - stop = true; - stop_reason = NOMAD::FEAS_REACHED; - } - - // continue: - else { - stop = false; - stop_reason = NOMAD::NO_STOP; - } - } - else - stop = true; - - // reset flags to there previous state : - // C. Tribes march 2014 ---- these flags are mads static and must be put back to their original value after running mads - NOMAD::Mads::set_flag_check_bimads ( flag_check_bimads ); - NOMAD::Mads::set_flag_reset_mesh ( flag_reset_mesh ); - NOMAD::Mads::set_flag_p1_active ( flag_p1_active ); - NOMAD::Mads::set_flag_reset_barriers ( flag_reset_barriers ); - - // NOMAD::Mads::set_flag_check_bimads ( true ); - // NOMAD::Mads::set_flag_reset_mesh ( true ); - // NOMAD::Mads::set_flag_p1_active ( false ); - - // number of search points: - nb_search_pts = stats.get_eval() - old_eval; - - // restore evaluator: - ev_control.set_evaluator ( old_ev ); - delete p1ev; - - // restore the Pareto front: - mads.set_pareto_front ( old_pareto_front ); - - // restore parameters: - _p.set_VNS_SEARCH ( old_VNS_trigger ); - _p.set_F_TARGET ( old_f_target ); - _p.set_L_CURVE_TARGET ( old_lct ); - _p.set_BB_OUTPUT_TYPE ( old_bbot ); - _p.set_DISPLAY_DEGREE ( old_display_degree ); - _p.set_SOLUTION_FILE ( old_sol_file ); - _p.reset_stats_file(); - _p.set_STATS_FILE ( old_stats_file_name , old_stats_file ); - _p.set_DISPLAY_STATS (old_ds); - - _p.check ( false , // remove_history_file = false - true , // remove_solution_file = true - false ); // remove_stats_file = true - - - // counters: - stats.add_p1_iterations ( stats.get_iterations() - old_it ); - stats.add_p1_bbe ( stats.get_bb_eval () - old_bbe ); - - // for the update of new_feas_inc and new_infeas_inc (1/2): - const NOMAD::Barrier & active_barrier = mads.get_active_barrier(); - const NOMAD::Eval_Point * old_feasible_incumbent = NULL; - const NOMAD::Eval_Point * old_infeasible_incumbent = NULL; - old_feasible_incumbent = active_barrier.get_best_feasible(); - old_infeasible_incumbent = active_barrier.get_best_infeasible(); - - // update the barriers and compute the true values - // of f and h for all evaluated points: - NOMAD::Barrier & true_barrier = mads.get_true_barrier(); - NOMAD::Barrier & sgte_barrier = mads.get_sgte_barrier(); - - true_barrier.reset(); - sgte_barrier.reset(); - - // scan the active cache: - const NOMAD::Cache & active_cache = mads.get_cache(); - if ( active_cache.empty() ) - { - stop = true; - stop_reason = NOMAD::P1_FAIL; - return; - } - - const NOMAD::Eval_Point * cur = active_cache.begin(); - while ( cur ) - { - - if ( cur->is_eval_ok() && cur->get_signature() ) - { - - NOMAD::Eval_Point * modifiable_x = &NOMAD::Cache::get_modifiable_point ( *cur ); - - modifiable_x->set_direction ( NULL ); - modifiable_x->set_poll_center_type ( NOMAD::UNDEFINED_POLL_CENTER_TYPE ); - modifiable_x->set_user_eval_priority ( NOMAD::Double() ); - modifiable_x->set_rand_eval_priority ( NOMAD::Double() ); - - old_ev->compute_f ( *modifiable_x ); - old_ev->compute_h ( *modifiable_x ); - - // insertion in barrier: - (( cur->get_eval_type() == NOMAD::TRUTH ) ? true_barrier : sgte_barrier).insert (*cur); - } - - cur = active_cache.next(); - } - - success = active_barrier.get_success(); - - if ( !stop && success == NOMAD::UNSUCCESSFUL ) - { - stop = true; - stop_reason = NOMAD::P1_FAIL; - return; - } - - true_barrier.update_and_reset_success(); - sgte_barrier.update_and_reset_success(); - - // update of new_feas_inc and new_infeas_inc (2/2): - const NOMAD::Eval_Point * bf = active_barrier.get_best_feasible (); - const NOMAD::Eval_Point * bi = active_barrier.get_best_infeasible(); - if ( bf && bf != old_feasible_incumbent ) - new_feas_inc = bf; - if ( bi && bi != old_infeasible_incumbent ) - new_infeas_inc = bi; - - // final displays: - if ( bf && bf->get_current_run() ) - { - - // solution file: - ev_control.write_solution_file ( *bf ); - - // stats_file: - const std::string & stats_file_name = _p.get_stats_file_name(); - if ( !stats_file_name.empty() && display_degree > NOMAD::NO_DISPLAY) - ev_control.stats_file ( stats_file_name , bf , true , NULL ); - - // display_stats - if (display_degree > NOMAD::NO_DISPLAY) - ev_control.display_stats(false, out, old_ds , bf , true , NULL ); - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::close_block ( "end of phase one" ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Search.hpp deleted file mode 100644 index 56776de23..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Phase_One_Search.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Phase_One_Search.hpp - \brief NOMAD::Search subclass for the phase one (headers) - \author Sebastien Le Digabel - \date 2010-04-09 - \see Phase_One_Search.cpp -*/ -#ifndef __PHASE_ONE_SEARCH__ -#define __PHASE_ONE_SEARCH__ - -#include "Search.hpp" -#include "Mads.hpp" - -namespace NOMAD { - - /// NOMAD::Search subclass for the phase one. - /** - - The phase one occurs when no feasible starting point has been given. - - It consists in minimizing the constraint violations and it stops - as soon as a feasible point is found. - */ - class Phase_One_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Phase_One_Search ( NOMAD::Parameters & p ) - : NOMAD::Search ( p , NOMAD::P1_SEARCH ) {} - - /// Destructor. - virtual ~Phase_One_Search ( void ) {} - - /// The phase one search. - /** - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Point.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Point.cpp deleted file mode 100644 index c2efa394b..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Point.cpp +++ /dev/null @@ -1,584 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Point.cpp - \brief Custom class for points (implementation) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Point.hpp - */ -#include "Point.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -#ifdef MEMORY_DEBUG -int NOMAD::Point::_cardinality = 0; -int NOMAD::Point::_max_cardinality = 0; -#endif - -int NOMAD::Point::_display_limit = NOMAD::DEFAULT_POINT_DISPLAY_LIMIT; - -/*-----------------------------------------------------------*/ -/* constructor */ -/*-----------------------------------------------------------*/ -NOMAD::Point::Point ( int n , const NOMAD::Double & d ) : _n (n) , _coords (NULL) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Point::_cardinality; - if ( NOMAD::Point::_cardinality > NOMAD::Point::_max_cardinality ) - ++NOMAD::Point::_max_cardinality; -#endif - if (_n > 0) - { - _coords = new NOMAD::Double [_n]; - if ( d.is_defined() ) - std::fill ( _coords , _coords+_n , d ); - } - else - _n = 0; -} - -/*-----------------------------------------------------------*/ -/* copy constructor */ -/*-----------------------------------------------------------*/ -NOMAD::Point::Point ( const NOMAD::Point & p ) : _n (p._n) , _coords (NULL) -{ -#ifdef MEMORY_DEBUG - ++NOMAD::Point::_cardinality; - if ( NOMAD::Point::_cardinality >= NOMAD::Point::_max_cardinality ) - ++NOMAD::Point::_max_cardinality; -#endif - if ( _n > 0 ) - { - NOMAD::Double * p1 = _coords = new NOMAD::Double [_n]; - const NOMAD::Double * p2 = p._coords; - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 ) - *p1 = *p2; - } -} - -/*-----------------------------------------------*/ -/* destructor */ -/*-----------------------------------------------*/ -NOMAD::Point::~Point ( void ) -{ -#ifdef MEMORY_DEBUG - --NOMAD::Point::_cardinality; -#endif - delete [] _coords; -} - -/*-----------------------------------------------*/ -/* This method changes the point's dimension */ -/* and sets all values to d */ -/*-----------------------------------------------*/ -void NOMAD::Point::reset ( int n , const NOMAD::Double & d ) -{ - if ( n <= 0 ) - { - _n = 0; - delete [] _coords; - _coords = NULL; - } - else - { - if ( _n != n ) - { - delete [] _coords; - _n = n; - _coords = new NOMAD::Double [_n]; - } - if ( d.is_defined() ) - std::fill ( _coords , _coords+_n , d ); - } -} - -/*----------------------------------------------------------------*/ -/* This method changes the array's dimension (and keeps values) */ -/*----------------------------------------------------------------*/ -void NOMAD::Point::resize ( int n ) -{ - if ( n == _n ) - return; - - if ( n <= 0 ) - { - _n = 0; - delete [] _coords; - _coords = NULL; - return; - } - NOMAD::Double * new_coords = new NOMAD::Double [n]; - if ( _coords ) - { - int min = ( n < _n ) ? n : _n; - - NOMAD::Double * p1 = new_coords; - const NOMAD::Double * p2 = _coords; - - for ( int i = 0 ; i < min ; ++i , ++p1 , ++p2 ) - *p1 = *p2; - - delete [] _coords; - } - _coords = new_coords; - _n = n; -} - -/*-----------------------------------------------------------*/ -/* '[]' operators */ -/*-----------------------------------------------------------*/ - -// const version: -const NOMAD::Double & NOMAD::Point::operator [] ( int i ) const -{ - if ( !_coords ) - throw NOMAD::Point::Not_Defined ( "Point.cpp" , __LINE__ , - "operator x[i] (const): 'x' not defined" ); - if ( i < 0 || i >= _n ) - throw NOMAD::Point::Bad_Access ( "Point.cpp" , __LINE__ , - "operator x[i] (const): 'i' outside the array's bounds." ); - return _coords[i]; -} - -// non-const version: -NOMAD::Double & NOMAD::Point::operator [] ( int i ) -{ - if ( !_coords ) - throw NOMAD::Point::Not_Defined ( "Point.cpp" , __LINE__ , - "operator x[i]: 'x' not defined" ); - if ( i < 0 || i >= _n ) - throw NOMAD::Point::Bad_Access ( "Point.cpp" , __LINE__ , - "operator x[i] (const): 'i' outside the array's bounds." ); - return _coords[i]; -} - -/*-----------------------------------------------------------*/ -/* affectation operator */ -/*-----------------------------------------------------------*/ -const NOMAD::Point & NOMAD::Point::operator = ( const NOMAD::Point & p ) -{ - if ( this == &p ) - return *this; - - if ( _n != p._n ) - { - delete [] _coords; - _n = p._n; - if (_n > 0) - _coords = new NOMAD::Double [_n]; - else - _coords = NULL; - } - - NOMAD::Double * p1 = _coords; - const NOMAD::Double * p2 = p._coords; - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 ) - *p1 = *p2; - - return *this; -} - -/*------------------------------------*/ -/* projection to mesh of size delta */ -/* (*this = ref + k * delta) */ -/*------------------------------------*/ -void NOMAD::Point::project_to_mesh ( const NOMAD::Point & ref , - const NOMAD::Point & delta , - const NOMAD::Point & lb , - const NOMAD::Point & ub ) -{ - if ( delta._n != _n || - ref._n != _n || - ( lb._n > 0 && lb._n != _n ) || - ( ub._n > 0 && ub._n != _n ) ) - throw NOMAD::Point::Bad_Operation ( "Point.cpp" , __LINE__ , - "Point::project_to_mesh(): invalid Point sizes" ); - - NOMAD::Double * p = _coords , - * pr = ref._coords , - * pd = delta._coords , - * pl = lb._coords , - * pu = ub._coords; - int k; - - if ( lb._n == 0 && ub._n == 0 ) - for ( k = 0 ; k < _n ; ++k , ++pr , ++p , ++pd ) - p->project_to_mesh ( *pr , *pd ); - else if ( lb._n == 0 ) - for ( k = 0 ; k < _n ; ++k , ++pr , ++p , ++pd , ++pu ) - p->project_to_mesh ( *pr , *pd , NOMAD::Double() , *pu ); - else if ( ub._n == 0 ) - for ( k = 0 ; k < _n ; ++k , ++pr , ++p , ++pd , ++pl ) - p->project_to_mesh ( *pr , *pd , *pl ); - else - for ( k = 0 ; k < _n ; ++k , ++pr , ++p , ++pd , ++pl , ++pu ) - p->project_to_mesh ( *pr , *pd , *pl , *pu ); -} - - -/*-----------------------------------------------------------*/ -/* display */ -/*-----------------------------------------------------------*/ -void NOMAD::Point::display ( const NOMAD::Display & out , - const std::string & sep , - int w , - int lim ) const -{ - int nm1 = _n-1; - - // for a limited display of maximum lim elements: - if ( lim > 0 && lim < _n ) - { - - int l1 = (lim + 1) / 2 , l2 = lim / 2 , i; - - // first coordinates: - for ( i = 0 ; i < l1 ; ++i ) - out << std::setw ( w ) << _coords[i] << sep; - - // separator: - out << "..." << sep; - - // last coordinates: - for ( i = _n - l2 ; i < nm1 ; ++i ) - out << std::setw ( w ) << _coords[i] << sep; - } - - // normal display (lim <= 0 or lim >= _n): - else - { - const NOMAD::Double * p = _coords; - for ( int i = 0 ; i < nm1 ; ++i , ++p ) - out << std::setw ( w ) << *p << sep; - } - - // last coordinate (different because there is no separator after that): - if ( _n > 0 ) - out << std::setw ( w ) << _coords[nm1]; -} - -/*-----------------------------------------------------------*/ -/* input (can read undefined coordinates) */ -/*-----------------------------------------------------------*/ -std::istream & NOMAD::operator >> ( std::istream & in , NOMAD::Point & p ) -{ - int n = p.size(); - for ( int k = 0 ; k < n ; ++k ) - in >> p[k]; - if ( in.fail() ) - throw NOMAD::Point::Bad_Input ( "Point.cpp" , __LINE__ , "in >> x: bad input" ); - return in; -} - -/*-----------------------------------------------------------*/ -/* set the point's coordinate with the array 'a' of size n */ -/* the Point's dimension is changed to n */ -/*-----------------------------------------------------------*/ -void NOMAD::Point::set ( int n , const NOMAD::Double * a ) -{ - if ( n <= 0 || !a ) - return; - - if ( _n != n ) - { - delete [] _coords; - _n = n; - _coords = new NOMAD::Double [_n]; - } - - NOMAD::Double * p = _coords; - for ( int k = 0 ; k < _n ; ++k , ++p , ++a ) - *p = *a; -} - -/*-----------------------------------------------------------*/ -/* check if all the point values are defined */ -/*-----------------------------------------------------------*/ -bool NOMAD::Point::is_complete ( void ) const -{ - if ( _n <= 0 ) - return false; - const NOMAD::Double * p = _coords; - for ( int i = 0 ; i < _n ; ++i , ++p ) - if ( !p->is_defined() ) - return false; - return true; -} - -/*---------------------------------------------------------------*/ -/* check if at least one value is defined in the _coords array */ -/*---------------------------------------------------------------*/ -bool NOMAD::Point::is_defined ( void ) const -{ - if ( _n <= 0 ) - return false; - const NOMAD::Double * p = _coords; - for ( int i = 0 ; i < _n ; ++i , ++p ) - if ( p->is_defined() ) - return true; - return false; -} - -/*---------------------------------------------------------------*/ -/* count the number of values that are defined */ -/*---------------------------------------------------------------*/ -int NOMAD::Point::nb_defined ( void ) const -{ - const NOMAD::Double * p = _coords; - int k = 0; - for ( int i = 0 ; i < _n ; ++i , ++p ) - if ( p->is_defined() ) - ++k; - return k; -} - -/*-----------------------------------------------------------*/ -/* negation */ -/*-----------------------------------------------------------*/ -const NOMAD::Point NOMAD::Point::operator - ( void ) const -{ - NOMAD::Point tmp (_n); - NOMAD::Double * p1 = tmp._coords; - const NOMAD::Double * p2 = _coords; - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 ) - *p1 = - *p2; - return tmp; -} - -/*----------------------------------------------------------*/ -/* scalar multiplication */ -/*----------------------------------------------------------*/ -const NOMAD::Point & NOMAD::Point::operator *= ( const NOMAD::Double & d ) -{ - NOMAD::Double * p = _coords; - for ( int k = 0 ; k < _n ; ++k , ++p ) - *p *= d; - return *this; -} - -/*----------------------------------------------------------*/ -/* multiplication of two points */ -/*----------------------------------------------------------*/ -const NOMAD::Point NOMAD::Point::operator * ( const NOMAD::Point & p ) const -{ - if ( p._n != _n ) - throw NOMAD::Point::Bad_Operation ( "Point.cpp" , __LINE__ , - "x * y: x.size != y.size" ); - NOMAD::Point tmp ( _n ); - NOMAD::Double * p1 = tmp._coords; - const NOMAD::Double * p2 = _coords; - const NOMAD::Double * p3 = p._coords; - - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 , ++p3 ) - *p1 = *p2 * *p3; - - return tmp; -} - -/*----------------------------------------------------------*/ -/* division of two points */ -/*----------------------------------------------------------*/ -const NOMAD::Point NOMAD::Point::operator / ( const NOMAD::Point & p ) const -{ - if ( p._n != _n ) - throw NOMAD::Point::Bad_Operation ( "Point.cpp" , __LINE__ , - "x / y: x.size != y.size" ); - NOMAD::Point tmp ( _n ); - NOMAD::Double * p1 = tmp._coords; - const NOMAD::Double * p2 = _coords; - const NOMAD::Double * p3 = p._coords; - - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 , ++p3 ) - *p1 = *p2 / *p3; - - return tmp; -} - -/*----------------------------------------------------------*/ -/* addition of two points */ -/*----------------------------------------------------------*/ -const NOMAD::Point NOMAD::Point::operator + ( const NOMAD::Point & p ) const -{ - if ( p._n != _n ) - throw NOMAD::Point::Bad_Operation ( "Point.cpp" , __LINE__ , - "x + y: x.size != y.size" ); - NOMAD::Point tmp ( _n ); - NOMAD::Double * p1 = tmp._coords; - const NOMAD::Double * p2 = _coords; - const NOMAD::Double * p3 = p._coords; - - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 , ++p3 ) - *p1 = *p2 + *p3; - - return tmp; -} - -/*----------------------------------------------------------*/ -/* subtraction of two points */ -/*----------------------------------------------------------*/ -const NOMAD::Point NOMAD::Point::operator - ( const NOMAD::Point & p ) const -{ - if ( p._n != _n ) - throw NOMAD::Point::Bad_Operation ( "Point.cpp" , __LINE__ , - "x - y: x.size != y.size" ); - NOMAD::Point tmp ( _n ); - NOMAD::Double * p1 = tmp._coords; - const NOMAD::Double * p2 = _coords; - const NOMAD::Double * p3 = p._coords; - - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 , ++p3 ) - *p1 = *p2 - *p3; - - return tmp; -} - -/*--------------------------------------------------------------------------*/ -/* comparison operator '<': it is used to find and store the points */ -/* in the cache */ -/*--------------------------------------------------------------------------*/ -bool NOMAD::Point::operator < ( const NOMAD::Point & p ) const -{ - if ( this == &p ) - return false; - - if ( _n < p._n ) - return true; - if ( _n > p._n ) - return false; - - const NOMAD::Double * p1 = _coords; - const NOMAD::Double * p2 = p._coords; - - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 ) - { - - if ( *p1 < *p2 ) - return true; - - if ( *p1 > *p2 ) - return false; - } - - return false; -} - -/*---------------------------------------------------------------------*/ -/* the same as operator < but with consideration of undefined values */ -/*---------------------------------------------------------------------*/ -bool NOMAD::Point::comp_with_undef ( const NOMAD::Point & p ) const -{ - if ( this == &p ) - return false; - - if ( _n < p._n ) - return true; - if ( _n > p._n ) - return false; - - const NOMAD::Double * p1 = _coords; - const NOMAD::Double * p2 = p._coords; - - bool p1d , p2d; - - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 ) - { - p1d = p1->is_defined(); - p2d = p2->is_defined(); - - if ( !p1d && !p2d ) - continue; - - if ( !p1d ) - return true; - - if ( !p2d ) - return false; - - if ( *p1 < *p2 ) - return true; - - if ( *p1 > *p2 ) - return false; - } - return false; -} - -/*-----------------------------------------------------------*/ -/* operator == */ -/*-----------------------------------------------------------*/ -bool NOMAD::Point::operator == ( const NOMAD::Point & p ) const -{ - if ( this == &p ) - return true; - if ( p._n != _n ) - return false; - - const NOMAD::Double * p1 = _coords; - const NOMAD::Double * p2 = p._coords; - for ( int k = 0 ; k < _n ; ++k , ++p1 , ++p2 ) - if ( *p1 != *p2 ) - return false; - - return true; -} - -/*-----------------------------------------------------------*/ -/* computation of the angle with another point */ -/*-----------------------------------------------------------*/ -const NOMAD::Double NOMAD::Point::get_angle ( const NOMAD::Point & x ) const -{ - if ( _n != x._n ) - return NOMAD::Double(); - - NOMAD::Double inner_product = 0.0 , norm_1 = 0.0 , norm_2 = 0.0; - - const NOMAD::Double * p1 = _coords; - const NOMAD::Double * p2 = x._coords; - - for ( int i = 0 ; i < _n ; ++i , ++p1 , ++p2 ) - { - norm_1 += *p1 * *p1; - norm_2 += *p2 * *p2; - inner_product += *p1 * *p2; - } - - if ( norm_1 == 0.0 || norm_2 == 0.0 ) - return NOMAD::Double(); - - return acos ( ( inner_product / ( norm_1.sqrt() * norm_2.sqrt() ) ).value() ); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Point.hpp deleted file mode 100644 index e20de9ce9..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Point.hpp +++ /dev/null @@ -1,464 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Point.hpp - \brief Custom class for points (headers) - \author Sebastien Le Digabel - \date 2010-04-05 - \see Point.cpp -*/ -#ifndef __POINT__ -#define __POINT__ - -#include -#include -#include "Double.hpp" - -namespace NOMAD { - - /// \c accumulate operator for \c squared_norm(). - struct squared_norm_op { - /** This function returns \c d1+d2^2 and is designed as an - \c accumulate operator. - \param d1 The NOMAD::Double \c d1 -- \b IN. - \param d2 The NOMAD::Double \c d2 -- \b IN. - \return A third NOMAD::Double equal to \c d1+d2^2. - */ - NOMAD::Double operator () ( const NOMAD::Double & d1 , const NOMAD::Double & d2 ) { - return d1 + d2.pow2(); - } - }; - - /// \c accumulate operator for \c size_of(). - struct size_of_op { - /** This function returns \c i+size_of(d) and is designed as an - \c accumulate operator. - \param i The integer \c i -- \b IN. - \param d The NOMAD::Double \c d -- \b IN. - \return An integer equal to \c i+size_of(d). - */ - int operator () ( int i , const NOMAD::Double & d ) { - return i + d.size_of(); - } - }; - - /// Custom class for points. - /** - Coordinates are NOMAD::Double objects. - */ - class Point { - - private: - -#ifdef MEMORY_DEBUG - static int _cardinality; ///< Number of NOMAD::Point objects in memory. - static int _max_cardinality; ///< Max number of NOMAD::Point objects in memory. -#endif - - /** - Max number of coordinates to display. - Default to 20, debug value at -1 (no limit). - */ - static int _display_limit; - - int _n; ///< Dimension of the point. - NOMAD::Double * _coords; ///< Coordinates of the point. - - public: - - /*-------------------------------------------------------------------*/ - - /// Exception class for a bad access with NOMAD::Point objects. - class Bad_Access : public NOMAD::Exception { - public: - /// Constructor. - Bad_Access ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /// Exception class for NOMAD::Point objects that are not defined. - class Not_Defined : public NOMAD::Exception { - public: - /// Constructor. - Not_Defined ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /// Exception class for input errors with NOMAD::Point objects. - class Bad_Input : public NOMAD::Exception { - public: - /// Constructor. - Bad_Input ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /// Exception class for bad operations with NOMAD::Point objects. - class Bad_Operation : public NOMAD::Exception { - public: - /// Constructor. - Bad_Operation ( const std::string & file , - int line , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) {} - }; - - /*-------------------------------------------------------------------*/ - -#ifdef MEMORY_DEBUG - /// Access to the number of NOMAD::Point objects in memory. - /** - \return The number of NOMAD::Point objects in memory. - */ - static int get_cardinality ( void ) { return Point::_cardinality; } - - /// Access to the max number of NOMAD::Point objects in memory. - /** - \return The max number of NOMAD::Point objects in memory. - */ - static int get_max_cardinality ( void ) { return Point::_max_cardinality; } -#endif - - /// Constructor. - /** - \param n Dimension of the point -- \b IN --\b optional (default = 0). - \param d Initial value for all coordinates - -- \b IN -- \b optional (default = undefined real). - */ - explicit Point ( int n = 0 , const NOMAD::Double & d = NOMAD::Double() ); - - /// Copy constructor. - /** - \param p The copied object -- \b IN. - */ - Point ( const Point & p ); - - /// Affectation operator. - /** - \param p The right-hand side object -- \b IN. - \return \c *this as the result of the affectation. - */ - const Point & operator = ( const Point & p ); - - /// Destructor. - virtual ~Point ( void ); - - /// Change the NOMAD::Point dimension. - /** - Sets also all coordinates to d. - \param n New dimension -- \b IN --\b optional (default = 0). - \param d Initial value for all coordinates - -- \b IN -- \b optional (default = undefined real). - */ - void reset ( int n = 0 , const NOMAD::Double & d = NOMAD::Double() ); - - /// Clear the point. - virtual void clear ( void ) { reset(); } - - /// Change the NOMAD::Point dimension. - /** - The values are kept. - \param n New dimension of the point -- \b IN. - */ - void resize ( int n ); - - /// Set a new display limit. - /** - \param dl An integer for the new display limit -- \b IN. - */ - static void set_display_limit ( int dl ) { Point::_display_limit = dl; } - - /// Access to the display limit. - /** - \return The display limit. - */ - static int get_display_limit ( void ) { return Point::_display_limit; } - - /// Const operator \c []. - /** - \param i The index (0 for the first element) -- \b IN. - \return The \c (i+1)th coordinate. - */ - const NOMAD::Double & operator [] ( int i ) const; - - /// Non-const operator \c []. - /** - \param i The index (0 for the first element) -- \b IN. - \return The \c (i+1)th coordinate. - */ - NOMAD::Double & operator [] ( int i ); - - /// Size of the point in memory. - /** - \return An integer for the size of the point in bytes. - */ - virtual int size_of ( void ) const - { - return std::accumulate ( _coords , - _coords+_n , - static_cast(sizeof(_n)) , - size_of_op() ); - } - - /// Access to the dimension of the point. - /** - \return The dimension of the point. - */ - int size ( void ) const { return _n; } - - /// Test if the point is empty (dimension equal to zero). - /** - \return A boolean equal to \c true if the point is empty. - */ - bool empty ( void ) const { return _n==0; } - - /// Set all the coordinates to a specifi value. - /** - \param d The value for all coordinates -- \b IN. - */ - void set ( const NOMAD::Double & d ) const - { std::fill ( _coords , _coords+_n , d ); } - - /// Set the coordinates with an array of reals. - /** - \param n Dimension of the point -- \b IN. - \param a Array of size \c n of reals -- \b IN. - */ - void set ( int n , const NOMAD::Double * a ); - - /// Check if all the coordinates are defined. - /** - \return A boolean equal to \c true if all the coordinates are defined. - */ - bool is_complete ( void ) const; - - /// Check if at least one coordinate is defined. - /** - This virtual method is redefined in class NOMAD::Direction. - \return A boolean equal to \c true if at least one coordinate is defined. - */ - virtual bool is_defined ( void ) const; - - /// Count the number of defined values. - /** - \return The number of values that are defined. - */ - int nb_defined ( void ) const; - - /// Squared norm of the point. - /** - \return A NOMAD::Double with the squared norm of the point. - */ - const NOMAD::Double squared_norm ( void ) const - { - return std::accumulate ( _coords , - _coords+_n , - NOMAD::Double(0.0) , - squared_norm_op() ); - } - - /// Norm of the point. - /** - \return A NOMAD::Double with the norm of the point. - */ - const NOMAD::Double norm ( void ) const { return squared_norm().sqrt(); } - - /// Dot product with another point \c x. - /** - \param x The other point \c x -- \b IN. - \return The dot product \c *this \c . \c x. - */ - const NOMAD::Double dot_product ( const Point & x ) const - { return std::inner_product ( _coords , _coords+_n , x._coords , NOMAD::Double(0.0) ); } - - /// Angle with another point \c x. - /** - \param x The other point \c x -- \b IN. - \return The angle between \c *this and \c x. - */ - const NOMAD::Double get_angle ( const Point & x ) const; - - /// Mutiplication with a scalar. - /** - - This implements \c *this \c = \c d \c * \c *this. - - The current object \c *this is modified. - \param d The scalar -- \b IN. - \return The point times \c d. - */ - const Point & operator *= ( const NOMAD::Double & d ); - - /// Multiplication with another point. - /** - - The multiplication is done coordinate by coordinate. - - The current object \c *this is not modified. - \param p The other point -- \b IN. - \return A third point equal to \c *this \c .* \c p. - */ - const Point operator * ( const Point & p ) const; - - /// Division with another point. - /** - - The division is done coordinate by coordinate. - - The current object \c *this is not modified. - \param p The other point -- \b IN. - \return A third point equal to \c *this \c ./ \c p. - */ - const Point operator / ( const Point & p ) const; - - /// Addition with another point. - /** - The current object \c *this is not modified. - \param p The other point -- \b IN. - \return A third point equal to \c *this \c + \c p. - */ - const Point operator + ( const Point & p ) const; - - /// Substraction with another point. - /** - The current object \c *this is not modified. - \param p The other point -- \b IN. - \return A third point equal to \c *this \c - \c p. - */ - const Point operator - ( const Point & p ) const; - - /// Negation. - /** - The current object \c *this is not modified. - \return A new point equal to \c -*this. - */ - const Point operator - ( void ) const; - - /// Comparison operator \c <. - /** - \param p The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c p. - */ - virtual bool operator < ( const Point & p ) const; - - - /// Comparison operator \c ==. - /** - \param p The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c == \c p. - */ - bool operator == ( const Point & p ) const; - - /// Comparison operator \c !=. - /** - \param p The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c != \c p. - */ - bool operator != ( const Point & p ) const { return !(*this == p); } - - /// The same as operator \c < but with consideration of undefined values. - /** - \param p The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c p. - */ - bool comp_with_undef ( const Point & p ) const; - - /// Projection to the mesh. - /** - Projection to the mesh of size delta - ( \c *this \c = \c ref \c + \c k \c * \c delta ). - \param ref Reference for projection -- \b IN. - \param delta Mesh size parameter -- \b IN. - \param lb Lower bound -- \b IN -- \b optional - (default = undefined NOMAD::Point). - \param ub Upper bound -- \b IN -- \b optional - (default = undefined NOMAD::Point). - */ - void project_to_mesh ( const Point & ref , - const Point & delta , - const Point & lb = Point() , - const Point & ub = Point() ); - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - \param sep A string that is used as a separator between the coordinates - -- \b IN --\b optional (default = one space). - \param w An integer indicating a width for the display of - each coordinate -- \b IN -- \b optional - (default = -1, no limit). - \param lim Max number of coordinates to display -- \b IN - -- \b optional (default = -1, no limit). - */ - virtual void display ( const NOMAD::Display & out , - const std::string & sep = " " , - int w = -1 , - int lim = -1 ) const; - - }; - - /*---------------------------------------------------------------------------*/ - - /// Display a NOMAD::Point object. - /** - \param out The NOMAD::Display object -- \b IN. - \param p The NOMAD::Point object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Point & p ) { - p.display ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - return out; - } - - /// Input. - /** - - Allows the input of NOMAD::Double objects with operator \c >>. - - Can read undefined coordinates (parameter \c UNDEF_STR with default \c "-".) - - Example: - \code - NOMAD::Point x(3); - std::cout << "Enter x (3 coordinates): "; - std::cin >> x; - std::cout << "x is equal to " << x << std::endl; - \endcode - \param in A \c std::istream object (can be a file) -- \b IN/OUT. - \param p The NOMAD::Point object to be read -- \b OUT. - \return The modified \c std::istream object. - */ - std::istream & operator >> ( std::istream & in , Point & p ); -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Priority_Eval_Point.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Priority_Eval_Point.cpp deleted file mode 100644 index 636b58ecc..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Priority_Eval_Point.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Priority_Eval_Point.cpp - \brief Evaluation point with a priority (implementation) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Priority_Eval_Point.hpp -*/ -#include "Priority_Eval_Point.hpp" - -bool NOMAD::Priority_Eval_Point::_lexicographic_order=false; - -/*------------------------------------------------*/ -/* comparison operator */ -/*------------------------------------------------*/ -/* . x1.dominates(x2) returns true if x1 should */ -/* be evaluated before x2 */ -/* . x is a Priority_Eval_Point */ -/*------------------------------------------------*/ -bool NOMAD::Priority_Eval_Point::dominates -( const NOMAD::Set_Element & x ) const -{ - if ( this == &x ) - return false; - const NOMAD::Eval_Point * x1 = get_element(); - const NOMAD::Eval_Point * x2 = x.get_element(); - - // criterion 0: lexicographic order - if (_lexicographic_order) - return NOMAD::Point(*x1) < NOMAD::Point(*x2); - - - // criterion 1: user criterion: - // ------------ - const NOMAD::Double uep1 = x1->get_user_eval_priority(); - if ( uep1.is_defined() ) - { - const NOMAD::Double uep2 = x2->get_user_eval_priority(); - if ( uep2.is_defined() ) - { - if ( uep1 > uep2 ) - return true; - if ( uep2 > uep1 ) - return false; - } - } - - // specific Priority_Eval_Point elements of comparison: - NOMAD::Double x_f_sgte; - NOMAD::Double x_h_sgte; - NOMAD::Double x_f_model; - NOMAD::Double x_h_model; - NOMAD::Double x_angle_success_dir; - NOMAD::Double x_angle_simplex_grad; - - x.get_priority_criteria ( x_f_sgte , - x_h_sgte , - x_f_model , - x_h_model , - x_angle_success_dir , - x_angle_simplex_grad ); - - // criterion 2: give priority to already evaluated cache points: - // ------------ - if ( x1->is_in_cache() && !x2->is_in_cache() ) - return true; - if ( x2->is_in_cache() && !x1->is_in_cache() ) - return false; - - // criterion 3: give priority to already evaluated points - // ------------ that are eval_ok: - if ( x1->is_eval_ok() && !x2->is_eval_ok() ) - return true; - if ( x2->is_eval_ok() && !x1->is_eval_ok() ) - return false; - - // criterion 4: true f and h values: - // ----------- - int flag = compare_hf_values ( x1->get_h() , - x1->get_f() , - x2->get_h() , - x2->get_f() ); - if ( flag ) - return ( flag > 0 ); - - // criterion 5: surrogate f and h values: - // ------------ - flag = compare_hf_values ( _h_sgte , _f_sgte , x_h_sgte , x_f_sgte ); - if ( flag ) - return ( flag > 0 ); - - // criterion 6: model f and h values: - // ------------ - flag = compare_hf_values ( _h_model , _f_model , x_h_model , x_f_model ); - if ( flag ) - return ( flag > 0 ); - - - - // criterion 7: check the angle with the last successful direction: - // ------------ - if ( _angle_success_dir.is_defined() && x_angle_success_dir.is_defined() ) - { - if ( _angle_success_dir < x_angle_success_dir ) - return true; - if ( x_angle_success_dir < _angle_success_dir ) - return false; - } - - - // criterion 8: take the point with the best h value: - // ------------ - flag = compare_h_values ( x1->get_h() , x2->get_h() ); - if ( flag ) - return ( flag > 0 ); - - flag = compare_h_values ( _h_sgte , x_h_sgte ); - if ( flag ) - return ( flag > 0 ); - - flag = compare_h_values ( _h_model , x_h_model ); - if ( flag ) - return ( flag > 0 ); - - // criterion 9: random criterion for randomly generated directions: - // ------------- - const NOMAD::Double rep1 = x1->get_rand_eval_priority(); - if ( rep1.is_defined() ) - { - const NOMAD::Double rep2 = x2->get_rand_eval_priority(); - if ( rep2.is_defined() ) - { - if ( rep1 < rep2 ) - return true; - if ( rep2 < rep1 ) - return false; - } - } - - // criterion 10: compare the tags: - // ------------- - return x1->get_tag() < x2->get_tag(); - -} - -/*-----------------------------------------------*/ -/* compare the h values of two points */ -/*-----------------------------------------------*/ -/* . return h(x1) < h(x2) with the format: */ -/* 1 : x1 better than x2 */ -/* -1 : x2 better than x1 */ -/* 0 : undetermined */ -/* . private method */ -/*-----------------------------------------------*/ -int NOMAD::Priority_Eval_Point::compare_h_values ( const NOMAD::Double & hx1 , - const NOMAD::Double & hx2 ) const -{ - if ( hx1.is_defined() && hx2.is_defined() ) - { - if ( hx1 < hx2 ) - return 1; - if ( hx2 < hx1 ) - return -1; - } - return 0; -} - -/*-----------------------------------------------*/ -/* compare the h and f values of two points */ -/*-----------------------------------------------*/ -/* . return ( h(x1),f(x1) ) < ( h(x2),f(x2) ) */ -/* with the following format: */ -/* 1 : x1 better than x2 */ -/* -1 : x2 better than x1 */ -/* 0 : undetermined */ -/* . private method */ -/*-----------------------------------------------*/ -int NOMAD::Priority_Eval_Point::compare_hf_values ( const NOMAD::Double & hx1 , - const NOMAD::Double & fx1 , - const NOMAD::Double & hx2 , - const NOMAD::Double & fx2 ) const -{ - if ( fx1.is_defined() && fx2.is_defined() ) - { - - if ( hx1.is_defined() && hx2.is_defined() ) - { - // x1 is feasible: - if ( hx1 <= _h_min ) - { - // both points are feasible: - if ( hx2 <= _h_min ) - { - if ( fx1 < fx2 ) - return 1; - if ( fx2 < fx1 ) - return -1; - } - - // x1 feasible and x2 infeasible: - else - return 1; - } - - // x1 is infeasible: - else - { - // x2 is feasible: - if ( hx2 <= _h_min ) - return -1; - - // both points are infeasible: - if ( ( hx1 < hx2 && fx1 < fx2 ) || - ( hx1 == hx2 && fx1 < fx2 ) || - ( hx1 < hx2 && fx1 == fx2 ) ) - return 1; - - if ( ( hx2 < hx1 && fx2 < fx1 ) || - ( hx2 == hx1 && fx2 < fx1 ) || - ( hx2 < hx1 && fx2 == fx1 ) ) - return -1; - } - } - - // we only have f values: - else - { - if ( fx1 < fx2 ) - return 1; - if ( fx2 < fx1 ) - return -1; - } - } - return 0; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Priority_Eval_Point.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Priority_Eval_Point.hpp deleted file mode 100644 index bebb29a14..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Priority_Eval_Point.hpp +++ /dev/null @@ -1,227 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Priority_Eval_Point.hpp - \brief Evaluation point with a priority (headers) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Priority_Eval_Point.cpp -*/ -#ifndef __PRIORITY_EVAL_POINT__ -#define __PRIORITY_EVAL_POINT__ - -#include "Set_Element.hpp" -#include "Eval_Point.hpp" - -namespace NOMAD { - - /// Evaluation point with a priority. - class Priority_Eval_Point : public NOMAD::Set_Element { - - private: - - NOMAD::Double _h_min; ///< \c h_min value for comparison operator. - NOMAD::Double _f_sgte; ///< Objective surrogate value. - NOMAD::Double _h_sgte; ///< Feasibility surrogate value. - NOMAD::Double _f_model; ///< Objective model value. - NOMAD::Double _h_model; ///< Feasibility model value. - NOMAD::Double _angle_success_dir; ///< Angle with last successful direction. - NOMAD::Double _angle_simplex_grad; ///< Angle with simplex gradient. - static bool _lexicographic_order; ///< Use lexicographic order for comparison - - /// Affectation operator. - /** - \param x The right-hand side object -- \b IN. - */ - Priority_Eval_Point & operator = ( const Priority_Eval_Point & x ); - - /// Compare the \c h values of two points. - /** - The two points to compare are \c x1 and \c x2. - \param hx1 \c h(x1) -- \b IN. - \param hx2 \c h(x2) -- \b IN. - \return \c h(x1) \c < \c h(x2) - with the following format: - - 1: \c x1 best than \c x2. - - -1: \c x2 best than \c x1. - - 0: undetermined. - */ - int compare_h_values ( const NOMAD::Double & hx1 , - const NOMAD::Double & hx2 ) const; - - /// Compare the \c h and \c f values of two points. - /** - The two points to compare are \c x1 and \c x2. - \param hx1 \c h(x1) -- \b IN. - \param fx1 \c f(x1) -- \b IN. - \param hx2 \c h(x2) -- \b IN. - \param fx2 \c f(x2) -- \b IN. - \return \c (h(x1),f(x1)) \c < \c (h(x2),f(x2)) - with the following format: - - 1: \c x1 best than \c x2. - - -1: \c x2 best than \c x1. - - 0: undetermined. - */ - int compare_hf_values ( const NOMAD::Double & hx1 , - const NOMAD::Double & fx1 , - const NOMAD::Double & hx2 , - const NOMAD::Double & fx2 ) const; - public: - - /// Constructor. - /** - \param x A pointer to the evaluation point -- \b IN. - \param h_min \c h_min value -- \b IN. - */ - explicit Priority_Eval_Point ( const NOMAD::Eval_Point * x , - const NOMAD::Double & h_min ) - : NOMAD::Set_Element ( x ) , - _h_min ( h_min ) {} - - /// Copy constructor. - /** - \param pep The copied object -- \b IN. - */ - explicit Priority_Eval_Point ( const Priority_Eval_Point & pep ) - : NOMAD::Set_Element ( pep.get_element() ) , - _h_min ( pep._h_min ) , - _f_sgte ( pep._f_sgte ) , - _h_sgte ( pep._h_sgte ) , - _f_model ( pep._f_model ) , - _h_model ( pep._h_model ) , - _angle_success_dir ( pep._angle_success_dir ) , - _angle_simplex_grad ( pep._angle_simplex_grad ) {} - - /// Destructor. - virtual ~Priority_Eval_Point ( void ) {} - - /// Access to specific elements of comparison. - /** - - This method is defined virtual in NOMAD::Set_Element so that - \c operator \c < \c (Set_Element x) can invoke - it on \c x (which is in fact a \c Priority_Eval_Point). - - This avoids an expensive downcast in \c operator \c < . - \param f_sgte Objective surrogate value -- \b OUT. - \param h_sgte Feasibility surrogate value -- \b OUT. - \param f_model Objective model value -- \b OUT. - \param h_model Feasibility model value -- \b OUT. - \param angle_success_dir Angle with last successful direction -- \b OUT. - \param angle_simplex_grad Angle with simplex gradient -- \b OUT. - */ - virtual void get_priority_criteria ( NOMAD::Double & f_sgte , - NOMAD::Double & h_sgte , - NOMAD::Double & f_model , - NOMAD::Double & h_model , - NOMAD::Double & angle_success_dir , - NOMAD::Double & angle_simplex_grad ) const - { - f_sgte = _f_sgte; - h_sgte = _h_sgte; - f_model = _f_model; - h_model = _h_model; - angle_success_dir = _angle_success_dir; - angle_simplex_grad = _angle_simplex_grad; - } - - /// Comparison operator. - /** - This virtual function directly call \c dominates(). - \param x The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c x. - */ - virtual bool operator < ( const NOMAD::Set_Element & x ) const - { return dominates ( x ); } - - /// Comparison operator. - /** - \param x The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c x. - */ - bool dominates ( const NOMAD::Set_Element & x ) const; - - /// Access to the evaluation point. - /** - \return A pointer to the evaluation point. - */ - const NOMAD::Eval_Point * get_point ( void ) const { return get_element(); } - - /// Set the angle with last successful direction. - /** - \param a The angle with last successful direction -- \b IN. - */ - void set_angle_success_dir ( const NOMAD::Double & a ) { _angle_success_dir = a; } - - /// Set the angle with simplex gradient . - /** - \param a The angle with simplex gradient -- \b IN. - */ - void set_angle_simplex_grad ( const NOMAD::Double & a ) { _angle_simplex_grad = a; } - - - /// Set the objective surrogate value. - /** - \param f The objective surrogate value -- \b IN. - */ - void set_f_sgte ( const NOMAD::Double & f ) { _f_sgte = f; } - - /// Set the feasibility surrogate value. - /** - \param h The feasibility surrogate value -- \b IN. - */ - void set_h_sgte ( const NOMAD::Double & h ) { _h_sgte = h; } - - /// Set the objective model value. - /** - \param f The objective model value -- \b IN. - */ - void set_f_model ( const NOMAD::Double & f ) { _f_model = f; } - - /// Set the feasibility model value. - /** - \param h The feasibility model value -- \b IN. - */ - void set_h_model ( const NOMAD::Double & h ) { _h_model = h; } - - /// Set the lexicographic order for sorting. - /** - */ - static void set_lexicographic_order ( bool order ) { _lexicographic_order = order; } - - - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model.cpp deleted file mode 100644 index 2cf04cd94..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model.cpp +++ /dev/null @@ -1,2052 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Quad_Model.cpp - \brief Quadratic regression or MFN interpolation model (implementation) - \author Sebastien Le Digabel - \date 2010-08-31 - \see Quad_Model.hpp - */ -#include "Quad_Model.hpp" - -/*-----------------------------------------------------------*/ -/* constructor */ -/*-----------------------------------------------------------*/ -NOMAD::Quad_Model::Quad_Model -( const NOMAD::Display & out , - const std::vector & bbot , - const NOMAD::Cache & cache , - const NOMAD::Signature & signature ) -: _out ( out ) , -_bbot ( bbot ) , -_interpolation_type ( NOMAD::UNDEFINED_INTERPOLATION_TYPE ) , -_n ( signature.get_n() ) , -_nfree ( _n ) , -_fixed_vars ( new bool [_n] ) , -_index ( NULL ) , -_alpha ( NULL ) , -_cache ( cache ) , -_signature ( signature ) , -_error_flag ( true ) -{ - for ( int i = 0 ; i < _n ; ++i ) - _fixed_vars[i] = false; - init_alpha(); -} - -/*-----------------------------------------------------------*/ -/* destructor */ -/*-----------------------------------------------------------*/ -NOMAD::Quad_Model::~Quad_Model ( void ) -{ - int m = static_cast ( _bbot.size() ); - for ( int i = 0 ; i < m ; ++i ) - delete _alpha[i]; - delete [] _alpha; - delete [] _fixed_vars; - delete [] _index; - - // clear the interpolation set Y: - for ( size_t k = 0 ; k < _Y.size() ; ++k ) - delete _Y[k]; -} - -/*-----------------------------------------------------------*/ -/* initialize alpha, the model parameters (private) */ -/*-----------------------------------------------------------*/ -void NOMAD::Quad_Model::init_alpha ( void ) -{ - _n_alpha = ( _nfree + 1 ) * ( _nfree + 2 ) / 2; - - int i , m = static_cast ( _bbot.size() ); - - // initialize _alpha: - // ------------------ - if ( _alpha ) - { - for ( i = 0 ; i < m ; ++i ) - delete _alpha[i]; - delete [] _alpha; - } - - _alpha = new NOMAD::Point * [m]; - - for ( i = 0 ; i < m ; ++i ) - _alpha[i] = ( _bbot[i] == NOMAD::OBJ || NOMAD::bbot_is_constraint(_bbot[i]) ) ? - new NOMAD::Point ( _n_alpha ) : NULL; - - // initialize _index: - // ------------------ - - // example: with 3 variables (X,Y,Z) with Y fixed. - // -------- - // the problem is reduced to the two variables x=X and y=Z, - // and _index is corresponds to: - // - // 0 1 0 1 : index[0] = 0 - // 1 X 1 x : index[1] = 1 - // 2 Y 2 y : index[2] = 3 - // 3 Z 3 .5 x^2 : index[3] = 4 - // 4 .5 X^2 4 .5 y^2 : index[4] = 6 - // 5 .5 Y^2 5 xy : index[5] = 8 - // 6 .5 Z^2 - // 7 XY - // 8 XZ - // 9 YZ - // - // If there are no fixed variables, index is of size (n+1)(n+2)/2 - // with index[i] = i. - - delete [] _index; - - _index = new int [_n_alpha]; - - int nm1 = _n - 1; - int c1 = 2*_n + 1; - int c2 = 1; - int k1 , k2; - - _index[0] = 0; - for ( i = 0 ; i < _n ; ++i ) - { - if ( !_fixed_vars[i] ) - { - _index[c2 ] = i+1; - _index[c2+_nfree] = i+1+_n; - ++c2; - } - } - - c2 += _nfree; - - for ( k1 = 0 ; k1 < nm1 ; ++k1 ) - for ( k2 = k1+1 ; k2 < _n ; ++k2 ) - { - if ( !_fixed_vars[k1] && !_fixed_vars[k2] ) - _index[c2++] = c1; - ++c1; - } -} - -/*---------------------------------------------------------*/ -/* check evaluation point outputs before the integration */ -/* into an interpolation set (private) */ -/*---------------------------------------------------------*/ -bool NOMAD::Quad_Model::check_outputs ( const NOMAD::Point & bbo , int m ) const { - - if ( bbo.size() != m ) - return false; - - for ( int i = 0 ; i < m ; ++i ) - if ( !bbo[i].is_defined() || bbo[i].value() > NOMAD::MODEL_MAX_OUTPUT ) - return false; - - return true; -} - -/*-----------------------------------------------------------*/ -/* construct the interpolation set Y */ -/*-----------------------------------------------------------*/ -void NOMAD::Quad_Model::construct_Y ( const NOMAD::Point & center , - const NOMAD::Point & interpolation_radius , - int max_Y_size ) -{ - _error_flag = true; - - if ( center.size() != _n || - interpolation_radius.size() != _n || - !center.is_complete() || - !interpolation_radius.is_complete() ) - return; - - _error_flag = false; - _center = center; - - int m = static_cast ( _bbot.size() ); - - // browse the cache: - const NOMAD::Eval_Point * cur = _cache.begin(); - while ( cur ) - { - - if ( cur->get_eval_status() == NOMAD::EVAL_OK && - cur->get_n () == _n && - _signature.is_compatible (*cur) ) - { - - const NOMAD::Point & bbo = cur->get_bb_outputs(); - - if ( check_outputs ( bbo , m ) ) - { - - // the center point has been found - // (it is put in first position): - if ( _center == *cur ) - { - _Y.push_back ( new NOMAD::Eval_Point ( *cur ) ); - int nYm1 = get_nY() - 1; - if ( nYm1 > 0 ) - { - NOMAD::Eval_Point * tmp = _Y[0]; - _Y[0 ] = _Y[nYm1]; - _Y[nYm1] = tmp; - } - } - - // other points must within the interpolation radius: - else if ( is_within_radius ( *cur , interpolation_radius ) ) - { - _Y.push_back ( new NOMAD::Eval_Point ( *cur ) ); - } - } - } - cur = _cache.next(); - } - - // respect the limit on the number of points: - if ( get_nY() > max_Y_size ) - reduce_Y ( center , max_Y_size ); -} - -/*-----------------------------------------------------------------*/ -/* reduce the number of interpolation points */ -/*-----------------------------------------------------------------*/ -void NOMAD::Quad_Model::reduce_Y ( const NOMAD::Point & center , - int max_Y_size ) -{ - int nY = get_nY(); - - if ( nY <= max_Y_size ) - return; - - std::multiset Ys; - for ( int k = 0 ; k < nY ; ++k ) - Ys.insert ( NOMAD::Model_Sorted_Point ( _Y[k] , center ) ); - - _Y.clear(); - - std::multiset::const_iterator it , end = Ys.end(); - for ( it = Ys.begin() ; it != end ; ++it ) { - if ( get_nY() < max_Y_size ) - _Y.push_back ( static_cast ( it->get_point() ) ); - else - delete it->get_point(); - } -} - -/*-----------------------------------------------------------*/ -/* check if an unscaled point is in B(center,radius) for a */ -/* given radius (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::Quad_Model::is_within_radius ( const NOMAD::Point & x , - const NOMAD::Point & radius ) const -{ - if ( x.size() != _n || radius.size() != _n ) - return false; - - for ( int i = 0 ; i < _n ; ++i ) - { - if ( !x[i].is_defined() || - !radius[i].is_defined() || - radius[i] < ( x[i] - _center[i]).abs() ) - return false; - } - return true; -} - -/*------------------------------------------------------*/ -/* check if a scaled point is inside the trust radius */ -/*------------------------------------------------------*/ -bool NOMAD::Quad_Model::is_within_trust_radius ( const NOMAD::Point & x ) const -{ - // check that all scaled coordinates are in [-1;1] and - // that fixed variables are equal to zero: - for ( int i = 0 ; i < _n ; ++i ) - if ( !_ref [i].is_defined() || - !_scaling[i].is_defined() || - ! x[i].is_defined() || - x[i].abs() > 1.0 || - ( _fixed_vars[i] && x[i] != 0.0 ) ) - return false; - return true; -} - -/*--------------------------------------------------------------*/ -/* . define scaling to put all coordinates centered in [-r;r] */ -/* . looks also for fixed variables */ -/*--------------------------------------------------------------*/ -void NOMAD::Quad_Model::define_scaling ( const NOMAD::Double & r ) -{ - if ( _error_flag || _Y.empty() ) { - _error_flag = true; - return; - } - - int i , k; - int nY = get_nY(); - NOMAD::Point min(_n) , max(_n); - NOMAD::Double tmp; - - // The parameters defining the scaling with rotation (see define_scaling_by_direction) are cleared. - // Only the parameters for the basic scaling are set - _dirP.clear(); - _epsilon.clear(); - _delta_m.clear(); - - - _scaling.clear(); - _ref.clear (); - _ref.reset ( _n ); - _scaling.reset ( _n ); - - // compute the reference (center of Y): - for ( k = 0 ; k < nY ; ++k ) - { - - if ( !_Y[k] || _n != _Y[k]->size() ) - { - _error_flag = true; - return; - } - - for ( i = 0 ; i < _n ; ++i ) - { - tmp = (*_Y[k])[i]; - if ( !min[i].is_defined() || tmp < min[i] ) - min[i] = tmp; - if ( !max[i].is_defined() || tmp > max[i] ) - max[i] = tmp; - } - } - - for ( i = 0 ; i < _n ; ++i ) - _ref[i] = ( min[i] + max[i] ) / 2.0; - -#ifdef MODEL_STATS - _Yw = NOMAD::Double(); - for ( i = 0 ; i < _n ; ++i ) - { - tmp = max[i]-min[i]; - if ( !_Yw.is_defined() || tmp > _Yw ) - _Yw = tmp; - } -#endif - -#ifdef DEBUG - _out << std::endl - << "define_scaling(): reference = ( " << _ref << " )" << std::endl; -#endif - - // compute the scaling (and detect fixed variables): - for ( k = 0 ; k < nY ; ++k ) { - - for ( i = 0 ; i < _n ; ++i ) { - tmp = ( (*_Y[k])[i] - _ref[i] ).abs(); - if ( !_scaling[i].is_defined() || _scaling[i] < tmp ) - _scaling[i] = tmp; - } - } - - _nfree = _n; - - for ( i = 0 ; i < _n ; ++i ) - { - if ( _scaling[i] == 0.0 ) - { - _scaling [i] = 0.0; - _fixed_vars[i] = true; - --_nfree; - if ( _nfree == 0 ) - { - _scaling.clear(); - _ref.clear(); - _error_flag = true; - return; - } - } - else - _scaling[i] *= 1.0/r; // all coordinates in [-r;r] - } - - if ( _nfree < _n ) - init_alpha(); - - for ( k = 0 ; k < nY ; ++k ) - { - if ( !scale ( *_Y[k] ) ) - { - _scaling.clear(); - _error_flag = true; - return; - } - } - -#ifdef DEBUG - _out << "define_scaling(): scaling = ( " << _scaling << " )" << std::endl; -#endif - - _error_flag = false; -} - -/*-------------------------------------------------------------------*/ -/* . Scaling with rotation based on a set of directions. */ -/* See paper: */ -/* Reducing the number of function evaluations in */ -/* Mesh Adaptive Direct Search algorithms, Audet, Ianni, */ -/* LeDigabel, Tribes, 2014 */ -/* . looks also for fixed variables */ -/*-------------------------------------------------------------------*/ -void NOMAD::Quad_Model::define_scaling_by_directions ( const std::list & dirs, const NOMAD::Point & delta_m, const NOMAD::Double & epsilon ) -{ - if ( _error_flag || _Y.empty() ) { - _error_flag = true; - return; - } - - int i , k; - int nY = get_nY(); - NOMAD::Point min(_n) , max(_n); - NOMAD::Double tmp; - - - // The parameters defining the basic scaling (see define_scaling) are cleared. - // Only the parameters for the direction scaling are set - _scaling.clear(); - _ref.clear (); - - // For direction scaling - if (static_cast (dirs.size())!=_n || static_cast(delta_m.size()) != _n || epsilon<=0.0 || epsilon>=1) - { - _error_flag = true; - return; - } - _delta_m=delta_m; - // Get D' from dirs (scaling with delta_m - std::list::const_iterator itDir; - for (itDir=dirs.begin(); itDir != dirs.end(); itDir++) - { - NOMAD::Direction dir_i(_n,0.0,itDir->get_type()); - dir_i.set_index(itDir->get_index()); - for ( int i = 0 ; i < _n ; ++i ) - { - if (_delta_m[i]<=0.0) - { - _error_flag=true; - return; - } - dir_i[i]=(*itDir)[i]/_delta_m[i]; - } - _dirP.push_back(dir_i); - } - - _epsilon=epsilon; - - - // compute the min and the max: - for ( k = 0 ; k < nY ; ++k ) - { - - if ( !_Y[k] || _n != _Y[k]->size() ) - { - _error_flag = true; - return; - } - - for ( i = 0 ; i < _n ; ++i ) - { - tmp = (*_Y[k])[i]; - if ( !min[i].is_defined() || tmp < min[i] ) - min[i] = tmp; - if ( !max[i].is_defined() || tmp > max[i] ) - max[i] = tmp; - } - } - -#ifdef MODEL_STATS - _Yw = NOMAD::Double(); - for ( i = 0 ; i < _n ; ++i ) - { - tmp = max[i]-min[i]; - if ( !_Yw.is_defined() || tmp > _Yw ) - _Yw = tmp; - } -#endif - - // Detect fixed variables: - _nfree = _n; - for ( i = 0 ; i < _n ; ++i ) - { - bool fixed_var_i=true; - for ( k = 0 ; k < nY ; ++k ) - { - if ( ( (*_Y[k])[i] - _center[i] ).abs() > 0.0 ) - { - fixed_var_i=false; - break; - } - } - _fixed_vars[i]=fixed_var_i; - if (fixed_var_i) - --_nfree; - - if ( _nfree == 0 ) - { - _scaling.clear(); - _ref.clear(); - _dirP.clear(); - _error_flag = true; - return; - } - } - if ( _nfree < _n ) - init_alpha(); - - // Perform scaling of Y - for ( k = 0 ; k < nY ; ++k ) - { - if ( !scale ( *_Y[k] ) ) - { - _scaling.clear(); - _dirP.clear(); - _error_flag = true; - return; - } - } - -#ifdef DEBUG - _out << "define_scaling_by_direction(): " << std::endl; - for ( itDir = _dirP.begin() ; itDir != _dirP.end() ; ++itDir ) - { - _out << "dirPrime "; - _out.display_int_w ( (*itDir).get_index() , static_cast(_dirP.size()) ); - _out << " : " << *itDir << std::endl; - } -#endif - - _error_flag = false; -} - - -/*--------------------------------------------------------------*/ -/* scale a point */ -/*--------------------------------------------------------------*/ -bool NOMAD::Quad_Model::scale ( NOMAD::Point & x ) const -{ - if ( _error_flag || _n != x.size() ) - return false; - - if (_dirP.size()==0) - { - // Scale without rotation - for ( int i = 0 ; i < _n ; ++i ) - { - if ( !_ref [i].is_defined() || - !_scaling[i].is_defined() || - ! x[i].is_defined() ) - return false; - x[i] -= _ref[i]; - if ( _scaling[i] != 0 ) - x[i] /= _scaling[i]; - } - } - else - { - if (! _epsilon.is_defined() || !_delta_m.is_complete()) - return false; - // Scale with rotation based on direction and center (see paper Reducing the number of function evaluations in Mesh Adaptive Direct Search algorithms, Audet, Ianni, LeDigabel, Tribes, 2014 - // T(y)=(D')^-1*(center-x)/delta_m/(1-epsilon) - epsilon*1/(1-epsilon) - // (D')^-1=(D')^T/normCol^2 - NOMAD::Point temp(_n,0.0); - NOMAD::Double normCol2=0.0; - std::list::const_iterator itDir=_dirP.begin(); - for ( int i = 0 ; i < _n ; ++i ) - { - normCol2+=pow((*itDir)[i].value(),2.0); - - if (_delta_m[i] !=0.0) - temp[i]=(_center[i].value()-x[i].value())/_delta_m[i].value()/(1.0-_epsilon.value()); - else - return false; - x[i]=0.0; - } - int j=0; - for (itDir=_dirP.begin(); itDir != _dirP.end(); itDir++,j++) - { - for ( int i = 0 ; i < _n ; ++i ) - { - x[j]+=temp[i].value()*(*itDir)[i].value()/normCol2.value(); - } - x[j]-=_epsilon.value()/(1.0-_epsilon.value()); - } - } - - return true; -} - -/*-----------------------------------------------------------*/ -/* unscale a point */ -/*-----------------------------------------------------------*/ -bool NOMAD::Quad_Model::unscale ( NOMAD::Point & x ) const -{ - if ( _error_flag || _n != x.size() ) - return false; - - if (_dirP.size()==0) - { - // Scale without rotation - for ( int i = 0 ; i < _n ; ++i ) - { - if ( !_ref [i].is_defined() || - !_scaling[i].is_defined() || - ! x[i].is_defined() ) - return false; - - x[i] *= _scaling[i]; - x[i] += _ref [i]; - } - } - else - { - - if (! _epsilon.is_defined() || !_delta_m.is_complete()) - return false; - - // UnScale with rotation see paper Reducing the number of function evaluations in Mesh Adaptive Direct Search algorithms, Audet, Ianni, LeDigabel, Tribes, 2014 - //T^−1(x) = center+ _delta_m Dp ((ε−1)x−ε1) - NOMAD::Point temp(_n,0.0); - for ( int i = 0 ; i < _n ; ++i ) - { - temp[i]=(x[i]*(_epsilon-1.0)-_epsilon)*_delta_m[i]; - x[i]=0.0; - } - std::list::const_iterator itDir; - int j=0; - for (itDir=_dirP.begin(); itDir != _dirP.end(); itDir++,j++) - { - for (int i=0 ; i< _n ; i++) - { - x[i]+=temp[j]*(*itDir)[i]; - } - } - for ( int i = 0 ; i < _n ; ++i ) - { - x[i]+=_center[i]; - } - } - - return true; -} - -/*-----------------------------------------------------------*/ -/* unscale the slope at a point */ -/*-----------------------------------------------------------*/ -bool NOMAD::Quad_Model::unscale_grad ( NOMAD::Point & x ) const -{ - if ( _error_flag || _n != x.size() ) - return false; - - for ( int i = 0 ; i < _n ; ++i ) - { - - if (!_scaling[i].is_defined() || !x[i].is_defined() ) - return false; - - x[i] *= _scaling[i]; - } - - return true; -} - -/*------------------------------------------------------------------*/ -/* compute the element (i,j) of the interpolation matrix M(phi,Y) */ -/* (private) */ -/*------------------------------------------------------------------*/ -double NOMAD::Quad_Model::compute_M ( int i , int j ) const { - - if ( _error_flag ) - return 0.0; - - if ( j == 0 ) - return 1.0; - - if ( j <= _nfree ) - return (*_Y[i])[_index[j]-1].value(); - - if ( j <= 2 * _nfree ) - return 0.5 * pow ( (*_Y[i])[_index[j-_nfree]-1].value() , 2.0 ); - - int nm1 = _nfree - 1; - int jm2n , dec , r , i1 , i2; - - jm2n = j - 2 * _nfree; - dec = nm1; - r = jm2n; - i1 = -1; - - while ( r > 0 ) { - r -= dec; - ++i1; - --dec; - } - - i2 = r + nm1; - - return (*_Y[i])[_index[i1+1]-1].value() * (*_Y[i])[_index[i2+1]-1].value(); -} - -/*-----------------------------------------------------------*/ -/* construct m models (one by output) */ -/*-----------------------------------------------------------*/ -void NOMAD::Quad_Model::construct ( bool use_WP , - double eps , - int max_mpn , - int max_Y_size ) -{ - if ( _error_flag ) - return; - - int p1 = get_nY(); - - - // MFN interpolation: - if ( p1 < _n_alpha ) { - _interpolation_type = NOMAD::MFN; - _error_flag = !construct_MFN_model ( eps , max_mpn , max_Y_size ); - } - else { - - _error_flag = true; - - // well-poised regression: - if ( use_WP && p1 > _n_alpha ) { - _interpolation_type = NOMAD::WP_REGRESSION; - _error_flag = !construct_WP_model ( max_Y_size ); - } - - // regression: - if ( _error_flag ) { - _interpolation_type = NOMAD::REGRESSION; - _error_flag = !construct_regression_model ( eps , max_mpn , max_Y_size ); - } - } -} - -/*---------------------------------------------------------------*/ -/* find interpolation point with max Lagrange polynomial value */ -/*---------------------------------------------------------------*/ -/* . ji = argmax |li(x)| for x in Y */ -/* . used in construct_WP_model() */ -/* . private */ -/*---------------------------------------------------------------*/ -int NOMAD::Quad_Model::find_max_lix -( const NOMAD::Point & li , - const std::vector & Y , - int i1 , - int i2 , - NOMAD::Double & max_lix ) const -{ - max_lix = -1.0; - int ji = -1; - NOMAD::Double tmp; - for ( int j = i1 ; j <= i2 ; ++j ) { - tmp = eval ( *Y[j] , li ); - if ( tmp.is_defined() ) { - tmp = tmp.abs(); - if ( tmp > max_lix ) { - max_lix = tmp; - ji = j; - } - } - } - if ( ji < 0 ) - max_lix.clear(); - return ji; -} - -/*-----------------------------------------------------------*/ -/* construct well-poised (WP) model (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::Quad_Model::construct_WP_model ( int max_Y_size ) -{ - -#ifdef DEBUG - _out << std::endl - << NOMAD::open_block ( "NOMAD::Quad_Model::construct_WP_model()" ); -#endif - - // check the set Y: - if ( !check_Y() ) - return false; - - int i , j , k , p1 = get_nY(); - - // the number of points (p+1) must be in [1+(n+1)(n+2)/2;MS_MAX_Y_SIZE]: - if ( p1 <= _n_alpha || p1 > max_Y_size ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::construct_WP_model(): " - << "(p+1) not in [1+(n+1)(n+2)/2;" << max_Y_size << "]" - << std::endl << NOMAD::close_block() << std::endl; -#endif - return false; - } - - // Lagrange polynomials: - std::vector l; - for ( i = 0 ; i < _n_alpha ; ++i ) { - l.push_back ( new NOMAD::Point ( _n_alpha ) ); - for ( j = 0 ; j < _n_alpha ; ++j ) - (*l[i])[j] = (i==j) ? 1.0 : 0.0; - } - - // creation of sets Y1 and Y2; Y2 contains all available points - // of _Y and Y1 will be the 'well-poised' set with n_alpha points: - std::vector Y1 , Y2 = _Y; - int iy2 , ny2m1 = p1-1; - NOMAD::Double max_lix , liyi , ljyi; - - // we init Y1 with the first point of Y: - Y1.push_back ( Y2[0] ); - Y2[0] = Y2[ny2m1]; - Y2.resize ( ny2m1 ); - - // use algo 6.2 p.95 of the DFO book in order to construct Lagrange polynomials: - // ----------------------------------------------------------------------------- - for ( i = 0 ; i < _n_alpha ; ++i ) { - - // 1. point selection (select a point in Y2: Y2[iy2]): - // ------------------- - if ( i > 0 ) { - - ny2m1 = static_cast(Y2.size())-1; - iy2 = find_max_lix ( *l[i] , Y2 , 0 , ny2m1 , max_lix ); - - if ( iy2 < 0 ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::construct_WP_model(): " - << "cannot find candidate in Y" - << std::endl << NOMAD::close_block() << std::endl; -#endif - for ( i = 0 ; i < _n_alpha ; ++i ) - delete l[i]; - return false; - } - - // add Y2[iy2] in Y1: - Y1.push_back ( Y2[iy2] ); - Y2[iy2] = Y2[ny2m1]; - Y2.resize (ny2m1); - } - - // 2. normalization: - // ----------------- - liyi = eval ( *Y1[i] , *l[i] ); - - if ( liyi.abs().value() < 1e-15 ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::construct_WP_model(): set Y is not poised" - << std::endl << NOMAD::close_block() << std::endl; -#endif - for ( i = 0 ; i < _n_alpha ; ++i ) - delete l[i]; - return false; - } - - for ( k = 0 ; k < _n_alpha ; ++k ) { - (*l[i])[k] /= liyi; - if ( (*l[i])[k].abs().value() < 1e-15 ) - (*l[i])[k] = 0.0; - } - - // 3. orthogonalization: - // --------------------- - for ( j = 0 ; j < _n_alpha ; ++j ) - if ( j != i ) { - ljyi = eval ( *Y1[i] , *l[j] ); - for ( k = 0 ; k < _n_alpha ; ++k ) { - (*l[j])[k] = (*l[j])[k] - ljyi * (*l[i])[k]; - if ( (*l[j])[k].abs().value() < 1e-15 ) - (*l[j])[k] = 0.0; - } - } - } - -#ifdef DEBUG - display_lagrange_polynomials ( l , Y1 ); -#endif - - // compute alpha: - // -------------- - int m = static_cast ( _bbot.size() ); - for ( i = 0 ; i < m ; ++i ) - if ( _alpha[i] ) { - for ( j = 0 ; j < _n_alpha ; ++j ) { - (*_alpha[i])[j] = 0.0; - for ( k = 0 ; k < _n_alpha ; ++k ) - (*_alpha[i])[j] += Y1[k]->get_bb_outputs()[i] * (*l[k])[j]; - } - } - - // poisedness improvement using algorithm 6.3 page 95: - // --------------------------------------------------- - - // old alpha: - NOMAD::Point ** old_alpha = new NOMAD::Point * [m] , ** tmp_alpha; - for ( i = 0 ; i < m ; ++i ) - old_alpha[i] = ( _alpha[i] ) ? - new NOMAD::Point ( _n_alpha ) : NULL; - - int ik; - NOMAD::Double ljyk , lkyk , lix , new_rel_err , - cur_rel_err = compute_max_rel_err(); - - if ( cur_rel_err.is_defined() && cur_rel_err.value() > 1e-15 ) { - - for ( int niter = 0 ; niter < 10 ; ++niter ) { - - ny2m1 = static_cast(Y2.size())-1; - - if ( ny2m1 < 0 ) - break; - - max_lix = -1.0; - iy2 = -1; - ik = -1; - - for ( i = 0 ; i < _n_alpha ; ++i ) { - - j = find_max_lix ( *l[i] , Y2 , 0 , ny2m1 , lix ); - if ( j >= 0 && lix > max_lix ) { - max_lix = lix; - iy2 = j; - ik = i; - } - } - - if ( ik < 0 ) - break; - - // set Y1[ik] = Y2[iy2]: - Y1[ik ] = Y2[iy2]; - Y2[iy2] = Y2[ny2m1]; - Y2.resize ( ny2m1 ); - - lkyk = eval ( *Y1[ik] , *l[ik] ); - - if ( lkyk.abs() <= 1e-15 ) - break; - - // update Lagrange polynomials: - // ---------------------------- - - // normalization and orthogonalization: - for ( i = 0 ; i < _n_alpha ; ++i ) - (*l[ik])[i] /= lkyk; - - for ( j = 0 ; j < _n_alpha ; ++j ) { - if ( j != ik ) { - ljyk = eval ( *Y1[ik] , *l[j] ); - for ( i = 0 ; i < _n_alpha ; ++i ) - (*l[j])[i] = (*l[j])[i] - ljyk * (*l[ik])[i]; - } - } - - // save old alpha and compute new one: - for ( i = 0 ; i < m ; ++i ) - if ( _alpha[i] ) { - *(old_alpha[i]) = *(_alpha[i]); - for ( j = 0 ; j < _n_alpha ; ++j ) { - (*_alpha[i])[j] = 0.0; - for ( k = 0 ; k < _n_alpha ; ++k ) - (*_alpha[i])[j] += Y1[k]->get_bb_outputs()[i] * (*l[k])[j]; - } - } - - // compute new error: - new_rel_err = compute_max_rel_err(); - - // if no better error, restore old alpha and exit loop: - if ( !new_rel_err.is_defined() || new_rel_err >= cur_rel_err ) { - tmp_alpha = _alpha; - _alpha = old_alpha; - old_alpha = tmp_alpha; - break; - } - - cur_rel_err = new_rel_err; - } - } - - for ( i = 0 ; i < m ; ++i ) - delete old_alpha[i]; - delete [] old_alpha; - for ( i = 0 ; i < _n_alpha ; ++i ) - delete l[i]; - -#ifdef DEBUG - _out.close_block(); -#endif - - return true; -} - -/*-----------------------------------------------------------*/ -/* construct regression model (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::Quad_Model::construct_regression_model ( double eps , - int max_mpn , - int max_Y_size ) -{ -#ifdef DEBUG - _out << std::endl - << NOMAD::open_block ( "NOMAD::Quad_Model::construct_regression_model()" ); -#endif - - _error_flag = false; - - // check the set Y: - if ( !check_Y() ) - return false; - - int p1 = get_nY(); - - // the number of points (p+1) must be in [(n+1)(n+2)/2;MS_MAX_Y_SIZE]: - if ( p1 < _n_alpha || p1 > max_Y_size ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::construct_regression_model(): " - << "(p+1) not in [(n+1)(n+2)/2;" - << max_Y_size << "]" - << std::endl << NOMAD::close_block() << std::endl; -#endif - return false; - } - - // for this procedure, the number of points is limited to 500 - // (because of the SVD decomposition): - if ( p1 > 500 ) { - reduce_Y ( NOMAD::Point ( _n , 0.0 ) , 500 ); - p1 = 500; - } - - // construct the matrix F=M'M (_n_alpha,_n_alpha): - // ----------------------------------------------- - int i , j , k; - double ** F = new double *[_n_alpha]; - double ** M = new double *[p1]; - for ( i = 0 ; i < p1 ; ++i ) { - M[i] = new double[_n_alpha]; - for ( j = 0 ; j < _n_alpha ; ++j ) - M[i][j] = compute_M ( i , j ); - } - - for ( i = 0 ; i < _n_alpha ; ++i ) { - F[i] = new double[_n_alpha]; - for ( j = 0 ; j <= i ; ++j ) { - F[i][j] = 0.0; - for ( k = 0 ; k < p1 ; ++k ) - F[i][j] += M[k][i] * M[k][j]; - if ( i != j ) - F[j][i] = F[i][j]; - } - } - -#ifdef DEBUG - _out << std::endl << "F="; - for ( i = 0 ; i < _n_alpha ; ++i ) { - _out << "\t"; - for ( j = 0 ; j < _n_alpha ; ++j ) - _out << std::setw(12) << F[i][j] << " "; - _out << std::endl; - } -#endif - - bool error = false; - - // SVD decomposition of the F matrix (F=U.W.V'): - // --------------------------------------------- - // (F will be transformed in U) - - double * W = new double [_n_alpha]; - double ** V = new double *[_n_alpha]; - for ( i = 0 ; i < _n_alpha ; ++i ) - V[i] = new double[_n_alpha]; - - std::string error_msg; - if ( NOMAD::SVD_decomposition ( error_msg , F , W , V , _n_alpha , _n_alpha , max_mpn ) ) { - - // compute condition number: - compute_cond ( W , _n_alpha , eps ); - -#ifdef DEBUG - _out << std::endl << "F="; - for ( i = 0 ; i < _n_alpha ; ++i ) { - _out << "\t"; - for ( j = 0 ; j < _n_alpha ; ++j ) - _out << std::setw(12) << F[i][j] << " "; - _out << std::endl; - } - - _out << std::endl << "W=\t"; - for ( i = 0 ; i < _n_alpha ; ++i ) - _out << std::setw(12) << W[i] << " "; - _out << std::endl << std::endl << "cond=" << _cond << std::endl; - - _out << std::endl << "V="; - for ( i = 0 ; i < _n_alpha ; ++i ) { - _out << "\t"; - for ( j = 0 ; j < _n_alpha ; ++j ) - _out << std::setw(12) << V[i][j] << " "; - _out << std::endl; - } -#endif - - } - else { -#ifdef DEBUG - _out << std::endl << "NOMAD::Quad_Model::construct_regression_model(): " - << "SVD decomposition (" << error_msg << ")" - << std::endl << NOMAD::close_block() << std::endl; -#endif - error = true; - _cond.clear(); - } - - // resolution of system F.alpha = M'.f(Y): - // --------------------------------------- - if ( !error ) { - int m = static_cast ( _bbot.size() ); - for ( i = 0 ; i < m ; ++i ) - if ( _alpha[i] ) - solve_regression_system ( M , F , W , V , i , *_alpha[i] , eps ); - } - - // free memory: - for ( i = 0 ; i < _n_alpha ; ++i ) { - delete [] F[i]; - delete [] V[i]; - } - for ( i = 0 ; i < p1 ; ++i ) - delete [] M[i]; - delete [] M; - delete [] F; - delete [] V; - delete [] W; - -#ifdef DEBUG - _out.close_block(); -#endif - - return !error; -} - -/*-------------------------------------------------------------*/ -/* compute condition number (private) */ -/*-------------------------------------------------------------*/ -void NOMAD::Quad_Model::compute_cond ( const double * W , int n , double eps ) -{ - double min = NOMAD::INF; - double max = -min; - for ( int i = 0 ; i < n ; ++i ) { - if ( W[i] < min ) - min = W[i]; - if ( W[i] > max ) - max = W[i]; - } - if ( min < eps ) - min = eps; - _cond = max / min; -} - -/*-------------------------------------------------------------*/ -/* resolution of system F.alpha = M'.f(Y) for the regression */ -/* (private) */ -/*-------------------------------------------------------------*/ -void NOMAD::Quad_Model::solve_regression_system ( double ** M , - double ** F , - double * W , - double ** V , - int bbo_index , - NOMAD::Point & alpha , - double eps ) const -{ - // resize the alpha vector: - if ( alpha.size() != _n_alpha ) - alpha.reset ( _n_alpha , 0.0 ); - - double * alpha_tmp = new double [_n_alpha]; - int i , k , p1 = get_nY(); - - // solve the system: - for ( i = 0 ; i < _n_alpha ; ++i ) { - alpha_tmp[i] = 0.0; - for ( k = 0 ; k < p1 ; ++k ) - alpha_tmp[i] += M[k][i] * ( _Y[k]->get_bb_outputs()[bbo_index].value() ); - } - - double * alpha_tmp2 = new double [_n_alpha]; - - // some W values will be zero (or near zero); - // each value that is smaller than eps is ignored - - for ( i = 0 ; i < _n_alpha ; ++i ) { - alpha_tmp2[i] = 0.0; - for ( k = 0 ; k < _n_alpha ; ++k ) - if ( W[i] > eps ) - alpha_tmp2[i] += F[k][i] * alpha_tmp[k] / W[i]; - } - - delete [] alpha_tmp; - - for ( i = 0 ; i < _n_alpha ; ++i ) { - alpha[i] = 0.0; - for ( k = 0 ; k < _n_alpha ; ++k ) - alpha[i] += V[i][k] * alpha_tmp2[k]; - } - - delete [] alpha_tmp2; -} - -/*----------------------------------------------------------*/ -/* construct Minimum Frobenius Norm (MFN) model (private) */ -/*----------------------------------------------------------*/ -bool NOMAD::Quad_Model::construct_MFN_model ( double eps , - int max_mpn , - int max_Y_size ) -{ -#ifdef DEBUG - _out << std::endl - << NOMAD::open_block ( "NOMAD::Quad_Model::construct_MFN_model()" ); -#endif - - // check the set Y: - if ( !check_Y() ) - return false; - - int p1 = get_nY(); - - // the number of points (p+1) must be in [n+1;(n+1)(n+2)/2-1]: - if ( p1 <= _nfree || p1 >= _n_alpha ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::construct_MFN_model(): " - << "(p+1) not in [n+1;(n+1)(n+2)/2-1]" - << std::endl << NOMAD::close_block() << std::endl; -#endif - return false; - } - - // for this procedure, the number of points is limited to 250 - // (because of the SVD decomposition): - if ( p1 > 250 ) { - reduce_Y ( NOMAD::Point ( _n , 0.0 ) , 250 ); - p1 = 250; - } - - // construct the matrix F (4 parts): - // --------------------------------- - // [ 1 | 2 ] - // [ --+-- ] - // [ 3 | 4 ] - - int i , j , k; - int np1 = _nfree + 1; - int nF = np1 + p1; - double ** F = new double *[nF]; - double ** M = new double *[p1]; - for ( i = 0 ; i < nF ; ++i ) - F[i] = new double[nF]; - - // 1/4: MQ.MQ' (p+1,p+1): - { - for ( i = 0 ; i < p1 ; ++i ) - { - M[i] = new double[_n_alpha]; - for ( j = 0 ; j < _n_alpha ; ++j ) - M[i][j] = compute_M ( i , j ); - for ( j = 0 ; j <= i ; ++j ) - { - F[i][j] = 0.0; - for ( k = np1 ; k < _n_alpha ; ++k ) - F[i][j] += M[i][k] * M[j][k]; - if ( i != j ) - F[j][i] = F[i][j]; - } - } - } - - // 2/4: ML (p+1,n+1): - for ( i = 0 ; i < p1 ; ++i ) - { - F[i][p1] = 1.0; - for ( j = p1+1 ; j < nF ; ++j ) - F[i][j] = M[i][j-p1]; - } - - // 3/4: ML' (n+1,p+1): - for ( j = 0 ; j < p1 ; ++j ) - { - F[p1][j] = 1.0; - for ( i = p1+1 ; i < nF ; ++i ) - F[i][j] = M[j][i-p1]; - } - - // 4/4: 0 (n+1,n+1): - for ( i = p1 ; i < nF ; ++i ) - for ( j = p1 ; j < nF ; ++j ) - F[i][j] = 0.0; - - -#ifdef DEBUG - _out << std::endl << "F="; - for ( i = 0 ; i < nF ; ++i ) - { - _out << "\t"; - for ( j = 0 ; j < nF ; ++j ) - _out << std::setw(12) << F[i][j] << " "; - _out << std::endl; - } -#endif - - for ( i = 0 ; i < p1 ; ++i ) - delete [] M[i]; - delete [] M; - - bool error = false; - - // SVD decomposition of the F matrix (F = U.W.V'): - // ----------------------------------------------- - // (F will be transformed in U) - - double * W = new double [nF]; - double ** V = new double *[nF]; - for ( i = 0 ; i < nF ; ++i ) - V[i] = new double[nF]; - - std::string error_msg; - - if ( NOMAD::SVD_decomposition ( error_msg , F , W , V , nF , nF , max_mpn ) ) { - - // compute condition number: - compute_cond ( W , nF , eps ); - -#ifdef DEBUG - _out << std::endl << "F="; - for ( i = 0 ; i < nF ; ++i ) - { - _out << "\t"; - for ( j = 0 ; j < nF ; ++j ) - _out << std::setw(12) << F[i][j] << " "; - _out << std::endl; - } - - _out << std::endl << "W=\t"; - for ( i = 0 ; i < nF ; ++i ) - _out << std::setw(12) << W[i] << " "; - _out << std::endl << std::endl << "cond=" << _cond << std::endl; - - _out << std::endl << "V="; - for ( i = 0 ; i < nF ; ++i ) - { - _out << "\t"; - for ( j = 0 ; j < nF ; ++j ) - _out << std::setw(12) << V[i][j] << " "; - _out << std::endl; - } -#endif - - } - else - { -#ifdef DEBUG - _out << std::endl << "NOMAD::Quad_Model::construct_MFN_model(): " - << "SVD decomposition (" << error_msg << ")" - << std::endl << std::endl; -#endif - error = true; - _cond.clear(); - } - - // resolution of system F.[mu alpha_L]'=[f(Y) 0]' : - // ------------------------------------------------ - if ( !error ) - { - int m = static_cast ( _bbot.size() ); - for ( i = 0 ; i < m ; ++i ) - if ( _alpha[i] ) - solve_MFN_system ( F , W , V , i , *_alpha[i] , eps ); - } - - // free memory: - for ( i = 0 ; i < nF ; ++i ) - { - delete [] F[i]; - delete [] V[i]; - } - delete [] F; - delete [] V; - delete [] W; - -#ifdef DEBUG - _out.close_block(); -#endif - - return !error; -} - -/*--------------------------------------------------*/ -/* resolution of system F.[mu alpha_L]'=[f(Y) 0]' */ -/* for MFN interpolation (private) */ -/*--------------------------------------------------*/ -void NOMAD::Quad_Model::solve_MFN_system ( double ** F , - double * W , - double ** V , - int bbo_index , - NOMAD::Point & alpha , - double eps ) const -{ - // resize the alpha vector: - if ( alpha.size() != _n_alpha ) - alpha.reset ( _n_alpha , 0.0 ); - - int i , k , k1 , k2 , - np1 = _nfree + 1 , - nm1 = _nfree - 1 , - p1 = get_nY() , - nF = np1 + p1; - - // step 1/2: find alpha_L and mu: - // --------- - double * alpha_tmp = new double [np1]; - double * mu_tmp = new double [ p1]; - double * mu = new double [ p1]; - - // if F is singular, some W values will be zero (or near zero); - // each value that is smaller than eps is ignored: - for ( i = 0 ; i < p1 ; ++i ) - { - mu_tmp[i] = 0.0; - if ( W[i] > eps ) - for ( k = 0 ; k < p1 ; ++k ) - mu_tmp[i] += F[k][i] * - ( _Y[k]->get_bb_outputs()[bbo_index].value() ) / W[i]; - } - - for ( i = p1 ; i < nF ; ++i ) - { - alpha_tmp[i-p1] = 0.0; - if ( W[i] > eps ) - for ( k = 0 ; k < p1 ; ++k ) - alpha_tmp[i-p1] += F[k][i] * - ( _Y[k]->get_bb_outputs()[bbo_index].value() ) / W[i]; - } - - for ( i = 0 ; i < p1 ; ++i ) - { - mu[i] = 0.0; - for ( k = 0 ; k < p1 ; ++k ) - mu[i] += V[i][k] * mu_tmp[k]; - for ( k = p1 ; k < nF ; ++k ) - mu[i] += V[i][k] * alpha_tmp[k-p1]; - } - - for ( i = p1 ; i < nF ; ++i ) - { - alpha[i-p1] = 0.0; - for ( k = 0 ; k < p1 ; ++k ) - alpha[i-p1] += V[i][k] * mu_tmp[k]; - for ( k = p1 ; k < nF ; ++k ) - alpha[i-p1] += V[i][k] * alpha_tmp[k-p1]; - } - - delete [] alpha_tmp; - delete [] mu_tmp; - -#ifdef DEBUG - _out << std::endl << "output #" << bbo_index << ": mu=\t"; - for ( i = 0 ; i < p1 ; ++i ) - _out << std::setw(12) << mu[i] << " "; - _out << std::endl; - - _out << std::endl << "output #" << bbo_index << ": alpha_intermediate=\t"; - for ( i = 0 ; i < alpha.size() ; ++i ) - _out << std::setw(12) << alpha[i] << " "; - _out << std::endl; - -#endif - - // step 2/2: find alpha_Q: - // --------- - for ( i = 0 ; i < _nfree ; ++i ) - { - alpha[i+np1] = 0.0; - for ( k = 0 ; k < p1 ; ++k ) - alpha[i+np1] += mu[k] * pow ( (*_Y[k])[_index[i+1]-1].value() , 2.0 ) / 2.0; - } - - for ( k1 = 0 ; k1 < nm1 ; ++k1 ) - for ( k2 = k1+1 ; k2 < _nfree ; ++k2 ) - { - alpha[i+np1] = 0.0; - for ( k = 0 ; k < p1 ; ++k ) - alpha[i+np1] += mu[k] * (*_Y[k])[_index[k1+1]-1].value() * (*_Y[k])[_index[k2+1]-1].value(); - ++i; - } - - delete [] mu; -} - -/*-----------------------------------------------------------*/ -/* check the interpolation set Y (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::Quad_Model::check_Y ( void ) const -{ - if ( _Y.empty() ) { -#ifdef DEBUG - _out << std::endl << "NOMAD::Quad_Model::check_Y(): set Y is empty" - << std::endl << std::endl; -#endif - return false; - } - - int nY = get_nY(); - int m = static_cast ( _bbot.size() ); - - for ( int k = 0 ; k < nY ; ++k ) { - - if ( _Y[k] == NULL ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::check_Y(): NULL pointer in the set Y" - << std::endl << std::endl; -#endif - return false; - } - - if ( _Y[k]->get_eval_status() != NOMAD::EVAL_OK ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::check_Y(): a point in Y failed to evaluate" - << std::endl << std::endl; -#endif - return false; - } - - const NOMAD::Point & bbo = _Y[k]->get_bb_outputs(); - - if ( !bbo.is_complete() ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::check_Y(): some bb outputs in Y are not defined" - << std::endl << std::endl; -#endif - return false; - } - - if ( bbo.size() != m ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::check_Y(): " - << "bb outputs in Y do not have the same dimension" - << std::endl << std::endl; -#endif - return false; - } - - if ( _Y[k]->size() != _n ) { -#ifdef DEBUG - _out << std::endl - << "NOMAD::Quad_Model::check_Y(): " - << "points in Y do not have the same dimension" - << std::endl << std::endl; -#endif - return false; - } - } - return true; -} - -/*----------------------------------------------------*/ -/* check if the model is ready for evaluations */ -/*----------------------------------------------------*/ -bool NOMAD::Quad_Model::check ( void ) const -{ - if ( !_alpha ) - return false; - - int nalpha = (_nfree+1)*(_nfree+2)/2; - int i , m = static_cast ( _bbot.size() ); - - for ( int bbo_index = 0 ; bbo_index < m ; ++bbo_index ) - { - - if ( _alpha[bbo_index] ) - { - - if ( _alpha[bbo_index]->size() != nalpha ) - return false; - - for ( i = 0 ; i < nalpha ; ++i ) - if ( !(*_alpha[bbo_index])[i].is_defined() ) - return false; - } - } - - return true; -} - - -/*--------------------------------------------------------------------------*/ -/* evaluate a model at a given point */ -/*--------------------------------------------------------------------------*/ -/* . the method assumes that x.size()==_n, alpha.is_complete(), and */ -/* alpha.size()==(_nfree+1)*(_nfree+2)/2 */ -/* . a more efficient version is used in Quad_Model_Evaluator::eval_x() ) */ -/*--------------------------------------------------------------------------*/ -NOMAD::Double NOMAD::Quad_Model::eval ( const NOMAD::Point & x , - const NOMAD::Point & alpha ) const -{ - int i , j , k = 1 , nm1 = _n-1; - NOMAD::Double z = alpha[0]; - - for ( i = 0 ; i < _n ; ++i ) - { - if ( !_fixed_vars[i] ) - { - z += x[i] * ( alpha[k] + 0.5 * alpha[k+_nfree] * x[i] ); - ++k; - } - } - - k += _nfree; - - for ( i = 0 ; i < nm1 ; ++i ) - if ( !_fixed_vars[i] ) - for ( j = i+1 ; j < _n ; ++j ) - if ( !_fixed_vars[j] ) - z += alpha[k++] * x[i] * x[j]; - - return z; -} - - -/*----------------------------------------------------------------*/ -/* compute model h and f values at a point */ -/*----------------------------------------------------------------*/ -void NOMAD::Quad_Model::eval_hf ( const NOMAD::Point & x , - const NOMAD::Double & h_min , - NOMAD::hnorm_type h_norm , - NOMAD::Double & h , - NOMAD::Double & f ) const -{ - f.clear(); - h = 0.0; - - int m = static_cast(_bbot.size()); - NOMAD::Double bboi; - - for ( int i = 0 ; i < m ; ++i ) { - - if ( _alpha[i] ) { - - bboi = eval ( x , *_alpha[i] ); - - if ( bboi.is_defined() ) { - - if ( _bbot[i] == NOMAD::EB || _bbot[i] == NOMAD::PEB_E ) { - - if ( bboi > h_min ) { - h.clear(); - return; - } - } - - else if ( ( _bbot[i] == NOMAD::FILTER || - _bbot[i] == NOMAD::PB || - _bbot[i] == NOMAD::PEB_P ) ) { - if ( bboi > h_min ) { - switch ( h_norm ) { - case NOMAD::L1: - h += bboi; - break; - case NOMAD::L2: - h += bboi * bboi; - break; - case NOMAD::LINF: - if ( bboi > h ) - h = bboi; - break; - } - } - } - - else if ( _bbot[i] == NOMAD::OBJ ) - f = bboi; - } - } - } - - if ( h_norm == NOMAD::L2 ) - h = h.sqrt(); -} - - - - -/*-----------------------------------------------------*/ -/* compute the maximal relative error of a model for */ -/* the interpolation set (private) */ -/*-----------------------------------------------------*/ -NOMAD::Double NOMAD::Quad_Model::compute_max_rel_err ( void ) const -{ - NOMAD::Double truth_value , model_value , rel_err , max_rel_err; - int k , nY = get_nY() , m = static_cast ( _bbot.size() ); - - for ( int bbo_index = 0 ; bbo_index < m ; ++bbo_index ) { - if ( _alpha[bbo_index] ) { - for ( k = 0 ; k < nY ; ++k ) { - if ( _Y[k] && _Y[k]->get_eval_status() == NOMAD::EVAL_OK ) { - truth_value = _Y[k]->get_bb_outputs()[bbo_index]; - if ( truth_value.is_defined() ) { - model_value = eval ( *_Y[k] , *_alpha[bbo_index] ); - if ( model_value.is_defined() ) { - if ( truth_value.abs() != 0.0 ) { - rel_err = (truth_value-model_value).abs() / truth_value.abs(); - if ( !max_rel_err.is_defined() || rel_err > max_rel_err ) - max_rel_err = rel_err; - } - } - } - } - } - } - } - return max_rel_err; -} - -/*---------------------------------------------*/ -/* compute the cumulated error of a model */ -/* for the points of the interpolation set Y */ -/* and for one output in particular */ -/* (private) */ -/*---------------------------------------------*/ -void NOMAD::Quad_Model::compute_model_error ( int bbo_index , - NOMAD::Double & error , - NOMAD::Double & min_rel_err , - NOMAD::Double & max_rel_err , - NOMAD::Double & avg_rel_err ) const -{ - NOMAD::Double truth_value , model_value , rel_err; - int nY = get_nY() , cnt = 0; - bool chk = true; - - max_rel_err.clear(); - min_rel_err.clear(); - avg_rel_err = error = 0.0; - -#ifdef DEBUG - std::ostringstream msg; - msg << "output #" << bbo_index; - _out.open_block ( msg.str() ); -#endif - - for ( int k = 0 ; k < nY ; ++k ) - if ( _Y[k] && _Y[k]->get_eval_status() == NOMAD::EVAL_OK ) - { - truth_value = _Y[k]->get_bb_outputs()[bbo_index]; - - if ( truth_value.is_defined() ) - { - model_value = eval ( *_Y[k] , *_alpha[bbo_index] ); - if ( model_value.is_defined() ) - { - rel_err.clear(); - if ( truth_value.abs() != 0.0 ) - rel_err = (truth_value-model_value).abs() / truth_value.abs(); - else - { - if (truth_value.abs()==model_value.abs()) - rel_err=0.0; - else - rel_err=NOMAD::INF; - } - if ( !max_rel_err.is_defined() || rel_err > max_rel_err ) - max_rel_err = rel_err; - if ( !min_rel_err.is_defined() || rel_err < min_rel_err ) - min_rel_err = rel_err; - avg_rel_err += rel_err; - ++cnt; - -#ifdef DEBUG - _out << "Y[" << k << "]= ( "; - _Y[k]->NOMAD::Point::display ( _out ); - _out << " )" << " f=" << truth_value - << " m=" << model_value << " error^2=" - << ( model_value - truth_value ).pow2() - << " rel_err=" << rel_err - << std::endl; -#endif - error += ( model_value - truth_value ).pow2(); - } - else - { - chk = false; - break; - } - } - else - { - chk = false; - break; - } - } - -#ifdef DEBUG - _out.close_block(); -#endif - - if ( chk) - { // Case where chk is true (at least one model_value and the corresponding thruth value were defined => cnt != 0) - error = error.sqrt(); - avg_rel_err = avg_rel_err / cnt; - } - else - { - error.clear(); - min_rel_err.clear(); - max_rel_err.clear(); - avg_rel_err.clear(); - } -} - -/*-----------------------------------------------------------*/ -/* display the model coefficients */ -/*-----------------------------------------------------------*/ -void NOMAD::Quad_Model::display_model_coeffs ( const NOMAD::Display & out ) const -{ - if ( _error_flag ) { - out << "model coefficients: could not be constructed" << std::endl; - return; - } - - int m = static_cast ( _bbot.size() ); - - out << NOMAD::open_block ( "model coefficients" ); - for ( int i = 0 ; i < m ; ++i ) { - out << "output #"; - out.display_int_w ( i , m ); - out << ": "; - if ( _alpha[i] ) { - out<< "[ "; - _alpha[i]->display ( out , " " , 6 ); - out << " ]"; - } - else - out << "NULL"; - out << std::endl; - } - out.close_block(); -} - -/*-----------------------------------------------------------*/ -/* display the interpolation set Y */ -/*-----------------------------------------------------------*/ -void NOMAD::Quad_Model::display_Y ( const NOMAD::Display & out , - const std::string & title ) const -{ - out << NOMAD::open_block ( title ); - int nY = get_nY(); - for ( int k = 0 ; k < nY ; ++k ) { - out << "#"; - out.display_int_w ( k , nY ); - out << ": "; - if ( _Y[k] ) { - out << "( "; - _Y[k]->NOMAD::Point::display ( out , " " , 12 ); - out << " ) bbo=[ "; - _Y[k]->get_bb_outputs().display ( out , " " , 12 ); - out << " ]"; - } - else - out << "NULL"; - out << std::endl; - } - out.close_block(); -} - -/*-------------------------------------------------------*/ -/* display cumulated error on the interpolation points */ -/*-------------------------------------------------------*/ -void NOMAD::Quad_Model::display_Y_error ( const NOMAD::Display & out ) const -{ - if ( _error_flag ) { - out << "model error on the interpolation set: cannot be computed" - << std::endl; - return; - } - - int i ; - int index = -1; - int m = static_cast ( _bbot.size() ); - - for ( i = 0 ; i < m ; ++i ) - if ( _alpha[i] ) { - if ( index >= 0 ) { - index = -1; - break; - } - else - index = i; - } - - NOMAD::Double error , min_rel_err , max_rel_err , avg_rel_err; - - // only one output: - if ( index >= 0 ) { - compute_model_error ( index , error , min_rel_err , max_rel_err , avg_rel_err ); - out << "model errors on the interpolation set: error=" - << error << " min_rel_err=" << min_rel_err - << " max_rel_err=" << max_rel_err << " avg_rel_err=" << avg_rel_err - << std::endl; - } - - // several outputs: - else { - - out.open_block ( "model error on the interpolation set" ); - - NOMAD::Double error_i , min_rel_err_i , max_rel_err_i , avg_rel_err_i; - - error = avg_rel_err = 0.0; - min_rel_err.clear(); - max_rel_err.clear(); - - int cnt = 0; - - for ( i = 0 ; i < m ; ++i ) - if ( _alpha[i] ) { - - ++cnt; - - compute_model_error ( i , - error_i , - min_rel_err_i , - max_rel_err_i , - avg_rel_err_i ); - - if (error_i.is_defined()) - error += error_i; - if (avg_rel_err_i.is_defined()) - avg_rel_err += avg_rel_err_i; - if ( !min_rel_err.is_defined() || min_rel_err_i < min_rel_err ) - min_rel_err = min_rel_err_i; - if ( !max_rel_err.is_defined() || max_rel_err_i > max_rel_err ) - max_rel_err = max_rel_err_i; - - out << "output #" << i << ": error=" << error_i - << " min_rel_err=" << min_rel_err_i << " max_rel_err=" - << max_rel_err_i << " avg_rel_err=" << avg_rel_err_i << std::endl; - } - - out << std::endl << "global: error=" << error - << " min_rel_err=" << min_rel_err - << " max_rel_err=" << max_rel_err - << " avg_rel_err=" << avg_rel_err / cnt - << std::endl << NOMAD::close_block(); - } -} - -/*-----------------------------------------------*/ -/* display Lagrange polynomials (private) */ -/*-----------------------------------------------*/ -void NOMAD::Quad_Model::display_lagrange_polynomials -( const std::vector & l , - const std::vector & Y ) const -{ - int i , j , nY = static_cast ( Y.size() ); - - // display Lagrange polynomials: - _out << std::endl << NOMAD::open_block ( "Lagrange polynomials" ); - for ( i = 0 ; i < _n_alpha ; ++i ) { - _out << "l["; - _out.display_int_w ( i , _n_alpha ); - _out << "] = [ "; - l[i]->NOMAD::Point::display ( _out , " " , 14 , -1 ); - _out << "]" << std::endl; - } - _out.close_block(); - - // display current set Y: - _out << std::endl << NOMAD::open_block ( "current set Y" ); - for ( i = 0 ; i < nY ; ++i ) { - _out << "Y["; - _out.display_int_w ( i , nY ); - _out << "] = "; - if ( Y[i] ) { - _out << "( "; - Y[i]->NOMAD::Point::display ( _out , " " , 6 , -1 ); - _out << " )"; - } - else - _out << "NULL"; - _out << std::endl; - } - - _out.close_block(); - - // display l(Y): should be the identity matrix: - NOMAD::Double tmp , err = 0.0; - _out << std::endl << NOMAD::open_block ( "l(Y)" ); - for ( i = 0 ; i < _n_alpha ; ++i ) { - _out << "l["; - _out.display_int_w ( i , _n_alpha ); - _out << "]: "; - for ( j = 0 ; j < _n_alpha ; ++j ) { - tmp.clear(); - if ( j < nY && Y[j] ) { - tmp = eval ( *Y[j] , *l[i] ); - err += (i==j) ? (tmp-1.0).abs() : tmp.abs(); - } - tmp.display ( _out , "%6.3f" ); - _out << " "; - } - _out << std::endl; - } - _out << std::endl << "error (with identity) = " - << err << std::endl << NOMAD::close_block() << std::endl; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model.hpp deleted file mode 100644 index 98a39dbaf..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model.hpp +++ /dev/null @@ -1,452 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Quad_Model.hpp - \brief Quadratic regression or MFN interpolation model (headers) - \author Sebastien Le Digabel - \date 2010-08-31 - \see Quad_Model.cpp -*/ -#ifndef __QUAD_MODEL__ -#define __QUAD_MODEL__ - -#include "Cache.hpp" -#include "Model_Sorted_Point.hpp" -#include "Evaluator.hpp" - -namespace NOMAD { - - /// Class for quadratic regression or MFN interpolation model. - class Quad_Model : private NOMAD::Uncopyable { - - /*-------------------------------------------------------------------------*/ - private: - - const NOMAD::Display & _out; ///< Display. - - std::vector _Y; ///< Interpolation points. - - const std::vector & _bbot; ///< Blackbox output types. - - NOMAD::interpolation_type _interpolation_type; ///< Interpolation type. - - int _n; ///< Dimension. - int _nfree; ///< Number of free variables. - int _n_alpha; ///< Number of model coefficients. - bool * _fixed_vars; ///< Fixed variables. - int * _index; ///< Var. indexes with fixed var. - NOMAD::Point ** _alpha; ///< Model coefficients. - NOMAD::Point _center; ///< Model center. - NOMAD::Point _ref; ///< Reference for scaling. - NOMAD::Point _scaling; ///< Scaling. - const NOMAD::Cache & _cache; ///< Cache. - const NOMAD::Signature & _signature; ///< Signature. - bool _error_flag; ///< Error flag. - std::list _dirP; ///< Directions used for scaling (may be empty) - NOMAD::Point _delta_m; ///< Mesh size used for scaling - NOMAD::Double _epsilon; ///< Offset for direction scaling - - - NOMAD::Double _cond; ///< Condition number. - - /// Initialize alpha (model parameters). - void init_alpha ( void ); - - /// Check if an unscaled point is in \c B(center,radius) for a given radius. - /** - \param x The unscaled point -- \b IN. - \param radius The radius -- \b IN. - \return \c true is \c x is in \c B(center,radius). - */ - bool is_within_radius ( const NOMAD::Point & x , - const NOMAD::Point & radius ) const; - - /// Check the interpolation set \c Y. - /** - \return \c true if the interpolation set is valid. - */ - bool check_Y ( void ) const; - - /// Check outputs before the integration into \c Y. - /** - \param bbo The outputs -- \b IN. - \param m Number of outputs -- \b IN. - return \c true if the \c m outputs are valid. - */ - bool check_outputs ( const NOMAD::Point & bbo , int m ) const; - - /// Reduce the number of interpolation points. - /** - The points are sorted accorded to their distance to the model center. - \param center Center of the model -- \b IN. - \param max_Y_size Max number of interpolation points -- \b IN. - */ - void reduce_Y ( const NOMAD::Point & center , int max_Y_size ); - - /// Compute condition number. - /** - \param W Matrix W given as a vector -- \b IN. - \param n Size of \c W -- \b IN - \param eps Epsilon -- \b IN. - */ - void compute_cond ( const double * W , int n , double eps ); - - /// Compute the cumulated error of a model for one output. - /** - The errors are computed on the interpolation set \c Y. - \param bbo_index Blackbox output index -- \b IN. - \param error Cumulated error -- \b OUT. - \param min_rel_err Min relative error -- \b OUT. - \param max_rel_err Max relative error -- \b OUT. - \param avg_rel_err Average relative error -- \b OUT. - */ - void compute_model_error ( int bbo_index , - NOMAD::Double & error , - NOMAD::Double & min_rel_err , - NOMAD::Double & max_rel_err , - NOMAD::Double & avg_rel_err ) const; - - /// Compute the maximal relative error of a model. - /** - The error is computed for the interpolation set \c Y. - \return The maximal relative error. - */ - NOMAD::Double compute_max_rel_err ( void ) const; - - /// Compute the element \c (i,j) of the interpolation matrix \c M(phi,Y). - /** - \param i Row index -- \b IN. - \param j Column index -- \b IN. - */ - double compute_M ( int i , int j ) const; - - /// Construct Minimum Frobenius Norm (MFN) model. - /** - - This occurs when \c p+1 \c < \c (n+1)(n+2)/2. - \param eps Epsilon -- \b IN. - \param max_mpn Maximum \c m+n value for SVD matrices -- \b IN. - \param max_Y_size Maximum number of elements in \c Y -- \b IN. - \return \c true if the construction succeeded - */ - bool construct_MFN_model ( double eps , int max_mpn , int max_Y_size ); - - /// Construct regression model. - /** - - This occurs when \c p+1 \c >= \c (n+1)(n+2)/2. - \param eps Epsilon -- \b IN. - \param max_mpn Maximum \c m+n value for SVD matrices -- \b IN. - \param max_Y_size Maximum number of elements in \c Y -- \b IN. - \return \c true if the construction succeeded - */ - bool construct_regression_model ( double eps , - int max_mpn , - int max_Y_size ); - - /// Construct well-poised (WP) model. - /** - \param max_Y_size Maximum number of elements in \c Y -- \b IN. - \return \c true if the construction succeeded - */ - bool construct_WP_model ( int max_Y_size ); - - /// Find interpolation point with max Lagrange polynomial value. - /** - \param li Lagrange polynomial -- \b IN. - \param Y Interpolation points candidates -- \b IN. - \param i1 Initial index in \c Y -- \b IN. - \param i2 Final index in \c Y -- \b IN. - \param max_lix Absolute value of the max value -- \b OUT. - \return Index of interpolation point. - */ - int find_max_lix ( const NOMAD::Point & li , - const std::vector & Y , - int i1 , - int i2 , - NOMAD::Double & max_lix ) const; - - /// Resolution of system \c F.[mu alpha_L]'=[f(Y) 0]' for MFN interpolation. - /** - \param U Matrix \c F=U from the SVD decomposition \c U.W.V' -- \b IN. - \param W Matrix \c W from the SVD decomposition \c U.W.V' -- \b IN. - \param V Matrix \c V from the SVD decomposition \c U.W.V' -- \b IN. - \param bbo_index Blackbox output index -- \b IN. - \param alpha Model parameters -- \b IN. - \param eps Epsilon -- \b IN. - */ - void solve_MFN_system ( double ** U , - double * W , - double ** V , - int bbo_index , - NOMAD::Point & alpha , - double eps ) const; - - /// Resolution of system \c F.alpha=M'.f(Y) for the regression. - /** - \param M Matrix \c M -- \b IN. - \param U Matrix \c F=U from the SVD decomposition \c U.W.V' -- \b IN. - \param W Matrix \c W from the SVD decomposition \c U.W.V' -- \b IN. - \param V Matrix \c V from the SVD decomposition \c U.W.V' -- \b IN. - \param bbo_index Blackbox output index -- \b IN. - \param alpha Model parameters -- \b IN. - \param eps Epsilon -- \b IN. - */ - void solve_regression_system ( double ** M , - double ** U , - double * W , - double ** V , - int bbo_index , - NOMAD::Point & alpha , - double eps ) const; - - /// Display Lagrange polynomials. - /** - \param l Lagrange polynomials -- \b IN. - \param Y Interpolation set -- \b IN. - */ - void display_lagrange_polynomials - ( const std::vector & l , - const std::vector & Y ) const; - -#ifdef MODEL_STATS - mutable NOMAD::Double _Yw; ///< Width of the interpolation set \c Y. - - public: - - /// Access to the width of the interpolation set \c X (or \c Y). - /** - \return The width of the interpolation set. - */ - const NOMAD::Double & get_Yw ( void ) const { return _Yw; } -#endif - - /*-------------------------------------------------------------------------*/ - public: - - /// Constructor. - /** - \param out The NOMAD::Display object -- \b IN. - \param bbot Output types -- \b IN. - \param cache Cache -- \b IN. - \param signature Signature -- \b IN. - */ - Quad_Model ( const NOMAD::Display & out , - const std::vector & bbot , - const NOMAD::Cache & cache , - const NOMAD::Signature & signature ); - - /// Destructor. - virtual ~Quad_Model ( void ); - - /// Evaluate a model at a given point. - /** - \param x The point -- \b IN. - \param alpha Model parameters -- \b IN. - \return Model value. - */ - NOMAD::Double eval ( const NOMAD::Point & x , - const NOMAD::Point & alpha ) const; - - /// Compute model \c h and \c f values at a point. - /** - \param x The point -- \b IN. - \param h_min Value of \c h_min -- \b IN.. - \param h_norm Norm used to compute \c h -- \b IN.. - \param h Value of \c h -- \b OUT. - \param f Value of \c f -- \b OUT. - */ - void eval_hf ( const NOMAD::Point & x , - const NOMAD::Double & h_min , - NOMAD::hnorm_type h_norm , - NOMAD::Double & h , - NOMAD::Double & f ) const; - - - /// Access to the interpolation type. - /** - \return The interpolation type. - */ - const NOMAD::interpolation_type & get_interpolation_type ( void ) const - { - return _interpolation_type; - } - - /// Access to the center of the model. - /** - \return The center. - */ - const NOMAD::Point & get_center ( void ) const { return _center; } - - /// Access to the dimension. - /** - \return The dimension \c n. - */ - int get_n ( void ) const { return _n; } - - /// Access to the number of free variables. - /** - \return The number of free variables \c n. - */ - int get_nfree ( void ) const { return _nfree; } - - /// Access to the model parameters. - /** - \return The model parameters \c alpha. - */ - NOMAD::Point ** get_alpha ( void ) const { return _alpha; } - - /// Check if the model is ready for evaluations. - /** - \return A boolean equal to \c true if the model is ready. - */ - bool check ( void ) const; - - /// Access to the fixed variables. - /** - \param i Variable index -- \b IN. - \return \c true if variable \c i is fixed. - */ - bool variable_is_fixed ( int i ) const { return _fixed_vars[i]; } - - /// Access to the number of interpolation points. - /** - \return The number of interpolation points \c nY=p+1. - */ - int get_nY ( void ) const { return static_cast ( _Y.size() ); } - - /// Access to the condition number. - /** - \return The condition number. - */ - const NOMAD::Double & get_cond ( void ) const { return _cond; } - - /// Access to the error flag. - /** - \return The error flag. - */ - bool get_error_flag ( void ) const { return _error_flag; } - - /// Construct the interpolation set \c Y. - /** - \param center Model center -- \b IN. - \param interpolation_radius Interpolation radius -- \b IN. - \param max_Y_size Maximum number of elements in \c Y -- \b IN. - */ - void construct_Y ( const NOMAD::Point & center , - const NOMAD::Point & interpolation_radius , - int max_Y_size ); - - /// Construct \c m models (one by output). - /** - \param use_WP Use or not well-poisedness -- \b IN. - \param eps Epsilon -- \b IN. - \param max_mpn Maximum \c m+n value for SVD matrices -- \b IN. - \param max_Y_size Maximum number of elements in \c Y -- \b IN. - */ - void construct ( bool use_WP , - double eps , - int max_mpn , - int max_Y_size ); - - /// Define scaling to put all coordinates centered in \c [-r;r]. - /** - - Looks also for fixed variables. - \param r The \c r parameter corresponds to \c MODEL_RADIUS_FACTOR -- \b IN. - */ - void define_scaling ( const NOMAD::Double & r ); - - /// Define scaling based on directions. See paper: Reducing the number of function evaluations in Mesh Adaptive Direct Search algorithms, Audet, Ianni, LeDigabel, Tribes, 2014 - /** - - Looks also for fixed variables. - \param dirP The \c dirP parameter corresponds to set of directions formin a hyper-cube centered on poll center -- \b IN. - \param delta_m The \c delta_m parameter is the dimension of the mesh -- \b IN. - \param epsilon The \c epsilon parameter is the hyper-cube offset from the poll center -- \b IN. - */ - void define_scaling_by_directions ( const std::list & dirP, const NOMAD::Point & delta_m, const NOMAD::Double &epsilon ); - - - /// Scale a point. - /** - \param x The point to scale -- \b IN/OUT. - \return \c true if the scaling worked. - */ - bool scale ( NOMAD::Point & x ) const; - - /// Unscale a point. - /** - \param x The point to unscale -- \b IN/OUT. - \return \c true if the unscaling worked. - */ - bool unscale ( NOMAD::Point & x ) const; - - /// Unscale the gradient at a point. - /** - \param x The grad to unscale -- \b IN/OUT. - \return \c true if the unscaling worked. - */ - bool unscale_grad ( NOMAD::Point & x ) const; - - - /// Check if a caled point is inside the trust radius. - /** - \param x The scaled point -- \b IN. - \return \c true is \c x is in the trust radius. - */ - bool is_within_trust_radius ( const NOMAD::Point & x ) const; - - /// Display the model coefficients. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display_model_coeffs ( const NOMAD::Display & out ) const; - - /// Display the interpolation set \c Y. - /** - \param out The NOMAD::Display object -- \b IN. - \param title Title of the display block -- \b IN - --\b optional (default="interpolation set Y"). - */ - void display_Y ( const NOMAD::Display & out , - const std::string & title = "interpolation set Y" ) const; - - /// Display cumulated error on the interpolation points. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display_Y_error ( const NOMAD::Display & out ) const; - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Evaluator.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Evaluator.cpp deleted file mode 100644 index 388384f4c..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Evaluator.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version (3.7.0.beta)*/ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Quad_Model_Evaluator.cpp - \brief NOMAD::Evaluator subclass for quadratic model optimization (implementation) - \author Sebastien Le Digabel - \date 2010-08-31 - \see Quad_Mopel_Evaluator.hpp -*/ -#include "Quad_Model_Evaluator.hpp" - -/*-----------------------------*/ -/* constructor */ -/*-----------------------------*/ -NOMAD::Quad_Model_Evaluator::Quad_Model_Evaluator -( const NOMAD::Parameters & p , - const NOMAD::Quad_Model & model ) - : - _n ( model.get_n() ) , - _nm1 ( _n-1 ) , - _m ( p.get_bb_nb_outputs() ) , - _x ( NULL ) , - _alpha ( NULL ) , - _model_ready ( model.check() ) -{ - if ( _model_ready ) - { - - int i , j , k , k2 , nalpha = (_n+1)*(_n+2)/2 , nfree = model.get_nfree(); - NOMAD::Point ** model_alpha = model.get_alpha(); - - _x = new double [_n]; - _alpha = new double * [_m]; - - for ( int io = 0 ; io < _m ; ++io ) - { - _alpha[io] = NULL; - if ( model_alpha[io] ) - { - _alpha[io] = new double[nalpha]; - _alpha[io][0] = (*model_alpha[io])[0].value(); - - for ( i = 1 ; i < nalpha ; ++i ) - _alpha[io][i] = 0.0; - - k = 0; - - for ( i = 0 ; i < _n ; ++i ) - { - if ( !model.variable_is_fixed(i) ) - { - ++k; - _alpha[io][i+1 ] = (*model_alpha[io])[k ].value(); - _alpha[io][i+1+_n] = (*model_alpha[io])[k+nfree].value(); - } - } - - k += nfree; - k2 = 2*_n; - - for ( i = 0 ; i < _nm1 ; ++i ) - { - if ( !model.variable_is_fixed(i) ) - { - for ( j = i+1 ; j < _n ; ++j ) - { - ++k2; - if ( !model.variable_is_fixed(j) ) - _alpha[io][k2] = (*model_alpha[io])[++k].value(); - } - } - else - for ( j = i+1 ; j < _n ; ++j ) - ++k2; - } - } - } - } -} - -/*-----------------------------*/ -/* destructor */ -/*-----------------------------*/ -NOMAD::Quad_Model_Evaluator::~Quad_Model_Evaluator ( void ) -{ - if ( _model_ready ) - { - for ( int i = 0 ; i < _m ; ++i ) - if ( _alpha[i] ) - delete [] _alpha[i]; - delete [] _alpha; - delete [] _x; - } -} - -/*------------------------------------------------------------------------*/ -/* evaluate the blackboxes quad model at a given trial point */ -/*------------------------------------------------------------------------*/ -/* */ -/* x is in [-1000;1000] and must be scaled to [-1;1] for the evalutation */ -/* */ -/*------------------------------------------------------------------------*/ -bool NOMAD::Quad_Model_Evaluator::eval_x -( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const -{ - - count_eval=false; - if ( !_model_ready ) - return false; - - int i , j , k; - double z , * alpha , * p; - - for ( i = 0 ; i < _n ; ++i ) - _x[i] = x[i].value() / 1000.0; - - for ( int oi = 0 ; oi < _m ; ++oi ) - { - - alpha = _alpha[oi]; - - if ( alpha ) - { - - z = alpha[0]; - p = _x; - - for ( k = 1 ; k <= _n ; ++k , ++p ) - z += *p * ( alpha[k] + 0.5 * alpha[k+_n] * *p ); - - k += _n-1; - - for ( i = 0 ; i < _nm1 ; ++i ) - for ( j = i+1 ; j < _n ; ++j ) - z += alpha[++k] * _x[i] * _x[j]; - - x.set_bb_output ( oi , z ); - } - - else - x.set_bb_output ( oi , 0.0 ); - } - - count_eval = true; - return true; -} - - -/*------------------------------------------------------------------------*/ -/* evaluate the gradient of a blackbox quad model at a given trial point */ -/*------------------------------------------------------------------------*/ -/* */ -/* x is in [-1000;1000] and must be scaled to [-1;1] for the evalutation */ -/* */ -/*------------------------------------------------------------------------*/ -bool NOMAD::Quad_Model_Evaluator::evalGrad_x -(const NOMAD::Point & x , - NOMAD::Point & g , - const int & output_index , - bool & count_eval ) const -{ - - if ( !_model_ready ) - return false; - - double * alpha ; - - for (int i = 0 ; i < _n ; ++i ) - _x[i] = x[i].value() / 1000.0; - - alpha = _alpha[output_index]; - - if ( !alpha ) - return false; - - int i , j , k ; - - for ( k = 1 ; k <= _n ; ++k ) - g[k-1] = alpha[k] + alpha[k+_n] * _x[k-1]; - - - k += _n-1; - - for ( i = 0 ; i < _nm1 ; ++i ) - for ( j = i+1 ; j < _n ; ++j ) - g[i] += alpha[++k] * _x[j]; - - count_eval = true; - return true; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Evaluator.hpp deleted file mode 100644 index 48df6d114..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Evaluator.hpp +++ /dev/null @@ -1,128 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Quad_Model_Evaluator.hpp - \brief NOMAD::Evaluator subclass for quadratic model optimization (headers) - \author Sebastien Le Digabel - \date 2010-08-31 - \see Quad_Model_Evaluator.cpp - */ -#ifndef __QUAD_MODEL_EVALUATOR__ -#define __QUAD_MODEL_EVALUATOR__ - -#include "Search.hpp" - - -namespace NOMAD { - - /// NOMAD::Evaluator subclass for quadratic model optimization. - class Quad_Model_Evaluator { - - private: - - int _n; ///< Number of variables. - int _nm1; ///< Number of variables minus one. - int _m; ///< Number of blackbox outputs. - double * _x; ///< An evaluation point. - double ** _alpha; ///< Model parameters. - bool _model_ready; ///< \c true if model ready to evaluate. - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param model Model -- \b IN. - */ - Quad_Model_Evaluator ( const NOMAD::Parameters & p , - const NOMAD::Quad_Model & model ); - - /// Destructor. - virtual ~Quad_Model_Evaluator ( void ); - - /// Evaluate the blackboxes at a given trial point. - /** - \param x The trial point -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const; - - /// Evaluate the blackbox functions at a given trial point (#2). - /** - - Non-const version. - - Calls the const version by default. - - May be user-defined. - - Surrogate or true evaluation depending on the value of \c x.is_surrogate(). - \param x The trial point -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) - { - return static_cast(this)->eval_x ( x , h_max, count_eval ); - } - - - - - /// Evaluate the gradient of a blackboxe at a given trial point. - /** - \param x The trial point -- \b IN/OUT. - \param g The gradient of a bb model at the trial point \c x -- \b OUT. - \param output_index The index of the black box. -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - - virtual bool evalGrad_x (const NOMAD::Point & x , - NOMAD::Point & g , - const int & output_index , - bool & count_eval ) const; - - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Search.cpp deleted file mode 100644 index 41aedfdbe..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Search.cpp +++ /dev/null @@ -1,991 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Quad_Model_Search.cpp - \brief Quadratic Model search (implementation) - \author Sebastien Le Digabel - \date 2010-08-30 - \see Quad_Model_Search.hpp - */ -#include "Quad_Model_Search.hpp" - -/*----------------------------------------------------------------*/ -/* the search */ -/*----------------------------------------------------------------*/ -/* Search parameters: */ -/* ------------------ */ -/* */ -/* . MODEL_SEARCH: flag to activate the model search (MS) */ -/* (here its value is NOMAD::QUADRATIC_MODEL) */ -/* */ -/* . MODEL_SEARCH_OPTIMISTIC: if true, the direction from the */ -/* model center to the trial point */ -/* is computed and prossibly used */ -/* in the speculative search */ -/* default=yes */ -/* */ -/* . MODEL_SEARCH_PROJ_TO_MESH: project or not to mesh */ -/* default=yes */ -/* */ -/* . MODEL_SEARCH_MAX_TRIAL_PTS: limit on the number of trial */ -/* points for one search (in */ -/* {1,2,3,4} and with default=4 */ -/* for quadratic models) */ -/* */ -/* . MODEL_RADIUS_FACTOR (r): Y points are in B(xk,r.Delta^p_k) */ -/* default=2.0 */ -/* */ -/* . MODEL_MAX_Y_SIZE: limit on the size of Y; if equal to */ -/* (n+1)(n+2)/2, regression is never used */ -/* default=500 */ -/* */ -/* . MODEL_EVAL_SORT: if true, all evaluation points are sorted */ -/* according to model values; for the model */ -/* search, this is used to order the up to 4 */ -/* trial points. */ -/* default=yes */ -/* */ -/* . MODEL_USE_WP: if true, well-poisedness strategy is applied */ -/* for regression models */ -/* */ -/* . construct model centered around best_feas and best_infeas */ -/* or just around best_feas; */ -/* default=around them both, not modifiable */ -/* */ -/* SVD decomposition parameters: */ -/* ----------------------------- */ -/* . SVD_EPS : epsilon; default=1e-13 */ -/* . SVD_MAX_MPN: max matrix size: default: m+n <= 1500 */ -/* */ -/*----------------------------------------------------------------*/ -void NOMAD::Quad_Model_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - new_feas_inc = new_infeas_inc = NULL; - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - count_search = false; - - _one_search_stats.reset(); - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - - if ( stop ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "Quad_Model_Search::search(): not performed (stop flag is active)" - << std::endl; - return; - } - - // black-box output types: - const std::vector & bbot = _p.get_bb_output_type(); - const std::list & index_obj_list = _p.get_index_obj(); - - if ( index_obj_list.empty() ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "Quad_Model_Search::search(): not performed with no objective function" - << std::endl; - return; - } - - - // initial displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << NOMAD::MODEL_SEARCH << " #" - << _all_searches_stats.get_MS_nb_searches(); - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - // surrogate or truth model evaluations: - NOMAD::eval_type ev_type = - ( _p.get_opt_only_sgte() ) ? NOMAD::SGTE : NOMAD::TRUTH; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "model construction for " << ev_type << std::endl; - - // active cache: - const NOMAD::Cache & cache = mads.get_cache(); - - // active barrier: - const NOMAD::Barrier & barrier = - ( ev_type == NOMAD::SGTE ) ? mads.get_sgte_barrier() : mads.get_true_barrier(); - - // current incumbents: xk[0]=best_feas and xk[1]=best_infeas: - const NOMAD::Eval_Point * xk[2]; - xk[0] = barrier.get_best_feasible (); - xk[1] = barrier.get_best_infeasible(); - - if ( !xk[0] && !xk[1] ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH << " (no incumbent)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - return; - } - - // from this point the search is counted: - count_search = true; - _one_search_stats.add_MS_nb_searches(); - - // display the number of cache points: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "number of points in cache: " - << cache.size() << std::endl; - - // stats: - NOMAD::Stats & stats = mads.get_stats(); - - // number of interpolation points: - int nY[2]; - nY[0] = nY[1] = -1; - - int min_Y_size = _p.get_model_quad_min_Y_size(); - int max_Y_size = _p.get_model_quad_max_Y_size(); - - // use or not well-poisedness: - bool use_WP = _p.get_model_quad_use_WP(); - - // flag to detect model errors: - bool model_ok = false; - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // main loop on the two incumbents (feasible and infeasible): - // --------- - for ( int i_inc = 0 ; i_inc < 2 ; ++i_inc ) - { - - if ( xk[i_inc] ) - { - - // display the model center: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << std::endl << "model center"; - if ( xk[0] && xk[1] ) - out << " (" << i_inc+1 << "/2)"; - out << ": " << *xk[i_inc] << std::endl; - } - - // get and check the signature: - NOMAD::Signature * signature = xk[i_inc]->get_signature(); - if ( !signature ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH << " (no signature)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - return; - } - - // current mesh index: - NOMAD::Point mesh_indices = signature->get_mesh()->get_mesh_indices(); - - - int n = signature->get_n(); - if ( n != xk[i_inc]->size() ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH << " (incompatible signature)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - return; - } - - // compute the interpolation radius: points in Y must be at - // a max distance of ms_radius_factor times Delta^k: - NOMAD::Point Delta , delta; - signature->get_mesh()->get_Delta ( Delta ); - signature->get_mesh()->get_delta ( delta ); - - - NOMAD::Point interpolation_radius = Delta; - interpolation_radius *= _p.get_model_quad_radius_factor(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "mesh indices : (" << mesh_indices << ")" << std::endl - << "mesh size parameter : ( " << delta << " )" << std::endl - << "poll size parameter : ( " << Delta << " )" << std::endl - << "interpolation radius : ( " << interpolation_radius - << " )" << std::endl; - - // creation of the model: - NOMAD::Quad_Model model ( out , bbot , cache , *signature ); - - - - NOMAD::Clock clock; - - // construct interpolation set Y: - // ------------------------------ - model.construct_Y ( *xk[i_inc] , - interpolation_radius , - max_Y_size ); - - nY[i_inc] = model.get_nY(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << "number of points in Y: " << nY[i_inc] - << " (p=" << nY[i_inc]-1; - if ( nY[i_inc] < 2 ) - out << ", not enough"; - out << ")" << std::endl; - } - - if ( nY[i_inc] < 2 ) - _one_search_stats.add_not_enough_pts(); - else - { - -#ifdef DEBUG - out << std::endl; - model.display_Y ( out , "unscaled interpolation set Y" ); -#endif - - // define scaling: - // --------------- - // The min box around the interpolation set Y - // is scaled to [-r;r] with r=MODEL_RADIUS_FACTOR. - model.define_scaling ( _p.get_model_quad_radius_factor() ); - -#ifdef DEBUG - out << std::endl; - model.display_Y ( out , "scaled interpolation set Ys" ); -#endif - - // error check: - if ( model.get_error_flag() ) - _one_search_stats.add_construction_error(); - - // not enough points (this is not counted as an error): - else if ( nY[i_inc] < 2 || - ( min_Y_size < 0 && nY[i_inc] <= model.get_nfree() ) ) - _one_search_stats.add_not_enough_pts(); - - // no error and enough points in Y: - else - { - - // construct model: - // ---------------- - model.construct ( use_WP , NOMAD::SVD_EPS , NOMAD::SVD_MAX_MPN , max_Y_size ); - _one_search_stats.add_construction_time ( clock.get_CPU_time() ); - _one_search_stats.update_nY ( model.get_nY() ); - - // display model characteristics: -#ifdef DEBUG - out << std::endl; - model.display_model_coeffs ( out ); - out << std::endl; - model.display_Y_error ( out ); -#endif - // count model: - if ( ev_type == NOMAD::TRUTH ) - _one_search_stats.add_nb_truth(); - else - _one_search_stats.add_nb_sgte(); - - switch ( model.get_interpolation_type() ) - { - case NOMAD::MFN: - _one_search_stats.add_nb_MFN(); - break; - case NOMAD::WP_REGRESSION: - _one_search_stats.add_nb_WP_regression(); - break; - case NOMAD::REGRESSION: - _one_search_stats.add_nb_regression(); - break; - default: - break; - } - - // check model error flag: - const NOMAD::Double & cond = model.get_cond(); - if ( model.get_error_flag() || - !cond.is_defined() || - cond > NOMAD::SVD_MAX_COND ) - { - if ( model.get_error_flag() ) - _one_search_stats.add_construction_error(); - else - _one_search_stats.add_bad_cond(); - } - else - { - - model_ok = true; - - // optimize model: - // --------------- - NOMAD::Point xf , xi; - - clock.reset(); - - bool optimization_ok = optimize_model ( model , - xk , - i_inc , - display_degree , - out , - xf , - xi , - stop , - stop_reason ); - - _one_search_stats.add_optimization_time ( clock.get_CPU_time() ); - - if ( optimization_ok ) - { - - // get solution(s), project to mesh (+round for integers), and create trial points: - // ---------------------------------------------------------- - if ( xf.is_defined() ) - create_trial_point ( ev_control , - xf , - model , - *signature , - mesh_indices , - delta , - display_degree , - out ); - - if ( xi.is_defined() ) - create_trial_point ( ev_control , - xi , - model , - *signature , - mesh_indices , - delta , - display_degree , - out ); - } - else - _one_search_stats.add_MS_opt_error(); - } - } - } - } - } // end of main loop - - // check the number of times that not enough points could be considered: - if ( nY[0] <= 1 && nY[1] <= 1 ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH - << " (not enough points)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - return; - } - - // check if no model has been computed: - if ( !model_ok ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH - << " (model computation or optimization error)"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - return; - } - - nb_search_pts = ev_control.get_nb_eval_points(); - - // reduce the list of trial points from a maximum - // of 4 points to MODEL_SEARCH_MAX_TRIAL_PTS points: - int max_trial_pts = _p.get_model_search_max_trial_pts(); - if ( max_trial_pts > 4 ) - max_trial_pts = 4; - if ( nb_search_pts > max_trial_pts ) - { - ev_control.reduce_eval_lop ( max_trial_pts ); - nb_search_pts = ev_control.get_nb_eval_points(); - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << "the list of trial points is reduced to " - << nb_search_pts << " point"; - if ( nb_search_pts > 1 ) - out << "s"; - out << std::endl; - } - } - - _one_search_stats.update_MS_max_search_pts ( nb_search_pts ); - - // evaluate the trial points: - // -------------------------- - int bbe = stats.get_bb_eval(); - int sgte_eval = stats.get_sgte_eval (); - int cache_hits = stats.get_cache_hits(); - - new_feas_inc = new_infeas_inc = NULL; - - ev_control.disable_model_eval_sort(); - - ev_control.eval_list_of_points ( _type , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - ev_control.enable_model_eval_sort(); - - // update stats: - _one_search_stats.add_MS_bb_eval ( stats.get_bb_eval () - bbe ); - _one_search_stats.add_MS_sgte_eval ( stats.get_sgte_eval () - sgte_eval ); - _one_search_stats.add_MS_cache_hits ( stats.get_cache_hits() - cache_hits ); - - if ( success == NOMAD::FULL_SUCCESS ) - _one_search_stats.add_MS_success(); - - _one_search_stats.add_MS_pts ( nb_search_pts ); - - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH << " (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } -} - -/*---------------------------------------------------------------*/ -/* project to mesh and create a trial point (private) */ -/*---------------------------------------------------------------*/ -void NOMAD::Quad_Model_Search::create_trial_point -( NOMAD::Evaluator_Control & ev_control , - NOMAD::Point x , - const NOMAD::Quad_Model & model , - NOMAD::Signature & signature , - const NOMAD::Point & mesh_indices , - const NOMAD::Point & delta , - NOMAD::dd_type display_degree , - const NOMAD::Display & out ) -{ - - bool proj_to_mesh = _p.get_model_search_proj_to_mesh(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << "candidate"; - if ( proj_to_mesh ) - out << " (before projection)"; - out << ": ( " << x << " )" << std::endl; - } - - // model center: - NOMAD::Point center = model.get_center(); - - // model search point: - int n = x.size(); - - // projection to mesh: - if ( proj_to_mesh ) - { - x.project_to_mesh ( center , delta , _p.get_lb() , _p.get_ub() ); - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "candidate (after projection) : ( " - << x << " )" << std::endl; - } - - - // Round for integer and binary variables: - bool has_integer=false; - bool has_binary=false; - for (int i=0;i= 0.0 ) - x[i] = x[i].NOMAD::Double::ceil(); - else - x[i] = x[i].NOMAD::Double::floor(); - } - // binary variables: - else if ( _p.get_bb_input_type()[i] == NOMAD::BINARY ) - { - has_binary=true; - if ( x[i]!= 0.0 ) - x[i] = 1.0; - } - } - if ( has_integer && display_degree == NOMAD::FULL_DISPLAY ) - out << "candidate (after rounding integer) : ( " - << x << " )" << std::endl; - - if ( has_binary && display_degree == NOMAD::FULL_DISPLAY ) - out << "candidate (after rounding binary) : ( " - << x << " )" << std::endl; - - - // compare x and center: - if ( x == center ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "candidate rejected (candidate==model center)" << std::endl; - return; - } - - - - NOMAD::Eval_Point * tk = new NOMAD::Eval_Point; - - // if the search is optimistic, a direction is computed (this - // will be used in case of success in the speculative search): - if ( _p.get_model_search_optimistic() ) - { - NOMAD::Direction dir ( n , 0.0 , NOMAD::MODEL_SEARCH_DIR ); - dir.Point::operator = ( x - center ); - tk->set_direction ( &dir ); - } - - tk->set ( n , _p.get_bb_nb_outputs() ); - tk->set_signature ( &signature ); - tk->Point::operator = ( x ); - - // compute model f and h in order to accept or reject the trial point: - NOMAD::Double h0 , f0; // model values of f and h at the center - NOMAD::Double h1 , f1; // model values of f and h at the trial point - - const NOMAD::Double & h_min = _p.get_h_min(); - NOMAD::hnorm_type h_norm = _p.get_h_norm(); - - model.scale ( x ); - - model.eval_hf ( NOMAD::Point (n,0) , h_min , h_norm , h0 , f0 ); - model.eval_hf ( x , h_min , h_norm , h1 , f1 ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - { -#ifdef DEBUG - out << "model at center : h=" << h0 << " f=" << f0 << std::endl; -#endif - out << "model at candidate: h=" << h1 << " f=" << f1 - << std::endl << std::endl; - } - - bool accept_point = true; - - if ( !f1.is_defined() || !h1.is_defined() ) - accept_point = false; - else - { - if ( !f0.is_defined() || !h0.is_defined() ) - accept_point = true; - else - accept_point = (f1 <= f0) || (h1 <= h0); - } - - // we check that the candidate does not correspond to another candidate: - if ( accept_point ) - { - const std::set & eval_lop - = ev_control.get_eval_lop(); - - std::set::const_iterator it , end = eval_lop.end(); - - for ( it = eval_lop.begin() ; it != end ; ++it ) - if ( it->get_point()->NOMAD::Point::operator == ( *tk ) ) - { - accept_point = false; - break; - } - } - - // add the new point to the list of search trial points: - if ( accept_point ) { - ev_control.add_eval_point ( tk , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - f1 , - h1 ); -#ifdef MODEL_STATS - if ( tk ) { - tk->set_mod_use ( 1 ); // 1 for model search - tk->set_cond ( model.get_cond() ); - tk->set_Yw ( model.get_Yw () ); - tk->set_nY ( model.get_nY () ); - tk->set_mh ( h1 ); - tk->set_mf ( f1 ); - } -#endif - - } - else { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "candidate rejected" << std::endl; - _one_search_stats.add_MS_rejected(); - delete tk; - } -} - -/*---------------------------------------------------------------*/ -/* optimize a model (private) */ -/*---------------------------------------------------------------*/ -/* */ -/* . scaling puts points in [-1;1] but the model is optimized */ -/* in [-1000;1000] */ -/* */ -/*---------------------------------------------------------------*/ -bool NOMAD::Quad_Model_Search::optimize_model -( const NOMAD::Quad_Model & model , - const NOMAD::Eval_Point ** xk , - int i_inc , - NOMAD::dd_type display_degree , - const NOMAD::Display & out , - NOMAD::Point & xf , - NOMAD::Point & xi , - bool & stop , - NOMAD::stop_type & stop_reason ) -{ - xf.clear(); - xi.clear(); - - int n = model.get_n(); - bool error = false; - std::string error_str; - int i; - - // initial displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "model optimization"; - if ( xk[0] && xk[1] ) - oss << " (" << i_inc+1 << "/2)"; - out << std::endl << NOMAD::open_block ( oss.str() ); - } - - // parameters creation: - NOMAD::Parameters model_param ( out ); - - // number of variables: - model_param.set_DIMENSION ( n ); - - // blackbox outputs: - model_param.set_BB_OUTPUT_TYPE ( _p.get_bb_output_type() ); - - // barrier parameters: - model_param.set_H_MIN ( _p.get_h_min () ); - model_param.set_H_NORM ( _p.get_h_norm() ); - - // starting points: - { - // 1/2: point (0,...,0): - model_param.set_X0 ( NOMAD::Point ( n , 0.0 ) ); - - // 2/2: model center if different than (0,..,0) and if in [-1;1]: - NOMAD::Point x1 = model.get_center(); - - if ( x1.size() == n && x1.is_complete() ) - { - - model.scale ( x1 ); - - bool diff = false; - bool bnd_ok = true; - - for ( i = 0 ; i < n ; ++i ) - { - - if ( x1[i] != 0 ) - diff = true; - - if ( x1[i].abs() > 1.0 ) - { - bnd_ok = false; - break; - } - - x1[i] *= 1000.0; - } - - if ( diff && bnd_ok ) - model_param.set_X0 ( x1 ); - } - } - - // fixed variables: - for ( i = 0 ; i < n ; ++i ) - if ( model.variable_is_fixed(i) || _p.variable_is_fixed(i) ) - model_param.set_FIXED_VARIABLE(i); - - // no model search and no model ordering: - model_param.set_MODEL_SEARCH ( false ); - model_param.set_MODEL_EVAL_SORT ( false ); - model_param.set_DIRECTION_TYPE(NOMAD::ORTHO_2N); - - - // display: - model_param.set_DISPLAY_DEGREE ( NOMAD::NO_DISPLAY ); - - // mesh: use isotropic mesh - model_param.set_ANISOTROPIC_MESH ( false ); - model_param.set_MESH_UPDATE_BASIS ( 4.0 ); - model_param.set_MESH_COARSENING_EXPONENT ( 1 ); - model_param.set_MESH_REFINING_EXPONENT ( -1 ); - model_param.set_INITIAL_MESH_INDEX ( 0 ); - model_param.set_INITIAL_MESH_SIZE ( NOMAD::Point ( n , 100.0 ) ); - - // maximum number of evaluations: - if (_p.get_nb_obj()==2) - model_param.set_MULTI_OVERALL_BB_EVAL ( 50000 ); - else - model_param.set_MAX_BB_EVAL ( 50000 ); - - - model_param.set_SNAP_TO_BOUNDS ( true ); - - // disable user calls: - model_param.set_USER_CALLS_ENABLED ( false ); - - // set flags: - bool flag_check_bimads , flag_reset_mesh , flag_reset_barriers , flag_p1_active; - NOMAD::Mads::get_flags ( flag_check_bimads , - flag_reset_mesh , - flag_reset_barriers , - flag_p1_active ); - - NOMAD::Mads::set_flag_check_bimads (false ); - NOMAD::Mads::set_flag_reset_mesh ( true ); - NOMAD::Mads::set_flag_reset_barriers ( true ); - NOMAD::Mads::set_flag_p1_active ( false ); - - // bounds: - { - NOMAD::Point lb ( n , -1.0 ); - NOMAD::Point ub ( n , 1.0 ); - - const NOMAD::Point & LB = _p.get_lb(); - const NOMAD::Point & UB = _p.get_ub(); - - if ( LB.is_defined() || UB.is_defined() ) - { - - model.unscale ( lb ); - model.unscale ( ub ); - - for ( i = 0 ; i < n ; ++i ) - { - - if ( LB[i].is_defined() && LB[i] > lb[i] ) - lb[i] = LB[i]; - - if ( UB[i].is_defined() && UB[i] < ub[i] ) - ub[i] = UB[i]; - } - - model.scale ( lb ); - model.scale ( ub ); - - for ( i = 0 ; i < n ; ++i ) - { - if ( ub[i] < lb[i] || lb[i] > 0.0 || ub[i] < 0.0 ) - { - error = true; - error_str = "optimization error: problem with bounds"; - break; - } - lb[i] *= 1000.0; - ub[i] *= 1000.0; - } - } - else - { - lb *= 1000.0; - ub *= 1000.0; - } - - model_param.set_LOWER_BOUND ( lb ); - model_param.set_UPPER_BOUND ( ub ); - } - - if ( !error ) - { - - try - { - - // parameters validation: - model_param.check(); - - // model evaluator creation: - NOMAD::Evaluator *ev; - if (model_param.get_nb_obj()==2) - ev =new NOMAD::Multi_Obj_Quad_Model_Evaluator( model_param , model ); - else - ev=new NOMAD::Single_Obj_Quad_Model_Evaluator(model_param, model); - - // algorithm creation and execution: - NOMAD::Mads mads ( model_param , ev ); - - // Handle the case where nb_bb_obj>=2 but no-bimads (case of PhaseOneSearch) ---> need Phase_One_Evaluator for compute_f - NOMAD::Phase_One_Evaluator * p1ev=NULL; - if ( model_param.get_nb_obj() >= 2 && ! flag_check_bimads ) - { - p1ev = new NOMAD::Phase_One_Evaluator ( model_param , *ev ); - mads.get_evaluator_control().set_evaluator ( p1ev ); - } - - NOMAD::stop_type st = mads.run(); - - delete ev; - if (p1ev) - delete p1ev; - - // check the stopping criterion: - if ( st == NOMAD::CTRL_C || st == NOMAD::MAX_CACHE_MEMORY_REACHED ) { - std::ostringstream oss; - oss << "model optimization: " << st; - error_str = oss.str(); - error = true; - stop = true; - stop_reason = st; - } - - else if ( st == NOMAD::MAX_BB_EVAL_REACHED ) - _one_search_stats.add_MS_max_bbe(); - - // display solution: -#ifdef DEBUG - NOMAD::Display out_tmp = out; - out_tmp.set_degrees ( NOMAD::NORMAL_DISPLAY ); - mads.display ( out_tmp ); -#endif - - // update the stats on the number of model evaluations: - _one_search_stats.update_MS_model_opt ( mads.get_stats().get_bb_eval() ); - - // get the solution(s): - const NOMAD::Eval_Point * best_feas = mads.get_best_feasible (); - const NOMAD::Eval_Point * best_infeas = mads.get_best_infeasible(); - - if ( best_feas ) { - xf = *best_feas; - xf *= 0.001; - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << "best feasible point after unscaling : ( "; - xf.NOMAD::Point::display ( out ); - out << " )" << std::endl; - } - - model.unscale ( xf ); - } - else if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "no feasible solution" << std::endl; - - if ( best_infeas ) { - xi = *best_infeas; - xi *= 0.001; - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << "best infeasible point before unscaling: ( "; - xi.NOMAD::Point::display ( out ); - out << " )" << std::endl; - } - - model.unscale ( xi ); - } - else if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "no infeasible solution" << std::endl; - - if ( !xf.is_defined() && !xi.is_defined() ) { - error = true; - error_str = "optimization error: no solution"; - } - } - catch ( std::exception & e ) { - error = true; - error_str = std::string ( "optimization error: " ) + e.what(); - } - } - - // error before run: - else if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "error before run" << std::endl; - - // reset flags: - NOMAD::Mads::set_flag_check_bimads ( flag_check_bimads ); - NOMAD::Mads::set_flag_reset_mesh ( flag_reset_mesh ); - NOMAD::Mads::set_flag_reset_barriers ( flag_reset_barriers ); - NOMAD::Mads::set_flag_p1_active ( flag_p1_active ); - - - // close display block: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - if ( error ) - out.close_block ( error_str ); - else - out.close_block(); - out << std::endl; - } - - return !error; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Search.hpp deleted file mode 100644 index 30788dfea..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Quad_Model_Search.hpp +++ /dev/null @@ -1,151 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Quad_Model_Search.hpp - \brief Quadratic Model search (headers) - \author Sebastien Le Digabel - \date 2010-08-30 - \see Quad_Model_Search.cpp -*/ -#ifndef __QUAD_MODEL_SEARCH__ -#define __QUAD_MODEL_SEARCH__ - -#include "Mads.hpp" -#include "Single_Obj_Quad_Model_Evaluator.hpp" -#include "Multi_Obj_Quad_Model_Evaluator.hpp" - -namespace NOMAD { - - /// Model search. - class Quad_Model_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - private: - - NOMAD::Model_Stats _one_search_stats; ///< Stats for one search. - NOMAD::Model_Stats _all_searches_stats; ///< Stats for all searches. - - /// Model optimization. - /** - \param model The model -- \b IN. - \param xk The two model centers -- \b IN. - \param i_inc Model center index (\c 0 or \c 1 ) -- \b IN. - \param display_degree Display degree -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param xf Feasible solution \c xf -- \b OUT. - \param xi Infeasible solution \c xi -- \b OUT. - \param stop Stop flag -- \b OUT. - \param stop_reason Stop reason -- \b OUT. - */ - bool optimize_model ( const NOMAD::Quad_Model & model , - const NOMAD::Eval_Point ** xk , - int i_inc , - NOMAD::dd_type display_degree , - const NOMAD::Display & out , - NOMAD::Point & xf , - NOMAD::Point & xi , - bool & stop , - NOMAD::stop_type & stop_reason ); - - /// Project to mesh and create a trial point. - /** - \param ev_control The NOMAD::Evaluator_Control object -- \b IN. - \param x The point coordinates -- \b IN. - \param model The model -- \b IN. - \param signature Signature -- \b IN. - \param mesh_indices Mesh indic -- \b IN. - \param delta Mesh size parameter -- \b IN. - \param display_degree Display degree -- \b IN. - \param out The NOMAD::Display object -- \b IN. - */ - void create_trial_point - ( NOMAD::Evaluator_Control & ev_control , - NOMAD::Point x , - const NOMAD::Quad_Model & model , - NOMAD::Signature & signature , - const NOMAD::Point & mesh_indices , - const NOMAD::Point & delta , - NOMAD::dd_type display_degree , - const NOMAD::Display & out ); - - /*----------------------------------------------------------------------*/ - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Quad_Model_Search ( NOMAD::Parameters & p ) - : NOMAD::Search ( p , NOMAD::MODEL_SEARCH ) {} - - /// Destructor. - virtual ~Quad_Model_Search ( void ) {} - - /// Reset. - virtual void reset ( void ) {} - - /// The quadratic model search. - /** - Based on quadratic regression/MFN interpolation models. - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - //// Display stats. - /** - \param out The NOMAD::Display object -- \b IN. - */ - virtual void display ( const NOMAD::Display & out ) const - { - out << _all_searches_stats; - } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/RNG.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/RNG.cpp deleted file mode 100644 index fd79a3158..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/RNG.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonsmooth Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file RNG.cpp - \brief Custom class for random number generator (implementation) - \author Christophe Tribes and Sebastien Le Digabel - \date 2011-09-28 - \see rng.hpp - */ - -#include "RNG.hpp" -#include - -//** Default values for the provided number seed */ -int NOMAD::RNG::_s = 0; - - -uint32_t NOMAD::RNG::x_def = 123456789; -uint32_t NOMAD::RNG::y_def = 362436069; -uint32_t NOMAD::RNG::z_def = 521288629; -uint32_t NOMAD::RNG::_x = x_def; -uint32_t NOMAD::RNG::_y = y_def; -uint32_t NOMAD::RNG::_z = z_def; - - -void NOMAD::RNG::set_seed(int s) -{ - - if( s<=INT_MAX && s>=0 ) - _s=s; - else - throw NOMAD::Exception ( "RNG.cpp" , __LINE__ , - "NOMAD::RNG::set_seed(): invalid seed. Seed should be in [0,INT_MAX]" ); - - reset_seed_to_default(); - for ( int i=0 ; i<_s ; i++) - NOMAD::RNG::rand(); - - -} - -uint32_t NOMAD::RNG::rand ( void ) -{ - // http://madrabbit.org/~ray/code/xorshf96.c //period 2^96-1 - - uint32_t t; - _x ^= _x << 16; - _x ^= _x >> 5; - _x ^= _x << 1; - - t = _x; - _x = _y; - _y = _z; - _z = t ^ _x ^ _y; - - return _z; -} - - -/*----------------------------------------*/ -/* normal random generators */ -/*----------------------------------------*/ -double NOMAD::RNG::normal_rand( double mean , double var ) -{ - // Box-Muller transformation~\cite{BoMu58} - - double x1 , x2 , w; - - do - { - x1 = NOMAD::RNG::rand(-1.0,1.0); - x2 = NOMAD::RNG::rand(-1.0,1.0); - w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 ); - - w = sqrt( (-2.0 * log( w ) ) / w ); - - return pow ( var,0.5) * x1 * w + mean; -} -double NOMAD::RNG::normal_rand_mean_0 ( double Var , int Nsample ) -{ - double sum = 0.0; - double a=pow( 3.0*Var,0.5 ); - for ( int i=0 ; i. */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file RNG.hpp - \brief Custom class for random number generator - \author Christophe Tribes and Sebastien Le Digabel - \date 2011-09-28 - \see RNG.cpp - */ - -#ifndef __RNG__ -#define __RNG__ - -#include "defines.hpp" -#include "Exception.hpp" - -using namespace std; - -namespace NOMAD { - - - /// Class for random number generator - /** - This class is used to set a seed for the random number generator and - get a random integer or a random double between two values. - */ - class RNG { - - public: - - /// Get current seed - /* - /return An integer in [0,UINT32_MAX]. - */ - static int get_seed ( void ) - { - return static_cast(_s); - } - - /// Reset seed to its default value - static void reset_seed_to_default ( void ) - { - _x=x_def; - _y=y_def; - _z=z_def; - } - - /// Set seed - /* - /param s The seed -- \b IN. - */ - static void set_seed(int s); - - - /// Get a random integer as uint32 - /** This function serves to obtain a random number \c - /return An integer in the interval [0,UINT32_MAX]. - */ - static uint32_t rand(); - - - /// Get a random number having a normal distribution as double - /* - /param a Lower bound -- \b IN. - /param b Upper bound -- \b IN. - /return A double in the interval [a,b]. - */ - static double rand(double a, double b) - { - return a+((b-a)*NOMAD::RNG::rand())/UINT32_MAX; - } - - /// Get a random number approaching a normal distribution (N(0,Var)) as double - // A series of Nsample random numbers Xi in the interval [-sqrt(3*Var);+sqrt(3*Var)] is used -> E[Xi]=0, Var(Xi)=var - // see http://en.wikipedia.org/wiki/Central_limit_theorem - /* - /param Nsample Number of samples for averaging -- \b IN. - /param Var Variance of the target normal distribution -- \b IN. - /return A double in the interval [-sqrt(3*Var);+sqrt(3*Var)]. - */ - static double normal_rand_mean_0( double Var=1 , int Nsample=12 ) ; - - - /// Get a random number approaching a normal distribution ( N(Mean,Var) ) as double - /* - /param Mean Mean of the target normal distribution -- \b IN. - /param Var Variance of the target normal distribution -- \b IN. - /return A random number. - */ - static double normal_rand( double Mean=0 , double Var=1 ) ; - - - private: - - static uint32_t x_def,y_def,z_def,_x,_y,_z; ///< Default parameter value for the random number generator (_s used as the seed). - static int _s; - }; -} - - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Random_Pickup.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Random_Pickup.cpp deleted file mode 100644 index ce1f737fa..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Random_Pickup.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Random_Pickup.cpp - \brief Class for randomly pick up integers (implementation) - \author Sebastien Le Digabel - \date 2010-04-07 - \see Random_Pickup.hpp -*/ -#include "Random_Pickup.hpp" - -/*---------------------------------------------------------*/ -/* constructor */ -/*---------------------------------------------------------*/ -NOMAD::Random_Pickup::Random_Pickup ( int n ) - : _n0 ( n ) , - _n ( n ) , - _elts ( new int[n] ) -{ - for ( int i = 0 ; i < n ; ++i ) - _elts[i] = i; -} - -/*---------------------------------------------------------*/ -/* reset */ -/*---------------------------------------------------------*/ -void NOMAD::Random_Pickup::reset ( void ) -{ - _n = _n0; - for ( int i = 0 ; i < _n ; ++i ) - _elts[i] = i; -} - -/*---------------------------------------------------------*/ -/* randomly pick up an element */ -/*---------------------------------------------------------*/ -int NOMAD::Random_Pickup::pickup ( void ) -{ - if ( _n == 0 ) - return 0; - int ind = NOMAD::RNG::rand()%_n; - int tmp = _elts[ind]; - if ( ind < _n - 1 ) { - _elts[ind ] = _elts[_n-1]; - _elts[_n-1] = tmp; - } - --_n; - - return tmp; -} - -/*---------------------------------------------------------*/ -/* cancel the last pick up */ -/*---------------------------------------------------------*/ -void NOMAD::Random_Pickup::cancel_last_pickup ( void ) -{ - if ( _n < _n0 ) - ++_n; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Random_Pickup.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Random_Pickup.hpp deleted file mode 100644 index f5c824c9b..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Random_Pickup.hpp +++ /dev/null @@ -1,98 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Random_Pickup.hpp - \brief Class for randomly pick up integers (headers) - \author Sebastien Le Digabel - \date 2010-04-07 - \see Random_Pickup.cpp -*/ -#ifndef __RANDOM_PICKUP__ -#define __RANDOM_PICKUP__ - -#include -#include -#include "Uncopyable.hpp" -#include "RNG.hpp" - -namespace NOMAD { - - /// Class for randomly pick up integers. - /** - - The integers are chosen in [0;n-1] and are distinct. - - Example displaying 5 different integers in [0;4]: - \code - NOMAD::Random_Pickup rp(5); - for ( int i = 0 ; i < 5 ; ++i ) - std::cout << rp.pickup() << std::endl; - \endcode - */ - class Random_Pickup : private NOMAD::Uncopyable { - - private: - - int _n0; ///< Initial value of \c n. - int _n; ///< Current value of \c n. - int * _elts; ///< Elements that have not been chosen yet. - - public: - - /// Constructor. - /** - \param n -- The integer \c n defining the range - of values that can be picked up -- \b IN. - */ - Random_Pickup ( int n ); - - /// Destructor. - virtual ~Random_Pickup ( void ) { delete [] _elts; } - - /// Reset. - void reset ( void ); - - /// Randomly pick up an element in [0;n-1]. - /** - \return The element. - */ - int pickup ( void ); - - /// Cancel the last pick up. - void cancel_last_pickup ( void ); - - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/SMesh.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/SMesh.cpp deleted file mode 100644 index f9f7445f6..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/SMesh.cpp +++ /dev/null @@ -1,340 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file SMesh.cpp - \brief Class for the MADS mesh (implementation) - \author Sebastien Le Digabel - \date 2010-04-06 - \see SMesh.hpp - */ -#include "SMesh.hpp" - - - -/*-----------------------------------------------------------*/ -/* update the mesh */ -/*-----------------------------------------------------------*/ -void NOMAD::SMesh::update ( NOMAD::success_type success , const NOMAD::Direction *dir) // , const NOMAD::OrthogonalMesh * mesh ) -{ - // defaults: - // full success: lk = lk - 1 - // failure : lk = lk + 1 - - - if ( success == NOMAD::FULL_SUCCESS ) - { - _mesh_index -= _coarsening_step; - if ( _mesh_index < -NOMAD::L_LIMITS ) - _mesh_index = -NOMAD::L_LIMITS; - } - else if ( success == NOMAD::UNSUCCESSFUL ) - _mesh_index -= _refining_step; - - if ( _mesh_index > _max_mesh_index ) - _max_mesh_index = _mesh_index; - - - if ( _mesh_index < _min_mesh_index ) - _min_mesh_index = _mesh_index; -} - -/*-----------------------------------------------------------*/ -/* Update the provided mesh indices (the Mesh is unchanged). */ -/*-----------------------------------------------------------*/ -void NOMAD::SMesh::update ( NOMAD::success_type success , NOMAD::Point & mesh_indices, const NOMAD::Direction *dir ) const -{ - - if ( mesh_indices.is_defined() ) - { - for (int i=0; i < mesh_indices.size() ; i++) - { - if ( success == NOMAD::FULL_SUCCESS ) - { - mesh_indices[i] -= _coarsening_step; - if ( mesh_indices[i] < -NOMAD::L_LIMITS ) - mesh_indices[i] = -NOMAD::L_LIMITS; - } - else if ( success == NOMAD::UNSUCCESSFUL ) - mesh_indices[i] -= _refining_step; - } - } -} - - -/*-----------------------------------------------------------*/ -/* manually set the mesh index */ -/*-----------------------------------------------------------*/ -void NOMAD::SMesh::set_mesh_indices ( const NOMAD::Point & r ) -{ - if (!r.is_defined()) - _mesh_index=0; - else - _mesh_index=r[0].NOMAD::Double::round(); - - if ( _mesh_index > _max_mesh_index ) - _max_mesh_index = _mesh_index; - if ( _mesh_index < _min_mesh_index ) - _min_mesh_index = _mesh_index; -} - - - -/*-----------------------------------------------------------*/ -/* set the limit mesh index (max value) */ -/*-----------------------------------------------------------*/ -void NOMAD::SMesh::set_limit_mesh_index ( int l ) -{ - - _limit_mesh_index=l; - -} - - - -/*-----------------------------------------------------------*/ -/* display */ -/*-----------------------------------------------------------*/ -void NOMAD::SMesh::display ( const NOMAD::Display & out ) const -{ - out << "n : " << get_n() << std::endl - << "mesh update basis : " << _update_basis << std::endl - << "mesh coarsening step: " << _coarsening_step << std::endl - << "mesh refining step : " << _refining_step << std::endl - << "initial mesh size : " - << "(" << _delta_0 << " )" << std::endl; - out << "minimal mesh size : "; - if ( _delta_min.is_defined() ) - out << "(" << _delta_min << " )" << std::endl; - else - out << "none"; - out << std::endl - << "minimal poll size : "; - if ( _Delta_min.is_defined() ) - out << "(" << _Delta_min << " )" << std::endl; - else - out << "none"; - out << std::endl; -} - -/*----------------------------------------------------------*/ -/* check the stopping conditions on the minimal poll size */ -/* and on the minimal mesh size */ -/*----------------------------------------------------------*/ -void NOMAD::SMesh::check_min_mesh_sizes ( bool & stop , - NOMAD::stop_type & stop_reason ) const -{ - if ( stop ) - return; - - // 1. mesh index tests: - if ( abs ( _mesh_index ) > NOMAD::L_LIMITS ) - { - stop = true; - stop_reason = NOMAD::L_LIMITS_REACHED; - } - - // 2. delta_k^p (poll size) tests: - if ( check_min_poll_size_criterion ( ) ) - { - stop = true; - stop_reason = NOMAD::DELTA_P_MIN_REACHED; - } - - // 3. delta_k^m (mesh size) tests: - if ( check_min_mesh_size_criterion ( ) ) - { - stop = true; - stop_reason = NOMAD::DELTA_M_MIN_REACHED; - } -} - -/*-----------------------------------------------------------*/ -/* check the minimal poll size (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::SMesh::check_min_poll_size_criterion ( ) const -{ - if ( !_Delta_min.is_defined() ) - return false; - NOMAD::Point Delta; - return get_Delta ( Delta ); -} - -/*-----------------------------------------------------------*/ -/* check the minimal mesh size (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::SMesh::check_min_mesh_size_criterion ( ) const -{ - if ( !_delta_min.is_defined() ) - return false; - NOMAD::Point delta; - return get_delta ( delta ); -} - -/*----------------------------------------------------------------*/ -/* get delta (mesh size parameter) */ -/* delta^k = delta^0 \tau^{ell_0^+ - ell_k^+} */ -/*----------------------------------------------------------------*/ -/* the function also returns true if one value is < delta_min */ -/* (stopping criterion MIN_MESH_SIZE) */ -/*----------------------------------------------------------------*/ -bool NOMAD::SMesh::get_delta ( NOMAD::Point & delta ) const -{ - delta.reset ( _n ); - - // power_of_tau = tau^{ max{0,l0} - max{0,lk} }: - NOMAD::Double power_of_tau - = pow ( _update_basis.value() , - ( (_initial_mesh_index > 0) ? _initial_mesh_index : 0) - - ( (_mesh_index > 0) ? _mesh_index : 0) ); - - bool stop = false; - - // delta^k = power_of_tau * delta^0: - for ( int i = 0 ; i < _n ; ++i ) - { - delta[i] = _delta_0[i] * power_of_tau; - if ( !stop && _delta_min.is_defined() && delta[i] < _delta_min[i] ) - stop = true; - - } - - return stop; -} - -/*----------------------------------------------------------------*/ -/* get delta_max (the larget mesh size) */ -/*----------------------------------------------------------------*/ -NOMAD::Point NOMAD::SMesh::get_delta_max ( ) const -{ - - NOMAD::Point delta_max ( _n ); - - // power_of_tau = tau^{ max{0,l0} - max{0,lk} }: - NOMAD::Double power_of_tau - = pow ( _update_basis.value() , - ( (_initial_mesh_index > 0) ? _initial_mesh_index : 0) - - ( (_min_mesh_index > 0) ? _min_mesh_index : 0) ); - - // delta^k = power_of_tau * delta^0: - for ( int i = 0 ; i < _n ; ++i ) - delta_max[i] = _delta_0[i] * power_of_tau; - - return delta_max; -} - - -/*-------------------------------------------------------------------*/ -/* get Delta (poll size parameter) */ -/* Delta^k = Delta^m_k \tau^{ |ell_k|/2 } */ -/* = delta^0 \tau^{ell_0^+ - ell_k^+ + |ell_k|/2} */ -/*-------------------------------------------------------------------*/ -/* the function also returns true if all values are < Delta_min */ -/*-------------------------------------------------------------------*/ -bool NOMAD::SMesh::get_Delta ( NOMAD::Point & Delta ) const -{ - - Delta.reset ( _n ); - - // power_of_tau = tau^{ max{0,l0} - max{0,lk} + |lk|/2}: - NOMAD::Double power_of_tau - = pow ( _update_basis.value() , abs(_mesh_index) / 2.0 + - ( (_initial_mesh_index > 0) ? _initial_mesh_index : 0) - - ( (_mesh_index > 0) ? _mesh_index : 0) ); - - bool stop = true; - bool mps_def = _Delta_min.is_complete(); - - // Delta^k = power_of_tau * Delta^0: - for ( int i = 0 ; i < _n ; ++i ) - { - Delta[i] = _Delta_0[i] * power_of_tau; - if ( !mps_def || Delta[i] >= _Delta_min[i] ) - stop = false; - - if ( _Delta_min.is_defined() && _Delta_min[i].is_defined() && Delta[i] < _Delta_min[i] ) - Delta[i]=_Delta_min[i]; - } - - return stop; -} - - -NOMAD::Double NOMAD::SMesh::scale_and_project(int i, NOMAD::Double l) const -{ - - NOMAD::Point delta; - NOMAD::Point Delta; - get_delta ( delta ); - get_Delta ( Delta ); - - - if ( delta.is_defined() && Delta.is_defined() && i <= _n) - { - NOMAD::Double d= Delta[i] / delta[i] * l; - return d.NOMAD::Double::round()*delta[i]; - } - else - throw NOMAD::Exception ( "SMesh.cpp" , __LINE__ , - "Mesh scaling and projection cannot be performed!" ); - -} - - - - -NOMAD::Point NOMAD::SMesh::get_mesh_ratio_if_success ( void ) const -{ - - NOMAD::Double power_of_tau - = pow ( _update_basis.value() , - ( (_initial_mesh_index > 0) ? _initial_mesh_index : 0) - - ( (_mesh_index > 0) ? _mesh_index : 0) ); - - NOMAD::Double power_of_tau_if_success - = pow ( _update_basis.value() , - ( (_initial_mesh_index > 0) ? _initial_mesh_index : 0) - - ( (_mesh_index - _coarsening_step > 0) ? _mesh_index - _coarsening_step : 0) ); - - try - { - NOMAD::Double ratio_scalaire = power_of_tau_if_success/power_of_tau; - return NOMAD::Point( _n , ratio_scalaire ); - } - catch ( NOMAD::Double::Invalid_Value & ) - { - return NOMAD::Point( _n,-1 ); - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/SMesh.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/SMesh.hpp deleted file mode 100644 index 666b2871d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/SMesh.hpp +++ /dev/null @@ -1,288 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file SMesh.hpp - \brief Class for the static orthogonal MADS mesh (headers) - \author Christophe Tribes - \date 2010-04-06 - \see OrthogonalMesh.cpp SMesh.cpp - */ -#ifndef __SMESH__ -#define __SMESH__ - -#include "Point.hpp" -#include "OrthogonalMesh.hpp" - -namespace NOMAD { - - /// Class for the MADS orthogonal static mesh. - /** - - The static mesh is defined with the basic directions and a - mesh size parameter delta^k. - - The mesh size parameter is defined with a single mesh index (the integer r^k) - and the initial mesh size delta^0 for all coordinates. - - The poll size parameter Delta^k (single value for all coordinates) is not - used to define the mesh but to define the poll trial points. - - At each MADS iteration the mesh is updated with - delta^k+1 = tau^w+ delta^k and w+ >= 0 (dominating iteration) - or with - delta^k+1 = tau^w- delta^k and w- < 0 (iteration failure). - The mesh is not changed after improving iterations. - - Mesh and poll size parameters are stored as NOMAD::Point objects - (one value for each variable). The scaling is done once based on initial mesh size. - - See the MADS papers for more details on the mesh. - */ - - class SMesh : public NOMAD::OrthogonalMesh { - - private: - - int _initial_mesh_index; - int _mesh_index; - int _min_mesh_index; ///< Minimal value reached by the mesh index - int _max_mesh_index; ///< Maximal value reached by the mesh index - - /*--------------------------------------------------------------*/ - - /// Private affectation operator. - /** - \param m The right-hand side object -- \b IN. - */ - const SMesh & operator = ( const SMesh & m ); - - /// Check the minimal poll size criterion. - bool check_min_poll_size_criterion ( ) const; - - /// Check the minimal mesh size criterion. - bool check_min_mesh_size_criterion ( ) const; - - /*--------------------------------------------------------------*/ - - public: - - /// Constructor. - /** - \param delta_0 Initial mesh size delta_0 -- \b IN. - \param Delta_min Minimal poll size Delta_min (may be undefined) -- \b IN. - \param delta_min Minimal mesh size delta_min (may be undefined) -- \b IN. - \param mesh_update_basis Mesh update basis (tau), default=4 -- \b IN. - \param mesh_coarsening_step Mesh coarsening step (w+), default=1 -- \b IN. - \param mesh_refining_step Mesh refining step (w-), default=-1 -- \b IN. - \param initial_mesh_index Initial mesh index ell_0, default=0 -- \b IN. - \param limit_max_mesh_index Limit max of the mesh index, default=L_LIMITS -- \b IN. - \param fixed_variables Fixed variables -- \b IN. - */ - SMesh ( const NOMAD::Point & delta_0 , - const NOMAD::Point & Delta_min , - const NOMAD::Point & delta_min , - const NOMAD::Point & fixed_variables , - NOMAD::Double mesh_update_basis=4.0, - int mesh_coarsening_step=1, - int mesh_refining_step=-1, - int initial_mesh_index=0, - int limit_max_mesh_index=NOMAD::L_LIMITS) - : NOMAD::OrthogonalMesh ( delta_0, - Delta_min, - delta_min, - fixed_variables, - mesh_update_basis, - mesh_coarsening_step, - mesh_refining_step , - limit_max_mesh_index ), - _initial_mesh_index ( initial_mesh_index ), - _mesh_index ( _initial_mesh_index ), - _min_mesh_index ( initial_mesh_index ), - _max_mesh_index ( initial_mesh_index ) {} - - - /// Copy constructor. - /** - \param m The copied object -- \b IN. - */ - SMesh ( const SMesh & m ) - : OrthogonalMesh(m) , - _initial_mesh_index ( m._initial_mesh_index ), - _mesh_index ( m._initial_mesh_index ), - _min_mesh_index( m._initial_mesh_index ), - _max_mesh_index ( m._initial_mesh_index ) {} - - /// Destructor. - virtual ~SMesh ( void ) - { - _delta_0.clear(); - _Delta_0.clear(); - _delta_min.clear(); - _Delta_min.clear(); - } - - - /// Access to the mesh index. - /** - \return A Point with the mesh index. - */ - const NOMAD::Point get_mesh_indices ( void ) const - { - return NOMAD::Point( 1 , NOMAD::Double(_mesh_index) ); - } - - /// Access to the min mesh index reached so far. - /** - \return A Point with the mesh index. - */ - const NOMAD::Point get_min_mesh_indices ( void ) const - { - return NOMAD::Point( 1 , NOMAD::Double(_min_mesh_index) ); - } - - - /// Access to the max mesh index reached so far. - /** - \return A Point with the mesh index. - */ - const NOMAD::Point get_max_mesh_indices ( void ) const - { - return NOMAD::Point( 1 , NOMAD::Double(_max_mesh_index) ); - } - - - /// Manually set the mesh index using a point. (set_mesh_indices for consistency with XMesh) - /** - \param r The mesh index provided as a point -- \b IN. - */ - void set_mesh_indices ( const NOMAD::Point & r ); - - - - /// Manually set the limit mesh index used for termination criterion (max value for SMesh). - /** - \param l The limit mesh index for all coordinates -- \b IN. - */ - void set_limit_mesh_index ( int l ); - - - - /// Test if finest mesh so far. - /** - \return True if mesh index greater or equal to the maximal mesh index; False otherwise. - */ - bool is_finest(void) const {return _mesh_index >= _max_mesh_index; } - - - /// Access to the mesh ratios after a success - /** - \return A point with the ratio for each coordinate - */ - NOMAD::Point get_mesh_ratio_if_success( void ) const; - - - /// Update the provided mesh indices (the Mesh is unchanged). - /** - \param success Type of success of the iteration -- \b IN. - \param mesh_indices The mesh indices before and after the update -- \b IN/OUT. - \param dir The direction that is considered (opt) -- \b IN. - */ - void update ( NOMAD::success_type success , NOMAD::Point & mesh_indices, const NOMAD::Direction *dir=NULL ) const ; - - - /// Update the Mesh. - /** - \param success Type of success of the iteration -- \b IN. - \param dir The direction that is considered (opt) -- \b IN. - */ - void update ( NOMAD::success_type success , const NOMAD::Direction *dir=NULL); - - - /// Reset the mesh to its original size (mesh indices). - void reset ( void ) - { - set_mesh_indices( NOMAD::Point(1,NOMAD::Double(_initial_mesh_index))) ; - _min_mesh_index=_initial_mesh_index ; - _max_mesh_index=_initial_mesh_index; - } - - /// Access to the mesh size parameter delta^k. - /** - \param delta The mesh size parameter delta^k -- \b OUT. - \return A boolean equal to \c true if all values are - strictly inferior than the associated minimal - mesh size delta_min - (stopping criterion MIN_MESH_SIZE). - */ - virtual bool get_delta ( NOMAD::Point & delta ) const ; - - /// Access to the larget mesh size so far. - /** - \return delta_max The largest mesh size reached so far -- \b OUT. - */ - NOMAD::Point get_delta_max ( void ) const ; - - /// Access to the poll size parameter Delta^k. - /** - \param Delta The poll size parameter Delta^k -- \b OUT. - \return A boolean equal to \c true if all values are - strictly inferior than the associated minimal - mesh size Delta_min - (stopping criterion MIN_POLL_SIZE). - */ - virtual bool get_Delta ( NOMAD::Point & Delta ) const ; - - /// Check the stopping conditions on the minimal poll and mesh sizes. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - void check_min_mesh_sizes ( bool & stop , - NOMAD::stop_type & stop_reason ) const; - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - - /// Scale and project the ith component of a vector on the mesh - /** - \param i The vector component number -- \b IN. - \param l The vector component value -- \b IN. - \return The ith component of a vector after mesh scaling and projection - */ - NOMAD::Double scale_and_project(int i, NOMAD::Double l) const ; - - - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Search.hpp deleted file mode 100644 index 0cafeba9d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Search.hpp +++ /dev/null @@ -1,125 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Search.hpp - \brief Generic class for search strategies (headers) - \author Sebastien Le Digabel - \date 2010-04-08 -*/ -#ifndef __SEARCH__ -#define __SEARCH__ - -#include "Evaluator_Control.hpp" - -namespace NOMAD { - - // Forward declarations. - class Mads; - - /// Generic class for search strategies. - /** - This is an abstract class (it is not possible to create NOMAD::Search objects). - */ - class Search { - - protected: - - NOMAD::Parameters & _p; ///< Parameters. - NOMAD::search_type _type; ///< Search type. - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param t Search type -- \b IN. - */ - Search ( NOMAD::Parameters & p , - NOMAD::search_type t ) - : _p ( p ) , - _type ( t ) {} - - /// Destructor. - virtual ~Search ( void ) {} - - /// The search. - /** - - Has to be implemented by every NOMAD::Search subclass. - - Pure virtual method. - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search - ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) = 0; - - /// Reset. - virtual void reset ( void ) {} - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - virtual void display ( const NOMAD::Display & out ) const {} - - }; - - /// Display a NOMAD::Search object. - /** - \param out The NOMAD::Display object -- \b IN. - \param s The NOMAD::Search object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Search & s ) { - s.display ( out ); - return out; - } - -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Set_Element.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Set_Element.hpp deleted file mode 100644 index a7da9c007..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Set_Element.hpp +++ /dev/null @@ -1,166 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Set_Element.hpp - \brief Element of a set (headers) - \author Sebastien Le Digabel - \date 2010-04-12 -*/ -#ifndef __SET_ELEMENT__ -#define __SET_ELEMENT__ - -namespace NOMAD { - - // forward declarations: - class Double; - class Eval_Point; - - /// Generic class for elements of a \c std::set. - /** - This is an abstract class (it is not possible to create NOMAD::Set_Element objects). - */ - template - class Set_Element { - - private: - -#ifdef MEMORY_DEBUG - static int _cardinality; ///< Number of NOMAD::Set_Element objects in memory. - static int _max_cardinality; ///< Max number of NOMAd::Set_Element objects in memory. -#endif - - const T * _el; ///< A pointer to the element. - - /// Affectation operator. - /** - \param se The right-hand side object -- \b IN. - */ - Set_Element & operator = ( const Set_Element & se ); - - /// Copy constructor. - /** - \param se The copied object -- \b IN. - */ - Set_Element ( const Set_Element & se ); - - public: - - /// Constructor. - /** - \param el A pointer on the element -- \b IN. - */ - explicit Set_Element ( const T * el ) : _el ( el ) - { -#ifdef MEMORY_DEBUG - ++Set_Element::_cardinality; - if ( Set_Element::_cardinality > Set_Element::_max_cardinality ) - ++Set_Element::_max_cardinality; -#endif - } - - /// Destructor. - virtual ~Set_Element ( void ) - { -#ifdef MEMORY_DEBUG - --Set_Element::_cardinality; -#endif - } - - /// Specific NOMAD::Priority_Eval_Point elements of comparison. - /** - - Only NOMAD::Priority_Eval_Point::get_priority_criteria() does something. - - \see Priority_Eval_Point.hpp . - \param c1 A real -- \b IN. - \param c2 A real -- \b IN. - \param c3 A real -- \b IN. - \param c4 A real -- \b IN. - \param c5 A real -- \b IN. - \param c6 A real -- \b IN. - */ - virtual void get_priority_criteria ( NOMAD::Double & c1 , - NOMAD::Double & c2 , - NOMAD::Double & c3 , - NOMAD::Double & c4 , - NOMAD::Double & c5 , - NOMAD::Double & c6 ) const {} - /// Comparison operator. - /** - - Has to be implemented by every NOMAD::Set_Element subclass. - - Pure virtual method. - \param se The right-hand side object -- \b IN. - */ - virtual bool operator < ( const Set_Element & se ) const = 0; - - /// Access to the element. - /** - \return A pointer to the element. - */ - const T * get_element ( void ) const { return _el; } - - /// Set an element. - /** - \param el A pointer to the element -- \b IN. - */ - void set_element ( const T * el ) { _el = el; } - -#ifdef MEMORY_DEBUG - - /// Access to the number of NOMAD::Set_Element objects in memory. - /** - \return Number of NOMAD::Set_Element objects in memory. - */ - static int get_cardinality ( void ) { return Set_Element::_cardinality; } - - /// Access to the max number of NOMAD::Set_Element objects in memory. - /** - \return Max number of NOMAD::Set_Element objects in memory. - */ - static int get_max_cardinality ( void ) { return Set_Element::_max_cardinality; } - -#endif - }; - -#ifdef MEMORY_DEBUG - - /// Initialization of _cardinality. - template int NOMAD::Set_Element::_cardinality = 0; - - /// Initialization of _max_cardinality. - template int NOMAD::Set_Element::_max_cardinality = 0; -#endif -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature.cpp deleted file mode 100644 index eabaf056d..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature.cpp +++ /dev/null @@ -1,1092 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Signature.cpp - \brief Evaluation point signature (implementation) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Signature.hpp - */ -#include "Signature.hpp" -#include "SMesh.hpp" -#include "XMesh.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -#ifdef MEMORY_DEBUG -int NOMAD::Signature::_cardinality = 0; -int NOMAD::Signature::_max_cardinality = 0; -#endif - -bool NOMAD::Signature::_warning_has_been_displayed=false; - -/*--------------------------------------------------*/ -/* constructor 1 */ -/*--------------------------------------------------*/ -NOMAD::Signature::Signature -( int n , - const std::vector & input_types , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - bool use_smesh , - bool anisotropic_mesh , - const NOMAD::Point & initial_poll_size , - const NOMAD::Point & min_poll_size , - const NOMAD::Point & min_mesh_size , - NOMAD::Double & mesh_update_basis , - NOMAD::Double & poll_update_basis , - int & mesh_coarsening_exponent, - int & mesh_refining_exponent, - int initial_mesh_index , - const NOMAD::Point & scaling , - const NOMAD::Point & fixed_variables , - const std::vector & periodic_variables, - std::set & var_groups , - const NOMAD::Display & out ) -: _std ( false ) , -_out ( out ) -{ - // Mesh index starts at 0 for an xmesh and decreases as the mesh size decreases - // The mesh index is reset to 0 as the mesh is reset. - if ( ! use_smesh ) - _mesh=new NOMAD::XMesh(anisotropic_mesh, - initial_poll_size, - min_poll_size, - min_mesh_size, - fixed_variables, - poll_update_basis, // XMesh set poll update basis (default 2) - mesh_coarsening_exponent, - mesh_refining_exponent); - else // Mesh index can be provided for isotropic smesh and increases as the mesh size decreases - _mesh=new NOMAD::SMesh(initial_poll_size, // new initial_poll_size ~ old initial mesh size - min_poll_size, - min_mesh_size, - fixed_variables, - mesh_update_basis, // SMesh set mesh update basis (default 4) - mesh_coarsening_exponent, - mesh_refining_exponent, - initial_mesh_index ); - - init ( n , - input_types , - lb , - ub , - scaling , - fixed_variables , - periodic_variables , - var_groups ); - -#ifdef MEMORY_DEBUG - ++NOMAD::Signature::_cardinality; - if ( NOMAD::Signature::_cardinality > NOMAD::Signature::_max_cardinality ) - ++NOMAD::Signature::_max_cardinality; -#endif -} - -/*--------------------------------------------------*/ -/* constructor 2 */ -/*--------------------------------------------------*/ -NOMAD::Signature::Signature -( int n , - const std::vector & input_types , - const NOMAD::Point & initial_poll_size , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - const std::set & direction_types , - const std::set & sec_poll_dir_types , - const NOMAD::Display & out ) -: _std ( false ) , -_out ( out ) -{ - if ( static_cast ( input_types.size() ) != n ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::Signature(): bad argument: input_types" ); - - // Default mesh is isotropic xmesh - //------------------------------------------ - _mesh=new NOMAD::XMesh (false, - initial_poll_size, - NOMAD::Point(), - NOMAD::Point(), - NOMAD::Point()); - - - // automatic creation of groups of variables: - // ------------------------------------------ - std::set var_groups; - - { - std::set vi_cbi; // list of cont./bin./int. variables - std::set vi_cat; // list of categorical variables - - for ( int i = 0 ; i < n ; ++i ) - if ( input_types[i] != NOMAD::CATEGORICAL ) - vi_cbi.insert(i); - else - vi_cat.insert(i); - - // creation of a group for cont./bin./int. variables: - if ( !vi_cbi.empty() ) - var_groups.insert ( new NOMAD::Variable_Group ( vi_cbi , - direction_types , - sec_poll_dir_types , - out ) ); - - // creation of a group for categorical variables: - if ( !vi_cat.empty() ) - var_groups.insert ( new NOMAD::Variable_Group ( vi_cat , - direction_types , - sec_poll_dir_types, - out ) ); - - } - - // init: - // ----- - init ( n , - input_types , - lb , - ub , - NOMAD::Point() , - NOMAD::Point() , - std::vector() , - var_groups ); - - // delete the temporary groups of variables: - std::set::iterator - it , end = var_groups.end(); - - for ( it = var_groups.begin() ; it != end ; ++it ) - delete *it; - -#ifdef MEMORY_DEBUG - ++NOMAD::Signature::_cardinality; - if ( NOMAD::Signature::_cardinality > NOMAD::Signature::_max_cardinality ) - ++NOMAD::Signature::_max_cardinality; -#endif -} - -/*--------------------------------------------------*/ -/* copy constructor */ -/*--------------------------------------------------*/ -NOMAD::Signature::Signature ( const NOMAD::Signature & s ) -: _lb ( s._lb ) , -_ub ( s._ub ) , -_scaling ( s._scaling ) , -_fixed_variables ( s._fixed_variables ) , -_input_types ( s._input_types ) , -_all_continuous ( s._all_continuous ) , -_has_categorical ( s._has_categorical ) , -_periodic_variables ( s._periodic_variables ) , -_std ( false ) , -_feas_success_dir ( s._feas_success_dir ) , -_infeas_success_dir ( s._infeas_success_dir ) , -_out (s._out) -{ - - - if (dynamic_cast (s._mesh)) - _mesh = new NOMAD::SMesh (*(static_cast(s._mesh))); - else - _mesh = new NOMAD::XMesh (*(static_cast(s._mesh))); - - std::list::const_iterator it , end = s._var_groups.end(); - for ( it = s._var_groups.begin() ; it != end ; ++it ) - _var_groups.push_back ( new NOMAD::Variable_Group(**it) ); - -#ifdef MEMORY_DEBUG - ++NOMAD::Signature::_cardinality; - if ( NOMAD::Signature::_cardinality > NOMAD::Signature::_max_cardinality ) - ++NOMAD::Signature::_max_cardinality; -#endif -} - -/*--------------------------------------------------*/ -/* destructor */ -/*--------------------------------------------------*/ -NOMAD::Signature::~Signature ( void ) -{ - clear(); -#ifdef MEMORY_DEBUG - --NOMAD::Signature::_cardinality; -#endif -} - -/*--------------------------------------------------------------------------------*/ -/* clear (private method called by destructor and after an exception is thrown) */ -/*--------------------------------------------------------------------------------*/ -void NOMAD::Signature::clear ( void ) -{ - _all_continuous = true; - _has_categorical = false; - _std = false; - reset_var_groups(); - _feas_success_dir.clear(); - _infeas_success_dir.clear(); - _lb.clear(); - _ub.clear(); - _scaling.clear(); - _fixed_variables.clear(); - _input_types.clear(); - _periodic_variables.clear(); - delete _mesh; - -} - -/*--------------------------------------------------*/ -/* feasible success direction */ -/*--------------------------------------------------*/ -void NOMAD::Signature::set_feas_success_dir ( const NOMAD::Direction & d ) -{ - if ( d.size() != static_cast(_input_types.size()) ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::set_feas_success_dir(): bad direction" ); - _feas_success_dir = d; -} - -/*--------------------------------------------------*/ -/* infeasible success direction */ -/*--------------------------------------------------*/ -void NOMAD::Signature::set_infeas_success_dir ( const NOMAD::Direction & d ) -{ - if ( d.size() != static_cast(_input_types.size()) ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::set_infeas_success_dir(): bad direction" ); - _infeas_success_dir = d; -} - - -/*--------------------------------------------------*/ -/* initializations (private) */ -/*--------------------------------------------------*/ -void NOMAD::Signature::init -( int n , - const std::vector & input_types , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - const NOMAD::Point & scaling , - const NOMAD::Point & fixed_variables , - const std::vector & periodic_variables , - std::set & var_groups ) -{ - // reset directions: - _feas_success_dir.clear(); - _infeas_success_dir.clear(); - - // check the dimension (n): - if ( n <= 0 ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: n" ); - - // bounds: - if ( lb.empty() ) - _lb.reset ( n ); - else if ( lb.size() == n ) - _lb = lb; - else - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: lb" ); - if ( ub.empty() ) - _ub.reset ( n ); - else if ( ub.size() == n ) - _ub = ub; - else - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: ub" ); - - // scaling: - if ( scaling.empty() ) - _scaling.reset ( n ); - else if ( scaling.size() == n ) - _scaling = scaling; - else - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: scaling" ); - int i; - for ( i = 0 ; i < n ; ++i ) - if ( _scaling[i].is_defined() && _scaling[i] == 0.0 ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: scaling (zero value)" ); - - // fixed variables: - if ( fixed_variables.empty() ) - _fixed_variables.reset ( n ); - else if ( fixed_variables.size() == n ) - _fixed_variables = fixed_variables; - else - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: fixed_variables" ); - - // periodic variables: - _periodic_variables = periodic_variables; - if ( !_periodic_variables.empty() ) - { - - if ( static_cast(periodic_variables.size()) != n ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: periodic_variables" ); - - for ( i = 0 ; i < n ; ++i ) - if ( _periodic_variables[i] && ( !_lb[i].is_defined() || !_ub[i].is_defined() ) ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): incompatible periodic variables" ); - } - - // input types: - if ( static_cast(input_types.size()) != n ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: input_types" ); - _input_types = input_types; - _all_continuous = true; - _has_categorical = false; - - for ( i = 0 ; i < n ; ++i ) - { - - if ( (_lb[i].is_defined() || _ub[i].is_defined() ) && _input_types[i] == NOMAD::CATEGORICAL && _out.get_gen_dd()>=NOMAD::NORMAL_DISPLAY && !_warning_has_been_displayed ) - { - _out << NOMAD::open_block("Warning:") - << "NOMAD::Signature::init(): Providing explicit bounds for categorical variables is irrelevant. Bounds are provided implicitely by the neighbors function." << std::endl - << NOMAD::close_block(); - _warning_has_been_displayed=true; - } - - if ( _fixed_variables[i].is_defined() && ((_lb[i].is_defined() && _fixed_variables[i] < _lb[i]) || (_ub[i].is_defined() && _fixed_variables[i] > _ub[i]) || - ( (_input_types[i] == NOMAD::INTEGER || _input_types[i] == NOMAD::CATEGORICAL ) - && !_fixed_variables[i].is_integer() ) || - ( _input_types[i] == NOMAD::BINARY && !_fixed_variables[i].is_binary() ) ) ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: fixed variable inconsistent with bounds or input types" ); - - if ( _lb[i].is_defined() && _ub[i].is_defined() ) - { - if ( _lb[i].is_defined() && _ub[i].is_defined() && _lb[i].value()> ub[i].value() ) - { - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): bad argument: lower bound must be lower than upper bound!" ); - } - if ( _lb[i] == _ub[i] ) - _fixed_variables[i]=_lb[i]; - } - } - for ( i = 0 ; i < n ; ++i ) - { - if ( _input_types[i] == NOMAD::CATEGORICAL ) - { - _has_categorical = true; - _all_continuous = false; - break; - } - if ( _input_types[i] != NOMAD::CONTINUOUS ) - { - _all_continuous = false; - if ( _has_categorical ) - break; - } - - - } - - // variable groups: - reset_var_groups(); - - std::set::iterator - end = var_groups.end() , it; - bool mod=false; - for ( it = var_groups.begin() ; it != end ; ++it ) - { - - - if ( !(*it)->check ( _fixed_variables , input_types , NULL, mod ) ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): incompatible variable group" ); - - } - - // if the indices in var_groups have been modified than var_groups is reconstructed to ensure proper ordering - if ( mod ) - { - std::set tmp_var_groups; - for ( it = var_groups.begin() ; it != end ; ++it ) - { - tmp_var_groups.insert(*it); - } - var_groups.clear(); - var_groups=tmp_var_groups; - tmp_var_groups.clear(); - - } - - for ( it = var_groups.begin() ; it != end ; ++it ) - _var_groups.push_back( new NOMAD::Variable_Group (**it) ); - - // mesh: - if ( _mesh->get_initial_poll_size().size() != n || - ( _mesh->get_min_mesh_size().is_defined() && _mesh->get_min_mesh_size().size() != n) || - ( _mesh->get_min_poll_size().is_defined() && _mesh->get_min_poll_size().size() != n) ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::init(): mesh arguments with different sizes" ); - - - -} - -/*--------------------------------------------------*/ -/* Access to the number of categorical variables */ -/*--------------------------------------------------*/ -int NOMAD::Signature::get_n_categorical ( void ) const -{ - int n_cat=0; - for (int i = 0 ; i < get_n() ; ++i ) - if ( _input_types[i] == NOMAD::CATEGORICAL ) - n_cat++; - - return n_cat; -} - -/*--------------------------------------------------*/ -/* Access to the number of categorical variables */ -/*--------------------------------------------------*/ -int NOMAD::Signature::get_nb_fixed_variables ( void ) const -{ - int n_fixed=0; - for (int i = 0 ; i < get_n() ; ++i ) - if ( _fixed_variables[i].is_defined() ) - n_fixed++; - - return n_fixed; -} - - - -/*--------------------------------------------------*/ -/* reset */ -/*--------------------------------------------------*/ -void NOMAD::Signature::reset -( int n , - const std::vector & input_types , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - const NOMAD::Point & scaling , - const NOMAD::Point & fixed_variables , - const std::vector & periodic_variables , - std::set & var_groups ) -{ - reset_mesh(); - reset_var_groups(); - init ( n , - input_types , - lb , - ub , - scaling , - fixed_variables , - periodic_variables , - var_groups ); -} - -/*--------------------------------------------------*/ -/* reset_var_groups (private) */ -/*--------------------------------------------------*/ -void NOMAD::Signature::reset_var_groups ( void ) -{ - std::list::const_iterator - end = _var_groups.end() , it; - for ( it = _var_groups.begin() ; it != end ; ++it ) - delete *it; - _var_groups.clear(); -} - -/*----------------------------------------------------------*/ -/* check the compatibility of a point */ -/* . we only check the number of variables */ -/* . other stuff (fixed variables, binary variables,...) */ -/* will be checked by Eval_Point::check() */ -/*----------------------------------------------------------*/ -bool NOMAD::Signature::is_compatible ( const NOMAD::Point & x ) const -{ - if ( get_n() != x.size() || _var_groups.empty() ) - return false; - return true; -} - -/*-----------------------------------------------------*/ -/* compute the directions */ -/*-----------------------------------------------------*/ -void NOMAD::Signature::get_directions ( std::list & dirs , - NOMAD::poll_type poll , - const NOMAD::Point & poll_center ) -{ - - NOMAD::Direction * pd; - int i; - std::list::const_iterator it_dir , end_dir; - std::set::const_iterator it_vi , end_vi; - - int n = get_n(); - NOMAD::Point delta=_mesh->get_delta ( ); - NOMAD::Point Delta=_mesh->get_Delta ( ); - - - // Reset dir_group_index. - // For each signature, a variable_group has a unique set of directions generated and a unique dir_group_index starting by zero (-1 if no dirs) - _dir_group_index=-1; - - // loop on variable groups: - std::list::const_iterator end_vg = _var_groups.end() , it_vg; - for ( it_vg = _var_groups.begin() ; it_vg != end_vg ; ++it_vg ) - { - - const std::set & var_indexes = (*it_vg)->get_var_indexes(); - - // get the directions on a unit nc-sphere for the current group of variables: - std::list dirs_nc; - (*it_vg)->get_directions ( dirs_nc , poll , *_mesh ); // _mesh of all directions - - - // scale with delta and resize the directions to size n; - // also round integer and binary variables: - end_dir = dirs_nc.end(); - if (static_cast(dirs_nc.size())!=0) - ++_dir_group_index; - for ( it_dir = dirs_nc.begin() ; it_dir != end_dir ; ++it_dir ) - { - - dirs.push_back ( NOMAD::Direction ( n , 0.0 , it_dir->get_type(),_dir_group_index) ); - - pd = &(*(--dirs.end())); - - end_vi = var_indexes.end(); - i = 0; - - - for ( it_vi = var_indexes.begin() ; it_vi != end_vi ; ++it_vi ,++i) - { - // Scaling and projection on the mesh - (*pd)[*it_vi] = _mesh->scale_and_project(*it_vi,(*it_dir)[i]); - - // integer variables: - if ( _input_types[*it_vi] == NOMAD::INTEGER ) - { - if ( (*pd)[*it_vi] >= Delta[*it_vi]/3.0 ) - (*pd)[*it_vi] = (*pd)[*it_vi].ceil(); - else if ( (*pd)[*it_vi] <= -Delta[*it_vi]/3.0 ) - (*pd)[*it_vi] = (*pd)[*it_vi].floor(); - else - (*pd)[*it_vi] = (*pd)[*it_vi].round(); - } - - // binary variables: - else if ( _input_types[*it_vi] == NOMAD::BINARY ) - { - if ( (*pd)[*it_vi] != 0.0 ) - (*pd)[*it_vi] = 1.0; - } - - // categorical variables: set direction=0: - else if ( _input_types[*it_vi] == NOMAD::CATEGORICAL ) - (*pd)[*it_vi] = 0.0; - } - - } - } -} - -/*----------------------------------------------------------------*/ -/* get just one direction for a given mesh (used by VNS search) */ -/*----------------------------------------------------------------*/ -void NOMAD::Signature::get_one_direction ( NOMAD::Direction & dir , int ell) const -{ - int i; - std::set::const_iterator it_vi , end_vi; - - // get delta_m (mesh size parameter): - int n = get_n(); - NOMAD::Point delta=_mesh->get_delta ( ); - NOMAD::Point Delta=_mesh->get_Delta ( ); - - dir.reset ( n , 0.0 ); - dir.set_type ( NOMAD::UNDEFINED_DIRECTION ); - - // The mesh indices are modified and must be reset properly once the one direction is obtained - const NOMAD::Point old_mesh_indices=_mesh->get_mesh_indices(); - NOMAD::Point modified_mesh_indices(n,NOMAD::Double(ell)); - _mesh->set_mesh_indices(modified_mesh_indices); - - // loop on variable groups: - std::list::const_iterator end_vg = _var_groups.end() , it_vg; - for ( it_vg = _var_groups.begin() ; it_vg != end_vg ; ++it_vg ) - { - - const std::set & var_indexes = (*it_vg)->get_var_indexes(); - - // get the direction for the current group of variables: - NOMAD::Direction dir_nc ( static_cast(var_indexes.size()) , 0.0 , NOMAD::UNDEFINED_DIRECTION ); - - // get a direction on a unit nc-sphere - if ( (*it_vg)->get_one_direction ( dir_nc ) ) - { - - // scale with delta_m and round integer and binary variables: - end_vi = var_indexes.end(); - i = 0; - for ( it_vi = var_indexes.begin() ; it_vi != end_vi ; ++it_vi ) - { - - dir[*it_vi]=_mesh->scale_and_project(*it_vi,dir_nc[i++]); - - - // integer variables: - if ( _input_types[*it_vi] == NOMAD::INTEGER ) - { - if ( dir[*it_vi] >= Delta[*it_vi]/3.0 ) - dir[*it_vi] = ceil ( dir[*it_vi].value() ); - else if ( dir [*it_vi] <= -Delta[*it_vi]/3.0 ) - dir[*it_vi] = floor ( dir[*it_vi].value() ); - else - { - double x=dir[*it_vi].value(); - dir[*it_vi] = (x>0)? floor(x+0.5): ceil(x-0.5); - } - } - - // binary variables: - else if ( _input_types[*it_vi] == NOMAD::BINARY ) - { - if ( dir[*it_vi] != 0.0 ) - dir[*it_vi] = 1.0; - } - - // categorical variables: set direction=0: - else if ( _input_types[*it_vi] == NOMAD::CATEGORICAL ) - dir[*it_vi] = 0.0; - } - } - } - - // Reset the mesh indices to their previous values - _mesh->set_mesh_indices(old_mesh_indices); -} - -/*----------------------------------*/ -/* scaling */ -/* (done before an evaluation) */ -/*----------------------------------*/ -void NOMAD::Signature::scale ( NOMAD::Point & x ) -{ - int n = get_n(); - if ( n != x.size() ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::scale(x): x.size() != signature.size()" ); - NOMAD::Double sci; - for ( int i = 0 ; i < n ; ++i ) - { - sci = _scaling[i]; - if ( sci.is_defined() ) - x[i] *= sci; - } -} - -/*----------------------------------*/ -/* unscaling */ -/* (done after an evaluation) */ -/*----------------------------------*/ -void NOMAD::Signature::unscale ( NOMAD::Point & x ) -{ - int n = get_n(); - if ( n != x.size() ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::unscale(x): x.size() != signature.size()" ); - NOMAD::Double sci; - for ( int i = 0 ; i < n ; ++i ) - { - sci = _scaling[i]; - if ( sci.is_defined() ) - x[i] /= sci; - } -} - -/*-----------------------------------------------------------------------*/ -/* snap to bounds */ -/*-----------------------------------------------------------------------*/ -/* . returns true if x has been modified */ -/* . supposes that treat_periodic_variables() has already been invoked */ -/* (if periodic variables have been treated, then bounds are */ -/* satisfied and there is no need to snap anymore */ -/*-----------------------------------------------------------------------*/ -bool NOMAD::Signature::snap_to_bounds ( NOMAD::Point & x , NOMAD::Direction * direction ) -{ - int n = get_n(); - if ( n != x.size() ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::snap_to_bounds(x): x.size() != signature.size()" ); - - bool modified = false; - bool no_periodic_var = _periodic_variables.empty(); - - for ( int i = 0 ; i < n ; ++i ) - - if ( no_periodic_var || !_periodic_variables[i] ) - { - - const NOMAD::Double & ubi = _ub[i]; - NOMAD::Double & xi = x[i]; - if ( ubi.is_defined() && xi > ubi ) - { - if (direction) - (*direction)[i] += ubi - xi; - xi = ubi; - modified = true; - } - const NOMAD::Double & lbi = _lb[i]; - if ( lbi.is_defined() && xi < lbi ) - { - if (direction) - (*direction)[i] += (lbi - xi); - xi = lbi; - modified = true; - } - } - - return modified; -} - -/*--------------------------------------------------*/ -/* treat the periodic variables */ -/* returns true if x has been modified */ -/*--------------------------------------------------*/ -bool NOMAD::Signature::treat_periodic_variables ( NOMAD::Point & x , - const NOMAD::Direction * old_dir , - NOMAD::Direction *& new_dir ) -{ - if ( _periodic_variables.empty() ) - return false; - - int n = get_n(); - if ( n != x.size() ) - throw NOMAD::Signature::Signature_Error ( "Signature.cpp" , __LINE__ , *this , - "NOMAD::Signature::treat_periodic_variables(x): x.size() != signature.size()" ); - - new_dir = ( old_dir ) ? new NOMAD::Direction (*old_dir) : NULL; - - bool modified = false; - - for ( int i = 0 ; i < n ; ++i ) - { - - NOMAD::bb_input_type bbit = _input_types[i]; - - - if ( _periodic_variables[i] && !_fixed_variables[i].is_defined() && - ( bbit == NOMAD::CONTINUOUS || bbit == NOMAD::INTEGER ) ) - { - - const NOMAD::Double & ubi = _ub[i]; - const NOMAD::Double & lbi = _lb[i]; - NOMAD::Double & xi = x[i]; - - bool chk = false; - - NOMAD::Double new_x = xi; - while ( new_x > ubi ) - { - new_x += lbi - ubi; - chk = true; - } - - if ( !chk ) - { - while ( new_x < lbi ) - { - new_x += ubi - lbi; - chk = true; - } - } - - if ( chk ) - { - - if ( bbit == NOMAD::INTEGER ) - new_x.round(); - - if (new_dir) - (*new_dir)[i] += new_x - xi; - - x[i] = new_x; - modified = true; - } - } - } - - return modified; -} - -/*--------------------------------------------------*/ -/* display */ -/*--------------------------------------------------*/ -void NOMAD::Signature::display ( const NOMAD::Display & out ) const -{ - if ( _std ) - out << "(standard signature)" << std::endl; - - // dimension: - out << "n : " << get_n() << std::endl; - - // bounds: - out << "lb : "; - if ( _lb.is_defined() ) - out << "( " << _lb << ")"; - else - out << "none"; - out << std::endl; - out << "ub : "; - if ( _ub.is_defined() ) - out << "( " << _ub << ")"; - else - out << "none"; - out << std::endl; - - // scaling: - out << "scaling : "; - if ( _scaling.is_defined() ) - out << "( " << _scaling << ")"; - else - out << "none"; - out << std::endl; - - // fixed variables: - out << "fixed variables : "; - if ( _fixed_variables.is_defined() ) - out << "( " << _fixed_variables << ")"; - else - out << "none"; - out << std::endl; - - // input types: - out << "input types : (" << _input_types << " )" << std::endl; - - // periodic variables: - out << "periodic variables: "; - if ( _periodic_variables.empty() ) - out << "none" << std::endl; - else - { - size_t pvs = _periodic_variables.size(); - out << "{"; - for ( size_t k = 0 ; k < pvs ; ++k ) - out << _periodic_variables[k] << " "; - out << "}" << std::endl; - } - - // success directions: - out << "feas. succ. dir. : "; - if ( _feas_success_dir.is_defined() ) - out << _feas_success_dir << std::endl; - else - out << "none"; - out << std::endl - << "infeas. succ. dir.: "; - if ( _infeas_success_dir.is_defined() ) - out << _infeas_success_dir; - else - out << "none"; - out << std::endl; - - // variable groups: - out << NOMAD::open_block ( "variable groups" ); - int i = 0; - std::list::const_iterator end = _var_groups.end() , it; - for ( it = _var_groups.begin() ; it != end ; ++it ) - { - out << NOMAD::open_block ( "group #" + NOMAD::itos(i++) ) - << **it << NOMAD::close_block(); - } - out.close_block(); - - // mesh: - out << NOMAD::open_block ( "mesh" ) ; - out << "initial poll size: ( " << _mesh->get_initial_poll_size() << " )" << std::endl; - out << "initial mesh size: ( " << _mesh->get_initial_mesh_size() << " )" << std::endl; - out << "minimum mesh size: ( " << _mesh->get_min_mesh_size() << " )" << std::endl; - out << "minimum poll size: ( " << _mesh->get_min_poll_size() << " )" << std::endl; - out << NOMAD::close_block(); -} - -/*-------------------------------------------*/ -/* comparison operator '<' */ -/*-------------------------------------------*/ -/* (success directions are not considered) */ -/*-------------------------------------------*/ -bool NOMAD::Signature::operator < ( const NOMAD::Signature & s ) const -{ - if ( this == &s ) - return false; - - // standard signature: not checked: standard and non-standard signatures can be == - // ( this is tested in Parameters::check() ) - - // dimension: - // ---------- - int n = static_cast(_lb.size()); - int sn = static_cast(s._lb.size()); - - if ( n < sn ) - return true; - if ( sn < n ) - return false; - - // variable groups: - // ---------------- - size_t nvg1 = _var_groups.size(); - size_t nvg2 = s._var_groups.size(); - if ( nvg1 != nvg2 ) - return (nvg1 < nvg2); - - std::list::const_iterator - it1 = _var_groups.begin() , - it2 = s._var_groups.begin() , - end = _var_groups.end(); - - while ( it1 != end ) - { - if ( **it1 < **it2 ) - return true; - if ( **it2 < **it1 ) - return false; - ++it1; - ++it2; - } - - // first check on the periodic variables: - // -------------------------------------- - bool p1_empty = _periodic_variables.empty(); - bool p2_empty = s._periodic_variables.empty(); - if ( p1_empty != p2_empty ) - return p1_empty; - - // first check on the mesh: - // ------------------------ - bool chkm = _mesh->get_min_mesh_size().is_defined(); - bool chkp = _mesh->get_min_poll_size().is_defined(); - - bool s_chkm = s._mesh->get_min_mesh_size().is_defined(); - bool s_chkp = s._mesh->get_min_poll_size().is_defined(); - - if ( _mesh->get_initial_mesh_size() != s._mesh->get_initial_mesh_size() && - _mesh->get_min_mesh_size() != s._mesh->get_min_mesh_size() && - _mesh->get_min_poll_size() != s._mesh->get_min_poll_size() ) - { - if ( chkm != s_chkm ) - return !chkm; - if ( chkp != s_chkp ) - return !chkp; - } - - /*---------------------------*/ - /* loop on all coordinates */ - /*---------------------------*/ - for ( int i = 0 ; i < n ; ++i ) - { - - // input types: - // ------------ - if ( _input_types[i] < s._input_types[i] ) - return true; - if ( s._input_types[i] < _input_types[i] ) - return false; - - // bounds: - // ------- - if ( _lb[i].comp_with_undef ( s._lb[i] ) ) - return true; - if ( s._lb[i].comp_with_undef ( _lb[i] ) ) - return false; - if ( _ub[i].comp_with_undef ( s._ub[i] ) ) - return true; - if ( s._ub[i].comp_with_undef ( _ub[i] ) ) - return false; - - // scaling: - // -------- - if ( _scaling[i].comp_with_undef ( s._scaling[i] ) ) - return true; - if ( s._scaling[i].comp_with_undef ( _scaling[i] ) ) - return false; - - // fixed variables: - // ---------------- - if ( _fixed_variables[i].comp_with_undef ( s._fixed_variables[i] ) ) - return true; - if ( s._fixed_variables[i].comp_with_undef ( _fixed_variables[i] ) ) - return false; - - // periodic variables: - // ------------------- - if ( !p1_empty && _periodic_variables[i] != s._periodic_variables[i] ) - return _periodic_variables[i]; - - // mesh: - // ----- - if ( _mesh->get_initial_mesh_size() != s._mesh->get_initial_mesh_size() && - _mesh->get_min_mesh_size() != s._mesh->get_min_mesh_size() && - _mesh->get_min_poll_size() != s._mesh->get_min_poll_size() ) - { - if ( _mesh->get_initial_mesh_size()[i].comp_with_undef ( s._mesh->get_initial_mesh_size()[i] ) ) - return true; - if ( s._mesh->get_initial_mesh_size()[i].comp_with_undef ( _mesh->get_initial_mesh_size()[i] ) ) - return false; - - - if ( chkm ) - { - if ( _mesh->get_min_mesh_size()[i].comp_with_undef ( s._mesh->get_min_mesh_size()[i] ) ) - return true; - if ( s._mesh->get_min_mesh_size()[i].comp_with_undef ( _mesh->get_min_mesh_size()[i] ) ) - return false; - } - if ( chkp ) - { - if ( _mesh->get_min_poll_size()[i].comp_with_undef ( s._mesh->get_min_poll_size()[i] ) ) - return true; - if ( s._mesh->get_min_poll_size()[i].comp_with_undef ( _mesh->get_min_poll_size()[i] ) ) - return false; - } - } - } - - // both signatures are equal: - return false; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature.hpp deleted file mode 100644 index 04904f0a6..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature.hpp +++ /dev/null @@ -1,552 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Signature.hpp - \brief Evaluation point signature (headers) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Signature.cpp - */ -#ifndef __SIGNATURE__ -#define __SIGNATURE__ - -#include "Variable_Group.hpp" - -namespace NOMAD { - - /// Evaluation point signature. - class Signature { - - private: - -#ifdef MEMORY_DEBUG - static int _cardinality; ///< Number of NOMAD::Signature objects in memory. - static int _max_cardinality; ///< Max number of NOMAD::Signature objects in memory. -#endif - - NOMAD::Point _lb; ///< Lower bounds. - NOMAD::Point _ub; ///< Upper bounds. - NOMAD::Point _scaling; ///< Scaling. - NOMAD::Point _fixed_variables; ///< Fixed variables. - - std::vector _input_types; ///< Input types. - - bool _all_continuous; ///< Flag equal to \c true if all variables are continuous. - bool _has_categorical; ///< Flag equal to \c true if there are categorical variables. - - static bool _warning_has_been_displayed; ///< Flag equal to \c true if the warning has already been displayed - - std::vector _periodic_variables; ///< Periodic variables. - - /// Groups of variables. - /** - Include the directions/ - */ - std::list _var_groups; - - /// Mesh associated to this signature. - NOMAD::OrthogonalMesh *_mesh; ///< Orthogonal mesh - - /** - Flag equal to \c true if the signature is standard - (i.e created in Parameters class). - */ - bool _std; - - // Feasible successful direction. - /** - Mutable since it is not used in - \c operator \c < and have to be often changed. - */ - mutable NOMAD::Direction _feas_success_dir; - - // Infeasible successful direction. - /** - Mutable since it is not used in - \c operator \c < and have to be often changed. - */ - mutable NOMAD::Direction _infeas_success_dir; - - - // Direction group index - int _dir_group_index; - - // Display - NOMAD::Display _out; - - /*---------------------------------------------------------------------------*/ - - /// Initializations. - /** - \param n Number of variables -- \b IN. - \param input_types Types of the variables -- \b IN. - \param lb Lower bounds -- \b IN. - \param ub Upper bounds -- \b IN. - \param scaling Scaling -- \b IN. - \param fixed_variables Fixed variables -- \b IN. - \param periodic_variables Periodic variables -- \b IN. - \param var_groups Groups of variables -- \b IN. - */ - void init - ( int n , - const std::vector & input_types , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - const NOMAD::Point & scaling , - const NOMAD::Point & fixed_variables , - const std::vector & periodic_variables , - std::set & var_groups ); - - /// Reset groups of variables. - void reset_var_groups ( void ); - - /// Clear. - /** - Private method called by the destructor and after an exception is thrown. - */ - void clear ( void ); - - /// Affectation operator. - /** - \param s The right-hand side object. - */ - const Signature & operator = ( const Signature & s ); - - public: - - /*---------------------------------------------------------------------------*/ - - /// Exception class for an invalid signature. - class Signature_Error : public NOMAD::Exception { - public: - /// Constructor. - Signature_Error ( const std::string & file , - int line , - Signature & s , - const std::string & msg ) - : NOMAD::Exception ( file , line , msg ) { s.clear(); } - }; - - /*---------------------------------------------------------------------------*/ - - /// Constructor #1. - /** - Advanced version. - \param n Number of variables -- \b IN. - \param input_types Types of the variables -- \b IN. - \param use_smesh Type of mesh (SMesh, XMesh) -- \b IN. - \param anisotropic_mesh Anisotropy of mesh (XMesh) -- \b IN. - \param initial_poll_size Initial poll size -- \b IN. - \param min_poll_size Minimum poll size -- \b IN. - \param min_mesh_size Minimim mesh size -- \b IN. - \param mesh_update_basis Mesh update basis -- \b IN. - \param poll_update_basis Poll update basis -- \b IN. - \param mesh_coarsening_exponent Mesh coarsening exponent -- \b IN. - \param mesh_refining_exponent Mesh refining exponent -- \b IN. - \param initial_mesh_index Initial mesh index -- \b IN. - \param lb Lower bounds -- \b IN. - \param ub Upper bounds -- \b IN. - \param scaling Scaling -- \b IN. - \param fixed_variables Fixed variables -- \b IN. - \param periodic_variables Periodic variables -- \b IN. - \param var_groups Groups of variables -- \b IN. - \param out Display -- \b IN. - */ - Signature - ( int n , - const std::vector & input_types , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - bool use_smesh , - bool anisotropic_mesh , - const NOMAD::Point & initial_poll_size , - const NOMAD::Point & min_poll_size , - const NOMAD::Point & min_mesh_size , - NOMAD::Double & mesh_update_basis , - NOMAD::Double & poll_update_basis , - int & mesh_coarsening_exponent, - int & mesh_refining_exponent, - int initial_mesh_index , - const NOMAD::Point & scaling , - const NOMAD::Point & fixed_variables , - const std::vector & periodic_variables, - std::set & var_groups , - const NOMAD::Display & out=NOMAD::Display() - ); - - /// Constructor #2. - /** - Basic version that will automatically construct groups of variables. - \param n Number of variables -- \b IN. - \param input_types Types of the variables -- \b IN. - \param initial_poll_size Initial poll size -- \b IN. - \param lb Lower bounds -- \b IN. - \param ub Upper bounds -- \b IN. - \param direction_types Types of directions -- \b IN. - \param sec_poll_dir_types Types of directions for secondary poll -- \b IN. - \param out Display -- \b IN. - */ - Signature ( int n , - const std::vector & input_types , - const NOMAD::Point & initial_poll_size , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - const std::set & direction_types , - const std::set & sec_poll_dir_types , - const NOMAD::Display & out = NOMAD::Display() - ); - - /// Copy constructor. - /** - \param s The copied object. - */ - Signature ( const Signature & s ); - - /// Destructor. - virtual ~Signature ( void ); - - /// Reset. - /** - \param n Number of variables -- \b IN. - \param input_types Types of the variables -- \b IN. - \param lb Lower bounds -- \b IN. - \param ub Upper bounds -- \b IN. - \param scaling Scaling -- \b IN. - \param fixed_variables Fixed variables -- \b IN. - \param periodic_variables Periodic variables -- \b IN. - \param var_groups Groups of variables -- \b IN. - */ - void reset - ( int n , - const std::vector & input_types , - const NOMAD::Point & lb , - const NOMAD::Point & ub , - const NOMAD::Point & scaling , - const NOMAD::Point & fixed_variables , - const std::vector & periodic_variables , - std::set & var_groups ); - - /// Define a signature to be standard. - void set_std ( void ) { _std = true; } - - /// Set a feasible successful direction. - /** - \param dir The direction -- \b IN. - */ - void set_feas_success_dir ( const NOMAD::Direction & dir ); - - /// Set an infeasible successful direction. - /** - \param dir The direction -- \b IN. - */ - void set_infeas_success_dir ( const NOMAD::Direction & dir ); - - /// Reset the feasible successful direction. - void reset_feas_success_dir ( void ) const { _feas_success_dir.clear(); } - - /// Reset the infeasible successful direction. - void reset_infeas_success_dir ( void ) const { _infeas_success_dir.clear(); } - - /// Scaling. - /** - Performed before an evaluation. - \param x The scaled point -- \b IN/OUT. - */ - void scale ( NOMAD::Point & x ); - - /// Unscaling. - /** - Performed after an evaluation. - \param x The unscaled point -- \b IN/OUT. - */ - void unscale ( NOMAD::Point & x ); - - /// Snap to bounds. - /** - - Supposes that \c this->treat_periodic_variables() has already been invoked. - - If periodic variables have been treated, then bounds are - satisfied and there is no need to snap anymore. - \param x The point to snap -- \b IN/OUT. - \param direction A pointer to the direction associated to this point - (may be \c NULL) -- \b IN/OUT. - \return A Boolean equal to \c true if \c x has been modified. - */ - bool snap_to_bounds ( NOMAD::Point & x , NOMAD::Direction * direction ); - - /// Treat the periodic variables. - /** - \param x The point to treat -- \b IN/OUT. - \param old_dir A pointer to the direction associated to this point - (before the treatment; may be \c NULL) -- \b IN. - \param new_dir A pointer to the direction associated to this point - (after the treatment; may be \c NULL) -- \b OUT. - \return A boolean equal to \c true if \c x has been modified. - */ - bool treat_periodic_variables ( NOMAD::Point & x , - const NOMAD::Direction * old_dir , - NOMAD::Direction *& new_dir ); - - /// Access to the lower bounds. - /** - \return The lower bounds. - */ - const NOMAD::Point & get_lb ( void ) const { return _lb; } - - /// Access to the upper bounds. - /** - \return The upper bounds. - */ - const NOMAD::Point & get_ub ( void ) const { return _ub; } - - /// Access to the mesh. - /** - \return The orthogonal mesh. - */ - NOMAD::OrthogonalMesh * get_mesh ( void ) const { return _mesh; } - - - /// Update the Mesh (poll and mesh sizes). - /** - \param success Type of success of the iteration -- \b IN. - \param dir Direction of the iteration (optional) -- \b IN. - */ - void update_mesh ( NOMAD::success_type success, const NOMAD::Direction * dir=NULL ) - { - _mesh->update ( success, dir ); - } - - /// Complete reset of the mesh. - /** - */ - void reset_mesh ( void ) { _mesh->reset(); } - - /// Reset of the mesh indices. - /** - /param mesh_indices - */ - void reset_mesh ( NOMAD::Point & mesh_indices ) { _mesh->set_mesh_indices( mesh_indices); } - - - /// Access to the scaling. - /** - \return The scaling. - */ - const NOMAD::Point & get_scaling ( void ) const { return _scaling; } - - /// Access to the fixed variables. - /** - \return The fixed variables. - */ - const NOMAD::Point & get_fixed_variables ( void ) const { return _fixed_variables; } - - - /// Access to the number of fixed variables. - /** - \return The number of fixed variables. - */ - int get_nb_fixed_variables ( void ) const; - - - - /// Access to the feasible successful direction. - /** - \return The feasible successful direction - (may be undefined). - */ - const NOMAD::Direction & get_feas_success_dir ( void ) const - { - return _feas_success_dir; - } - - /// Access to the infeasible successful direction. - /** - \return The infeasible successful direction - (may be undefined). - */ - const NOMAD::Direction & get_infeas_success_dir ( void ) const - { - return _infeas_success_dir; - } - - /// Access to the periodic variables. - /** - \return The periodic variables. - */ - const std::vector & get_periodic_variables ( void ) const - { - return _periodic_variables; - } - - /// Check if all variables are continuous. - /** - \return A boolean equal to \c true if all variables are continuous. - */ - bool all_continuous ( void ) const { return _all_continuous; } - - /// Check if there are categorical variables. - /** - \return A boolean equal to \c true if there are categorical variables. - */ - bool has_categorical ( void ) const { return _has_categorical; } - - /// Access to the number of categorical variables. - /** - \return Integer equal to the number of categorical variables. - */ - int get_n_categorical ( void ) const ; - - /// Access to the number of variables. - /** - \return The number of variables. - */ - int get_n ( void ) const { return static_cast ( _input_types.size() ); } - - /// Access to the input types. - /** - \return The input types. - */ - const std::vector & get_input_types ( void ) const - { - return _input_types; - } - - /// Access to the input types. - /** - \return The input types. - */ - const std::vector & get_input_type ( void ) const - { - return _input_types; - } - - /// Access to the groups of variables. - /** - \return The groups of variables. - */ - const std::list & get_var_groups ( void ) const - { - return _var_groups; - } - - - /// Check the compatibility of a point. - /** - - Only the number of variables is checked. - - Other criteria (fixed variables, binary variables,...) - are checked by NOMAD::Eval_Point::check(). - \param x The point to check -- \b IN. - \return A boolean equal to \c true if the point is compatible - with the signature. - */ - bool is_compatible ( const NOMAD::Point & x ) const; - - /// Access to the directions. - /** - - The computed directions already include Delta^k_m. - \param dirs List of directions -- \b OUT. - \param poll Type of poll (primary or secondary) -- \b IN. - \param poll_center Poll center -- \b IN. - */ - void get_directions ( std::list & dirs , - NOMAD::poll_type poll , - const NOMAD::Point & poll_center ); - - - /// Access to one direction for a given mesh. - /** - Used for example in the VNS search. - \param dir The direction -- \b OUT. - \param mesh_index Mesh index ell -- \b IN. - */ - void get_one_direction ( NOMAD::Direction & dir , - int mesh_index ) const; - - - /// Comparison operator \c < . - /** - Successful directions are not considered. - \param s The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c s. - */ - bool operator < ( const Signature & s ) const; - - /// Comparison operator \c != . - /** - \param s The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c != \c s. - */ - bool operator != ( const Signature & s ) const - { - return ( (*this < s) || (s < *this) ); - } - -#ifdef MEMORY_DEBUG - - /// Access to the number of NOMAD::Signature objects in memory. - /** - \return Number of NOMAD::Signature objects in memory. - */ - static int get_cardinality ( void ) { return Signature::_cardinality; } - - /// Access to the max number of NOMAD::Signature objects in memory. - /** - \return Max number of NOMAD::Signature objects in memory. - */ - static int get_max_cardinality ( void ) { return Signature::_max_cardinality; } -#endif - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - }; - - /// Display a NOMAD::Signature object. - /** - \param out The NOMAD::Display object -- \b IN. - \param s The NOMAD::Signature object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Signature & s ) { - s.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature_Element.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature_Element.hpp deleted file mode 100644 index 3bc4145ef..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Signature_Element.hpp +++ /dev/null @@ -1,100 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Signature_Element.hpp - \brief Signature inside a set (headers) - \author Sebastien Le Digabel - \date 2010-04-12 -*/ -#ifndef __SIGNATURE_ELEMENT__ -#define __SIGNATURE_ELEMENT__ - -#include "Set_Element.hpp" -#include "Signature.hpp" - -namespace NOMAD { - - /// Signature inside a set of signatures. - class Signature_Element : public NOMAD::Set_Element { - - private: - - /// Affectation operator. - /** - \param se The right-hand side object -- \b IN. - */ - Signature_Element & operator = ( const Signature_Element & se ); - - public: - - /// Constructor. - /** - \param s A pointer to a NOMAD::Signature -- \b IN. - */ - explicit Signature_Element ( const NOMAD::Signature * s ) - : NOMAD::Set_Element ( s ) {} - - /// Copy constructor. - /** - \param se The copied object -- \b IN. - */ - Signature_Element ( const Signature_Element & se ) - : NOMAD::Set_Element ( se.get_element() ) {} - - /// Destructor. - virtual ~Signature_Element ( void ) {} - - /// Comparison operator. - /** - \param se The right-hand side object -- \b IN. - */ - virtual bool operator < ( const NOMAD::Set_Element & se ) const - { - return ( *get_element() < *(se.get_element()) ); - } - - /// Access to the signature. - /** - \return A pointer to the signature. - */ - NOMAD::Signature * get_signature ( void ) const - { - return const_cast ( get_element() ); - } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Single_Obj_Quad_Model_Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Single_Obj_Quad_Model_Evaluator.hpp deleted file mode 100644 index 838f0d3af..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Single_Obj_Quad_Model_Evaluator.hpp +++ /dev/null @@ -1,84 +0,0 @@ - -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version (3.7.0.beta)*/ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Single_Obj_Quad_Model_Evaluator.hpp - \brief NOMAD::Evaluator subclass for quadratic model optimization (headers) - \author Christophe Tribes - \date 2014-06-19 - \see Single_Obj_Quad_Model_Evaluator.cpp - */ -#ifndef __SINGLE_OBJ_QUAD_MODEL_EVALUATOR__ -#define __SINGLE_OBJ_QUAD_MODEL_EVALUATOR__ - -#include "Quad_Model_Evaluator.hpp" -#include "Evaluator.hpp" - -namespace NOMAD { - - /// Single objective NOMAD::Evaluator subclass for quadratic model. - class Single_Obj_Quad_Model_Evaluator : public NOMAD::Quad_Model_Evaluator, public NOMAD::Evaluator { - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param model Model -- \b IN. - */ - Single_Obj_Quad_Model_Evaluator ( const NOMAD::Parameters & p , - const NOMAD::Quad_Model & model ) : NOMAD::Quad_Model_Evaluator(p,model),NOMAD::Evaluator(p){_is_model_evaluator=true;} - - /// Destructor. - virtual ~Single_Obj_Quad_Model_Evaluator ( void ){;} - - - /// Evaluate the blackboxes quad model at a given trial point - /** - \param x point to evaluate -- \b IN/OUT. - \param h_max h_max for barrier -- \b IN. - \param count_eval Count eval if true -- \b IN. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const {return Quad_Model_Evaluator::eval_x(x,h_max,count_eval);} - - - - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Slave.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Slave.cpp deleted file mode 100644 index 5c4437c95..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Slave.cpp +++ /dev/null @@ -1,596 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Slave.cpp - \brief Slave process (implementation) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Slave.hpp - */ -#include "Slave.hpp" - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -int NOMAD::Slave::_rank = -1; -int NOMAD::Slave::_np = -1; -int NOMAD::Slave::_data_sent = 0; -int NOMAD::Slave::_data_rcvd = 0; -bool NOMAD::Slave::_are_running = false; -bool NOMAD::Slave::_stop_ok = false; - -/*----------------------------------------*/ -/* initializations (private) */ -/*----------------------------------------*/ -void NOMAD::Slave::init ( void ) const -{ -#ifdef USE_MPI - MPI_Comm_rank ( MPI_COMM_WORLD, &NOMAD::Slave::_rank ); - MPI_Comm_size ( MPI_COMM_WORLD, &NOMAD::Slave::_np ); -#else - NOMAD::Slave::_rank = 0; - NOMAD::Slave::_np = 1; -#endif - - // Slave::force_quit() will be called if ctrl-c is pressed: - if ( !NOMAD::Slave::is_master() ) { - - NOMAD::Evaluator::force_quit(); - - signal ( SIGTERM , NOMAD::Slave::force_quit ); - signal ( SIGINT , NOMAD::Slave::force_quit ); -#ifndef WINDOWS - signal ( SIGPIPE , NOMAD::Slave::force_quit ); // (ctrl-c during a "| more") -#endif - } -} - -/*----------------------------------------*/ -/* get the process rank */ -/* (static) */ -/*----------------------------------------*/ -int NOMAD::Slave::get_rank ( void ) -{ - if ( NOMAD::Slave::_rank < 0 ) { -#ifdef USE_MPI - MPI_Comm_rank ( MPI_COMM_WORLD, &NOMAD::Slave::_rank ); -#else - NOMAD::Slave::_rank = 0; -#endif - } - return NOMAD::Slave::_rank; -} - -/*----------------------------------------*/ -/* get the number of processes */ -/* (static) */ -/*----------------------------------------*/ -int NOMAD::Slave::get_nb_processes ( void ) -{ - if ( NOMAD::Slave::_np < 0 ) { -#ifdef USE_MPI - MPI_Comm_size ( MPI_COMM_WORLD, &NOMAD::Slave::_np ); -#else - NOMAD::Slave::_np = 1; -#endif - } - return NOMAD::Slave::_np; -} - -/*----------------------*/ -/* run the slave code */ -/*----------------------*/ -void NOMAD::Slave::run ( void ) const -{ -#ifdef USE_MPI - - MPI_Request req; - char signal = 0; - NOMAD::Eval_Point * x = NULL; - bool count_eval = false; - - while ( true ) { - - // receive signal from master: - // --------------------------- - NOMAD::Slave::receive_data ( &signal , 1 , MPI_CHAR , 0 , &req ); - - // slave is ready or not initialized: - NOMAD::Slave::send_data ( &NOMAD::READY_SIGNAL , 1 , MPI_CHAR , 0 , false ); - - NOMAD::Slave::wait_request ( req ); - - // EVAL signal: - // ------------ - if ( signal == NOMAD::EVAL_SIGNAL ) { - - // receive and evaluate the point: - x = eval_point ( count_eval ); - - } - - // RESULT signal: - // -------------- - else if ( signal == NOMAD::RESULT_SIGNAL ) - { - - // send the evaluation result to the master: - send_eval_result ( x , count_eval ); - - delete x; - x = NULL; - } - - // STOP signal: - // ------------ - else if ( signal == NOMAD::STOP_SIGNAL ) - break; - - // WAIT signal: - // ------------ - // else if ( signal == NOMAD::WAIT_SIGNAL ) { - // } - } - - if ( x ) - delete x; - -#endif -} - -/*-----------------------------------------*/ -/* initialize all the slaves */ -/* (static) */ -/*-----------------------------------------*/ -void NOMAD::Slave::init_slaves ( const NOMAD::Display & out ) -{ -#ifdef USE_MPI - - if ( !NOMAD::Slave::is_master() || NOMAD::Slave::_are_running ) - return; - - NOMAD::dd_type display_degree = out.get_gen_dd(); - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "initializing slaves" ); - - MPI_Status status; - MPI_Request ** req = new MPI_Request * [ NOMAD::Slave::_np ]; - int nb_initialized = 0; - int nb_slaves = NOMAD::Slave::_np - 1; - int source; - char signal; - NOMAD::Clock clk; - - // 1. launch requests: - for ( source = 1 ; source < NOMAD::Slave::_np ; ++source ) { - req[source] = new MPI_Request; - NOMAD::Slave::receive_data ( &signal , 1 , MPI_CHAR , source , req[source] ); - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "." << std::endl; - } - - // 2. test requests (with a maximal delay of MAX_REQ_WAIT): - int cnt = 0 , flag; - while ( nb_initialized < nb_slaves && clk.get_real_time() < NOMAD::MAX_REQ_WAIT ) - { - - for ( source = 1 ; source < NOMAD::Slave::_np ; ++source ) - { - - if ( req[source] ) - { - - MPI_Test ( req[source] , &flag , &status ); - - if ( flag ) - { - - MPI_Wait ( req[source] , &status ); - - // send the WAIT signal: - NOMAD::Slave::send_data ( &NOMAD::WAIT_SIGNAL , 1 , MPI_CHAR , source , true ); - - delete req[source]; - req[source] = NULL; - ++nb_initialized; - } - } - } - // a constant is used in order to display only a few '.' : - if ( display_degree == NOMAD::FULL_DISPLAY && cnt%1000000==0 ) - out << "." << std::endl; - - ++cnt; - } - - // 3. delete requests: - std::list err_list; - for ( source = 1 ; source < NOMAD::Slave::_np ; ++source ) - { - if ( req[source] ) - { - err_list.push_back ( source ); - MPI_Cancel ( req[source] ); - delete req[source]; - } - } - delete [] req; - - NOMAD::Slave::_are_running = true; - NOMAD::Slave::_stop_ok = false; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block() << std::endl; - - if ( !err_list.empty() ) - { - - std::ostringstream oss; - oss << "could not initialize slave"; - if ( err_list.size() > 1 ) - { - oss << "s"; - std::list::const_iterator it , end = err_list.end(); - for ( it = err_list.begin() ; it != end ; ++it ) - oss << " #" << *it; - } - else - oss << " #" << *err_list.begin(); - - throw NOMAD::Exception ( "Slave.cpp" , __LINE__ , oss.str() ); - } - -#endif -} - -/*-----------------------------------------*/ -/* stop the slaves */ -/* (static) */ -/*-----------------------------------------*/ -void NOMAD::Slave::stop_slaves ( const NOMAD::Display & out ) -{ -#ifdef USE_MPI - - if ( !NOMAD::Slave::is_master() || NOMAD::Slave::_stop_ok ) - return; - - NOMAD::dd_type display_degree = out.get_gen_dd(); - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "stopping slaves" ); - - int nb_stopped = 0; - int nb_slaves = NOMAD::Slave::_np - 1; - int source; - char signal; - - NOMAD::Clock clk; - - MPI_Status status; - MPI_Request ** req = new MPI_Request * [ NOMAD::Slave::_np ]; - - // 1. launch requests: - for ( source = 1 ; source < NOMAD::Slave::_np ; ++source ) { - req[source] = new MPI_Request; - NOMAD::Slave::receive_data ( &signal , 1 , MPI_CHAR , source , req[source] ); - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "." << std::endl; - } - - // 2. test requests (with a maximal delay of MAX_REQ_WAIT): - int cnt = 0 , flag; - while ( nb_stopped < nb_slaves && clk.get_real_time() < NOMAD::MAX_REQ_WAIT ) { - - for ( source = 1 ; source < NOMAD::Slave::_np ; ++source ) { - - if ( req[source] ) { - - MPI_Test ( req[source] , &flag , &status ); - - if ( flag ) { - - MPI_Wait ( req[source] , &status ); - - // send the STOP signal: - NOMAD::Slave::send_data ( &NOMAD::STOP_SIGNAL , 1 , MPI_CHAR , source , true ); - - delete req[source]; - req[source] = NULL; - ++nb_stopped; - } - } - } - // a constant is used in order to display only a few '.' : - if ( display_degree == NOMAD::FULL_DISPLAY && cnt%1000000==0 ) - out << "." << std::endl; - ++cnt; - } - - NOMAD::Slave::_are_running = false; - NOMAD::Slave::_stop_ok = true; - - // 3. delete requests: - for ( source = 1 ; source < NOMAD::Slave::_np ; ++source ) { - if ( req[source] ) { - MPI_Cancel ( req[source] ); - delete req[source]; - NOMAD::Slave::_stop_ok = false; - } - } - delete [] req; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block() << std::endl; - -#endif -} - -#ifdef USE_MPI - -/*------------------------------------------------------*/ -/* receive data (static, private) */ -/*------------------------------------------------------*/ -int NOMAD::Slave::receive_data ( void * buf , - int count , - MPI_Datatype datatype , - int source , // may be MPI_ANY_SOURCE - MPI_Request * req ) -{ - int tag = ( NOMAD::Slave::is_master() ) ? source : NOMAD::Slave::get_rank(); - - // immediate receive: - if ( req ) { - if ( source == MPI_ANY_SOURCE ) - throw NOMAD::Exception ( "Slave.cpp" , __LINE__ , - "Slave::receive_data(): immediate receive with no source" ); - MPI_Irecv ( buf , count , datatype , source , tag , MPI_COMM_WORLD , req ); - } - - // normal receive: - else { - MPI_Status status; - if ( source == MPI_ANY_SOURCE ) - tag = MPI_ANY_TAG; - MPI_Recv ( buf , count , datatype , source , tag , MPI_COMM_WORLD , &status ); - source = status.MPI_SOURCE; - } - - // stats: - int size; - MPI_Type_size ( datatype , &size ); - NOMAD::Slave::_data_rcvd += count * size; - - return source; -} - -/*------------------------------------------------------*/ -/* send data (static, private) */ -/*------------------------------------------------------*/ -void NOMAD::Slave::send_data ( const void * buf , - int count , - MPI_Datatype datatype , - int dest , - bool ready_send ) -{ - int tag = ( NOMAD::Slave::is_master() ) ? dest : NOMAD::Slave::get_rank(); - - // ready send: - if ( ready_send ) - MPI_Rsend ( const_cast(buf) , count , datatype , - dest , tag , MPI_COMM_WORLD ); - - // normal send: - else - MPI_Send ( const_cast(buf) , count , datatype , - dest , tag , MPI_COMM_WORLD ); - - // stats: - int size; - MPI_Type_size ( datatype , &size ); - NOMAD::Slave::_data_sent += count * size; -} - -/*------------------------------------------------------*/ -/* receive and evaluate an Eval_Point from the master */ -/* (private) */ -/*------------------------------------------------------*/ -NOMAD::Eval_Point * NOMAD::Slave::eval_point ( bool & count_eval ) const -{ - // 1. receive the point: - int itab[3]; - MPI_Request req; - NOMAD::Slave::receive_data ( itab , 3 , MPI_INT , 0 , &req ); - NOMAD::Slave::send_data ( &NOMAD::READY_SIGNAL , 1 , MPI_CHAR , 0 , false ); - NOMAD::Slave::wait_request ( req ); - - int n = itab[0]; - double * dtab = new double[n+1]; - - NOMAD::Slave::receive_data ( dtab , n+1 , MPI_DOUBLE , 0 , &req ); - NOMAD::Slave::send_data ( &NOMAD::READY_SIGNAL , 1 , MPI_CHAR , 0 , false ); - NOMAD::Slave::wait_request ( req ); - - // 2. create the Eval_Point: - int bb_nb_outputs=_p->get_bb_nb_outputs(); - NOMAD::Eval_Point * x = new NOMAD::Eval_Point ( n , bb_nb_outputs ); - for ( int i = 0 ; i < n ; ++i ) - (*x)[i] = dtab[i]; - NOMAD::Double h_max = dtab[n]; - - x->set_tag ( itab[2] ); - x->set_eval_type ( ( itab[1] > 0 ) ? NOMAD::SGTE : NOMAD::TRUTH ); - - delete [] dtab; - - // 3. evaluate the point: - bool eval_ok; - try { - eval_ok = _ev->eval_x ( *x , h_max , count_eval ); - } - catch ( ... ) { - eval_ok = false; - } - - x->set_eval_status ( ( eval_ok ) ? NOMAD::EVAL_OK : NOMAD::EVAL_FAIL ); - - return x; -} - -/*-----------------------------------------------------*/ -/* send an evaluation result to the master (private) */ -/*-----------------------------------------------------*/ -void NOMAD::Slave::send_eval_result ( const NOMAD::Eval_Point * x , - bool count_eval ) const -{ - // receive a signal from the master: - char signal; - NOMAD::Slave::receive_data ( &signal , 1 , MPI_CHAR , 0 , NULL ); - - // send the evaluation result: - int m = _p->get_bb_nb_outputs(); - int s = 2*m+2; - double * dtab = new double [s]; - const NOMAD::Point & bbo = x->get_bb_outputs(); - - // bb_outputs (m values): - for ( int i = 0 ; i < m ; ++i ) { - if ( bbo[i].is_defined() ) { - dtab[i ] = bbo[i].value(); - dtab[i+m] = 1.0; - } - else { - dtab[i ] = NOMAD::INF; - dtab[i+m] = -1.0; - } - } - - // evaluation status: - dtab[2*m] = ( x->get_eval_status() == NOMAD::EVAL_OK ) ? 1.0 : -1.0; - - // count_eval: - dtab[s-1] = ( count_eval ) ? 1.0 : -1.0; - - // send the array: - NOMAD::Slave::send_data ( dtab , s , MPI_DOUBLE , 0 , true ); - - delete [] dtab; -} - -/*---------------------------------------------*/ -/* receive an evaluation result from a slave */ -/*---------------------------------------------*/ -void NOMAD::Slave::receive_eval_result ( int slave_rank , - NOMAD::Eval_Point * x , - bool & eval_ok , - bool & count_eval ) const -{ - // send the RESULT signal to the slave: - NOMAD::Slave::send_data ( &NOMAD::RESULT_SIGNAL , 1 , MPI_CHAR , slave_rank , true ); - - // receive the evaluation result as a double array: - int m = _p->get_bb_nb_outputs(); - int s = 2*m+2; - double * dtab = new double [s]; - - MPI_Request req; - NOMAD::Slave::receive_data ( dtab , s , MPI_DOUBLE , slave_rank , &req ); - NOMAD::Slave::send_data ( &NOMAD::READY_SIGNAL , 1 , MPI_CHAR , slave_rank , false ); - NOMAD::Slave::wait_request ( req ); - - // interpret the array: - for ( int i = 0 ; i < m ; ++i ) - x->set_bb_output ( i , ( dtab[i+m] > 0.0 ) ? dtab[i] : NOMAD::Double() ); - - eval_ok = ( dtab[2*m] > 0.0 ); - - x->set_eval_status ( eval_ok ? NOMAD::EVAL_OK : NOMAD::EVAL_FAIL ); - - count_eval = ( dtab[s-1] > 0.0 ); - - delete [] dtab; -} - -/*-----------------------------------------------------*/ -/* send an Eval_Point to a slave */ -/*-----------------------------------------------------*/ -void NOMAD::Slave::send_eval_point ( const NOMAD::Eval_Point * x , - int slave_rank , - const NOMAD::Double & h_max ) const -{ - char signal; - int itab[3]; - int n = x->size(); - - // n: - itab[0] = n; - - // evaluation type (+1: sgte eval; -1: true eval): - itab[1] = ( x->get_eval_type() == NOMAD::SGTE ) ? 1 : -1; - - // tag of the point: - itab[2] = x->get_tag(); - - // point coordinates: - double * dtab = new double[n+1]; - for ( int i = 0 ; i < n ; ++i ) - dtab[i] = (*x)[i].value(); - dtab[n] = h_max.value(); - - // wait for the slave signal: - NOMAD::Slave::receive_data ( &signal , 1 , MPI_CHAR , slave_rank , NULL ); - - // send n and evaluation type: - NOMAD::Slave::send_data ( itab , 3 , MPI_INT , slave_rank , true ); - - // wait for the slave signal: - NOMAD::Slave::receive_data ( &signal , 1 , MPI_CHAR , slave_rank , NULL ); - - // send the point coordinates: - NOMAD::Slave::send_data ( dtab , n+1 , MPI_DOUBLE , slave_rank , true ); - - delete [] dtab; -} - -/*-----------------------------------------*/ -/* wait for a MPI request */ -/* (static) */ -/*-----------------------------------------*/ -void NOMAD::Slave::wait_request ( MPI_Request & req ) -{ - MPI_Status status; - MPI_Wait ( &req , &status ); -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Slave.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Slave.hpp deleted file mode 100644 index ab232a8ef..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Slave.hpp +++ /dev/null @@ -1,246 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Slave.hpp - \brief Slave process (headers) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Slave.cpp -*/ -#ifndef __SLAVE__ -#define __SLAVE__ - -#include "Evaluator.hpp" - -namespace NOMAD { - - /// Slave process for the parallel version. - class Slave : private NOMAD::Uncopyable { - - private: - - static int _rank; /// Process rank. - static int _np; /// Number of processes. - - static int _data_sent; /// Stats on the sent data. - static int _data_rcvd; /// Stats on the received data. - - static bool _are_running; ///< \c true if the slaves are running. - static bool _stop_ok; ///< \c true if the slaves stopped without error. - - const NOMAD::Parameters * _p; ///< Parameters (may be NULL). - NOMAD::Evaluator * _ev; ///< Evaluator (may be NULL). - - /// Initializations. - void init ( void ) const; - - /// Force quit. - /** - - Called by pressing Ctrl-C. - - Does nothing: the slave will be stopped by the master. - \param signalValue Signal value -- \b IN. - */ - static void force_quit ( int signalValue ) {} - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param ev A pointer to an evaluator -- \b IN. - */ - Slave ( const NOMAD::Parameters & p , NOMAD::Evaluator * ev ) - { _p=&p; _ev=ev; init(); } - - /// Destructor. - virtual ~Slave ( void ) {} - - /// Run the slave code. - void run ( void ) const; - - /// Access to the stat \c _data_sent. - /** - \return The stat \c _data_sent. - */ - static int get_data_sent ( void ) { return Slave::_data_sent; } - - /// Access to the stat \c _data_rcvd. - /** - \return The stat \c _data_rcvd. - */ - static int get_data_rcvd ( void ) { return Slave::_data_rcvd; } - - /// Access to the process rank. - /** - \return The process rank. - */ - static int get_rank ( void ); - - /// Access to the number of processes. - /** - \return The number of processes. - */ - static int get_nb_processes ( void ); - - /// Check if the slaves are running. - /** - \return A boolean equal to \c true if the slaves are running. - */ - static bool are_running ( void ) { return _are_running; } - - /// Check if the current slave is the master. - /** - \return A boolean equal to \c true if the current slave is the master. - */ - static bool is_master ( void ) { return ( Slave::get_rank() == 0 ); } - - /// Initialize all the slaves. - /** - \param out Display -- \b IN. - */ - static void init_slaves ( const NOMAD::Display & out ); - - /// Stop all the slaves. - /** - \param out Display -- \b IN. - */ - static void stop_slaves ( const NOMAD::Display & out ); - -#ifdef USE_MPI - - private: - - /// Receive and evaluate a point from the master. - /** - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A pointer to the point. - */ - NOMAD::Eval_Point * eval_point ( bool & count_eval ) const; - - /// Send an evaluation result to the master. - /** - \param x The evaluation point -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b IN. - */ - void send_eval_result ( const NOMAD::Eval_Point * x , bool count_eval ) const; - - /// Send data. - /** - \param buf Data to send -- \b IN. - \param count Data quantity -- \b IN. - \param datatype Data type -- \b IN. - \param dest Destination -- \b IN. - \param ready_send Flag equal to \c true if \c Rsend is used instead of \c Send - -- \b IN. - */ - static void send_data ( const void * buf , - int count , - MPI_Datatype datatype , - int dest , - bool ready_send ); - - /// Receive data. - /** - \param buf Data to receive -- \b OUT. - \param count Data quantity -- \b IN. - \param datatype Data type -- \b IN. - \param source Source (may be \c MPI_ANY_SOURCE) -- \b IN. - \param req Pointer to a MPI request (may be \c NULL) -- \b IN/OUT. - \return The source. - */ - static int receive_data ( void * buf , - int count , - MPI_Datatype datatype , - int source , - MPI_Request * req ); - - /// Wait for a MPI request. - /** - \param req The request -- \b IN/OUT. - */ - static void wait_request ( MPI_Request & req ); - - public: - - /// Send an evaluation point to a slave. - /** - \param x A pointer to the evaluation point to send -- \b IN. - \param slave_rank Destination -- \b IN. - \param h_max Maximal feasibility value \c h_max -- \b IN. - */ - void send_eval_point ( const NOMAD::Eval_Point * x , - int slave_rank , - const NOMAD::Double & h_max ) const; - - /// Receive an evaluation result from a slave. - /** - \param slave_rank Source -- \b IN. - \param x A pointer to the evaluation point received -- \b OUT. - \param eval_ok Flag indicating if the evaluation succeeded -- \b OUT. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - */ - void receive_eval_result ( int slave_rank , - NOMAD::Eval_Point * x , - bool & eval_ok , - bool & count_eval ) const; - - /// Receive a signal from a slave. - /** - \param signal The signal -- \b OUT. - \return The source. - */ - static int receive_signal ( char & signal ) - { - return Slave::receive_data ( &signal , 1 , MPI_CHAR , MPI_ANY_SOURCE , NULL ); - } - - /// Send a signal to a slave. - /** - \param signal The signal -- \b IN. - \param slave_rank Destination -- \b IN. - */ - static void send_signal ( char signal , int slave_rank ) - { - Slave::send_data ( &signal , 1 , MPI_CHAR , slave_rank , true ); - } - -#endif - }; -} -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Speculative_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Speculative_Search.cpp deleted file mode 100644 index 3379d0dc7..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Speculative_Search.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Speculative_Search.cpp - \brief Speculative search (implementation) - \author Sebastien Le Digabel - \date 2010-04-12 - \see Speculative.hpp - */ -#include "Speculative_Search.hpp" - -/*-------------------------------------------------------------*/ -/* MADS speculative search */ -/*-------------------------------------------------------------*/ -/* x_k = x_{k-1} + \Delta^m_{k-1} d */ -/* s_k = x_{k-1} + \Delta^m_k d if l_{k-1} > 0 */ -/* or x_{k-1} + \tau * \Delta^m_k d otherwise */ -/*-------------------------------------------------------------*/ -/* the directions that we use already contain \Delta^m: */ -/* dir = \Delta^m_{k-1} d */ -/*-------------------------------------------------------------*/ -/* the test ' if (new_feas_inc || new_infeas_inc ) ' is true */ -/* and has already been made in Mads.cpp */ -/*-------------------------------------------------------------*/ -void NOMAD::Speculative_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - // new_feas_inc and new_infeas_inc are used as inputs, - // so do not initialize them to NULL here - - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - count_search = !stop; - - if ( stop ) - return; - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << NOMAD::SPEC_SEARCH; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - //int lkm1; // l_{k-1} - // int lk; // l_k - int n; - NOMAD::Signature * signature; - NOMAD::Point delta_m_k; - NOMAD::Point delta_m_km1; - NOMAD::Point factor; - NOMAD::Point xkm1; - NOMAD::Eval_Point * sk; - const NOMAD::Eval_Point * x[2]; - x[0] = new_feas_inc; - x[1] = new_infeas_inc; - - // Evaluator_Control: - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - for ( int i = 0 ; i < 2 ; ++i ) - { - if ( x[i] && x[i]->get_signature() ) - { - - const NOMAD::Direction * dir = x[i]->get_direction(); - if ( dir && ( dir->is_mads() || dir->get_type()==NOMAD::MODEL_SEARCH_DIR ) ) { - - // get the x_k's signature: - signature = x[i]->get_signature(); - if ( !signature ) - throw NOMAD::Exception ( "Speculative_Search.cpp" , __LINE__ , - "Speculative_Search::search(): could not get the signature" ); - - xkm1 = *x[i] - *dir; - - factor = signature->get_mesh()->get_mesh_ratio_if_success(); - n=signature->get_n(); - for ( int k = 0 ; k < n ; ++k ) - { - if ( factor[k].is_defined() ) - { - if ( factor[k] == 1 ) - { - // factor determined based on mesh type ( default is 4 = mesh_update_basis = 2* poll_update_basis ) - if ( dynamic_cast (signature->get_mesh()) ) - factor[k] = signature->get_mesh()->get_update_basis()*2.0; - else - factor[k] = signature->get_mesh()->get_update_basis(); - - } - else if ( factor[k] == 0 ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "could not compute " << _type << " point: stop" << std::endl - << NOMAD::close_block ( "end of speculative search" ); - stop = true; - stop_reason = NOMAD::MESH_PREC_REACHED; - return; - } - - } - else - factor[k]=0; - - } - NOMAD::Point mesh_indices_k( x[i]->get_signature()->get_mesh()->get_mesh_indices() ); - signature->get_mesh()->update( NOMAD::FULL_SUCCESS, mesh_indices_k , dir ); - - // speculative search point: - NOMAD::Direction new_dir ( n , 0.0 , dir->get_type() ); - new_dir.Point::operator = ( factor * *dir ); - - sk = new NOMAD::Eval_Point; - sk->set ( n , _p.get_bb_nb_outputs() ); - sk->set_signature ( signature ); - sk->set_direction ( &new_dir ); - - sk->Point::operator = ( xkm1 + new_dir ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << "trial point #" << sk->get_tag() - << ": ( "; - sk->Point::display ( out ," " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // add the new point to the list of search trial points: - ev_control.add_eval_point ( sk , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - } - } - - nb_search_pts = ev_control.get_nb_eval_points(); - - // eval_list_of_points:s - // -------------------- - new_feas_inc = new_infeas_inc = NULL; - - ev_control.eval_list_of_points ( _type , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of speculative search (" << success << ")"; - out << NOMAD::close_block ( oss.str() ) << std::endl; - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Speculative_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Speculative_Search.hpp deleted file mode 100644 index 280a64585..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Speculative_Search.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Speculative_Search.hpp - \brief Speculative search (headers) - \author Sebastien Le Digabel - \date 2010-04-12 - \see Speculative.cpp -*/ -#ifndef __SPECULATIVE_SEARCH__ -#define __SPECULATIVE_SEARCH__ - -#include "Search.hpp" -#include "Mads.hpp" - -namespace NOMAD { - - /// Speculative search. - /** - The speculative search consists in looking further away along - the successful direction after an improvement. - */ - class Speculative_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - Speculative_Search ( NOMAD::Parameters & p ) - : NOMAD::Search ( p , NOMAD::SPEC_SEARCH ) {} - - /// Destructor. - virtual ~Speculative_Search ( void ) {} - - /// The speculative search. - /** - - x_k = x_{k-1} + Delta^m_{k-1} d \n - s_k = x_{k-1} + Delta^m_{k-1} d if ell_{k-1} > 0 \n - or tau * Delta^m_{k-1} d otherwise. - - The directions that we use already contain Delta^m: - direction = Delta^m_{k-1} d - - The following test - \code - if ( new_feas_inc || new_infeas_inc ) - \endcode - is equal to \c true and has already been made in \c Mads.cpp. - - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Stats.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Stats.cpp deleted file mode 100644 index 87d5b8361..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Stats.cpp +++ /dev/null @@ -1,365 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Stats.cpp - \brief Algorithm stats (implementation) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Stats.hpp -*/ -#include "Stats.hpp" - -/*---------------------------------------------------------*/ -/* affectation operator */ -/*---------------------------------------------------------*/ -NOMAD::Stats & NOMAD::Stats::operator = ( const NOMAD::Stats & s ) -{ - _eval = s._eval; - _sim_bb_eval = s._sim_bb_eval; - _sgte_eval = s._sgte_eval; - _bb_eval = s._bb_eval; - _block_eval = s._block_eval; - _failed_eval = s._failed_eval; - _cache_hits = s._cache_hits; - _interrupted_eval = s._interrupted_eval; - _iterations = s._iterations; - _nb_poll_searches = s._nb_poll_searches; - _poll_pts = s._poll_pts; - _poll_success = s._poll_success; - _nb_success_dyn_dir= s._nb_success_dyn_dir; - _nb_ext_polls = s._nb_ext_polls; - _ext_poll_pts = s._ext_poll_pts; - _ext_poll_succ = s._ext_poll_succ; - _ext_poll_bb_eval = s._ext_poll_bb_eval; - _ext_poll_descents = s._ext_poll_descents; - _nb_spec_searches = s._nb_spec_searches; - _spec_pts = s._spec_pts; - _spec_success = s._spec_success; - _nb_LH_searches = s._nb_LH_searches; - _LH_pts = s._LH_pts; - _LH_success = s._LH_success; - _nb_cache_searches = s._nb_cache_searches; - _CS_pts = s._CS_pts; - _CS_success = s._CS_success; - _model_stats = s._model_stats; - _nb_VNS_searches = s._nb_VNS_searches; - _VNS_pts = s._VNS_pts; - _VNS_success = s._VNS_success; - _VNS_bb_eval = s._VNS_bb_eval; - _VNS_sgte_eval = s._VNS_sgte_eval; - _nb_usr_searches = s._nb_usr_searches; - _usr_srch_pts = s._usr_srch_pts; - _usr_srch_success = s._usr_srch_success; - _p1_iterations = s._p1_iterations; - _p1_bbe = s._p1_bbe; - _mads_runs = s._mads_runs; - _clock = s._clock; - _stat_sum = s._stat_sum; - _stat_avg = s._stat_avg; - _cnt_avg = s._cnt_avg; - -#ifdef USE_MPI - _asynchronous_success = s._asynchronous_success; - _MPI_data_size = s._MPI_data_size; -#endif - - return *this; -} - -/*---------------------------------------------------------*/ -/* reset the stats */ -/*---------------------------------------------------------*/ -void NOMAD::Stats::reset ( void ) -{ - _eval = - _sim_bb_eval = - _sgte_eval = - _bb_eval = - _block_eval = - _failed_eval = - _cache_hits = - _interrupted_eval = - _iterations = - _nb_poll_searches = - _poll_pts = - _poll_success = - _nb_ext_polls = - _ext_poll_pts = - _ext_poll_succ = - _ext_poll_bb_eval = - _ext_poll_descents = - _nb_spec_searches = - _spec_pts = - _spec_success = - _nb_LH_searches = - _LH_pts = - _LH_success = - _nb_cache_searches = - _CS_pts = - _CS_success = - _nb_VNS_searches = - _VNS_pts = - _VNS_success = - _VNS_bb_eval = - _VNS_sgte_eval = - _nb_usr_searches = - _usr_srch_pts = - _usr_srch_success = - _p1_iterations = - _p1_bbe = - _nb_success_dyn_dir = - _mads_runs = 0; - - _model_stats.reset(); - - _stat_sum.clear(); - _stat_avg.clear(); - _cnt_avg = 0; - -#ifdef USE_MPI - _asynchronous_success = 0; - _MPI_data_size = -1; -#endif - - _clock.reset(); -} - -/*---------------------------------------------------------*/ -/* update stats from another Stats object */ -/*---------------------------------------------------------*/ -/* for_search==true means that this method has been */ -/* invoked from a search */ -/*---------------------------------------------------------*/ -void NOMAD::Stats::update ( const NOMAD::Stats & s , bool for_search ) -{ - _eval += s._eval; - _sim_bb_eval += s._sim_bb_eval; - _sgte_eval += s._sgte_eval; - _bb_eval += s._bb_eval; - _block_eval += s._block_eval; - _failed_eval += s._failed_eval; - _cache_hits += s._cache_hits; - _interrupted_eval += s._interrupted_eval; - _nb_ext_polls += s._nb_ext_polls; - _ext_poll_pts += s._ext_poll_pts; - _ext_poll_succ += s._ext_poll_succ; - _ext_poll_bb_eval += s._ext_poll_bb_eval; - _ext_poll_descents += s._ext_poll_descents; - _nb_LH_searches += s._nb_LH_searches; - _LH_pts += s._LH_pts; - _LH_success += s._LH_success; - _nb_cache_searches += s._nb_cache_searches; - _CS_pts += s._CS_pts; - _CS_success += s._CS_success; - _nb_usr_searches += s._nb_usr_searches; - _usr_srch_pts += s._usr_srch_pts; - _usr_srch_success += s._usr_srch_success; - _nb_success_dyn_dir += s._nb_success_dyn_dir; - -#ifdef USE_MPI - _asynchronous_success += s._asynchronous_success; - _MPI_data_size = s._MPI_data_size; -#endif - - // _stat_sum and _stat_avg: - int tmp = _cnt_avg + s._cnt_avg; - update_stat_sum ( s._stat_sum ); - update_stat_avg ( s._stat_avg ); - _cnt_avg = tmp; - - // specific updates when for_search==false: - if ( !for_search ) { - _nb_poll_searches += s._nb_poll_searches; - _poll_pts += s._poll_pts; - _poll_success += s._poll_success; - _nb_spec_searches += s._nb_spec_searches; - _spec_pts += s._spec_pts; - _spec_success += s._spec_success; - _nb_VNS_searches += s._nb_VNS_searches; - _VNS_pts += s._VNS_pts; - _VNS_success += s._VNS_success; - _VNS_bb_eval += s._VNS_bb_eval; - _VNS_sgte_eval += s._VNS_sgte_eval; - _p1_iterations += s._p1_iterations; - _p1_bbe += s._p1_bbe; - _iterations += s._iterations; - } -} - -/*---------------------------------------------------------*/ -/* update _stat_sum */ -/*---------------------------------------------------------*/ -void NOMAD::Stats::update_stat_sum ( const NOMAD::Double & d ) -{ - if ( !d.is_defined() ) - return; - if ( _stat_sum.is_defined() ) - _stat_sum += d; - else - _stat_sum = d; -} - -/*---------------------------------------------------------*/ -/* update _stat_avg */ -/*---------------------------------------------------------*/ -void NOMAD::Stats::update_stat_avg ( const NOMAD::Double & d ) -{ - if ( !d.is_defined() ) - return; - if ( _stat_avg.is_defined() ) - _stat_avg += d; - else - _stat_avg = d; - ++_cnt_avg; -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Stats::display ( const NOMAD::Display & out ) const -{ - out << "MADS iterations : " << _iterations; - if ( _p1_iterations > 0 ) - out << " (phase one: " << _p1_iterations << ")"; - out << std::endl; - if ( _sgte_cost > 0 ) - out << "bb evaluations (with sgte cost) : " << get_bb_eval(); - else - out << "blackbox evaluations : " << _bb_eval; - out << std::endl; - if ( _block_eval > 0) - out << "Block of evaluations : " << _block_eval; - if ( _p1_bbe > 0 ) - out << " (phase one: " << _p1_bbe << ")"; - out << std::endl; - if ( _sim_bb_eval != _bb_eval ) - out << "simulated blackbox evaluations : " << _sim_bb_eval << std::endl; - out << "evaluations : " << _eval << std::endl; - if ( _sgte_cost > 0 || _sgte_eval > 0 ) - out << "surrogate evaluations : " << _sgte_eval << std::endl; - out << "failed evaluations : " << _failed_eval; - if ( _failed_eval > 0 && _failed_eval==_bb_eval+_sgte_eval ) - out << " (all evaluations failed)"; - out << std::endl; - - out << "interrupted sequences of eval. : " << _interrupted_eval << std::endl; - - if ( _mads_runs > 1 ) - out << "number of MADS runs : " << _mads_runs << std::endl; - - out << "cache hits : " << _cache_hits << std::endl - - << "number of poll searches : " << _nb_poll_searches << std::endl; - if ( _nb_poll_searches > 0 ) - out << "poll successes : " << _poll_success << std::endl - << "poll points : " << _poll_pts << std::endl; - - out << "dyn. direction successes : " << _nb_success_dyn_dir << std::endl; - - if ( _nb_ext_polls > 0 ) - out << "number of extended polls : " << _nb_ext_polls << std::endl - << "number of ext. poll descents : " << _ext_poll_descents << std::endl - << "number of ext. poll successes : " << _ext_poll_succ << std::endl - << "number of ext. poll points : " << _ext_poll_pts << std::endl - << "number of ext. poll bb eval : " << _ext_poll_bb_eval << std::endl; - out << "number of speculative searches : " << _nb_spec_searches << std::endl; - if ( _nb_spec_searches > 0 ) - out << "speculative search successes : " << _spec_success << std::endl - << "speculative search points : " << _spec_pts << std::endl; - out << "number of user searches : " << _nb_usr_searches << std::endl; - if ( _nb_usr_searches > 0 ) - out << "user search successes : " << _usr_srch_success << std::endl - << "user search points : " << _usr_srch_pts << std::endl; - out << "number of LH searches : " << _nb_LH_searches << std::endl; - if ( _nb_LH_searches > 0 ) - out << "LH search successes : " << _LH_success << std::endl - << "LH search points : " << _LH_pts << std::endl; - out << "number of cache searches : " << _nb_cache_searches << std::endl; - if ( _nb_cache_searches > 0 ) - out << "cache search successes : " << _CS_success << std::endl - << "cache search points : " << _CS_pts << std::endl; - out << "number of VNS searches : " << _nb_VNS_searches << std::endl; - if ( _nb_VNS_searches > 0 ) { - out << "VNS search successes : " << _VNS_success << std::endl - << "VNS search points : " << _VNS_pts << std::endl - << "VNS blackbox evaluations : " << _VNS_bb_eval << std::endl; - if ( _VNS_sgte_eval > 0 ) - out << "VNS surrogate evaluations : " << _VNS_sgte_eval << std::endl; - } - if ( _model_stats.get_nb_models() > 0 ) { -#ifdef DEBUG - out << NOMAD::open_block ( "model stats" ) - << _model_stats - << NOMAD::close_block(); -#else - out << "number of models built : " - << _model_stats.get_nb_models() << std::endl - << "number of model searches : " - << _model_stats.get_MS_nb_searches() << std::endl; - if ( _model_stats.get_MS_nb_searches() > 0 ) { - out << "model search successes : " - << _model_stats.get_MS_success() << std::endl - << "model search points : " - << _model_stats.get_MS_pts() << std::endl - << "model search blackbox eval. : " - << _model_stats.get_MS_bb_eval() << std::endl; - if ( _model_stats.get_MS_sgte_eval() > 0 ) - out << "model search sgte evaluations : " - << _model_stats.get_MS_sgte_eval() << std::endl; - } -#endif - } - else - out << "no model has been constructed" << std::endl; -#ifdef USE_MPI - out << "number of asynchronous successes: " << _asynchronous_success << std::endl; - out << "total size of MPI communications: "; - if ( _MPI_data_size < 0 ) - out << "-"; - else - out.display_size_of ( _MPI_data_size ); - out << std::endl; -#endif - - out << "wall-clock time : "; - out.display_time ( _clock.get_real_time() ); - out << std::endl; - - if ( _stat_sum.is_defined() ) - out << "stat sum : " << _stat_sum << std::endl; - if ( _stat_avg.is_defined() ) - out << "stat avg : " << get_stat_avg() << std::endl; - } diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Stats.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Stats.hpp deleted file mode 100644 index d34889fbb..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Stats.hpp +++ /dev/null @@ -1,540 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Stats.hpp - \brief Algorithm stats (headers) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Stats.cpp -*/ -#ifndef __STATS__ -#define __STATS__ - -#include "Clock.hpp" -#include "Double.hpp" -#include "Model_Stats.hpp" - -namespace NOMAD { - - /// Algorithm stats. - class Stats { - - private: - - /// Number of evaluations. - /** - Blackbox evaluations + cache hits. - */ - int _eval; - - /// Number of simulated blackbox evaluations. - /** - Blackbox evaluations + initial cache hits. - */ - int _sim_bb_eval; - - int _sgte_eval; ///< Number of surrogate evaluations. - int _sgte_cost; ///< Surrogate cost. - int _bb_eval; ///< Number of blackbox evaluations. - int _block_eval; ///< Number of block of evaluations. - int _failed_eval; ///< Number of failed evaluations. - int _cache_hits; ///< Number of cache hits. - int _interrupted_eval; ///< Number of interrupted sequence of evaluations. - int _iterations; ///< Number of iterations. - NOMAD::Double _stat_sum; ///< Sum stat (output of type NOMAD::STAT_SUM). - NOMAD::Double _stat_avg; ///< Average stat (output of type NOMAD::STAT_AVG). - int _cnt_avg; ///< Number of values for the \c avg stat. - int _p1_iterations; ///< Iterations in MADS phase one. - int _p1_bbe; ///< Blackbox evaluations in phase one. - NOMAD::Clock _clock; ///< Wall-clock time. - int _mads_runs; ///< Number of MADS runs (for multi-objective runs). - - // Polls: - int _nb_poll_searches; ///< Number of poll searches. - int _poll_pts; ///< Number of poll points. - int _poll_success; ///< Number of poll successes. - - // Extended polls: - int _nb_ext_polls; ///< Number of extended polls. - int _ext_poll_pts; ///< Number of extended poll points. - int _ext_poll_succ; ///< Number of extended poll successes. - int _ext_poll_bb_eval; ///< Number of extended poll blackbox evaluations. - int _ext_poll_descents; ///< Number of extended poll descents. - - // Speculative searches: - int _nb_spec_searches; ///< Number of speculative searches. - int _spec_pts; ///< Number of speculative search points. - int _spec_success; ///< Number of speculative search successes. - -#ifdef USE_MPI - int _asynchronous_success; ///< Number of asynchronous successes. - int _MPI_data_size; ///< Size of MPI messages. -#endif - - // LH searches: - int _nb_LH_searches; ///< Number of Latin-Hypercube (LH) searches. - int _LH_pts; ///< Number of Latin-Hypercube (LH) search points. - int _LH_success; ///< Number of LH search successes. - - // Cache searches: - int _nb_cache_searches; ///< Number of cache searches (CS). - int _CS_pts; ///< Number of CS search points. - int _CS_success; ///< Number of CS search successes. - - /// Model stats. - NOMAD::Model_Stats _model_stats; - - // VNS searches: - int _nb_VNS_searches; ///< Number of VNS searches. - int _VNS_pts; ///< Number of VNS search points. - int _VNS_success; ///< Number of VNS search successes. - int _VNS_bb_eval; ///< Number of VNS blackbox evaluations. - int _VNS_sgte_eval; ///< Number of VNS surrogate evaluations. - - // User searches: - int _nb_usr_searches; ///< Number of user searches. - int _usr_srch_pts; ///< Number of user search points. - int _usr_srch_success; ///< Number of user search successes. - - // Dynamic management of poll directions - int _nb_success_dyn_dir; ///< Number of successfull polling in the direction added dynamically - - -public: - - /// Constructor. - /** - \param sgte_cost Surrogate cost -- \b IN -- \b optional (default = \c -1). - */ - explicit Stats ( int sgte_cost = -1 ) : _sgte_cost(sgte_cost) { reset(); } - - /// Copy constructor. - /** - \param s The copied object -- \b IN. - */ - explicit Stats ( const Stats & s ) - : _eval ( s._eval ) , - _sim_bb_eval ( s._sim_bb_eval ) , - _sgte_eval ( s._sgte_eval ) , - _sgte_cost ( s._sgte_cost ) , - _bb_eval ( s._bb_eval ) , - _block_eval ( s._block_eval ) , - _failed_eval ( s._failed_eval ) , - _cache_hits ( s._cache_hits ) , - _interrupted_eval ( s._interrupted_eval ) , - _iterations ( s._iterations ) , - _stat_sum ( s._stat_sum ) , - _stat_avg ( s._stat_avg ) , - _cnt_avg ( s._cnt_avg ) , - _p1_iterations ( s._p1_iterations ) , - _p1_bbe ( s._p1_bbe ) , - _clock ( s._clock ) , - _mads_runs ( s._mads_runs ) , - _nb_poll_searches ( s._nb_poll_searches ) , - _poll_pts ( s._poll_pts ) , - _poll_success ( s._poll_success ) , - _nb_ext_polls ( s._nb_ext_polls ) , - _ext_poll_pts ( s._ext_poll_pts ) , - _ext_poll_succ ( s._ext_poll_succ ) , - _ext_poll_bb_eval ( s._ext_poll_bb_eval ) , - _ext_poll_descents ( s._ext_poll_descents ) , - _nb_spec_searches ( s._nb_spec_searches ) , - _spec_pts ( s._spec_pts ) , - _spec_success ( s._spec_success ) , -#ifdef USE_MPI - _asynchronous_success ( s._asynchronous_success ) , - _MPI_data_size ( s._MPI_data_size ) , -#endif - _nb_LH_searches ( s._nb_LH_searches ) , - _LH_pts ( s._LH_pts ) , - _LH_success ( s._LH_success ) , - _nb_cache_searches ( s._nb_cache_searches ) , - _CS_pts ( s._CS_pts ) , - _CS_success ( s._CS_success ) , - _nb_VNS_searches ( s._nb_VNS_searches ) , - _VNS_pts ( s._VNS_pts ) , - _VNS_success ( s._VNS_success ) , - _VNS_bb_eval ( s._VNS_bb_eval ) , - _VNS_sgte_eval ( s._VNS_sgte_eval ) , - _nb_usr_searches ( s._nb_usr_searches ) , - _usr_srch_pts ( s._usr_srch_pts ) , - _usr_srch_success ( s._usr_srch_success ) , - _nb_success_dyn_dir ( s._nb_success_dyn_dir ) {} - - /// Affectation operator. - /** - \param s The right-hand side object -- \b IN. - */ - Stats & operator = ( const Stats & s ); - - /// Destructor. - virtual ~Stats ( void ) {} - - /// Reset the stats. - void reset ( void ); - - /// Update stats from another NOMAD::Stats object. - /** - \param s The other NOMAD::Stats object -- \b IN. - \param for_search A flag equal to \c true if the method - has been invoked within a search step - -- \b IN. - */ - void update ( const Stats & s , bool for_search ); - - /// Update the \c sum stat. - /** - \param d New \c sum element -- \b IN. - */ - void update_stat_sum ( const NOMAD::Double & d ); - - /// Update the \c avg stat. - /** - \param d New \c avg element -- \b IN. - */ - void update_stat_avg ( const NOMAD::Double & d ); - - /// Add \c 1 to stat \c _mads_run. - void add_mads_run ( void ) { ++_mads_runs; } - - /// Set the number of MADS runs. - void set_mads_runs ( int mads_runs ) { _mads_runs = mads_runs; } - - /// Add \c 1 to stat \c _eval. - void add_eval ( void ) { ++_eval; } - - /// Add \c 1 to stat \c _sim_bb_eval. - void add_sim_bb_eval ( void ) { ++_sim_bb_eval; } - - /// Add \c 1 to stat \c _sgte_eval. - void add_sgte_eval ( void ) { ++_sgte_eval; } - - /// Add \c count_eval to stat \c _sgte_eval. - void add_sgte_eval ( int count_eval ) { _sgte_eval+=count_eval; } - - /// Add \c 1 to stat \c _bb_eval. - void add_bb_eval ( void ) { ++_bb_eval; } - - /// Add \c 1 to stat \c _block_eval. - void add_one_block_eval ( void ) { ++_block_eval; } - - /// Add \c count_eval to stat \c _bb_eval. - void add_bb_eval ( int count_eval ) { _bb_eval+=count_eval; } - - /// Add \c 1 to stat \c _failed_eval. - void add_failed_eval ( void ) { ++_failed_eval; } - - /// Add \c 1 to stat \c _cache_hits. - void add_cache_hit ( void ) { ++_cache_hits; } - - /// Add \c 1 to stat \c _interrupted_eval. - void add_interrupted_eval ( void ) { ++_interrupted_eval; } - - /// Add \c 1 to stat \c _iterations. - void add_iteration ( void ) { ++_iterations; } - - /// Add \c 1 to stat \c _nb_poll_searches. - void add_nb_poll_searches ( void ) { ++_nb_poll_searches; } - - /// Add \c 1 to stat \c _poll_success. - void add_poll_success ( void ) { ++_poll_success; } - - /// Add \c 1 to stat \c _nb_ext_polls. - void add_nb_ext_polls ( void ) { ++_nb_ext_polls; } - - /// Add \c 1 to stat \c _ext_poll_succ. - void add_ext_poll_succ ( void ) { ++_ext_poll_succ; } - - /// Add \c 1 to stat \c _ext_poll_descents. - void add_ext_poll_descent ( void ) { ++_ext_poll_descents; } - - /// Add \c 1 to stat \c _nb_spec_searches. - void add_nb_spec_searches ( void ) { ++_nb_spec_searches; } - - /// Add \c 1 to stat \c _spec_success. - void add_spec_success ( void ) { ++_spec_success; } - - /// Add \c 1 to stat \c _LH_success. - void add_LH_success ( void ) { ++_LH_success; } - - /// Add \c 1 to stat \c _nb_cache_searches. - void add_nb_cache_searches ( void ) { ++_nb_cache_searches; } - - /// Add \c 1 to stat \c _nb_LH_searches. - void add_nb_LH_searches ( void ) { ++_nb_LH_searches; } - - /// Add \c 1 to stat \c _CS_success. - void add_CS_success ( void ) { ++_CS_success; } - - /// Add \c 1 to stat \c _nb_VNS_searches. - void add_nb_VNS_searches ( void ) { ++_nb_VNS_searches; } - - /// Add \c 1 to stat \c _VNS_success. - void add_VNS_success ( void ) { ++_VNS_success; } - - /// Add \c 1 to stat \c _nb_usr_searches. - void add_nb_usr_searches ( void ) { ++_nb_usr_searches; } - - /// Add \c 1 to stat \c _usr_srch_success. - void add_usr_srch_success ( void ) { ++_usr_srch_success; } - - - /// Add \c 1 to stat \c _nb_success_dyn_dir. - void add_nb_success_dyn_dir(void) {++_nb_success_dyn_dir;} - - /// Add an integer to stat \c _p1_iterations. - /** - \param i The integer -- \b IN. - */ - void add_p1_iterations ( int i ) { _p1_iterations += i; } - - /// Add an integer to stat \c _p1_bbe. - /** - \param i The integer -- \b IN. - */ - void add_p1_bbe ( int i ) { _p1_bbe += i; } - - /// Add an integer to stat \c _poll_pts. - /** - \param i The integer -- \b IN. - */ - void add_poll_pts ( int i ) { _poll_pts += i; } - - /// Add an integer to stat \c _ext_poll_pts. - /** - \param i The integer -- \b IN. - */ - void add_ext_poll_pts ( int i ) { _ext_poll_pts += i; } - - /// Add an integer to stat \c _ext_poll_bb_eval. - /** - \param i The integer -- \b IN. - */ - void add_ext_poll_bb_eval ( int i ) { _ext_poll_bb_eval += i;} - - /// Add an integer to stat \c _spec_pts. - /** - \param i The integer -- \b IN. - */ - void add_spec_pts ( int i ) { _spec_pts += i; } - - /// Add an integer to stat \c _LH_pts. - /** - \param i The integer -- \b IN. - */ - void add_LH_pts ( int i ) { _LH_pts += i; } - - /// Add an integer to stat \c _CS_pts. - /** - \param i The integer -- \b IN. - */ - void add_CS_pts ( int i ) { _CS_pts += i; } - - /// Update model stats. - void update_model_stats ( const NOMAD::Model_Stats & ms ) - { - _model_stats.update ( ms ); - } - - /// Add an integer to stat \c _VNS_pts. - /** - \param i The integer -- \b IN. - */ - void add_VNS_pts ( int i ) { _VNS_pts += i; } - - /// Add an integer to stat \c _VNS_bb_eval. - /** - \param i The integer -- \b IN. - */ - void add_VNS_bb_eval ( int i ) { _VNS_bb_eval += i; } - - /// Add an integer to stat \c _VNS_sgte_eval. - /** - \param i The integer -- \b IN. - */ - void add_VNS_sgte_eval ( int i ) { _VNS_sgte_eval += i; } - - /// Add an integer to stat \c _usr_srch_pts. - /** - \param i The integer -- \b IN. - */ - void add_usr_srch_pts ( int i ) { _usr_srch_pts += i; } - -#ifdef USE_MPI - - /// Add \c 1 to stat \c _asynchronous_success. - void add_asynchronous_success ( void ) { ++_asynchronous_success; } - - /// Add an integer to stat \c _MPI_data_size. - /** - \param i The integer -- \b IN. - */ - void set_MPI_data_size ( int i ) { _MPI_data_size = i; } -#endif - - /// Access to the stat \c _eval. - /** - \return The stat \c _eval. - */ - int get_eval ( void ) const { return _eval; } - - /// Access to the stat \c _sim_bb_eval. - /** - \return The stat \c _sim_bb_eval. - */ - int get_sim_bb_eval ( void ) const { return _sim_bb_eval; } - - /// Access to the stat \c _sgte_eval. - /** - \return The stat \c _sgte_eval. - */ - int get_sgte_eval ( void ) const { return _sgte_eval; } - - /// Access to the real time stat. - /** - \return The real time stat. - */ - int get_real_time ( void ) const { return _clock.get_real_time(); } - - /// Access to the stat \c _iterations. - /** - \return The stat \c _iterations. - */ - int get_iterations ( void ) const { return _iterations; } - - /// Access to the stat \c _failed_eval. - /** - \return The stat \c _failed_eval. - */ - int get_failed_eval ( void ) const { return _failed_eval; } - - /// Access to the stat \c _mads_runs. - /** - \return The stat \c _mads_runs. - */ - int get_mads_runs ( void ) const { return _mads_runs; } - - /// Access to the stat \c _LH_pts. - /** - \return The stat \c _LH_pts. - */ - int get_LH_pts ( void ) const { return _LH_pts; } - - /// Access to the stat \c _CS_pts. - /** - \return The stat \c _CS_pts. - */ - int get_CS_pts ( void ) const { return _CS_pts; } - - /// Access to the stat \c _VNS_bb_eval. - /** - \return The stat \c _VNS_bb_eval. - */ - int get_VNS_bb_eval ( void ) const { return _VNS_bb_eval; } - - /// Access to the stat \c _VNS_sgte_eval. - /** - \return The stat \c _VNS_sgte_eval. - */ - int get_VNS_sgte_eval ( void ) const { return _VNS_sgte_eval; } - - /// Access to the number of cache hits. - /** - \return The number of cache hits. - */ - int get_cache_hits ( void ) const { return _cache_hits; } - - /// Access to the number of blackbox evaluations (includes surrogate cost). - /** - \return The number of blackbox evaluations. - */ - int get_bb_eval ( void ) const - { - return ( _sgte_cost > 0 ) ? _bb_eval + _sgte_eval / _sgte_cost : _bb_eval; - } - - - /// Access to the number of block of evaluations (includes bb and surrogates). - /** - \return The number of blackbox evaluations. - */ - int get_block_eval ( void ) const - { - return _block_eval; - } - - /// Access to the \c sum stat. - /** - \return The \c sum stat. - */ - NOMAD::Double get_stat_sum ( void ) const { return _stat_sum; } - - /// Access to the \c avg stat. - /** - \return The \c avg stat. - */ - NOMAD::Double get_stat_avg ( void ) const - { - return ( _cnt_avg > 0 ) ? _stat_avg/_cnt_avg : NOMAD::Double(); - } - - /// Access to the model stats. - /** - \return The model stats. - */ - const NOMAD::Model_Stats & get_model_stats ( void ) const { return _model_stats; } - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::Stats object. - /** - \param out The NOMAD::Display object -- \b IN. - \param s The NOMAD::Stats object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Stats & s ) { - s.display ( out ); - return out; - } -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model.cpp deleted file mode 100644 index a77ef856a..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model.cpp +++ /dev/null @@ -1,1551 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Model.cpp - \brief TGP (Bayesian treed Gaussian process) model for all outputs (implementation) - \author Sebastien Le Digabel - \date 2011-02-07 - \see TGP_Model.hpp -*/ - -#ifndef USE_TGP - -int TGP_DUMMY; // avoids that TGP_Model.o has no symbols with ranlib - -#else - -#include "TGP_Model.hpp" - -/*-----------------------------------*/ -/* constructor 1/2 */ -/*-----------------------------------*/ -NOMAD::TGP_Model::TGP_Model ( int n0 , - const std::vector & bbot , - const NOMAD::Display & out , - NOMAD::TGP_mode_type mode ) - : _out ( out ) , - _bbot ( bbot ) , - _p ( 0 ) , - _n0 ( n0 ) , - _n ( 0 ) , - _n_XX ( 0 ) , - _av_index ( NULL ) , - _fv_index ( NULL ) , - _X ( NULL ) , - _XX ( NULL ) , - _Ds2x ( NULL ) , - _improv ( NULL ) , - _model_computed ( false ) , - _nep_flag ( false ) , - _tgp_mode ( mode ) , - _tgp_models ( NULL ) , - _tgp_rect ( NULL ) , - _tgp_linburn ( true ) , - _usr_pmax ( -1 ) , - _tgp_verb ( false ) -{ - _usr_BTE[0] = _usr_BTE[1] = _usr_BTE[2] = -1; - - // user mode: this is not the good constructor to call: - if ( mode == NOMAD::TGP_USER ) - throw NOMAD::Exception ( "TGP_Model.cpp" , __LINE__ , - "this constructor only accepts fast or precise TGP modes" ); - - _error_str = "NOMAD::TGP_Model::set_X() has not been called"; -} - -/*--------------------------------------------------------*/ -/* constructor 2/2 (with user BTE and pmax and no bbot) */ -/*--------------------------------------------------------*/ -NOMAD::TGP_Model::TGP_Model ( int n0 , - const NOMAD::Display & out , - int BTE[3] , - bool linburn , - int pmax , - bool verb ) - : _out ( out ) , - _p ( 0 ) , - _n0 ( n0 ) , - _n ( 0 ) , - _n_XX ( 0 ) , - _av_index ( NULL ) , - _fv_index ( NULL ) , - _X ( NULL ) , - _XX ( NULL ) , - _Ds2x ( NULL ) , - _improv ( NULL ) , - _model_computed ( false ) , - _nep_flag ( false ) , - _tgp_mode ( NOMAD::TGP_USER ) , - _tgp_models ( NULL ) , - _tgp_rect ( NULL ) , - _tgp_linburn ( linburn ) , - _usr_pmax ( pmax ) , - _tgp_verb ( verb ) -{ - - // user BTE parameters: - _usr_BTE[0] = BTE[0]; - _usr_BTE[1] = BTE[1]; - _usr_BTE[2] = BTE[2]; - - // default bbot: just one objective output: - _bbot.push_back ( NOMAD::OBJ ); - - _error_str = "NOMAD::TGP_Model::set_X() has not been called"; -} - -/*--------------------------------------------*/ -/* destructor */ -/*--------------------------------------------*/ -NOMAD::TGP_Model::~TGP_Model ( void ) -{ - clear(); - - if ( _Ds2x ) { - int i , m = _bbot.size(); - for ( i = 0 ; i < m ; ++i ) - if ( _Ds2x[i] ) - delete [] _Ds2x[i]; - delete [] _Ds2x; - } - - if ( _improv ) - delete [] _improv; -} - -/*--------------------------------------------*/ -/* clear memory (private) */ -/*--------------------------------------------*/ -/* members that depend only on constructor */ -/* arguments are not reseted here */ -/*--------------------------------------------*/ -void NOMAD::TGP_Model::clear ( void ) -{ - int i; - - if ( _av_index ) { - delete [] _av_index; - _av_index = NULL; - } - - if ( _fv_index ) { - delete [] _fv_index; - _fv_index = NULL; - } - - if ( _X ) { - for ( i = 0 ; i < _p ; ++i ) - delete [] _X[i]; - delete [] _X; - _X = NULL; - } - - if ( _XX ) { - for ( i = 0 ; i < _n_XX ; ++i ) - delete [] _XX[i]; - delete [] _XX; - _XX = NULL; - } - - if ( _tgp_models ) { - int m = _bbot.size(); - for ( i = 0 ; i < m ; ++i ) - if ( _tgp_models[i] ) { - delete _tgp_models[i]; - } - delete [] _tgp_models; - _tgp_models = NULL; - } - - if ( _tgp_rect ) { - delete_matrix ( _tgp_rect ); - _tgp_rect = NULL; - } - - _error_str.clear(); - _lb.clear(); - _ub.clear(); - _fv.clear(); - - _p = _n = _n_XX = 0; - - _model_computed = false; -} - -/*--------------------------------------------*/ -/* set the interpolation set X (1/2) */ -/*--------------------------------------------*/ -bool NOMAD::TGP_Model::set_X ( const NOMAD::Cache & cache , // only truth evals - const NOMAD::Point * center , // the incumbent - int seed , - bool remove_fv ) -{ - std::vector X; - - const NOMAD::Eval_Point * cur = cache.begin(); - while ( cur ) { - X.push_back ( cur ); - cur = cache.next(); - } - - return set_X ( X , center , seed , remove_fv ); -} - -/*--------------------------------------------*/ -/* set the interpolation set X (2/2) */ -/*--------------------------------------------*/ -bool NOMAD::TGP_Model::set_X -( const std::vector & X , - const NOMAD::Point * center , - int seed , - bool remove_fv ) -{ - clear(); - _nep_flag = false; - - if ( X.size() <= 1 ) { - _error_str = ( X.empty() ) ? - "interpolation set X is empty" : "only one point in interpolation set X"; - _nep_flag = true; - return false; - } - - // filter and sort X: - std::list filtered_X; - _p = filter_and_sort_X ( X , center , filtered_X ); - - if ( _p == 0 ) { - _error_str = "no valid interpolation point"; - _nep_flag = true; - return false; - } - - int pmin , pmax; - bool valid = false; - - while ( !valid ) { - - _n = check_fixed_variables ( filtered_X , remove_fv ); - - if ( _n <= 1 ) { - _error_str = ( _n == 0 ) ? - "only fixed variables" : "interpolation set of dimension 1"; - return false; - } - - // get the limits pmin <= p <= pmax: - if ( !get_p_limits ( _n , pmin , pmax ) ) - return false; - - if ( _p < pmin ) { - std::ostringstream oss; - oss << "not enough interpolation points (" - << _p << "<=" << pmin << ")"; - _error_str = oss.str(); - _nep_flag = true; - return false; - } - - // reduce the number of interpolation points: - if ( _p > pmax ) { - filtered_X.resize ( pmax ); - _p = pmax; - valid = false; - } - - // the interpolation set has a valid size: - else - valid = true; - } - - // display limits on p: -#ifdef TGP_DEBUG - _out << std::endl - << "number of interpolation points: " - << pmin << " <= p=" << _p << " <= " << pmax - << std::endl; -#endif - - // create interpolation matrix X: - int i = 0 , j; - _X = new double * [_p]; - - std::list::const_iterator - it , end = filtered_X.end(); - for ( it = filtered_X.begin() ; it != end ; ++it , ++i ) { - _X[i] = new double[_n]; - for ( j = 0 ; j < _n ; ++j ) - _X[i][j] = (**it)[_fv_index[j]].value(); - } - - // check that X is of full rank: - if ( !NOMAD::TGP_Model::check_full_rank ( _X , _p , _n ) ) { - _error_str = "X is not of full rank"; - return false; - } - - // construct individual TGP models (one for each output): - int m = _bbot.size(); - _tgp_models = new NOMAD::TGP_Output_Model * [m]; - for ( i = 0 ; i < m ; ++i ) { - _tgp_models[i] = NULL; - if ( _bbot[i] == NOMAD::OBJ || NOMAD::bbot_is_constraint(_bbot[i]) ) - _tgp_models[i] = new NOMAD::TGP_Output_Model ( filtered_X , - i , - seed , - _out ); - } - - return _error_str.empty(); -} - -/*----------------------------------------------------*/ -/* get the limits pmin <= p <= pmax (private) */ -/*----------------------------------------------------*/ -bool NOMAD::TGP_Model::get_p_limits ( int n , int & pmin , int & pmax ) -{ - if ( n <= 0 ) { - _error_str = "bad value of n for the computation of pmin and pmax"; - return false; - } - - // TGP fast mode: - // -------------- - // - // example of some values for pmin and pmax: - // - // n pmin pmax - // - // 2 7 30 - // 3 8 30 - // 4 9 30 - // 5 10 30 - // 6 11 32 - // 7 12 35 - // 8 13 37 - // 9 14 40 - // 10 15 42 - // 20 25 60 - // 50 55 94 - // 55 60 99 - // 56 61 100 - // 57 62 100 - // 95 100 100 - // 96 101 101 - // 100 105 105 - - if ( _tgp_mode == NOMAD::TGP_FAST ) { - pmin = n+5; - - pmax = static_cast ( floor ( sqrt(180.0*n) ) ); - - if ( pmax > 100 ) - pmax = 100; - - if ( pmax < 30 ) - pmax = 30; - - if ( pmax < pmin ) - pmax = pmin; - - return true; - } - - // TGP precise mode: pmin=n+1 and pmax=100 - // ----------------- - if ( _tgp_mode == NOMAD::TGP_PRECISE ) { - pmin = n+1; - pmax = 100; - return true; - } - - // TGP user mode: pmin=n+1 and pmax is user decided with constructor 2/2 - // -------------- - if ( _tgp_mode == NOMAD::TGP_USER ) { - pmin = n+1; - pmax = _usr_pmax; - if ( pmax < pmin ) { - std::ostringstream oss; - oss << "user pmax value must be > " << n; - _error_str = oss.str(); - return false; - } - return true; - } - - return true; -} - -/*----------------------------------------------*/ -/* get the TGP BTE parameters (private) */ -/*----------------------------------------------*/ -bool NOMAD::TGP_Model::get_BTE ( int BTE[3] ) -{ - // fast TGP mode: - // -------------- - // . if p=pmin, then B=2000 - // . if p=pmax, then B=1000 - // . if pmin ( 10.0 * floor ( (a * _p + b) / 10.0 ) ); - BTE[1] = 3*BTE[0]; - BTE[2] = 10; - } - - // precise TGP mode: - // ----------------- - else if ( _tgp_mode == NOMAD::TGP_PRECISE ) { - BTE[0] = 2000; - BTE[1] = 7000; - BTE[2] = 2; - } - - // user mode: - // ---------- - else { - BTE[0] = _usr_BTE[0]; - BTE[1] = _usr_BTE[1]; - BTE[2] = _usr_BTE[2]; - - // check the user BTE parameters: - if ( BTE[0] <= 0 || - BTE[1] <= 0 || - BTE[2] <= 0 || - BTE[1] <= BTE[0] ) { - _error_str = "error with user BTE"; - return false; - } - } - - return true; -} - -/*--------------------------------------------------------------*/ -/* compute the ranges, check the fixed variables, set the */ -/* different indexes, and return the number of free variables */ -/* (private) */ -/*--------------------------------------------------------------*/ -int NOMAD::TGP_Model::check_fixed_variables -( const std::list & X , - bool remove_fv ) -{ - - int i; - - if ( !_av_index ) { - _av_index = new int [_n0]; - for ( i = 0 ; i < _n0 ; ++i ) - _av_index[i] = -1; - } - - _lb = NOMAD::Point ( _n0 ); - _ub = NOMAD::Point ( _n0 ); - _fv = NOMAD::Point ( _n0 ); - - // compute ranges: - std::list::const_iterator it , end = X.end(); - for ( it = X.begin() ; it != end ; ++it ) { - for ( i = 0 ; i < _n0 ; ++i ) { - if ( !_lb[i].is_defined() || (**it)[i] < _lb[i] ) - _lb[i] = (**it)[i]; - if ( !_ub[i].is_defined() || (**it)[i] > _ub[i] ) - _ub[i] = (**it)[i]; - } - } - - // compute n (number of free variables), the fixed variables, and the indexes: - int n = 0; - - std::vector fv_index_tmp; - for ( i = 0 ; i < _n0 ; ++i ) { - if ( remove_fv && _lb[i] == _ub[i] ) { - _fv [i] = _lb[i]; - _av_index[i] = -1; - } - else { - fv_index_tmp.push_back ( i ); - _av_index[i] = n++; - } - } - - // complete the fixed var index construction: - if ( _fv_index ) - delete [] _fv_index; - _fv_index = NULL; - - if ( n > 0 ) { - _fv_index = new int[n]; - for ( i = 0 ; i < n ; ++i ) - _fv_index[i] = fv_index_tmp[i]; - } - - return n; -} - -/*--------------------------------------------------------*/ -/* filter and sort an interpolation set X (private) */ -/* . the points are sorted relatively to the distance */ -/* from the center */ -/* . if the center is not defined (equal to NULL), */ -/* an alternate center is constructed */ -/*--------------------------------------------------------*/ -int NOMAD::TGP_Model::filter_and_sort_X -( const std::vector & X , - const NOMAD::Point * center , - std::list & filtered_X ) const -{ - NOMAD::Point alt_center; - const NOMAD::Eval_Point * cur = NULL; - int p0 = X.size() , i; - - // alternate center if center==NULL: - if ( !center ) { - int j; - NOMAD::Point lb(_n0) , ub(_n0); - for ( i = 0 ; i < p0 ; ++i ) { - cur = X[i]; - if ( test_interpolation_point ( cur ) ) { - for ( j = 0 ; j < _n0 ; ++j ) { - if ( !lb[j].is_defined() || (*cur)[j] < lb[j] ) - lb[j] = (*cur)[j]; - if ( !ub[j].is_defined() || (*cur)[j] > ub[j] ) - ub[j] = (*cur)[j]; - } - } - } - alt_center = NOMAD::Point(_n0); - for ( j = 0 ; j < _n0 ; ++j ) - alt_center[j] = ( lb[j] + ub[j] ) / 2.0; - } - - // X_tmp is used to sort the points: - std::multiset tmp_X; - - for ( i = 0 ; i < p0 ; ++i ) { - - cur = X[i]; - - // test if the interpolation point is valid for interpolation: - if ( test_interpolation_point ( cur ) ) { - - NOMAD::Model_Sorted_Point sorted_pt - ( &NOMAD::Cache::get_modifiable_point (*cur) , - (center) ? *center : alt_center ); - - tmp_X.insert ( sorted_pt ); - } - } - - // copy the set X_tmp to filtered_X: - std::multiset::const_iterator it , end = tmp_X.end(); - for ( it = tmp_X.begin() ; it != end ; ++it ) - filtered_X.push_back ( static_cast ( it->get_point() ) ); - - return filtered_X.size(); -} - -/*-----------------------------------------------------*/ -/* tests to check if an interpolation point is valid */ -/* (private) */ -/*-----------------------------------------------------*/ -bool NOMAD::TGP_Model::test_interpolation_point ( const NOMAD::Eval_Point * x ) const -{ - if ( !x || x->size() != _n0 || !x->is_eval_ok() ) - return false; - - int m = _bbot.size(); - const NOMAD::Point & bbo = x->get_bb_outputs(); - - if ( bbo.size() != m ) - return false; - - for ( int j = 0 ; j < m ; ++j ) - if ( ( _bbot[j] == NOMAD::OBJ || NOMAD::bbot_is_constraint(_bbot[j]) ) && - ( !bbo[j].is_defined() || bbo[j].abs() > NOMAD::MODEL_MAX_OUTPUT ) ) - return false; - - // point is valid: - return true; -} - -/*--------------------------------------------*/ -/* compute the models (one for each output) */ -/*--------------------------------------------*/ -bool NOMAD::TGP_Model::compute -( std::vector & XX_pts , // IN/OUT - bool compute_Ds2x , // IN - bool compute_improv , // IN - bool pred_outside_bnds ) // IN -{ - _model_computed = false; - - if ( !_error_str.empty() ) - return false; - - int i , j , index_obj = -1 , n_XX0 = XX_pts.size() , m = _bbot.size(); - - // check bbot: there must be exactly one objective: - for ( i = 0 ; i < m ; ++i ) { - if ( _bbot[i] == NOMAD::OBJ ) { - if ( index_obj < 0 ) - index_obj = i; - else { - _error_str = "more than one objective"; - return false; - } - } - } - if ( index_obj < 0 ) { - _error_str = "no objective"; - return false; - } - - // check n_XX0: - if ( n_XX0 == 0 ) { - _error_str = "no user-provided prediction point"; - return false; - } - - // reset XX_pts outputs: - for ( i = 0 ; i < n_XX0 ; ++i ) { - for ( j = 0 ; j < m ; ++j ) - XX_pts[i]->set_bb_output ( j , NOMAD::Double() ); - XX_pts[i]->set_eval_status ( NOMAD::EVAL_FAIL ); - } - - // create the XX matrix (prediction points): - std::vector XX_filtered_pts; - NOMAD::Eval_Point * cur2; - - // the list of points has to be filtered: - NOMAD::Double tmp; - bool chk; - - for ( i = 0 ; i < n_XX0 ; ++i ) { - if ( XX_pts[i]->size() == _n0 ) { - cur2 = XX_pts[i]; - chk = true; - for ( j = 0 ; j < _n0 ; ++j ) { - tmp = (*cur2)[j]; - if ( !pred_outside_bnds && ( tmp < _lb[j] || tmp > _ub[j] ) ) { - chk = false; - break; - } - } - if ( chk ) - XX_filtered_pts.push_back ( cur2 ); - } - } - - if ( _XX ) { - for ( i = 0 ; i < _n_XX ; ++i ) - delete [] _XX[i]; - delete [] _XX; - } - - _n_XX = XX_filtered_pts.size(); - - if ( _n_XX == 0 ) { - _error_str = "no prediction point after filtering"; - return false; - } - - _XX = new double * [_n_XX]; - for ( i = 0 ; i < _n_XX ; ++i ) { - _XX[i] = new double[_n]; - for ( j = 0 ; j < _n ; ++j ) - _XX[i][j] = (*XX_filtered_pts[i])[_fv_index[j]].value(); - } - - // Xsplit: X+XX: size = nsplit x n: - int nsplit = _p + _n_XX; - double ** Xsplit = new double * [nsplit]; - - for ( i = 0 ; i < _p ; ++i ) { - Xsplit[i] = new double [_n]; - for ( j = 0 ; j < _n ; ++j ) - Xsplit[i][j] = _X[i][j]; - } - - for ( i = _p ; i < nsplit ; ++i ) { - Xsplit[i] = new double [_n]; - for ( j = 0 ; j < _n ; ++j ) - Xsplit[i][j] = _XX[i-_p][j]; - } - - // get the rectangle: - if ( _tgp_rect ) - delete_matrix ( _tgp_rect ); - _tgp_rect = get_data_rect ( Xsplit , nsplit , _n ); - - // TGP parameters: - Params tgp_params ( _n ); - double * dparams = NOMAD::TGP_Model::get_TGP_dparams ( _n ); - tgp_params.read_double ( dparams ); - delete [] dparams; - - int BTE[3]; - if ( !get_BTE ( BTE ) ) { - for ( i = 0 ; i < nsplit ; ++i ) - delete [] Xsplit[i]; - delete [] Xsplit; - return false; - } - - // display BTE: -#ifdef TGP_DEBUG - _out << std::endl - << "BTE={" << BTE[0] << ", " << BTE[1] << ", " << BTE[2] << "}" - << std::endl; -#endif - - // compute the individual TGP models (one for each output): - double * ZZ = new double [_n_XX]; - - // Ds2x, expected reduction in predictive variance: - if ( _Ds2x == NULL ) { - _Ds2x = new double * [m]; - for ( i = 0 ; i < m ; ++i ) - _Ds2x[i] = NULL; - } - else { - for ( i = 0 ; i < m ; ++i ) - if ( _Ds2x[i] ) { - delete [] _Ds2x[i]; - _Ds2x[i] = NULL; - } - } - - // improv, expected improvement of the objective (ranks): - if ( _improv ) { - delete [] _improv; - _improv = NULL; - } - if ( compute_improv ) - _improv = new int [_n_XX]; - - for ( i = 0 ; i < m ; ++i ) { - - if ( _tgp_models[i] ) { - - _Ds2x[i] = ( compute_Ds2x ) ? new double [_n_XX] : NULL; - - _tgp_models[i]->compute ( _X , - _XX , - Xsplit , - _n , - _n_XX , - nsplit , - &tgp_params , - _tgp_rect , - BTE , - _tgp_linburn , - _tgp_verb , - ZZ , - _Ds2x[i] , - (i==index_obj) ? _improv : NULL ); - - // set XX_pts outputs #i: - for ( j = 0 ; j < _n_XX ; ++j ) { - XX_filtered_pts[j]->set_bb_output ( i , ZZ[j] ); - XX_filtered_pts[j]->set_eval_status ( NOMAD::EVAL_OK ); - } - - // check if TGP has been interrupted: - if ( NOMAD::TGP_Output_Model::get_force_quit() ) { - _error_str = "TGP has been interrupted with ctrl-c"; - break; - } - } - } - - // clear memory: - for ( i = 0 ; i < nsplit ; ++i ) - delete [] Xsplit[i]; - delete [] Xsplit; - delete [] ZZ; - - _model_computed = _error_str.empty(); - - return _model_computed; -} - -/*--------------------------------------------*/ -/* prediction at one point */ -/* (x can be of size _n or _n0) */ -/*--------------------------------------------*/ -bool NOMAD::TGP_Model::predict ( NOMAD::Eval_Point & x , bool pred_outside_bnds ) -{ - if ( !_error_str.empty() ) - return false; - - if ( !_model_computed ) { - _error_str = "NOMAD::TGP_Model::compute() has not been called"; - return false; - } - - int i , i0 , ix , m = x.get_m() , nx = x.size(); - - // reset point outputs: - x.set_eval_status ( NOMAD::EVAL_FAIL ); - for ( i = 0 ; i < m ; ++i ) - x.set_bb_output ( i , NOMAD::Double() ); - - // check dimensions: - if ( m != static_cast(_bbot.size()) || - ( nx != _n0 && nx != _n ) ) { - _error_str = "predict error: bad x dimensions"; - return false; - } - - double ZZ , * XX = new double[_n]; - - // set the coordinates and check the bounds: - for ( i = 0 ; i < _n ; ++i ) { - - ix = ( nx == _n0 ) ? _fv_index[i] : i; - - if ( !pred_outside_bnds ) { - i0 = _fv_index[i]; - if ( x[ix] < _lb[i0] || x[ix] > _ub[i0] ) { - delete [] XX; - return false; // this is not an error - } - } - - XX[i] = x[ix].value(); - } - - // predictions (one for each output): - for ( i = 0 ; i < m ; ++i ) - if ( _tgp_models[i] ) { - if ( !_tgp_models[i]->predict ( XX , - _n , - ZZ , - _tgp_rect ) ) { - std::ostringstream oss; - oss << "predict error: problem with model #" << i; - _error_str = oss.str(); - break; - } - x.set_bb_output ( i , ZZ ); - } - - delete [] XX; - - if ( !_error_str.empty() ) { - x.set_eval_status ( NOMAD::EVAL_FAIL ); - return false; - } - - x.set_eval_status ( NOMAD::EVAL_OK ); - return true; -} - -/*-----------------------------------------------------------------*/ -/* this function checks if the p x n matrix X is of full rank by */ -/* applying the Cholesky decomposition to the sym. def. pos. */ -/* nxn matrix X'X */ -/* (static, private) */ -/*-----------------------------------------------------------------*/ -bool NOMAD::TGP_Model::check_full_rank ( double ** X , int p , int n ) { - - int i , j , k , ki , kii , kij , kj , kji , nn12 = n*(n+1)/2; - - // create XTX (X'X): - double * XTX = new double [nn12]; - for ( i = 0 ; i < n ; ++i ) { - ki = i*(i+1)/2; - for ( j = 0 ; j <= i ; ++j ) { - kij = ki + j; - XTX[kij] = 0.0; - for ( k = 0 ; k < p ; ++k ) - XTX[kij] += X[k][i] * X[k][j]; - } - } - - // create chol: - double * chol = new double [nn12] , tmp1 , tmp2 , eps = 1e-10; - - // Choleski decomposition: - for ( i = 0 ; i < n ; ++i ) { - - ki = i*(i+1)/2; - kii = ki+i; - tmp1 = XTX[kii]; - for ( k = 0 ; k < i ; ++k ) - tmp1 -= pow(chol[ki+k],2.0); - if ( fabs ( tmp1 ) <= eps ) { - delete [] XTX; - delete [] chol; - return false; - } - - if ( i == n-1 ) - break; - - tmp1 = sqrt(tmp1); - chol[kii] = tmp1; - - for ( j = i+1 ; j < n ; ++j ) { - kj = j*(j+1)/2; - kji = kj+i; - tmp2 = XTX[kji]; - for ( k = 0 ; k < i ; ++k ) - tmp2 -= chol[ki+k]*chol[kj+k]; - chol[kji] = tmp2/tmp1; - } - } - - delete [] XTX; - delete [] chol; - - return true; -} - -/*----------------------------------------------------------------*/ -/* compute model h and f values given one blackbox output */ -/*----------------------------------------------------------------*/ -void NOMAD::TGP_Model::eval_hf ( const NOMAD::Point & bbo , - const NOMAD::Double & h_min , - NOMAD::hnorm_type h_norm , - NOMAD::Double & h , - NOMAD::Double & f ) const -{ - f.clear(); - h = 0.0; - - int m = bbo.size(); - - if ( m != static_cast(_bbot.size()) ) - throw NOMAD::Exception ( "TGP_Model.cpp" , __LINE__ , - "TGP_Model::eval_hf() called with an invalid bbo argument" ); - - NOMAD::Double bboi; - - for ( int i = 0 ; i < m ; ++i ) { - - bboi = bbo[i]; - - if ( bboi.is_defined() ) { - - if ( _bbot[i] == NOMAD::EB || _bbot[i] == NOMAD::PEB_E ) { - - if ( bboi > h_min ) { - h.clear(); - return; - } - } - - else if ( ( _bbot[i] == NOMAD::FILTER || - _bbot[i] == NOMAD::PB || - _bbot[i] == NOMAD::PEB_P ) ) { - if ( bboi > h_min ) { - switch ( h_norm ) { - case NOMAD::L1: - h += bboi; - break; - case NOMAD::L2: - h += bboi * bboi; - break; - case NOMAD::LINF: - if ( bboi > h ) - h = bboi; - break; - } - } - } - - else if ( _bbot[i] == NOMAD::OBJ ) - f = bboi; - } - - } - - if ( h_norm == NOMAD::L2 ) - h = h.sqrt(); -} - -/*---------------------------------------*/ -/* compute the TGP dparam array */ -/* (static, private) */ -/*---------------------------------------*/ -double * NOMAD::TGP_Model::get_TGP_dparams ( int n ) { - - double * dparams = new double [n*(n+3)+41]; - int i , j , k; - - // tree (p <- c(as.numeric(params$tree))): - dparams[0] = 0.5; - dparams[1] = 2.0; - dparams[2] = n+2; - if ( dparams[2] < 10 ) - dparams[2] = 10; - dparams[3] = 1.0; - dparams[4] = n; - - // params$meanfn == "linear" : - dparams[5] = 0.0; - - // params$bprior == "bflat" : - dparams[6] = 2.0; - - // p <- c(p, as.numeric(params$beta)) : n+1 zeros - k = 6; - for ( i = 0 ; i <= n ; ++i ) - dparams[++k] = 0.0; - - // p <- c(p, as.numeric(params$Wi)) : I_{n+1} - for ( i = 0 ; i <= n ; ++i ) - for ( j = 0 ; j <= n ; ++j ) - dparams[++k] = (i!=j) ? 0.0 : 1.0; - - // p <- c(p, as.numeric(params$s2tau2)): - dparams[++k] = 1.0; - dparams[++k] = 1.0; - - // p <- c(p, as.numeric(params$s2.p)): - dparams[++k] = 5.0; - dparams[++k] = 10.0; - - // p <- c(p, as.numeric(params$s2.lam)): - dparams[++k] = 0.2; - dparams[++k] = 10.0; - - // p <- c(p, as.numeric(params$tau2.p)): - dparams[++k] = 5.0; - dparams[++k] = 10.0; - - // p <- c(p, as.numeric(params$tau2.lam)): - dparams[++k] = 0.2; - dparams[++k] = 0.1; - - // params$corr == "expsep" : - dparams[++k] = 1.0; - - // p <- c(p, as.numeric(params$gd)): - dparams[++k] = 0.1; - dparams[++k] = 0.5; - - // p <- c(p, as.numeric(params$nug.p)): - dparams[++k] = 1.0; - dparams[++k] = 1.0; - dparams[++k] = 1.0; - dparams[++k] = 1.0; - - // if (params$nug.lam[1] == "fixed"), p <- c(p, rep(-1, 4)) : - dparams[++k] = -1.0; - dparams[++k] = -1.0; - dparams[++k] = -1.0; - dparams[++k] = -1.0; - - // p <- c(p, as.numeric(params$gamma)): - dparams[++k] = 0.0; - dparams[++k] = 0.2; - dparams[++k] = 0.7; - - // p <- c(p, as.numeric(params$d.p)): - dparams[++k] = 1.0; - dparams[++k] = 20.0; - dparams[++k] = 10.0; - dparams[++k] = 10.0; - - // if (params$d.lam[1] == "fixed"), p <- c(p, rep(-1, 4)): - dparams[++k] = -1.0; - dparams[++k] = -1.0; - dparams[++k] = -1.0; - dparams[++k] = -1.0; - - return dparams; -} - -/*--------------------------------------------*/ -/* display the interpolation set X */ -/*--------------------------------------------*/ -void NOMAD::TGP_Model::display_X ( const NOMAD::Display & out , - int display_limit ) const -{ - if ( _p == 0 || !_X ) { - out << "no interpolation points" << std::endl; - return; - } - - int i , j; - int m = _bbot.size(); - int i0 = ( display_limit > 0 ) ? _p - display_limit : 0; - NOMAD::Point x(_n) , bbo(m); - - out << NOMAD::open_block ( "interpolation points (X)"); - - if ( i0 > 0 ) - out << "..." << std::endl; - else if ( i0 < 0 ) - i0 = 0; - - for ( i = i0 ; i < _p ; ++i ) { - - for ( j = 0 ; j < _n ; ++j ) - x[j] = _X[i][j]; - - bbo = NOMAD::Point(m); - if ( _tgp_models ) - for ( j = 0 ; j < m ; ++j ) - if ( _tgp_models[j] ) - bbo[j] = (_tgp_models[j]->get_Z())[i]; - - out << "#"; - out.display_int_w ( i , _p ); - out << " x=("; - x.display ( out , " " , 15 , -1 ); - out << " ) f(x)=["; - bbo.display ( out , " " , 15 , -1 ); - out << " ]" << std::endl; - } - - std::ostringstream oss; - oss << "(size=" << _p << ")"; - out << NOMAD::close_block ( oss.str() ) << std::endl; -} - -/*---------------------------------------------------------*/ -/* get the XX points with the largest expected reduction */ -/* in predictive variance, for each output */ -/* (no duplicates) */ -/*---------------------------------------------------------*/ -void NOMAD::TGP_Model::get_Ds2x_points ( std::set & pts_indexes ) const -{ - pts_indexes.clear(); - if ( !_Ds2x || _n_XX == 0 ) - return; - - int i , j , k , m = _bbot.size(); - - for ( i = 0 ; i < m ; ++i ) - if ( _Ds2x[i] ) { - - NOMAD::Double max; - k = -1; - for ( j = 0 ; j < _n_XX ; ++j ) - if ( !max.is_defined() || _Ds2x[i][j] > max ) { - max = _Ds2x[i][j]; - k = j; - } - - if ( k >= 0 ) - pts_indexes.insert ( k ); - } -} - -/*----------------------------------------------------------------------------*/ -/* get the XX points with the largest expected improvement of the objective */ -/*----------------------------------------------------------------------------*/ -void NOMAD::TGP_Model::get_improv_points ( std::list & pts_indexes ) const -{ - pts_indexes.clear(); - if ( !_improv || _n_XX == 0 ) - return; - - int j; - NOMAD::Point * XX_pt; - std::multiset pts; - std::multiset::const_iterator it , end; - - // 1. sort: - for ( j = 0 ; j < _n_XX ; ++j ) { - XX_pt = new NOMAD::Point ( 1 ); - (*XX_pt)[0] = j; - pts.insert ( NOMAD::Model_Sorted_Point ( XX_pt , _improv[j] ) ); - } - - // 2. construct pts_indexes (exclude points with improv >= n_XX): - end = pts.end(); - for ( it = pts.begin() ; it != end ; ++it ) { - if ( it->get_dist() < _n_XX ) - pts_indexes.push_back ( static_cast ( (*it->get_point())[0].value() ) ); - delete it->get_point(); - } -} - -/*--------------------------------------------------------------*/ -/* display the expected improvement of the objective (improv) */ -/* (better ranks are displayed first) */ -/*--------------------------------------------------------------*/ -void NOMAD::TGP_Model::display_improv ( const NOMAD::Display & out , - int display_limit ) const -{ - if ( !_improv || _n_XX == 0 ) { - out << "improv has not been computed" << std::endl; - return; - } - - int j , k; - NOMAD::Point * XX_pt; - std::multiset pts; - std::multiset::const_iterator it , end; - - // 1. sort: - for ( j = 0 ; j < _n_XX ; ++j ) { - - // construct a NOMAD::Point from matrix _XX: - XX_pt = new NOMAD::Point ( _fv ); - for ( k = 0 ; k < _n0 ; ++k ) - if ( _av_index[k] >= 0 ) - (*XX_pt)[k] = _XX[j][_av_index[k]]; - - // insert this point in the sorted list: - pts.insert ( NOMAD::Model_Sorted_Point ( XX_pt , _improv[j] ) ); - } - - // 2. display: - end = pts.end(); - for ( j = 0 , it = pts.begin() ; it != end ; ++it , ++j ) { - - if ( display_limit <= 0 || j < display_limit ) { - out << "x=( "; - it->get_point()->display ( out , " " , 6 , -1 ); - out << " ) improv=" << it->get_dist() << std::endl; - } - - else if ( j == display_limit ) - out << "..." << std::endl; - - delete it->get_point(); - } -} - -/*----------------------------------------------------------------*/ -/* display the expected reduction in predictive variance (Ds2x) */ -/* (larger values are displayed first) */ -/*----------------------------------------------------------------*/ -void NOMAD::TGP_Model::display_Ds2x ( const NOMAD::Display & out , - int display_limit ) const -{ - if ( !_Ds2x || _n_XX == 0 ) { - out << "matrix Ds2x has not been computed" << std::endl; - return; - } - - int i , j , k , m = _bbot.size(); - NOMAD::Point * XX_pt; - std::multiset pts; - std::multiset::const_iterator it , end; - - for ( i = 0 ; i < m ; ++i ) { - - if ( m > 1 ) { - std::ostringstream oss; - oss << "output #" << i; - out << NOMAD::open_block ( oss.str() ); - } - - if ( _Ds2x[i] ) { - - // 1. sort: - for ( j = 0 ; j < _n_XX ; ++j ) { - - // construct a NOMAD::Point from matrix _XX: - XX_pt = new NOMAD::Point ( _fv ); - for ( k = 0 ; k < _n0 ; ++k ) - if ( _av_index[k] >= 0 ) - (*XX_pt)[k] = _XX[j][_av_index[k]]; - - // insert this point in the sorted list: - pts.insert ( NOMAD::Model_Sorted_Point ( XX_pt , -_Ds2x[i][j] ) ); - } - - // 2. display: - end = pts.end(); - for ( j = 0 , it = pts.begin() ; it != end ; ++it , ++j ) { - - if ( display_limit <= 0 || j < display_limit ) { - out << "x=( "; - it->get_point()->display ( out , " " , 6 , -1 ); - out << " ) Ds2x=" << it->get_dist()*-1.0 << std::endl; - } - - else if ( j == display_limit ) - out << "..." << std::endl; - - delete it->get_point(); - } - - pts.clear(); - } - else - out << "NULL" << std::endl; - - if ( m > 1 ) - out.close_block(); - } -} - -/*-------------------------------------------------------*/ -/* display the error stats for the interpolation set X */ -/*-------------------------------------------------------*/ -void NOMAD::TGP_Model::display_X_errors ( const NOMAD::Display & out ) -{ - if ( _p == 0 || !_X ) { - out << "no interpolation points" << std::endl; - return; - } - - int i , j , m = _bbot.size(); - NOMAD::Point min_err(m) , max_err(m) , avg_err(m,0.0) , sd_err(m,0.0); - NOMAD::Eval_Point x ( _n , m ); - double ** err = new double * [_p]; - - for ( i = 0 ; i < _p ; ++i ) { - - err[i] = new double[m]; - - for ( j = 0 ; j < _n ; ++j ) - x[j] = _X[i][j]; - - if ( predict ( x , true ) ) { - - for ( j = 0 ; j < m ; ++j ) - if ( _tgp_models[j] ) { - - // relative error (in %) for point #i and output #j: - err[i][j] = ( x.get_bb_outputs()[j].rel_err((_tgp_models[j]->get_Z())[i]) - * 100.0).value(); - - // out << "f=" << (_tgp_models[j]->get_Z())[i] << " " - // << "m=" << x.get_bb_outputs()[j] << " err=" << err[i][j] - // << std::endl; - - if ( !min_err[j].is_defined() || err[i][j] < min_err[j].value() ) - min_err[j] = err[i][j]; - - if ( !max_err[j].is_defined() || err[i][j] > max_err[j].value() ) - max_err[j] = err[i][j]; - - avg_err[j] += err[i][j]; - } - } - else { - for ( j = 0 ; j <= i ; ++j ) - delete [] err[j]; - delete [] err; - out << "cannot predict interpolation errors (" - << _error_str << ")" << std::endl; - return; - } - } - - for ( j = 0 ; j < m ; ++j ) - if ( _tgp_models[j] ) { - - // compute the median error: - NOMAD::Double med_err; - { - if ( _p == 1 ) - med_err = err[0][j]; - else if ( _p == 2 ) - med_err = ( err[0][j] + err[1][j] ) / 2.0; - - else { - std::multiset sorted_errors; - for ( i = 0 ; i < _p ; ++i ) - sorted_errors.insert ( err[i][j] ); - std::multiset::const_iterator it , end = sorted_errors.end(); - --end; - for ( it = sorted_errors.begin() , i = 0 ; it != end ; ++it , ++i ) { - if ( i == (_p+1)/2-1 ) { - med_err = *it; - if ( _p%2==0 ) { - ++it; - med_err = ( med_err + *it ) / 2.0; - } - break; - } - } - } - } - - // compute the mean and the standard deviation: - avg_err[j] /= _p; - for ( i = 0 ; i < _p ; ++i ) - sd_err[j] += ( avg_err[j] - err[i][j] ).pow2(); - sd_err[j] = (sd_err[j] / _p).sqrt(); - - // display: - if ( m > 1 ) { - std::ostringstream oss; - oss << "output #" << j; - if ( _tgp_models[j]->is_fixed() ) - oss << " (fixed)"; - else if ( _tgp_models[j]->is_binary() ) - oss << " (binary)"; - out << NOMAD::open_block ( oss.str() ); - } - - out << "min : "; - min_err[j].display ( out , "%6.2f" ); - out << std::endl << "max : "; - max_err[j].display ( out , "%6.2f" ); - out << std::endl << "median: "; - med_err.display ( out , "%6.2f" ); - out << std::endl << "mean : "; - avg_err[j].display ( out , "%6.2f" ); - out << std::endl << "sd : "; - sd_err[j].display ( out , "%6.2f" ); - out << std::endl; - - if ( m > 1 ) - out.close_block(); - } - - for ( i = 0 ; i < _p ; ++i ) - delete [] err[i]; - delete [] err; -} - -/*--------------------------------------------*/ -/* display */ -/*--------------------------------------------*/ -void NOMAD::TGP_Model::display ( const NOMAD::Display & out ) const -{ - if ( !_error_str.empty() ) { - out << "error with model" << std::endl; - return; - } - - int i , j; - - // fixed variables: - out << "fixed_var = [ " << _fv << "]" << std::endl; - out << "av_index = "; - if ( _av_index ) { - out << "[ "; - for ( i = 0 ; i < _n0 ; ++i ) - out << _av_index[i] << " "; - out << "]" << std::endl; - } - else - out << "NULL" << std::endl; - out << "fv_index = "; - if ( _fv_index ) { - out << "[ "; - for ( i = 0 ; i < _n ; ++i ) - out << _fv_index[i] << " "; - out << "]" << std::endl; - } - else - out << "NULL" << std::endl; - - // bounds: - out << "lb = [ " << _lb << "]" << std::endl - << "ub = [ " << _ub << "]" << std::endl - << std::endl; - - // display X: - if ( !_X ) - out << "X = NULL" << std::endl; - else { - out << "X = ["; - for ( i = 0 ; i < _p ; ++i ) { - out << "\t"; - for ( j = 0 ; j < _n ; ++j ) - out << std::setw(15) << _X[i][j] << " "; - out << ( (i==_p-1) ? "]" : ";" ) << std::endl; - } - out << "size(X)=" << _p << "x" << _n << std::endl << std::endl; - } - - // display XX: - if ( !_XX ) - out << "XX = NULL" << std::endl; - else { - out << "XX = ["; - for ( i = 0 ; i < _n_XX ; ++i ) { - out << "\t"; - for ( j = 0 ; j < _n ; ++j ) - out << std::setw(15) << _XX[i][j] << " "; - out << ( (i==_n_XX-1) ? "]" : ";" ) << std::endl; - } - out << "size(XX)=" << _n_XX << "x" << _n << std::endl << std::endl; - } - - // display models: - out << std::endl; - if ( _tgp_models ) { - int m = _bbot.size(); - for ( i = 0 ; i < m ; ++i ) { - if ( _tgp_models[i] ) { - std::ostringstream oss; - oss << "model #" << i; - out.open_block ( oss.str() ); - _tgp_models[i]->display ( out ); - out.close_block(); - } - else - out << "model #" << i << ": NULL" << std::endl; - out << std::endl; - } - } - else - out << "no models" << std::endl << std::endl; -} - -/*----------------------------------------------------------------*/ -/* access to the width of the interpolation set */ -/*----------------------------------------------------------------*/ -#ifdef MODEL_STATS -NOMAD::Double NOMAD::TGP_Model::get_Yw ( void ) const -{ - NOMAD::Double Yw , tmp; - for ( int i = 0 ; i < _n0 ; ++i ) { - tmp = _ub[i]-_lb[i]; - if ( !Yw.is_defined() || tmp > Yw ) - Yw = tmp; - } - return Yw; -} -#endif - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model.hpp deleted file mode 100644 index 48debd92b..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model.hpp +++ /dev/null @@ -1,397 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Model.hpp - \brief TGP (Bayesian treed Gaussian process) model for all outputs (headers) - \author Sebastien Le Digabel - \date 2011-02-07 - \see TGP_Model.cpp -*/ -#ifdef USE_TGP - -#ifndef __TGP_MODEL__ -#define __TGP_MODEL__ - -#include "TGP_Output_Model.hpp" -#include "Model_Sorted_Point.hpp" -#include "Cache.hpp" - -namespace NOMAD { - - /// TGP models for all outputs. - class TGP_Model : private NOMAD::Uncopyable { - - private: - - const NOMAD::Display & _out; ///< Display. - - std::vector _bbot; ///< Blackbox output types. - - std::string _error_str; ///< Error string. - - int _p; ///< Number of interpolation points. - - int _n0; ///< Original dimension (all variables). - int _n; ///< Number of free variables (\c n \c <= \c n0). - - int _n_XX; ///< Number of points (rows) in \c XX. - - NOMAD::Point _lb; ///< Lower bounds for \c X (size=\c n0). - NOMAD::Point _ub; ///< Upper bounds for \c X (size=\c n0). - NOMAD::Point _fv; ///< Fixed variables for \c X (size=\c n0). - - int * _av_index; ///< All variables index. - int * _fv_index; ///< Free variables index. - // - // avi[j] in [0;n -1], j in [0;n0-1]; avi[j]=-1: var j fixed - // fvi[j] in [0;n0-1], j in [0;n-1] - // - // example with n0=3 and n=2 (second variable is fixed): - // _av_index: [ 0 -1 1 ] - // _fv_index: [ 0 2 ] - - double ** _X; ///< Interpolation matrix \c X (size = \c p \c x \c n). - - double ** _XX; ///< Points at which evaluate the model (prediction points). - - double ** _Ds2x; ///< Expected reduction in predictive variance (\c Ds2x). - - int * _improv; ///< Expected improvement (ranks). - - bool _model_computed; ///< Flag to check if the model has been computed. - bool _nep_flag; ///< 'Not enought points' (nep) flag. - - NOMAD::TGP_mode_type _tgp_mode; ///< TGP mode (fast, precise, or user). - - NOMAD::TGP_Output_Model ** _tgp_models; ///< TGP models (one for each output). - // - // tgp_models[i] may be NULL if bbot[i] - // is not an objective or a constraint - - double ** _tgp_rect; ///< TGP rectangle (bounds). - - int _usr_BTE[3]; ///< User \c BTE parameters (TGP default: 2000,7000,2). - - bool _tgp_linburn; ///< TGP \c linburn parameter. - - int _usr_pmax; ///< User max number of interpolation points in \c X. - - bool _tgp_verb; ///< Display (\c verb) parameter. - - /// Clear memory. - void clear ( void ); - - /// Filter and sort the intepolation set \c X. - /** - \param X Original interpolation set (typically the cache) -- \b IN. - \param center Center of the model (may be NULL) -- \b IN. - \param filtered_X Filtered and sorted interpolation set -- \b OUT. - \return The number of filtered interpolation points. - */ - int filter_and_sort_X - ( const std::vector & X , - const NOMAD::Point * center , - std::list & filtered_X ) const; - - /** - Compute the ranges, check the fixed variables, set the - different indexes, and return the number of free variables. - \param X Filtered and sorted interpolation set -- \b IN. - \param remove_fv Set to \c true to eliminate fixed variables -- \b IN. - \return The number of free variables (member \c _n). - */ - int check_fixed_variables ( const std::list & X , - bool remove_fv ); - - /// Tests to check if an interpolation point is valid for interpolation. - /** - \param x The interpolation point -- \b IN. - \return A boolean equal to \c true if \c x is valid. - */ - bool test_interpolation_point ( const NOMAD::Eval_Point * x ) const; - - /// Get the limits on the interpolation set size \c p. - /** - \param n Number of free variables -- \b IN. - \param pmin Inf limit on \c p the number of interpolation points -- \b OUT. - \param pmax Sup limit on \c p -- \b OUT. - \return A boolean equal to \c true if the limits are valid. - */ - bool get_p_limits ( int n , int & pmin , int & pmax ); - - /// Get the TGP \c BTE parameters. - /** - \param BTE The BTE parameters -- \b OUT. - \return A boolean equal to \c true if the BTE parameters are valid. - */ - bool get_BTE ( int BTE[3] ); - - /// Compute the TGP \c dparam array. - /** - \param n Dimension -- \b IN. - \return A pointer to the \c dparam array. - */ - static double * get_TGP_dparams ( int n ); - - /// Check if the interpolation matrix is of full rank. - /** - \param X The \c X matrix -- \b IN. - \param p Number of rows -- \b IN. - \param n Number of columns -- \b IN. - \return A boolean equal to \c true if \c X is of full rank. - */ - static bool check_full_rank ( double ** X , int p , int n ); - - public: - - /// Constructor 1/2. - /** - \param n0 Dimension including fixed variables -- \b IN. - \param bbot Blackbox output types -- \b IN. - \param out Display object -- \b IN. - \param mode TGP mode (fast or precise only) -- \b IN. - */ - explicit TGP_Model ( int n0 , - const std::vector & bbot , - const NOMAD::Display & out , - NOMAD::TGP_mode_type mode ); - - /// Constructor 2/2 (with no blackbox output types; a value of \c m=1 is taken). - /** - This is the user TGP mode. - \param n0 Dimension including fixed variables -- \b IN. - \param out Display object -- \b IN. - \param BTE TGP \c B, \c T, and \c E parameters -- \b IN. - \param linburn TGP \c linburn parameter -- \b IN. - \param pmax Max number of interpolation points in \c X -- \b IN. - \param verb TGP \c verb parameter -- \b IN. - */ - explicit TGP_Model ( int n0 , - const NOMAD::Display & out , - int BTE[3] , - bool linburn , - int pmax , - bool verb ); - - /// Destructor. - virtual ~TGP_Model ( void ); - - /// Set the interpolation set \c X from a cache. - /** - \param cache Cache of true evaluations -- \b IN. - \param center Center of the model (the incumbent; may be \c NULL) -- \b IN. - \param seed Random seed -- \b IN. - \param remove_fv Set to \c true to eliminate fixed variables -- \b IN. - \return A boolean equal to \c true if no error occured. - */ - bool set_X ( const NOMAD::Cache & cache , - const NOMAD::Point * center , - int seed , - bool remove_fv ); - - /// Set the interpolation set \c X from a set of points. - /** - \param X The set of points -- \b IN. - \param center Center of the model ( may be \c NULL) -- \b IN. - \param seed Random seed -- \b IN. - \param remove_fv Set to \c true to eliminate fixed variables -- \b IN. - \return A boolean equal to \c true if no error occured. - */ - bool set_X ( const std::vector & X , - const NOMAD::Point * center , - int seed , - bool remove_fv ); - - /// Compute the models (one for each output). - /** - \param XX_pts Prediction points -- \b IN/OUT. - \param compute_Ds2x Flag to activate the Ds2x computation -- \b IN. - \param compute_improv Flag to activate the improv computation -- \b IN. - \param pred_outside_bnds If \c false, no prediction outside bounds -- \b IN. - \return A boolean equal to \c true if the model computation worked. - */ - bool compute ( std::vector & XX_pts , - bool compute_Ds2x , - bool compute_improv , - bool pred_outside_bnds ); - - /// Prediction at one point. - /** - \param x The point (size \c _n or \c _n0) -- \b IN. - \param pred_outside_bnds Set to \c false to not predict outside bounds -- \b IN. - \return A boolean equal to \c true if the prediction worked. - */ - bool predict ( NOMAD::Eval_Point & x , bool pred_outside_bnds ); - - /// Compute model \c h and \c f values given one blackbox output. - /** - \param bbo Blackbox output -- \b IN. - \param h_min Value of \c h_min -- \b IN.. - \param h_norm Norm used to compute \c h -- \b IN.. - \param h Value of \c h -- \b OUT. - \param f Value of \c f -- \b OUT. - */ - void eval_hf ( const NOMAD::Point & bbo , - const NOMAD::Double & h_min , - NOMAD::hnorm_type h_norm , - NOMAD::Double & h , - NOMAD::Double & f ) const; - - /// Get the \c XX points with the largest expected improvement of the objective. - /** - \param pts_index The \c XX points indexes -- \b OUT. - */ - void get_improv_points ( std::list & pts_indexes ) const; - - /// Get the \c XX points with the largest expected reduction in predictive variance. - /** - \param pts_index The \c XX points indexes -- \b OUT. - */ - void get_Ds2x_points ( std::set & pts_indexes ) const; - - /// Get error string. - /** - \return The error string. - */ - const std::string & get_error_str ( void ) const { return _error_str; } - - /// Get \c nep flag (nep=not enough points). - /** - \return The nep flag. - */ - bool get_nep_flag ( void ) const { return _nep_flag; } - - /// Access to the number of interpolation points \c p. - /** - \return The number of interpolation points. - */ - int get_p ( void ) const { return _p; } - - /// Access to the number of free variables \c n. - /** - \return The number of free variables. - */ - int get_n ( void ) const { return _n; } - - /// Access to the total number of variables \c n0. - /** - \return The total number of variables. - */ - int get_n0 ( void ) const { return _n0; } - - /// Access to the lower bounds. - /** - \return The lower bounds. - */ - const NOMAD::Point & get_lb ( void ) const { return _lb; } - - /// Access to the upper bounds. - /** - \return The upper bounds. - */ - const NOMAD::Point & get_ub ( void ) const { return _ub; } - -#ifdef MODEL_STATS - /// Access to the width of the interpolation set \c X (or \c Y). - /** - \return The width of the interpolation set. - */ - NOMAD::Double get_Yw ( void ) const; -#endif - - /// Access to improv. - /** - \param i Index in the \c XX matrix -- \b IN. - \return The improv value of the ith point in \c XX. - */ - int get_improv ( int i ) const - { - return ( _improv == NULL || i < 0 || i >= _n_XX ) ? -1 : _improv[i]; - } - - /// Display the expected reduction in predictive variance (\c Ds2x). - /** - \param out Display -- \b IN. - \param display_limit Max number of pts displayed (-1 for no limit) -- \b IN. - */ - void display_Ds2x ( const NOMAD::Display & out , int display_limit = -1 ) const; - - /// Display the expected improvement ranks (\c improv). - /** - \param out Display -- \b IN. - \param display_limit Max number of pts displayed (-1 for no limit) -- \b IN. - */ - void display_improv ( const NOMAD::Display & out , int display_limit = -1 ) const; - - /// Display error stats for the interpolation set \c X. - /** - \param out Display -- \b IN. - */ - void display_X_errors ( const NOMAD::Display & out ); - - /// Display interpolation set \x X. - /** - \param out Display -- \b IN. - \param display_limit Max number of pts displayed (-1 for no limit) -- \b IN. - */ - void display_X ( const NOMAD::Display & out , int display_limit = -1 ) const; - - /// Default display. - void display ( void ) { display ( _out ); } - - /// Display. - /** - \param out Display -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::TGP_Model object. - /** - \param out The NOMAD::Display object -- \b IN. - \param s The NOMAD::TGP_Model object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::TGP_Model & s ) { - s.display ( out ); - return out; - } -} - -#endif - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Evaluator.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Evaluator.cpp deleted file mode 100644 index 16a96775f..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Evaluator.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Model_Evaluator.cpp - \brief NOMAD::Evaluator subclass for TGP model optimization (implementation) - \author Sebastien Le Digabel - \date 2011-02-17 - \see TGP_Mopel_Evaluator.hpp -*/ - -#ifndef USE_TGP - -int TGP_MODEL_EVALUATOR_DUMMY; // avoids that TGP_Model_Evaluator.o has no symbols with ranlib - -#else - -#include "TGP_Model_Evaluator.hpp" - -/*------------------------------------------------------------------------*/ -/* evaluate the TGP model at a given trial point */ -/*------------------------------------------------------------------------*/ -bool NOMAD::TGP_Model_Evaluator::eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const -{ - count_eval = true; - if ( !_model.predict ( x , true ) ) - return false; - return true; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Evaluator.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Evaluator.hpp deleted file mode 100644 index 44ac92651..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Evaluator.hpp +++ /dev/null @@ -1,98 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Model_Evaluator.hpp - \brief NOMAD::Evaluator subclass for TGP model optimization (headers) - \author Sebastien Le Digabel - \date 2011-02-17 - \see TGP_Model_Evaluator.cpp -*/ -#ifdef USE_TGP - -#ifndef __TGP_MODEL_EVALUATOR__ -#define __TGP_MODEL_EVALUATOR__ - -#include "Search.hpp" -#include "Evaluator.hpp" - -namespace NOMAD { - - /// NOMAD::Evaluator subclass for quadratic model optimization. - class TGP_Model_Evaluator : public NOMAD::Evaluator { - - private: - -// int _n; ///< Number of variables. -// int _nm1; ///< Number of variables minus one. -// int _m; ///< Number of blackbox outputs. -// double * _x; ///< An evaluation point. -// double ** _alpha; ///< Model parameters. -// bool _model_ready; ///< \c true if model ready to evaluate. - - NOMAD::TGP_Model & _model; ///< The TGP model. - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - \param model Model -- \b IN. - */ - TGP_Model_Evaluator ( const NOMAD::Parameters & p , - NOMAD::TGP_Model & model ) - : NOMAD::Evaluator ( p ) , - _model ( model ) {} - - /// Destructor. - virtual ~TGP_Model_Evaluator ( void ) {} - - /// Evaluate the blackboxes at a given trial point. - /** - \param x The trial point -- \b IN/OUT. - \param h_max Maximal feasibility value \c h_max -- \b IN. - \param count_eval Flag indicating if the evaluation has to be counted - or not -- \b OUT. - \return A boolean equal to \c false if the evaluation failed. - */ - virtual bool eval_x ( NOMAD::Eval_Point & x , - const NOMAD::Double & h_max , - bool & count_eval ) const; - }; -} - -#endif - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.cpp deleted file mode 100644 index 7b01e3968..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.cpp +++ /dev/null @@ -1,1738 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Model_Search.cpp - \brief TGP Model search (implementation) - \author Sebastien Le Digabel - \date 2011-02-17 - \see TGP_Model_Search.hpp -*/ - -#ifndef USE_TGP - -int TGP_MODEL_SEARCH_DUMMY; // avoids that TGP_Model_Search.o has no symbols with ranlib - -#else - -#include "TGP_Model_Search.hpp" - -/*-----------------------------------*/ -/* reset (virtual) */ -/*-----------------------------------*/ -void NOMAD::TGP_Model_Search::reset ( void ) -{ - if ( _model ) - delete _model; - _model = NULL; -} - -/*--------------------------------------------------------*/ -/* delete a list of points: one version for points, and */ -/* one version for evaluation points (static, private) */ -/*--------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::clear_pts ( std::vector & pts ) -{ - size_t k , n = pts.size(); - for ( k = 0 ; k < n ; ++k ) - delete pts[k]; - pts.clear(); -} - -void NOMAD::TGP_Model_Search::clear_pts ( std::vector & pts ) -{ - size_t k , n = pts.size(); - for ( k = 0 ; k < n ; ++k ) - delete pts[k]; - pts.clear(); -} - -/*------------------------------------------------------------------*/ -/* the search */ -/*------------------------------------------------------------------*/ -/* Search parameters: */ -/* ------------------ */ -/* */ -/* . MODEL_SEARCH: flag to activate the model search (MS) */ -/* (here its value is NOMAD::TGP_MODEL) */ -/* */ -/* . MODEL_SEARCH_OPTIMISTIC: if true, the direction from the */ -/* model center to the trial point */ -/* is computed and prossibly used */ -/* in the speculative search */ -/* default=yes */ -/* */ -/* . MODEL_SEARCH_PROJ_TO_MESH: project or not to mesh */ -/* default=yes */ -/* */ -/* . MODEL_SEARCH_MAX_TRIAL_PTS: limit on the number of trial */ -/* points for one search */ -/* default=10 */ -/* */ -/* . MODEL_TGP_MODE: TGP mode (FAST or PRECISE) */ -/* default=FAST */ -/* */ -/*------------------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - new_feas_inc = new_infeas_inc = NULL; - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - count_search = false; - - _one_search_stats.reset(); - - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - int display_lim = 15; - - if ( stop ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): not performed (stop flag is active)" - << std::endl; - return; - } - - // active cache (we accept only true function evaluations): - const NOMAD::Cache & cache = mads.get_cache(); - if ( cache.get_eval_type() != NOMAD::TRUTH ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): not performed on surrogates" - << std::endl; - return; - } - - // check that there is one objective exactly: - const std::list & index_obj_list = _p.get_index_obj(); - - if ( index_obj_list.empty() ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): not performed with no objective function" - << std::endl; - return; - } - if ( index_obj_list.size() > 1 ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): not performed with biobjective" - << std::endl; - return; - } - - // active barrier: - const NOMAD::Barrier & barrier = mads.get_true_barrier(); - - // get the incumbent: - const NOMAD::Eval_Point * incumbent = barrier.get_best_feasible(); - if ( !incumbent ) - incumbent = barrier.get_best_infeasible(); - if ( !incumbent ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): no incumbent" - << std::endl; - return; - } - - // get and check the signature, and compute the dimension: - NOMAD::Signature * signature = incumbent->get_signature(); - - if ( !signature ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): no signature" - << std::endl; - return; - } - - int n = signature->get_n(); - - if ( n != incumbent->size() ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "TGP_Model_Search::search(): incompatible signature" - << std::endl; - return; - } - - // initial displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << NOMAD::MODEL_SEARCH << " #" - << _all_searches_stats.get_MS_nb_searches(); - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - // from this point the search is counted: - count_search = true; - _one_search_stats.add_MS_nb_searches(); - -// C.Tribes august 26, 2014 --- not needed -// // mesh: -// int mesh_index = NOMAD::Mesh::get_mesh_index(); - NOMAD::Point delta_m; - // B.Talgorn march 7, 2014 --- - //NEWMESH - //signature->get_mesh().get_delta_m ( delta_m , mesh_index ); - signature->get_mesh()->get_delta(delta_m); - - // initial displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) { -#ifdef TGP_DEBUG - out << "seed : " - << _p.get_seed() << std::endl; -#endif - out << "number of cache points: " << cache.size() << std::endl - // C.Tribes august 26, 2014 --- not needed - // << "mesh index : " << mesh_index << std::endl - << "mesh size parameter : ( " << delta_m << " )" << std::endl - << "incumbent : ( "; - incumbent->NOMAD::Point::display - ( out , " " , 2 , NOMAD::Point::get_display_limit() ); - out << " )" << std::endl; - } - - // construct the model: - NOMAD::Stats & stats = mads.get_stats(); - bool compute_Ds2x; - std::vector XX; - std::string error_str; - - if ( !model_construction ( cache , - *incumbent , - delta_m , - out , - display_degree , - display_lim , - stats , - compute_Ds2x , - XX , - stop , - stop_reason , - error_str ) ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block ( "failure: " + error_str ) - << std::endl; - return; - } - - // trial_pts = oracle_pts + Ds2x_pts + improv_pts - // - // oracle_pts: given by the model optimization - // Ds2x_pts : XX points with the largest expected reduction in predictive variance - // improv_pts: XX points with the largest expected improvement for the objective - - int max_pts = _p.get_model_search_max_trial_pts(); - - /*-----------------------*/ - /* oracle points (1/3) */ - /*-----------------------*/ - std::vector oracle_pts; - if ( !create_oracle_pts ( cache , - *incumbent , - delta_m , - out , - display_degree , - display_lim , - XX , - oracle_pts , - stop , - stop_reason ) && stop ) { - - // delete XX and oracle_pts: - NOMAD::TGP_Model_Search::clear_pts ( XX ); - NOMAD::TGP_Model_Search::clear_pts ( oracle_pts ); - - // quit: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::close_block ( "algorithm stop" ) - << std::endl; - return; - } - - /*---------------------*/ - /* Ds2x points (2/3) */ - /*---------------------*/ - std::vector Ds2x_pts; - if ( compute_Ds2x ) - create_Ds2x_pts ( XX , out , display_degree , display_lim , Ds2x_pts ); - - /*-----------------------*/ - /* improv points (3/3) */ - /*-----------------------*/ - std::vector improv_pts; - create_improv_pts ( XX , - *incumbent , - max_pts , - out , - display_degree , - display_lim , - improv_pts ); - - // create the complete list of trial points: - // ----------------------------------------- - std::vector trial_pts; - create_trial_pts ( oracle_pts , - Ds2x_pts , - improv_pts , - *incumbent , - max_pts , - out , - display_degree , - trial_pts ); - - // evaluator control: - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // add the trial points to the evaluator control for evaluation: - int i , nop = trial_pts.size(); - for ( i = 0 ; i < nop ; ++i ) - register_point ( *trial_pts[i] , - *signature , - *incumbent , - // C.Tribes august 26, 2014 --- not needed - // mesh_index , - display_degree , - ev_control ); - - // display the evaluator control list of points: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << std::endl << NOMAD::open_block ( "list of trial points" ); - const std::set & lop = ev_control.get_eval_lop(); - std::set::const_iterator it , end = lop.end(); - nop = lop.size(); - for ( it = lop.begin() , i = 0 ; it != end ; ++it , ++i ) { - out << "#"; - out.display_int_w ( i , nop ); - out << " x=( "; - it->get_point()->NOMAD::Point::display ( out , " " , 15 , -1 ); - out << " )" << std::endl; - } - out.close_block(); - } - - // delete XX and the trial points - // (do not delete Ds2x_pts and improv_pts because - // they are XX points, contrary to oracle_pts): - NOMAD::TGP_Model_Search::clear_pts ( XX ); - NOMAD::TGP_Model_Search::clear_pts ( oracle_pts ); - - nb_search_pts = ev_control.get_nb_eval_points(); - - if ( nb_search_pts == 0 ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "no trial point" << std::endl; - } - - else { - - _one_search_stats.update_MS_max_search_pts ( nb_search_pts ); - - // evaluate the trial points: - // -------------------------- - int bbe = stats.get_bb_eval(); - int sgte_eval = stats.get_sgte_eval (); - int cache_hits = stats.get_cache_hits(); - - new_feas_inc = new_infeas_inc = NULL; - - ev_control.disable_model_eval_sort(); - - std::list * evaluated_pts = NULL; - if ( display_degree == NOMAD::FULL_DISPLAY ) - evaluated_pts = new std::list; - - ev_control.eval_list_of_points ( _type , - mads.get_true_barrier() , - mads.get_sgte_barrier() , - mads.get_pareto_front() , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success , - evaluated_pts ); - - // display the prediction error for the evaluated points: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - display_eval_pred_errors ( *evaluated_pts , out ); - delete evaluated_pts; - } - - ev_control.enable_model_eval_sort(); - - // update stats: - _one_search_stats.add_MS_bb_eval ( stats.get_bb_eval () - bbe ); - _one_search_stats.add_MS_sgte_eval ( stats.get_sgte_eval () - sgte_eval ); - _one_search_stats.add_MS_cache_hits ( stats.get_cache_hits() - cache_hits ); - - if ( success == NOMAD::FULL_SUCCESS ) - _one_search_stats.add_MS_success(); - - _one_search_stats.add_MS_pts ( nb_search_pts ); - } - - // update stats objects: - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - std::ostringstream oss; - oss << "end of " << NOMAD::MODEL_SEARCH << " (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } -} - -/*---------------------------------------------------------------*/ -/* create XX a list of prediction points (private) */ -/*---------------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::set_XX -( const NOMAD::Cache & cache , - int n , - int m , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - std::vector & XX ) const -{ - // . we begin with 1999 points, filter them to remove points - // that appear more than once or in the cache. - // . then we prune the list to 499 points. - // . we do not begin directly with 500 points because it - // gives more flexibility with the projection. - // . we terminate by adding the incumbent. - // --> we obtain a list of at most 500 prediction points. - - int j , i = 0 , n_XX = 1999; // 2000-1 - bool proj_to_mesh = _p.get_model_search_proj_to_mesh(); - bool remove_pt; - - // XX is made of n_XX-1 LH points inside the model bounds - // (and the incumbent will be added at the end): - NOMAD::LH_Search::LH_points ( n, m, n_XX, _model->get_lb(), _model->get_ub(), XX ); - - while ( i < n_XX ) { - - remove_pt = false; - - // project to the mesh: - if ( proj_to_mesh ) - XX[i]->project_to_mesh ( incumbent , delta_m , _p.get_lb() , _p.get_ub() ); - - // remove if point is in cache: - if ( cache.find ( *XX[i] ) ) - remove_pt = true; - - // check if this point is already in XX - // (may occur only if the point has been projected): - if ( proj_to_mesh && !remove_pt ) { - - if ( incumbent == (*XX[i]) ) - remove_pt = true; - - else - for ( j = 0 ; j < i ; ++j ) - if ( XX[j]->NOMAD::Point::operator == ( *XX[i] ) ) { - remove_pt = true; - break; - } - } - - // remove the point: - if ( remove_pt ) { - delete XX[i]; - --n_XX; - if ( i != n_XX ) - XX[i] = XX[n_XX]; - XX.resize ( n_XX ); - } - else - ++i; - } - - // reduce to 500-1 points (we eliminate randomly): - while ( n_XX >= 500 ) { - - i = rand()%n_XX; - - delete XX[i]; - --n_XX; - if ( i != n_XX ) - XX[i] = XX[n_XX]; - XX.resize(n_XX); - } - - // add the incumbent as the last point of XX: - XX.push_back ( new NOMAD::Eval_Point ( n , m ) ); - XX[n_XX]->NOMAD::Point::operator = ( incumbent ); -} - -/*---------------------------------------------------------------------*/ -/* create the complete list of trial points (oracle + Ds2x + improv) */ -/* (private) */ -/*---------------------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::create_trial_pts -( const std::vector & oracle_pts , // IN - const std::vector & Ds2x_pts , // IN - const std::vector & improv_pts , // IN - const NOMAD::Point & incumbent , // IN - int max_pts , // IN - const NOMAD::Display & out , // IN - NOMAD::dd_type display_degree , // IN - std::vector & trial_pts ) const // OUT -{ - bool found; - size_t i , j , - n1 = oracle_pts.size() , - n2 = Ds2x_pts.size () , - n3 = improv_pts.size(); - - std::vector l2 , l3; - - // 1. remove duplicates: - // --------------------- - // - // . oracle_pts are not XX points - // . Ds2x_pts and improv_pts are XX points - // . there is no duplicate in each list separately - // - for ( i = 0 ; i < n2 ; ++i ) { - found = false; - - if ( *Ds2x_pts[i] == incumbent ) - found = true; - else { - for ( j = 0 ; j < n1 ; ++j ) - if ( *Ds2x_pts[i] == *oracle_pts[j] ) { - found = true; - break; - } - } - if ( !found ) - l2.push_back ( Ds2x_pts[i] ); - } - - n2 = l2.size(); - - for ( i = 0 ; i < n3 ; ++i ) { - found = false; - if ( *improv_pts[i] == incumbent ) - found = true; - else { - for ( j = 0 ; j < n1 ; ++j ) - if ( *improv_pts[i] == *oracle_pts[j] ) { - found = true; - break; - } - } - if ( !found ) { - for ( j = 0 ; j < n2 ; ++j ) - if ( improv_pts[i] == l2[j] ) { - found = true; - break; - } - } - if ( !found ) - l3.push_back ( improv_pts[i] ); - } - - n3 = l3.size(); - - // 2. construct the list of trial points: - // ------------------------------------ - trial_pts.clear(); - - int nb_pts = static_cast ( n1 + n2 + n3 ); - - // no need to reduce the number of trial points: - if ( max_pts <= 0 || nb_pts <= max_pts ) { - - - // 1. oracle points: - for ( i = 0 ; i < n1 ; ++i ) - trial_pts.push_back ( oracle_pts[i] ); - - // 2, improv points: - for ( i = 0 ; i < n3 ; ++i ) - trial_pts.push_back ( l3[i] ); - - // 3. Ds2x points: - for ( i = 0 ; i < n2 ; ++i ) - trial_pts.push_back ( l2[i] ); - - } - - // reduce the list to max_pts points: - else { - - nb_pts = 0; - - size_t i1 = 0 , i2 = 0 , i3 = 0; - - while ( true ) { - - // one point from the oracle points: - if ( i1 < n1 ) { - trial_pts.push_back ( oracle_pts[i1++] ); - ++nb_pts; - if ( nb_pts == max_pts ) - break; - } - - // two from the improv points: - for ( i = 0 ; i < 2 ; ++i ) { - if ( i3 < n3 ) { - trial_pts.push_back ( l3[i3++] ); - ++nb_pts; - if ( nb_pts == max_pts ) - break; - } - } - if ( nb_pts == max_pts ) - break; - - // one from the Ds2x points: - if ( i2 < n2 ) { - trial_pts.push_back ( l2[i2++] ); - ++nb_pts; - if ( nb_pts == max_pts ) - break; - } - } - } - - // 3. display the list of trial points: - // ------------------------------------ - // if ( display_degree == NOMAD::FULL_DISPLAY ) { - // out.open_block ( "list of trial points (debug)" ); - // n1 = trial_pts.size(); - // for ( i = 0 ; i < n1 ; ++i ) { - // out << "#"; - // out.display_int_w ( i , n1 ); - // out << " x=( " << *trial_pts[i] << " )" << std::endl; - // } - // out.close_block(); - // } -} - -/*---------------------------------------------------------*/ -/* create the list of improv points (private) */ -/*---------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::create_improv_pts -( const std::vector & XX , // IN - const NOMAD::Point & incumbent , // IN - int max_pts , // IN - const NOMAD::Display & out , // IN - NOMAD::dd_type display_degree , // IN - int display_lim , // IN - std::vector & improv_pts ) const // OUT -{ - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::open_block ( "improv points construction" ) - << std::endl; - - // reset improv points: - improv_pts.clear(); - - // display improv points directly from the NOMAD::TGP_Model object: -#ifdef TGP_DEBUG - out << NOMAD::open_block ( "expected improvement of the objective (improv)" ); - _model->display_improv ( out , display_lim ); - out << NOMAD::close_block() << std::endl; -#endif - - std::list pts_indexes; - _model->get_improv_points ( pts_indexes ); - - if ( pts_indexes.empty() ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "no improv candidate" ) - << std::endl; - return; - } - - std::list::const_iterator it , end = pts_indexes.end(); - - // with constraints, the list is re-sorted in order to put the - // predicred feasible points first: - if ( _p.has_constraints() ) { - - std::list feas_pts , infeas_pts; - - NOMAD::Double h , f; - const NOMAD::Double & h_min = _p.get_h_min(); - - for ( it = pts_indexes.begin() ; it != end ; ++it ) { - if ( predict ( *XX[*it] , h , f ) && h <= h_min ) - feas_pts.push_back ( *it ); - else - infeas_pts.push_back ( *it ); - } - - pts_indexes.clear(); - - end = feas_pts.end(); - for ( it = feas_pts.begin() ; it != end ; ++it ) - pts_indexes.push_back ( *it ); - - end = infeas_pts.end(); - for ( it = infeas_pts.begin() ; it != end ; ++it ) - pts_indexes.push_back ( *it ); - - end = pts_indexes.end(); - } - - // compute max_index just for the display: - int i , j , max_index = -1 , ni = -1; - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - ni = pts_indexes.size(); - if ( max_pts > 0 && ni > max_pts ) - ni = max_pts; - - for ( it = pts_indexes.begin() ; it != end ; ++it ) { - if ( *it > max_index ) - max_index = *it; - } - } - - // add the points to improv_pts: - bool rejected; - i = j = 0; - for ( it = pts_indexes.begin() ; it != end ; ++it ) { - - // we check the max number of points: - rejected = ( max_pts > 0 && max_pts == i ); - - // we reject the point if it is the incumbent: - if ( !rejected && incumbent == *XX[*it] ) - rejected = true; - - // we add the point: - if ( !rejected ) { - improv_pts.push_back ( XX[*it] ); - ++i; - } - - // display: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - if ( display_lim <= 0 || j < display_lim ) { - if ( rejected ) - out << "rejected candidate "; - else { - out << "improv candidate #"; - out.display_int_w ( i-1 , ni ); - } - out << " (XX point #"; - out.display_int_w ( *it , max_index ); - out << "): x=( "; - XX[*it]->NOMAD::Point::display ( out , " " , 6 , -1 ); - out << " )"; - if ( rejected ) { - if ( max_pts > 0 && max_pts == i ) - out << " (max number of points)"; - else - out << " (candidate==incumbent)"; - } - else - out << " improv=" << _model->get_improv(*it); - out << std::endl; - } - if ( display_lim > 0 && j == display_lim ) - out << "..." << std::endl; - ++j; - } - - // if no display, stop the loop if there is already too many points: - else if ( max_pts > 0 && max_pts == i ) - break; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "end of improv points construction" ) - << std::endl; -} - -/*------------------------------------------------------------*/ -/* create the list of Ds2x points, the points that maximize */ -/* the expected reduction in predictive variance */ -/* (private) */ -/*------------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::create_Ds2x_pts -( const std::vector & XX , // IN - const NOMAD::Display & out , // IN - NOMAD::dd_type display_degree , // IN - int display_lim , // IN - std::vector & Ds2x_pts ) const // OUT -{ - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::open_block ( "Ds2x points construction" ) - << std::endl; - - // reset Ds2x points: - Ds2x_pts.clear(); - - // display Ds2x points directly from the NOMAD::TGP_Model object: -#ifdef TGP_DEBUG - out << NOMAD::open_block ( "expected reduction in predictive variance (Ds2x)" ); - _model->display_Ds2x ( out , display_lim ); - out << NOMAD::close_block() << std::endl; -#endif - - std::set pts_indexes; - _model->get_Ds2x_points ( pts_indexes ); - - if ( pts_indexes.empty() ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "no Ds2x candidate" ) - << std::endl; - return; - } - - std::set::const_iterator it , end = pts_indexes.end(); - int i , max_index = -1 , m = _p.get_bb_nb_outputs() , n_XX = XX.size(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - for ( it = pts_indexes.begin() ; it != end ; ++it ) { - if ( *it > max_index ) - max_index = *it; - } - } - - for ( it = pts_indexes.begin() , i = 0 ; it != end ; ++it , ++i ) { - - Ds2x_pts.push_back ( XX[*it] ); - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << "Ds2x candidate #"; - out.display_int_w ( i , m ); - out << " (XX point #"; - out.display_int_w ( *it , max_index ); - out << "): x=( "; - XX[*it]->NOMAD::Point::display ( out , " " , 6 , -1 ); - out << " )"; - if ( *it == n_XX - 1 ) - out << " (rejected: candidate==incumbent)"; - out << std::endl; - } - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "end of Ds2x points construction" ) - << std::endl; -} - -/*-------------------------------------------------------------------*/ -/* create a list of oracle points, given by the model optimization */ -/* (private) */ -/*-------------------------------------------------------------------*/ -bool NOMAD::TGP_Model_Search::create_oracle_pts -( const NOMAD::Cache & cache , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - int display_lim , - const std::vector & XX , - std::vector & oracle_pts , - bool & stop , - NOMAD::stop_type & stop_reason ) -{ - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << NOMAD::open_block ( "oracle points construction" ) - << std::endl; - - // reset oracle points: - NOMAD::TGP_Model_Search::clear_pts ( oracle_pts ); - - int i , n_XX = XX.size(); - - // starting points selection: - const NOMAD::Eval_Point * x0s[3]; - x0s[0] = x0s[1] = x0s[2] = NULL; - - // open display block for model predictions: -#ifdef TGP_DEBUG - out << NOMAD::open_block ( "TGP predictions (XX+ZZ)"); - int i0 = ( display_lim > 0 ) ? n_XX - display_lim : 0; - if ( i0 > 0 ) - out << "..." << std::endl; -#endif - - NOMAD::Double f_model , h_model; - const NOMAD::Double & h_min = _p.get_h_min(); - NOMAD::hnorm_type h_norm = _p.get_h_norm(); - - for ( i = 0 ; i < n_XX ; ++i ) { - - // compute model h and f values: - _model->eval_hf ( XX[i]->get_bb_outputs() , - h_min , - h_norm , - h_model , - f_model ); - - if ( h_model.is_defined() && f_model.is_defined() ) { - - XX[i]->set_f ( f_model ); - XX[i]->set_h ( h_model ); - - // feasible point: - if ( XX[i]->is_feasible ( h_min ) ) { - if ( !x0s[0] || f_model < x0s[0]->get_f() ) - x0s[0] = XX[i]; - } - - // infeasible point: - else { - if ( !x0s[1] || h_model < x0s[1]->get_h() ) - x0s[1] = XX[i]; - - if ( !x0s[2] || f_model < x0s[2]->get_f() ) - x0s[2] = XX[i]; - } - } - - // display model predictions: -#ifdef TGP_DEBUG - if ( i >= i0 ) { - out << "#"; - out.display_int_w ( i , n_XX ); - out << " x=("; - XX[i]->NOMAD::Point::display ( out , " " , 15 , -1 ); - out << " ) m(x)=["; - XX[i]->get_bb_outputs().display ( out , " " , 15 , -1 ); - out << " ]"; - - if ( h_model.is_defined() && f_model.is_defined() ) - out << " hm=" << h_model << " fm=" << f_model; - else - out << " no model value"; - out << std::endl; - } -#endif - -#ifdef MODEL_STATS - if ( XX[i] && f_model.is_defined() && h_model.is_defined() ) { - XX[i]->set_mod_use ( 1 ); // 1 for model search - XX[i]->set_Yw ( _model->get_Yw () ); - XX[i]->set_nY ( p ); - XX[i]->set_mh ( h_model ); - XX[i]->set_mf ( f_model ); - } -#endif - } - -#ifdef TGP_DEBUG - // close display block for model predictions: - { - std::ostringstream oss; - oss << "(size=" << n_XX << ")"; - out << NOMAD::close_block ( oss.str() ) << std::endl; - } - - // compute and display prediction errors: - out << NOMAD::open_block ( "prediction relative errors on X(%)" ); - _model->display_X_errors ( out ); - out << NOMAD::close_block() << std::endl; - -#endif - - if ( !x0s[0] && !x0s[1] && !x0s[2] ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "oracle points error: no model starting point" ) - << std::endl; - return false; - } - - // display starting points: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << std::endl - << NOMAD::open_block ( "model starting points" ); - - for ( i = 0 ; i < 3 ; ++i ) { - - out << "#" << i << ": "; - if ( !x0s[i] ) - out << "NULL" << std::endl; - else { - - out << " x=("; - x0s[i]->NOMAD::Point::display ( out , " " , 15 , -1 ); - out << " ) m(x)=["; - x0s[i]->get_bb_outputs().display ( out , " " , 15 , -1 ); - out << " ]" - << " hm=" << std::setw(15) << x0s[i]->get_h() - << " fm=" << std::setw(15) << x0s[i]->get_f() - << std::endl; - } - } - out << NOMAD::close_block() << std::endl; - } - - // optimize model: - // --------------- - NOMAD::Point * xf = NULL , * xi = NULL; - NOMAD::Clock clock; - - bool optimization_ok = optimize_model ( x0s , - out , - display_degree , - xf , - xi , - stop , - stop_reason ); - - _one_search_stats.add_optimization_time ( clock.get_CPU_time() ); - - if ( stop || !optimization_ok || ( xf == NULL && xi == NULL ) ) { - std::string error_str; - if ( xf == NULL && xi == NULL ) - error_str = "no model optimization solution"; - else { - if ( xf ) delete xf; - if ( xi ) delete xi; - error_str = ( stop ) ? "algorithm stop" : "model optimization error"; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "oracle points error: " + error_str ) - << std::endl; - return false; - } - - // project and check xf and xi: - if ( xf && !check_oracle_point ( cache , - incumbent , - delta_m , - out , - display_degree , - *xf ) ) { - delete xf; - xf = NULL; - } - - if ( xi && !check_oracle_point ( cache , - incumbent , - delta_m , - out , - display_degree , - *xi ) ) { - delete xi; - xi = NULL; - } - - // add xf and xi in the list of oracle points: - if ( xf ) - oracle_pts.push_back ( xf ); - - if ( xi ) { - - // check that xi != xf: - if ( xf && *xf == *xi ) { - delete xi; - xi = NULL; - } - - if ( xi ) - oracle_pts.push_back ( xi ); - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::close_block ( "end of oracle points construction" ) - << std::endl; - - return true; -} - -/*------------------------------------------------------*/ -/* project and accept or reject an oracle trial point */ -/* (private) */ -/*------------------------------------------------------*/ -bool NOMAD::TGP_Model_Search::check_oracle_point -( const NOMAD::Cache & cache , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - NOMAD::Point & x ) -{ - bool proj_to_mesh = _p.get_model_search_proj_to_mesh(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << std::endl << "oracle candidate"; - if ( proj_to_mesh ) - out << " (before projection)"; - out << ": ( " << x << " )" << std::endl; - } - - // projection to mesh: - if ( proj_to_mesh ) { - x.project_to_mesh ( incumbent , delta_m , _p.get_lb() , _p.get_ub() ); - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "oracle candidate (after projection) : ( " - << x << " )" << std::endl; - } - - // compare x and incumbent coordinates: - if ( x == incumbent ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "oracle candidate rejected (candidate==incumbent)" << std::endl; - return false; - } - - // two evaluations points are created in order to: - // 1. check if the candidate is in cache - // 2. have a prediction at x and at the incumbent: - int n = x.size() , m = _p.get_bb_nb_outputs(); - - NOMAD::Eval_Point * tk = new NOMAD::Eval_Point ( n , m ); // trial point - tk->Point::operator = ( x ); - - // check if the point is in cache: - if ( cache.find ( *tk ) ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "oracle candidate rejected (found in cache)" << std::endl; - delete tk; - return false; - } - - NOMAD::Eval_Point * ic = new NOMAD::Eval_Point ( n , m ); // incumbent copy - ic->Point::operator = ( incumbent ); - - // model predictions (in order to accept or reject the trial point): - bool pred_error = !_model->predict ( *ic , true ) || // pred_outside_bnds = true - !_model->predict ( *tk , true ); // pred_outside_bnds = true - - const NOMAD::Double & h_min = _p.get_h_min(); - NOMAD::hnorm_type h_norm = _p.get_h_norm(); - - NOMAD::Double h0 , f0; // model values of f and h at the center - NOMAD::Double h1 , f1; // model values of f and h at the trial point - - if ( !pred_error ) - _model->eval_hf ( tk->get_bb_outputs() , h_min , h_norm , h1 , f1 ); - - delete tk; - - if ( pred_error || !h1.is_defined() || !f1.is_defined() ) { - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - if ( pred_error ) - out << "prediction error: oracle candidate rejected"; - else - out << "no model value (EB constraint violated?): oracle candidate rejected"; - out << std::endl; - } - - delete ic; - - return false; - } - - // accept or reject the trial point: - bool accept_point = false; - _model->eval_hf ( ic->get_bb_outputs(), h_min, h_norm, h0, f0 ); - if ( !h0.is_defined() || !f0.is_defined() ) - accept_point = true; - - delete ic; - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl - << "incumbent prediction : h0=" << h0 << " f0=" << f0 << std::endl - << "trial point prediction: h1=" << h1 << " f1=" << f1 << std::endl; - - if ( !accept_point ) - accept_point = (f1 < f0) || (h1 < h0); - - if ( !accept_point ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "oracle candidate rejected" << std::endl; - _one_search_stats.add_MS_rejected(); - return false; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "oracle candidate accepted" << std::endl; - - return true; -} - -/*--------------------------------------------------------*/ -/* insert a trial point in the evaluator control object */ -/* (private) */ -/*--------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::register_point -( NOMAD::Point x , - NOMAD::Signature & signature , - const NOMAD::Point & incumbent , - // C.Tribes august 26, 2014 --- mesh_index not needed - // int mesh_index , - NOMAD::dd_type display_degree , - NOMAD::Evaluator_Control & ev_control ) const -{ - int n = x.size(); - - NOMAD::Eval_Point * tk = new NOMAD::Eval_Point ( n , _p.get_bb_nb_outputs() ); - - // if the search is optimistic, a direction is computed (this - // will be used in case of success in the speculative search): - if ( _p.get_model_search_optimistic() ) { - NOMAD::Direction dir ( n , 0.0 , NOMAD::MODEL_SEARCH_DIR ); - dir.Point::operator = ( x - incumbent ); - tk->set_direction ( &dir ); - } - - tk->set_signature ( &signature ); - // B.Talgorn march 7, 2014 --- - //NEWMESH : mesh_index is not needed anymore. It is included in the signature. - //tk->set_mesh_index ( &mesh_index ); - tk->Point::operator = ( x ); - - // add the new point to the list of search trial points: - ev_control.add_eval_point ( tk , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); -#ifdef MODEL_STATS - if ( tk ) { - NOMAD::Double h1 , f1; - if ( _model->predict ( *tk , true ) ) // pred_outside_bnds = true - _model->eval_hf ( tk->get_bb_outputs() , - _p.get_h_min() , - _p.get_h_norm() , - h1 , - f1 ); - if ( h1.is_defined() && f1.is_defined() ) { - tk->set_mod_use ( 1 ); // 1 for model search - tk->set_Yw ( _model->get_Yw() ); - tk->set_nY ( model.get_p () ); - tk->set_mh ( h1 ); - tk->set_mf ( f1 ); - } - } -#endif -} - -/*---------------------------------------------------------------*/ -/* model construction (private) */ -/*---------------------------------------------------------------*/ -bool NOMAD::TGP_Model_Search::model_construction -( const NOMAD::Cache & cache , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - int display_lim , - NOMAD::Stats & stats , - bool & compute_Ds2x , - std::vector & XX , - bool & stop , - NOMAD::stop_type & stop_reason , - std::string & error_str ) -{ - int i , n_XX , n = incumbent.size(); - - compute_Ds2x = false; - - // reset XX: - { - n_XX = XX.size(); - for ( i = 0 ; i < n_XX ; ++i ) - delete XX[i]; - XX.clear(); - n_XX = 0; - } - - error_str.clear(); - - if ( stop ) - return false; - - NOMAD::Clock clock; - - // TGP model creation: - if ( _model ) - delete _model; - - NOMAD::TGP_mode_type tgp_mode = _p.get_model_tgp_mode(); - - _model = new NOMAD::TGP_Model ( n , - _p.get_bb_output_type() , - out , - tgp_mode ); - - // construct interpolation set (X): - // -------------------------------- - if ( !_model->set_X ( cache , - &incumbent , - _p.get_seed() , - true ) ) { // remove_fv = true - - if ( _model->get_nep_flag() ) - _one_search_stats.add_not_enough_pts(); - - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - - error_str = _model->get_error_str(); - - delete _model; - _model = NULL; - - return false; - } - - // create the list of prediction points (XX) - // (they are used to get starting points - // and to get IMPROV and DS2X stats): - // ----------------------------------- - set_XX ( cache , - n , - _p.get_bb_output_type().size() , - incumbent , - delta_m , - XX ); - - n_XX = XX.size(); - - // display sets X and XX: - // ---------------------- -#ifdef TGP_DEBUG - - // X: - _model->display_X ( out , display_lim ); - - // XX (only the 10 last points are displayed): - out << NOMAD::open_block ( "prediction points (XX)"); - int i0 = ( display_lim > 0 ) ? n_XX - display_lim : 0; - if ( i0 > 0 ) - out << "..." << std::endl; - else if ( i0 < 0 ) - i0 = 0; - for ( i = i0 ; i < n_XX ; ++i ) { - out << "#"; - out.display_int_w ( i , n_XX ); - out << " x=("; - XX[i]->NOMAD::Point::display ( out , " " , 15 , -1 ); - out << " )" << std::endl; - } - std::ostringstream oss; - oss << "(size=" << n_XX << ")"; - out << NOMAD::close_block ( oss.str() ) << std::endl; -#endif - - // model construction: - // ------------------- - int p = _model->get_p(); // number of points in X - - if ( display_degree == NOMAD::FULL_DISPLAY ) { - out << "TGP model construction (p=" - << p << ") ..."; - out.flush(); - } - - // decide compute_Ds2x flag: - compute_Ds2x = true; - if ( tgp_mode == NOMAD::TGP_PRECISE && n_XX > 100 ) - compute_Ds2x = false; - - if ( !_model->compute ( XX , - compute_Ds2x , - true , // compute_improv = true - false ) ) { // pred_outside_bnds = false - - _one_search_stats.add_construction_error(); - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "... error" << std::endl; - - // delete XX points: - for ( i = 0 ; i < n_XX ; ++i ) - delete XX[i]; - XX.clear(); - n_XX = 0; - - stats.update_model_stats ( _one_search_stats ); - _all_searches_stats.update ( _one_search_stats ); - - error_str = _model->get_error_str(); - - delete _model; - _model = NULL; - - // check if ctrl-c has been pressed: - if ( NOMAD::TGP_Output_Model::get_force_quit() ) { - stop = true; - stop_reason = NOMAD::CTRL_C; - } - - return false; - } - - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << "... OK" << std::endl << std::endl; - - // update model stats: - _one_search_stats.add_construction_time ( clock.get_CPU_time() ); - _one_search_stats.update_nY ( p ); - _one_search_stats.add_nb_truth(); - _one_search_stats.add_nb_TGP(); - - return true; -} - -/*---------------------------------------------------------------*/ -/* optimize a model (private) */ -/*---------------------------------------------------------------*/ -bool NOMAD::TGP_Model_Search::optimize_model -( const NOMAD::Eval_Point * x0s[3] , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - NOMAD::Point *& xf , - NOMAD::Point *& xi , - bool & stop , - NOMAD::stop_type & stop_reason ) -{ - // reset xf and xi: - if ( xf ) delete xf; xf = NULL; - if ( xi ) delete xi; xi = NULL; - - if ( !_model ) { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "model optimization error (no model)" - << std::endl; - return false; - } - - std::string error_str; - bool error = false; - int i , n = _model->get_n0(); - - // model bounds: - const NOMAD::Point & lb = _model->get_lb(); - const NOMAD::Point & ub = _model->get_ub(); - - // initial displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << NOMAD::open_block ( "model optimization" ); - - // parameters creation: - NOMAD::Parameters model_param ( out ); - - // C.Tribes august 26, 2014 --- Seed is provided once when reading parameter file or NOMAD::Parameters::set_SEED function - // random seed: - // model_param.set_SEED ( _p.get_seed() + 10*_all_searches_stats.get_MS_nb_searches() ); - - // number of variables: - model_param.set_DIMENSION ( n ); - - // blackbox outputs: - model_param.set_BB_OUTPUT_TYPE ( _p.get_bb_output_type() ); - - // C.Tribes august 26, 2014 --- all variables are treated as continuous (integer and binary. Categoricals disable models anyway). Projection on mesh is done later. - // C.Tribes august 26, --- this change prevents an exception when fixed variables are detected - // model_param.set_BB_INPUT_TYPE ( _p.get_bb_input_type() ); - // blackbox inputs: - // Default: all variables are treated as continuous - - // barrier parameters: - model_param.set_H_MIN ( _p.get_h_min () ); - model_param.set_H_NORM ( _p.get_h_norm() ); - - // starting points: - for ( i = 0 ; i < 3 ; ++i ) - if ( x0s[i] ) - model_param.set_X0 ( *x0s[i] ); - - // fixed variables: - for ( i = 0 ; i < n ; ++i ) - if ( lb[i] == ub[i] || _p.variable_is_fixed(i) ) - model_param.set_FIXED_VARIABLE(i); - - // no model search and no model ordering: - model_param.set_MODEL_SEARCH ( false ); - model_param.set_MODEL_EVAL_SORT ( false ); - - // display: - model_param.set_DISPLAY_DEGREE ( NOMAD::NO_DISPLAY ); - if ( display_degree == NOMAD::FULL_DISPLAY ) { - - model_param.set_DISPLAY_DEGREE ( NOMAD::NORMAL_DISPLAY ); - // model_param.set_DISPLAY_DEGREE ( NOMAD::FULL_DISPLAY ); - - if ( n <= 5 ) - model_param.set_DISPLAY_STATS ( "bbe mesh_index ( %14.12gsol ) %14.12gobj" ); - else if ( n <= 10 ) - model_param.set_DISPLAY_STATS ( "bbe mesh_index ( sol ) obj" ); - else - model_param.set_DISPLAY_STATS ( "bbe obj" ); - } -// C.Tribes august 26, 2014 --- modif for OrthogonalMesh -// // mesh: -// int mesh_index = NOMAD::Mesh::get_mesh_index(); -// int min_mesh_index = NOMAD::Mesh::get_min_mesh_index(); -// int max_mesh_index = NOMAD::Mesh::get_max_mesh_index(); -// int max_halton_index = NOMAD::Mesh::get_max_halton_index(); -// -// NOMAD::Mesh::init ( 4.0 , 1 , -1 , 0 ); - // mesh: use isotropic mesh - model_param.set_ANISOTROPIC_MESH ( false ); - model_param.set_MESH_UPDATE_BASIS ( 4.0 ); - model_param.set_MESH_COARSENING_EXPONENT ( 1 ); - model_param.set_MESH_REFINING_EXPONENT ( -1 ); - model_param.set_INITIAL_MESH_INDEX ( 0 ); - - - // searches: - // model_param.set_LH_SEARCH ( 1000 , 100 ); - // model_param.set_OPPORTUNISTIC_LH ( true ); - // model_param.set_VNS_SEARCH ( true ); - - // maximum number of evaluations (2000 or 10000): - model_param.set_MAX_BB_EVAL - ( ( _p.get_model_tgp_mode() == NOMAD::TGP_PRECISE ) ? 10000 : 2000 ); - - // min mesh size: - // model_param.set_MAX_MESH_INDEX ( 30 ); - // model_param.set_MIN_MESH_SIZE ( NOMAD::Double ( 1e-8 ) , false ); - - model_param.set_SNAP_TO_BOUNDS ( true ); - // model_param.set_SNAP_TO_BOUNDS ( false ); - - // disable user calls: - model_param.set_USER_CALLS_ENABLED ( false ); - - // set flags: - bool flag_check_bimads , flag_reset_mesh , flag_reset_barriers , flag_p1_active; - NOMAD::Mads::get_flags ( flag_check_bimads , - flag_reset_mesh , - flag_reset_barriers , - flag_p1_active ); - - NOMAD::Mads::set_flag_check_bimads ( true ); - NOMAD::Mads::set_flag_reset_mesh ( true ); - NOMAD::Mads::set_flag_reset_barriers ( true ); - NOMAD::Mads::set_flag_p1_active ( false ); - - // bounds: - model_param.set_LOWER_BOUND ( lb ); - model_param.set_UPPER_BOUND ( ub ); - - try { - - // parameters validation: - model_param.check(); - - // out << "TGP PARAMETERS:" << std::endl << model_param << std::endl; - - // model evaluator creation: - NOMAD::TGP_Model_Evaluator ev ( model_param , *_model ); - - // algorithm creation and execution: - NOMAD::Mads mads ( model_param , &ev ); - NOMAD::stop_type st = mads.run(); - - // check the stopping criterion: - if ( st == NOMAD::CTRL_C || st == NOMAD::MAX_CACHE_MEMORY_REACHED ) { - std::ostringstream oss; - oss << "model optimization: " << st; - error_str = oss.str(); - error = true; - stop = true; - stop_reason = st; - } - - else if ( st == NOMAD::MAX_BB_EVAL_REACHED ) - _one_search_stats.add_MS_max_bbe(); - - // update the stats on the number of model evaluations: - _one_search_stats.update_MS_model_opt ( mads.get_stats().get_bb_eval() ); - - // get the solution(s): - const NOMAD::Eval_Point * best_feas = mads.get_best_feasible (); - const NOMAD::Eval_Point * best_infeas = mads.get_best_infeasible(); - - if ( best_feas ) - xf = new NOMAD::Point ( *best_feas ); - if ( best_infeas ) - xi = new NOMAD::Point ( *best_infeas ); - - if ( !xf && !xi ) { - error = true; - error_str = "optimization error: no solution"; - } - } - catch ( std::exception & e ) { - error = true; - error_str = std::string ( "optimization error: " ) + e.what(); - } - - // reset flags: - NOMAD::Mads::set_flag_check_bimads ( flag_check_bimads ); - NOMAD::Mads::set_flag_reset_mesh ( flag_reset_mesh ); - NOMAD::Mads::set_flag_reset_barriers ( flag_reset_barriers ); - NOMAD::Mads::set_flag_p1_active ( flag_p1_active ); - -// C.Tribes august 26, 2014 --- not needed with orthogonalMesh -// // reset mesh to what it was before: -// NOMAD::Mesh::init ( _p.get_mesh_update_basis().value() , -// _p.get_mesh_coarsening_exponent() , -// _p.get_mesh_refining_exponent() , -// _p.get_initial_mesh_index() ); -// -// NOMAD::Mesh::set_max_halton_index ( max_halton_index ); -// -// NOMAD::Mesh::set_mesh_index ( min_mesh_index ); -// NOMAD::Mesh::set_mesh_index ( max_mesh_index ); -// NOMAD::Mesh::set_mesh_index ( mesh_index ); - - // close display block: - if ( display_degree == NOMAD::FULL_DISPLAY ) { - if ( error ) - out.close_block ( error_str ); - else - out.close_block(); - } - - return !error; -} - -/*---------------------------------------------------------*/ -/* display the prediction error for the evaluated points */ -/* (private) */ -/*---------------------------------------------------------*/ -bool NOMAD::TGP_Model_Search::predict ( const NOMAD::Point & x , - NOMAD::Double & h , - NOMAD::Double & f ) const -{ - h.clear(); - f.clear(); - - if ( !_model ) - return false; - - NOMAD::Eval_Point y ( x.size() , _p.get_bb_nb_outputs() ); - y.NOMAD::Point::operator = ( x ); - - if ( _model->predict ( y , true ) ) // pred_outside_bnds = true - _model->eval_hf ( y.get_bb_outputs() , _p.get_h_min() , _p.get_h_norm() , h , f ); - - return ( h.is_defined() && f.is_defined() ); -} - -/*---------------------------------------------------------*/ -/* display the prediction error for the evaluated points */ -/* (private) */ -/*---------------------------------------------------------*/ -void NOMAD::TGP_Model_Search::display_eval_pred_errors -( const std::list & evaluated_pts , - const NOMAD::Display & out ) -{ - if ( !_model ) - return; - - int i , j = 0; - int nb_pts = evaluated_pts.size() , - n = _model->get_n0() , - m = _p.get_bb_nb_outputs(); - const NOMAD::Double & h_min = _p.get_h_min(); - NOMAD::hnorm_type h_norm = _p.get_h_norm(); - NOMAD::Double h , f , hm , fm , err; - NOMAD::Eval_Point x ( n , m ); - - out << std::endl << NOMAD::open_block ( "evaluated points" ); - std::list::const_iterator it , end = evaluated_pts.end(); - for ( it = evaluated_pts.begin() ; it != end ; ++it ) { - - if ( !(*it) ) - continue; - - h = (*it)->get_h(); - f = (*it)->get_f(); - - for ( i = 0 ; i < n ; ++i ) - x[i] = (**it)[i]; - - _model->predict ( x , true ); // pred_outside_bnds = true - _model->eval_hf ( x.get_bb_outputs(), h_min , h_norm , hm , fm ); - - out << "#"; - out.display_int_w ( j++ , nb_pts ); - - out << " x=("; - if ( n < 5 ) - (*it)->NOMAD::Point::display ( out , " " , 6 , -1 ); - else - (*it)->NOMAD::Point::display ( out , " " , -1 , 20 ); - out << ")"; - if ( _p.has_constraints() ) { - err = (h.is_defined() && hm.is_defined()) ? h.rel_err(hm) * 100.0 : 100.0; - out << " [h="; - h.display ( out , "%11.3g" ); - out << " hm="; - hm.display ( out , "%11.3g" ); - out << " err_h="; - err.display ( out , "%.2f" ); - out << "%]"; - } - err = (f.is_defined() && fm.is_defined()) ? f.rel_err(fm) * 100.0 : 100.0; - out << " [f="; - f.display ( out , "%11.3g" ); - out << " fm="; - fm.display ( out , "%11.3g" ); - out << " err_f="; - err.display ( out , "%.2f" ); - out << "%]" << std::endl; - } - - out.close_block(); -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.hpp deleted file mode 100644 index 6b22f1911..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Model_Search.hpp +++ /dev/null @@ -1,334 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Model_Search.hpp - \brief TGP Model search (headers) - \author Sebastien Le Digabel - \date 2011-02-17 - \see TGP_Model_Search.cpp -*/ -#ifdef USE_TGP - -#ifndef __TGP_MODEL_SEARCH__ -#define __TGP_MODEL_SEARCH__ - -#include "LH_Search.hpp" -#include "TGP_Model_Evaluator.hpp" - -namespace NOMAD { - - /// Model search. - class TGP_Model_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - private: - - NOMAD::TGP_Model * _model; - - NOMAD::Model_Stats _one_search_stats; ///< Stats for one search. - NOMAD::Model_Stats _all_searches_stats; ///< Stats for all searches. - - /// Delete a list of points. - /** - \param pts The points -- \b IN/OUT. - */ - static void clear_pts ( std::vector & pts ); - - /// Delete a list of evaluation points. - /** - \param pts The points -- \b IN/OUT. - */ - static void clear_pts ( std::vector & pts ); - - /// Model construction. - /** - \param cache Cache of true evaluations -- \b IN. - \param incumbent The incumbent -- \b IN. - \param delta_m Mesh size parameter -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param display_lim Max number of pts when sets are displayed -- \b IN. - \param stats Model search stats -- \b IN/OUT. - \param compute_Ds2x Flag to enable/disable Ds2x computation -- \b OUT. - \param XX The set of prediction points -- \b OUT. - \param stop Stop flag -- \b OUT. - \param stop_reason Stop reason -- \b OUT. - \param error_std Error string -- \b OUT. - \return A boolean equal to \c true if the model has been constructed. - */ - bool model_construction ( const NOMAD::Cache & cache , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - int display_lim , - NOMAD::Stats & stats , - bool & compute_Ds2x , - std::vector & XX , - bool & stop , - NOMAD::stop_type & stop_reason , - std::string & error_str ); - - /// Create a list of prediction points. - /** - \param cache Cache of true evaluations -- \b IN. - \param n Number of variables -- \b IN. - \param m Number of outputs -- \b IN. - \param incumbent The incumbent -- \b IN. - \param delta_m Mesh size parameter -- \b IN. - \param XX The set of prediction points -- \b OUT. - */ - void set_XX ( const NOMAD::Cache & cache , - int n , - int m , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - std::vector & XX ) const; - - /// Create the complete list of trial points (oracle + Ds2x + improv). - /** - \param oracle_pts Oracle points -- \b IN. - \param Ds2x_pts Ds2x points -- \b IN. - \param improv_pts Improv points -- \b IN. - \param incumbent The incumbent -- \b IN. - \param max_pts Max number of trial points -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param trial_pts The list of trial points -- \b OUT. - */ - void create_trial_pts - ( const std::vector & oracle_pts , - const std::vector & Ds2x_pts , - const std::vector & improv_pts , - const NOMAD::Point & incumbent , - int max_pts , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - std::vector & trial_pts ) const; - - /// Create oracle points by optimizing the model. - /** - \param cache Cache of true evaluations -- \b IN. - \param incumbent The incumbent -- \b IN. - \param delta_m Mesh size parameter -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param display_lim Max number of pts when sets are displayed -- \b IN. - \param XX The set of prediction points -- \b IN. - \param oracle_pts Oracle candidates points -- \b OUT. - \param stop Stop flag -- \b OUT. - \param stop_reason Stop reason -- \b OUT. - \return A boolean equal to \c true oracle points are proposed. - */ - bool create_oracle_pts - ( const NOMAD::Cache & cache , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - int display_lim , - const std::vector & XX , - std::vector & oracle_pts , - bool & stop , - NOMAD::stop_type & stop_reason ); - - /// Model optimization. - /** - \param x0s The three starting points -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param xf Feasible solution \c xf -- \b OUT. - \param xi Infeasible solution \c xi -- \b OUT. - \param stop Stop flag -- \b OUT. - \param stop_reason Stop reason -- \b OUT. - */ - bool optimize_model ( const NOMAD::Eval_Point * x0s[3] , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - NOMAD::Point *& xf , - NOMAD::Point *& xi , - bool & stop , - NOMAD::stop_type & stop_reason ); - - /// Project and accept or reject an oracle trial point. - /** - \param cache Cache of true evaluations -- \b IN. - \param incumbent The incumbent -- \b IN. - \param delta_m Mesh size parameter -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param x The oracle point -- \b IN/OUT. - \return A boolean equal to \c true if the point is accepted. - */ - bool check_oracle_point - ( const NOMAD::Cache & cache , - const NOMAD::Point & incumbent , - const NOMAD::Point & delta_m , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - NOMAD::Point & x ); - - /// Insert a trial point in the evaluator control object. - /** - \param x The point coordinates -- \b IN. - \param signature Signature -- \b IN. - \param incumbent The incumbent -- \b IN. - \param display_degree Display degree -- \b IN. - \param ev_control The NOMAD::Evaluator_Control object -- \b IN/OUT. - */ - void register_point ( NOMAD::Point x , - NOMAD::Signature & signature , - const NOMAD::Point & incumbent , - // C.Tribes august 26, 2014 --- not needed - // int mesh_index , - NOMAD::dd_type display_degree , - NOMAD::Evaluator_Control & ev_control ) const; - - /// Create the list of improv points. - /** - These points (from the set \c XX) maximize - the expected improvement of the objective. - Priority is given to predicted feasible points. - \param XX The set of prediction points -- \b IN. - \param incumbent The incumbent -- \b IN. - \param max_pts Max number of points -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param display_lim Max number of pts when sets are displayed -- \b IN. - \param Ds2x_pts The list of improv points -- \b OUT. - */ - void create_improv_pts - ( const std::vector & XX , - const NOMAD::Point & incumbent , - int max_pts , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - int display_lim , - std::vector & improv_pts ) const; - - /// Create the list of Ds2x points. - /** - These points (from the set \c XX) maximize the expected reduction in - predictive variance for each output. - \param XX The set of prediction points -- \b IN. - \param out The NOMAD::Display object -- \b IN. - \param display_degree Display degree -- \b IN. - \param display_lim Max number of pts when sets are displayed -- \b IN. - \param Ds2x_pts The list of Ds2x points -- \b OUT. - */ - void create_Ds2x_pts - ( const std::vector & XX , - const NOMAD::Display & out , - NOMAD::dd_type display_degree , - int display_lim , - std::vector & Ds2x_pts ) const; - - /// Prediction at one point. - /** - \param x The point -- \b IN. - \param h Value of \c h -- \b OUT. - \param f Value of \c f -- \b OUT. - \return A boolean equal to \c true if the prediction was possible. - */ - bool predict ( const NOMAD::Point & x , - NOMAD::Double & h , - NOMAD::Double & f ) const; - - /// Display the prediction error for the evaluated points. - /** - \param evaluated_pts List of evaluated points -- \b IN. - \param out The NOMAD::Display object -- \b IN. - */ - void display_eval_pred_errors - ( const std::list & evaluated_pts , - const NOMAD::Display & out ); - - /*----------------------------------------------------------------------*/ - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - TGP_Model_Search ( NOMAD::Parameters & p ) - : NOMAD::Search ( p , NOMAD::MODEL_SEARCH ) , _model ( NULL ) {} - - /// Destructor. - virtual ~TGP_Model_Search ( void ) { reset(); } - - /// Reset. - virtual void reset ( void ); - - /// The TGP model search. - /** - Based on quadratic regression/MFN interpolation models. - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - - /// Access to the model. - /** - \return The model. - */ - NOMAD::TGP_Model * get_model ( void ) const { return _model; } - - //// Display stats. - /** - \param out The NOMAD::Display object -- \b IN. - */ - virtual void display ( const NOMAD::Display & out ) const - { - out << _all_searches_stats; - } - }; -} - -#endif -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Output_Model.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Output_Model.cpp deleted file mode 100644 index d164d1139..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Output_Model.cpp +++ /dev/null @@ -1,486 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Output_Model.cpp - \brief TGP (Bayesian treed Gaussian process) model for one output (implementation) - \author Sebastien Le Digabel - \date 2011-02-07 - \see TGP_Output_Model.hpp -*/ - -#ifndef USE_TGP - -int TGP_OUTPUT_MODEL_DUMMY; // avoids that TGP_Output_Model.o has no symbols with ranlib - -#else - -#include "TGP_Output_Model.hpp" - -/*---------------------------------------------------------*/ -/* NOMAD-TGP callback function (called regularly by TGP) */ -/*---------------------------------------------------------*/ -// SLD -- 2014-09-04 -// void NOMAD::TGP_callback ( bool & TGP_interrupt ) -// { -// if ( NOMAD::TGP_Output_Model::get_force_quit() ) -// TGP_interrupt = true; -// } - -/*-----------------------------------*/ -/* static members initialization */ -/*-----------------------------------*/ -double NOMAD::TGP_Output_Model::_ditemps[7] = - { 1.0 , 0.0 , 0.0 , 1.0 , 1.0 , 0.0 , 1.0 }; - -bool NOMAD::TGP_Output_Model::_force_quit = false; - -/*-----------------------------------*/ -/* constructor */ -/*-----------------------------------*/ -NOMAD::TGP_Output_Model::TGP_Output_Model -( const std::list & X_pts , - int bbo_index , - int seed , - const NOMAD::Display & out ) - : _out ( out ) , - _p ( X_pts.size() ) , - _Z ( new double[_p] ) , - _Z_is_scaled ( false ) , - _is_binary ( true ) , - _bin_values ( 2 ) , - _is_fixed ( false ) , - _tgp_state ( NULL ) , - _tgp_model ( NULL ) , - _tgp_its ( NULL ) -{ - NOMAD::TGP_Output_Model::_force_quit = false; - - _Z_scaling[0] = _Z_scaling[1] = 0.0; - - std::list::const_iterator it , end = X_pts.end(); - - NOMAD::Double tmp , Zmin , Zmax , Zsum = 0.0; - int j = 0; - - for ( it = X_pts.begin() ; it != end ; ++it ) { - - // the output value: - tmp = (*it)->get_bb_outputs()[bbo_index]; - _Z[j++] = tmp.value(); - - // Z scaling parameters (1/2): - Zsum += tmp; - if ( !Zmin.is_defined() || tmp < Zmin ) - Zmin = tmp; - if ( !Zmax.is_defined() || tmp > Zmax ) - Zmax = tmp; - - // check if the output is binary: - if ( _is_binary ) { - if ( !_bin_values[0].is_defined() ) - _bin_values[0] = tmp; - else if ( !_bin_values[1].is_defined() && tmp != _bin_values[0] ) - _bin_values[1] = tmp; - else { - if ( tmp != _bin_values[0] && tmp != _bin_values[1] ) - _is_binary = false; - } - } - } - - // Z scaling parameters (1/2): - _Z_scaling[0] = (Zmax - Zmin).value(); - - // the output is fixed: - if ( _Z_scaling[0] == 0.0 ) - _is_fixed = true; - - else { - - _Z_scaling[1] = (Zsum/_p).value() / _Z_scaling[0]; - - if ( !_is_binary ) - _bin_values = NOMAD::Point(2); - - // RNG (random number generator): - int state[] = { 896 , 265 , 371 }; - - // if seed==0, the model will be the same as the one constructed in R, - // with values taken from the R tgp functions for: - // set.seed(0) - // state <- sample(seq(0, 999), 3) - - // otherwise use rand() to get three different integers in [0;999]: - if ( seed != 0 ) { - state[0] = rand()%1000; - while ( state[1] == state[0] ) - state[1] = rand()%1000; - while ( state[2] == state[0] || state[2] == state[1] ) - state[2] = rand()%1000; - } - _tgp_state = newRNGstate ( three2lstate ( state ) ); - - // importance tempering: - _tgp_its = new Temper ( NOMAD::TGP_Output_Model::_ditemps ); - } -} - -/*--------------------------------------------*/ -/* destructor */ -/*--------------------------------------------*/ -NOMAD::TGP_Output_Model::~TGP_Output_Model ( void ) -{ - if ( _Z ) - delete [] _Z; - if ( _tgp_model ) - delete _tgp_model; - if ( _tgp_its ) - delete _tgp_its; - if ( _tgp_state ) - deleteRNGstate ( _tgp_state ); -} - -/*--------------------------------------------*/ -/* compute the model */ -/*--------------------------------------------*/ -void NOMAD::TGP_Output_Model::compute ( double ** X , - double ** XX , - double ** Xsplit , - int n , - int n_XX , - int nsplit , - Params * tgp_params , - double ** tgp_rect , - int * tgp_BTE , - bool tgp_linburn , - bool tgp_verb , - double * ZZ , // OUT - double * Ds2x , // OUT, may be NULL - int * improv ) // OUT, may be NULL -{ - bool compute_Ds2x = ( Ds2x != NULL ); - bool compute_improv = ( improv != NULL ); - - // the output is fixed: - if ( _is_fixed ) { - for ( int j = 0 ; j < n_XX ; ++j ) { - ZZ[j] = _bin_values[0].value(); - if ( compute_Ds2x ) - Ds2x[j] = 0.0; - } - return; - } - - // scale Z: - scale_Z(); - - // construct the TGP model: - _tgp_model = new Model ( tgp_params , - n , - tgp_rect , - 0 , // Id=0 - false , // trace=false - _tgp_state ); - - _tgp_model->Init ( X , - _p , - n , - _Z , - _tgp_its , - NULL , // dtree=NULL - 0 , // ncol=0 - NULL ); // dhier=NULL - - // set the NOMAD-TGP callback function: - // _tgp_model->set_callback ( NOMAD::TGP_callback ); // SLD -- 2014-09-04 - - // TGP verbim (display): -#ifdef TGP_DEBUG - _tgp_model->Outfile ( stdout , 1 ); // set 10 for full display -#else - if ( tgp_verb ) - _tgp_model->Outfile ( stdout , 1 ); - else - _tgp_model->Outfile ( NULL , 0 ); -#endif - - // set the splitting locations (Xsplit): - _tgp_model->set_Xsplit ( Xsplit , nsplit , n ); - - // linear model initialization rounds -B thru 1: - if ( tgp_linburn ) - _tgp_model->Linburn ( tgp_BTE[0] , _tgp_state ); - - // do model rounds 1 thru B (burn in): - _tgp_model->Burnin ( tgp_BTE[0] , _tgp_state ); - - // do the MCMC rounds B,...,T: - Preds * tgp_preds = new_preds ( XX , - n_XX , - 0 , - n , - tgp_rect , - tgp_BTE[1]-tgp_BTE[0] , - false , // pred_n - true , // krige - _tgp_its->IT_ST_or_IS() , - compute_Ds2x , - compute_improv , - false , // sens - tgp_BTE[2] ); - - _tgp_model->Sample ( tgp_preds , tgp_BTE[1]-tgp_BTE[0] , _tgp_state ); - - // if importance tempering, then update the pseudo-prior - // based on the observation counts: - if ( _tgp_its->Numit() > 1 ) - _tgp_its->UpdatePrior ( _tgp_model->update_tprobs() , _tgp_its->Numit() ); - - // copy back the itemps: - _tgp_model->DupItemps ( _tgp_its ); - - // kriging mean: - wmean_of_columns ( ZZ , - tgp_preds->ZZm , - tgp_preds->R , - n_XX , - (_tgp_its->IT_ST_or_IS()) ? tgp_preds->w : NULL ); - - int i; - - // expected reduction in predictive variance (Ds2x): - if ( compute_Ds2x ) { - for ( i = 0 ; i < n_XX ; ++i ) - Ds2x[i] = 0.0; - if ( tgp_preds->Ds2x ) - wmean_of_columns ( Ds2x , - tgp_preds->Ds2x , - tgp_preds->R , - tgp_preds->nn , - (_tgp_its->IT_ST_or_IS()) ? tgp_preds->w : NULL ); - } - - // expected improvement of objective (improv): - if ( compute_improv ) { - - // double * improvec = new double [n_XX]; - // wmean_of_columns ( improvec , - // tgp_preds->improv, - // tgp_preds->R, - // tgp_preds->nn, - // (_tgp_its->IT_ST_or_IS()) ? tgp_preds->w : NULL ); - // for ( i = 0 ; i < n_XX ; ++i ) - // _out << "IMPROVEC[" << i<< "] = " << improvec[i] << std::endl; - // delete [] improvec; - - int *ir = (int*) GetImprovRank ( tgp_preds->R , - tgp_preds->nn , - tgp_preds->improv , - true , // improv=true - tgp_preds->nn , // numirank = n_XX - (_tgp_its->IT_ST_or_IS()) ? tgp_preds->w : NULL ); - - for ( i = 0 ; i < n_XX ; ++i ) { - improv[i] = ir[i]; - if ( improv[i] == 0 ) - improv[i] = n_XX; - } - - free ( ir ); - - // for ( i = 0 ; i < n_XX ; ++i ) - // _out << "RANK[" << i<< "] = " << improv[i] << std::endl; - } - - delete_preds ( tgp_preds ); - -#ifdef TGP_DEBUG - _tgp_model->Outfile ( NULL , 0 ); -#endif - - // unscale Z and ZZ: - unscale_Z ( ZZ , n_XX ); - unscale_Z(); - - // treat binary output: - if ( _is_binary ) - treat_binary_output ( ZZ , n_XX ); - - // disable TGP display: - _tgp_model->Outfile ( NULL , 0 ); -} - -/*--------------------------------------------*/ -/* prediction at one point */ -/*--------------------------------------------*/ -bool NOMAD::TGP_Output_Model::predict ( double * XX , - int n , - double & ZZ , - double ** tgp_rect ) const -{ - if ( _is_fixed ) { - ZZ = _bin_values[0].value(); - return true; - } - - // do the MCMC rounds B,...,T: - Preds * tgp_preds = new_preds ( &XX , - 1 , - 0 , - n , - tgp_rect , - 1 , // instead of T-B - false , // pred_n - true , // krige - _tgp_its->IT_ST_or_IS() , - false , // delta_s2 (flag for Ds2x) - false , // improv - false , // sens - 1 ); // instead of E - - // new TGP function for the one point prediction: - _tgp_model->MAPreplace(); - - // prediction: - _tgp_model->Predict ( tgp_preds , - 1 , // instead of T-B - _tgp_state ); - - // kriging mean: - ZZ = *tgp_preds->ZZm[0]; - // no need to do: - // wmean_of_columns ( &ZZ , - // tgp_preds->ZZm , - // tgp_preds->R , - // 1 , - // (_tgp_its->IT_ST_or_IS()) ? tgp_preds->w : NULL ); - - delete_preds ( tgp_preds ); - - // unscale: - unscale_Z ( &ZZ , 1 ); - - // treat binary output: - if ( _is_binary ) - treat_binary_output ( &ZZ , 1 ); - - return true; -} - -/*--------------------------------------------*/ -/* scale Z or ZZ (private) */ -/*--------------------------------------------*/ -void NOMAD::TGP_Output_Model::scale_Z ( void ) -{ - if ( _Z_is_scaled || _is_fixed ) - return; - scale_Z ( _Z , _p ); - _Z_is_scaled = true; -} - -void NOMAD::TGP_Output_Model::scale_Z ( double * Z , int n ) const -{ - if ( _is_fixed ) - return; - for ( int i = 0 ; i < n ; ++i ) - Z[i] = Z[i] / _Z_scaling[0] - _Z_scaling[1]; -} - -/*--------------------------------------------*/ -/* unscale Z or ZZ (private) */ -/*--------------------------------------------*/ -void NOMAD::TGP_Output_Model::unscale_Z ( void ) -{ - if ( !_Z_is_scaled || _is_fixed ) - return; - unscale_Z ( _Z , _p ); - _Z_is_scaled = false; -} - -void NOMAD::TGP_Output_Model::unscale_Z ( double * Z , int n ) const -{ - if ( _is_fixed ) - return; - for ( int i = 0 ; i < n ; ++i ) - Z[i] = ( Z[i] + _Z_scaling[1] ) * _Z_scaling[0]; -} - -/*--------------------------------------------*/ -/* treat binary output (private) */ -/*--------------------------------------------*/ -void NOMAD::TGP_Output_Model::treat_binary_output ( double * ZZ , int nout ) const -{ - NOMAD::Double d0 , d1; - for ( int j = 0 ; j < nout ; ++j ) { - d0 = (_bin_values[0] - ZZ[j]).abs(); - d1 = (_bin_values[1] - ZZ[j]).abs(); - if ( d0 < d1 ) - ZZ[j] = _bin_values[0].value(); - else - ZZ[j] = _bin_values[1].value(); - } -} - -/*--------------------------------------------*/ -/* display */ -/*--------------------------------------------*/ -void NOMAD::TGP_Output_Model::display ( const NOMAD::Display & out ) const -{ - out << "Z ("; - if ( !_Z_is_scaled ) - out << "un"; - out << "scaled)" << " = [ "; - for ( int i = 0 ; i < _p ; ++i ) { - out << std::setw(15) << _Z[i]; - if ( (i+1)%5 == 0 ) - out << " ;" << std::endl << " "; - else - out << " "; - } - out << "]" << std::endl - << "size(Z)=" << _p << std::endl; - if ( _is_fixed ) - out << "fixed output"; - else if ( _is_binary ) - out << "binary output: values in {" - << _bin_values[0] << "," << _bin_values[1] - << "}"; - out << std::endl - << "Z_scaling=[" << _Z_scaling[0] << "," << _Z_scaling[1] - << "]" << std::endl; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Output_Model.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Output_Model.hpp deleted file mode 100644 index 028b72086..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/TGP_Output_Model.hpp +++ /dev/null @@ -1,241 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.0.beta */ -/* */ -/* Copyright (C) 2001-2014 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file TGP_Output_Model.hpp - \brief TGP (Bayesian treed Gaussian process) model for one output (headers) - \author Sebastien Le Digabel - \date 2011-02-07 - \see TGP_Output_Model.cpp -*/ -#ifdef USE_TGP - -#ifndef __TGP_OUTPUT_MODEL__ -#define __TGP_OUTPUT_MODEL__ - -#include "Eval_Point.hpp" -#include "tgp.h" - -/*------------------------------*/ -/* TGP C functions prototypes */ -/*------------------------------*/ -extern "C" -{ - unsigned long three2lstate ( int * state ); - void * newRNGstate ( unsigned long s ); - void deleteRNGstate ( void * seed ); - unsigned int * GetImprovRank ( int, int, double **, int, int, double * ); -} - -namespace NOMAD { - - // NOMAD-TGP callback function (called regularly by TGP). - // void TGP_callback ( bool & TGP_interrupt ); // SLD -- 2014-09-04 - - /// TGP models for one output. - class TGP_Output_Model : private NOMAD::Uncopyable { - - private: - - const NOMAD::Display & _out; ///< Display. - - int _p; ///< Number of interpolation points. - - double * _Z; ///< Output vector (size = \c p). - - double _Z_scaling[2]; ///< To scale/unscale \c Z. - bool _Z_is_scaled; ///< If \c Z is scaled or not. - - bool _is_binary; ///< If the output has only two values. - NOMAD::Point _bin_values; ///< Binary output values. - - bool _is_fixed; ///< Only one output value saved in \c bin_values[0]. - - void * _tgp_state; ///< RNG (random number generator). - - Model * _tgp_model; ///< The TGP model. - - Temper * _tgp_its; ///< Importance tempering object. - - static double _ditemps[7]; ///< Importance tempering parameters. - - static bool _force_quit; ///< Flag equal to \c true if ctrl-c is pressed. - - /// Treat binary output. - /** - \param ZZ Output vector -- \b IN/OUT. - \param nout Size of output -- \b IN. - */ - void treat_binary_output ( double * ZZ , int nout ) const; - - /// Scale member \c _Z. - void scale_Z ( void ); - - /// Unscale member \c _Z. - void unscale_Z ( void ); - - /// Scale an output \c Z. - /** - \param Z Output to scale -- \b IN/OUT. - \param n Size of output -- \b IN. - */ - void scale_Z ( double * Z , int n ) const; - - /// Unscale an output \c Z. - /** - \param Z Output to unscale -- \b IN/OUT. - \param n Size of output -- \b IN. - */ - void unscale_Z ( double * Z , int n ) const; - - public: - - /// Constructor. - /** - \param X_pts Interpolation points with output values -- \b IN. - \param bbo_index Output index -- \b IN. - \param seed Random seed (\c 0 to have the same \c R results) -- \b IN. - \param out Display object -- \b IN. - */ - explicit TGP_Output_Model - ( const std::list & X_pts , - int bbo_index , - int seed , - const NOMAD::Display & out ); - - /// Destructor. - virtual ~TGP_Output_Model ( void ); - - /// Force quit (called by pressing ctrl-c). - static void force_quit ( void ) - { - NOMAD::TGP_Output_Model::_force_quit = true; - } - - /// Access to the \c force_quit flag. - /** - \return The \c force_quit flag. - */ - static bool get_force_quit ( void ) { return NOMAD::TGP_Output_Model::_force_quit; } - - /// Compute the model. - /** - \param X \c X matrix (\c X_pts \c x \c n): interpolation pts -- \b IN. - \param XX \c XX matrix (\c n_XX \c x \c n): prediction points -- \b IN. - \param Xsplit \x Xsplit matrix (\c X plus \c XX) -- \b IN. - \param n Dimension and number of columns of the matrices -- \b IN. - \param n_XX Number of rows of \c XX -- \b IN. - \param nsplit Number of rows of \c Xsplit (\c X_pts \c + \c n_XX) -- \b IN. - \param tgp_params TGP parameters -- \b IN. - \param tgp_rect TGP rectangle -- \b IN. - \param tgp_BTE TGP \c B,\c T, and \c R parameters -- \b IN. - \param tgp_linburn TGP \c linburn parameter -- \b IN. - \param tgp_verb TGP \c verb parameter -- \b IN. - \param ZZ \c ZZ vector (size \c n_XX): prediction values -- \b OUT. - \param Ds2x Expected reduction in predictive var (size \c n_XX) -- \b OUT. - \param improv Expected improvement of the obj. (size \c n_XX) -- \b OUT. - */ - void compute ( double ** X , - double ** XX , - double ** Xsplit , - int n , - int n_XX , - int nsplit , - Params * tgp_params , - double ** tgp_rect , - int * tgp_BTE , - bool tgp_linburn , - bool tgp_verb , - double * ZZ , - double * Ds2x , - int * improv ); - - /// Prediction at one point. - /** - \param XX \c XX matrix (\c n_XX \c x \c n): prediction points -- \b IN. - \param n Dimension and number of columns of the matrices -- \b IN. - \param ZZ \c ZZ vector (size \c n_XX): prediction values -- \b OUT. - \param tgp_rect TGP rectangle -- \b IN. - \return A boolean equal to \c true if the prediction went well. - */ - bool predict ( double * XX , - int n , - double & ZZ , - double ** tgp_rect ) const; - - /// Access to \c Z. - /** - \return The \c Z vector. - */ - const double * get_Z ( void ) const { return _Z; } - - /// Access to the \c fixed flag. - /** - \return The \c fixed flag. - */ - bool is_fixed ( void ) const { return _is_fixed; } - - /// Access to the \c binary flag. - /** - \return The \c binary flag. - */ - bool is_binary ( void ) const { return _is_binary; } - - /// Default display. - void display ( void ) { display ( _out ); } - - /// Display. - /** - \param out Display -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - }; - - /// Display a NOMAD::TGP_Output_Model object. - /** - \param out The NOMAD::Display object -- \b IN. - \param s The NOMAD::TGP_Output_Model object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::TGP_Output_Model & s ) { - s.display ( out ); - return out; - } - -} - -#endif -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Uncopyable.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Uncopyable.hpp deleted file mode 100644 index 992160c13..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Uncopyable.hpp +++ /dev/null @@ -1,72 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Uncopyable.hpp - \brief Base class for uncopyable classes (headers) - \author Sebastien Le Digabel - \date 2010-04-02 -*/ -#ifndef __UNCOPYABLE__ -#define __UNCOPYABLE__ - -namespace NOMAD { - - /// Uncopyable class. - /** - Base class for uncopyable classes - (see Scott Meyer's Effective C++, 3rd ed., item #6). - */ - class Uncopyable { - - protected: - - /// Constructor. - explicit Uncopyable ( void ) {} - - /// Destructor. - virtual ~Uncopyable ( void ) {} - - private: - - /// Undefined copy constructor. - Uncopyable ( const Uncopyable & ); - - /// Undefined affectation operator. - Uncopyable & operator = ( const Uncopyable & ); - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/VNS_Search.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/VNS_Search.cpp deleted file mode 100644 index 75a9a2fec..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/VNS_Search.cpp +++ /dev/null @@ -1,636 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file VNS_Search.cpp - \brief VNS search (implementation) - \author Sebastien Le Digabel - \date 2010-04-12 - \see VNS_Search.hpp - */ -#include "VNS_Search.hpp" - -/*---------------------------------------------------------*/ -/* reset */ -/*---------------------------------------------------------*/ -void NOMAD::VNS_Search::reset ( void ) -{ - _k = _k_max = 1; - _old_x = NULL; - -} - -/*---------------------------------------------------------*/ -/* the search */ -/* VNS: x --[shaking(k)]--> x' --[descent]--> x" */ -/*---------------------------------------------------------*/ -void NOMAD::VNS_Search::search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ) -{ - new_feas_inc = new_infeas_inc = NULL; - nb_search_pts = 0; - success = NOMAD::UNSUCCESSFUL; - count_search = !stop; - - if ( stop ) - return; - - // initial display: - const NOMAD::Display & out = _p.out(); - NOMAD::dd_type display_degree = out.get_search_dd(); - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << NOMAD::VNS_SEARCH; - out << std::endl << NOMAD::open_block ( oss.str() ) << std::endl; - } - - bool opt_only_sgte = _p.get_opt_only_sgte(); - - // the barriers: - NOMAD::Barrier & true_barrier = mads.get_true_barrier(); - NOMAD::Barrier & sgte_barrier = mads.get_sgte_barrier(); - const NOMAD::Barrier & active_barrier = mads.get_active_barrier(); - - // point x: - NOMAD::Double best_f; - bool x_feas = true; - const NOMAD::Eval_Point * x = active_barrier.get_best_feasible(); - if ( x ) - best_f = x->get_f(); - else - { - x = active_barrier.get_best_infeasible(); - x_feas = false; - } - - if ( !x ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block ( "end of VNS search (no incumbent)" ); - return; - } - - // update _k and _old_x: - if ( x == _old_x ) - { - ++_k; - if ( _k > _k_max ) - _k_max = _k; - } - else - _k = 1; - - _old_x = x; - - // get the signature: - NOMAD::Signature * signature = x->get_signature(); - if ( !signature ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block ( "end of VNS search (no signature)" ); - return; - } - - int n = signature->get_n(); - if ( n != x->size() ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block ( "end of VNS search (incompatible signature)" ); - return; - } - - // shaking: get ONE direction from the signature: - NOMAD::Direction dir; - - signature->get_one_direction ( dir , _k - 1); - - - // shaking: construct x': - NOMAD::Point xp = *x + dir; - - // shaking: the perturbation is tried twice with dir and -dir - // (in case x == x + dir after snapping) - for ( int nbt = 0 ; nbt < 2 ; ++nbt ) - { - - // treat xp: periodic variables or bounds: - if ( _p.has_periodic_variables() ) - { - NOMAD::Direction * tmp_dir = NULL; - signature->treat_periodic_variables ( xp , NULL , tmp_dir ); - } - else - signature->snap_to_bounds ( xp , NULL ); - - if ( xp == *x ) - { - - // no third try: the search fails - if ( nbt == 1 ) - { - if ( display_degree == NOMAD::FULL_DISPLAY ) - out.close_block ( "end of VNS search (shaking failed)" ); - return; - } - - // 2nd try (-dir instead of dir): - xp = *x - dir; - } - } - - // Current mesh indices - const NOMAD::Point old_mesh_indices = signature->get_mesh()->get_mesh_indices ( ); - const NOMAD::Point old_delta_min = signature->get_mesh()->get_min_mesh_size(); - - - // stats: - NOMAD::Stats & stats = mads.get_stats(); - - // current number of blackbox evaluations: - int bbe = stats.get_bb_eval(); - int blk_eva = stats.get_block_eval(); - int sgte_eval = stats.get_sgte_eval(); - int mads_iterations = stats.get_iterations(); - bool has_sgte = _p.has_sgte(); - - // displays: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - out << " it = " << mads_iterations << std::endl - << " bbe = " << bbe << std::endl - << " blk_eva = " << blk_eva << std::endl; - if ( has_sgte ) - out << " sgte_eval = " << sgte_eval << std::endl; - out << "mesh_indices = ( " << old_mesh_indices << " ) " << std::endl - << " k = " << _k << std::endl - << " kmax = " << _k_max << std::endl - << " x = ( "; - x->Point::display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " ) f=" << x->get_f() << " h=" << x->get_h() << std::endl - << " dir = ( "; - dir.Point::display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " ) |dir|="; - NOMAD::Double norm = dir.norm(); - out << norm << std::endl; - out << " xp = ( "; - xp.display ( out , " " , 5 , _p.get_point_display_limit() ); - out << " )" << std::endl << std::endl; - out << "bb_eval (before+VNS only) objective_value" - << std::endl << std::endl; - } - - // save parameters that are going to be modified: - // ---------------------------------------------- - std::string old_display_degree; - _p.out().get_display_degree ( old_display_degree ); - - NOMAD::model_params_type old_mp; - _p.get_model_parameters ( old_mp ); - - bool old_ses = _p.get_sgte_eval_sort(); - bool old_sif = _p.get_stop_if_feasible(); - int old_max_time = _p.get_max_time(); - int old_max_bbe = _p.get_max_bb_eval(); - int old_max_eval = _p.get_max_eval(); - int old_max_sgte_eval = _p.get_max_sgte_eval(); - int old_max_it = _p.get_max_iterations(); - int old_max_cfi = _p.get_max_consecutive_failed_iterations(); - int old_LH_p0 = _p.get_LH_search_p0(); - int old_LH_pi = _p.get_LH_search_pi(); - bool old_opp_LH = _p.get_opportunistic_LH(); - bool old_CS = _p.get_cache_search(); - bool old_opp_CS = _p.get_opportunistic_cache_search(); - int old_max_sbe = _p.get_max_sim_bb_eval(); - NOMAD::Double old_sst = _p.get_stat_sum_target(); - NOMAD::Double old_lct = _p.get_L_curve_target(); - NOMAD::Double old_trigger = _p.get_VNS_trigger(); - NOMAD::Point old_ft = _p.get_f_target(); - const std::list old_ds = _p.get_display_stats(); - const std::list old_stats_file = _p.get_stats_file(); - const std::string old_stats_file_name = _p.get_stats_file_name(); - const std::string old_sol_file = _p.get_solution_file(); - const std::string old_his_file = _p.get_history_file(); - bool old_uce = _p.get_user_calls_enabled(); - bool old_epe = _p.get_extended_poll_enabled(); - const std::vector old_bbot = _p.get_bb_output_type(); - - // save list of starting points: - std::string x0_cache_file = _p.get_x0_cache_file(); - std::vector x0s; - { - const std::vector & x0s_tmp = _p.get_x0s(); - size_t nx0 = x0s_tmp.size() , k; - for ( k = 0 ; k < nx0 ; ++k ) - x0s.push_back ( new Point ( *x0s_tmp[k] ) ); - } - - // modify parameters: - // ------------------ - _p.set_DISPLAY_DEGREE(NOMAD::NO_DISPLAY); - - _p.set_SOLUTION_FILE ( "" ); - _p.set_LH_SEARCH ( 0 , 0 ); - _p.set_VNS_SEARCH ( false ); - _p.set_CACHE_SEARCH ( false ); - _p.set_MAX_ITERATIONS ( -1 ); - _p.set_MAX_CONSECUTIVE_FAILED_ITERATIONS ( -1 ); - _p.reset_X0(); - _p.reset_stats_file(); - - - if ( has_sgte ) - { - _p.set_OPT_ONLY_SGTE ( true ); - _p.set_MODEL_SEARCH ( NOMAD::NO_MODEL ); - _p.set_MODEL_EVAL_SORT ( NOMAD::NO_MODEL ); - } - - _p.set_USER_CALLS_ENABLED ( false ); - _p.set_EXTENDED_POLL_ENABLED ( false ); - - // DISPLAY_STATS: - { - if ( has_sgte ) - _p.set_DISPLAY_STATS ( NOMAD::itos(sgte_eval) + "+SGTE OBJ (VNS--surrogate)" ); - else - { - std::list ds = old_ds; - std::list::iterator it = ds.begin(); - std::list::const_iterator end = ds.end(); - std::string s_bbe = NOMAD::itos(bbe) + "+"; - std::string s_blk = NOMAD::itos(blk_eva) + "+"; - while ( it != end ) - { - if ( *it == "BBE" ) - ds.insert ( it , s_bbe ); - if ( *it == "BLK_EVA" ) - ds.insert ( it , s_blk ); - ++it; - } - ds.push_back ( " (VNS)" ); - _p.set_DISPLAY_STATS ( ds ); - } - } - - // STATS_FILE: - { - std::list sf = old_stats_file; - std::list::iterator it = sf.begin(); - std::list::const_iterator end = sf.end(); - std::string s_bbe = NOMAD::itos(bbe) + "+"; - std::string s_blk = NOMAD::itos(blk_eva) + "+"; - while ( it != end ) - { - if ( *it == "BBE" ) - sf.insert ( it , s_bbe ); - if ( *it == "BLK_EVA" ) - sf.insert ( it , s_blk ); - ++it; - } - sf.push_back ( " (VNS)" ); - - _p.set_STATS_FILE( old_stats_file_name, sf); - } - - - // Mesh size at current mads iterate can be used as termination criterion for vns search. - // Mesh indices are reinitialized during p.check() - NOMAD::Point delta=signature->get_mesh()->get_delta ( ); - signature->get_mesh()->set_min_mesh_sizes( delta ); - - - // X0: - _p.set_EXTERN_SIGNATURE ( signature ); - _p.set_X0 ( xp ); - - // MAX_BB_EVAL: - if ( old_max_bbe < 0 ) - _p.set_MAX_BB_EVAL ( 100 * n ); - else - _p.set_MAX_BB_EVAL ( old_max_bbe - bbe ); - - // MAX_SGTE_EVAL: - if ( old_max_sgte_eval > 0 ) - _p.set_MAX_SGTE_EVAL ( old_max_sgte_eval - sgte_eval ); - - // MAX_EVAL: - if ( old_max_eval > 0 ) - _p.set_MAX_EVAL ( old_max_eval - stats.get_eval() ); - - // MAX_SIM_BB_EVAL: - if ( old_max_sbe > 0 ) - _p.set_MAX_SIM_BB_EVAL ( old_max_sbe - stats.get_sim_bb_eval() ); - - // STAT_SUM_TARGET: - if ( old_sst.is_defined() ) - _p.set_STAT_SUM_TARGET ( old_sst - stats.get_stat_sum() ); - - // MAX_TIME: - if ( old_max_time > 0 ) - _p.set_MAX_TIME ( old_max_time - stats.get_real_time() ); - - // L_CURVE_TARGET: - if ( !has_sgte ) - _p.set_L_CURVE_TARGET ( best_f ); - - // F_TARGET and STOP_IF_FEASIBLE: - if ( has_sgte ) - { - _p.reset_f_target(); - _p.set_STOP_IF_FEASIBLE ( false ); - } - - // check the parameters: - _p.check ( false , // remove_history_file = false - false , // remove_solution_file = false - false ); // remove_stats_file = false - - // Evaluator_Control: - NOMAD::Evaluator_Control & ev_control = mads.get_evaluator_control(); - - // descent: run MADS: - // ------------------ - NOMAD::Mads VNS_mads ( _p , - ev_control.get_evaluator () , - mads.get_extended_poll () , - &ev_control.get_cache () , - &ev_control.get_sgte_cache() ); - NOMAD::Mads::set_flag_reset_mesh ( false ); - NOMAD::Mads::set_flag_reset_barriers ( true ); - - NOMAD::stop_type st = VNS_mads.run(); - - NOMAD::Mads::set_flag_reset_mesh ( true ); - - // update stats: - { - const NOMAD::Stats & VNS_stats = VNS_mads.get_stats(); - stats.update ( VNS_stats , true ); // for_search = true - stats.add_VNS_bb_eval ( VNS_stats.get_bb_eval () ); - stats.add_VNS_sgte_eval ( VNS_stats.get_sgte_eval() ); - } - - // check MADS stopping criteria: - if ( st == NOMAD::CTRL_C || - st == NOMAD::ERROR || - st == NOMAD::UNKNOWN_STOP_REASON || - st == NOMAD::FEAS_REACHED || - st == NOMAD::MAX_CACHE_MEMORY_REACHED || - st == NOMAD::STAT_SUM_TARGET_REACHED || - st == NOMAD::MAX_SGTE_EVAL_REACHED || - st == NOMAD::F_TARGET_REACHED || - st == NOMAD::MAX_SIM_BB_EVAL_REACHED || - st == NOMAD::MAX_TIME_REACHED || - (st == NOMAD::MAX_BB_EVAL_REACHED && old_max_bbe > 0 ) ) - { - stop_reason = st; - stop = true; - } - - // Pareto front: - NOMAD::Pareto_Front * pareto_front = mads.get_pareto_front(); - - // restore starting points: - { - _p.reset_X0(); - size_t nx0 = x0s.size(); - - if ( nx0 > 0 ) - { - - for ( size_t k = 0 ; k < nx0 ; ++k ) - { - _p.set_X0 ( *x0s[k] ); - delete x0s[k]; - } - } - else if ( !x0_cache_file.empty() ) - _p.set_X0 ( x0_cache_file ); - } - - // restore other saved parameters: - _p.set_model_parameters ( old_mp ); - _p.set_USER_CALLS_ENABLED ( old_uce ); - _p.set_EXTENDED_POLL_ENABLED ( old_epe ); - _p.set_VNS_SEARCH ( old_trigger ); - _p.set_F_TARGET ( old_ft ); - _p.set_STOP_IF_FEASIBLE ( old_sif ); - _p.set_L_CURVE_TARGET ( old_lct ); - _p.set_DISPLAY_DEGREE ( old_display_degree ); - _p.set_DISPLAY_STATS ( old_ds ); - _p.set_STATS_FILE ( old_stats_file_name , old_stats_file ); - _p.set_SOLUTION_FILE ( old_sol_file ); - _p.set_MAX_BB_EVAL ( old_max_bbe ); - _p.set_MAX_EVAL ( old_max_eval ); - _p.set_MAX_SGTE_EVAL ( old_max_sgte_eval ); - _p.set_MAX_ITERATIONS ( old_max_it ); - _p.set_MAX_CONSECUTIVE_FAILED_ITERATIONS ( old_max_cfi ); - _p.set_STAT_SUM_TARGET ( old_sst ); - _p.set_LH_SEARCH ( old_LH_p0 , old_LH_pi ); - _p.set_OPPORTUNISTIC_LH ( old_opp_LH ); - _p.set_CACHE_SEARCH ( old_CS ); - _p.set_OPPORTUNISTIC_CACHE_SEARCH ( old_opp_CS ); - _p.set_MAX_SIM_BB_EVAL ( old_max_sbe ); - _p.set_MAX_TIME ( old_max_time ); - _p.set_SGTE_EVAL_SORT ( old_ses ); - _p.set_OPT_ONLY_SGTE ( opt_only_sgte ); - _p.set_BB_OUTPUT_TYPE ( old_bbot ); - - - _p.check ( false , // remove_history_file = false - false , // remove_solution_file = false - false ); // remove_stats_file = false - - // restore min mesh sizes and mesh indices - signature->get_mesh()->set_min_mesh_sizes( old_delta_min ); - signature->get_mesh()->set_mesh_indices( old_mesh_indices ); // Needed because mesh indices reinitialized during p.check() - - - // surrogate evaluations: perform only one true evaluation: - if ( has_sgte && !opt_only_sgte ) - { - - if ( !stop ) - { - - // remember old best surrogates incumbents: - const NOMAD::Eval_Point * old_sgte_bf = sgte_barrier.get_best_feasible (); - const NOMAD::Eval_Point * old_sgte_bi = sgte_barrier.get_best_infeasible(); - - // update the surrogate barrier - // (no need to invoke Evaluator_Control::process_barrier_points() here - // since only surrogate evaluations have been made): - sgte_barrier.insert ( VNS_mads.get_sgte_barrier() ); - NOMAD::success_type sgte_succ = sgte_barrier.get_success(); - sgte_barrier.update_and_reset_success(); - - // we generate only a true trial point if the - // surrogates improved the surrogate barrier: - if ( sgte_succ != NOMAD::UNSUCCESSFUL ) - { - - // choose the best surrogate point(s) where to evaluate the true function: - const NOMAD::Eval_Point * sgte_bf = sgte_barrier.get_best_feasible (); - const NOMAD::Eval_Point * sgte_bi = sgte_barrier.get_best_infeasible(); - - std::list candidates; - - if ( sgte_bf && ( !x_feas || sgte_bf != old_sgte_bf ) ) - candidates.push_back ( sgte_bf ); - - if ( sgte_bi && sgte_bi != old_sgte_bi ) - candidates.push_back ( sgte_bi ); - - // generate the new trial points: - NOMAD::Eval_Point * sk; - std::list::const_iterator - it , end = candidates.end(); - for ( it = candidates.begin() ; it != end ; ++it ) - { - - // display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - out << std::endl << "VNS surrogate candidate: " - << **it << std::endl; - - sk = new NOMAD::Eval_Point; - sk->set ( n , _p.get_bb_nb_outputs() ); - sk->set_signature ( signature ); - sk->Point::operator = ( **it ); - - // add the new point to the list of search trial points: - ev_control.add_eval_point ( sk , - display_degree , - _p.get_snap_to_bounds() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() , - NOMAD::Double() ); - } - - // eval_list_of_points: - // -------------------- - success = NOMAD::UNSUCCESSFUL; - new_feas_inc = new_infeas_inc = NULL; - - ev_control.eval_list_of_points ( _type , - true_barrier , - sgte_barrier , - pareto_front , - stop , - stop_reason , - new_feas_inc , - new_infeas_inc , - success ); - - // number of search points (0 or 1 or 2): - nb_search_pts = static_cast ( candidates.size() ); - } - } - } - - // true evaluations (or surrogate evaluations if opt_only_sgte==true): - else - { - - // for the update of new_feas_inc and new_infeas_inc (1/2): - const NOMAD::Eval_Point * old_feasible_incumbent = - active_barrier.get_best_feasible(); - const NOMAD::Eval_Point * old_infeasible_incumbent = - active_barrier.get_best_infeasible(); - - // update barriers and process VNS search points: - NOMAD::success_type sgte_succ - = ev_control.process_barrier_points ( sgte_barrier , - VNS_mads.get_sgte_barrier() , - pareto_front , - display_degree , - NOMAD::VNS_SEARCH ); - NOMAD::success_type true_succ - = ev_control.process_barrier_points ( true_barrier , - VNS_mads.get_true_barrier() , - pareto_front , - display_degree , - NOMAD::VNS_SEARCH ); - - // update of new_feas_inc and new_infeas_inc (2/2): - const NOMAD::Eval_Point * bf = active_barrier.get_best_feasible (); - const NOMAD::Eval_Point * bi = active_barrier.get_best_infeasible(); - if ( bf && bf != old_feasible_incumbent ) - new_feas_inc = bf; - - if ( bi && bi != old_infeasible_incumbent ) - { - new_infeas_inc = bi; - // check the PEB constraints: if we have a new best infeasible - // incumbent from another infeasible incumbent - // ( active_barrier.check_PEB_constraints() ): - if ( _p.get_barrier_type() == NOMAD::PEB_P ) - ( ( _p.get_opt_only_sgte() ) ? sgte_barrier : true_barrier ).check_PEB_constraints ( *new_infeas_inc , display_degree==NOMAD::FULL_DISPLAY ); - } - - // number of search points and success: - if ( opt_only_sgte ) - { - nb_search_pts = VNS_mads.get_stats().get_sgte_eval(); - success = sgte_succ; - } - else - { - nb_search_pts = VNS_mads.get_stats().get_eval(); - success = true_succ; - } - - // solution file: - if ( bf ) - ev_control.write_solution_file ( *bf ); - - } - - // final display: - if ( display_degree == NOMAD::FULL_DISPLAY ) - { - std::ostringstream oss; - oss << "end of VNS search (" << success << ")"; - out << std::endl << NOMAD::close_block ( oss.str() ) << std::endl; - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/VNS_Search.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/VNS_Search.hpp deleted file mode 100644 index 5f431e799..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/VNS_Search.hpp +++ /dev/null @@ -1,103 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file VNS_Search.hpp - \brief VNS search (headers) - \author Sebastien Le Digabel - \date 2010-04-12 - \see VNS_Search.cpp -*/ -#ifndef __VNS_SEARCH__ -#define __VNS_SEARCH__ - -#include "Mads.hpp" -#include "Search.hpp" - -namespace NOMAD { - - /// Variable Neighborhood Search (VNS) search. - class VNS_Search : public NOMAD::Search , private NOMAD::Uncopyable { - - private: - - int _k; ///< VNS neighborhood parameter. - int _k_max; ///< Maximum value of \c _k. - const NOMAD::Eval_Point * _old_x; ///< Previous reference point (updates \c _k). - - - public: - - /// Constructor. - /** - \param p Parameters -- \b IN. - */ - VNS_Search ( NOMAD::Parameters & p ) - : NOMAD::Search ( p , NOMAD::VNS_SEARCH ) , - _k ( 1 ) , - _k_max ( 1 ) , - _old_x ( NULL ) {} - - /// Destructor. - virtual ~VNS_Search ( void ) {} - - /// Reset. - virtual void reset ( void ); - - /// The VNS search. - /** - Principle: x --[shaking(k)]--> x' --[descent]--> x'' . - \param mads NOMAD::Mads object invoking this search -- \b IN/OUT. - \param nb_search_pts Number of generated search points -- \b OUT. - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - \param success Type of success -- \b OUT. - \param count_search Count or not the search -- \b OUT. - \param new_feas_inc New feasible incumbent -- \b IN/OUT. - \param new_infeas_inc New infeasible incumbent -- \b IN/OUT. - */ - virtual void search ( NOMAD::Mads & mads , - int & nb_search_pts , - bool & stop , - NOMAD::stop_type & stop_reason , - NOMAD::success_type & success , - bool & count_search , - const NOMAD::Eval_Point *& new_feas_inc , - const NOMAD::Eval_Point *& new_infeas_inc ); - - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Variable_Group.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Variable_Group.cpp deleted file mode 100644 index b3c9dda91..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Variable_Group.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Variable_Group.cpp - \brief Group of variables (implementation) - \author Sebastien Le Digabel - \date 2010-04-22 - \see Variable_Group.hpp - */ -#include "Variable_Group.hpp" - -/*-------------------------------------------------------------*/ -/* check (also removes fixed variables from the group) */ -/*-------------------------------------------------------------*/ -bool NOMAD::Variable_Group::check -( const NOMAD::Point & fixed_vars , - const std::vector & bbit , - std::vector * in_group , - bool & mod ) -{ - - // initial checks: - if ( _var_indexes.empty() ) - return false; - - bool binary = true; - bool categorical = false; - bool reset_dirs = false; - - // other checks + filling of vector in_group: - int n = static_cast(bbit.size()); - std::set::const_iterator end = _var_indexes.end() , - it = _var_indexes.begin(); - - while ( it != end ) - { - - if ( *it < 0 || *it >= n ) - return false; - - // check if the variable is fixed: - if ( fixed_vars[*it].is_defined() ) - { - reset_dirs = true; - _var_indexes.erase ( it++ ); - mod=true; - continue; - } - - if ( bbit[*it] == NOMAD::CATEGORICAL ) - { - categorical = true; - binary = false; - } - else - { - if ( categorical ) - return false; - if ( bbit[*it] != NOMAD::BINARY ) - binary = false; - } - - if ( in_group ) - (*in_group)[*it] = true; - - ++it; - } - - // modify the directions if a fixed variable has been removed: - if ( reset_dirs ) - { - - std::set direction_types = _directions->get_direction_types(); - std::set sec_poll_dir_types = _directions->get_sec_poll_dir_types(); - - delete _directions; - - _directions = new Directions ( static_cast(_var_indexes.size()) , - direction_types , - sec_poll_dir_types , - _out ); - } - - if ( binary ) - _directions->set_binary(); - - else - { - - // we check here that NOMAD::GPS_BINARY is not in - // dir_types nor in sec_poll_dir_types: - const std::set & direction_types - = _directions->get_direction_types(); - const std::set & sec_poll_dir_types - = _directions->get_sec_poll_dir_types(); - - if ( direction_types.find ( NOMAD::GPS_BINARY ) != direction_types.end () || - sec_poll_dir_types.find ( NOMAD::GPS_BINARY ) != sec_poll_dir_types.end() ) - return false; - - if ( categorical ) - _directions->set_categorical(); - } - - return true; -} - -/*---------------------------------------------------------*/ -/* compute the directions */ -/*---------------------------------------------------------*/ -void NOMAD::Variable_Group::get_directions ( std::list & dirs , - NOMAD::poll_type poll , - const NOMAD::OrthogonalMesh & mesh ) -{ - - _directions->compute ( dirs , - poll , - mesh ); - return; -} - -/*---------------------------------------------------------*/ -/* comparison operator */ -/*---------------------------------------------------------*/ -bool NOMAD::Variable_Group::operator < ( const NOMAD::Variable_Group & vg ) const -{ - // variable indexes: - if ( _var_indexes.size() < vg._var_indexes.size() ) - return true; - if ( _var_indexes.size() > vg._var_indexes.size() ) - return false; - - std::set::const_iterator it1 , - it2 = vg._var_indexes.begin() , - end = _var_indexes.end(); - for ( it1 = _var_indexes.begin() ; it1 != end ; ++it1 , ++it2 ) { - if ( *it1 < *it2 ) - return true; - if ( *it1 > *it2 ) - return false; - } - - // directions: - return ( *_directions < *vg._directions ); -} - -/*---------------------------------------------------------*/ -/* display */ -/*---------------------------------------------------------*/ -void NOMAD::Variable_Group::display ( const NOMAD::Display & out ) const -{ - out << "indexes: { "; - std::set::const_iterator end = _var_indexes.end(); - for ( std::set::const_iterator it = _var_indexes.begin() ; it != end ; ++it ) - out << *it << " "; - out << "}" << std::endl; - if ( _directions->is_categorical() ) - out << "no directions (categorical variables)" << std::endl; - else - out << NOMAD::open_block ( "directions" ) - << *_directions - << NOMAD::close_block(); -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Variable_Group.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Variable_Group.hpp deleted file mode 100644 index 8de0a37d3..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/Variable_Group.hpp +++ /dev/null @@ -1,213 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file Variable_Group.hpp - \brief Group of variables (headers) - \author Sebastien Le Digabel - \date 2010-04-XX - \see Variable_Group.cpp - */ -#ifndef __VARIABLE_GROUP__ -#define __VARIABLE_GROUP__ - -#include "Directions.hpp" - -namespace NOMAD { - - /// Group of variables. - /** - A group can be composed of integer / continous / binary variables - or only categorical variables. - */ - class Variable_Group { - - private: - - std::set _var_indexes; ///< The variable indexes. - NOMAD::Directions * _directions; ///< The directions. - const NOMAD::Display & _out; ///< Display. - - /// Affectation operator. - /** - \param vg The right-hand side object -- \b IN. - */ - Variable_Group & operator = ( const Variable_Group & vg ); - - public: - - /// Constructor. - /** - \param var_indexes Variable indexes -- \b IN. - \param direction_types Direction types -- \b IN. - \param sec_poll_dir_types Direction types for secondary poll -- \b IN. - \param out Display -- \b IN. - */ - Variable_Group ( const std::set & var_indexes , - const std::set & direction_types , - const std::set & sec_poll_dir_types , - const NOMAD::Display & out ) - : _var_indexes ( var_indexes ), - _directions ( new Directions ( static_cast(var_indexes.size()) , - direction_types , - sec_poll_dir_types , - out ) ) , - _out ( out ) {} - - /// Copy constructor. - /** - \param vg The copied object -- \b IN. - */ - Variable_Group ( const Variable_Group & vg ) - : _var_indexes ( vg._var_indexes ) , - _directions ( new Directions ( *vg._directions ) ) , - _out ( vg._out ) {} - - /// Destructor. - virtual ~Variable_Group ( void ) { delete _directions; } - - /// Comparison operator. - /** - \param vg The right-hand side object -- \b IN. - \return A boolean equal to \c true if \c *this \c < \c vg. - */ - bool operator < ( const Variable_Group & vg ) const; - - /// Check the group. - /** - Also removes fixed variables from the group. - \param fixed_vars Fixed variables -- \b IN. - \param bbit Input types -- \b IN. - \param in_group A pointer to a vector indicating if variables - belong to a group (may be \c NULL) -- \b OUT. - \param mod True if the variable group has been modified -- \b out - \return A boolean equal to \c true if the verification is valid. - */ - bool check ( const NOMAD::Point & fixed_vars , - const std::vector & bbit , - std::vector * in_group , - bool & mod ); - - /// Check if the directions are Ortho-MADS directions. - /** - \return A boolean equal to \c true if the directions are Ortho-MADS directions. - */ - bool is_orthomads ( void ) const { return _directions->is_orthomads(); } - - - /// Access to the variable indexes. - /** - \return The variable indexes. - */ - const std::set & get_var_indexes ( void ) const { return _var_indexes; } - - /// Access to the direction types. - /** - \return The direction types. - */ - const std::set & get_direction_types ( void ) const - { - return _directions->get_direction_types(); - } - - /// Access to the direction types for the secondary poll. - /** - \return The direction types for the secondary poll. - */ - const std::set & get_sec_poll_dir_types ( void ) const - { - return _directions->get_sec_poll_dir_types(); - } - - /// Access to the directions. - /** - \param dirs List of directions -- \b OUT. - \param poll Type of poll (primary or secondary) -- \b IN. - \param mesh Mesh -- \b IN. - */ - void get_directions ( std::list & dirs , - NOMAD::poll_type poll , - const NOMAD::OrthogonalMesh & mesh ); - - - /// Access to one direction for a given mesh. - /** - Used for example in the VNS search. - \param dir The direction -- \b OUT. - */ - bool get_one_direction ( NOMAD::Direction & dir ) - { - return _directions->compute_dir_on_unit_sphere( dir ); - } - - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Display. - /** - Uses the \c this->_out member as NOMAD::Display object. - */ - void display ( void ) const { display ( _out ); } - }; - - /// Display a NOMAD::Variable_Group object. - /** - \param out The NOMAD::Display object -- \b IN. - \param vg The NOMAD::Variable_Group object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::Variable_Group & vg ) { - vg.display ( out ); - return out; - } - - /// Allow the comparison between two pointers to NOMAD::Variable_Group objects. - /** - Used with \c set in class NOMAD::Parameters. - */ - struct VG_Comp { - /// Comparison between two NOMAD::Variable_Group objects. - bool operator() ( const Variable_Group * vg1 , const Variable_Group * vg2 ) const { - return (*vg1 < *vg2); - } - }; -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/XMesh.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/XMesh.cpp deleted file mode 100644 index 80b75f235..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/XMesh.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file XMesh.cpp - \brief Class for the MADS xmesh (implementation) - \author Christophe Tribes - \date 2014-07 - \see XMesh.hpp - */ -#include "XMesh.hpp" -#include - - -/*-----------------------------------------------------------*/ -/* init the XMesh */ -/*-----------------------------------------------------------*/ -void NOMAD::XMesh::init ( ) -{ - bool chkMesh = _delta_min.is_defined(); - bool chkPoll = _Delta_min.is_defined(); - _n = _delta_0.size(); - - - if ( !_Delta_0.is_complete() ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::init(): Delta_0 has undefined values" ); - if ( _delta_0.size() != _Delta_0.size() ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::init(): delta_0 and Delta_0 have different sizes" ); - - if ( !_delta_0.is_complete() ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::init(): delta_0 has undefined values" ); - - if ( chkMesh && _delta_min.size() != _n ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::init(): delta_0 and delta_min have different sizes" ); - - if ( chkPoll && _Delta_min.size() != _n ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::init(): delta_0 and Delta_min have different sizes" ); - - if ( _limit_mesh_index >0 ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::XMesh(): limit mesh index must be <=0 " ); - - - _r.resize( _n ); - _r_max.resize( _n ); - _r_min.resize( _n ); - - for ( int k = 0 ; k < _n ; ++k ) - { - _r[k]=0; - _r_max[k]=0; - _r_min[k]=0; - } - - -} - - -/*-----------------------------------------------------------*/ -/* Update the provided mesh indices (the Mesh is unchanged). */ -/*-----------------------------------------------------------*/ -void NOMAD::XMesh::update ( NOMAD::success_type success , NOMAD::Point & mesh_indices, const NOMAD::Direction *dir ) const -{ - - if ( mesh_indices.is_defined() ) - { - - if ( dir && dir->size() != mesh_indices.size() ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::update(): mesh_indices and dir have different sizes" ); - - for (int i=0; i < mesh_indices.size() ; i++) - { - if ( success == NOMAD::FULL_SUCCESS ) - { - - if ( (*dir)[i] !=0.0) - mesh_indices[i] += _coarsening_step; - - if ( mesh_indices[i] > -NOMAD::XL_LIMITS ) - mesh_indices[i] = -NOMAD::XL_LIMITS; - } - else if ( success == NOMAD::UNSUCCESSFUL ) - mesh_indices[i] += _refining_step; - } - } -} - - - -/*-----------------------------------------------------------*/ -/* update the XMesh */ -/*-----------------------------------------------------------*/ -void NOMAD::XMesh::update ( NOMAD::success_type success , const NOMAD::Direction * dir) -{ - // defaults: - // full success: r^k_j = r^k_j + 1 if (dir_k != 0 and anistropic_mesh) and r^k_j remains the same if dir_k=0 - // failure : r^k_j = r^k_j - 1 - - - if ( dir && dir->size() != _n ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::update(): delta_0 and dir have different sizes" ); - - if ( success == NOMAD::FULL_SUCCESS ) - { - // Evaluate ||d||_inf - NOMAD::Double norm_inf=0; - NOMAD::Point delta=NOMAD::OrthogonalMesh::get_delta(); - - if ( _anisotropic_mesh ) - { - for (int i=0; i < _n; i++) - { - if ( dir && (*dir)[i].abs()/delta[i] > norm_inf ) - norm_inf=(*dir)[i].abs()/delta[i]; - } - } - else - norm_inf=-1; - - // Determine current max mesh index - NOMAD::Double max_index=NOMAD::XL_LIMITS; - for (int j=0; j < _n; j++) - if ( _r[j] > max_index ) - max_index=_r[j]; - - - // Update mesh indices for coordinates with |dir_j|>1/n_free_variables ||dir||_inf or mesh index >=-2 - for (int i=0; i < _n; i++) - { - if ( ! dir || (*dir)[i].abs()/delta[i] > norm_inf/_n_free_variables || _r[i] >=-2 ) - { - _r[i] += _coarsening_step; - - if (_r[i] > -NOMAD::XL_LIMITS ) - _r[i] = -NOMAD::XL_LIMITS; - - if ( _r[i] > _r_max[i] ) - _r_max[i] = _r[i]; - - } - } - - - // Udate mesh indices for coordinates with |dir_l| < 1/n_free_variables ||dir||_inf and mesh index < 2*max_mesh_index - for (int l=0; l < _n; l++) - { - if ( dir && _r[l] < -2 && (*dir)[l].abs()/delta[l] <= norm_inf/_n_free_variables && _r[l] < 2*max_index ) - _r[l]+= _coarsening_step; - } - - } - else if ( success == NOMAD::UNSUCCESSFUL ) - for (int i=0; i< _n; i++) - { - _r[i] += _refining_step; - - if ( _r[i] < _r_min[i] ) - _r_min[i] = _r[i]; - - } -} - - -/*-----------------------------------------------------------*/ -/* display */ -/*-----------------------------------------------------------*/ -void NOMAD::XMesh::display ( const NOMAD::Display & out ) const -{ - out << "n : " << _n << std::endl - << "tau : " << _update_basis << std::endl - << "poll coarsening exponent: " << _coarsening_step << std::endl - << "poll refining exponent : " << _refining_step << std::endl; - out << "minimal mesh size : "; - if ( _delta_min.is_defined() ) - out << "(" << _delta_min << " )" << std::endl; - else - out << "none"; - out << std::endl - << "minimal poll size : "; - if ( _Delta_min.is_defined() ) - out << "( " << _Delta_min << " )" << std::endl; - else - out << "none"; - - out << std::endl << "initial poll size : "; - if (_Delta_0.is_defined()) - out <<"( " << _Delta_0 << " )" << std::endl; - else - out <<"( none )" << std::endl; - - out << std::endl << "initial mesh size : "; - - if ( _delta_0.is_defined() ) - out <<"( " << _delta_0 << " )" << std::endl; - else - out <<"( none )" << std::endl; - - out << std::endl; -} - - -/*----------------------------------------------------------*/ -/* check the stopping conditions on the minimal poll size */ -/* and on the minimal mesh size */ -/*----------------------------------------------------------*/ -void NOMAD::XMesh::check_min_mesh_sizes ( bool & stop , - NOMAD::stop_type & stop_reason ) const -{ - if ( stop ) - return; - - // Coarse mesh stopping criterion - stop=false; - - for (int i=0;i<_n;i++) - if ( _r[i] > -NOMAD::XL_LIMITS ) - { - stop = true; - break; - } - - if (stop) - { - stop_reason = NOMAD::XL_LIMITS_REACHED; - return; - } - - stop=true; - - // Fine mesh stopping criterion - // All mesh indices must < _limit_mesh_index to trigger this stopping criterion - for (int i=0;i<_n;i++) - { - if ( _r[i] >= _limit_mesh_index ) - { - stop = false; - break; - } - } - if (stop) - { - stop_reason = NOMAD::XL_LIMITS_REACHED; - return; - } - - // 2. Delta^k (poll size) tests: - if ( check_min_poll_size_criterion ( ) ) - { - stop = true; - stop_reason = NOMAD::DELTA_P_MIN_REACHED; - } - - // 3. delta^k (mesh size) tests: - if ( check_min_mesh_size_criterion ( ) ) - { - stop = true; - stop_reason = NOMAD::DELTA_M_MIN_REACHED; - } -} - -/*-----------------------------------------------------------*/ -/* check the minimal poll size (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::XMesh::check_min_poll_size_criterion ( ) const -{ - if ( !_Delta_min.is_defined() ) - return false; - - NOMAD::Point Delta; - return get_Delta ( Delta ); -} - -/*-----------------------------------------------------------*/ -/* check the minimal mesh size (private) */ -/*-----------------------------------------------------------*/ -bool NOMAD::XMesh::check_min_mesh_size_criterion ( ) const -{ - if ( !_delta_min.is_defined() ) - return false; - - NOMAD::Point delta; - return get_delta ( delta ); -} - - -/*--------------------------------------------------------------*/ -/* get delta (mesh size parameter) */ -/* delta^k = delta^0 \tau ^min{0,2*r^k} */ -/*--------------------------------------------------------------*/ -/* the function also returns true if ALL delta[i] < delta_min */ -/*----------------------------------------------------------------*/ -bool NOMAD::XMesh::get_delta ( NOMAD::Point & delta ) const -{ - - delta.resize(_n); - - bool stop = true; - - // delta^k = power_of_beta * delta^0: - for ( int i = 0 ; i < _n ; ++i ) - { - NOMAD::Double power_of_beta - = pow ( _update_basis.value() , ( (_r[i] >= 0) ? 0 : 2*_r[i].value() ) ); - - delta[i] = _delta_0[i] * power_of_beta; - - if ( _delta_min.is_defined() && _delta_min[i].is_defined() && delta[i] >= _delta_min[i] ) - stop = false; - } - - return stop; -} - -/*--------------------------------------------------------------*/ -/* get Delta (poll size parameter) */ -/* Delta^k = Delta^0 \tau ^{r^k} */ -/*--------------------------------------------------------------*/ -/* the function also returns true if all values are < Delta_min */ -/*----------------------------------------------------------------*/ -bool NOMAD::XMesh::get_Delta ( NOMAD::Point & Delta ) const -{ - - bool stop = true; - bool mms_def = _Delta_min.is_complete(); - - - Delta.resize(_n); - - // delta^k = power_of_tau * delta^0: - for ( int i = 0 ; i < _n ; ++i ) - { - Delta[i] = _Delta_0[i] * pow( _update_basis.value() , _r[i].value() ); - - if ( !mms_def || Delta[i] >= _Delta_min[i] ) - stop = false; - - if ( _Delta_min.is_defined() && _Delta_min[i].is_defined() && Delta[i] < _Delta_min[i] ) - Delta[i]=_Delta_min[i]; - - } - - return stop; -} - - -bool NOMAD::XMesh::is_finest ( ) const -{ - for ( int i = 0 ; i < _n ; ++i ) - { - if ( _r[i] > _r_min[i] ) - return false; - } - return true; -} - - -/*-----------------------------------------------------------*/ -/* set the mesh indices */ -/*-----------------------------------------------------------*/ -void NOMAD::XMesh::set_mesh_indices ( const NOMAD::Point & r ) -{ - - if ( r.size() != _n ) - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "NOMAD::XMesh::set_mesh_indices(): dimension of provided mesh indices must be consistent with their previous dimension" ); - - _r=r; - for ( int i = 0 ; i < _n ; ++i ) - { - if ( r[i] > _r_max[i] ) - _r_max[i] = r[i]; - if ( r[i] < _r_min[i] ) - _r_min[i] = r[i]; - } -} - - -/*-----------------------------------------------------------*/ -/* set the limit mesh index (min value for XMesh) */ -/*-----------------------------------------------------------*/ -void NOMAD::XMesh::set_limit_mesh_index ( int l ) -{ - _limit_mesh_index=l; -} - - -/*-----------------------------------------------------------*/ -/* scale and project on the mesh */ -/*-----------------------------------------------------------*/ -NOMAD::Double NOMAD::XMesh::scale_and_project(int i, NOMAD::Double l) const -{ - NOMAD::Point delta; - NOMAD::Point Delta; - get_delta ( delta ); - get_Delta ( Delta ); - - - if ( delta.is_defined() && Delta.is_defined() && i <= _n) - { - NOMAD::Double d= Delta[i] / delta[i] * l; - return d.NOMAD::Double::round()*delta[i]; - } - else - throw NOMAD::Exception ( "XMesh.cpp" , __LINE__ , - "Mesh scaling and projection cannot be performed!" ); - - -} - - -NOMAD::Point NOMAD::XMesh::get_mesh_ratio_if_success ( void ) const -{ - - try - { - NOMAD::Point ratio( _n ); - for (int i=0 ; i < _n ; i++) - { - NOMAD::Double power_of_tau - = pow ( _update_basis.value() , ( (_r[i] >= 0) ? 0 : 2*_r[i].value() ) ); - - NOMAD::Double power_of_tau_if_success - = pow ( _update_basis.value() , ( (_r[i] + _coarsening_step >= 0) ? 0 : 2*(_r[i].value() + _coarsening_step) ) ); - - ratio[i] = power_of_tau_if_success/power_of_tau; - - } - - return ratio; - } - catch ( NOMAD::Double::Invalid_Value & ) - { - return NOMAD::Point( _n,-1 ); - } -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/XMesh.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/XMesh.hpp deleted file mode 100644 index 4a12ce526..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/XMesh.hpp +++ /dev/null @@ -1,292 +0,0 @@ - - -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Christophe Tribes */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file XMesh.hpp - \brief Class for the xmesh (extensible mesh) (headers) - \author Christophe Tribes - \date 2014-07 - \see XMesh.cpp - */ -#ifndef __XMESH__ -#define __XMESH__ - -#include "OrthogonalMesh.hpp" - -namespace NOMAD { - - /// Class for the MADS Xmesh. - /** - - The Xmesh in NOMAD is defined with the basic directions and the - mesh size parameter delta^k for each coordinate. - */ - - class XMesh : public NOMAD::OrthogonalMesh { - - /*--------------------------------------------------------------*/ - private: - - NOMAD::Point _r; // Mesh index per coordinate. - NOMAD::Point _r_min; - NOMAD::Point _r_max; - bool _anisotropic_mesh; - - - - /*--------------------------------------------------------------*/ - - /// Private affectation operator. - /** - \param m The right-hand side object -- \b IN. - */ - const XMesh & operator = ( const XMesh & m ); - - /// Check the minimal poll size criterion. - bool check_min_poll_size_criterion ( ) const; - - /// Check the minimal mesh size criterion. - bool check_min_mesh_size_criterion ( ) const; - - void init ( ); - - public: - - /// Constructor. - /** - \param anistropic_mesh Use anisotropic mesh or not -- \b IN. - \param Delta_0 Initial poll size Delta^0 -- \b IN. - \param Delta_min Minimal poll size Delta^min (may be undefined) -- \b IN. - \param delta_min Minimal mesh size delta^min (may be undefined) -- \b IN. - \param fixed_variables Fixed variables -- \b IN. - \param poll_update_basis Poll update basis (b); default=2 -- \b IN. - \param poll_coarsening_step Poll coarsening step (w+); default=1 -- \b IN. - \param poll_refining_step Poll refining step (w-); default=-1 -- \b IN. - \param limit_min_mesh_index Limit mesh index (<0) -- \b IN. - */ - XMesh (bool anisotropic_mesh, - const NOMAD::Point & Delta_0 , - const NOMAD::Point & Delta_min , - const NOMAD::Point & delta_min , - const NOMAD::Point & fixed_variables, - NOMAD::Double poll_update_basis=2.0, - int poll_coarsening_step=1, - int poll_refining_step=-1 , - int limit_min_mesh_index=NOMAD::XL_LIMITS ) - : NOMAD::OrthogonalMesh ( Delta_0, - Delta_min, - delta_min, - fixed_variables, - poll_update_basis, - poll_coarsening_step, - poll_refining_step , - limit_min_mesh_index ), - _anisotropic_mesh ( anisotropic_mesh ){ init();} - - - - - /// Copy constructor. - /** - \param m The copied object -- \b IN. - */ - XMesh ( const XMesh & m ) - : OrthogonalMesh ( m ) , - _r ( m._r ), - _r_min ( m._r_min ), - _r_max ( m._r_max ), - _anisotropic_mesh ( m._anisotropic_mesh ){} - - /// Destructor. - ~XMesh ( void ) - { - _delta_0.clear(); - _Delta_0.clear(); - _delta_min.clear(); - _Delta_min.clear(); - } - - - /// Access to the mesh size parameter delta^k for earch coordinate. - /** - - It is a NOMAD::Point of size \c nc the number of free variables. - \param delta The mesh size parameter delta^k -- \b OUT. - -- \b optional (default = the current mesh index ell_k.) - \return A boolean equal to \c true if all values are - strictly inferior than the associated minimal - mesh size delta_min (stopping criterion MIN_MESH_SIZE). - */ - bool get_delta ( NOMAD::Point & delta ) const ; - - /// Access to the largest mesh size for earch coordinate. - /** - \return delta_max - */ - NOMAD::Point get_delta_max ( void ) const { return _delta_0;} - - - /// Access to the poll size Delta^k for each coordinate. - /** - - It is a NOMAD::Point of size \c nc the number of free variables. - \param Delta The poll size parameter Delta^k -- \b OUT. - \return A boolean equal to \c true if all values are - strictly inferior than the associated minimal - poll size Delta_min - (stopping criterion MIN_POLL_SIZE). - */ - bool get_Delta ( NOMAD::Point & Delta) const ; - - - /// Update the provided mesh indices (the Mesh is unchanged). - /** - \param success Type of success of the iteration -- \b IN. - \param mesh_indices The mesh indices before and after the update -- \b IN/OUT. - \param dir The direction that is considered (opt) -- \b IN. - */ - void update ( NOMAD::success_type success , NOMAD::Point & mesh_indices, const NOMAD::Direction *dir=NULL ) const ; - - - /// Test if mesh finer than initial. - /** - \return True if mesh size is smaller than initial mesh size for all components; False otherwise. - */ - bool is_finer_than_initial (void) const {return true;} - - - - /// Update the XMesh (poll and mesh sizes). - /** - \param success Type of success of the iteration -- \b IN. - \param dir Direction of the iteration -- \b IN. - */ - void update ( NOMAD::success_type success, const NOMAD::Direction * dir=NULL); - - /// Reset the mesh to its original size (mesh indices). - void reset ( void ) { init() ;} - - - /// Display. - /** - \param out The NOMAD::Display object -- \b IN. - */ - void display ( const NOMAD::Display & out ) const; - - /// Test if r < r_min so far for all coordinates. - /** - \return True if mesh is the finest so far, False otherwise. - */ - bool is_finest ( void ) const; - - - /// Scale and project the ith component of a vector on the mesh - /** - \param i The vector component number -- \b IN. - \param l The vector component value -- \b IN. - \return The ith component of a vector after mesh scaling and projection - */ - NOMAD::Double scale_and_project(int i, NOMAD::Double l) const ; - - - /// Check the stopping conditions on the minimal poll and mesh sizes. - /** - \param stop Stop flag -- \b IN/OUT. - \param stop_reason Stop reason -- \b OUT. - */ - void check_min_mesh_sizes ( bool & stop , - NOMAD::stop_type & stop_reason ) const; - - /// Access to the mesh indices per coordinate. - /** - \return A point with the mesh index for each coordinate. - */ - const NOMAD::Point get_mesh_indices ( void ) const { return _r; } - - /// Access to the min mesh indices reached so far. - /** - \return A point with the mesh index for each coordinate. - */ - const NOMAD::Point get_min_mesh_indices ( void ) const { return _r_min; } - - - /// Access to the max mesh indices reached so far. - /** - \return A point with the mesh index for each coordinate. - */ - const NOMAD::Point get_max_mesh_indices ( void ) const { return _r_max; } - - - /// Manually set the mesh index. - /** - \param r The mesh index provided as a point -- \b IN. - */ - void set_mesh_indices ( const NOMAD::Point & r ); - - - - /// Manually set the limit mesh index (termination criterion). - /** - \param l The limit mesh index for all coordinates -- \b IN. - */ - void set_limit_mesh_index ( int l ); - - - - /// Access to the mesh ratios after a success - /** - \return A point with the ratio for each coordinate - */ - NOMAD::Point get_mesh_ratio_if_success ( void ) const; - - - - }; - - /// Display a NOMAD::XMesh object. - /** - \param out The NOMAD::Display object -- \b IN. - \param m The NOMAD::XMesh object to be displayed -- \b IN. - \return The NOMAD::Display object. - */ - inline const NOMAD::Display & operator << ( const NOMAD::Display & out , - const NOMAD::XMesh & m ) - { - m.display ( out ); - return out; - } - -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/defines.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/defines.hpp deleted file mode 100644 index 270967eba..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/defines.hpp +++ /dev/null @@ -1,511 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file defines.hpp - \brief Definitions - \author Sebastien Le Digabel - \date 2010-03-23 - */ -#ifndef __DEFINES__ -#define __DEFINES__ - -#include -#include -#include -#include -#include -#include - - -// #define R_VERSION // defined for the R version only - -// Matlab version OPTI style (if not defined than GERAD style) -// #define OPTI_VERSION - -// Define in order to display debug information -//#define DEBUG - -// define in order to display memory debug information: -//#define MEMORY_DEBUG - -// define in order to display TGP information. -// #define TGP_DEBUG - -// #define USE_TGP is defined in the makefile - -#ifdef DEBUG -#ifndef MEMORY_DEBUG -#define MEMORY_DEBUG -#ifndef TGP_DEBUG -#define TGP_DEBUG -#endif -#endif -#endif - - -// CASE Linux using gnu compiler -#ifdef __gnu_linux__ -#define GCC_X -#endif - -// CASE OSX using gnu compiler -#ifdef __APPLE__ -#ifdef __GNUC__ -#define GCC_X -#endif -#endif - -// CASE minGW using gnu compiler -#ifdef __MINGW32__ -#define WINDOWS -#ifdef __GNUC__ -#define GCC_X -#endif -#endif - -// CASE Visual Studio C++ compiler -#ifdef _MSC_VER -#define WINDOWS -#pragma warning(disable:4996) -#endif - -// For NOMAD random number generator -#if !defined(UINT32_MAX) -typedef unsigned int uint32_t; -#define UINT32_MAX 0xffffffff -#endif - -// to display model stats for each evaluation at -// which a model has been used (looks better -// with DISPLAY_DEGREE set to zero); -// The displayed stats are: -// type (1:model_search, 2:model_ordering) -// mesh_index -// cardinality of Y -// width of Y -// Y condition number -// h value, model for h, relative error (if constraints) -// f value, model for f, relative error - -// #define MODEL_STATS - -namespace NOMAD { - - /// Current version: - const std::string BASE_VERSION = "3.7.1"; - -#ifdef R_VERSION - const std::string VERSION = BASE_VERSION + ".R"; -#else -#ifdef USE_MPI -#ifdef USE_TGP - const std::string VERSION = BASE_VERSION + ".TGP" + ".MPI"; -#else - const std::string VERSION = BASE_VERSION + ".MPI"; -#endif -#else -#ifdef USE_TGP - const std::string VERSION = BASE_VERSION + ".TGP"; -#else - const std::string VERSION = BASE_VERSION; -#endif -#endif -#endif - - // Directory separator, plus LGPL and user guide files -#ifdef WINDOWS - const char DIR_SEP = '\\'; ///< Directory separator - const std::string HOME = "%NOMAD_HOME%"; ///< Home directory -#else - const char DIR_SEP = '/'; ///< Directory separator - const std::string HOME = "$NOMAD_HOME"; ///< Home directory -#endif - - /// Licence file - const std::string LGPL_FILE = HOME+DIR_SEP+"src"+DIR_SEP+"lgpl.txt"; - - /// User guide file - const std::string USER_GUIDE_FILE = HOME+DIR_SEP+"doc"+DIR_SEP+"user_guide.pdf"; - - /// Examples directory - const std::string EXAMPLES_DIR = HOME+DIR_SEP+"examples"; - - /// Tools directory - const std::string TOOLS_DIR = HOME+DIR_SEP+"tools"; - - /// Tag for valid cache files -#ifdef GCC_X - const int CACHE_FILE_ID = 77041301; -#else -#ifdef GCC_WINDOWS - const int CACHE_FILE_ID = 77041302; -#else -#ifdef _MSC_VER - const int CACHE_FILE_ID = 77041303; -#else - const int CACHE_FILE_ID = 77041304; -#endif -#endif -#endif - -#ifdef USE_MPI - // MPI constants - const int MAX_REQ_WAIT = 3 ; ///< Maximum time to wait for a request - const char STOP_SIGNAL = 'S'; ///< Stop signal - const char EVAL_SIGNAL = 'X'; ///< Evaluation signal - const char READY_SIGNAL = 'R'; ///< Ready signal - const char RESULT_SIGNAL = 'O'; ///< Result signal - const char WAIT_SIGNAL = 'W'; ///< Wait signal -#endif - - /// Maximum number of variables. - const int MAX_DIMENSION = 1000; - - // Old static Mesh index constants - const int L_LIMITS = 50; ///< Limits for the smesh index values - const int UNDEFINED_L = L_LIMITS+1; ///< Undefined value for the smesh index - - // xmesh index constants - const int XL_LIMITS = -50; ///< Limits for the xmesh index values - const int UNDEFINED_XL = XL_LIMITS-1; ///< Undefined value for the xmesh index - - - /// Default epsilon used by NOMAD::Double - /** Use Parameters::set_EPSILON(), or parameter EPSILON, - or NOMAD::Double::set_epsilon() to change it - */ - const double DEFAULT_EPSILON = 1e-13; - - /// Maximal output value for points used for models. - const double MODEL_MAX_OUTPUT = 1e10; - - /// Default infinity string used by NOMAD::Double - /** Use Parameters::set_INF_STR(), or parameter INF_STR, - or NOMAD::Double::set_inf_str() to change it - */ - const std::string DEFAULT_INF_STR = "inf"; - - /// Default undefined value string used by NOMAD::Double - /** Use Parameters::set_UNDEF_STR(), or parameter UNDEF_STR, - or NOMAD::Double::set_undef_str() to change it - */ - const std::string DEFAULT_UNDEF_STR = "NaN"; - - /// log(10) (for display widths.) - const double LOG10 = 2.30258509299; - - const double INF = std::numeric_limits::max(); ///< Infinity - - const double D_INT_MAX = UINT32_MAX; ///< The UINT32_MAX constant as a \c double - - // Singular Value Decomposition (SVD) constants: - const double SVD_EPS = 1e-13; ///< Epsilon for SVD - const int SVD_MAX_MPN = 1500; ///< Matrix maximal size (\c m+n ) - const double SVD_MAX_COND = NOMAD::INF; ///< Max. acceptable cond. number - - /// Default value for parameter POINT_DISPLAY_LIMIT - /** Use Parameters::set_POINT_DISPLAY_LIMIT() or parameter POINT_DISPLAY_LIMIT - or Point::set_display_limit() to change it */ - const int DEFAULT_POINT_DISPLAY_LIMIT = 20; - - // Display precisions. - const int DISPLAY_PRECISION_STD = 10; ///< Standard display precision - const int DISPLAY_PRECISION_BB = 15; ///< Display precision for blackboxes - - /// Constant for blackbox files #1. - const std::string BLACKBOX_INPUT_FILE_PREFIX = "nomad"; - - /// Constant for blackbox files #2. - const std::string BLACKBOX_INPUT_FILE_EXT = "input"; - - /// Constant for blackbox files #3. - const std::string BLACKBOX_OUTPUT_FILE_PREFIX = "nomad"; - - /// Constant for blackbox files #4. - const std::string BLACKBOX_OUTPUT_FILE_EXT = "output"; - - /// Display degree type. - enum dd_type - { - NO_DISPLAY , ///< No display - MINIMAL_DISPLAY, ///< Minimal dispay - NORMAL_DISPLAY , ///< Normal display - FULL_DISPLAY ///< Full display - }; - - /// Types of the variables - // (do not modify this order) - enum bb_input_type - { - CONTINUOUS , ///< Continuous variable (default) (R) - INTEGER , ///< Integer variable (I) - CATEGORICAL , ///< Categorical variable (C) - BINARY ///< Binary variable (B) - }; - - /// Blackbox outputs type - enum bb_output_type - { - OBJ , ///< Objective value - EB , ///< Extreme barrier constraint - PB , ///< progressive barrier constraint - // PEB ///< PB constraint that becomes EB once satisfied - PEB_P , ///< PEB constraint, state P (PB) - PEB_E , ///< PEB constraint, state E (EB) - FILTER , ///< Filter constraint - CNT_EVAL , ///< Output set to 0 or 1 to specify to count or not the - ///< blackbox evaluation - STAT_AVG , ///< Stat (average) - STAT_SUM , ///< Stat (sum) - UNDEFINED_BBO ///< Ignored output - }; - - /// Formulation for multi-objective optimization - enum multi_formulation_type - { - NORMALIZED , ///< Normalized formulation - PRODUCT , ///< Product formulation - DIST_L1 , ///< Distance formulation with norm L1 - DIST_L2 , ///< Distance formulation with norm L2 - DIST_LINF , ///< Distance formulation with norm Linf - UNDEFINED_FORMULATION ///< Undefined formulation - }; - - /// Poll type - enum poll_type - { - PRIMARY , ///< Primary poll - SECONDARY ///< Secondary poll - }; - - /// Poll center feasibility type - enum poll_center_type - { - FEASIBLE , ///< Feasible poll center type - INFEASIBLE , ///< Infeasible poll center type - UNDEFINED_POLL_CENTER_TYPE ///< Undefined poll center type - }; - - /// Search type - enum search_type - { - X0_EVAL , ///< Starting point evaluation - POLL , ///< Poll - EXTENDED_POLL , ///< Extended poll - SEARCH , ///< Generic search - CACHE_SEARCH , ///< Cache search (does not require evals) - SPEC_SEARCH , ///< MADS speculative search (dynamic order in GPS) - LH_SEARCH , ///< Latin Hypercube (LH) search - LH_SEARCH_P1 , ///< Latin Hypercube (LH) search during phase one - MODEL_SEARCH , ///< Model search - VNS_SEARCH , ///< VNS search - P1_SEARCH , ///< Phase one search - ASYNCHRONOUS , ///< Parallel asynchronous final evaluations - USER_SEARCH , ///< User search - UNDEFINED_SEARCH ///< Undefined search - }; - - /// Model type - enum model_type - { - QUADRATIC_MODEL , ///< Quadratic model - TGP_MODEL , ///< TGP model - NO_MODEL ///< No models - }; - - /// TGP mode - enum TGP_mode_type - { - TGP_FAST , ///< TGP fast mode. - TGP_PRECISE , ///< TGP precise mode. - TGP_USER ///< TGP user mode. - }; - - /// Success type of an iteration - // (do not modify this order) - enum success_type - { - UNSUCCESSFUL , ///< Failure - PARTIAL_SUCCESS , ///< Partial success (improving) - FULL_SUCCESS ///< Full success (dominating) - }; - - /// Quadratic interpolation type - enum interpolation_type - { - MFN , ///< Minimum Frobenius Norm interpolation. - REGRESSION , ///< Regression. - WP_REGRESSION , ///< Well-poised regression. - UNDEFINED_INTERPOLATION_TYPE ///< Undefined. - }; - - /// Stopping criteria - enum stop_type - { - NO_STOP , ///< No stop - ERROR , ///< Error - UNKNOWN_STOP_REASON , ///< Unknown - CTRL_C , ///< Ctrl-C - USER_STOPPED , ///< User-stopped in Evaluator::update_iteration() - MESH_PREC_REACHED , ///< Mesh minimum precision reached - X0_FAIL , ///< Problem with starting point evaluation - P1_FAIL , ///< Problem with phase one - DELTA_M_MIN_REACHED , ///< Min mesh size - DELTA_P_MIN_REACHED , ///< Min poll size - L_MAX_REACHED , ///< Max mesh index - L_MIN_REACHED , ///< Min mesh index - L_LIMITS_REACHED , ///< Mesh index limits - XL_LIMITS_REACHED , ///< Mesh index limits - MAX_TIME_REACHED , ///< Max time - MAX_BB_EVAL_REACHED , ///< Max number of blackbox evaluations - MAX_SGTE_EVAL_REACHED , ///< Max number of surrogate evaluations - MAX_EVAL_REACHED , ///< Max number of evaluations - MAX_SIM_BB_EVAL_REACHED , ///< Max number of sim bb evaluations - MAX_ITER_REACHED , ///< Max number of iterations - MAX_CONS_FAILED_ITER , ///< Max number of consecutive failed iterations - FEAS_REACHED , ///< Feasibility - F_TARGET_REACHED , ///< F_TARGET - STAT_SUM_TARGET_REACHED , ///< STAT_SUM_TARGET - L_CURVE_TARGET_REACHED , ///< L_CURVE_TARGET - MULTI_MAX_BB_REACHED , ///< Max number of blackbox evaluations (multi obj.) - MULTI_NB_MADS_RUNS_REACHED , ///< Max number of MADS runs (multi obj.) - MULTI_STAGNATION , ///< Stagnation criterion (multi obj.) - MULTI_NO_PARETO_PTS , ///< No Pareto points (multi obj.) - MAX_CACHE_MEMORY_REACHED ///< Max cache memory - }; - - /// Type of norm used for the computation of h - enum hnorm_type - { - L1 , ///< norm L1 - L2 , ///< norm L2 - LINF ///< norm Linf - }; - - /// Types of directions - // (do not modify this order) - enum direction_type - { - UNDEFINED_DIRECTION , ///< Undefined direction - MODEL_SEARCH_DIR , ///< Model search direction - NO_DIRECTION , ///< No direction - ORTHO_1 , ///< OrthoMADS 1 - ORTHO_2 , ///< OrthoMADS 2 - ORTHO_NP1_QUAD , ///< OrthoMADS n+1 use Quad model to determine n+1-th direction - ORTHO_NP1_NEG , ///< OrthoMADS n+1 use negative sum of n first directions to determine n+1-th direction - DYN_ADDED , ///< Dynamic addition (n+1-th direction added for ORTHO n+1) - ORTHO_2N , ///< OrthoMADS 2n - LT_1 , ///< LT-MADS 1 - LT_2 , ///< LT-MADS 2 - LT_2N , ///< LT-MADS 2n - LT_NP1 , ///< LT-MADS n+1 - GPS_BINARY , ///< GPS for binary variables - GPS_2N_STATIC , ///< GPS 2n static (classic coordinate search) - GPS_2N_RAND , ///< GPS 2n random - GPS_NP1_STATIC_UNIFORM , ///< GPS n+1 static uniform - GPS_NP1_STATIC , ///< GPS n+1 static - GPS_NP1_RAND_UNIFORM , ///< GPS n+1 random uniform - GPS_NP1_RAND , ///< GPS n+1 - PROSPECT_DIR ///< Prospect direction - }; - - /// Type for Eval_Point::check() failures - enum check_failed_type - { - CHECK_OK , ///< Correct check - LB_FAIL , ///< LB failure - UB_FAIL , ///< UB failure - FIX_VAR_FAIL , ///< Fixed variables failure - BIN_FAIL , ///< Binary failure - CAT_FAIL , ///< Categorical failure - INT_FAIL ///< Integer failure - }; - - /// Type for cache indexes in Cache: - enum cache_index_type - { - CACHE_1 , ///< Cache index #1 - CACHE_2 , ///< Cache index #2 - CACHE_3 , ///< Cache index #3 - UNDEFINED_CACHE ///< Undefined cache index - }; - - /// Type for DISPLAY_STATS parameter - // (do not modify this order): - enum display_stats_type - { - DS_OBJ , ///< Objective (f) value - // (keep in first position) - DS_SIM_BBE , ///< Number of simulated bb evaluations - DS_BBE , ///< Number of bb evaluations - DS_BLK_EVA , ///< Number of block evaluation calls - DS_SGTE , ///< Number of surrogate evaluations - DS_BBO , ///< All blackbox outputs - DS_EVAL , ///< Number of evaluations - DS_TIME , ///< Wall-clock time - DS_MESH_INDEX , ///< Mesh index - DS_MESH_SIZE , ///< Mesh size parameter Delta^m_k - DS_DELTA_M , ///< Same as \c DS_MESH_SIZE - DS_POLL_SIZE , ///< Poll size parameter Delta^p_k - DS_DELTA_P , ///< Same as \c DS_POLL_SIZE - DS_SOL , ///< Solution vector - DS_VAR , ///< One variable - DS_STAT_SUM , ///< Stat sum - DS_STAT_AVG , ///< Stat avg - DS_UNDEFINED ///< Undefined value - // (keep in last position) - }; - - /// Type for evaluation - enum eval_type - { - TRUTH , ///< Truth - SGTE ///< Surrogate - }; - - /// Type for an evaluation status - enum eval_status_type - { - EVAL_FAIL , ///< Evaluation failure - EVAL_USER_REJECT , ///< Evaluation was rejected by user (not failure -> may submitted again) - EVAL_OK , ///< Correct evaluation - EVAL_IN_PROGRESS , ///< Evaluation in progress - UNDEFINED_STATUS ///< Undefined evaluation status - }; - -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/nomad.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/nomad.cpp deleted file mode 100644 index 9d5995bb8..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/nomad.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file nomad.cpp - \brief NOMAD main file - \author Sebastien Le Digabel - \date 2010-04-12 - */ -#include "nomad.hpp" - -/*------------------------------------------*/ -/* NOMAD main function */ -/*------------------------------------------*/ -int main ( int argc , char ** argv ) -{ - - // display: - NOMAD::Display out ( std::cout ); - out.precision ( NOMAD::DISPLAY_PRECISION_STD ); - - - std::string error; - { - // NOMAD initializations: - NOMAD::begin ( argc , argv ); - - // usage: - if ( argc < 2 ) - { - NOMAD::display_usage ( argv[0],std::cerr ); - NOMAD::end(); - return EXIT_FAILURE; - } - - // parameters file: - std::string param_file_name = argv[1]; - std::string opt = param_file_name; - NOMAD::toupper ( opt ); - - // display version if option '-v' has been specified: - if ( opt == "-U" ) - { - NOMAD::display_usage ( argv[0], out ); - NOMAD::end(); - return EXIT_SUCCESS; - } - - - // display version if option '-v' has been specified: - if ( opt == "-V" || opt =="-VERSION") - { - NOMAD::display_version ( out ); - NOMAD::end(); - return EXIT_SUCCESS; - } - - // display info if option '-i' has been specified: - if ( opt == "-I" || opt == "-INFO" ) - { - NOMAD::display_info ( out ); - NOMAD::display_usage ( argv[0], out ); - NOMAD::end(); - return EXIT_SUCCESS; - } - - // parameters creation: - NOMAD::Parameters p ( out ); - - // display help on parameters if option '-h' has been specified: - if ( opt == "-H" || opt == "-HELP" ) - { - p.help ( argc , argv ); - NOMAD::end(); - return EXIT_SUCCESS; - } - - // display developer help on parameters if option '-d' has been specified: - if ( opt == "-D" ) - { - p.help ( argc , argv,true ); - NOMAD::end(); - return EXIT_SUCCESS; - } - - - // check the number of processess: -#ifdef USE_MPI - if ( NOMAD::Slave::get_nb_processes() < 2 ) - { - std::cerr << "ERROR: Incorrect command to run with MPI." << std::endl; - NOMAD::display_usage ( argv[0], std::cerr ); - NOMAD::end(); - return EXIT_FAILURE; - } -#endif - - try { - - - // read parameters file: - p.read ( param_file_name ); - - // parameters check: - p.check(); - - // display NOMAD info: - if ( p.get_display_degree() > NOMAD::MINIMAL_DISPLAY) - NOMAD::display_info ( out ); - - // parameters display: - if ( NOMAD::Slave::is_master() && - p.get_display_degree() == NOMAD::FULL_DISPLAY ) - out << std::endl - << NOMAD::open_block ( "parameters" ) << std::endl - << p - << NOMAD::close_block(); - - // algorithm creation and execution: - NOMAD::Mads mads ( p , NULL ); - if ( p.get_nb_obj() == 1 ) - mads.run(); - else - mads.multi_run(); - -#ifdef MODEL_STATS - mads.display_model_stats ( out ); -#endif - - } - catch ( std::exception & e ) - { - if ( NOMAD::Slave::is_master() ) - { - error = std::string ( "NOMAD has been interrupted: " ) + e.what(); - std::cerr << std::endl << error << std::endl << std::endl; - } - } - - NOMAD::Slave::stop_slaves ( out ); - NOMAD::end(); - } - -#ifdef MEMORY_DEBUG - NOMAD::display_cardinalities ( out ); -#endif - - return ( error.empty() ) ? EXIT_SUCCESS : EXIT_FAILURE; -} - -/*-----------------------------------------------------*/ -/* display NOMAD most important structures in memory */ -/*-----------------------------------------------------*/ -#ifdef MEMORY_DEBUG -void NOMAD::display_cardinalities ( const NOMAD::Display & out ) -{ - -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - return; -#endif - - // compute the biggest int value for appropriate display width: - int max = (NOMAD::Double::get_max_cardinality() > NOMAD::Point::get_max_cardinality()) - ? NOMAD::Double::get_max_cardinality() : NOMAD::Point::get_max_cardinality(); - if ( NOMAD::Direction::get_max_cardinality() > max ) - max = NOMAD::Direction::get_max_cardinality(); - if ( NOMAD::Set_Element::get_max_cardinality() > max ) - max = NOMAD::Set_Element::get_max_cardinality(); - if ( NOMAD::Set_Element::get_max_cardinality() > max ) - max = NOMAD::Set_Element::get_max_cardinality(); - if ( NOMAD::Cache_File_Point::get_max_cardinality() > max ) - max = NOMAD::Cache_File_Point::get_max_cardinality(); - - // cardinalities display: - // ---------------------- - out << std::endl - << NOMAD::open_block ( "important objects in memory" ); - - // NOMAD::Signature: - out << "Signature : "; - out.display_int_w ( NOMAD::Signature::get_cardinality() , max ); - out << " (max="; - out.display_int_w ( NOMAD::Signature::get_max_cardinality() , max ); - out << ")" << std::endl; - - // NOMAD::Double: - out << "Double : "; - out.display_int_w ( NOMAD::Double::get_cardinality() , max ); - out << " (max="; - out.display_int_w ( NOMAD::Double::get_max_cardinality() , max ); - out << ")" << std::endl; - - // NOMAD::Point: - out << "Point : "; - out.display_int_w ( NOMAD::Point::get_cardinality() , max ); - out << " (max="; - out.display_int_w ( NOMAD::Point::get_max_cardinality() , max ); - out << ")" << std::endl; - - // NOMAD::Direction: - out << "Direction : "; - out.display_int_w ( NOMAD::Direction::get_cardinality() , max ); - out << " (max="; - out.display_int_w ( NOMAD::Direction::get_max_cardinality() , max ); - out << ")" << std::endl; - - // Set_Element: - out << "Set_Element: "; - out.display_int_w (NOMAD::Set_Element::get_cardinality(), max); - out << " (max="; - out.display_int_w (NOMAD::Set_Element::get_max_cardinality(), max); - out << ")" << std::endl; - - // Set_Element: - out << "Set_Element : "; - out.display_int_w (NOMAD::Set_Element::get_cardinality(), max); - out << " (max="; - out.display_int_w (NOMAD::Set_Element::get_max_cardinality(), max); - out << ")" << std::endl; - - // NOMAD::Cache_File_Point: - out << "Cache_File_Point : "; - out.display_int_w ( NOMAD::Cache_File_Point::get_cardinality() , max ); - out << " (max="; - out.display_int_w ( NOMAD::Cache_File_Point::get_max_cardinality() , max ); - out << ")" << std::endl; - - out << NOMAD::close_block(); -} -#endif - -/*------------------------------------------*/ -/* display NOMAD version */ -/*------------------------------------------*/ -void NOMAD::display_version ( const NOMAD::Display & out ) -{ -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - return; -#endif - out << std::endl << "NOMAD - version " - << NOMAD::VERSION << " - www.gerad.ca/nomad" - << std::endl << std::endl; -} - -/*------------------------------------------*/ -/* display NOMAD information */ -/*------------------------------------------*/ -void NOMAD::display_info ( const NOMAD::Display & out ) -{ -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - return; -#endif - NOMAD::display_version ( out ); - out << NOMAD::open_block ( "Copyright (C) 2001-2015" ) - << "Mark A. Abramson - The Boeing Company" << std::endl - << "Charles Audet - Ecole Polytechnique de Montreal" << std::endl - << "Gilles Couture - Ecole Polytechnique de Montreal" << std::endl - << "John E. Dennis, Jr. - Rice University" << std::endl - << "Sebastien Le Digabel - Ecole Polytechnique de Montreal" << std::endl - << "Christophe Tribes - Ecole Polytechnique de Montreal" << std::endl - << NOMAD::close_block() - << std::endl - << "Funded in part by AFOSR and Exxon Mobil." << std::endl - << std::endl - << "License : \'" << NOMAD::LGPL_FILE << "\'" << std::endl - << "User guide: \'" << NOMAD::USER_GUIDE_FILE << "\'" << std::endl - << "Examples : \'" << NOMAD::EXAMPLES_DIR << "\'" << std::endl - << "Tools : \'" << NOMAD::TOOLS_DIR << "\'" << std::endl - << std::endl - << "Please report bugs to nomad@gerad.ca" - << std::endl; -} - -/*------------------------------------------*/ -/* display NOMAD usage */ -/*------------------------------------------*/ -void NOMAD::display_usage ( char* exeName, const NOMAD::Display & out ) -{ -#ifdef USE_MPI - if ( !NOMAD::Slave::is_master() ) - return; - out << std::endl - << "Run NOMAD.MPI : mpirun -np p " << exeName << " parameters_file" << std::endl - << "Info : " << exeName << " -i" << std::endl - << "Help : " << exeName << " -h keyword(s) (or 'all')" << std::endl - << "Developer help : " << exeName << " -d keyword(s) (or 'all')" << std::endl - << "Version : " << exeName << " -v" << std::endl - << "Usage : " << exeName << " -u" << std::endl - << std::endl; -#else - out << std::endl - << "Run NOMAD : " << exeName << " parameters_file" << std::endl - << "Info : " << exeName << " -i" << std::endl - << "Help : " << exeName << " -h keyword(s) (or 'all')" << std::endl - << "Developer help : " << exeName << " -d keyword(s) (or 'all')" << std::endl - << "Version : " << exeName << " -v" << std::endl - << "Usage : " << exeName << " -u" << std::endl - << std::endl; -#endif -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/nomad.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/nomad.hpp deleted file mode 100644 index 070e2dca1..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/nomad.hpp +++ /dev/null @@ -1,80 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file nomad.hpp - \brief NOMAD header file - \author Sebastien Le Digabel - \date 2010-04-12 -*/ -#ifndef __NOMAD__ -#define __NOMAD__ - -#include "Mads.hpp" - - -namespace NOMAD { - - /// Display NOMAD information. - /** - \param out A NOMAD::Display object -- \b IN. - */ - void display_info ( const NOMAD::Display & out ); - - /// Display NOMAD version. - /** - \param out A NOMAD::Display object -- \b IN. - */ - void display_version ( const NOMAD::Display & out ); - - /// Display NOMAD usage. - /** - \param exeName Name of executable -- \b IN. - \param out A NOMAD::Display object -- \b IN. - */ - void display_usage ( char* exeName, const NOMAD::Display & out ); - void display_usage ( const NOMAD::Display & out ); - -#ifdef MEMORY_DEBUG - /// Display NOMAD most important structures in memory. - /** - Is defined only in debug mode with flag MEMORY_DEBUG active. - \param out A NOMAD::Display object -- \b IN. - */ - void display_cardinalities ( const NOMAD::Display & out ); -#endif -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/utils.cpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/utils.cpp deleted file mode 100644 index 4a76117c5..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/utils.cpp +++ /dev/null @@ -1,1165 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file utils.cpp - \brief Utility functions - \author Sebastien Le Digabel - \date 2010-03-23 - \see utils.hpp -*/ -#include "utils.hpp" - -/*---------------------------------------------------------------*/ -/* construct the first n prime numbers */ -/*---------------------------------------------------------------*/ -void NOMAD::construct_primes ( int n , int * primes ) -{ - bool is_prime; - double kk; - int i = 0 , k = 2 , j; - while ( true ) { - is_prime = true; - kk = sqrt ( static_cast(k) ); - for ( j = 2 ; j <= kk ; ++j ) - if ( k%j==0 ) { - is_prime = false; - break; - } - if ( is_prime ) { - primes[i++] = k; - if ( i==n ) - break; - } - ++k; - } -} - -/*--------------------------------------------*/ -/* decompose a string (sentence) into words */ -/*--------------------------------------------*/ -void NOMAD::get_words ( const std::string & sentence , std::list & words ) -{ - std::string s; - std::istringstream in ( sentence ); - while ( true ) { - in >> s; - if ( in.fail() ) - break; - words.push_back ( s ); - } -} - -/*---------------------------------------------------------------*/ -/* get the pid (process id): used as random seed or unique tag */ -/*---------------------------------------------------------------*/ -int NOMAD::get_pid ( void ) -{ -#ifdef _MSC_VER - return _getpid(); -#else - return getpid(); -#endif -} - -/*---------------------------------------*/ -/* called at the beginning of NOMAD */ -/*---------------------------------------*/ -void NOMAD::begin ( int argc , char ** argv ) -{ -#ifdef USE_MPI - MPI_Init ( &argc , &argv ); -#endif -} - -/*---------------------------------------*/ -/* called at the end of NOMAD */ -/*---------------------------------------*/ -void NOMAD::end ( void ) -{ -#ifdef USE_MPI - MPI_Finalize(); -#endif -} - -/*-----------------------------------------------------------------*/ -/* check if a file exists and is executable */ -/*-----------------------------------------------------------------*/ -bool NOMAD::check_exe_file ( const std::string & file_name ) -{ -#ifdef WINDOWS - // don't check on Windows: - return true; -#else - return ( access ( file_name.c_str() , X_OK ) == 0 ); -#endif -} - -/*-----------------------------------------------------------------*/ -/* check if a file exists and is readable */ -/*-----------------------------------------------------------------*/ -bool NOMAD::check_read_file ( const std::string & file_name ) -{ -#ifdef _MSC_VER - return ( _access ( file_name.c_str() , 4 ) == 0 ); -#else - return ( access ( file_name.c_str() , R_OK ) == 0 ); -#endif -} - -/*-----------------------------------------------------------------*/ -/* NOMAD::itos */ -/*-----------------------------------------------------------------*/ -std::string NOMAD::itos ( int i ) -{ - std::ostringstream oss; - oss << i; - return oss.str(); -} - -/*-----------------------------------------------------------------*/ -/* NOMAD::itos */ -/*-----------------------------------------------------------------*/ -std::string NOMAD::itos ( size_t i ) -{ - std::ostringstream oss; - oss << i; - return oss.str(); -} - - -/*-----------------------------------------------------------------*/ -/* NOMAD::toupper - 1/2 */ -/*-----------------------------------------------------------------*/ -void NOMAD::toupper ( std::string & s ) -{ - size_t ns = s.size(); - for ( size_t i = 0 ; i < ns ; ++i ) - s[i] = std::toupper(s[i]); -} - -/*-----------------------------------------------------------------*/ -/* NOMAD::toupper - 2/2 */ -/*-----------------------------------------------------------------*/ -void NOMAD::toupper ( std::list & ls ) -{ - std::list::iterator it; - std::list::const_iterator end = ls.end(); - for ( it = ls.begin() ; it != end ; ++it ) - NOMAD::toupper ( *it ); -} - -/*-----------------------------------------------------------------*/ -/* NOMAD::atoi */ -/*-----------------------------------------------------------------*/ -bool NOMAD::atoi ( const std::string & s , int & i ) -{ - i = -1; - if ( s.empty() ) - return false; - - size_t n = s.size(); - - if ( s[0] == '-' ) { - if ( n > 1 && s[1] == '-' ) - return false; - std::string ss = s; - ss.erase(ss.begin()); - if ( NOMAD::atoi ( ss , i ) ) { - i = -i; - return true; - } - return false; - } - - for ( size_t k = 0 ; k < n ; ++k ) - if ( !isdigit(s[k]) ) - return false; - i = std::atoi(s.c_str()); - return true; -} - -bool NOMAD::atoi ( char c , int & i ) { - std::string s = "-"; - s[0] = c; - return NOMAD::atoi(s,i); -} - -/*-------------------------------------------------------------------*/ -/* if a NOMAD::bb_output_type variable corresponds to a constraint */ -/*-------------------------------------------------------------------*/ -bool NOMAD::bbot_is_constraint ( NOMAD::bb_output_type bbot ) -{ - return ( bbot == NOMAD::EB || - bbot == NOMAD::PB || - bbot == NOMAD::PEB_P || - bbot == NOMAD::PEB_E || - bbot == NOMAD::FILTER ); -} - -/*-----------------------------------------------------------------------*/ -/* if a NOMAD::direction_type variable corresponds to a MADS direction */ -/*-----------------------------------------------------------------------*/ -bool NOMAD::dir_is_mads ( NOMAD::direction_type dt ) -{ - return (dt == NOMAD::ORTHO_1 || - dt == NOMAD::ORTHO_2 || - dt == NOMAD::ORTHO_NP1_QUAD || - dt == NOMAD::ORTHO_NP1_NEG || - dt == NOMAD::DYN_ADDED || - dt == NOMAD::ORTHO_2N || - dt == NOMAD::LT_1 || - dt == NOMAD::LT_2 || - dt == NOMAD::LT_2N || - dt == NOMAD::LT_NP1 ); -} - -/*----------------------------------------------------------------------*/ -/* if a NOMAD::direction_type variable corresponds to a GPS direction */ -/*----------------------------------------------------------------------*/ -bool NOMAD::dir_is_gps ( NOMAD::direction_type dt ) -{ - return ( dt == NOMAD::GPS_BINARY || - dt == NOMAD::GPS_2N_STATIC || - dt == NOMAD::GPS_2N_RAND || - dt == NOMAD::GPS_NP1_STATIC_UNIFORM || - dt == NOMAD::GPS_NP1_STATIC || - dt == NOMAD::GPS_NP1_RAND_UNIFORM || - dt == NOMAD::GPS_NP1_RAND ); -} - -/*--------------------------------------------------------------------------*/ -/* if a NOMAD::direction_type variable corresponds to a LT-MADS direction */ -/*--------------------------------------------------------------------------*/ -bool NOMAD::dir_is_ltmads ( NOMAD::direction_type dt ) -{ - return ( dt == NOMAD::LT_1 || - dt == NOMAD::LT_2 || - dt == NOMAD::LT_2N || - dt == NOMAD::LT_NP1 ); -} - -/*-------------------------------------------------------------------------*/ -/* if a NOMAD::direction_type variable corresponds to a random direction */ -/*-------------------------------------------------------------------------*/ -bool NOMAD::dir_is_random ( NOMAD::direction_type dt ) -{ - return ( dt == NOMAD::GPS_NP1_RAND || - dt == NOMAD::GPS_NP1_RAND_UNIFORM || - dt == NOMAD::GPS_2N_RAND || - dt == NOMAD::LT_1 || - dt == NOMAD::LT_2 || - dt == NOMAD::LT_2N || - dt == NOMAD::LT_NP1 ); -} - -/*-----------------------------------------------------------------------------*/ -/* if a NOMAD::direction_type variable corresponds to a Ortho-MADS direction */ -/*-----------------------------------------------------------------------------*/ -bool NOMAD::dir_is_orthomads ( NOMAD::direction_type dt ) -{ - return (dt == NOMAD::ORTHO_1 || - dt == NOMAD::ORTHO_2 || - dt == NOMAD::ORTHO_NP1_QUAD || - dt == NOMAD::ORTHO_NP1_NEG || - dt == NOMAD::ORTHO_2N ); -} - -/*---------------------------------------------------------------------*/ -/* check if a set of directions includes one Ortho-MADS direction */ -/* (true if at least one direction in the set is of type Ortho-MADS) */ -/*---------------------------------------------------------------------*/ -bool NOMAD::dirs_have_orthomads ( const std::set & dir_types ) -{ - std::set::const_iterator it , end = dir_types.end(); - for ( it = dir_types.begin() ; it != end ; ++it ) - if ( NOMAD::dir_is_orthomads (*it) ) - return true; - return false; -} - -/*---------------------------------------------------------------------*/ -/* check if a set of directions includes one Ortho-MADS N+1 direction */ -/* (true if at least one direction in the set is of type Ortho-MADS) */ -/*---------------------------------------------------------------------*/ -bool NOMAD::dirs_have_orthomads_np1( const std::set & dir_types ) -{ - std::set::const_iterator it , end = dir_types.end(); - for ( it = dir_types.begin() ; it != end ; ++it ) - if ( (*it)==NOMAD::ORTHO_NP1_QUAD || (*it)==NOMAD::ORTHO_NP1_NEG) - return true; - return false; -} - -/*---------------------------------------------------*/ -/* returns true if one of the string of ls is in s */ -/*---------------------------------------------------*/ -bool NOMAD::string_find ( const std::string & s , const std::list & ls ) -{ - std::list::const_iterator it , end = ls.end(); - for ( it = ls.begin() ; it != end ; ++it ) - if ( NOMAD::string_find ( s , *it ) ) - return true; - return false; -} - -/*---------------------------------------------------*/ -/* search a string into another string */ -/*---------------------------------------------------*/ -bool NOMAD::string_find ( const std::string & s1 , const std::string & s2 ) -{ - return ( s1.find(s2) < s1.size() ); -} - -/*--------------------------------------------------------------------------*/ -/* returns true if one of the string in ls is an element of s */ -/*--------------------------------------------------------------------------*/ -bool NOMAD::string_match ( const std::string & s , const std::list & ls ) -{ - std::list::const_iterator it , end = ls.end(); - for ( it = ls.begin() ; it != end ; ++it ) - if ( s.compare(*it) == 0 ) - return true; - return false; -} - - -/*-----------------------------------------------------------------*/ -/* interpret a list of strings as a direction type */ -/*-----------------------------------------------------------------*/ -bool NOMAD::strings_to_direction_type ( const std::list & ls , - NOMAD::direction_type & dt ) -{ - - dt = NOMAD::UNDEFINED_DIRECTION; - - if ( ls.empty() || ls.size() > 4 ) - return false; - - std::list::const_iterator it = ls.begin() , end = ls.end(); - std::string s = *it; - NOMAD::toupper ( s ); - - // no direction: - if ( s == "NONE" ) { - dt = NOMAD::NO_DIRECTION; - return true; - } - - // Ortho-MADS with 1, 2, n+1 (plus QUAD or NEG), or 2n directions: - if ( s == "ORTHO" ) - { - ++it; - if ( it == end ) - { - dt = NOMAD::ORTHO_NP1_QUAD; // Default for ORTHO - return true; - } - if ( *it == "1" ) - { - dt = NOMAD::ORTHO_1; - return true; - } - if ( *it == "2" ) - { - dt = NOMAD::ORTHO_2; - return true; - } - s = *it; - NOMAD::toupper ( s ); - if ( s == "2N" ) - { - dt = NOMAD::ORTHO_2N; - return true; - } - if ( s == "N+1" ) - { - ++it; - if (it==end) - { - dt = NOMAD::ORTHO_NP1_QUAD; // Default for ORTHO N+1 - return true; - } - s = *it; - NOMAD::toupper ( s ); - if ( s=="QUAD" ) - { - dt= NOMAD::ORTHO_NP1_QUAD; - return true; - } - if ( s=="NEG" ) - { - dt=NOMAD::ORTHO_NP1_NEG; - return true; - } - - } - - return false; - } - - // LT-MADS with 1, 2 or 2n directions: - if ( s == "LT" ) { - ++it; - if ( it == end ) { - dt = NOMAD::LT_2N; - return true; - } - if ( *it == "1" ) { - dt = NOMAD::LT_1; - return true; - } - if ( *it == "2" ) { - dt = NOMAD::LT_2; - return true; - } - s = *it; - NOMAD::toupper ( s ); - if ( s == "N+1" ) { - dt = NOMAD::LT_NP1; - return true; - } - if ( s == "2N" ) { - dt = NOMAD::LT_2N; - return true; - } - return false; - } - - // GPS: - if ( s == "GPS" ) { - ++it; - if ( it == end ) { - dt = NOMAD::GPS_2N_STATIC; - return true; - } - s = *it; - NOMAD::toupper ( s ); - - // GPS for binary variables: - if ( s == "BINARY" || s == "BIN" ) { - dt = NOMAD::GPS_BINARY; - return true; - } - - // GPS, n+1 directions: - if ( s == "N+1" ) { - ++it; - if ( it == end ) { - dt = NOMAD::GPS_NP1_STATIC; - return true; - } - s = *it; - NOMAD::toupper ( s ); - - // GPS, n+1, static: - if ( s == "STATIC" ) { - ++it; - if ( it == end ) { - dt = NOMAD::GPS_NP1_STATIC; - return true; - } - s = *it; - NOMAD::toupper ( s ); - if ( s == "UNIFORM" ) { - dt = NOMAD::GPS_NP1_STATIC_UNIFORM; - return true; - } - return false; - } - - // GPS, n+1, random: - if ( s == "RAND" || s == "RANDOM" ) { - ++it; - if ( it == end ) { - dt = NOMAD::GPS_NP1_RAND; - return true; - } - s = *it; - NOMAD::toupper ( s ); - if ( s == "UNIFORM" ) { - dt = NOMAD::GPS_NP1_RAND_UNIFORM; - return true; - } - return false; - } - return false; - } - - // 2n directions: - if ( s == "2N" ) { - ++it; - if ( it == end ) { - dt = NOMAD::GPS_2N_STATIC; - return true; - } - s = *it; - NOMAD::toupper ( s ); - if ( s == "STATIC" ) { - dt = NOMAD::GPS_2N_STATIC; - return true; - } - if ( s == "RAND" || s == "RANDOM" ) { - dt = NOMAD::GPS_2N_RAND; - return true; - } - return false; - } - return false; - } - return false; -} - -/*---------------------------------------*/ -/* convert a string into a hnorm_type */ -/*---------------------------------------*/ -bool NOMAD::string_to_hnorm_type ( const std::string & s , NOMAD::hnorm_type & hn ) -{ - std::string ss = s; - NOMAD::toupper(ss); - if ( ss == "L1" ) { - hn = NOMAD::L1; - return true; - } - if ( ss == "L2" ) { - hn = NOMAD::L2; - return true; - } - if ( ss == "LINF" ) { - hn = NOMAD::LINF; - return true; - } - return false; -} - -/*-----------------------------------------*/ -/* convert a string into a TGP_mode_type */ -/*-----------------------------------------*/ -bool NOMAD::string_to_TGP_mode_type ( const std::string & s , NOMAD::TGP_mode_type & m ) -{ - std::string ss = s; - NOMAD::toupper(ss); - if ( ss == "FAST" ) { - m = NOMAD::TGP_FAST; - return true; - } - if ( ss == "PRECISE" ) { - m = NOMAD::TGP_PRECISE; - return true; - } - if ( ss == "USER" ) { - m = NOMAD::TGP_USER; - return true; - } - return false; -} - -/*--------------------------------------------------*/ -/* convert a string into a multi_formulation_type */ -/*--------------------------------------------------*/ -bool NOMAD::string_to_multi_formulation_type ( const std::string & s , - NOMAD::multi_formulation_type & mft ) -{ - std::string ss = s; - NOMAD::toupper(ss); - if ( ss == "NORMALIZED" ) { - mft = NOMAD::NORMALIZED; - return true; - } - if ( ss == "PRODUCT" ) { - mft = NOMAD::PRODUCT; - return true; - } - if ( ss == "DIST_L1" ) { - mft = NOMAD::DIST_L1; - return true; - } - if ( ss == "DIST_L2" ) { - mft = NOMAD::DIST_L2; - return true; - } - if ( ss == "DIST_LINF" ) { - mft = NOMAD::DIST_LINF; - return true; - } - return false; -} - -/*-------------------------------------------*/ -/* convert a string into a bb_output_type */ -/*-------------------------------------------*/ -bool NOMAD::string_to_bb_output_type ( const std::string & s , - NOMAD::bb_output_type & bbot ) -{ - std::string ss = s; - NOMAD::toupper(ss); - - if ( ss == "OBJ" ) { - bbot = NOMAD::OBJ; - return true; - } - if ( ss == "EB" ) { - bbot = NOMAD::EB; - return true; - } - if ( ss == "PB" || ss == "CSTR" ) { - bbot = NOMAD::PB; - return true; - } - if ( ss == "PEB" ) { - bbot = NOMAD::PEB_P; - return true; - } - if ( ss == "F" ) { - bbot = NOMAD::FILTER; - return true; - } - if ( ss == "STAT_AVG" ) { - bbot = NOMAD::STAT_AVG; - return true; - } - if ( ss == "STAT_SUM" ) { - bbot = NOMAD::STAT_SUM; - return true; - } - if ( ss == "CNT_EVAL" ) { - bbot = NOMAD::CNT_EVAL; - return true; - } - if ( ss == "NOTHING" || ss == "-" ) { - bbot = NOMAD::UNDEFINED_BBO; - return true; - } - return false; -} - -/*-----------------------------------------------------------------*/ -/* convert a string into a bb_input_type */ -/*-----------------------------------------------------------------*/ -bool NOMAD::string_to_bb_input_type ( const std::string & s , - NOMAD::bb_input_type & bbit ) -{ - std::string ss = s; - NOMAD::toupper ( ss ); - if ( ss=="R" || ss=="REAL" ) { - bbit = NOMAD::CONTINUOUS; - return true; - } - if ( ss=="C" || ss=="CAT" ) { - bbit = NOMAD::CATEGORICAL; - return true; - } - if ( ss=="B" || ss=="BIN" ) { - bbit = NOMAD::BINARY; - return true; - } - if ( ss=="I" || ss=="INT" ) { - bbit = NOMAD::INTEGER; - return true; - } - return false; -} - -/*-----------------------------------------------------------------*/ -/* convert a string into a model_type */ -/*-----------------------------------------------------------------*/ -bool NOMAD::string_to_model_type ( const std::string & s , - NOMAD::model_type & mt ) -{ - std::string ss = s; - NOMAD::toupper ( ss ); - if ( ss=="TGP" || ss=="TGP_MODEL" ) { - mt = NOMAD::TGP_MODEL; - return true; - } - if ( ss=="QUADRATIC" || ss=="QUADRATIC_MODEL" ) { - mt = NOMAD::QUADRATIC_MODEL; - return true; - } - - mt = NOMAD::NO_MODEL; - return false; -} - -/*----------------------------------------------------------------------*/ -/* convert a string in {"YES","NO","Y","N"} to a bool */ -/* value of return: -1: error */ -/* 0: bool=false */ -/* 1: bool=true */ -/*----------------------------------------------------------------------*/ -int NOMAD::string_to_bool ( const std::string & ss ) -{ - std::string s = ss; - NOMAD::toupper ( s ); - if ( s=="Y" || s=="YES" || s=="1" || s=="TRUE" ) - return 1; - if ( s=="N" || s=="NO" || s=="0" || s=="FALSE" ) - return 0; - return -1; -} - -/*---------------------------------------------------*/ -/* convert a string 'i-j' to the integers i and j */ -/*---------------------------------------------------*/ -bool NOMAD::string_to_index_range ( const std::string & s , - int & i , - int & j , - int * n , - bool check_order ) -{ - if ( s.empty() ) - return false; - - if ( s == "*" ) { - if ( !n ) - return false; - i = 0; - j = *n-1; - return true; - } - - if ( s[0] == '-' ) { - - size_t ns = s.size(); - if ( ns > 1 && s[1] == '-' ) - return false; - - std::string ss = s; - ss.erase ( ss.begin() ); - - if ( NOMAD::string_to_index_range ( ss , i , j , n , false ) ) { - i = -i; - return true; - } - return false; - } - - std::istringstream in (s); - std::string s1; - - getline ( in , s1 , '-' ); - - if (in.fail()) - return false; - - size_t k , n1 = s1.size(); - - if ( n1 >= s.size() - 1 ) { - for ( k = 0 ; k < n1 ; ++k ) - if (!isdigit(s1[k])) - return false; - if ( !NOMAD::atoi ( s1 , i ) ) - return false; - if ( n1 == s.size() ) { - j = i; - return true; - } - if (n) { - j = *n-1; - return true; - } - return false; - } - - std::string s2; - getline (in, s2); - - if (in.fail()) - return false; - - size_t n2 = s2.size(); - for ( k = 0 ; k < n2 ; ++k ) - if ( !isdigit(s2[k]) ) - return false; - - if ( !NOMAD::atoi ( s1, i ) || !NOMAD::atoi ( s2 , j ) ) - return false; - - return !check_order || i <= j; -} - - -int NOMAD::get_rank(double ** M, - size_t m, - size_t n) -{ - double * W = new double [n]; - double ** V = new double *[n]; - for (size_t i = 0 ; i < n ; ++i ) - { - V[i]=new double [n]; - } - - std::string error_msg; - NOMAD::SVD_decomposition ( error_msg , M , W , V , static_cast(m) , static_cast(n) ); - - for (size_t i=0;iNOMAD::SVD_EPS) - rank++; - } - - delete [] W; - return rank; - -} - - -/*--------------------------------------------------------------*/ -/* SVD decomposition */ -/* inspired and recoded from an old numerical recipes version */ -/*--------------------------------------------------------------*/ -/* */ -/* M = U . W . V' */ -/* */ -/* M ( m x n ) */ -/* U ( m x n ) */ -/* W ( n x n ) */ -/* V ( n x n ) */ -/* */ -/* U.U' = U'.U = I if m = n */ -/* U'.U = I if m > m */ -/* */ -/* V.V' = V'.V = I */ -/* */ -/* W diagonal */ -/* */ -/* M is given as first argument and becomes U */ -/* W is given as a size-n vector */ -/* V is given, not V' */ -/* */ -/*--------------------------------------------------------------*/ -bool NOMAD::SVD_decomposition ( std::string & error_msg , - double ** M , - double * W , - double ** V , - int m , - int n , - int max_mpn ) // default=1500 -{ - error_msg.clear(); - - if ( max_mpn > 0 && m+n > max_mpn ) { - error_msg = "SVD_decomposition() error: m+n > " + NOMAD::itos ( max_mpn ); - return false; - } - - double * rv1 = new double[n]; - double scale = 0.0; - double g = 0.0; - double norm = 0.0; - - int nm1 = n - 1; - - bool flag; - int i , j , k , l , its , jj , nm = 0; - double s , f , h , tmp , c , x , y , z , absf , absg , absh; - - const int NITER = 30; - - // Initialization W and V - for (i=0; i < n; ++i) - { - W[i]=0.0; - for (j=0; j < n ; ++j) - V[i][j]=0.0; - } - - // Householder reduction to bidiagonal form: - for ( i = 0 ; i < n ; ++i ) - { - l = i + 1; - rv1[i] = scale * g; - g = s = scale = 0.0; - if ( i < m ) - { - for ( k = i ; k < m ; ++k ) - scale += fabs ( M[k][i] ); - if ( scale ) { - for ( k = i ; k < m ; ++k ) - { - M[k][i] /= scale; - s += M[k][i] * M[k][i]; - } - f = M[i][i]; - g = ( f >= 0.0 ) ? -fabs(sqrt(s)) : fabs(sqrt(s)); - h = f * g - s; - M[i][i] = f - g; - for ( j = l ; j < n ; ++j ) { - for ( s = 0.0 , k = i ; k < m ; ++k ) - s += M[k][i] * M[k][j]; - f = s / h; - for ( k = i ; k < m ; ++k ) - M[k][j] += f * M[k][i]; - } - for ( k = i ; k < m ; ++k ) - M[k][i] *= scale; - } - } - W[i] = scale * g; - g = s = scale = 0.0; - if ( i < m && i != nm1 ) - { - for ( k = l ; k < n ; ++k ) - scale += fabs ( M[i][k] ); - if ( scale ) - { - for ( k = l ; k < n ; ++k ) - { - M[i][k] /= scale; - s += M[i][k] * M[i][k]; - } - f = M[i][l]; - g = ( f >= 0.0 ) ? -fabs(sqrt(s)) : fabs(sqrt(s)); - h = f * g - s; - M[i][l] = f - g; - for ( k = l ; k < n ; ++k ) - rv1[k] = M[i][k] / h; - for ( j = l ; j < m ; ++j ) { - for ( s=0.0,k=l ; k < n ; ++k ) - s += M[j][k] * M[i][k]; - for ( k=l ; k < n ; ++k ) - M[j][k] += s * rv1[k]; - } - for ( k = l ; k < n ; ++k ) - M[i][k] *= scale; - } - } - tmp = fabs ( W[i] ) + fabs ( rv1[i] ); - norm = ( norm > tmp ) ? norm : tmp; - } - - // accumulation of right-hand transformations: - for ( i = nm1 ; i >= 0 ; --i ) - { - if ( i < nm1 ) - { - if ( g ) - { - for ( j = l ; j < n ; ++j ) - V[j][i] = ( M[i][j] / M[i][l] ) / g; - for ( j = l ; j < n ; ++j ) { - for ( s = 0.0 , k = l ; k < n ; ++k ) - s += M[i][k] * V[k][j]; - for ( k = l ; k < n ; ++k ) - V[k][j] += s * V[k][i]; - } - } - for ( j = l ; j < n ; ++j ) - V[i][j] = V[j][i] = 0.0; - } - V[i][i] = 1.0; - g = rv1[i]; - l = i; - } - - // accumulation of left-hand transformations: - for ( i = ( ( m < n ) ? m : n ) - 1 ; i >= 0 ; --i ) - { - l = i + 1; - g = W[i]; - for ( j = l ; j < n ; ++j ) - M[i][j] = 0.0; - if ( g ) { - g = 1.0 / g; - for ( j = l ; j < n ; ++j ) - { - for ( s = 0.0 , k = l ; k < m ; ++k ) - s += M[k][i] * M[k][j]; - f = ( s / M[i][i] ) * g; - for ( k = i ; k < m ; ++k ) - M[k][j] += f * M[k][i]; - } - for ( j = i ; j < m ; ++j ) - M[j][i] *= g; - } - else - for ( j = i ; j < m ; ++j ) - M[j][i] = 0.0; - ++M[i][i]; - } - - // diagonalization of the bidiagonal form: - for ( k = nm1 ; k >= 0 ; --k ) - { - for ( its = 1 ; its <= NITER ; its++ ) - { - flag = true; - for ( l = k ; l >= 0 ; l-- ) - { - nm = l - 1; - if ( nm < 0 || fabs ( rv1[l]) + norm == norm ) - { - flag = false; - break; - } - if ( fabs ( W[nm] ) + norm == norm ) - break; - } - if ( flag ) - { - c = 0.0; - s = 1.0; - for ( i = l ; i <= k ; i++ ) - { - f = s * rv1[i]; - rv1[i] = c * rv1[i]; - if ( fabs(f) + norm == norm ) - break; - g = W[i]; - - absf = fabs(f); - absg = fabs(g); - h = ( absf > absg ) ? - absf * sqrt ( 1.0 + pow ( absg/absf , 2.0 ) ) : - ( ( absg==0 ) ? 0.0 : absg * sqrt ( 1.0 + pow ( absf/absg , 2.0 ) ) ); - - W[i] = h; - h = 1.0 / h; - c = g * h; - s = -f * h; - for ( j = 0 ; j < m ; ++j ) { - y = M[j][nm]; - z = M[j][ i]; - M[j][nm] = y * c + z * s; - M[j][ i] = z * c - y * s; - } - } - } - z = W[k]; - if ( l == k) { - if ( z < 0.0 ) { - W[k] = -z; - for ( j = 0 ; j < n ; j++ ) - V[j][k] = -V[j][k]; - } - break; // this 'break' is always active if k==0 - } - if ( its == NITER ) - { - error_msg = "SVD_decomposition() error: no convergence in " + - NOMAD::itos ( NITER ) + " iterations"; - delete [] rv1; - return false; - } - x = W[l]; - nm = k - 1; - y = W[nm]; - g = rv1[nm]; - h = rv1[k]; - f = ( (y-z) * (y+z) + (g-h) * (g+h) ) / ( 2.0 * h * y ); - - absf = fabs(f); - g = ( absf > 1.0 ) ? - absf * sqrt ( 1.0 + pow ( 1.0/absf , 2.0 ) ) : - sqrt ( 1.0 + pow ( absf , 2.0 ) ); - - f = ( (x-z) * (x+z) + - h * ( ( y / ( f + ( (f >= 0)? fabs(g) : -fabs(g) ) ) ) - h ) ) / x; - c = s = 1.0; - - for ( j = l ; j <= nm ; ++j ) { - i = j + 1; - g = rv1[i]; - y = W[i]; - h = s * g; - g = c * g; - - absf = fabs(f); - absh = fabs(h); - z = ( absf > absh ) ? - absf * sqrt ( 1.0 + pow ( absh/absf , 2.0 ) ) : - ( ( absh==0 ) ? 0.0 : absh * sqrt ( 1.0 + pow ( absf/absh , 2.0 ) ) ); - - rv1[j] = z; - c = f / z; - s = h / z; - f = x * c + g * s; - g = g * c - x * s; - h = y * s; - y *= c; - for ( jj = 0 ; jj < n ; ++jj ) - { - x = V[jj][j]; - z = V[jj][i]; - V[jj][j] = x * c + z * s; - V[jj][i] = z * c - x * s; - } - - absf = fabs(f); - absh = fabs(h); - z = ( absf > absh ) ? - absf * sqrt ( 1.0 + pow ( absh/absf , 2.0 ) ) : - ( ( absh==0 ) ? 0.0 : absh * sqrt ( 1.0 + pow ( absf/absh , 2.0 ) ) ); - - W[j] = z; - - if ( z ) - { - z = 1.0 / z; - c = f * z; - s = h * z; - } - f = c * g + s * y; - x = c * y - s * g; - for ( jj = 0 ; jj < m ; ++jj ) - { - y = M[jj][j]; - z = M[jj][i]; - M[jj][j] = y * c + z * s; - M[jj][i] = z * c - y * s; - } - } - rv1[l] = 0.0; - rv1[k] = f; - W [k] = x; - } - } - - delete [] rv1; - return true; -} diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp b/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp deleted file mode 100644 index b6631e5fe..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/nomad_src/utils.hpp +++ /dev/null @@ -1,387 +0,0 @@ -/*-------------------------------------------------------------------------------------*/ -/* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct search - version 3.7.1 */ -/* */ -/* Copyright (C) 2001-2015 Mark Abramson - the Boeing Company, Seattle */ -/* Charles Audet - Ecole Polytechnique, Montreal */ -/* Gilles Couture - Ecole Polytechnique, Montreal */ -/* John Dennis - Rice University, Houston */ -/* Sebastien Le Digabel - Ecole Polytechnique, Montreal */ -/* Christophe Tribes - Ecole Polytechnique, Montreal */ -/* */ -/* funded in part by AFOSR and Exxon Mobil */ -/* */ -/* Author: Sebastien Le Digabel */ -/* */ -/* Contact information: */ -/* Ecole Polytechnique de Montreal - GERAD */ -/* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ -/* e-mail: nomad@gerad.ca */ -/* phone : 1-514-340-6053 #6928 */ -/* fax : 1-514-340-5665 */ -/* */ -/* This program is free software: you can redistribute it and/or modify it under the */ -/* terms of the GNU Lesser General Public License as published by the Free Software */ -/* Foundation, either version 3 of the License, or (at your option) any later */ -/* version. */ -/* */ -/* This program is distributed in the hope that it will be useful, but WITHOUT ANY */ -/* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A */ -/* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ -/* */ -/* You should have received a copy of the GNU Lesser General Public License along */ -/* with this program. If not, see . */ -/* */ -/* You can find information on the NOMAD software at www.gerad.ca/nomad */ -/*-------------------------------------------------------------------------------------*/ -/** - \file utils.hpp - \brief Utility functions (headers) - \author Sebastien Le Digabel - \date 2010-03-23 - \see utils.cpp -*/ -#ifndef __UTILS__ -#define __UTILS__ - -#ifdef USE_MPI -#include -#endif - -#include -#include -#include -#include -#include -#include - -// use of 'access' or '_access', and getpid() or _getpid(): -#ifdef _MSC_VER -#include -#include -#else -#include -#endif - -#include "defines.hpp" - - -namespace NOMAD { - - /// Convert a string into a NOMAD::bb_input_type. - /** - \param s The string -- \b IN. - \param bbit The NOMAD::bb_input_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_bb_input_type ( const std::string & s , NOMAD::bb_input_type & bbit ); - - /// Convert a string into a NOMAD::bb_output_type. - /** - \param s The string -- \b IN. - \param bbot The NOMAD::bb_output_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_bb_output_type ( const std::string & s , NOMAD::bb_output_type & bbot ); - - /// Convert a string into a NOMAD::hnorm_type. - /** - \param s The string -- \b IN. - \param hn The NOMAD::hnorm_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_hnorm_type ( const std::string & s , NOMAD::hnorm_type & hn ); - - /// Convert a string into a NOMAD::TGP_mode_type. - /** - \param s The string -- \b IN. - \param m The NOMAD::TGP_mode_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_TGP_mode_type ( const std::string & s , NOMAD::TGP_mode_type & m ); - - /// Convert a string into a multi_formulation_type. - /** - \param s The string -- \b IN. - \param mft The NOMAD::multi_formulation_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_multi_formulation_type ( const std::string & s , - NOMAD::multi_formulation_type & mft ); - - /// Convert a string with format "i-j" into two integers i and j. - /** - If s=="*" and if n is defined, then i=0 and j=*n-1. - - \param s The string -- \b IN. - \param i The first integer \c i -- \b OUT. - \param j The second integer \c j -- \b OUT. - \param n Number of variables; use \c NULL if unknown - -- \b IN -- \b optional (default = \c NULL). - \param check_order A boolean indicating if \c i and \c j are to be compared - -- \b IN -- \b optional (default = \c true). - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_index_range ( const std::string & s , - int & i , - int & j , - int * n = NULL , - bool check_order = true ); - - - /// Convert a string in {"QUADRATIC","TGP"} to a \c NOMAD::model_type. - /** - \param s The string -- \b IN. - \param mt The NOMAD::model_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool string_to_model_type ( const std::string & s , NOMAD::model_type & mt ); - - /// Convert a string in {"YES","NO","Y","N","0","1","TRUE","FALSE"} to a boolean. - /** - \param s The string -- \b IN. - \return An integer equal to \c 0 for \c false, \c 1 for \c true, - and \c -1 if the conversion failed. - */ - int string_to_bool ( const std::string & s ); - - /// Interpret a list of strings as a direction type. - /** - \param ls The list of strings -- \b IN. - \param dt The NOMAD::direction_type -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool strings_to_direction_type ( const std::list & ls , - NOMAD::direction_type & dt ); - - /// If a NOMAD::bb_output_type variable corresponds to a constraint. - /** - \param bbot The NOMAD::bb_output_type -- \b IN. - \return A boolean equal to \c true if \c bbot corresponds to a constraint. - */ - bool bbot_is_constraint ( NOMAD::bb_output_type bbot ); - - /// If a NOMAD::direction_type variable corresponds to a MADS direction. - /** - \param dt The NOMAD::direction_type -- \b IN. - \return A boolean equal to \c true if \c dt corresponds to a MADS direction. - */ - bool dir_is_mads ( NOMAD::direction_type dt ); - - /// If a NOMAD::direction_type variable corresponds to a GPS direction. - /** - \param dt The NOMAD::direction_type -- \b IN. - \return A boolean equal to \c true if \c dt corresponds to a GPS direction. - */ - bool dir_is_gps ( NOMAD::direction_type dt ); - - /// If a NOMAD::direction_type variable corresponds to a LT-MADS direction. - /** - \param dt The NOMAD::direction_type -- \b IN. - \return A boolean equal to \c true if \c dt corresponds to a LT-MADS direction. - */ - bool dir_is_ltmads ( NOMAD::direction_type dt ); - - /// If a NOMAD::direction_type variable corresponds to a random direction. - /** - \param dt The NOMAD::direction_type -- \b IN. - \return A boolean equal to \c true if \c dt corresponds to a random direction. - */ - bool dir_is_random ( NOMAD::direction_type dt ); - - - /// If a NOMAD::direction_type variable corresponds to a Ortho-MADS direction. - /** - \param dt The NOMAD::direction_type -- \b IN. - \return A boolean equal to \c true if \c dt corresponds to a Ortho-MADS direction. - */ - bool dir_is_orthomads ( NOMAD::direction_type dt ); - - /// If a NOMAD::direction_type variable corresponds to a Ortho-MADS direction using XMesh. - /** - \param dt The NOMAD::direction_type -- \b IN. - \return A boolean equal to \c true if \c dt corresponds to a Ortho-MADS direction using XMesh. - */ - bool dir_is_orthomads_xmesh ( NOMAD::direction_type dt ); - - /// Check if a set of directions include Ortho-MADS direction. - /** - \param dir_types Set of direction types -- \b IN. - \return A boolean equal to \c true if at - least one direction in the set is - of type Ortho-MADS. - */ - bool dirs_have_orthomads ( const std::set & dir_types ); - - /// Check if a set of directions include Ortho-MADS direction using XMesh. - /** - \param dir_types Set of direction types -- \b IN. - \return A boolean equal to \c true if at - least one direction in the set is - of type Ortho-MADS+XMesh. - */ - bool dirs_have_orthomads_xmesh ( const std::set & dir_types ); - - - /// Check if a set of direction types include Ortho-MADS N+1 direction. - /** - \param dir_types Set of direction types -- \b IN. - \return A boolean equal to \c true if at - least one direction in the set is - of type Ortho-MADS N+1. - */ - bool dirs_have_orthomads_np1 ( const std::set & dir_types ); - - - /// Construct the n first prime numbers. - /** - \param n The integer \c n-- \b IN. - \param primes An integer array of size \c n for the prime numbers; - must be previously allocated -- \b OUT. - */ - void construct_primes ( int n , int * primes ); - - /// Decompose a string (sentence) into a list of strings (words). - /** - \param sentence The sentence -- \b IN. - \param words The words -- \b OUT. - */ - void get_words ( const std::string & sentence , std::list & words ); - - /// Check if a file exists and is executable. - /** - \param file_name A string corresponding to a file name -- \b IN. - \return A boolean equal to \c true if the file is executable. - */ - bool check_exe_file ( const std::string & file_name ); - - /// Check if a file exists and is readable. - /** - \param file_name A string corresponding to a file name -- \b IN. - \return A boolean equal to \c true if the file exists and is readable. - */ - bool check_read_file ( const std::string & file_name ); - - /// Get the process id (pid); useful for unique random seeds. - /** - \return An integer corresponding to the pid. - */ - int get_pid ( void ); - - /// Called at the beginning of NOMAD. - /** - \param argc Number of command line arguments. - \param argv Command line arguments. - */ - void begin ( int argc , char ** argv ); - - /// Called at the end of NOMAD. - void end ( void ); - - - /// Transform an integer into a string. - /** - \param i The integer -- \b IN. - \return The string. - */ - std::string itos ( int i ); - - - /// Transform a unsigned long (size_t) into a string. - /** - \param i The unsigned long -- \b IN. - \return The string. - */ - std::string itos ( size_t i ); - - - /// Put a string into upper cases. - /** - \param s The string -- \b IN/OUT. - */ - void toupper ( std::string & s ); - - /// Put a list of strings into upper cases. - /** - \param ls The list of strings -- \b IN/OUT. - */ - void toupper ( std::list & ls ); - - /// Convert a string into an integer. - /** - \param s The string -- \b IN. - \param i The integer -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool atoi ( const std::string & s , int & i ); - - /// Convert a character into an integer. - /** - \param c The character -- \b IN. - \param i The integer -- \b OUT. - \return A boolean equal to \c true if the conversion was possible. - */ - bool atoi ( char c , int & i ); - - /// Search a list of string inside a string. - /** - \param s The string -- \b IN. - \param ls The list of strings -- \b IN. - \return A boolean equal to \c true if one of the string of ls is in s. - */ - bool string_find ( const std::string & s , const std::list & ls ); - - /// Search a string into another string. - /** - \param s1 A string -- \b IN. - \param s2 A string -- \b IN. - \return A boolean equal to \c true if \c s2 is in \c s1. - */ - bool string_find ( const std::string & s1 , const std::string & s2 ); - - /// Search if a string matches an element in a list of string. - /** - \param s A string -- \b IN. - \param ls A list of strings -- \b IN. - \return A boolean equal to \c true if \c s matches an element in \c ls. - */ - bool string_match ( const std::string & s , const std::list & ls ); - - - /// SVD decomposition. - /** - - The \c mxn \c M matrix is decomposed into \c M=U.W.V'. - \param error_msg Error message when the function returns \c false -- \b OUT. - \param M The input \c mxn matrix; Will be replaced by \c U -- \b IN/OUT. - \param W The output \c nxn diagonal matrix -- \b OUT. - \param V The output \c nxn matrix -- \b OUT. - \param m Number of rows in M -- \b IN. - \param n Number of columns in M -- \b IN. - \param max_mpn Maximum allowed value for \c m+n; ignored if \c <=0 -- \b IN - -- \b optional (default = \c 1500). - \return A boolean equal to \c true if the decomposition worked. - */ - bool SVD_decomposition ( std::string & error_msg , - double ** M , - double * W , - double ** V , - int m , - int n , - int max_mpn = 1500 ); - - - // Get rank of a matrix using SVD decomposition - /** - - The \c mxn \c M matrix is decomposed into \c M=U.W.V'. The rank equals the size of W - \param M The input \c mxn matrix -- \b IN. - \param m Number of rows in M -- \b IN. - \param n Number of columns in M -- \b IN. - \return The rank>0 if the decomposition worked else 0. - */ - int get_rank(double **M, - size_t m, - size_t n); - - -} - -#endif diff --git a/pyoptsparse/pyoptsparse/pyNOMAD/source/numpy.i b/pyoptsparse/pyoptsparse/pyNOMAD/source/numpy.i deleted file mode 100644 index b6a588c03..000000000 --- a/pyoptsparse/pyoptsparse/pyNOMAD/source/numpy.i +++ /dev/null @@ -1,3161 +0,0 @@ -/* -*- C -*- (not really, but good for syntax highlighting) */ - -/* - * Copyright (c) 2005-2015, NumPy Developers. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * * Neither the name of the NumPy Developers nor the names of any - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifdef SWIGPYTHON - -%{ -#ifndef SWIG_FILE_WITH_INIT -#define NO_IMPORT_ARRAY -#endif -#include "stdio.h" -#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION -#include -%} - -/**********************************************************************/ - -%fragment("NumPy_Backward_Compatibility", "header") -{ -%#if NPY_API_VERSION < 0x00000007 -%#define NPY_ARRAY_DEFAULT NPY_DEFAULT -%#define NPY_ARRAY_FARRAY NPY_FARRAY -%#define NPY_FORTRANORDER NPY_FORTRAN -%#endif -} - -/**********************************************************************/ - -/* The following code originally appeared in - * enthought/kiva/agg/src/numeric.i written by Eric Jones. It was - * translated from C++ to C by John Hunter. Bill Spotz has modified - * it to fix some minor bugs, upgrade from Numeric to numpy (all - * versions), add some comments and functionality, and convert from - * direct code insertion to SWIG fragments. - */ - -%fragment("NumPy_Macros", "header") -{ -/* Macros to extract array attributes. - */ -%#if NPY_API_VERSION < 0x00000007 -%#define is_array(a) ((a) && PyArray_Check((PyArrayObject*)a)) -%#define array_type(a) (int)(PyArray_TYPE((PyArrayObject*)a)) -%#define array_numdims(a) (((PyArrayObject*)a)->nd) -%#define array_dimensions(a) (((PyArrayObject*)a)->dimensions) -%#define array_size(a,i) (((PyArrayObject*)a)->dimensions[i]) -%#define array_strides(a) (((PyArrayObject*)a)->strides) -%#define array_stride(a,i) (((PyArrayObject*)a)->strides[i]) -%#define array_data(a) (((PyArrayObject*)a)->data) -%#define array_descr(a) (((PyArrayObject*)a)->descr) -%#define array_flags(a) (((PyArrayObject*)a)->flags) -%#define array_enableflags(a,f) (((PyArrayObject*)a)->flags) = f -%#else -%#define is_array(a) ((a) && PyArray_Check(a)) -%#define array_type(a) PyArray_TYPE((PyArrayObject*)a) -%#define array_numdims(a) PyArray_NDIM((PyArrayObject*)a) -%#define array_dimensions(a) PyArray_DIMS((PyArrayObject*)a) -%#define array_strides(a) PyArray_STRIDES((PyArrayObject*)a) -%#define array_stride(a,i) PyArray_STRIDE((PyArrayObject*)a,i) -%#define array_size(a,i) PyArray_DIM((PyArrayObject*)a,i) -%#define array_data(a) PyArray_DATA((PyArrayObject*)a) -%#define array_descr(a) PyArray_DESCR((PyArrayObject*)a) -%#define array_flags(a) PyArray_FLAGS((PyArrayObject*)a) -%#define array_enableflags(a,f) PyArray_ENABLEFLAGS((PyArrayObject*)a,f) -%#endif -%#define array_is_contiguous(a) (PyArray_ISCONTIGUOUS((PyArrayObject*)a)) -%#define array_is_native(a) (PyArray_ISNOTSWAPPED((PyArrayObject*)a)) -%#define array_is_fortran(a) (PyArray_ISFORTRAN((PyArrayObject*)a)) -} - -/**********************************************************************/ - -%fragment("NumPy_Utilities", - "header") -{ - /* Given a PyObject, return a string describing its type. - */ - const char* pytype_string(PyObject* py_obj) - { - if (py_obj == NULL ) return "C NULL value"; - if (py_obj == Py_None ) return "Python None" ; - if (PyCallable_Check(py_obj)) return "callable" ; - if (PyString_Check( py_obj)) return "string" ; - if (PyInt_Check( py_obj)) return "int" ; - if (PyFloat_Check( py_obj)) return "float" ; - if (PyDict_Check( py_obj)) return "dict" ; - if (PyList_Check( py_obj)) return "list" ; - if (PyTuple_Check( py_obj)) return "tuple" ; -%#if PY_MAJOR_VERSION < 3 - if (PyFile_Check( py_obj)) return "file" ; - if (PyModule_Check( py_obj)) return "module" ; - if (PyInstance_Check(py_obj)) return "instance" ; -%#endif - - return "unkown type"; - } - - /* Given a NumPy typecode, return a string describing the type. - */ - const char* typecode_string(int typecode) - { - static const char* type_names[25] = {"bool", - "byte", - "unsigned byte", - "short", - "unsigned short", - "int", - "unsigned int", - "long", - "unsigned long", - "long long", - "unsigned long long", - "float", - "double", - "long double", - "complex float", - "complex double", - "complex long double", - "object", - "string", - "unicode", - "void", - "ntypes", - "notype", - "char", - "unknown"}; - return typecode < 24 ? type_names[typecode] : type_names[24]; - } - - /* Make sure input has correct numpy type. This now just calls - PyArray_EquivTypenums(). - */ - int type_match(int actual_type, - int desired_type) - { - return PyArray_EquivTypenums(actual_type, desired_type); - } - -%#ifdef SWIGPY_USE_CAPSULE - void free_cap(PyObject * cap) - { - void* array = (void*) PyCapsule_GetPointer(cap,SWIGPY_CAPSULE_NAME); - if (array != NULL) free(array); - } -%#endif - - -} - -/**********************************************************************/ - -%fragment("NumPy_Object_to_Array", - "header", - fragment="NumPy_Backward_Compatibility", - fragment="NumPy_Macros", - fragment="NumPy_Utilities") -{ - /* Given a PyObject pointer, cast it to a PyArrayObject pointer if - * legal. If not, set the python error string appropriately and - * return NULL. - */ - PyArrayObject* obj_to_array_no_conversion(PyObject* input, - int typecode) - { - PyArrayObject* ary = NULL; - if (is_array(input) && (typecode == NPY_NOTYPE || - PyArray_EquivTypenums(array_type(input), typecode))) - { - ary = (PyArrayObject*) input; - } - else if is_array(input) - { - const char* desired_type = typecode_string(typecode); - const char* actual_type = typecode_string(array_type(input)); - PyErr_Format(PyExc_TypeError, - "Array of type '%s' required. Array of type '%s' given", - desired_type, actual_type); - ary = NULL; - } - else - { - const char* desired_type = typecode_string(typecode); - const char* actual_type = pytype_string(input); - PyErr_Format(PyExc_TypeError, - "Array of type '%s' required. A '%s' was given", - desired_type, - actual_type); - ary = NULL; - } - return ary; - } - - /* Convert the given PyObject to a NumPy array with the given - * typecode. On success, return a valid PyArrayObject* with the - * correct type. On failure, the python error string will be set and - * the routine returns NULL. - */ - PyArrayObject* obj_to_array_allow_conversion(PyObject* input, - int typecode, - int* is_new_object) - { - PyArrayObject* ary = NULL; - PyObject* py_obj; - if (is_array(input) && (typecode == NPY_NOTYPE || - PyArray_EquivTypenums(array_type(input),typecode))) - { - ary = (PyArrayObject*) input; - *is_new_object = 0; - } - else - { - py_obj = PyArray_FROMANY(input, typecode, 0, 0, NPY_ARRAY_DEFAULT); - /* If NULL, PyArray_FromObject will have set python error value.*/ - ary = (PyArrayObject*) py_obj; - *is_new_object = 1; - } - return ary; - } - - /* Given a PyArrayObject, check to see if it is contiguous. If so, - * return the input pointer and flag it as not a new object. If it is - * not contiguous, create a new PyArrayObject using the original data, - * flag it as a new object and return the pointer. - */ - PyArrayObject* make_contiguous(PyArrayObject* ary, - int* is_new_object, - int min_dims, - int max_dims) - { - PyArrayObject* result; - if (array_is_contiguous(ary)) - { - result = ary; - *is_new_object = 0; - } - else - { - result = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*)ary, - array_type(ary), - min_dims, - max_dims); - *is_new_object = 1; - } - return result; - } - - /* Given a PyArrayObject, check to see if it is Fortran-contiguous. - * If so, return the input pointer, but do not flag it as not a new - * object. If it is not Fortran-contiguous, create a new - * PyArrayObject using the original data, flag it as a new object - * and return the pointer. - */ - PyArrayObject* make_fortran(PyArrayObject* ary, - int* is_new_object) - { - PyArrayObject* result; - if (array_is_fortran(ary)) - { - result = ary; - *is_new_object = 0; - } - else - { - Py_INCREF(array_descr(ary)); - result = (PyArrayObject*) PyArray_FromArray(ary, - array_descr(ary), - NPY_FORTRANORDER); - *is_new_object = 1; - } - return result; - } - - /* Convert a given PyObject to a contiguous PyArrayObject of the - * specified type. If the input object is not a contiguous - * PyArrayObject, a new one will be created and the new object flag - * will be set. - */ - PyArrayObject* obj_to_array_contiguous_allow_conversion(PyObject* input, - int typecode, - int* is_new_object) - { - int is_new1 = 0; - int is_new2 = 0; - PyArrayObject* ary2; - PyArrayObject* ary1 = obj_to_array_allow_conversion(input, - typecode, - &is_new1); - if (ary1) - { - ary2 = make_contiguous(ary1, &is_new2, 0, 0); - if ( is_new1 && is_new2) - { - Py_DECREF(ary1); - } - ary1 = ary2; - } - *is_new_object = is_new1 || is_new2; - return ary1; - } - - /* Convert a given PyObject to a Fortran-ordered PyArrayObject of the - * specified type. If the input object is not a Fortran-ordered - * PyArrayObject, a new one will be created and the new object flag - * will be set. - */ - PyArrayObject* obj_to_array_fortran_allow_conversion(PyObject* input, - int typecode, - int* is_new_object) - { - int is_new1 = 0; - int is_new2 = 0; - PyArrayObject* ary2; - PyArrayObject* ary1 = obj_to_array_allow_conversion(input, - typecode, - &is_new1); - if (ary1) - { - ary2 = make_fortran(ary1, &is_new2); - if (is_new1 && is_new2) - { - Py_DECREF(ary1); - } - ary1 = ary2; - } - *is_new_object = is_new1 || is_new2; - return ary1; - } -} /* end fragment */ - -/**********************************************************************/ - -%fragment("NumPy_Array_Requirements", - "header", - fragment="NumPy_Backward_Compatibility", - fragment="NumPy_Macros") -{ - /* Test whether a python object is contiguous. If array is - * contiguous, return 1. Otherwise, set the python error string and - * return 0. - */ - int require_contiguous(PyArrayObject* ary) - { - int contiguous = 1; - if (!array_is_contiguous(ary)) - { - PyErr_SetString(PyExc_TypeError, - "Array must be contiguous. A non-contiguous array was given"); - contiguous = 0; - } - return contiguous; - } - - /* Test whether a python object is (C_ or F_) contiguous. If array is - * contiguous, return 1. Otherwise, set the python error string and - * return 0. - */ - int require_c_or_f_contiguous(PyArrayObject* ary) - { - int contiguous = 1; - if (!(array_is_contiguous(ary) || array_is_fortran(ary))) - { - PyErr_SetString(PyExc_TypeError, - "Array must be contiguous (C_ or F_). A non-contiguous array was given"); - contiguous = 0; - } - return contiguous; - } - - /* Require that a numpy array is not byte-swapped. If the array is - * not byte-swapped, return 1. Otherwise, set the python error string - * and return 0. - */ - int require_native(PyArrayObject* ary) - { - int native = 1; - if (!array_is_native(ary)) - { - PyErr_SetString(PyExc_TypeError, - "Array must have native byteorder. " - "A byte-swapped array was given"); - native = 0; - } - return native; - } - - /* Require the given PyArrayObject to have a specified number of - * dimensions. If the array has the specified number of dimensions, - * return 1. Otherwise, set the python error string and return 0. - */ - int require_dimensions(PyArrayObject* ary, - int exact_dimensions) - { - int success = 1; - if (array_numdims(ary) != exact_dimensions) - { - PyErr_Format(PyExc_TypeError, - "Array must have %d dimensions. Given array has %d dimensions", - exact_dimensions, - array_numdims(ary)); - success = 0; - } - return success; - } - - /* Require the given PyArrayObject to have one of a list of specified - * number of dimensions. If the array has one of the specified number - * of dimensions, return 1. Otherwise, set the python error string - * and return 0. - */ - int require_dimensions_n(PyArrayObject* ary, - int* exact_dimensions, - int n) - { - int success = 0; - int i; - char dims_str[255] = ""; - char s[255]; - for (i = 0; i < n && !success; i++) - { - if (array_numdims(ary) == exact_dimensions[i]) - { - success = 1; - } - } - if (!success) - { - for (i = 0; i < n-1; i++) - { - sprintf(s, "%d, ", exact_dimensions[i]); - strcat(dims_str,s); - } - sprintf(s, " or %d", exact_dimensions[n-1]); - strcat(dims_str,s); - PyErr_Format(PyExc_TypeError, - "Array must have %s dimensions. Given array has %d dimensions", - dims_str, - array_numdims(ary)); - } - return success; - } - - /* Require the given PyArrayObject to have a specified shape. If the - * array has the specified shape, return 1. Otherwise, set the python - * error string and return 0. - */ - int require_size(PyArrayObject* ary, - npy_intp* size, - int n) - { - int i; - int success = 1; - int len; - char desired_dims[255] = "["; - char s[255]; - char actual_dims[255] = "["; - for(i=0; i < n;i++) - { - if (size[i] != -1 && size[i] != array_size(ary,i)) - { - success = 0; - } - } - if (!success) - { - for (i = 0; i < n; i++) - { - if (size[i] == -1) - { - sprintf(s, "*,"); - } - else - { - sprintf(s, "%ld,", (long int)size[i]); - } - strcat(desired_dims,s); - } - len = strlen(desired_dims); - desired_dims[len-1] = ']'; - for (i = 0; i < n; i++) - { - sprintf(s, "%ld,", (long int)array_size(ary,i)); - strcat(actual_dims,s); - } - len = strlen(actual_dims); - actual_dims[len-1] = ']'; - PyErr_Format(PyExc_TypeError, - "Array must have shape of %s. Given array has shape of %s", - desired_dims, - actual_dims); - } - return success; - } - - /* Require the given PyArrayObject to to be Fortran ordered. If the - * the PyArrayObject is already Fortran ordered, do nothing. Else, - * set the Fortran ordering flag and recompute the strides. - */ - int require_fortran(PyArrayObject* ary) - { - int success = 1; - int nd = array_numdims(ary); - int i; - npy_intp * strides = array_strides(ary); - if (array_is_fortran(ary)) return success; - /* Set the Fortran ordered flag */ - array_enableflags(ary,NPY_ARRAY_FARRAY); - /* Recompute the strides */ - strides[0] = strides[nd-1]; - for (i=1; i < nd; ++i) - strides[i] = strides[i-1] * array_size(ary,i-1); - return success; - } -} - -/* Combine all NumPy fragments into one for convenience */ -%fragment("NumPy_Fragments", - "header", - fragment="NumPy_Backward_Compatibility", - fragment="NumPy_Macros", - fragment="NumPy_Utilities", - fragment="NumPy_Object_to_Array", - fragment="NumPy_Array_Requirements") -{ -} - -/* End John Hunter translation (with modifications by Bill Spotz) - */ - -/* %numpy_typemaps() macro - * - * This macro defines a family of 75 typemaps that allow C arguments - * of the form - * - * 1. (DATA_TYPE IN_ARRAY1[ANY]) - * 2. (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) - * 3. (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) - * - * 4. (DATA_TYPE IN_ARRAY2[ANY][ANY]) - * 5. (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - * 6. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) - * 7. (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - * 8. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) - * - * 9. (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) - * 10. (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - * 11. (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - * 12. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) - * 13. (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - * 14. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) - * - * 15. (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) - * 16. (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - * 17. (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - * 18. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, , DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) - * 19. (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - * 20. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) - * - * 21. (DATA_TYPE INPLACE_ARRAY1[ANY]) - * 22. (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) - * 23. (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) - * - * 24. (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) - * 25. (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - * 26. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) - * 27. (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - * 28. (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) - * - * 29. (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) - * 30. (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - * 31. (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - * 32. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) - * 33. (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - * 34. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) - * - * 35. (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) - * 36. (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - * 37. (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - * 38. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) - * 39. (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - * 40. (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4) - * - * 41. (DATA_TYPE ARGOUT_ARRAY1[ANY]) - * 42. (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) - * 43. (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) - * - * 44. (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) - * - * 45. (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) - * - * 46. (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) - * - * 47. (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) - * 48. (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) - * - * 49. (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - * 50. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) - * 51. (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - * 52. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) - * - * 53. (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) - * 54. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) - * 55. (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) - * 56. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) - * - * 57. (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) - * 58. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4) - * 59. (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) - * 60. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4) - * - * 61. (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) - * 62. (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1) - * - * 63. (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - * 64. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) - * 65. (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - * 66. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2) - * - * 67. (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) - * 68. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3) - * 69. (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) - * 70. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3) - * - * 71. (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) - * 72. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) - * 73. (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) - * 74. (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) - * - * 75. (DATA_TYPE* INPLACE_ARRAY_FLAT, DIM_TYPE DIM_FLAT) - * - * where "DATA_TYPE" is any type supported by the NumPy module, and - * "DIM_TYPE" is any int-like type suitable for specifying dimensions. - * The difference between "ARRAY" typemaps and "FARRAY" typemaps is - * that the "FARRAY" typemaps expect Fortran ordering of - * multidimensional arrays. In python, the dimensions will not need - * to be specified (except for the "DATA_TYPE* ARGOUT_ARRAY1" - * typemaps). The IN_ARRAYs can be a numpy array or any sequence that - * can be converted to a numpy array of the specified type. The - * INPLACE_ARRAYs must be numpy arrays of the appropriate type. The - * ARGOUT_ARRAYs will be returned as new numpy arrays of the - * appropriate type. - * - * These typemaps can be applied to existing functions using the - * %apply directive. For example: - * - * %apply (double* IN_ARRAY1, int DIM1) {(double* series, int length)}; - * double prod(double* series, int length); - * - * %apply (int DIM1, int DIM2, double* INPLACE_ARRAY2) - * {(int rows, int cols, double* matrix )}; - * void floor(int rows, int cols, double* matrix, double f); - * - * %apply (double IN_ARRAY3[ANY][ANY][ANY]) - * {(double tensor[2][2][2] )}; - * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) - * {(double low[2][2][2] )}; - * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) - * {(double upp[2][2][2] )}; - * void luSplit(double tensor[2][2][2], - * double low[2][2][2], - * double upp[2][2][2] ); - * - * or directly with - * - * double prod(double* IN_ARRAY1, int DIM1); - * - * void floor(int DIM1, int DIM2, double* INPLACE_ARRAY2, double f); - * - * void luSplit(double IN_ARRAY3[ANY][ANY][ANY], - * double ARGOUT_ARRAY3[ANY][ANY][ANY], - * double ARGOUT_ARRAY3[ANY][ANY][ANY]); - */ - -%define %numpy_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE) - -/************************/ -/* Input Array Typemaps */ -/************************/ - -/* Typemap suite for (DATA_TYPE IN_ARRAY1[ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE IN_ARRAY1[ANY]) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE IN_ARRAY1[ANY]) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[1] = { $1_dim0 }; - array = obj_to_array_contiguous_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 1) || - !require_size(array, size, 1)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(freearg) - (DATA_TYPE IN_ARRAY1[ANY]) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[1] = { -1 }; - array = obj_to_array_contiguous_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 1) || - !require_size(array, size, 1)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); -} -%typemap(freearg) - (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[1] = {-1}; - array = obj_to_array_contiguous_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 1) || - !require_size(array, size, 1)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE IN_ARRAY2[ANY][ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE IN_ARRAY2[ANY][ANY]) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE IN_ARRAY2[ANY][ANY]) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[2] = { $1_dim0, $1_dim1 }; - array = obj_to_array_contiguous_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 2) || - !require_size(array, size, 2)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(freearg) - (DATA_TYPE IN_ARRAY2[ANY][ANY]) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[2] = { -1, -1 }; - array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 2) || - !require_size(array, size, 2)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); -} -%typemap(freearg) - (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[2] = { -1, -1 }; - array = obj_to_array_contiguous_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 2) || - !require_size(array, size, 2)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[2] = { -1, -1 }; - array = obj_to_array_fortran_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 2) || - !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); -} -%typemap(freearg) - (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[2] = { -1, -1 }; - array = obj_to_array_fortran_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 2) || - !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; - array = obj_to_array_contiguous_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 3) || - !require_size(array, size, 3)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(freearg) - (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[3] = { -1, -1, -1 }; - array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 3) || - !require_size(array, size, 3)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); -} -%typemap(freearg) - (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - /* for now, only concerned with lists */ - $1 = PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL, int* is_new_object_array=NULL) -{ - npy_intp size[2] = { -1, -1 }; - PyArrayObject* temp_array; - Py_ssize_t i; - int is_new_object; - - /* length of the list */ - $2 = PyList_Size($input); - - /* the arrays */ - array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); - object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); - is_new_object_array = (int *)calloc($2,sizeof(int)); - - if (array == NULL || object_array == NULL || is_new_object_array == NULL) - { - SWIG_fail; - } - - for (i=0; i<$2; i++) - { - temp_array = obj_to_array_contiguous_allow_conversion(PySequence_GetItem($input,i), DATA_TYPECODE, &is_new_object); - - /* the new array must be stored so that it can be destroyed in freearg */ - object_array[i] = temp_array; - is_new_object_array[i] = is_new_object; - - if (!temp_array || !require_dimensions(temp_array, 2)) SWIG_fail; - - /* store the size of the first array in the list, then use that for comparison. */ - if (i == 0) - { - size[0] = array_size(temp_array,0); - size[1] = array_size(temp_array,1); - } - - if (!require_size(temp_array, size, 2)) SWIG_fail; - - array[i] = (DATA_TYPE*) array_data(temp_array); - } - - $1 = (DATA_TYPE**) array; - $3 = (DIM_TYPE) size[0]; - $4 = (DIM_TYPE) size[1]; -} -%typemap(freearg) - (DATA_TYPE** IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - Py_ssize_t i; - - if (array$argnum!=NULL) free(array$argnum); - - /*freeing the individual arrays if needed */ - if (object_array$argnum!=NULL) - { - if (is_new_object_array$argnum!=NULL) - { - for (i=0; i<$2; i++) - { - if (object_array$argnum[i] != NULL && is_new_object_array$argnum[i]) - { Py_DECREF(object_array$argnum[i]); } - } - free(is_new_object_array$argnum); - } - free(object_array$argnum); - } -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, - * DATA_TYPE* IN_ARRAY3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[3] = { -1, -1, -1 }; - array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 3) || - !require_size(array, size, 3)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[3] = { -1, -1, -1 }; - array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 3) || - !require_size(array, size, 3) | !require_fortran(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); -} -%typemap(freearg) - (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, - * DATA_TYPE* IN_FARRAY3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[3] = { -1, -1, -1 }; - array = obj_to_array_fortran_allow_conversion($input, - DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 3) || - !require_size(array, size, 3) || !require_fortran(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[4] = { $1_dim0, $1_dim1, $1_dim2 , $1_dim3}; - array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 4) || - !require_size(array, size, 4)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(freearg) - (DATA_TYPE IN_ARRAY4[ANY][ANY][ANY][ANY]) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3, DIM_TYPE DIM4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[4] = { -1, -1, -1, -1 }; - array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 4) || - !require_size(array, size, 4)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); - $5 = (DIM_TYPE) array_size(array,3); -} -%typemap(freearg) - (DATA_TYPE* IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3, DIM_TYPE DIM4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - /* for now, only concerned with lists */ - $1 = PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL, int* is_new_object_array=NULL) -{ - npy_intp size[3] = { -1, -1, -1 }; - PyArrayObject* temp_array; - Py_ssize_t i; - int is_new_object; - - /* length of the list */ - $2 = PyList_Size($input); - - /* the arrays */ - array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); - object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); - is_new_object_array = (int *)calloc($2,sizeof(int)); - - if (array == NULL || object_array == NULL || is_new_object_array == NULL) - { - SWIG_fail; - } - - for (i=0; i<$2; i++) - { - temp_array = obj_to_array_contiguous_allow_conversion(PySequence_GetItem($input,i), DATA_TYPECODE, &is_new_object); - - /* the new array must be stored so that it can be destroyed in freearg */ - object_array[i] = temp_array; - is_new_object_array[i] = is_new_object; - - if (!temp_array || !require_dimensions(temp_array, 3)) SWIG_fail; - - /* store the size of the first array in the list, then use that for comparison. */ - if (i == 0) - { - size[0] = array_size(temp_array,0); - size[1] = array_size(temp_array,1); - size[2] = array_size(temp_array,2); - } - - if (!require_size(temp_array, size, 3)) SWIG_fail; - - array[i] = (DATA_TYPE*) array_data(temp_array); - } - - $1 = (DATA_TYPE**) array; - $3 = (DIM_TYPE) size[0]; - $4 = (DIM_TYPE) size[1]; - $5 = (DIM_TYPE) size[2]; -} -%typemap(freearg) - (DATA_TYPE** IN_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - Py_ssize_t i; - - if (array$argnum!=NULL) free(array$argnum); - - /*freeing the individual arrays if needed */ - if (object_array$argnum!=NULL) - { - if (is_new_object_array$argnum!=NULL) - { - for (i=0; i<$2; i++) - { - if (object_array$argnum[i] != NULL && is_new_object_array$argnum[i]) - { Py_DECREF(object_array$argnum[i]); } - } - free(is_new_object_array$argnum); - } - free(object_array$argnum); - } -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, - * DATA_TYPE* IN_ARRAY4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[4] = { -1, -1, -1 , -1}; - array = obj_to_array_contiguous_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 4) || - !require_size(array, size, 4)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DIM_TYPE) array_size(array,3); - $5 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_ARRAY4) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3, DIM_TYPE DIM4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[4] = { -1, -1, -1, -1 }; - array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 4) || - !require_size(array, size, 4) | !require_fortran(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); - $5 = (DIM_TYPE) array_size(array,3); -} -%typemap(freearg) - (DATA_TYPE* IN_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, - * DATA_TYPE* IN_FARRAY4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) -{ - $1 = is_array($input) || PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) - (PyArrayObject* array=NULL, int is_new_object=0) -{ - npy_intp size[4] = { -1, -1, -1 , -1 }; - array = obj_to_array_fortran_allow_conversion($input, DATA_TYPECODE, - &is_new_object); - if (!array || !require_dimensions(array, 4) || - !require_size(array, size, 4) || !require_fortran(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DIM_TYPE) array_size(array,3); - $5 = (DATA_TYPE*) array_data(array); -} -%typemap(freearg) - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* IN_FARRAY4) -{ - if (is_new_object$argnum && array$argnum) - { Py_DECREF(array$argnum); } -} - -/***************************/ -/* In-Place Array Typemaps */ -/***************************/ - -/* Typemap suite for (DATA_TYPE INPLACE_ARRAY1[ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE INPLACE_ARRAY1[ANY]) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE INPLACE_ARRAY1[ANY]) - (PyArrayObject* array=NULL) -{ - npy_intp size[1] = { $1_dim0 }; - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,1) || !require_size(array, size, 1) || - !require_contiguous(array) || !require_native(array)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) - (PyArrayObject* array=NULL, int i=1) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,1) || !require_contiguous(array) - || !require_native(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = 1; - for (i=0; i < array_numdims(array); ++i) $2 *= array_size(array,i); -} - -/* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) - (PyArrayObject* array=NULL, int i=0) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,1) || !require_contiguous(array) - || !require_native(array)) SWIG_fail; - $1 = 1; - for (i=0; i < array_numdims(array); ++i) $1 *= array_size(array,i); - $2 = (DATA_TYPE*) array_data(array); -} - -/* Typemap suite for (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) - (PyArrayObject* array=NULL) -{ - npy_intp size[2] = { $1_dim0, $1_dim1 }; - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,2) || !require_size(array, size, 2) || - !require_contiguous(array) || !require_native(array)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,2) || !require_contiguous(array) - || !require_native(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,2) || !require_contiguous(array) || - !require_native(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DATA_TYPE*) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,2) || !require_contiguous(array) - || !require_native(array) || !require_fortran(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,2) || !require_contiguous(array) || - !require_native(array) || !require_fortran(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DATA_TYPE*) array_data(array); -} - -/* Typemap suite for (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) - (PyArrayObject* array=NULL) -{ - npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,3) || !require_size(array, size, 3) || - !require_contiguous(array) || !require_native(array)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,3) || !require_contiguous(array) || - !require_native(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); -} - -/* Typemap suite for (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - $1 = PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL) -{ - npy_intp size[2] = { -1, -1 }; - PyArrayObject* temp_array; - Py_ssize_t i; - - /* length of the list */ - $2 = PyList_Size($input); - - /* the arrays */ - array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); - object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); - - if (array == NULL || object_array == NULL) - { - SWIG_fail; - } - - for (i=0; i<$2; i++) - { - temp_array = obj_to_array_no_conversion(PySequence_GetItem($input,i), DATA_TYPECODE); - - /* the new array must be stored so that it can be destroyed in freearg */ - object_array[i] = temp_array; - - if ( !temp_array || !require_dimensions(temp_array, 2) || - !require_contiguous(temp_array) || - !require_native(temp_array) || - !PyArray_EquivTypenums(array_type(temp_array), DATA_TYPECODE) - ) SWIG_fail; - - /* store the size of the first array in the list, then use that for comparison. */ - if (i == 0) - { - size[0] = array_size(temp_array,0); - size[1] = array_size(temp_array,1); - } - - if (!require_size(temp_array, size, 2)) SWIG_fail; - - array[i] = (DATA_TYPE*) array_data(temp_array); - } - - $1 = (DATA_TYPE**) array; - $3 = (DIM_TYPE) size[0]; - $4 = (DIM_TYPE) size[1]; -} -%typemap(freearg) - (DATA_TYPE** INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - if (array$argnum!=NULL) free(array$argnum); - if (object_array$argnum!=NULL) free(object_array$argnum); -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, - * DATA_TYPE* INPLACE_ARRAY3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,3) || !require_contiguous(array) - || !require_native(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DATA_TYPE*) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,3) || !require_contiguous(array) || - !require_native(array) || !require_fortran(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, - * DATA_TYPE* INPLACE_FARRAY3) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,3) || !require_contiguous(array) - || !require_native(array) || !require_fortran(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DATA_TYPE*) array_data(array); -} - -/* Typemap suite for (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE INPLACE_ARRAY4[ANY][ANY][ANY][ANY]) - (PyArrayObject* array=NULL) -{ - npy_intp size[4] = { $1_dim0, $1_dim1, $1_dim2 , $1_dim3 }; - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,4) || !require_size(array, size, 4) || - !require_contiguous(array) || !require_native(array)) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3, DIM_TYPE DIM4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,4) || !require_contiguous(array) || - !require_native(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); - $5 = (DIM_TYPE) array_size(array,3); -} - -/* Typemap suite for (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3, DIM_TYPE DIM4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - $1 = PySequence_Check($input); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - (DATA_TYPE** array=NULL, PyArrayObject** object_array=NULL) -{ - npy_intp size[3] = { -1, -1, -1 }; - PyArrayObject* temp_array; - Py_ssize_t i; - - /* length of the list */ - $2 = PyList_Size($input); - - /* the arrays */ - array = (DATA_TYPE **)malloc($2*sizeof(DATA_TYPE *)); - object_array = (PyArrayObject **)calloc($2,sizeof(PyArrayObject *)); - - if (array == NULL || object_array == NULL) - { - SWIG_fail; - } - - for (i=0; i<$2; i++) - { - temp_array = obj_to_array_no_conversion(PySequence_GetItem($input,i), DATA_TYPECODE); - - /* the new array must be stored so that it can be destroyed in freearg */ - object_array[i] = temp_array; - - if ( !temp_array || !require_dimensions(temp_array, 3) || - !require_contiguous(temp_array) || - !require_native(temp_array) || - !PyArray_EquivTypenums(array_type(temp_array), DATA_TYPECODE) - ) SWIG_fail; - - /* store the size of the first array in the list, then use that for comparison. */ - if (i == 0) - { - size[0] = array_size(temp_array,0); - size[1] = array_size(temp_array,1); - size[2] = array_size(temp_array,2); - } - - if (!require_size(temp_array, size, 3)) SWIG_fail; - - array[i] = (DATA_TYPE*) array_data(temp_array); - } - - $1 = (DATA_TYPE**) array; - $3 = (DIM_TYPE) size[0]; - $4 = (DIM_TYPE) size[1]; - $5 = (DIM_TYPE) size[2]; -} -%typemap(freearg) - (DATA_TYPE** INPLACE_ARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - if (array$argnum!=NULL) free(array$argnum); - if (object_array$argnum!=NULL) free(object_array$argnum); -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, - * DATA_TYPE* INPLACE_ARRAY4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_ARRAY4) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,4) || !require_contiguous(array) - || !require_native(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DIM_TYPE) array_size(array,3); - $5 = (DATA_TYPE*) array_data(array); -} - -/* Typemap suite for (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, - * DIM_TYPE DIM3, DIM_TYPE DIM4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_FARRAY4, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,4) || !require_contiguous(array) || - !require_native(array) || !require_fortran(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = (DIM_TYPE) array_size(array,0); - $3 = (DIM_TYPE) array_size(array,1); - $4 = (DIM_TYPE) array_size(array,2); - $5 = (DIM_TYPE) array_size(array,3); -} - -/* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, - * DATA_TYPE* INPLACE_FARRAY4) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DIM_TYPE DIM4, DATA_TYPE* INPLACE_FARRAY4) - (PyArrayObject* array=NULL) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_dimensions(array,4) || !require_contiguous(array) - || !require_native(array) || !require_fortran(array)) SWIG_fail; - $1 = (DIM_TYPE) array_size(array,0); - $2 = (DIM_TYPE) array_size(array,1); - $3 = (DIM_TYPE) array_size(array,2); - $4 = (DIM_TYPE) array_size(array,3); - $5 = (DATA_TYPE*) array_data(array); -} - -/*************************/ -/* Argout Array Typemaps */ -/*************************/ - -/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY1[ANY]) - */ -%typemap(in,numinputs=0, - fragment="NumPy_Backward_Compatibility,NumPy_Macros") - (DATA_TYPE ARGOUT_ARRAY1[ANY]) - (PyObject* array = NULL) -{ - npy_intp dims[1] = { $1_dim0 }; - array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); - if (!array) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(argout) - (DATA_TYPE ARGOUT_ARRAY1[ANY]) -{ - $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); -} - -/* Typemap suite for (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) - */ -%typemap(in,numinputs=1, - fragment="NumPy_Fragments") - (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) - (PyObject* array = NULL) -{ - npy_intp dims[1]; - if (!PyInt_Check($input)) - { - const char* typestring = pytype_string($input); - PyErr_Format(PyExc_TypeError, - "Int dimension expected. '%s' given.", - typestring); - SWIG_fail; - } - $2 = (DIM_TYPE) PyInt_AsLong($input); - dims[0] = (npy_intp) $2; - array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); - if (!array) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); -} -%typemap(argout) - (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) -{ - $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); -} - -/* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) - */ -%typemap(in,numinputs=1, - fragment="NumPy_Fragments") - (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) - (PyObject* array = NULL) -{ - npy_intp dims[1]; - if (!PyInt_Check($input)) - { - const char* typestring = pytype_string($input); - PyErr_Format(PyExc_TypeError, - "Int dimension expected. '%s' given.", - typestring); - SWIG_fail; - } - $1 = (DIM_TYPE) PyInt_AsLong($input); - dims[0] = (npy_intp) $1; - array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); - if (!array) SWIG_fail; - $2 = (DATA_TYPE*) array_data(array); -} -%typemap(argout) - (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) -{ - $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); -} - -/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) - */ -%typemap(in,numinputs=0, - fragment="NumPy_Backward_Compatibility,NumPy_Macros") - (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) - (PyObject* array = NULL) -{ - npy_intp dims[2] = { $1_dim0, $1_dim1 }; - array = PyArray_SimpleNew(2, dims, DATA_TYPECODE); - if (!array) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(argout) - (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) -{ - $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); -} - -/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) - */ -%typemap(in,numinputs=0, - fragment="NumPy_Backward_Compatibility,NumPy_Macros") - (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) - (PyObject* array = NULL) -{ - npy_intp dims[3] = { $1_dim0, $1_dim1, $1_dim2 }; - array = PyArray_SimpleNew(3, dims, DATA_TYPECODE); - if (!array) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(argout) - (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) -{ - $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); -} - -/* Typemap suite for (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) - */ -%typemap(in,numinputs=0, - fragment="NumPy_Backward_Compatibility,NumPy_Macros") - (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) - (PyObject* array = NULL) -{ - npy_intp dims[4] = { $1_dim0, $1_dim1, $1_dim2, $1_dim3 }; - array = PyArray_SimpleNew(4, dims, DATA_TYPECODE); - if (!array) SWIG_fail; - $1 = ($1_ltype) array_data(array); -} -%typemap(argout) - (DATA_TYPE ARGOUT_ARRAY4[ANY][ANY][ANY][ANY]) -{ - $result = SWIG_Python_AppendOutput($result,(PyObject*)array$argnum); -} - -/*****************************/ -/* Argoutview Array Typemaps */ -/*****************************/ - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim_temp) -{ - $1 = &data_temp; - $2 = &dim_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) -{ - npy_intp dims[1] = { *$2 }; - PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DATA_TYPE** ARGOUTVIEW_ARRAY1) - (DIM_TYPE dim_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim_temp; - $2 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) -{ - npy_intp dims[1] = { *$1 }; - PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$2)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) -{ - npy_intp dims[2] = { *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_ARRAY2) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) -{ - npy_intp dims[2] = { *$1, *$2 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") - (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) -{ - npy_intp dims[2] = { *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_FARRAY2) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) -{ - npy_intp dims[2] = { *$1, *$2 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) -{ - npy_intp dims[3] = { *$2, *$3, *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, - DATA_TYPE** ARGOUTVIEW_ARRAY3) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) -{ - npy_intp dims[3] = { *$1, *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") - (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) -{ - npy_intp dims[3] = { *$2, *$3, *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, - DATA_TYPE** ARGOUTVIEW_FARRAY3) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DATA_TYPE** ARGOUTVIEW_FARRAY3) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) -{ - npy_intp dims[3] = { *$1, *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3, DIM_TYPE* DIM4) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; - $5 = &dim4_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DATA_TYPE** ARGOUTVIEW_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) -{ - npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, - DATA_TYPE** ARGOUTVIEW_ARRAY4) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEW_ARRAY4) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &dim4_temp; - $5 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_ARRAY4) -{ - npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3, DIM_TYPE* DIM4) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; - $5 = &dim4_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") - (DATA_TYPE** ARGOUTVIEW_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) -{ - npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, - DATA_TYPE** ARGOUTVIEW_FARRAY4) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEW_FARRAY4) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &dim4_temp; - $5 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEW_FARRAY4) -{ - npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - $result = SWIG_Python_AppendOutput($result,obj); -} - -/*************************************/ -/* Managed Argoutview Array Typemaps */ -/*************************************/ - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim_temp) -{ - $1 = &data_temp; - $2 = &dim_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_ARRAY1, DIM_TYPE* DIM1) -{ - npy_intp dims[1] = { *$2 }; - PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DATA_TYPE** ARGOUTVIEWM_ARRAY1) - (DIM_TYPE dim_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim_temp; - $2 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEWM_ARRAY1) -{ - npy_intp dims[1] = { *$1 }; - PyObject* obj = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$2)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) -{ - npy_intp dims[2] = { *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEWM_ARRAY2) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_ARRAY2) -{ - npy_intp dims[2] = { *$1, *$2 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) -{ - npy_intp dims[2] = { *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEWM_FARRAY2) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEWM_FARRAY2) -{ - npy_intp dims[2] = { *$1, *$2 }; - PyObject* obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) -{ - npy_intp dims[3] = { *$2, *$3, *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, - DATA_TYPE** ARGOUTVIEWM_ARRAY3) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DATA_TYPE** ARGOUTVIEWM_ARRAY3) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_ARRAY3) -{ - npy_intp dims[3] = { *$1, *$2, *$3 }; - PyObject* obj= PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) -{ - npy_intp dims[3] = { *$2, *$3, *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, - DATA_TYPE** ARGOUTVIEWM_FARRAY3) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DATA_TYPE** ARGOUTVIEWM_FARRAY3) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEWM_FARRAY3) -{ - npy_intp dims[3] = { *$1, *$2, *$3 }; - PyObject* obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$4)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3, DIM_TYPE* DIM4) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; - $5 = &dim4_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) -{ - npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, - DATA_TYPE** ARGOUTVIEWM_ARRAY4) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_ARRAY4) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &dim4_temp; - $5 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) -{ - npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3, DIM_TYPE* DIM4) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; - $5 = &dim4_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) -{ - npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, - DATA_TYPE** ARGOUTVIEWM_FARRAY4) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_FARRAY4) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &dim4_temp; - $5 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) -{ - npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3, DIM_TYPE* DIM4) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; - $5 = &dim4_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_ARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) -{ - npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, - DATA_TYPE** ARGOUTVIEWM_ARRAY4) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_ARRAY4) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &dim4_temp; - $5 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_ARRAY4) -{ - npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, - DIM_TYPE* DIM3, DIM_TYPE* DIM4) - */ -%typemap(in,numinputs=0) - (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 ) - (DATA_TYPE* data_temp = NULL , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp) -{ - $1 = &data_temp; - $2 = &dim1_temp; - $3 = &dim2_temp; - $4 = &dim3_temp; - $5 = &dim4_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DATA_TYPE** ARGOUTVIEWM_FARRAY4, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4) -{ - npy_intp dims[4] = { *$2, *$3, *$4 , *$5 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$1)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, - DATA_TYPE** ARGOUTVIEWM_FARRAY4) - */ -%typemap(in,numinputs=0) - (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DIM_TYPE* DIM3 , DIM_TYPE* DIM4 , DATA_TYPE** ARGOUTVIEWM_FARRAY4) - (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DIM_TYPE dim4_temp, DATA_TYPE* data_temp = NULL ) -{ - $1 = &dim1_temp; - $2 = &dim2_temp; - $3 = &dim3_temp; - $4 = &dim4_temp; - $5 = &data_temp; -} -%typemap(argout, - fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements,NumPy_Utilities") - (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DIM_TYPE* DIM4, DATA_TYPE** ARGOUTVIEWM_FARRAY4) -{ - npy_intp dims[4] = { *$1, *$2, *$3 , *$4 }; - PyObject* obj = PyArray_SimpleNewFromData(4, dims, DATA_TYPECODE, (void*)(*$5)); - PyArrayObject* array = (PyArrayObject*) obj; - - if (!array || !require_fortran(array)) SWIG_fail; - -%#ifdef SWIGPY_USE_CAPSULE - PyObject* cap = PyCapsule_New((void*)(*$1), SWIGPY_CAPSULE_NAME, free_cap); -%#else - PyObject* cap = PyCObject_FromVoidPtr((void*)(*$1), free); -%#endif - -%#if NPY_API_VERSION < 0x00000007 - PyArray_BASE(array) = cap; -%#else - PyArray_SetBaseObject(array,cap); -%#endif - - $result = SWIG_Python_AppendOutput($result,obj); -} - -/**************************************/ -/* In-Place Array Typemap - flattened */ -/**************************************/ - -/* Typemap suite for (DATA_TYPE* INPLACE_ARRAY_FLAT, DIM_TYPE DIM_FLAT) - */ -%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, - fragment="NumPy_Macros") - (DATA_TYPE* INPLACE_ARRAY_FLAT, DIM_TYPE DIM_FLAT) -{ - $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), - DATA_TYPECODE); -} -%typemap(in, - fragment="NumPy_Fragments") - (DATA_TYPE* INPLACE_ARRAY_FLAT, DIM_TYPE DIM_FLAT) - (PyArrayObject* array=NULL, int i=1) -{ - array = obj_to_array_no_conversion($input, DATA_TYPECODE); - if (!array || !require_c_or_f_contiguous(array) - || !require_native(array)) SWIG_fail; - $1 = (DATA_TYPE*) array_data(array); - $2 = 1; - for (i=0; i < array_numdims(array); ++i) $2 *= array_size(array,i); -} - -%enddef /* %numpy_typemaps() macro */ -/* *************************************************************** */ - -/* Concrete instances of the %numpy_typemaps() macro: Each invocation - * below applies all of the typemaps above to the specified data type. - */ -%numpy_typemaps(signed char , NPY_BYTE , int) -%numpy_typemaps(unsigned char , NPY_UBYTE , int) -%numpy_typemaps(short , NPY_SHORT , int) -%numpy_typemaps(unsigned short , NPY_USHORT , int) -%numpy_typemaps(int , NPY_INT , int) -%numpy_typemaps(unsigned int , NPY_UINT , int) -%numpy_typemaps(long , NPY_LONG , int) -%numpy_typemaps(unsigned long , NPY_ULONG , int) -%numpy_typemaps(long long , NPY_LONGLONG , int) -%numpy_typemaps(unsigned long long, NPY_ULONGLONG, int) -%numpy_typemaps(float , NPY_FLOAT , int) -%numpy_typemaps(double , NPY_DOUBLE , int) - -/* *************************************************************** - * The follow macro expansion does not work, because C++ bool is 4 - * bytes and NPY_BOOL is 1 byte - * - * %numpy_typemaps(bool, NPY_BOOL, int) - */ - -/* *************************************************************** - * On my Mac, I get the following warning for this macro expansion: - * 'swig/python detected a memory leak of type 'long double *', no destructor found.' - * - * %numpy_typemaps(long double, NPY_LONGDOUBLE, int) - */ - -#ifdef __cplusplus - -%include - -%numpy_typemaps(std::complex, NPY_CFLOAT , int) -%numpy_typemaps(std::complex, NPY_CDOUBLE, int) - -#endif - -#endif /* SWIGPYTHON */ diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/LICENSE b/pyoptsparse/pyoptsparse/pyNSGA2/LICENSE deleted file mode 100644 index c006b447e..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -NSGA2 - Non Sorting Genetic Algorithm II -Copyright (c) 2005, Kalyanmoy Deb (deb@iitk.ac.in) -Modified for pyOpt - 2008, Ruben E. Perez (Ruben.Perez@rmc.ca) - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -copies of the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following conditions: - -Distribution, sublicense, and/or sell of this code for any commercial -purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNER. - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/README b/pyoptsparse/pyoptsparse/pyNSGA2/README deleted file mode 100644 index cb4bf0129..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the nsga2 class definition -and the nsga2 shared library, _nsga2.so or _nsga2.pyd. diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/__init__.py b/pyoptsparse/pyoptsparse/pyNSGA2/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/pyNSGA2.py b/pyoptsparse/pyoptsparse/pyNSGA2/pyNSGA2.py deleted file mode 100644 index 689c716c2..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/pyNSGA2.py +++ /dev/null @@ -1,220 +0,0 @@ -#/bin/env python -""" -pyNSGA2 - A variation of the pyNSGA2 wrapper specificially designed to -work with sparse optimization problems. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# NSGA2 Library -# ============================================================================= -try: - from . import nsga2 -except ImportError: - nsga2 = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -# ============================================================================= -# NSGA2 Optimizer Class -# ============================================================================= -class NSGA2(Optimizer): - """ - NSGA2 Optimizer Class - Inherited from Optimizer Abstract Class - """ - def __init__(self, *args, **kwargs): - - name = 'NSGA-II' - category = 'Global Optimizer' - defOpts = { - 'PopSize': [int, 100], - 'maxGen': [int, 1000], - 'pCross_real': [float, 0.6], - 'pMut_real': [float, 0.2], - 'eta_c': [float, 10], - 'eta_m': [float, 20], - 'pCross_bin': [float, 0.0], - 'pMut_bin': [float, 0.0], - 'PrintOut': [int, 1], # Flag to Turn On Output to filename (0 - , 1 - , 2 - ) - 'seed': [float, 0], # Random Number Seed (0 - Auto-Seed based on time clock) - 'xinit': [int, 0], # Use Initial Solution Flag (0 - random population, 1 - use given solution) - } - informs = {} - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - if nsga2 is None: - raise Error('There was an error importing the compiled \ - nsga2 module') - - def __call__(self, optProb, storeHistory=None, hotStart=None, **kwargs): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from NSGA2 does not match the history, function and - gradient evaluations revert back to normal evaluations. - - Notes - ----- - The kwargs are there such that the sens= argument can be - supplied (but ignored here in nsga2) - """ - - #====================================================================== - # NSGA-II - Objective/Constraint Values Function - #====================================================================== - def objconfunc(nreal, nobj, ncon, x, f, g): - xx = numpy.array(x) - fobj, fcon, fail = self._masterFunc(xx, ['fobj','fcon']) - fobj = numpy.atleast_1d(fobj) - f[0:nobj] = fobj - g[0:ncon] = -fcon[0:ncon] - - return f, g - - self.callCounter = 0 - - if len(optProb.constraints) == 0: - # If the user *actually* has an unconstrained problem, - # slsqp sort of chokes with that....it has to have at - # least one constraint. So we will add one - # automatically here: - self.unconstrained = True - optProb.dummyConstraint = False - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - - blx, bux, xs = self._assembleContinuousVariables() - xs = numpy.maximum(xs, blx) - xs = numpy.minimum(xs, bux) - n = len(xs) - ff = self._assembleObjective() - oneSided = True - - # Set the number of nonlinear constraints snopt *thinks* we have: - if self.unconstrained: - m = 0 - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'le', 'ni', 'li'], oneSided=oneSided, noEquality=True) - m = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - g = nsga2.new_doubleArray(m) - l = len(numpy.atleast_1d(ff)) - f = nsga2.new_doubleArray(l) - - if self.optProb.comm.rank == 0: - # Set history/hotstart - self._setHistory(storeHistory, hotStart) - - # Variables Handling - n = len(xs) - x = nsga2.new_doubleArray(n) - xl = nsga2.new_doubleArray(n) - xu = nsga2.new_doubleArray(n) - for i in range(n): - nsga2.doubleArray_setitem(x, i, xs[i]) - nsga2.doubleArray_setitem(xl, i, blx[i]) - nsga2.doubleArray_setitem(xu, i, bux[i]) - - # Setup argument list values - nfeval = 0 - opt = self.getOption - - if self.getOption('PrintOut') >=0 and self.getOption('PrintOut') <= 2: - printout = self.getOption('PrintOut') - else: - raise Error('Incorrect option PrintOut') - - seed = self.getOption('seed') - if seed == 0: - seed = time.time() - - # Run NSGA-II - nsga2.set_pyfunc(objconfunc) - t0 = time.time() - nsga2.nsga2(n, m, l, f, x, g, nfeval, xl, xu, opt('PopSize'), opt('maxGen'), - opt('pCross_real'), opt('pMut_real'), opt('eta_c'), opt('eta_m'), - opt('pCross_bin'), opt('pMut_bin'), printout,seed, opt('xinit')) - optTime = time.time() - t0 - - # Broadcast a -1 to indcate NSGA2 has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - #sol_inform['value'] = inform - #sol_inform['text'] = self.informs[inform[0]] - - xstar = [0.]*n - for i in range(n): - xstar[i] = nsga2.doubleArray_getitem(x,i) - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xstar) - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name, value): - pass diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/setup.py b/pyoptsparse/pyoptsparse/pyNSGA2/setup.py deleted file mode 100644 index 2376dc824..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/setup.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env python - -import os,sys - -from numpy.distutils.command import build_src -from numpy.distutils.misc_util import appendpath -from numpy.distutils.command.build_src import get_swig_modulename, get_swig_target -from distutils.dep_util import newer_group -from numpy.distutils import log - -#numpy/distutils/command/build_src.py -#584 if name != ext_name: -#587 ' but expected %r' % (source, name, ext_name)) -#608 name = ext_name -#624 #py_files.append(os.path.join(py_target_dir, name+'.py')) -#640 swig_cmd = [swig, "-python", "-noproxy"] - -def swig_sources(self, sources, extension): - # Assuming SWIG 1.3.14 or later. See compatibility note in - # http://www.swig.org/Doc1.3/Python.html#Python_nn6 - - new_sources = [] - swig_sources = [] - swig_targets = {} - target_dirs = [] - py_files = [] # swig generated .py files - target_ext = '.c' - if self.swig_cpp: - typ = 'c++' - is_cpp = True - else: - typ = None - is_cpp = False - skip_swig = 0 - ext_name = extension.name.split('.')[-1] - - for source in sources: - (base, ext) = os.path.splitext(source) - if ext == '.i': # SWIG interface file - if self.inplace: - target_dir = os.path.dirname(base) - py_target_dir = self.ext_target_dir - else: - target_dir = appendpath(self.build_src, os.path.dirname(base)) - py_target_dir = target_dir - if os.path.isfile(source): - name = get_swig_modulename(source) -# if name != ext_name: -# raise DistutilsSetupError( -# 'mismatch of extension names: %s provides %r' -# ' but expected %r' % (source, name, ext_name)) - if typ is None: - typ = get_swig_target(source) - is_cpp = typ=='c++' - if is_cpp: target_ext = '.cpp' - else: - typ2 = get_swig_target(source) - if typ!=typ2: - log.warn('expected %r but source %r defines %r swig target' \ - % (typ, source, typ2)) - if typ2=='c++': - log.warn('resetting swig target to c++ (some targets may have .c extension)') - is_cpp = True - target_ext = '.cpp' - else: - log.warn('assuming that %r has c++ swig target' % (source)) - target_file = os.path.join(target_dir,'%s_wrap%s' \ - % (name, target_ext)) - else: - log.warn(' source %s does not exist: skipping swig\'ing.' \ - % (source)) - name = ext_name - skip_swig = 1 - target_file = _find_swig_target(target_dir, name) - if not os.path.isfile(target_file): - log.warn(' target %s does not exist:\n '\ - 'Assuming %s_wrap.{c,cpp} was generated with '\ - '"build_src --inplace" command.' \ - % (target_file, name)) - target_dir = os.path.dirname(base) - target_file = _find_swig_target(target_dir, name) - if not os.path.isfile(target_file): - raise DistutilsSetupError("%r missing" % (target_file,)) - log.warn(' Yes! Using %r as up-to-date target.' \ - % (target_file)) - target_dirs.append(target_dir) - new_sources.append(target_file) - #py_files.append(os.path.join(py_target_dir, name+'.py')) - swig_sources.append(source) - swig_targets[source] = new_sources[-1] - else: - new_sources.append(source) - - if not swig_sources: - return new_sources - - if skip_swig: - return new_sources + py_files - - for d in target_dirs: - self.mkpath(d) - - swig = self.swig or self.find_swig() - swig_cmd = [swig, "-python"] + extension.swig_opts - if is_cpp: - swig_cmd.append('-c++') - for d in extension.include_dirs: - swig_cmd.append('-I'+d) - for source in swig_sources: - target = swig_targets[source] - depends = [source] + extension.depends - if self.force or newer_group(depends, target, 'newer'): - log.info("%s: %s" % (os.path.basename(swig) \ - + (is_cpp and '++' or ''), source)) - self.spawn(swig_cmd + self.swig_opts \ - + ["-o", target, '-outdir', py_target_dir, source]) - else: - log.debug(" skipping '%s' swig interface (up-to-date)" \ - % (source)) - - return new_sources + py_files - -build_src.build_src.swig_sources = swig_sources - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyNSGA2',parent_package,top_path) - - # platform-specific settings - extra_link_args = [] - if sys.platform == "darwin": - extra_link_args.append("-bundle") - #end - - config.add_library('nsga2', - sources=[os.path.join('source', '*.c')]) - config.add_extension('nsga2', - sources=['source/swig/nsga2.i'], - include_dirs=['source'], - libraries=['nsga2'], - extra_link_args=extra_link_args, - swig_opts=['-noproxy']) - config.add_data_files('LICENSE','README') - - return config diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/README b/pyoptsparse/pyoptsparse/pyNSGA2/source/README deleted file mode 100644 index f28d26bcb..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/README +++ /dev/null @@ -1,4 +0,0 @@ -This directory contains the C source for -NSGA2, the main routine of the original -program has been modified to enable Python -interfacing by Dr. Ruben E. Perez. diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/allocate.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/allocate.c deleted file mode 100644 index 271d9069d..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/allocate.c +++ /dev/null @@ -1,82 +0,0 @@ -/* Memory allocation and deallocation routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to allocate memory to a population */ -void allocate_memory_pop (population *pop, int size, Global global) -{ - int i; - pop->ind = (individual *)malloc(size*sizeof(individual)); - for (i=0; iind[i]), global); - } - return; -} - -/* Function to allocate memory to an individual */ -void allocate_memory_ind (individual *ind, Global global) -{ - int j; - if (global.nreal != 0) - { - ind->xreal = (double *)malloc(global.nreal*sizeof(double)); - } - if (global.nbin != 0) - { - ind->xbin = (double *)malloc(global.nbin*sizeof(double)); - ind->gene = (int **)malloc(global.nbin*sizeof(int)); - for (j=0; jgene[j] = (int *)malloc(global.nbits[j]*sizeof(int)); - } - } - ind->obj = (double *)malloc(global.nobj*sizeof(double)); - if (global.ncon != 0) - { - ind->constr = (double *)malloc(global.ncon*sizeof(double)); - } - return; -} - -/* Function to deallocate memory to a population */ -void deallocate_memory_pop (population *pop, int size, Global global) -{ - int i; - for (i=0; iind[i]), global); - } - free (pop->ind); - return; -} - -/* Function to deallocate memory to an individual */ -void deallocate_memory_ind (individual *ind, Global global) -{ - int j; - if (global.nreal != 0) - { - free(ind->xreal); - } - if (global.nbin != 0) - { - for (j=0; jgene[j]); - } - free(ind->xbin); - free(ind->gene); - } - free(ind->obj); - if (global.ncon != 0) - { - free(ind->constr); - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/auxiliary.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/auxiliary.c deleted file mode 100644 index 71d75dab2..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/auxiliary.c +++ /dev/null @@ -1,28 +0,0 @@ -/* Some utility functions (not part of the algorithm) */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to return the maximum of two variables */ -double maximum (double a, double b) -{ - if (a>b) - { - return(a); - } - return (b); -} - -/* Function to return the minimum of two variables */ -double minimum (double a, double b) -{ - if (a -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to cross two individuals */ -void crossover (individual *parent1, individual *parent2, individual *child1, individual *child2, Global global, int *nrealcross, int *nbincross) -{ - if (global.nreal!=0) - { - realcross (parent1, parent2, child1, child2, global, nrealcross); - } - if (global.nbin!=0) - { - bincross (parent1, parent2, child1, child2, global, nbincross); - } - return; -} - -/* Routine for real variable SBX crossover */ -void realcross (individual *parent1, individual *parent2, individual *child1, individual *child2, Global global, int *nrealcross) -{ - int i; - double rand; - double y1, y2, yl, yu; - double c1, c2; - double alpha, beta, betaq; - if (randomperc() <= global.pcross_real) - { - nrealcross++; - for (i=0; ixreal[i]-parent2->xreal[i]) > EPS) - { - if (parent1->xreal[i] < parent2->xreal[i]) - { - y1 = parent1->xreal[i]; - y2 = parent2->xreal[i]; - } - else - { - y1 = parent2->xreal[i]; - y2 = parent1->xreal[i]; - } - yl = global.min_realvar[i]; - yu = global.max_realvar[i]; - rand = randomperc(); - beta = 1.0 + (2.0*(y1-yl)/(y2-y1)); - alpha = 2.0 - pow(beta,-(global.eta_c+1.0)); - if (rand <= (1.0/alpha)) - { - betaq = pow ((rand*alpha),(1.0/(global.eta_c+1.0))); - } - else - { - betaq = pow ((1.0/(2.0 - rand*alpha)),(1.0/(global.eta_c+1.0))); - } - c1 = 0.5*((y1+y2)-betaq*(y2-y1)); - beta = 1.0 + (2.0*(yu-y2)/(y2-y1)); - alpha = 2.0 - pow(beta,-(global.eta_c+1.0)); - if (rand <= (1.0/alpha)) - { - betaq = pow ((rand*alpha),(1.0/(global.eta_c+1.0))); - } - else - { - betaq = pow ((1.0/(2.0 - rand*alpha)),(1.0/(global.eta_c+1.0))); - } - c2 = 0.5*((y1+y2)+betaq*(y2-y1)); - if (c1yu) - c1=yu; - if (c2>yu) - c2=yu; - if (randomperc()<=0.5) - { - child1->xreal[i] = c2; - child2->xreal[i] = c1; - } - else - { - child1->xreal[i] = c1; - child2->xreal[i] = c2; - } - } - else - { - child1->xreal[i] = parent1->xreal[i]; - child2->xreal[i] = parent2->xreal[i]; - } - } - else - { - child1->xreal[i] = parent1->xreal[i]; - child2->xreal[i] = parent2->xreal[i]; - } - } - } - else - { - for (i=0; ixreal[i] = parent1->xreal[i]; - child2->xreal[i] = parent2->xreal[i]; - } - } - return; -} - -/* Routine for two point binary crossover */ -void bincross (individual *parent1, individual *parent2, individual *child1, individual *child2, Global global, int *nbincross) -{ - int i, j; - double rand; - int temp, site1, site2; - for (i=0; i site2) - { - temp = site1; - site1 = site2; - site2 = temp; - } - for (j=0; jgene[i][j] = parent1->gene[i][j]; - child2->gene[i][j] = parent2->gene[i][j]; - } - for (j=site1; jgene[i][j] = parent2->gene[i][j]; - child2->gene[i][j] = parent1->gene[i][j]; - } - for (j=site2; jgene[i][j] = parent1->gene[i][j]; - child2->gene[i][j] = parent2->gene[i][j]; - } - } - else - { - for (j=0; jgene[i][j] = parent1->gene[i][j]; - child2->gene[i][j] = parent2->gene[i][j]; - } - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/crowddist.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/crowddist.c deleted file mode 100644 index 4b33b4cc1..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/crowddist.c +++ /dev/null @@ -1,134 +0,0 @@ -/* Crowding distance computation routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Routine to compute crowding distance based on ojbective function values when the population in in the form of a list */ -void assign_crowding_distance_list (population *pop, list *lst, int front_size, Global global) -{ - int **obj_array; - int *dist; - int i, j; - list *temp; - temp = lst; - if (front_size==1) - { - pop->ind[lst->index].crowd_dist = INF; - return; - } - if (front_size==2) - { - pop->ind[lst->index].crowd_dist = INF; - pop->ind[lst->child->index].crowd_dist = INF; - return; - } - obj_array = (int **)malloc(global.nobj*sizeof(int)); - dist = (int *)malloc(front_size*sizeof(int)); - for (i=0; iindex; - temp = temp->child; - } - assign_crowding_distance (pop, dist, obj_array, front_size, global); - free (dist); - for (i=0; iind[c1].crowd_dist = INF; - return; - } - if (front_size==2) - { - pop->ind[c1].crowd_dist = INF; - pop->ind[c2].crowd_dist = INF; - return; - } - obj_array = (int **)malloc(global.nobj*sizeof(int)); - dist = (int *)malloc(front_size*sizeof(int)); - for (i=0; iind[dist[j]].crowd_dist = 0.0; - } - for (i=0; iind[obj_array[i][0]].crowd_dist = INF; - } - for (i=0; iind[obj_array[i][j]].crowd_dist != INF) - { - if (pop->ind[obj_array[i][front_size-1]].obj[i] == pop->ind[obj_array[i][0]].obj[i]) - { - pop->ind[obj_array[i][j]].crowd_dist += 0.0; - } - else - { - pop->ind[obj_array[i][j]].crowd_dist += (pop->ind[obj_array[i][j+1]].obj[i] - pop->ind[obj_array[i][j-1]].obj[i])/(pop->ind[obj_array[i][front_size-1]].obj[i] - pop->ind[obj_array[i][0]].obj[i]); - } - } - } - } - for (j=0; jind[dist[j]].crowd_dist != INF) - { - pop->ind[dist[j]].crowd_dist = (pop->ind[dist[j]].crowd_dist)/global.nobj; - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/decode.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/decode.c deleted file mode 100644 index c48714d8b..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/decode.c +++ /dev/null @@ -1,45 +0,0 @@ -/* Routines to decode the population */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to decode a population to find out the binary variable values based on its bit pattern */ -void decode_pop (population *pop, Global global) -{ - int i; - if (global.nbin!=0) - { - for (i=0; iind[i]),global); - } - } - return; -} - -/* Function to decode an individual to find out the binary variable values based on its bit pattern */ -void decode_ind (individual *ind, Global global) -{ - int j, k; - int sum; - if (global.nbin!=0) - { - for (j=0; jgene[j][k]==1) - { - sum += pow(2,global.nbits[j]-1-k); - } - } - ind->xbin[j] = global.min_binvar[j] + (double)sum*(global.max_binvar[j] - global.min_binvar[j])/(double)(pow(2,global.nbits[j])-1); - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/dominance.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/dominance.c deleted file mode 100644 index f1f7e39ef..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/dominance.c +++ /dev/null @@ -1,88 +0,0 @@ -/* Domination checking routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Routine for usual non-domination checking - It will return the following values - 1 if a dominates b - -1 if b dominates a - 0 if both a and b are non-dominated */ - -int check_dominance (individual *a, individual *b, Global global) -{ - int i; - int flag1; - int flag2; - flag1 = 0; - flag2 = 0; - if (a->constr_violation<0 && b->constr_violation<0) - { - if (a->constr_violation > b->constr_violation) - { - return (1); - } - else - { - if (a->constr_violation < b->constr_violation) - { - return (-1); - } - else - { - return (0); - } - } - } - else - { - if (a->constr_violation < 0 && b->constr_violation == 0) - { - return (-1); - } - else - { - if (a->constr_violation == 0 && b->constr_violation <0) - { - return (1); - } - else - { - for (i=0; iobj[i] < b->obj[i]) - { - flag1 = 1; - - } - else - { - if (a->obj[i] > b->obj[i]) - { - flag2 = 1; - } - } - } - if (flag1==1 && flag2==0) - { - return (1); - } - else - { - if (flag1==0 && flag2==1) - { - return (-1); - } - else - { - return (0); - } - } - } - } - } -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/eval.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/eval.c deleted file mode 100644 index fd32f2a1a..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/eval.c +++ /dev/null @@ -1,42 +0,0 @@ -/* Routine for evaluating population members */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Routine to evaluate objective function values and constraints for a population */ -void evaluate_pop (population *pop, Global global) -{ - int i; - for (i=0; iind[i]),global); - } - return; -} - -/* Routine to evaluate objective function values and constraints for an individual */ -void evaluate_ind (individual *ind, Global global) -{ - int j; - nsga2func (global.nreal, global.nbin, global.nobj, global.ncon, ind->xreal, ind->xbin, ind->gene, ind->obj, ind->constr); - if (global.ncon==0) - { - ind->constr_violation = 0.0; - } - else - { - ind->constr_violation = 0.0; - for (j=0; jconstr[j]<0.0) - { - ind->constr_violation += ind->constr[j]; - } - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/fillnds.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/fillnds.c deleted file mode 100644 index b80d5c3c9..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/fillnds.c +++ /dev/null @@ -1,154 +0,0 @@ -/* Nond-domination based selection routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Routine to perform non-dominated sorting */ -void fill_nondominated_sort (population *mixed_pop, population *new_pop, Global global) -{ - int flag; - int i, j; - int end; - int front_size; - int archieve_size; - int rank=1; - list *pool; - list *elite; - list *temp1, *temp2; - pool = (list *)malloc(sizeof(list)); - elite = (list *)malloc(sizeof(list)); - front_size = 0; - archieve_size=0; - pool->index = -1; - pool->parent = NULL; - pool->child = NULL; - elite->index = -1; - elite->parent = NULL; - elite->child = NULL; - temp1 = pool; - for (i=0; i<2*global.popsize; i++) - { - insert (temp1,i); - temp1 = temp1->child; - } - i=0; - do - { - temp1 = pool->child; - insert (elite, temp1->index); - front_size = 1; - temp2 = elite->child; - temp1 = delnode (temp1); - temp1 = temp1->child; - do - { - temp2 = elite->child; - if (temp1==NULL) - { - break; - } - do - { - end = 0; - flag = check_dominance (&(mixed_pop->ind[temp1->index]), &(mixed_pop->ind[temp2->index]), global); - if (flag == 1) - { - insert (pool, temp2->index); - temp2 = delnode (temp2); - front_size--; - temp2 = temp2->child; - } - if (flag == 0) - { - temp2 = temp2->child; - } - if (flag == -1) - { - end = 1; - } - } - while (end!=1 && temp2!=NULL); - if (flag == 0 || flag == 1) - { - insert (elite, temp1->index); - front_size++; - temp1 = delnode (temp1); - } - temp1 = temp1->child; - } - while (temp1 != NULL); - temp2 = elite->child; - j=i; - if ( (archieve_size+front_size) <= global.popsize) - { - do - { - copy_ind (&mixed_pop->ind[temp2->index], &new_pop->ind[i], global); - new_pop->ind[i].rank = rank; - archieve_size+=1; - temp2 = temp2->child; - i+=1; - } - while (temp2 != NULL); - assign_crowding_distance_indices (new_pop, j, i-1, global); - rank+=1; - } - else - { - crowding_fill (mixed_pop, new_pop, i, front_size, elite, global); - archieve_size = global.popsize; - for (j=i; jind[j].rank = rank; - } - } - temp2 = elite->child; - do - { - temp2 = delnode (temp2); - temp2 = temp2->child; - } - while (elite->child !=NULL); - } - while (archieve_size < global.popsize); - while (pool!=NULL) - { - temp1 = pool; - pool = pool->child; - free (temp1); - } - while (elite!=NULL) - { - temp1 = elite; - elite = elite->child; - free (temp1); - } - return; -} - -/* Routine to fill a population with individuals in the decreasing order of crowding distance */ -void crowding_fill (population *mixed_pop, population *new_pop, int count, int front_size, list *elite, Global global) -{ - int *dist; - list *temp; - int i, j; - assign_crowding_distance_list (mixed_pop, elite->child, front_size, global); - dist = (int *)malloc(front_size*sizeof(int)); - temp = elite->child; - for (j=0; jindex; - temp = temp->child; - } - quicksort_dist (mixed_pop, dist, front_size); - for (i=count, j=front_size-1; iind[dist[j]], &new_pop->ind[i], global); - } - free (dist); - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/initialize.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/initialize.c deleted file mode 100644 index c80d480b6..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/initialize.c +++ /dev/null @@ -1,50 +0,0 @@ -/* Data initializtion routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to initialize a population randomly */ -void initialize_pop (population *pop, Global global) -{ - int i; - for (i=0; iind[i]),global); - } - return; -} - -/* Function to initialize an individual randomly */ -void initialize_ind (individual *ind, Global global) -{ - int j, k; - if (global.nreal!=0) - { - for (j=0; jxreal[j] = rndreal (global.min_realvar[j], global.max_realvar[j]); - } - } - if (global.nbin!=0) - { - for (j=0; jgene[j][k] = 0; - } - else - { - ind->gene[j][k] = 1; - } - } - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/list.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/list.c deleted file mode 100644 index f998a6292..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/list.c +++ /dev/null @@ -1,48 +0,0 @@ -/* A custom doubly linked list implemenation */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Insert an element X into the list at location specified by NODE */ -void insert (list *node, int x) -{ - list *temp; - if (node==NULL) - { - printf("\n Error!! asked to enter after a NULL pointer, hence exiting \n"); - exit(1); - } - temp = (list *)malloc(sizeof(list)); - temp->index = x; - temp->child = node->child; - temp->parent = node; - if (node->child != NULL) - { - node->child->parent = temp; - } - node->child = temp; - return; -} - -/* Delete the node NODE from the list */ -list* delnode (list *node) -{ - list *temp; - if (node==NULL) - { - printf("\n Error!! asked to delete a NULL pointer, hence exiting \n"); - exit(1); - } - temp = node->parent; - temp->child = node->child; - if (temp->child!=NULL) - { - temp->child->parent = temp; - } - free (node); - return (temp); -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/merge.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/merge.c deleted file mode 100644 index 221e6be35..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/merge.c +++ /dev/null @@ -1,62 +0,0 @@ -/* Routine for mergeing two populations */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Routine to merge two populations into one */ -void merge(population *pop1, population *pop2, population *pop3, Global global) -{ - int i, k; - for (i=0; iind[i]), &(pop3->ind[i]), global); - } - for (i=0, k=global.popsize; iind[i]), &(pop3->ind[k]), global); - } - return; -} - -/* Routine to copy an individual 'ind1' into another individual 'ind2' */ -void copy_ind (individual *ind1, individual *ind2, Global global) -{ - int i, j; - ind2->rank = ind1->rank; - ind2->constr_violation = ind1->constr_violation; - ind2->crowd_dist = ind1->crowd_dist; - if (global.nreal!=0) - { - for (i=0; ixreal[i] = ind1->xreal[i]; - } - } - if (global.nbin!=0) - { - for (i=0; ixbin[i] = ind1->xbin[i]; - for (j=0; jgene[i][j] = ind1->gene[i][j]; - } - } - } - for (i=0; iobj[i] = ind1->obj[i]; - } - if (global.ncon!=0) - { - for (i=0; iconstr[i] = ind1->constr[i]; - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/mutation.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/mutation.c deleted file mode 100644 index dbfbf2c77..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/mutation.c +++ /dev/null @@ -1,101 +0,0 @@ -/* Mutation routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to perform mutation in a population */ -void mutation_pop (population *pop, Global global,int *nrealmut,int *nbinmut) -{ - int i; - for (i=0; iind[i]),global,nrealmut,nbinmut); - } - return; -} - -/* Function to perform mutation of an individual */ -void mutation_ind (individual *ind, Global global,int *nrealmut,int *nbinmut) -{ - if (global.nreal!=0) - { - real_mutate_ind(ind, global, nrealmut); - } - if (global.nbin!=0) - { - bin_mutate_ind(ind, global, nbinmut); - } - return; -} - -/* Routine for binary mutation of an individual */ -void bin_mutate_ind (individual *ind, Global global,int *nbinmut) -{ - int j, k; - double prob; - for (j=0; jgene[j][k] == 0) - { - ind->gene[j][k] = 1; - } - else - { - ind->gene[j][k] = 0; - } - nbinmut+=1; - } - } - } - return; -} - -/* Routine for real polynomial mutation of an individual */ -void real_mutate_ind (individual *ind, Global global,int *nrealmut) -{ - int j; - double rnd, delta1, delta2, mut_pow, deltaq; - double y, yl, yu, val, xy; - for (j=0; jxreal[j]; - yl = global.min_realvar[j]; - yu = global.max_realvar[j]; - delta1 = (y-yl)/(yu-yl); - delta2 = (yu-y)/(yu-yl); - rnd = randomperc(); - mut_pow = 1.0/(global.eta_m+1.0); - if (rnd <= 0.5) - { - xy = 1.0-delta1; - val = 2.0*rnd+(1.0-2.0*rnd)*(pow(xy,(global.eta_m+1.0))); - deltaq = pow(val,mut_pow) - 1.0; - } - else - { - xy = 1.0-delta2; - val = 2.0*(1.0-rnd)+2.0*(rnd-0.5)*(pow(xy,(global.eta_m+1.0))); - deltaq = 1.0 - (pow(val,mut_pow)); - } - y = y + deltaq*(yu-yl); - if (yyu) - y = yu; - ind->xreal[j] = y; - nrealmut+=1; - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/nsga2.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/nsga2.c deleted file mode 100644 index cf886e6a3..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/nsga2.c +++ /dev/null @@ -1,396 +0,0 @@ -/* ------------------------------------------------------------------------------- - * - * NSGA-II (Non-dominated Sorting Genetic Algorithm - II) - * - * current version only works with continous design variables treated as reals - * no provisions for binary specification or integer/discrete variable handling - * - * nvar - number of variables - * ncon - number of constraints - * nobj - number of objectives - * f - - * x - - * g - - * nfeval - - * xl - - * xu - - * popsize - population size (a multiple of 4) - * ngen - number of generations - * pcross_real - probability of crossover of real variable (0.6-1.0) - * pmut_real - probablity of mutation of real variables (1/nreal) - * eta_c - distribution index for crossover (5-20) must be > 0 - * eta_m - distribution index for mutation (5-50) must be > 0 - * pcross_bin - probability of crossover of binary variable (0.6-1.0) - * pmut_bin - probability of mutation of binary variables (1/nbits) - * seed - seed value must be in (0,1) - * - * - * Output files - * - * - initial_pop.out: contains initial population data - * - final_pop.out: contains final population data - * - all_pop.out: containts generation population data - * - best_pop.out: contains best solutions - * - params.out: contains input parameters information - * - .out: contains runtime information - * - * ---------------------------------------------------------------------------- - * - * References: - * ----------- - * - * - Deb K., Agrawal S., Pratap A., and Meyarivan T., A Fast and Elitist - * multi-objective Genetic Algorithm: NSGA-II, IEEE Transactions on - * Evolutionary Computation (IEEE-TEC), 2002, Vol. 6, No. 2, pp 182-197 - * - * ---------------------------------------------------------------------------- - * - * Usage: - * ------ - * - * - * ---------------------------------------------------------------------------- - * - * Copyrights: - * ----------- - * - * - Original NSGA-II implementation: (C) Dr. Kalyanmoy Deb 2005 - * - Randon Number Generator: (C) Dr. David E. Goldberg 1986 - * - * ----------------------------------------------------------------------------*/ - - -/* ------------------------------------------------------------------------------- - * includefiles - * ---------------------------------------------------------------------------- */ -# include "nsga2.h" - - -/* ------------------------------------------------------------------------------- - * NSGA2 - * ---------------------------------------------------------------------------- */ -int nsga2(int nvar, int ncon, int nobj, double f[], double x[], double g[], - int nfeval, double xl[], double xu[], int popsize, int ngen, - double pcross_real, double pmut_real, double eta_c, double eta_m, - double pcross_bin, double pmut_bin, int printout, double seed, int xinit) -{ - /* declaration of local variables and structures */ - int i, j; - int nreal, nbin, *nbits, bitlength; - double *min_realvar, *max_realvar; - double *min_binvar, *max_binvar; - int *nbinmut, *nrealmut, *nbincross, *nrealcross; - - Global global; - - population *parent_pop; - population *child_pop; - population *mixed_pop; - - // "random" numbers seed - if (seed==0) - { - // use of clock to generate "random" seed - time_t seconds; - seconds=time(NULL); - seed=seconds; - } - - // Files - FILE *fpt1; - FILE *fpt2; - FILE *fpt3; - FILE *fpt4; - FILE *fpt5; - FILE *fpt6; - if (printout >= 1) - { - fpt1 = fopen("nsga2_initial_pop.out","w"); - fpt2 = fopen("nsga2_final_pop.out","w"); - fpt3 = fopen("nsga2_best_pop.out","w"); - if (printout == 2) - { - fpt4 = fopen("nsga2_all_pop.out","w"); - } - fpt5 = fopen("nsga2_params.out","w"); - fpt6 = fopen("nsga2_run.out","w"); - fprintf(fpt1,"# This file contains the data of initial population\n"); - fprintf(fpt2,"# This file contains the data of final population\n"); - fprintf(fpt3,"# This file contains the data of final feasible population (if found)\n"); - if (printout == 2) - { - fprintf(fpt4,"# This file contains the data of all generations\n"); - } - fprintf(fpt5,"# This file contains information about inputs as read by the program\n"); - fprintf(fpt6,"# This file contains runtime information\n"); - } - - // Input Handling - nreal = nvar; // number of real variables - nbin = 0; // number of binary variables - - min_realvar = (double *)malloc(nreal*sizeof(double)); - max_realvar = (double *)malloc(nreal*sizeof(double)); - - j = 0; - for (i=0; i= 1) - { - fprintf(fpt5,"\n Population size = %d",popsize); - fprintf(fpt5,"\n Number of generations = %d",ngen); - fprintf(fpt5,"\n Number of objective functions = %d",nobj); - fprintf(fpt5,"\n Number of constraints = %d",ncon); - fprintf(fpt5,"\n Number of variables = %d",nvar); - fprintf(fpt5,"\n Number of real variables = %d",nreal); - if (nreal!=0) - { - for (i=0; iind[i].xreal[j] = x[j]; - } - } - - // First Generation - if (printout >= 1) - { - fprintf(fpt6,"\n\n Initialization done, now performing first generation"); - } - decode_pop(parent_pop, global); - evaluate_pop(parent_pop, global); - assign_rank_and_crowding_distance (parent_pop, global); - if (printout >= 1) - { - report_pop (parent_pop, fpt1, global); - if (printout == 2) - { - fprintf(fpt4,"# gen = 1\n"); - report_pop(parent_pop,fpt4, global); - } - - fprintf(fpt6,"\n gen = 1"); - - fflush(fpt1); - fflush(fpt2); - fflush(fpt3); - if (printout == 2) - { - fflush(fpt4); - } - fflush(fpt5); - fflush(fpt6); - } - fflush(stdout); - - // Iterate Generations - for (i=2; i<=ngen; i++) - { - selection(parent_pop, child_pop, global, nrealcross, nbincross); - mutation_pop(child_pop, global, nrealmut, nbinmut); - decode_pop(child_pop, global); - evaluate_pop(child_pop, global); - merge (parent_pop, child_pop, mixed_pop, global); - fill_nondominated_sort (mixed_pop, parent_pop, global); - - /* Comment following three lines if information for all - generations is not desired, it will speed up the execution */ - if (printout >= 1) - { - if (printout == 2) - { - fprintf(fpt4,"# gen = %i\n",i); - report_pop(parent_pop,fpt4, global); - fflush(fpt4); - } - fprintf(fpt6,"\n gen = %i",i); - fflush(fpt6); - } - } - - // Output - if (printout >= 1) - { - fprintf(fpt6,"\n Generations finished"); - report_pop(parent_pop,fpt2, global); - report_feasible(parent_pop,fpt3, global); - - if (nreal!=0) - { - fprintf(fpt5,"\n Number of crossover of real variable = %i",nrealcross); - fprintf(fpt5,"\n Number of mutation of real variable = %i",nrealmut); - } - if (nbin!=0) - { - fprintf(fpt5,"\n Number of crossover of binary variable = %i",nbincross); - fprintf(fpt5,"\n Number of mutation of binary variable = %i",nbinmut); - } - fflush(stdout); - fflush(fpt1); - fflush(fpt2); - fflush(fpt3); - if (printout == 2) - { - fflush(fpt4); - } - fflush(fpt5); - fflush(fpt6); - fclose(fpt1); - fclose(fpt2); - fclose(fpt3); - if (printout == 2) - { - fclose(fpt4); - } - fclose(fpt5); - - } - - // - for (i=0; iind[i].constr_violation == 0.0 && parent_pop->ind[i].rank==1) - { - for (j=0; jind[i].obj[j]; - } - if (ncon!=0) - { - for (j=0; jind[i].constr[j]; - } - } - if (nreal!=0) - { - for (j=0; jind[i].xreal[j]; - } - } - break; - } - } - - // - if (nreal!=0) - { - free (min_realvar); - free (max_realvar); - } - if (nbin!=0) - { - free (min_binvar); - free (max_binvar); - free (nbits); - } - deallocate_memory_pop (parent_pop, popsize, global); - deallocate_memory_pop (child_pop, popsize, global); - deallocate_memory_pop (mixed_pop, 2*popsize, global); - free (parent_pop); - free (child_pop); - free (mixed_pop); - - // - if (printout >= 1) - { - fprintf(fpt6,"\n Routine successfully exited \n"); - fflush(fpt6); - fclose(fpt6); - } - - return (0); -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/nsga2.h b/pyoptsparse/pyoptsparse/pyNSGA2/source/nsga2.h deleted file mode 100644 index 3ed100b96..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/nsga2.h +++ /dev/null @@ -1,146 +0,0 @@ -/* ------------------------------------------------------------------------------- - * - * Header File for nsga2.c - * - * ---------------------------------------------------------------------------- */ - -# ifndef _GLOBAL_H_ -# define _GLOBAL_H_ - -# define INF 1.0e14 -# define EPS 1.0e-14 -# define E 2.71828182845905 -# define PI 3.14159265358979 - -/* ------------------------------------------------------------------------------- - * Includes - * ---------------------------------------------------------------------------- */ -# include -# include -# include -# include - -# include "rand.h" - -/* ------------------------------------------------------------------------------- - * Structures - * ---------------------------------------------------------------------------- */ -typedef struct -{ - int rank; - double constr_violation; - double *xreal; - int **gene; - double *xbin; - double *obj; - double *constr; - double crowd_dist; -} -individual; - -typedef struct -{ - individual *ind; -} -population; - -typedef struct lists -{ - int index; - struct lists *parent; - struct lists *child; -} -list; - -typedef struct -{ - int nreal; - int nbin; - int nobj; - int ncon; - int popsize; - double pcross_real; - double pcross_bin; - double pmut_real; - double pmut_bin; - double eta_c; - double eta_m; - int ngen; - int nbinmut; - int nrealmut; - int nbincross; - int nrealcross; - int *nbits; - double *min_realvar; - double *max_realvar; - double *min_binvar; - double *max_binvar; - int bitlength; -} -Global; - - - -/* ------------------------------------------------------------------------------- - * Headers - * ---------------------------------------------------------------------------- */ -int nsga2(int nvar, int ncon, int nobj, double f[], double x[], double g[], int nfeval, double xl[], double xu[], int popsize, int ngen, double pcross_real, double pmut_real, double eta_c, double eta_m, double pcross_bin, double pmut_bin, int printout, double seed, int xinit); - -void allocate_memory_pop (population *pop, int size, Global global); -void allocate_memory_ind (individual *ind, Global global); -void deallocate_memory_pop (population *pop, int size, Global global); -void deallocate_memory_ind (individual *ind, Global global); - -double maximum (double a, double b); -double minimum (double a, double b); - -void crossover (individual *parent1, individual *parent2, individual *child1, individual *child2, Global global, int *nrealcross, int *nbincross); -void realcross (individual *parent1, individual *parent2, individual *child1, individual *child2, Global global, int *nrealcross); -void bincross (individual *parent1, individual *parent2, individual *child1, individual *child2, Global global, int *nbincross); - -void assign_crowding_distance_list (population *pop, list *lst, int front_size, Global global); -void assign_crowding_distance_indices (population *pop, int c1, int c2, Global global); -void assign_crowding_distance (population *pop, int *dist, int **obj_array, int front_size, Global global); - -void decode_pop (population *pop, Global global); -void decode_ind (individual *ind, Global global); - -int check_dominance (individual *a, individual *b, Global global); - -void evaluate_pop (population *pop, Global global); -void evaluate_ind (individual *ind, Global global); - -void fill_nondominated_sort (population *mixed_pop, population *new_pop, Global global); -void crowding_fill (population *mixed_pop, population *new_pop, int count, int front_size, list *cur, Global global); - -void initialize_pop (population *pop, Global global); -void initialize_ind (individual *ind, Global global); - -void insert (list *node, int x); -list* delnode (list *node); - -void merge(population *pop1, population *pop2, population *pop3, Global global); -void copy_ind (individual *ind1, individual *ind2, Global global); - -void mutation_pop (population *pop, Global global, int *nrealmut, int *nbinmut); -void mutation_ind (individual *ind, Global global, int *nrealmut, int *nbinmut); -void bin_mutate_ind (individual *ind, Global global, int *nbinmut); -void real_mutate_ind (individual *ind, Global global, int *nrealmut); - -//void nsga2func (int nreal, int nbin, int nobj, int ncon, double *xreal, double *xbin, int **gene, double *obj, double *constr); - -void assign_rank_and_crowding_distance (population *new_pop, Global global); - -void report_pop (population *pop, FILE *fpt, Global global); -void report_feasible (population *pop, FILE *fpt, Global global); -//void report_ind (individual *ind, FILE *fpt); - -void quicksort_front_obj(population *pop, int objcount, int obj_array[], int obj_array_size); -void q_sort_front_obj(population *pop, int objcount, int obj_array[], int left, int right); -void quicksort_dist(population *pop, int *dist, int front_size); -void q_sort_dist(population *pop, int *dist, int left, int right); - -void selection (population *old_pop, population *new_pop, Global global, int *nrealcross, int *nbincross); -individual* tournament (individual *ind1, individual *ind2, Global global); - -# endif diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/rand.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/rand.c deleted file mode 100644 index 9e00b9f0e..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/rand.c +++ /dev/null @@ -1,113 +0,0 @@ -/* Definition of random number generation routines */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -double seed; -double oldrand[55]; -int jrand; - -/* Get seed number for random and start it up */ -void randomize() -{ - int j1; - for(j1=0; j1<=54; j1++) - { - oldrand[j1] = 0.0; - } - jrand=0; - warmup_random (seed); - return; -} - -/* Get randomize off and running */ -void warmup_random (double seed) -{ - int j1, ii; - double new_random, prev_random; - oldrand[54] = seed; - new_random = 0.000000001; - prev_random = seed; - for(j1=1; j1<=54; j1++) - { - ii = (21*j1)%54; - oldrand[ii] = new_random; - new_random = prev_random-new_random; - if(new_random<0.0) - { - new_random += 1.0; - } - prev_random = oldrand[ii]; - } - advance_random (); - advance_random (); - advance_random (); - jrand = 0; - return; -} - -/* Create next batch of 55 random numbers */ -void advance_random () -{ - int j1; - double new_random; - for(j1=0; j1<24; j1++) - { - new_random = oldrand[j1]-oldrand[j1+31]; - if(new_random<0.0) - { - new_random = new_random+1.0; - } - oldrand[j1] = new_random; - } - for(j1=24; j1<55; j1++) - { - new_random = oldrand[j1]-oldrand[j1-24]; - if(new_random<0.0) - { - new_random = new_random+1.0; - } - oldrand[j1] = new_random; - } -} - -/* Fetch a single random number between 0.0 and 1.0 */ -double randomperc() -{ - jrand++; - if(jrand>=55) - { - jrand = 1; - advance_random(); - } - return((double)oldrand[jrand]); -} - -/* Fetch a single random integer between low and high including the bounds */ -int rnd (int low, int high) -{ - int res; - if (low >= high) - { - res = low; - } - else - { - res = low + (randomperc()*(high-low+1)); - if (res > high) - { - res = high; - } - } - return (res); -} - -/* Fetch a single random real number between low and high including the bounds */ -double rndreal (double low, double high) -{ - return (low + (high-low)*randomperc()); -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/rand.h b/pyoptsparse/pyoptsparse/pyNSGA2/source/rand.h deleted file mode 100644 index 246bd256d..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/rand.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Declaration for random number related variables and routines */ - -# ifndef _RAND_H_ -# define _RAND_H_ - -/* Variable declarations for the random number generator */ -extern double seed; -extern double oldrand[55]; -extern int jrand; - -/* Function declarations for the random number generator */ -void randomize(void); -void warmup_random (double seed); -void advance_random (void); -double randomperc(void); -int rnd (int low, int high); -double rndreal (double low, double high); - -# endif diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/rank.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/rank.c deleted file mode 100644 index d4abd748e..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/rank.c +++ /dev/null @@ -1,104 +0,0 @@ -/* Rank assignment routine */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to assign rank and crowding distance to a population of size pop_size*/ -void assign_rank_and_crowding_distance (population *new_pop, Global global) -{ - int flag; - int i; - int end; - int front_size; - int rank=1; - list *orig; - list *cur; - list *temp1, *temp2; - orig = (list *)malloc(sizeof(list)); - cur = (list *)malloc(sizeof(list)); - front_size = 0; - orig->index = -1; - orig->parent = NULL; - orig->child = NULL; - cur->index = -1; - cur->parent = NULL; - cur->child = NULL; - temp1 = orig; - for (i=0; ichild; - } - do - { - if (orig->child->child == NULL) - { - new_pop->ind[orig->child->index].rank = rank; - new_pop->ind[orig->child->index].crowd_dist = INF; - break; - } - temp1 = orig->child; - insert (cur, temp1->index); - front_size = 1; - temp2 = cur->child; - temp1 = delnode (temp1); - temp1 = temp1->child; - do - { - temp2 = cur->child; - do - { - end = 0; - flag = check_dominance (&(new_pop->ind[temp1->index]), &(new_pop->ind[temp2->index]), global); - if (flag == 1) - { - insert (orig, temp2->index); - temp2 = delnode (temp2); - front_size--; - temp2 = temp2->child; - } - if (flag == 0) - { - temp2 = temp2->child; - } - if (flag == -1) - { - end = 1; - } - } - while (end!=1 && temp2!=NULL); - if (flag == 0 || flag == 1) - { - insert (cur, temp1->index); - front_size++; - temp1 = delnode (temp1); - } - temp1 = temp1->child; - } - while (temp1 != NULL); - temp2 = cur->child; - do - { - new_pop->ind[temp2->index].rank = rank; - temp2 = temp2->child; - } - while (temp2 != NULL); - assign_crowding_distance_list (new_pop, cur->child, front_size, global); - temp2 = cur->child; - do - { - temp2 = delnode (temp2); - temp2 = temp2->child; - } - while (cur->child !=NULL); - rank+=1; - } - while (orig->child!=NULL); - free (orig); - free (cur); - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/report.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/report.c deleted file mode 100644 index 05ec2df5c..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/report.c +++ /dev/null @@ -1,93 +0,0 @@ -/* Routines for storing population data into files */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Function to print the information of a population in a file */ -void report_pop (population *pop, FILE *fpt, Global global) -{ - int i, j, k; - for (i=0; iind[i].obj[j]); - } - if (global.ncon!=0) - { - for (j=0; jind[i].constr[j]); - } - } - if (global.nreal!=0) - { - for (j=0; jind[i].xreal[j]); - } - } - if (global.nbin!=0) - { - for (j=0; jind[i].gene[j][k]); - } - } - } - fprintf(fpt,"%e\t",pop->ind[i].constr_violation); - fprintf(fpt,"%d\t",pop->ind[i].rank); - fprintf(fpt,"%e\n",pop->ind[i].crowd_dist); - } - return; -} - -/* Function to print the information of feasible and non-dominated population in a file */ -void report_feasible (population *pop, FILE *fpt, Global global) -{ - int i, j, k; - for (i=0; iind[i].constr_violation == 0.0 && pop->ind[i].rank==1) - { - for (j=0; jind[i].obj[j]); - } - if (global.ncon!=0) - { - for (j=0; jind[i].constr[j]); - } - } - if (global.nreal!=0) - { - for (j=0; jind[i].xreal[j]); - } - } - if (global.nbin!=0) - { - for (j=0; jind[i].gene[j][k]); - } - } - } - fprintf(fpt,"%e\t",pop->ind[i].constr_violation); - fprintf(fpt,"%d\t",pop->ind[i].rank); - fprintf(fpt,"%e\n",pop->ind[i].crowd_dist); - } - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/sort.c b/pyoptsparse/pyoptsparse/pyNSGA2/source/sort.c deleted file mode 100644 index a3c68696c..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/sort.c +++ /dev/null @@ -1,92 +0,0 @@ -/* Routines for randomized recursive quick-sort */ - -# include -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Randomized quick sort routine to sort a population based on a particular objective chosen */ -void quicksort_front_obj(population *pop, int objcount, int obj_array[], int obj_array_size) -{ - q_sort_front_obj (pop, objcount, obj_array, 0, obj_array_size-1); - return; -} - -/* Actual implementation of the randomized quick sort used to sort a population based on a particular objective chosen */ -void q_sort_front_obj(population *pop, int objcount, int obj_array[], int left, int right) -{ - int index; - int temp; - int i, j; - double pivot; - if (leftind[obj_array[right]].obj[objcount]; - i = left-1; - for (j=left; jind[obj_array[j]].obj[objcount] <= pivot) - { - i+=1; - temp = obj_array[j]; - obj_array[j] = obj_array[i]; - obj_array[i] = temp; - } - } - index=i+1; - temp = obj_array[index]; - obj_array[index] = obj_array[right]; - obj_array[right] = temp; - q_sort_front_obj (pop, objcount, obj_array, left, index-1); - q_sort_front_obj (pop, objcount, obj_array, index+1, right); - } - return; -} - -/* Randomized quick sort routine to sort a population based on crowding distance */ -void quicksort_dist(population *pop, int *dist, int front_size) -{ - q_sort_dist (pop, dist, 0, front_size-1); - return; -} - -/* Actual implementation of the randomized quick sort used to sort a population based on crowding distance */ -void q_sort_dist(population *pop, int *dist, int left, int right) -{ - int index; - int temp; - int i, j; - double pivot; - if (leftind[dist[right]].crowd_dist; - i = left-1; - for (j=left; jind[dist[j]].crowd_dist <= pivot) - { - i+=1; - temp = dist[j]; - dist[j] = dist[i]; - dist[i] = temp; - } - } - index=i+1; - temp = dist[index]; - dist[index] = dist[right]; - dist[right] = temp; - q_sort_dist (pop, dist, left, index-1); - q_sort_dist (pop, dist, index+1, right); - } - return; -} diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/swig/README b/pyoptsparse/pyoptsparse/pyNSGA2/source/swig/README deleted file mode 100644 index 21e9839de..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/swig/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the swig signature file. -Do not edit these file unless you really know what you are doing. diff --git a/pyoptsparse/pyoptsparse/pyNSGA2/source/swig/nsga2.i b/pyoptsparse/pyoptsparse/pyNSGA2/source/swig/nsga2.i deleted file mode 100644 index 4936d97b9..000000000 --- a/pyoptsparse/pyoptsparse/pyNSGA2/source/swig/nsga2.i +++ /dev/null @@ -1,123 +0,0 @@ -%module nsga2 - -/* Includes the header in the wrapper code */ -%{ - #include "nsga2.h" -%} - - -/* Include SWIG cpointer support */ -%include "cpointer.i" -%pointer_functions(int, intPointer); -%pointer_functions(double, doublePointer); - -/* Include SWIG carrays support */ -%include "carrays.i" -%array_functions(int, intArray); -%array_functions(double, doubleArray); - - -/* Map Python function as an object */ -#ifdef SWIGPYTHON -%typemap(in) PyObject *pyfunc { - if (!PyCallable_Check($input)) { - PyErr_SetString(PyExc_TypeError, "Need a callable object!"); - return NULL; - } - $1 = $input; -} -#endif - - -/* Include set_pyfunc to Inline C */ -void set_pyfunc(PyObject *pyfunc); - - -/* Parse the header file to generate wrappers */ -%include "../nsga2.h" - - -/* Wrapper code */ -%{ - -/* Pointer to the Python function */ -static PyObject *py_fobjcon = NULL; - -/* Initialize Python callback function pointer */ -void set_pyfunc(PyObject *pyfunc) -{ - Py_XDECREF(py_fobjcon); - Py_XINCREF(pyfunc); - py_fobjcon = pyfunc; - Py_XDECREF(pyfunc); -} - -/* C <-> Python callback */ -void nsga2func (int nreal, int nbin, int nobj, int ncon, double *xreal, double *xbin, int **gene, double *obj, double *constr) -{ - - int i, j, k; - double getval; - PyObject *arglist, *result, *xx, *ff, *gg; - - arglist = PyTuple_New(6); - - PyTuple_SetItem(arglist,0,PyLong_FromLong(nreal)); - - PyTuple_SetItem(arglist,1,PyLong_FromLong(nobj)); - - PyTuple_SetItem(arglist,2,PyLong_FromLong(ncon)); - - xx = PyList_New(nreal); - for (i=0;i -# include -# include - -# include "nsga2.h" -# include "rand.h" - -/* Routine for tournament selection, it creates a new_pop from old_pop by performing tournament selection and the crossover */ -void selection (population *old_pop, population *new_pop, Global global, int *nrealcross, int *nbincross) -{ - int *a1, *a2; - int temp; - int i; - int rand; - individual *parent1, *parent2; - a1 = (int *)malloc(global.popsize*sizeof(int)); - a2 = (int *)malloc(global.popsize*sizeof(int)); - for (i=0; iind[a1[i]], &old_pop->ind[a1[i+1]], global); - parent2 = tournament (&old_pop->ind[a1[i+2]], &old_pop->ind[a1[i+3]], global); - crossover (parent1, parent2, &new_pop->ind[i], &new_pop->ind[i+1], global, nrealcross, nbincross); - parent1 = tournament (&old_pop->ind[a2[i]], &old_pop->ind[a2[i+1]], global); - parent2 = tournament (&old_pop->ind[a2[i+2]], &old_pop->ind[a2[i+3]], global); - crossover (parent1, parent2, &new_pop->ind[i+2], &new_pop->ind[i+3], global, nrealcross, nbincross); - } - free (a1); - free (a2); - return; -} - -/* Routine for binary tournament */ -individual* tournament (individual *ind1, individual *ind2, Global global) -{ - int flag; - flag = check_dominance (ind1, ind2, global); - if (flag==1) - { - return (ind1); - } - if (flag==-1) - { - return (ind2); - } - if (ind1->crowd_dist > ind2->crowd_dist) - { - return(ind1); - } - if (ind2->crowd_dist > ind1->crowd_dist) - { - return(ind2); - } - if ((randomperc()) <= 0.5) - { - return(ind1); - } - else - { - return(ind2); - } -} diff --git a/pyoptsparse/pyoptsparse/pyOpt_MPI.py b/pyoptsparse/pyoptsparse/pyOpt_MPI.py deleted file mode 100644 index 882bf2837..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_MPI.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python -''' -pyOptSparse_MPI - -A simple wrapper to MPI that enables pyOptSparse to work without -mpi4py. Only the method from the COMM object that are actually used in -pyOptSparse are included here. - -Copyright (c) 2008-2013 by Dr. Gaetan Kenway -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -''' -from __future__ import print_function -import warnings -class COMM(object): - def __init__(self): - self.rank = 0 - self.size = 1 - def bcast(self, obj=None, root=0): - return obj - def Reduce(self, sendbuf, recvbuf, op, root=0): - recvbuf = sendbuf.copy() - return recvbuf - def allreduce(self, sendobj=None, recvobj=None, op=None): - return sendobj - def gather(self, sendobj, recvobj=None, root=0): - return [sendobj] - def recv(self, obj=None, source=0, tag=0, status=None): - return obj - -class myMPI(object): - def __init__(self): - self.COMM_WORLD = COMM() - self.SUM = 'SUM' - self.LOR = 'OR' -try: - from mpi4py import MPI -except: - warn = 'mpi4py could not be imported. mpi4py is required to use\ - the parallel gradient analysis and parallel objective analysis for\ - non-gradient based optimizers. Continuing using a dummy MPI module\ - from pyOptSparse.' - warnings.warn(warn) - MPI = myMPI() diff --git a/pyoptsparse/pyoptsparse/pyOpt_constraint.py b/pyoptsparse/pyoptsparse/pyOpt_constraint.py deleted file mode 100644 index 7509b93ef..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_constraint.py +++ /dev/null @@ -1,377 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_constraint - -Holds the representation of a pyOptSparse constraint group - -Copyright (c) 2008-2013 by pyOpt Developers -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -""" -# ============================================================================= -# External Python modules -# ============================================================================= -import copy -import numpy -from .pyOpt_error import Error -from .pyOpt_utils import convertToCOO -INFINITY = 1e20 -eps = numpy.finfo(1.0).eps -# ============================================================================= -# Constraint Class -# ============================================================================= -class Constraint(object): - """ - Constraint Class Initialization - """ - def __init__(self, name, nCon, linear, wrt, jac, lower, upper, scale): - - self.name = name - self.ncon = nCon - self.linear = linear - self.wrt = wrt - self.jac = jac - self.partialReturnOk = None - self.scale = scale - self.rs = None - self.re = None - # Before we can do the processing below we need to have lower - # and upper arguments expanded: - - if lower is None: - lower = [None for i in range(self.ncon)] - elif numpy.isscalar(lower): - lower = lower*numpy.ones(self.ncon) - elif len(lower) == self.ncon: - pass # Some iterable object - else: - raise Error("The 'lower' argument to addCon or addConGroup is " - "invalid. It must be None, a scalar, or a " - "list/array or length ncon=%d." % nCon) - - if upper is None: - upper = [None for i in range(self.ncon)] - elif numpy.isscalar(upper): - upper = upper*numpy.ones(self.ncon) - elif len(upper) == self.ncon: - pass # Some iterable object - else: - raise Error("The 'upper' argument to addCon or addConGroup is " - "invalid. It must be None, a scalar, or a " - "list/array or length ncon=%d." %nCon) - - # ------ Process the scale argument - scale = numpy.atleast_1d(scale) - if len(scale) == 1: - scale = scale[0]*numpy.ones(nCon) - elif len(scale) == nCon: - pass - else: - raise Error("The length of the 'scal\' argument to " - "addCon or addConGroup is %d, but the number of " - "constraints is %d."% (len(scale), nCon)) - - # Save lower and upper...they are only used for printing however - self.lower = lower - self.upper = upper - # The current value of the constraint (for printing purposes) - self.value = numpy.zeros(self.ncon) - - # Now we determine what kind of constraint this is: - # 1. An equality constraint - # 2. A upper bound on a 1-sided constraint - # 3. A lower bound on a 1-sided constraint - # 4. Lower and Upper bounds on 2-sided constraint - # 5. No lower or upper bounds. Typically will only be used for - # dummy constraint on an unconstrained problem. - - # The first 3, will give a single "constraint" in all - # optimizers. Some optimizers can only do 1-sided constraints - # so type 4 and 5 must be split into two separate constraints - # automatically. - - # This keeps track of the equality constraints: - equalityConstraints = {'value': [], 'ind': [], 'fact': []} - - # All (inequality) constraints get added to - # "twoSidedConstraints". This will be used in optimizers that - # can do two-sided constraints properly - twoSidedConstraints = {'lower': [], 'upper': [], 'ind': [], 'fact': []} - - # All (inequality) constraints are also added to - # "oneSidedConstraints". These are processed such that the - # lower bound is ALWAYS -INFINITY such that: con <= upper For - # optimizers that need things <= zero, this can be processed - # with a (-value) offset. One sided constraints need a fact - # defined which is precisely 1.0 or -1.0. The -1.0 appears - # when a greater-than-constraint is turned into a - # less-than-constraint. - oneSidedConstraints = {'lower': [], 'upper': [], 'ind': [], 'fact': []} - - for icon in range(self.ncon): - # Check for equality constraint: - if lower[icon] == upper[icon] and lower[icon] is not None: - equalityConstraints['value'].append(lower[icon]*scale[icon]) - equalityConstraints['ind'].append(icon) - equalityConstraints['fact'].append(1.0) - - # Two sided constraint: - elif lower[icon] is not None and upper[icon] is not None: - twoSidedConstraints['lower'].append(lower[icon]*scale[icon]) - twoSidedConstraints['upper'].append(upper[icon]*scale[icon]) - twoSidedConstraints['ind'].append(icon) - twoSidedConstraints['fact'].append(1.0) - - # TWO sets of 1 sided constraints: - oneSidedConstraints['lower'].append(-INFINITY) - oneSidedConstraints['upper'].append(upper[icon]*scale[icon]) - oneSidedConstraints['ind'].append(icon) - oneSidedConstraints['fact'].append(1.0) - - oneSidedConstraints['lower'].append(-INFINITY) - oneSidedConstraints['upper'].append(-lower[icon]*scale[icon]) - oneSidedConstraints['ind'].append(icon) - oneSidedConstraints['fact'].append(-1.0) - - # Upper bound only: - elif upper[icon] is not None: - twoSidedConstraints['lower'].append(-INFINITY) - twoSidedConstraints['upper'].append(upper[icon]*scale[icon]) - twoSidedConstraints['ind'].append(icon) - twoSidedConstraints['fact'].append(1.0) - - # Just one, 1-sided constraint - oneSidedConstraints['lower'].append(-INFINITY) - oneSidedConstraints['upper'].append(upper[icon]*scale[icon]) - oneSidedConstraints['ind'].append(icon) - oneSidedConstraints['fact'].append(1.0) - - # Lower bound only: - elif lower[icon] is not None: - twoSidedConstraints['lower'].append(lower[icon]*scale[icon]) - twoSidedConstraints['upper'].append(INFINITY) - twoSidedConstraints['ind'].append(icon) - twoSidedConstraints['fact'].append(1.0) - - # Just one, 1-sided constraint - oneSidedConstraints['lower'].append(-INFINITY) - oneSidedConstraints['upper'].append(-lower[icon]*scale[icon]) - oneSidedConstraints['ind'].append(icon) - oneSidedConstraints['fact'].append(-1.0) - - # Fully unconstrained! - elif lower[icon] is None and upper[icon] is None: - twoSidedConstraints['lower'].append(-INFINITY) - twoSidedConstraints['upper'].append(INFINITY) - twoSidedConstraints['ind'].append(icon) - twoSidedConstraints['fact'].append(1.0) - - # Since this is just a dummy constraint, we only need - # a single one....it can just be less than INFINITY - oneSidedConstraints['lower'].append(-INFINITY) - oneSidedConstraints['upper'].append(INFINITY) - oneSidedConstraints['ind'].append(icon) - oneSidedConstraints['fact'].append(1.0) - # end if (con type) - # end for (con loop) - - # Convert the stuff to arrays: - oneSidedConstraints['ind'] = numpy.array(oneSidedConstraints['ind'], 'intc') - twoSidedConstraints['ind'] = numpy.array(twoSidedConstraints['ind'], 'intc') - equalityConstraints['ind'] = numpy.array(equalityConstraints['ind'], 'intc') - - oneSidedConstraints['fact'] = numpy.array(oneSidedConstraints['fact']) - twoSidedConstraints['fact'] = numpy.array(twoSidedConstraints['fact']) - equalityConstraints['fact'] = numpy.array(equalityConstraints['fact']) - - equalityConstraints['value'] = numpy.array(equalityConstraints['value']) - - # Now save this information: - self.equalityConstraints = equalityConstraints - self.oneSidedConstraints = oneSidedConstraints - self.twoSidedConstraints = twoSidedConstraints - - def finalize(self, variables, dvOffset, index): - """ **This function should not need to be called by the user** - - After the design variables have been finalized and the order - is known we can check the constraint for consistency. - - Parameters - ---------- - variables : Ordered Dict - The pyOpt variable list after they have been finalized. - - dvOffset : dict - Design variable offsets from pyOpt_optimization - - index : int - The starting index of this constraint in natural order - - """ - - # Set the row start and end - self.rs = index - self.re = index + self.ncon - - # First check if 'wrt' is supplied...if not we just take all - # the dvGroups - if self.wrt is None: - self.wrt = list(variables.keys()) - else: - # Sanitize the wrt input: - if isinstance(self.wrt, str): - self.wrt = [self.wrt.lower()] - else: - try: - self.wrt = list(self.wrt) - except: - raise Error("The 'wrt' argument to constraint '%s' must " - "be an iterable list"% self.name) - - # We allow 'None' to be in the list...they are null so - # just pop them out: - self.wrt = [dvGroup for dvGroup in self.wrt if dvGroup != None] - - # Now, make sure that each dvGroup the user supplied list - # *actually* are variables - for dvGroup in self.wrt: - if not dvGroup in variables: - raise Error("The supplied dvGroup '%s' in 'wrt' " - "for the %s constraint, does not exist. It " - "must be added with a call to addVar() or " - "addVarGroup()."% (dvGroup, self.name)) - - # Check for duplicates in wrt - wrt_uniq = list(set(self.wrt)) - if len(wrt_uniq) < len(self.wrt): - duplicate_vars = list(set([x for x in self.wrt if self.wrt.count(x) > 1])) - print("pyOptSparse Warning: The constraint %s was created with " - "duplicate\nvariables in 'wrt'. The following duplicates " - "were automatically removed: "%self.name) - for var in duplicate_vars: - print("\t\t%s"%var) - self.wrt = wrt_uniq - - # Last thing for wrt is to reorder them such that dvGroups are - # in order. This way when the jacobian is assembled in - # processDerivatives() the coorindate matrix will in the right - # order. - dvStart = [] - for dvGroup in self.wrt: - dvStart.append(dvOffset[dvGroup][0]) - - # This sort wrt using the keys in dvOffset - self.wrt = [x for (y, x) in sorted(zip(dvStart, self.wrt))] - - # Now we know which dvGroups this constraint will have a - # derivative with respect to (i.e. what is in the wrt list) - - # Now, it is possible that jacobians were given for none, some - # or all the dvGroups defined in wrt. - if self.jac is None: - # If the constraint is linear we have to *Force* the user to - # supply a constraint jacobian for *each* of the values in - # wrt. Otherwise, a matrix of zeros isn't meaningful for the - # sparse constraints. - - if self.linear: - raise Error("The 'jac' keyword to argument to addConGroup() " - "must be supplied for a linear constraint. " - "The constraint in error is %s."% self.name) - - # without any additional information about the jacobian - # structure, we must assume they are all dense. - self.jac = {} - for dvGroup in self.wrt: - ss = dvOffset[dvGroup] - ndvs = ss[1]-ss[0] - self.jac[dvGroup] = convertToCOO(numpy.zeros((self.ncon, ndvs))) - - # Set a flag for the constraint object, that not returning - # them all is ok. - self.partialReturnOk = True - - else: - # First sanitize input: - if not isinstance(self.jac, dict): - raise Error("The 'jac' keyword argument to addConGroup() " - "must be a dictionary. The constraint in error " - "is %s."% self.name) - - # Now loop over the set we *know* we need and see if any - # are in jac. We will actually pop them out, and that way - # if there is anything left at the end, we can tell the - # user supplied information was unused. - tmp = copy.deepcopy(self.jac) - self.jac = {} - for dvGroup in self.wrt: - ss = dvOffset[dvGroup] - ndvs = ss[1]-ss[0] - - try: - self.jac[dvGroup] = tmp.pop(dvGroup) - except KeyError: - # No big deal, just make a dense component...and - # set to zero - self.jac[dvGroup] = convertToCOO(numpy.zeros((self.ncon, ndvs))) - - # Convert Now check that the supplied jacobian to COO: - self.jac[dvGroup] = convertToCOO(self.jac[dvGroup]) - - # Generically check the shape: - if (self.jac[dvGroup]['shape'][0] != self.ncon or - self.jac[dvGroup]['shape'][1] != ndvs): - raise Error("The supplied jacobian for dvGroup %s' " - "in constraint %s, was the incorrect size. " - "Expecting a jacobian of size (%d, %d) but " - "received a jacobian of size (%d, %d)."%( - dvGroup, self.name, self.ncon, ndvs, - self.jac[dvGroup]['shape'][0], - self.jac[dvGroup]['shape'][1])) - # end for (dvGroup) - - # If there is anything left in jac print a warning: - for dvGroup in tmp: - print("pyOptSparse Warning: A jacobian with dvGroup key of " - "'%s' was unused in constraint %s. This will be " - "ignored."% (dvGroup, self.name)) - - # Since this function *may* be called multiple times, only - # set paritalReturnOk if it was the first pass: - if self.partialReturnOk is None: - # Finally partial returns NOT ok, since the user has - # supplied information about the sparsity: - self.partialReturnOk = False - - # end if (if Jac) - - def __str__(self): - """ - Print Constraint - - Documentation last updated: April. 30, 2008 - Peter W. Jansen - """ - res = '' - for i in range(self.ncon): - lower = self.lower[i] - upper = self.upper[i] - value = self.value[i] - if lower is None: - lower = -1e20 - if upper is None: - upper = 1e20 - - res += ' '+str(self.name).center(9) + \ - ' i %15.2e <= %8f <= %8.2e\n' %( - numpy.real(lower), numpy.real(value), - numpy.real(upper)) - - return res diff --git a/pyoptsparse/pyoptsparse/pyOpt_error.py b/pyoptsparse/pyoptsparse/pyOpt_error.py deleted file mode 100644 index 8719c0e2a..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_error.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -''' -pyOptSparse_error - -Holds a simple error handling class for pyOptSparse - -Copyright (c) 2008-2013 by Dr. Gaetan Kenway -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -''' -from __future__ import print_function - -class Error(Exception): - """ - Format the error message in a box to make it clear this - was a expliclty raised exception. - """ - def __init__(self, message): - msg = '\n+'+'-'*78+'+'+'\n' + '| pyOptSparse Error: ' - i = 21 - for word in message.split(): - if len(word) + i +1 > 78: # Finish line and start new one - msg += ' '*(79-i)+'|\n| ' + word + ' ' - i = 2 + len(word)+1 - else: - msg += word + ' ' - i += len(word)+1 - msg += ' '*(79-i) + '|\n' + '+'+'-'*78+'+'+'\n' - print(msg) - Exception.__init__(self) - -class pyOptSparseWarning(object): - """ - Format a warning message - """ - def __init__(self, message): - msg = '\n+'+'-'*78+'+'+'\n' + '| pyOptSparse Warning: ' - i = 23 - for word in message.split(): - if len(word) + i + 1 > 78: # Finish line and start new one - msg += ' '*(78-i)+'|\n| ' + word + ' ' - i = 1 + len(word)+1 - else: - msg += word + ' ' - i += len(word)+1 - msg += ' '*(78-i) + '|\n' + '+'+'-'*78+'+'+'\n' - print(msg) - diff --git a/pyoptsparse/pyoptsparse/pyOpt_gradient.py b/pyoptsparse/pyoptsparse/pyOpt_gradient.py deleted file mode 100644 index ac6476c5a..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_gradient.py +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_gradient - A class that produce gradients using finite -difference or complex step. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Developers ----------- -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Class Creation (GKK) -""" -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -from .pyOpt_MPI import MPI -# ============================================================================= -# Gradient Class -# ============================================================================= -class Gradient(object): - """ - Gradient class for automatically computing gradients with finite - difference or complex step. - - Parameters - ---------- - optProb : Optimization instance - This is the complete description of the optimization problem. - - sensType : str - 'FD' for forward difference, 'CD' for central difference, - 'FDR' for forward difference with relative step size, - 'CDR' for central difference with relative step size, - and 'CS' for complex step - - sensStep : number - Step size to use for differencing - - sensMode : str - Flag to compute gradients in parallel. - """ - - def __init__(self, optProb, sensType, sensStep=None, sensMode='', - comm=None): - self.optProb = optProb - self.sensType = sensType - if sensStep is None: - if self.sensType in ['fd', 'fdr']: - self.sensStep = 1e-6 - elif self.sensType in ['cd', 'cdr']: - self.sensStep = 1e-4 - else: - self.sensStep = 1e-40j - else: - self.sensStep = sensStep - self.sensMode = sensMode - self.comm = comm - - # Now we can compute which dvs each process will need to - # compute: - ndvs = self.optProb.ndvs - if self.sensMode == 'pgc' and self.comm: - self.mydvs = list(range(self.comm.rank, ndvs, self.comm.size)) - else: - self.mydvs = list(range(ndvs)) - - def _eval_func(self, x): - """internal method to call function and extract obj, con""" - - xCall = self.optProb.processX(x) - # Call objective - [funcs, fail] = self.optProb.objFun(xCall) - - # Process constraint in case they are in dict form - self.optProb.evaluateLinearConstraints(x, funcs) - fobj = self.optProb.processObjective(funcs, scaled=False) - - if self.sensType == 'cs': - fcon = self.optProb.processConstraints(funcs, scaled=False, - dtype='D', natural=True) - else: - fcon = self.optProb.processConstraints(funcs, scaled=False, - natural=True) - - return fobj, fcon, fail - - def __call__(self, x, funcs): - """ - We need to make this object "look" the same as a user supplied - function handle. That way, the optimizers need not care how - the gradients are **actually** calculated. - - Parameters - ---------- - x : array - Optimization variables from optimizer - - funcs : dict - Dictionary of all the function values - - Returns - ------- - gobj : 1D array - The derivative of the objective with respect to the design - variables - - gcon : 2D array - The derivative of the constraints with respect to the design - variables - - fail : bool - Flag for failure. It currently always returns False - """ - - # Since this is *very* dumb loop over all the design - # variables, it is easier to just loop over the x values as an - # array. Furthermore, since the user **should** have - # reasonably well scaled variables, the fixed step size should - # have more meaning. - - # Generate final array sizes for the objective and constraint - # gradients - ndvs = self.optProb.ndvs - ncon = self.optProb.nCon - gobj = numpy.zeros(ndvs, 'd') - gcon = numpy.zeros((ncon, ndvs), 'd') - - if self.sensMode == 'pgc': - funcsBase = self.comm.bcast(funcs) - else: - funcsBase = funcs - - # We DO NOT want the constraints scaled here....the constraint - # scaling will be taken into account when the derivatives are - # processed as per normal. - xBase = self.optProb.deProcessX(x) - self.optProb.evaluateLinearConstraints(xBase, funcsBase) - fconBase = self.optProb.processConstraints( - funcsBase, scaled=False, dtype='D', natural=True) - fobjBase = self.optProb.processObjective(funcsBase, scaled=False) - - # Convert to complex if necessary: - if self.sensType == 'cs': - xBase = xBase.astype('D') - - masterFail = False - - for i in self.mydvs: - xph = xBase.copy() - if self.sensType in ['fdr', 'cdr']: - sensStep = max(abs(self.sensStep*xph[i]), self.sensStep) - else: - sensStep = self.sensStep - xph[i] += sensStep - - fobj_ph, fcon_ph, fail = self._eval_func(xph) - if fail: - masterFail = True - - # forward difference - if self.sensType in ['fd', 'fdr']: - gobj[i] = (fobj_ph - fobjBase)/sensStep - gcon[:, i] = (fcon_ph - fconBase)/sensStep - - # central difference - elif self.sensType in ['cd', 'cdr']: - xmh = xph # xph isn't used anymore so just point to same location - xmh[i] -= 2*sensStep - - fobj_mh, fcon_mh, fail = self._eval_func(xmh) - if fail: - masterFail = True - - gobj[i] = (fobj_ph - fobj_mh)/(2*sensStep) - gcon[:, i] = (fcon_ph - fcon_mh)/(2*sensStep) - - # complex step - else: - gobj[i] = numpy.imag(fobj_ph)/numpy.imag(sensStep) - gcon[:, i] = numpy.imag(fcon_ph)/numpy.imag(sensStep) - - if self.sensMode == 'pgc': - # We just mpi_reduce to the root with sum. This uses the - # efficent numpy versions - self.comm.Reduce(gobj.copy(), gobj, op=MPI.SUM, root=0) - self.comm.Reduce(gcon.copy(), gcon, op=MPI.SUM, root=0) - - # Logically reduce (over the comm) if the fail if *ANY* - # gradient calc failed: - if self.comm is not None: - masterFail = self.comm.allreduce(masterFail, op=MPI.LOR) - - # Finally, we have to convert everything **back** to a - # dictionary so the rest of the code works: - funcs = {} - for objKey in self.optProb.objectives: - funcs[objKey] = {} - for dvGroup in self.optProb.variables: - ss = self.optProb.dvOffset[dvGroup] - funcs[objKey][dvGroup] = gobj[ss[0]:ss[1]] - - for conKey in self.optProb.constraints: - con = self.optProb.constraints[conKey] - funcs[conKey] = {} - for dvGroup in self.optProb.variables: - ss = self.optProb.dvOffset[dvGroup] - funcs[conKey][dvGroup] = gcon[con.rs:con.re,ss[0]:ss[1]] - - return funcs, masterFail - diff --git a/pyoptsparse/pyoptsparse/pyOpt_history.py b/pyoptsparse/pyoptsparse/pyOpt_history.py deleted file mode 100644 index acb157352..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_history.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_history - -Holds the Python Design Optimization History Class. - -Copyright (c) 2008-2013 by pyOpt Developers -All rights reserved. -Revision: 1.0 $Date: 11/12/2009 21:00$ - -Developers: ------------ -- Dr. Gaetan K. W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK 2013) -""" -from __future__ import print_function -# ============================================================================= -# External Python modules -# ============================================================================= -import os -from .pyOpt_error import Error -from .sqlitedict.sqlitedict import SqliteDict -# ============================================================================= -# History Class -# ============================================================================= -class History(object): - """ - Optimizer History Class Initialization. This is essentially a - thin wrapper around a SqliteDict dictionary to facilitate - operations with pyOptSparse - - Parameters - ---------- - fileName : str - File name for history file - - temp : bool - Flag to signify that the file should be deleted after it is - closed - - flag : str - String speciying the mode. Similar to what was used in - shelve. 'n' for a new database and 'r' to read an existing one. - """ - def __init__(self, fileName, temp=False, flag='n'): - - if flag == 'n': - # If writing, we expliclty remove the file to - # prevent old keys from "polluting" the new histrory - if os.path.exists(fileName): - os.remove(fileName) - self.db = SqliteDict(fileName) - elif flag == 'r': - if os.path.exists(fileName): - self.db = SqliteDict(fileName) - else: - raise Error("The requested history file %s to open in " - "read-only mode does not exist."% fileName) - else: - raise Error('The flag argument to History must be \'r\' or \'n\'.') - self.temp = temp - self.fileName = fileName - - # Load any keys it happens to have: - self.keys = list(self.db.keys()) - - def close(self): - """Close the underlying database""" - self.db.close() - if self.temp: - os.remove(self.fileName) - - def write(self, callCounter, data): - """This is the main to write data. Basically, we just pass in - the callCounter, the integer forming the key, and a dictionary - which will be written to the key""" - - # String key to database on disk - key = '%d'% callCounter - - self.db[key] = data - self.db['last'] = key - self.db.sync() - - def writeData(self, key, data): - """ - Write arbitrary key:data value to db - """ - self.db[key] = data - self.db.commit() - - def pointExists(self, callCounter): - """ - Determine if callCounter is in the database - """ - key = '%d'% callCounter - - if key in self.keys: - return True - else: - return False - - def read(self, callCounter): - """ - Read data for index 'callCounter'. Note that this - point should be verified by calling validPoint() first. - """ - key = '%d'% callCounter - return self.db[key] - - def readData(self, key): - """ - Read data for generic key 'key'. - """ - try: - return self.db[key] - except KeyError: - return None - - def __del__(self): - try: - self.db.close() - if self.temp: - os.remove(self.fileName) - except: - pass - -#============================================================================== -# Optimizer History Test -#============================================================================== -if __name__ == '__main__': - - # Test Optimizer History - print('Testing Optimizer History...') - diff --git a/pyoptsparse/pyoptsparse/pyOpt_objective.py b/pyoptsparse/pyoptsparse/pyOpt_objective.py deleted file mode 100644 index 2dfd8d273..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_objective.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_objective - -Holds the representation of a pyOptSparse objective - -Copyright (c) 2008-2013 by pyOpt Developers -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -""" -import numpy -# ============================================================================= -# Objective Class -# ============================================================================= -class Objective(object): - - """ - Optimization Objective Class - - Parameters - ---------- - name : str - Name of this objective - - scale : float - Scaling factor for objective. This does not change the actual - optimization problem, but may be used to give a more - human-meaningful value - """ - - def __init__(self, name, scale=1.0): - self.name = name - self.value = 0.0 - self.optimum = 0.0 - self.scale = scale - - def __str__(self): - """ - Structured Print of Objective - """ - res = ' Name Value Optimum\n' - res += ' '+str(self.name).center(9) - res += '%12g %12g\n'% (numpy.real(self.value), numpy.real(self.optimum)) - - return res - diff --git a/pyoptsparse/pyoptsparse/pyOpt_optimization.py b/pyoptsparse/pyoptsparse/pyOpt_optimization.py deleted file mode 100644 index da3f0a100..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_optimization.py +++ /dev/null @@ -1,1656 +0,0 @@ -#!/usr/bin/env python -""" -pyOptSparse_optimization - -Holds the Python Design Optimization Class - -The main purpose, of this class is to describe the structure and -potentially, sparsity pattern of an optimization problem. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -""" -from __future__ import print_function - -# ============================================================================= -# Standard Python modules -# ============================================================================= -import copy -import os -try: - from collections import OrderedDict -except ImportError: - try: - from ordereddict import OrderedDict - except ImportError: - print('Could not find any OrderedDict class. For 2.6 and earlier, \ -use:\n pip install ordereddict') - -try: - import six - from six import iteritems, iterkeys, next -except ImportError: - six = None - print ('Could not import \'six\' OpenMDAO type tuple return not available.') - -from .sqlitedict.sqlitedict import SqliteDict - -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -from scipy.sparse import coo_matrix - -# ============================================================================= -# Extension modules -# ============================================================================= -from .pyOpt_variable import Variable -from .pyOpt_objective import Objective -from .pyOpt_constraint import Constraint -from .pyOpt_error import Error -from .pyOpt_MPI import MPI -from .pyOpt_utils import * - -# ============================================================================= -# Misc Definitions -# ============================================================================= -INFINITY = 1e20 - - -# ============================================================================= -# Optimization Class -# ============================================================================= -class Optimization(object): - """ - Create a description of an optimization problem. - - Parameters - ---------- - name : str - Name given to optimization problem. This is name is currently - not used for anything, but may be in the future. - - objFun : python function - Python function handle of function used to evaluate the objective - function. - - comm : MPI intra communication - The communicator this problem will be solved on. This is - required for both analysis when the objective is computed in - parallel as well as to use the internal parallel gradient - computations. Defaults to MPI.COMM_WORLD if not given. - """ - - def __init__(self, name, objFun, comm=None): - - self.name = name - self.objFun = objFun - if comm is None: - self.comm = MPI.COMM_WORLD - else: - self.comm = comm - - # Ordered dictionaries to keep track of variables and constraints - self.variables = OrderedDict() - self.constraints = OrderedDict() - self.objectives = OrderedDict() - self.dvOffset = OrderedDict() - - # Variables to be set in finalizeConstraints - # have finalized the specification of the variable and the - # constraints - self.ndvs = None - self.conScale = None - self.nCon = None - self.invXScale = None - self.xOffset = None - self.linearJacobian = None - self.dummyConstraint = False - self.objectiveIdx = {} - self.bulk = None - - # Store the jacobian conversion maps - self._jac_map_coo_to_csr = None - - def addVar(self, name, *args, **kwargs): - """ - This is a convenience function. It simply calls addVarGroup() - with nVars=1. Variables added with addVar() are returned as - *scalars*. - """ - self.addVarGroup(name, 1, *args, scalar=True, **kwargs) - - def checkVarName(self, varName): - """ - Check if the desired variable name varName if has already been - added. If it is has already been added, return a mangled name - (a number appended) that *is* valid. This is intended to be used - by classes that automatically add variables to pyOptSparse - - Parameters - ---------- - varName : str - Variable name to check validity on - - Returns - ------- - validName : str - A valid variable name. May be the same as varName it that - was, in fact, a valid name. - """ - if varName not in self.variables: - return varName - else: - i = 0 - validName = varName + '_%d'% i - while validName in self.variables: - i += 1 - validName = varName + '_%d'% i - return validName - - def checkConName(self, conName): - """ - Check if the desired constraint name has already been - added. If it is has already been added, return a mangled name - (a number appended) that *is* valid. This is intended to be used - by classes that automatically add constraints to pyOptSparse. - - Parameters - ---------- - conName : str - Constraint name to check validity on - - Returns - ------- - validName : str - A valid constraint name. May be the same as conName it that - was, in fact, a valid name. - """ - if conName not in self.constraints: - return conName - else: - i = 0 - validName = conName + '_%d'% i - while validName in self.constraints: - i += 1 - validName = conName + '_%d'% i - return validName - - def addVarGroup(self, name, nVars, type='c', value=0.0, - lower=None, upper=None, scale=1.0, offset=0.0, - choices=None, **kwargs): - """ - Add a group of variables into a variable set. This is the main - function used for adding variables to pyOptSparse. - - Parameters - ---------- - name : str - Name of variable group. This name should be unique across all the design variable groups - - nVars : int - Number of design variables in this group. - - type : str. - String representing the type of variable. Suitable values for type - are: 'c' for continuous variables, 'i' for integer values and - 'd' for discrete selection. - - value : scalar or array. - Starting value for design variables. If it is a a scalar, the same - value is applied to all 'nVars' variables. Otherwise, it must be - iterable object with length equal to 'nVars'. - - lower : scalar or array. - Lower bound of variables. Scalar/array usage is the same as value - keyword - - upper : scalar or array. - Upper bound of variables. Scalar/array usage is the same as value - keyword - - scale : scalar or array. Define a user supplied scaling - variable for the design variable group. This is often - necessary when design variables of widely varying - magnitudes are used within the same - optimization. Scalar/array usage is the same as value - keyword. - - offset : scalar or array. Define a user supplied offset - variable for the design variable group. This is often - necessary when design variable has a large magnitude, but - only changes a little about this value. - - choices : list - Specify a list of choices for discrete design variables - - Examples - -------- - >>> # Add a single design variable 'alpha' - >>> optProb.addVar('alpha', type='c', value=2.0, lower=0.0, upper=10.0, \ - scale=0.1) - >>> # Add 10 unscaled variables of 0.5 between 0 and 1 with name 'y' - >>> optProb.addVarGroup('y', type='c', value=0.5, lower=0.0, upper=1.0, \ - scale=1.0) - - Notes - ----- - Calling addVar() and addVarGroup(..., nVars=1, ...) are - **NOT** equivalent! The variable added with addVar() will be - returned as scalar, while variable returned from addVarGroup - will be an array of length 1. - - It is recommended that the addVar() and addVarGroup() calls - follow the examples above by including all the keyword - arguments. This make it very clear the intent of the script's - author. The type, value, lower, upper and scale should be - given for all variables even if the default value is used. - """ - - # Check that the nVars is > 0. - if nVars < 1: - raise Error("The 'nVars' argument to addVarGroup must be greater " - "than or equal to 1. The bad DV is %s."%name) - - # Check that the type is ok: - if type not in ['c', 'i', 'd']: - raise Error("Type must be one of 'c' for continuous, " - "'i' for integer or 'd' for discrete.") - - # ------ Process the value argument - value = numpy.atleast_1d(value).real - if len(value) == 1: - value = value[0]*numpy.ones(nVars) - elif len(value) == nVars: - pass - else: - raise Error("The length of the 'value' argument to " - "addVarGroup is %d, but the number of " - "variables in nVars is %d."% (len(value), nVars)) - - if lower is None: - lower = [None for i in range(nVars)] - elif numpy.isscalar(lower): - lower = lower*numpy.ones(nVars) - elif len(lower) == nVars: - lower = numpy.atleast_1d(lower).real - else: - raise Error("The 'lower' argument to addVarGroup is " - "invalid. It must be None, a scalar, or a " - "list/array or length nVars=%d." %(nVars)) - - if upper is None: - upper = [None for i in range(nVars)] - elif numpy.isscalar(upper): - upper = upper*numpy.ones(nVars) - elif len(upper) == nVars: - upper = numpy.atleast_1d(upper).real - else: - raise Error("The 'upper' argument to addVarGroup is " - "invalid. It must be None, a scalar, or a " - "list/array or length nVars=%d." %(nVars)) - - # ------ Process the scale argument - if scale is None: - scale = numpy.ones(nVars) - else: - scale = numpy.atleast_1d(scale) - if len(scale) == 1: - scale = scale[0]*numpy.ones(nVars) - elif len(scale) == nVars: - pass - else: - raise Error("The length of the 'scale' argument to " - "addVarGroup is %d, but the number of " - "variables in nVars is %d."% ( - len(scale), nVars)) - - # ------ Process the offset argument - if offset is None: - offset = numpy.ones(nVars) - else: - offset = numpy.atleast_1d(offset) - if len(offset) == 1: - offset = offset[0]*numpy.ones(nVars) - elif len(offset) == nVars: - pass - else: - raise Error("The length of the 'offset' argument to " - "addVarGroup is %d, but the number of " - "variables in nVars is %d."% ( - len(offset), nVars)) - - # Determine if scalar i.e. it was called from addVar(): - scalar = kwargs.pop('scalar', False) - - # Now create all the variable objects - varList = [] - for iVar in range(nVars): - varName = name + '_%d'% iVar - varList.append(Variable(varName, type=type, value=value[iVar], - lower=lower[iVar], upper=upper[iVar], - scale=scale[iVar], offset=offset[iVar], - scalar=scalar, choices=choices)) - - if name in self.variables: - # Check that the variables happen to be the same - err = False - if not len(self.variables[name]) == len(varList): - raise Error("The supplied name '%s' for a variable group " - "has already been used!"% name) - for i in range(len(varList)): - if not varList[i] == self.variables[name][i]: - raise Error("The supplied name '%s' for a variable group " - "has already been used!"% name) - # We we got here, we know that the variables we wanted to - # add are **EXACTLY** the same so that's cool. We'll just - # overwrite with the varList below. - else: - # Finally we set the variable list - self.variables[name] = varList - - def delVar(self, name): - """ - Delete a variable or variable group - - Parameters - ---------- - name : str - Name of variable or variable group to remove - """ - try: - self.variables.pop(name) - except KeyError: - print('%s was not a valid design variable name.'% name) - - def _reduceDict(self, variables): - """ - This is a specialized function that is used to communicate - variables from dictionaries across the comm to ensure that all - processors end up with the same dictionary. It is used for - communicating the design variables and constraints, which may - be specified on different processors independently. - """ - - # Step 1: Gather just the key names: - allKeys = self.comm.gather(list(variables.keys()), root=0) - - # Step 2: Determine the unique set: - procKeys = {} - if self.comm.rank == 0: - # We can do the reduction efficiently using a dictionary: The - # algorithm is as follows: . Loop over the processors in order, - # and check if key is in procKeys. If it isn't, add with proc - # ID. This ensures that when we're done, the keys of 'procKeys' - # contains all the unique values we need, AND it has a single - # (lowest proc) that contains that key - for iProc in range(len(allKeys)): - for key in allKeys[iProc]: - if not key in procKeys: - procKeys[key] = iProc - - # Now pop any keys out with iProc = 0, since we want the - # list of ones NOT one the root proc - for key in list(procKeys.keys()): - if procKeys[key] == 0: - procKeys.pop(key) - - # Step 3. Now broadcast this back to everyone - procKeys = self.comm.bcast(procKeys, root=0) - - # Step 4. The required processors can send the variables - if self.comm.rank == 0: - for key in procKeys: - variables[key] = self.comm.recv(source=procKeys[key], tag=0) - else: - for key in procKeys: - if procKeys[key] == self.comm.rank: - self.comm.send(variables[key], dest=0, tag=0) - - # Step 5. And we finally broadcast the final list back: - variables = self.comm.bcast(variables, root=0) - - return variables - - def addObj(self, name, *args, **kwargs): - """ - Add Objective into Objectives Set - """ - - self.objectives[name] = Objective(name, *args, **kwargs) - - def addCon(self, name, *args, **kwargs): - """ - Convenience function. See addConGroup() for more information - """ - - self.addConGroup(name, 1, *args, **kwargs) - - def addConGroup(self, name, nCon, lower=None, upper=None, scale=1.0, - linear=False, wrt=None, jac=None): - """Add a group of variables into a variable set. This is the main - function used for adding variables to pyOptSparse. - - Parameters - ---------- - name : str - Constraint name. All names given to constraints must be unique - - nCon : int - The number of constraints in this group - - lower : scalar or array - The lower bound(s) for the constraint. If it is a scalar, - it is applied to all nCon constraints. If it is an array, - the array must be the same length as nCon. - - upper : scalar or array - The upper bound(s) for the constraint. If it is a scalar, - it is applied to all nCon constraints. If it is an array, - the array must be the same length as nCon. - - scale : scalar or array - - A scaling factor for the constraint. It is generally - advisable to have most optimization constraint around the - same order of magnitude. - - linear : bool - Flag to specify if this constraint is linear. If the - constraint is linear, both the 'wrt' and 'jac' keyword - arguments must be given to specify the constant portion of - the constraint jacobian. - - wrt : iterable (list, set, OrderedDict, array etc) - 'wrt' stand for stands for 'With Respect To'. This - specifies for what dvs have non-zero jacobian values - for this set of constraints. The order is not important. - - jac : dictionary - For linear and sparse non-linear constraints, the constraint - jacobian must be passed in. The structure is jac dictionary - is as follows: - - {'dvName1':, 'dvName2', , ...} - - They keys of the jacobian must correspond to the dvGroups - given in the wrt keyword argument. The dimensions of each - "chunk" of the constraint jacobian must be consistent. For - example, must have a shape of (nCon, nDvs) where - nDVs is the total number of design variables in - dvName1. may be a dense numpy array or it may be - scipy sparse matrix. However, it is *HIGHLY* recommended - that sparse constraints are supplied to pyOptSparse using - the pyOptSparse's simplified sparse matrix format. The - reason for this is that it is *impossible* for force scipy - sparse matrices to keep a fixed sparsity pattern; if the - sparsity pattern changes during an optimization, *IT WILL - FAIL*. - - The three simplified pyOptSparse sparse matrix formats are - summarized below: - - mat = {'coo':[row, col, data], 'shape':[nrow, ncols]} # A coo matrix - mat = {'csr':[rowp, colind, data], 'shape':[nrow, ncols]} # A csr matrix - mat = {'coo':[colp, rowind, data], 'shape':[nrow, ncols]} # A csc matrix - - Note that for nonlinear constraints (linear=False), the - values themselves in the matrices in jac do not matter, - but the sparsity structure **does** matter. It is - imperative that entries that will at some point have - non-zero entries have non-zero entries in jac - argument. That is, we do not let the sparsity structure of - the jacobian change throughout the optimization. This - stipulation is automatically checked internally. - - """ - - if name in self.constraints: - raise Error("The supplied name '%s' for a constraint group " - "has already been used."% name) - - # Simply add constraint object - self.constraints[name] = Constraint( - name, nCon, linear, wrt, jac, lower, upper, scale) - - def getDVs(self): - """ - Return a dictionary of the design variables. In most common - usage, this function is not required. - - Returns - ------- - outDVs : dict - The dictionary of variables. This is the same as 'x' that - would be used to call the user objective function. - """ - - outDVs = {} - for dvGroup in self.variables: - nvar = len(self.variables[dvGroup]) - # If it is a single DV, return a scalar rather than a numpy array - if nvar == 1: - var = self.variables[dvGroup][0] - outDVs[dvGroup] = var.value/var.scale + var.offset - else: - outDVs[dvGroup] = numpy.zeros(nvar) - for i in range(nvar): - var = self.variables[dvGroup][i] - outDVs[dvGroup][i] = var.value/var.scale + var.offset - - return outDVs - - def setDVs(self, inDVs): - """ - set the problem design variables from a dictionary. In most - common usage, this function is not required. - - Parameters - ---------- - inDVs : dict - The dictionary of variables. This dictionary is like the - 'x' that would be used to call the user objective - function. - """ - for dvGroup in self.variables: - if dvGroup in inDVs: - nvar = len(self.variables[dvGroup]) - scalar = self.dvOffset[dvGroup][2] - for i in range(nvar): - var = self.variables[dvGroup][i] - if scalar: - var.value = (float(inDVs[dvGroup])-var.offset)*var.scale - else: - # Must be an array - var.value = (inDVs[dvGroup][i]-var.offset)*var.scale - - def setDVsFromHistory(self, histFile, key=None): - """ - Set optimization variables from a previous optimization. This - is like a cold start, but some variables may have been added - or removed from the previous optimization. This will try to - set all variables it can. - - Parameters - ---------- - histFile : str - Filename of the history file to read - key : str - Key of the history file to use for the x values. The - default is None which will use the last x-value stored in - the dictionary. - """ - - if os.path.exists(histFile): - hist = SqliteDict(histFile) - if key is None: - key = hist['last'] - - self.setDVs(hist[key]['xuser']) - hist.close() - else: - raise Error("History file '%s' not found!."% histFile) - - def printSparsity(self, verticalPrint=False): - """ - This function prints an (ascii) visualization of the jacobian - sparsity structure. This helps the user visualize what - pyOptSparse has been given and helps ensure it is what the - user expected. It is highly recommended this function be - called before the start of every optimization to verify the - optimization problem setup. - - Parameters - ---------- - verticalPrint : bool - True if the design variable names in the header should be printed - vertically instead of horizontally. If true, this will make the - constraint Jacobian print out more narrow and taller. - - Warnings - -------- - This function is **collective** on the optProb comm. It is - therefore necessary to call this function on **all** - processors of the optProb comm. - - """ - self.finalizeDesignVariables() - self.finalizeConstraints() - - if self.comm.rank != 0: - return - - # Header describing what we are printing: - print('+'+'-'*78+'-'+'+') - print('|' + ' '*19 +'Sparsity structure of constraint Jacobian' + ' '*19 + '|') - print('+'+'-'*78+'-'+'+') - - # We will do this with a 2d numpy array of characters since it - # will make slicing easier - - # First determine the requried number of rows - nRow = 1 # Header - nRow += 1 # Line - maxConNameLen = 0 - hasLinear = False - for iCon in self.constraints: - nRow += 1 # Name - con = self.constraints[iCon] - maxConNameLen = max(maxConNameLen, - len(con.name)+6+int(numpy.log10(con.ncon))+1) - nRow += 1 # Line - - # And now the columns: - nCol = maxConNameLen - nCol += 2 # Space plus line - varCenters = [] - longestNameLength = 0 - for dvGroup in self.variables: - nvar = self.dvOffset[dvGroup][1] - self.dvOffset[dvGroup][0] - - # If printing vertically, put in a blank string of length 3 - if verticalPrint: - var_str = ' ' - - # Otherwise, put in the variable and its size - else: - var_str = dvGroup + ' (%d)'% nvar - - # Find the length of the longest name for design variables - longestNameLength = max(len(dvGroup), longestNameLength) - - varCenters.append(nCol + len(var_str)/2 + 1) - nCol += len(var_str) - nCol += 2 # Spaces on either side - nCol += 1 # Line - - txt = numpy.zeros((nRow, nCol), dtype=str) - txt[:, :] = ' ' - # Outline of the matrix on left and top - txt[1, maxConNameLen+1:-1] = '-' - txt[2:-1, maxConNameLen+1] = '|' - - # Print the variable names: - iCol = maxConNameLen + 2 - for dvGroup in self.variables: - nvar = self.dvOffset[dvGroup][1] - self.dvOffset[dvGroup][0] - if verticalPrint: - var_str = ' ' - else: - var_str = dvGroup + ' (%d)'% nvar - l = len(var_str) - txt[0, iCol+1 :iCol + l+1] = list(var_str) - txt[2:-1, iCol + l + 2] = '|' - iCol += l + 3 - - # Print the constraint names; - iRow = 2 - - for iCon in self.constraints: - con = self.constraints[iCon] - name = con.name - if con.linear: - name = name + '(L)' - - name = name + ' (%d)'% con.ncon - l = len(name) - # The name - txt[iRow, maxConNameLen-l:maxConNameLen] = list(name) - - # Now we write a 'X' if there is something there: - varKeys = list(self.variables.keys()) - for dvGroup in range(len(varKeys)): - if varKeys[dvGroup] in con.wrt: - txt[int(iRow), int(varCenters[dvGroup])] = 'X' - - # The separator - txt[iRow+1, maxConNameLen+1:] = '-' - iRow += 2 - - # Corners - just to make it nice :-) - txt[1, maxConNameLen+1] = '+' - txt[-1, maxConNameLen+1] = '+' - txt[1, -1] = '+' - txt[-1, -1] = '+' - - # If we're printing vertically, add an additional text array on top - # of the already created txt array - if verticalPrint: - - # It has the same width and a height corresponding to the length - # of the longest design variable name - newTxt = numpy.zeros((longestNameLength+1, nCol), dtype=str) - newTxt[:, :] = ' ' - txt = numpy.vstack((newTxt, txt)) - - # Loop through the letters in the longest design variable name - # and add the letters for each design variable - for i in range(longestNameLength+2): - - # Make a space between the name and the size - if i >= longestNameLength: - txt[i, :] = ' ' - - # Loop through each design variable - for j, dvGroup in enumerate(self.variables): - - # Print a letter in the name if any remain - if i < longestNameLength and i < len(dvGroup): - txt[i, int(varCenters[j])] = dvGroup[i] - - # Format and print the size of the design variable - elif i > longestNameLength: - var_str = '(' + str(self.dvOffset[dvGroup][1] - self.dvOffset[dvGroup][0]) + ')' - half_length = len(var_str) / 2 - k = int(varCenters[j]) - txt[i, int(k-half_length+1):int(k-half_length+1+len(var_str))] = list(var_str) - - for i in range(len(txt)): - print(''.join(txt[i])) - - def getDVConIndex(self, startIndex=1, printIndex=True): - """ - Return the index of a scalar DV/constraint, or the beginning - and end index (inclusive) of a DV/constraint array. - This is useful for looking at SNOPT gradient check output, - and the default startIndex=1 is for that purpose - """ - - # Get the begin and end index (inclusive) of design variables - # using infomation from finalizeDesignVariables() - dvIndex = OrderedDict() - # Loop over the actual DV names - for dvGroup in self.dvOffset: - ind0 = self.dvOffset[dvGroup][0] + startIndex - ind1 = self.dvOffset[dvGroup][1] + startIndex - # if it is a scalar DV, return just the index - if ind1 - ind0 == 1: - dvIndex[dvGroup] = [ind0] - else: - dvIndex[dvGroup] = [ind0, ind1-1] - - # Get the begin and end index (inclusive) of constraints - conIndex = OrderedDict() - conCounter = startIndex - for iCon in self.constraints: - n = self.constraints[iCon].ncon - if n == 1: - conIndex[iCon] = [conCounter] - else: - conIndex[iCon] = [conCounter, conCounter+n-1] - conCounter += n - - # Print them all to terminal - if printIndex and self.comm.rank == 0: - print('### DESIGN VARIABLES ###') - for dvGroup in dvIndex: - print(dvGroup, dvIndex[dvGroup]) - print('### CONSTRAINTS ###') - for conKey in conIndex: - print(conKey, conIndex[conKey]) - - return dvIndex, conIndex - -#======================================================================= -# All the functions from here down should not need to be called -# by the user. Most functions are public since the individual -# optimizers need to be able to call them -#======================================================================= - - def finalizeDesignVariables(self): - """ - Communicate design variables potentially from different - processors and form the DVOffset dict. This routine should be - called from the individual optimizers - """ - - # First thing we need is to determine the consistent set of - # variables from all processors. - self.variables = self._reduceDict(self.variables) - - dvCounter = 0 - self.dvOffset = OrderedDict() - - for dvGroup in self.variables: - n = len(self.variables[dvGroup]) - self.dvOffset[dvGroup] = [ - dvCounter, dvCounter + n, - self.variables[dvGroup][0].scalar] - dvCounter += n - self.ndvs = dvCounter - - def finalizeConstraints(self): - """ - **This function should not need to be called by the user** - - There are several functions for this routine: - - 1. Determine the number of constraints - - 2. Determine the final scaling array for the design variables - - 3. Determine if it is possible to return a complete dense - jacobian. Most of this time, we should be using the dictionary- - based return - """ - - # First thing we need is to determine the consistent set of - # constraints from all processors - self.constraints = self._reduceDict(self.constraints) - - # ---------------------------------------------------- - # Step 1. Determine number of constraints and scaling: - # ---------------------------------------------------- - - # Determine number of constraints - self.nCon = 0 - for iCon in self.constraints: - self.nCon += self.constraints[iCon].ncon - - # Loop over the constraints assigning the row start (rs) and - # row end (re) values. The actual ordering depends on if - # constraints are reordered or not. - rowCounter = 0 - conScale = numpy.zeros(self.nCon) - for iCon in self.constraints: - con = self.constraints[iCon] - con.finalize(self.variables, self.dvOffset, rowCounter) - rowCounter += con.ncon - conScale[con.rs:con.re] = con.scale - - if self.nCon > 0: - self.conScale = conScale - else: - self.conScale = None - - # ----------------------------------------- - # Step 2a. Assemble design variable scaling - # ----------------------------------------- - xscale = [] - for dvGroup in self.variables: - for var in self.variables[dvGroup]: - xscale.append(var.scale) - self.invXScale = 1.0/numpy.array(xscale) - - # ----------------------------------------- - # Step 2a. Assemble design variable offset - # ----------------------------------------- - xoffset = [] - for dvGroup in self.variables: - for var in self.variables[dvGroup]: - xoffset.append(var.offset) - self.xOffset = numpy.array(xoffset) - - # -------------------------------------- - # Step 3. Map objective names to indices - # -------------------------------------- - for idx, objKey in enumerate(self.objectives): - self.objectiveIdx[objKey] = idx - - # --------------------------------------------- - # Step 4. Final jacobian for linear constraints - # --------------------------------------------- - for iCon in self.constraints: - con = self.constraints[iCon] - if con.linear: - data = [] - row = [] - col = [] - - for dvGroup in con.jac: - # ss means 'start - stop' - ss = self.dvOffset[dvGroup] - - row.extend(con.jac[dvGroup]['coo'][IROW]) - col.extend(con.jac[dvGroup]['coo'][ICOL] +ss[0]) - data.extend(con.jac[dvGroup]['coo'][IDATA]) - - # Now create a coo, convert to CSR and store - con.linearJacobian = coo_matrix((data, (row, col)), - shape=[con.ncon, self.ndvs]).tocsr() - - def getOrdering(self, conOrder, oneSided, noEquality=False): - """ - Internal function that is used to produce a index list that - reorders the constraints the way a particular optimizer needs. - - Parameters - ---------- - conOrder : list - This must contain the following 4 strings: 'ni', 'li', - 'ne', 'le' which stand for nonlinear inequality, linear - inequality, nonlinear equality and linear equality. This - defines the order that the optimizer wants the constraints - - oneSided : bool - Flag to do all constraints as one-sided instead of two - sided. Most optimizers need this but some can deal with the - two-sided constraints properly (snopt and ipopt for - example) - - noEquality : bool - Flag to split equality constraints into two inequality - constraints. Some optimizers (CONMIN for example) can't do - equality constraints explicitly. - """ - - # Now for the fun part determine what *actual* order the - # constraints need to be in: We recognize the following - # constraint types: - # ne : nonlinear equality - # ni : nonlinear inequality - # le : linear equality - # li : linear inequality - - # The oneSided flag determines if we use the one or two sided - # constraints. The result of the following calculation is the - # a single index vector that that maps the natural ordering of - # the constraints to the order that optimizer has - # requested. This will be returned so the optimizer can do - # what they want with it. - - if self.nCon == 0: - if self.dummyConstraint: - return [], [-INFINITY], [INFINITY], None - else: - return numpy.array([], 'd') - - indices = [] - fact = [] - lower = [] - upper = [] - - for conType in conOrder: - for iCon in self.constraints: - con = self.constraints[iCon] - # Make the code below easier to read: - econ = con.equalityConstraints - if oneSided: - icon = con.oneSidedConstraints - else: - icon = con.twoSidedConstraints - - if conType == 'ne' and not con.linear: - if noEquality: - # Expand Equality constraint to two: - indices.extend(con.rs + econ['ind']) - fact.extend(econ['fact']) - lower.extend(econ['value']) - upper.extend(econ['value']) - #....And the other side - indices.extend(con.rs + econ['ind']) - fact.extend(-1.0*econ['fact']) - lower.extend(econ['value']) - upper.extend(econ['value']) - - else: - indices.extend(con.rs + econ['ind']) - fact.extend(econ['fact']) - lower.extend(econ['value']) - upper.extend(econ['value']) - - if conType == 'ni' and not con.linear: - indices.extend(con.rs + icon['ind']) - fact.extend(icon['fact']) - lower.extend(icon['lower']) - upper.extend(icon['upper']) - - if conType == 'le' and con.linear: - if noEquality: - # Expand Equality constraint to two: - indices.extend(con.rs + econ['ind']) - fact.extend(econ['fact']) - lower.extend([-INFINITY]*len(econ['fact'])) - upper.extend(econ['value']) - #....And the other side - indices.extend(con.rs + econ['ind']) - fact.extend(-1.0*econ['fact']) - lower.extend([-INFINITY]*len(econ['fact'])) - upper.extend(-econ['value']) - else: - indices.extend(con.rs + econ['ind']) - fact.extend(econ['fact']) - lower.extend(econ['value']) - upper.extend(econ['value']) - - if conType == 'li' and con.linear: - indices.extend(con.rs + icon['ind']) - fact.extend(icon['fact']) - lower.extend(icon['lower']) - upper.extend(icon['upper']) - - if len(fact) == 0: - fact = None - return numpy.array(indices), numpy.array(lower), numpy.array(upper), fact - - def processX(self, x): - """ - **This function should not need to be called by the user** - - Take the flattened array of variables in 'x' and return a - dictionary of variables keyed on the name of each variable. - - Parameters - ---------- - x : array - Flattened array from optimizer - """ - xg = OrderedDict() - imax = 0 - for dvGroup in self.variables: - istart = self.dvOffset[dvGroup][0] - iend = self.dvOffset[dvGroup][1] - scalar = self.dvOffset[dvGroup][2] - imax = max(imax, iend) - try: - if scalar: - xg[dvGroup] = x[..., istart] - else: - xg[dvGroup] = x[..., istart:iend].copy() - except IndexError: - raise Error("Error processing x. There " - "is a mismatch in the number of variables.") - if imax != self.ndvs: - raise Error("Error processing x. There " - "is a mismatch in the number of variables.") - return xg - - def deProcessX(self, x): - """ - **This function should not need to be called by the user** - - Take the dictionary form of x and convert back to flattened - array. - - Parameters - ---------- - x : dict - Dictionary form of variables - - Returns - ------- - x_array : array - Flattened array of variables - """ - - x_array = numpy.zeros(self.ndvs) - imax = 0 - for dvGroup in self.variables: - istart = self.dvOffset[dvGroup][0] - iend = self.dvOffset[dvGroup][1] - imax = max(imax, iend) - scalar = self.dvOffset[dvGroup][2] - try: - if scalar: - x_array[..., istart] = x[dvGroup] - else: - x_array[..., istart:iend] = x[dvGroup] - except IndexError: - raise Error("Error deprocessing x. There " - "is a mismatch in the number of variables.") - if imax != self.ndvs: - raise Error("Error deprocessing x. There is a mismatch in the" - " number of variables.") - - return x_array - - def processObjective(self, funcs, scaled=True): - """ - **This function should not need to be called by the user** - - This is currently just a stub-function. It is here since it - the future we may have to deal with multiple objectives so - this function will deal with that - - Parameters - ---------- - funcs : dictionary of function values - - Returns - ------- - obj : float or array - Processed objective(s). - """ - fobj = [] - for objKey in self.objectives.keys(): - if objKey in funcs: - if self.bulk is None: - try: - f = numpy.squeeze(funcs[objKey]).item() - except ValueError: - raise Error("The objective return value, '%s' must be a " - "scalar!"% objKey) - else: - f = numpy.squeeze(funcs[objKey]) - if f.shape != (self.bulk,): - raise Error("Expected %d return values for '%s', but received %d!" - % (self.bulk, objKey, f.shape)) - # Store objective for printing later - self.objectives[objKey].value = f - if scaled: - f *= self.objectives[objKey].scale - fobj.append(f) - else: - raise Error("The key for the objective, '%s' was not found." % - objKey) - - # Finally squeeze back out so we get a scalar for a single objective - return numpy.squeeze(fobj) - - def processConstraints(self, fcon_in, scaled=True, dtype='d', natural=False): - """ - **This function should not need to be called by the user** - - Parameters - ---------- - fcon_in : dict - Dictionary of constraint values - - scaled : bool - Flag specifying if the returned array should be scaled by - the pyOpt scaling. The only type this is not true is - when the automatic derivatives are used - - dtype : str - String specifying the data type to return. Normally this - is 'd' for a float. The complex-step derivative - computations will call this function with 'D' to ensure - that the complex perturbations pass through correctly. - - natural : bool - Flag to specify if the data should be returned in the - natural ordering. This is only used when computing - gradient automatically with FD/CS. - """ - - if self.dummyConstraint: - return numpy.array([0]) - - # We REQUIRE that fcon_in is a dict: - if self.bulk is not None: - fcon = numpy.zeros((self.bulk, self.nCon), dtype=dtype) - else: - fcon = numpy.zeros(self.nCon, dtype=dtype) - for iCon in self.constraints: - con = self.constraints[iCon] - if iCon in fcon_in: - - # Make sure it is at least 1-dimensional: - c = numpy.atleast_1d(fcon_in[iCon]) - if dtype == 'd': - c = numpy.real(c) - # Make sure it is the correct size: - if c.shape[-1] == self.constraints[iCon].ncon: - fcon[..., con.rs:con.re] = c - else: - raise Error("%d constraint values were returned in " - "%s, but expected %d." % ( - len(fcon_in[iCon]), iCon, - self.constraints[iCon].ncon)) - - # Store constraint values for printing later - con.value = copy.copy(c) - else: - raise Error("No constraint values were found for the " - "constraint '%s'."% iCon) - - # Perform scaling on the original jacobian: - if scaled: - fcon = self.conScale*fcon - - if natural: - return fcon - else: - if self.nCon > 0: - fcon = fcon[..., self.jacIndices] - fcon = self.fact*fcon - self.offset - return fcon - else: - return fcon - - def deProcessConstraints(self, fcon_in, scaled=True, dtype='d', natural=False): - """ - **This function should not need to be called by the user** - - Parameters - ---------- - fcon_in : array - Array of constraint values to be converted into a dictionary - - scaled : bool - Flag specifying if the returned array should be scaled by - the pyOpt scaling. The only type this is not true is - when the automatic derivatives are used - - dtype : str - String specifying the data type to return. Normally this - is 'd' for a float. The complex-step derivative - computations will call this function with 'D' to ensure - that the complex perturbations pass through correctly. - - natural : bool - Flag to specify if the input data is in the - natural ordering. This is only used when computing - gradient automatically with FD/CS. - """ - - if self.dummyConstraint: - return {'dummy':0} - - if not natural: - if self.nCon > 0: - fcon_in += self.offset - # Since self.fact elements are unit magnitude and the - # values are either 1 or -1... - fcon_in = self.fact * fcon_in - # Undo the ordering - fcon_in = fcon_in[self.jacIndicesInv] - - # Perform constraint scaling - if scaled: - fcon_in = fcon_in*self.conScale - - # We REQUIRE that fcon_in is an array: - fcon = {} - index = 0 - for iCon in self.constraints: - con = self.constraints[iCon] - fcon[iCon] = fcon_in[..., con.rs:con.re] - - return fcon - - def evaluateLinearConstraints(self, x, fcon): - """ - This function is required for optimizers that do not explicitly - treat the linear constraints. For those optimizers, we will - evaluate the linear constraints here. We place the values of - the linear constraints in the fcon dictionary such that it - appears as if the user evaluated these constraints. - - Parameters - ---------- - x : array - This must be the processed x-vector from the optimizer - - fcon : dict - Dictionary of the constraints. The linear constraints are - to be added to this dictionary. - """ - - # This is actually pretty easy; it's just a matvec with the - # proper linearJacobian entry we've already computed - for iCon in self.constraints: - if self.constraints[iCon].linear: - fcon[iCon] = self.constraints[iCon].linearJacobian.dot(x) - - def processObjectiveGradient(self, funcsSens): - """ - **This function should not need to be called by the user** - - This generic function is used to assemble the objective - gradient(s) - - Parameters - ---------- - funcsSens : dict - Dictionary of all function gradients. Just extract the - objective(s) we need here. - """ - - dvGroups = set(self.variables.keys()) - - nobj = len(self.objectives) - gobj = numpy.zeros((nobj, self.ndvs)) - - cond = False - if six: - # this version is required for python 3 compatibility - cond = isinstance(next(iterkeys(funcsSens)), str) - else: - # fallback if six is not available - cond = isinstance(funcsSens.keys()[0], str) - - if cond: - iObj = 0 - for objKey in self.objectives.keys(): - if objKey in funcsSens: - for dvGroup in funcsSens[objKey]: - if dvGroup in dvGroups: - # Now check that the array is the correct length: - ss = self.dvOffset[dvGroup] - tmp = numpy.array(funcsSens[objKey][dvGroup]).squeeze() - if tmp.size == ss[1]-ss[0]: - # Everything checks out so set: - gobj[iObj, ss[0]:ss[1]] = tmp * self.objectives[objKey].scale - else: - raise Error("The shape of the objective derivative " - "for dvGroup '%s' is the incorrect " - "length. Expecting a shape of %s but " - "received a shape of %s."% ( - dvGroup, (ss[1]-ss[0],), - funcsSens[objKey][dvGroup].shape)) - else: - raise Error("The dvGroup key '%s' is not valid"% dvGroup) - else: - raise Error("The key for the objective gradient, '%s', was not found." % - objKey) - iObj += 1 - else: # Then it must be a tuple; assume flat dict - for (objKey, dvGroup), _ in iteritems(funcsSens): - if objKey in self.objectives.keys(): - try: - iObj = self.objectiveIdx[objKey] - except KeyError: - raise Error("The key for the objective gradient, '%s', was not found." % - objKey) - try: - ss = self.dvOffset[dvGroup] - except KeyError: - raise Error("The dvGroup key '%s' is not valid"% dvGroup) - tmp = numpy.array(funcsSens[objKey, dvGroup]).squeeze() - if tmp.size == ss[1]-ss[0]: - # Everything checks out so set: - gobj[iObj, ss[0]:ss[1]] = tmp * self.objectives[objKey].scale - else: - raise Error("The shape of the objective derivative " - "for dvGroup '%s' is the incorrect " - "length. Expecting a shape of %s but " - "received a shape of %s."% ( - dvGroup, (ss[1]-ss[0],), - funcsSens[objKey, dvGroup].shape)) - - # Note that we looped over the keys in funcsSens[objKey] - # and not the variable keys since a variable key not in - # funcsSens[objKey] will just be left to zero. We have - # implicitly assumed that the objective gradient is dense - # and any keys that are provided are simply zero. - # end (objective keys) - - # Do column scaling (dv scaling) - gobj = self.invXScale * gobj - - # Finally squeeze back out so we get a 1D vector for a single objective - return numpy.squeeze(gobj) - - def processConstraintJacobian(self, gcon): - """ - **This function should not need to be called by the user** - - This generic function is used to assemble the entire - constraint jacobian. The order of the constraint jacobian is - in 'natural' ordering, that is the order the constraints have - been added (mostly; since it can be different when constraints - are added on different processors). - - The input is gcon, which is dict or an array. The array format - should only be used when the pyOpt_gradient class is used - since this results in a dense (and correctly oriented) - jacobian. The user should NEVER return a dense jacobian since - this extremely fickle and easy to break. The dict 'gcon' must - contain only the non-linear constraints jacobians; the linear - ones will be added automatically. - - Parameters - ---------- - gcon : array or dict - Constraint gradients. Either a complete 2D array or a nested - dictionary of gradients given with respect to the variables. - - Returns - ------- - gcon : dict with csr data - Return the jacobian in a sparse csr format. - can be easily converted to csc, coo or dense format as - required by individual optimizers - """ - - # We don't have constraints at all! However we *may* have to - # include a dummy constraint: - if self.nCon == 0: - if self.dummyConstraint: - return convertToCSR(numpy.zeros((1, self.ndvs))) - else: - return numpy.zeros((0, self.ndvs), 'd') - - # For simplicity we just add the linear constraints into gcon - # so they can be processed along with the rest: - for iCon in self.constraints: - if self.constraints[iCon].linear: - gcon[iCon] = copy.deepcopy(self.constraints[iCon].jac) - - # We now know we must process as a dictionary. Below are the - # lists for the matrix entries. - data = [] - row = [] - col = [] - ii = 0 - - # Otherwise, process constraints in the dictionary form. - # Loop over all constraints: - for iCon in self.constraints: - con = self.constraints[iCon] - - # Now loop over all required keys for this constraint: - for dvGroup in con.wrt: - # ss means 'start - stop' - ss = self.dvOffset[dvGroup] - ndvs = ss[1]-ss[0] - - gotDerivative = False - try: # Try using a nested dictionary return - if dvGroup in gcon[iCon]: - tmp = convertToCOO(gcon[iCon][dvGroup]) - gotDerivative = True - except KeyError: - try: # Using tuple dictornary return - tmp = convertToCOO(gcon[iCon, dvGroup]) - gotDerivative = True - except KeyError: - raise Error('The constraint jacobian entry for "{}" with respect to "{}"' - ', as was defined in addConGroup(), was not found in' - ' constraint jacobian dictionary provided.'.format(con.name, dvGroup)) - if not gotDerivative: - # All keys for this constraint must be returned - # since the user has explictly specified the wrt. - if not con.partialReturnOk: - raise Error( - "Constraint '%s' was expecting a jacobain with " - "respect to dvGroup '%s' as was supplied in " - "addConGroup(). This was not found in the " - "constraint jacobian dictionary"% ( - con.name, dvGroup)) - else: - # This key is not returned. Just use the - # stored jacobian that contains zeros - tmp = con.jac[dvGroup] - - # Now check that the jacobian is the correct shape - if not(tmp['shape'][0] == con.ncon and tmp['shape'][1] == ndvs): - raise Error("The shape of the supplied constraint " - "jacobian for constraint %s with respect to %s " - "is incorrect. " - "Expected an array of shape (%d, %d), but " - "received an array of shape (%d, %d)."% ( - con.name, dvGroup, con.ncon, ndvs, - tmp['shape'][0], tmp['shape'][1])) - - # Now check that supplied coo matrix has same length - # of data array - if len(tmp['coo'][2]) != len(con.jac[dvGroup]['coo'][2]): - raise Error("The number of nonzero elements for " - "constraint group '%s' with respect to %s " - "was not the correct size. The supplied " - "jacobian has %d nonzero " - "entries, but must contain %d nonzero " - "entries." % (con.name, dvGroup, len(tmp['coo'][2]), - len(con.jac[dvGroup]['coo'][2]))) - - # Include data from this jacobian chunk - data.append(tmp['coo'][IDATA]) - row.append(tmp['coo'][IROW] + ii) - col.append(tmp['coo'][ICOL] + ss[0]) - # end for (dvGroup in constraint) - ii += con.ncon - # end for (constraint loop) - - # now flatten all the data into a single array - data = numpy.concatenate(data).ravel() - row = numpy.concatenate(row).ravel() - col = numpy.concatenate(col).ravel() - - # Finally, construct CSR matrix from COO data and perform - # row and column scaling. - if self._jac_map_coo_to_csr is None: - gcon = {'coo':[row, col, numpy.array(data)], - 'shape':[self.nCon, self.ndvs]} - self._jac_map_coo_to_csr = mapToCSR(gcon) - - gcon = {'csr': (self._jac_map_coo_to_csr[IROW], - self._jac_map_coo_to_csr[ICOL], - numpy.array(data)[self._jac_map_coo_to_csr[IDATA]]), - 'shape':[self.nCon, self.ndvs]} - - scaleRows(gcon, self.conScale) - scaleColumns(gcon, self.invXScale) - - return gcon - - def __str__(self): - """ - Print Structured Optimization Problem - """ - TOL = 1.0E-6 - - text = '\n\nOptimization Problem -- {0}\n{1}\n Objective Function: {2}\n\n'.format(self.name, '='*80, self.objFun.__name__) - text += '\n Objectives\n' - - num_c = max([len(obj) for obj in self.objectives]) - fmt = ' {0:>7s} {1:{width}s} {2:>14s} {3:>14s}\n' - text += fmt.format('Index', 'Name', 'Value', 'Optimum', width=num_c) - fmt = ' {0:>7d} {1:{width}s} {2:>14.6E} {3:>14.6E}\n' - for idx, name in enumerate(self.objectives): - obj = self.objectives[name] - text += fmt.format(idx, obj.name, obj.value, obj.optimum, width=num_c) - - # Find the longest name in the variables - num_c = 0 - for varname in self.variables: - for var in self.variables[varname]: - num_c = max(len(var.name), num_c) - - fmt = ' {0:>7s} {1:{width}s} {2:>4s} {3:>14} {4:>14} {5:>14} {6:>8s}\n' - text += '\n Variables (c - continuous, i - integer, d - discrete)\n' - text += fmt.format('Index', 'Name', 'Type', 'Lower Bound', 'Value', - 'Upper Bound', 'Status', width=num_c) - fmt = ' {0:7d} {1:{width}s} {2:>4s} {3:14.6E} {4:14.6E} {5:14.6E} {6:>8s}\n' - - idx = 0 - for varname in self.variables: - for var in self.variables[varname]: - if var.type in ['c','i']: - value = var.value - lower = var.lower if var.lower is not None else -1.0E20 - upper = var.upper if var.upper is not None else 1.0E20 - status = '' - dL = value - lower - if dL > TOL: - pass - elif dL < -TOL: - # In violation of lower bound - status += 'L' - else: - # Active lower bound - status += 'l' - dU = upper - value - if dU > TOL: - pass - elif dU < -TOL: - # In violation of upper bound - status += 'U' - else: - # Active upper bound - status += 'u' - elif var.type == 'd': - choices = var.choices - value = choices[int(var.value)] - lower = min(choices) - upper = max(choices) - status = '' - else: - raise ValueError('Unrecognized type for variable {0}: {1}'.format(var.name, var.type)) - - text += fmt.format(idx, var.name, var.type, lower, value, upper, status, - width=num_c) - idx += 1 - - if len(self.constraints) > 0: - - try: - pi = self.pi - pi_label = 'Pi' - except AttributeError: - # the optimizer did not set the lagrange multipliers so set them to something obviously wrong - n_c_total = sum([self.constraints[c].ncon for c in self.constraints]) - pi = [9e100,]*n_c_total - pi_label = 'Pi(N/A)' - - text += '\n Constraints (i - inequality, e - equality)\n' - # Find the longest name in the constraints - num_c = max([len(self.constraints[i].name) for i in self.constraints]) - fmt = ' {0:>7s} {1:{width}s} {2:>4s} {3:>14} {4:>14} {5:>14} {6:>8s} {7:>8s}\n' - text += fmt.format('Index', 'Name', 'Type', 'Lower', 'Value', 'Upper', 'Status', pi_label, width=num_c) - fmt = ' {0:7d} {1:{width}s} {2:>4s} {3:>14.6E} {4:>14.6E} {5:>14.6E} {6:>8s} {7:>14.5E}\n' - idx = 0 - for iCon in self.constraints: - c = self.constraints[iCon] - for j in range(c.ncon): - lower = c.lower[j] if c.lower[j] is not None else -1.0E20 - upper = c.upper[j] if c.upper[j] is not None else 1.0E20 - value = c.value[j] - lagrange_multiplier = pi[j] - status = '' - typ = 'e' if j in c.equalityConstraints['ind'] else 'i' - if typ == 'e': - if abs(value - upper) > TOL: - status = 'E' - else: - dL = value - lower - if dL > TOL: - pass - elif dL < -TOL: - # In violation of lower bound - status += 'L' - else: - # Active lower bound - status += 'l' - - dU = upper - value - if dU > TOL: - pass - elif dU < -TOL: - # In violation of upper bound - status += 'U' - else: - # Active upper bound - status += 'u' - - text += fmt.format(idx, c.name, typ, lower, value, upper, status, pi[idx], width=num_c) - idx += 1 - - return text - -#============================================================================== -# Optimization Test -#============================================================================== -if __name__ == '__main__': - - print('Testing Optimization...') - optprob = Optimization('Optimization Problem', {}) diff --git a/pyoptsparse/pyoptsparse/pyOpt_optimizer.py b/pyoptsparse/pyoptsparse/pyOpt_optimizer.py deleted file mode 100644 index bc53b816e..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_optimizer.py +++ /dev/null @@ -1,900 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_optimizer - -Holds the Python Design Optimization Classes (base and inherited). - -Copyright (c) 2008-2013 by pyOpt Developers -All rights reserved. -Revision: 1.1 $Date: 08/05/2008 21:00$ - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) -""" -from __future__ import print_function -# ============================================================================= -# Imports -# ============================================================================= -import os -import time -import copy -import numpy -from .pyOpt_gradient import Gradient -from .pyOpt_error import Error, pyOptSparseWarning -from .pyOpt_history import History -from .pyOpt_solution import Solution -from .pyOpt_optimization import INFINITY -from .pyOpt_utils import convertToDense, convertToCOO, extractRows, \ - mapToCSC, scaleRows, IDATA -eps = numpy.finfo(1.0).eps - -# ============================================================================= -# Optimizer Class -# ============================================================================= -class Optimizer(object): - """ - Base optimizer class - - Parameters - ---------- - name : str - Optimizer name - category : str - Typically local or global - defOptions : dictionary - A dictionary containing the default options - informs : dict - Dictionary of the inform codes - """ - def __init__(self, name=None, category=None, defOptions=None, - informs=None, **kwargs): - - self.name = name - self.category = category - self.options = {} - self.options['defaults'] = defOptions - self.informs = informs - self.callCounter = 0 - self.sens = None - # Initialize Options - for key in defOptions: - self.options[key] = defOptions[key] - - koptions = kwargs.pop('options', {}) - for key in koptions: - self.setOption(key, koptions[key]) - - self.optProb = None - # Default options: - self.appendLinearConstraints = False - self.jacType = 'dense' - self.unconstrained = False - self.userObjTime = 0.0 - self.userSensTime = 0.0 - self.interfaceTime = 0.0 - self.userObjCalls = 0 - self.userSensCalls = 0 - self.storeSens = True - - # Cache storage - self.cache = {'x': None, 'fobj': None, 'fcon': None, - 'gobj': None, 'gcon': None} - - # A second-level cache for optimizers that require callbacks - # for each constraint. (eg. PSQP, FSQP, etc) - self.storedData = {} - self.storedData['x'] = None - - # Create object to pass information about major iterations. - # Only relevant for SNOPT. - self.iu0 = 0 - - # Store the jacobian conversion maps - self._jac_map_csr_to_csc = None - - def _clearTimings(self): - """Clear timings and call counters""" - self.userObjTime = 0.0 - self.userSensTime = 0.0 - self.interfaceTime = 0.0 - self.userObjCalls = 0 - self.userSensCalls = 0 - - def _setSens(self, sens, sensStep, sensMode): - """ - Common function to setup sens function - """ - - # If we have SNOPT set derivative level to 3...it will be - # reset if necessary - if self.name in ['SNOPT']: - # SNOPT is the only one where None is ok. - self.setOption('Derivative level', 3) - - # Next we determine what to what to do about - # derivatives. We must have a function or we use FD or CS: - if sens is None: - if self.name in ['SNOPT']: - # SNOPT is the only one where None is ok. - self.setOption('Derivative level', 0) - self.sens = None - else: - raise Error("'None' value given for sens. Must be one " - " of 'FD', 'FDR', 'CD', 'CDR', 'CS' or a user supplied function.") - elif hasattr(sens, '__call__'): - # We have function handle for gradients! Excellent! - self.sens = sens - elif sens.lower() in ['fd', 'fdr', 'cd', 'cdr', 'cs']: - # Create the gradient class that will operate just like if - # the user supplied function - self.sens = Gradient(self.optProb, sens.lower(), sensStep, - sensMode, self.optProb.comm) - else: - raise Error("Unknown value given for sens. Must be None, 'FD', " - "'FDR', 'CD', 'CDR', 'CS' or a python function handle") - - def _setHistory(self, storeHistory, hotStart): - """ - Generic routine for setting up the hot start information - - Parameters - ---------- - storeHistory : str - File for possible history file. Or None if not writing file. - - hotStart : str - Filename for history file for hot start - """ - # By default no hot start - self.hotStart = None - - # Determine if we want to do a hot start: - if hotStart is not None: - # Now, if if the hot start file and the history are - # the SAME, we don't allow that. We will create a copy - # of the hotStart file and use *that* instead. - import tempfile - import shutil - if storeHistory == hotStart: - if os.path.exists(hotStart): - fname = tempfile.mktemp() - shutil.copyfile(storeHistory, fname) - self.hotStart = History(fname, temp=True, flag='r') - else: - if os.path.exists(hotStart): - self.hotStart = History(hotStart, temp=False, flag='r') - else: - pyOptSparseWarning('Hot start file does not exist. \ - Performing a regular start') - - self.storeHistory = False - if storeHistory: - self.hist = History(storeHistory) - self.storeHistory = True - - if hotStart is not None: - varInfo = self.hotStart.readData('varInfo') - conInfo = self.hotStart.readData('conInfo') - if varInfo is not None: - self.hist.writeData('varInfo', varInfo) - if conInfo is not None: - self.hist.writeData('conInfo', conInfo) - - def _masterFunc(self, x, evaluate): - """ - This is the master function that **ALL** optimizers call from - the specific signature functions. The reason for this is that - we can generically do the hot-start replay, history storage, - timing and possibly caching once for all optimizers. It also - takes care of the MPI communication that allows the optimizer - to run on one process only, but within a larger MPI context. - - It does add one additional level of call, but we think it is - well worth it for reduce code duplication - - Parameters - ---------- - x : array - This is the raw x-array data from the optimizer - evaluate : list of strings - This list contains at least one of 'fobj', 'fcon', 'gobj' - or 'gcon'. This list tells this function which of the - values is required on return - """ - - # We are hot starting, we should be able to read the required - # information out of the hot start file, process it and then - # fire it back to the specific optimizer - timeA = time.time() - if self.hotStart: - - # This is a very inexpensive check to see if point exists - if self.hotStart.pointExists(self.callCounter): - # Read the actual data for this point: - data = self.hotStart.read(self.callCounter) - - # Get the x-value and (de)process - xuser = self.optProb.deProcessX(data['xuser']) - - # Validated x-point point to use: - xScaled = x*self.optProb.invXScale + self.optProb.xOffset - if numpy.linalg.norm(xScaled - xuser) < eps: - - # However, we may need a sens that *isn't* in the - # the dictionary: - funcs = None - funcsSens = None - validPoint = True - if 'fobj' in evaluate or 'fcon' in evaluate: - funcs = data['funcs'] - - if 'gobj' in evaluate or 'gcon' in evaluate: - if 'funcsSens' in data: - funcsSens = data['funcsSens'] - else: - validPoint = False - - # Only continue if valid: - if validPoint: - if self.storeHistory: - # Just dump the (exact) dictionary back out: - self.hist.write(self.callCounter, data) - - fail = data['fail'] - returns = [] - - # Process constraints/objectives - if funcs is not None: - self.optProb.evaluateLinearConstraints(xScaled, funcs) - fcon = self.optProb.processConstraints(funcs) - fobj = self.optProb.processObjective(funcs) - if 'fobj' in evaluate: - returns.append(fobj) - if 'fcon' in evaluate: - returns.append(fcon) - - # Process gradients if we have them - if funcsSens is not None: - gobj = self.optProb.processObjectiveGradient(funcsSens) - gcon = self.optProb.processConstraintJacobian(funcsSens) - gcon = self._convertJacobian(gcon) - - if 'gobj' in evaluate: - returns.append(gobj) - if 'gcon' in evaluate: - returns.append(gcon) - - # We can now safely increment the call counter - self.callCounter += 1 - returns.append(fail) - self.interfaceTime += time.time()-timeA - return returns - # end if (valid point -> all data present) - # end if (x's match) - # end if (point exists) - - # We have used up all the information in hot start so we - # can close the hot start file - self.hotStart.close() - self.hotStart = None - # end if (hot starting) - - # Now we have to actually run our function...this is where the - # MPI gets a little tricky. Up until now, only the root proc - # has called up to here...the rest of them are waiting at a - # broadcast to know what to do. - - args = [x, evaluate] - - # Broadcast the type of call (0 means regular call) - self.optProb.comm.bcast(0, root=0) - - # Now broadcast out the required arguments: - self.optProb.comm.bcast(args) - - result = self._masterFunc2(*args) - self.interfaceTime += time.time()-timeA - return result - - def _masterFunc2(self, x, evaluate, writeHist=True): - """ - Another shell function. This function is now actually called - on all the processors. - """ - - # Our goal in this function is to return the values requested - # in 'evaluate' for the corresponding x. We have to be a - # little cheeky here since some optimizers will make multiple - # call backs with the same x, one for the objective and one - # for the constraint. We therefore at the end of each function - # or sensitivity call we cache the x value and the fobj, fcon, - # gobj, and gcon values such that on the next pass we can just - # read them and return. - - xScaled = self.optProb.invXScale * x + self.optProb.xOffset - xuser = self.optProb.processX(xScaled) - - masterFail = False - - # Set basic parameters in history - hist = {'xuser': xuser} - returns = [] - # Start with fobj: - tmpObjCalls = self.userObjCalls - tmpSensCalls = self.userSensCalls - if 'fobj' in evaluate: - if numpy.linalg.norm(x-self.cache['x']) > eps: - timeA = time.time() - args = self.optProb.objFun(xuser) - if isinstance(args, tuple): - funcs = args[0] - fail = args[1] - elif args is None: - raise Error("No return values from user supplied " - "objective function. The function must " - "return \"funcs\" *OR* \"funcs, fail\"") - else: - funcs = args - fail = False - self.userObjTime += time.time()-timeA - if self.optProb.bulk is None: - self.userObjCalls += 1 - else: - self.userObjCalls += self.optProb.bulk - # User values stored is immediately - self.cache['funcs'] = copy.deepcopy(funcs) - - # Process constraints/objectives - self.optProb.evaluateLinearConstraints(xScaled, funcs) - fcon = self.optProb.processConstraints(funcs) - fobj = self.optProb.processObjective(funcs) - # Now clear out gobj and gcon in the cache since these - # are out of date and set the current ones - self.cache['gobj'] = None - self.cache['gcon'] = None - self.cache['x'] = x.copy() - self.cache['fobj'] = copy.deepcopy(fobj) - self.cache['fcon'] = copy.deepcopy(fcon) - - # Update fail flag - masterFail = masterFail or fail - - # fobj is now in cache - returns.append(self.cache['fobj']) - hist['funcs'] = self.cache['funcs'] - - if 'fcon' in evaluate: - if numpy.linalg.norm(x-self.cache['x']) > eps: - timeA = time.time() - - args = self.optProb.objFun(xuser) - if isinstance(args, tuple): - funcs = args[0] - fail = args[1] - elif args is None: - raise Error("No return values from user supplied " - "objective function. The function must " - "return \"funcs\" *OR* \"funcs, fail\"") - else: - funcs = args - fail = False - - self.userObjTime += time.time()-timeA - self.userObjCalls += 1 - # User values stored is immediately - self.cache['funcs'] = copy.deepcopy(funcs) - - # Process constraints/objectives - self.optProb.evaluateLinearConstraints(xScaled, funcs) - fcon = self.optProb.processConstraints(funcs) - fobj = self.optProb.processObjective(funcs) - # Now clear out gobj and gcon in the cache since these - # are out of date and set the current ones - self.cache['gobj'] = None - self.cache['gcon'] = None - self.cache['x'] = x.copy() - self.cache['fobj'] = copy.deepcopy(fobj) - self.cache['fcon'] = copy.deepcopy(fcon) - - # Update fail flag - masterFail = masterFail or fail - - # fcon is now in cache - returns.append(self.cache['fcon']) - hist['funcs'] = self.cache['funcs'] - - if 'gobj' in evaluate: - if numpy.linalg.norm(x-self.cache['x']) > eps: - # Previous evaluated point is *different* than the - # point requested for the derivative. Recursively call - # the routine with ['fobj', and 'fcon'] - self._masterFunc2(x, ['fobj', 'fcon'], writeHist=False) - # We *don't* count that extra call, since that will - # screw up the numbering...so we subtract the last call. - self.callCounter -= 1 - # Now, the point has been evaluated correctly so we - # determine if we have to run the sens calc: - - if self.cache['gobj'] is None: - timeA = time.time() - args = self.sens(xuser, self.cache['funcs']) - - if isinstance(args, tuple): - funcsSens = args[0] - fail = args[1] - elif args is None: - raise Error("No return values from user supplied " - "sensitivity function. The function must " - "return \"funcsSens\" *OR* \"funcsSens, fail\"") - else: - funcsSens = args - fail = False - - self.userSensTime += time.time()-timeA - self.userSensCalls += 1 - - # User values are stored is immediately - self.cache['funcsSens'] = copy.deepcopy(funcsSens) - - # Process objective gradient for optimizer - gobj = self.optProb.processObjectiveGradient(funcsSens) - - # Process constraint gradients for optimizer - gcon = self.optProb.processConstraintJacobian(funcsSens) - gcon = self._convertJacobian(gcon) - - # Set the cache values: - self.cache['gobj'] = gobj.copy() - self.cache['gcon'] = gcon.copy() - - # Update fail flag - masterFail = masterFail or fail - - # gobj is now in the cache - returns.append(self.cache['gobj']) - if self.storeSens: - hist['funcsSens'] = self.cache['funcsSens'] - - if 'gcon' in evaluate: - if numpy.linalg.norm(x-self.cache['x']) > eps: - # Previous evaluated point is *different* than the - # point requested for the derivative. Recursively call - # the routine with ['fobj', and 'fcon'] - self._masterFunc2(x, ['fobj', 'fcon'], writeHist=False) - # We *don't* count that extra call, since that will - # screw up the numbering...so we subtract the last call. - self.callCounter -= 1 - # Now, the point has been evaluated correctly so we - # determine if we have to run the sens calc: - if self.cache['gcon'] is None: - timeA = time.time() - - args = self.sens(xuser, self.cache['funcs']) - - if isinstance(args, tuple): - funcsSens = args[0] - fail = args[1] - elif args is None: - raise Error("No return values from user supplied " - "sensitivity function. The function must " - "return \"funcsSens\" *OR* \"funcsSens, fail\"") - else: - funcsSens = args - fail = False - - self.userSensTime += time.time()-timeA - self.userSensCalls += 1 - # User values stored is immediately - self.cache['funcsSens'] = copy.deepcopy(funcsSens) - - # Process objective gradient for optimizer - gobj = self.optProb.processObjectiveGradient(funcsSens) - - # Process constraint gradients for optimizer - gcon = self.optProb.processConstraintJacobian(funcsSens) - gcon = self._convertJacobian(gcon) - - # Set cache values - self.cache['gobj'] = gobj.copy() - self.cache['gcon'] = gcon.copy() - - # Update fail flag - masterFail = masterFail or fail - - # gcon is now in the cache - returns.append(self.cache['gcon']) - if self.storeSens: - hist['funcsSens'] = self.cache['funcsSens'] - - # Put the fail flag in the history: - hist['fail'] = masterFail - - # Save information about major iteration counting (only matters for SNOPT). - hist['iu0'] = self.iu0 - - # Add constraint and variable bounds at beginning of optimization. - # This info is used for visualization using OptView. - if self.callCounter == 0 and self.optProb.comm.rank == 0: - conInfo = {} - varInfo = {} - - # Cycle through constraints adding the bounds - for key in self.optProb.constraints.keys(): - lower = self.optProb.constraints[key].lower - upper = self.optProb.constraints[key].upper - scale = self.optProb.constraints[key].scale - conInfo[key] = {'lower':lower, 'upper':upper, 'scale':scale} - - # Cycle through variables and add the bounds - for dvGroup in self.optProb.variables: - varInfo[dvGroup] = {'lower':[], 'upper':[], 'scale':[]} - for var in self.optProb.variables[dvGroup]: - if var.type == 'c': - varInfo[dvGroup]['lower'].append(var.lower / var.scale) - varInfo[dvGroup]['upper'].append(var.upper / var.scale) - varInfo[dvGroup]['scale'].append(var.scale) - - # Save objective key for use in OptView - hist['objKey'] = list(self.optProb.objectives.keys())[0] - - # There is a special write for the bounds data - if self.storeHistory: - self.hist.writeData('varInfo', varInfo) - self.hist.writeData('conInfo', conInfo) - - # Write history if necessary - if (self.optProb.comm.rank == 0 and writeHist and self.storeHistory): - self.hist.write(self.callCounter, hist) - - # We can now safely increment the call counter - self.callCounter += 1 - - # Tack the fail flag on at the end - returns.append(masterFail) - - return returns - - def _internalEval(self, x): - """ - Special internal evaluation for optimizers that have a - separate callback for each constraint""" - - fobj, fcon, gobj, gcon, fail = self._masterFunc( - x, ['fobj', 'fcon', 'gobj', 'gcon']) - - self.storedData['x'] = x.copy() - self.storedData['fobj'] = fobj - self.storedData['fcon'] = fcon.copy() - self.storedData['gobj'] = gobj.copy() - self.storedData['gcon'] = gcon.copy() - - def _checkEval(self, x): - """Special check to be used with _internalEval()""" - if self.storedData['x'] is None: - return True - elif (self.storedData['x'] == x).all(): - return False - else: - return True - - def _convertJacobian(self, gcon_csr_in): - """ - Convert gcon which is a coo matrix into the format we need. - - The returned Jacobian gcon is the data only, not a dictionary. - """ - - # Now, gcon is a CSR sparse matrix. Depending on what the - # optimizer wants, we will convert. The conceivable options - # are: dense (most), csc (snopt), csr (???), or coo (IPOPT) - - if self.optProb.nCon > 0: - # Extract the rows we need: - gcon_csr = extractRows(gcon_csr_in, self.optProb.jacIndices) - - # Apply factor scaling because of constraint sign changes - scaleRows(gcon_csr, self.optProb.fact) - - # Now convert to final format: - if self.jacType == 'dense2d': - gcon = convertToDense(gcon_csr) - elif self.jacType == 'csc': - if self._jac_map_csr_to_csc is None: - self._jac_map_csr_to_csc = mapToCSC(gcon_csr) - gcon = gcon_csr['csr'][IDATA][self._jac_map_csr_to_csc[IDATA]] - elif self.jacType == 'csr': - pass - elif self.jacType == 'coo': - gcon = convertToCOO(gcon_csr) - gcon = gcon['coo'][IDATA] - if self.optProb.dummyConstraint: - gcon = gcon_csr_in['csr'][IDATA] - return gcon - - def _waitLoop(self): - """Non-root processors go into this waiting loop while the - root proc does all the work in the optimization algorithm""" - - mode = None - info = None - while True: - # * Note*: No checks for MPI here since this code is - # * only run in parallel, which assumes mpi4py is working - - # Receive mode and quit if mode is -1: - mode = self.optProb.comm.bcast(mode, root=0) - if mode == -1: - break - - # Otherwise receive info from shell function - info = self.optProb.comm.bcast(info, root=0) - - # Call the generic internal function. We don't care - # about return values on these procs - self._masterFunc2(*info) - - def _setInitialCacheValues(self): - """ - Once we know that the optProb has been set, we populate the - cache with a magic number. If the starting points for your - optimization is -9999999999 then you out of luck! - """ - self.cache['x'] = -999999999*numpy.ones(self.optProb.ndvs) - - def _assembleContinuousVariables(self): - """ - Utility function for assembling the design variables. Most - optimizers here use continuous variables so this chunk of code - can be reused. - """ - blx = [] - bux = [] - xs = [] - for dvGroup in self.optProb.variables: - for var in self.optProb.variables[dvGroup]: - if var.type == 'c': - blx.append(var.lower) - bux.append(var.upper) - xs.append(var.value) - - else: - raise Error("%s cannot handle integer or discrete " - "design variables" % self.name) - - blx = numpy.array(blx) - bux = numpy.array(bux) - xs = numpy.array(xs) - - return blx, bux, xs - - def _assembleConstraints(self): - """ - Utility function for assembling the design variables. Most - optimizers here use continuous variables so this chunk of code - can be reused. - """ - - # Constraints Handling -- make sure nonlinear constraints - # go first -- this is particular to slsqp - blc = [] - buc = [] - - for key in self.optProb.constraints.keys(): - if not self.optProb.constraints[key].linear: - blc.extend(self.optProb.constraints[key].lower) - buc.extend(self.optProb.constraints[key].upper) - - for key in self.optProb.constraints.keys(): - if self.optProb.constraints[key].linear: - blc.extend(self.optProb.constraints[key].lower) - buc.extend(self.optProb.constraints[key].upper) - - if self.unconstrained: - blc.append(-INFINITY) - buc.append(INFINITY) - - ncon = len(blc) - blc = numpy.array(blc) - buc = numpy.array(buc) - - return ncon, blc, buc - - def _assembleObjective(self): - """ - Utility function for assembling the design variables. Most - optimizers here use continuous variables so this chunk of code - can be reused. - """ - - nobj = len(self.optProb.objectives.keys()) - ff = [] - if nobj == 0: - raise Error("No objective function was supplied! One can " - "be added using a call to optProb.addObj()") - for objKey in self.optProb.objectives: - ff.append(self.optProb.objectives[objKey].value) - - return numpy.real(numpy.squeeze(ff)) - - def _createSolution(self, optTime, sol_inform, obj, xopt): - """ - Generic routine to create the solution after an optimizer - finishes. - """ - sol = Solution(self.optProb, optTime, sol_inform) - sol.userObjTime = self.userObjTime - sol.userSensTime = self.userSensTime - sol.userObjCalls = self.userObjCalls - sol.userSensCalls = self.userSensCalls - sol.interfaceTime = self.interfaceTime - self.userSensTime - self.userObjTime - sol.optCodeTime = sol.optTime - self.interfaceTime - sol.fStar = obj - n = len(self.optProb.invXScale) - xScaled = self.optProb.invXScale * xopt[0:n] + self.optProb.xOffset[0:n] - sol.xStar = self.optProb.processX(xScaled) - - # Now set the x-values: - i = 0 - for dvGroup in sol.variables: - for var in sol.variables[dvGroup]: - var.value = xopt[i] - i += 1 - - return sol - - def _communicateSolution(self, sol): - """ - Broadcast the solution from the root proc back to everyone. We - have to be a little careful since we can't in general - broadcast the function and comm so we have to set manually after the broadcast. - """ - - if sol is not None: - sol.comm = None - sol = self.optProb.comm.bcast(sol) - sol.objFun = self.optProb.objFun - sol.comm = self.optProb.comm - - return sol - - def _on_setOption(self, name, value): - """ - Set Optimizer Option Value (Optimizer Specific Routine) - """ - raise Error('This optimizer has not implemented _on_setOption') - - def setOption(self, name, value=None): - """ - Generic routine for all option setting. The routine does - error checking on the type of the value. - - Parameters - ---------- - name : str - Name of the option to set - value : varies - Variable value to set. - """ - - if name in self.options['defaults']: - if type(value) == self.options['defaults'][name][0]: - self.options[name] = [type(value), value] - else: - raise Error("Value type for option %s was incorrect. It was " - "expecting type '%s' by received type '%s'" % ( - name, self.options['defaults'][name][0], - type(value))) - else: - raise Error('Received an unknown option: %s' % repr(name)) - - # Now call the optimizer specific routine - self._on_setOption(name, value) - - def _on_getOption(self, name): - """ - Routine to be implemented by optimizer - """ - raise Error('This optimizer has not implemented _on_getOption') - - def getOption(self, name): - """ - Return the optimizer option value for name - - Parameters - ---------- - name : str - name of option for which to retrieve value - - Returns - ------- - value : varies - value of option for 'name' - """ - - if name in self.options['defaults']: - return self.options[name][1] - else: - raise Error('Received an unknown option: %s.' % repr(name)) - - # Now call the optimizer specific routine - self._on_getOption(name) - - def _on_getInform(self, info): - """ - Routine to be implemented by optimizer - """ - raise Error('This optimizer has not implemented _on_getInform') - - def getInform(self, infocode=None): - """ - Get optimizer result inform code at exit - - Parameters - ---------- - infocode : int - Integer information code - """ - - if infocode is None: - return self.informs - else: - return self._on_getInform(infocode) - -# ============================================================================= -# Generic OPT Constructor -# ============================================================================= - -def OPT(optName, *args, **kwargs): - """ - This is a simple utility function that enables creating an - optimizer based on the 'optName' string. This can be useful for - doing optimization studies with respect to optimizer since you - don't need massive if-statements. - - Parameters - ---------- - optName : str - String identifying the optimizer to create - - *args, **kwargs : varies - Passed to optimizer creation. - - Returns - ------- - opt : pyOpt_optimizer inherited optimizer - The desired optimizer - """ - - optName = optName.lower() - optList = ['snopt', 'ipopt', 'slsqp', 'fsqp', 'nlpqlp', 'conmin', - 'nsga2', 'nlpy_auglag', 'psqp', 'alpso'] - if optName == 'snopt': - from .pySNOPT.pySNOPT import SNOPT as opt - elif optName == 'ipopt': - from .pyIPOPT.pyIPOPT import IPOPT as opt - elif optName == 'slsqp': - from .pySLSQP.pySLSQP import SLSQP as opt - elif optName == 'fsqp': - from .pyFSQP.pyFSQP import FSQP as opt - elif optName == 'nlpqlp': - from .pyNLPQLP.pyNLPQLP import NLPQLP as opt - elif optName == 'psqp': - from .pyPSQP.pyPSQP import PSQP as opt - elif optName == 'conmin': - from .pyCONMIN.pyCONMIN import CONMIN as opt - elif optName == 'nsga2': - from .pyNSGA2.pyNSGA2 import NSGA2 as opt - elif optName == 'nlpy_auglag': - from .pyNLPY_AUGLAG.pyNLPY_AUGLAG import NLPY_AUGLAG as opt - elif optName == 'alpso': - from .pyALPSO.pyALPSO import ALPSO as opt - # elif optName == 'nomad': - # from .pyNOMAD.pyNOMAD import NOMAD as opt - else: - raise Error("The optimizer specified in 'optName' was \ -not recognized. The current list of supported optimizers is: %s" % - repr(optList)) - - # Create the optimizer and return it - return opt(*args, **kwargs) diff --git a/pyoptsparse/pyoptsparse/pyOpt_solution.py b/pyoptsparse/pyoptsparse/pyOpt_solution.py deleted file mode 100644 index 156ac4aae..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_solution.py +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_solution - -This class is used to describe the solution of an optimization -problem. This class is inherits from Optimization which enables a -solution to be used as an input to a subsequent optimization problem. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -""" -from __future__ import absolute_import -import copy -from .pyOpt_optimization import Optimization - -class Solution(Optimization): - """ - Solution Class Initialization - - Parameters - ---------- - optProb : Optimization problem class - Optimization problem used to create solution - - optTime : float - Time required for the optimziation - - optEvals : int - The number of function evalution for the solution - - optInform : int - The inform code from the optimization. - """ - - def __init__(self, optProb, optTime, optInform): - - Optimization.__init__(self, optProb.name, None) - - # Copy over the variables, constraints, and objectives - self.variables = copy.deepcopy(optProb.variables) - self.constraints = copy.deepcopy(optProb.constraints) - self.objectives = copy.deepcopy(optProb.objectives) - self.optTime = optTime - self.optInform = optInform - - def __str__(self): - """ - Print Structured Solution - """ - - text0 = Optimization.__str__(self) - text1 = '' - lines = text0.split('\n') - lines[1] = lines[1][len('Optimization Problem -- '):] - for i in range(5): - text1 += lines[i] + '\n' - - text1 += '\n Solution: \n' - text1 += ('-'*80) + '\n' - text1 += ' Total Time: %25.4f\n' % self.optTime - text1 += ' User Objective Time : %10.4f\n' % self.userObjTime - text1 += ' User Sensitivity Time : %10.4f\n' % self.userSensTime - if hasattr(self, 'userJProdTime'): - text1 += ' User J-Product Time : %10.4f\n' % self.userJProdTime - text1 += ' User J^T-Product Time : %10.4f\n' % self.userJTProdTime - text1 += ' Interface Time : %10.4f\n' % self.interfaceTime - text1 += ' Opt Solver Time: %10.4f\n' % self.optCodeTime - text1 += ' Calls to Objective Function : %7d\n' % self.userObjCalls - text1 += ' Calls to Sens Function : %7d\n' % self.userSensCalls - if hasattr(self, 'userJProdCalls'): - text1 += ' Calls to JProd Function : %7d\n' % self.userJProdCalls - text1 += ' Calls to JTProd Function : %7d\n' % self.userJTProdCalls - - for i in range(5, len(lines)): - text1 += lines[i] + '\n' - - text1 += ('-'*80) + '\n' - - return text1 diff --git a/pyoptsparse/pyoptsparse/pyOpt_utils.py b/pyoptsparse/pyoptsparse/pyOpt_utils.py deleted file mode 100644 index 298af7376..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_utils.py +++ /dev/null @@ -1,529 +0,0 @@ -#!/usr/bin/env python -''' -pyOptSparse_utils - -Holds a minimal set of sparse-matrix type routines for pyOptSparse. This -is designed to replace the HORRENDOUS scipy sparse matrix format. The -with scipy.sparse is that is the NO way to enforce a constant sparsity -structure which is required for the optimizers. We use a very simple -dictionary format to represent the three most common forms of sparse matrices: - -mat = {'coo':[row, col, data], 'shape':[nrow, ncols]} # A coo matrix -mat = {'csr':[rowp, colind, data], 'shape':[nrow, ncols]} # A csr matrix -mat = {'coo':[colp, rowind, data], 'shape':[nrow, ncols]} # A csc matrix - -Copyright (c) 2008-2013 -All rights reserved. - -Developers: ------------ -- Dr. Gaetan K.W. Kenway (GKK) -- Dr. Graeme J. Kennedy (GJK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2014) -''' -import numpy -import warnings -from .pyOpt_error import Error -# Define index memonics -IROW = 0 -ICOL = 1 - -IROWP = 0 -ICOLIND = 1 - -ICOLP = 0 -IROWIND = 1 - -IDATA = 2 -__all__ = ['convertToCOO', 'convertToCSR', 'convertToCSC', 'convertToDense', - 'mapToCSC', 'mapToCSR', - 'scaleColumns', 'scaleRows', 'extractRows', 'IROW', 'ICOL', - 'IROWP', 'ICOLIND', 'ICOLP', 'IROWIND', 'IDATA'] - - -def mapToCSR(mat): - """ - Given a pyoptsparse matrix definition, return a tuple containing a - map of the matrix to the CSR format. - - Parameters - ---------- - mat : dict - A sparse matrix representation. - - Returns - ------- - tup : tuple of numpy arrays - tup[0] : numpy array (size=num_rows+1) - An array that holds the indices in col_idx and data at which each - row begins. The last index of contains the number of nonzero - elements in the sparse array. - tup[1] : numpy array (size=nnz) - An array of the column indices of each element in data. - tup[2] : numpy array (size=nnz) - An indexing array which maps the elements in the data array - to elements in the CSR data array. - """ - if 'csr' in mat: - # First handle the trivial case CSR->CSR - row_p = mat['csr'][IROW] - col_idx = mat['csr'][ICOL] - idx_data = numpy.s_[:] - return row_p, col_idx, idx_data - - num_rows = mat['shape'][0] - num_cols = mat['shape'][1] - - if 'csc' in mat: - # If given a CSC matrix, expand the column pointers so we - # effectively have a COO representation. - csc_colp = mat['csr'][ICOL] - rows = mat['csc'][IROW] - nnz = csc_colp[-1] - - # Allocate the COO maps - cols = numpy.zeros(nnz, dtype='intc') - - # We already have a full representation of the columns. - # We need to decompress the representation of the rows. - for j in range(num_cols): - cols[csc_colp[j]:csc_colp[j+1]] = j - - elif 'coo' in mat: - rows = mat['coo'][IROW] - cols = mat['coo'][ICOL] - nnz = len(rows) - - # Allocate the row pointer array - row_p = numpy.zeros(num_rows+1, dtype='intc') - - # Get the sort order that puts data in row-major form - idx_data = numpy.lexsort((cols, rows)) - - # Apply the row-major indexing to the COO column and row indices - col_idx = numpy.asarray(cols, dtype='intc')[idx_data] - rows_rowmaj = numpy.asarray(rows, dtype='intc')[idx_data] - - # Now for i = 0 to num_rows-1, row_p[i] is the first occurrence - # of i in rows_rowmaj - row_p[:-1] = numpy.digitize(numpy.arange(num_rows), rows_rowmaj, right=True) - - # By convention store nnz in the last element of row_p - row_p[-1] = nnz - - return row_p, col_idx, idx_data - - -def mapToCSC(mat): - """ - Given a pyoptsparse matrix definition, return a tuple containing a - map of the matrix to the CSC format. - - Parameters - ---------- - mat : dict - A sparse matrix representation. - - Returns - ------- - tup : tuple of numpy arrays - tup[0] : numpy array (size=nnz) - An array that holds the row index of each element in the CSC - representation of the data. - tup[1] : numpy array (size=num_cols+1) - An array that holds the indices in the CSC representation - and data at which each column begins. The last index of - contains the number of nonzero elements in the sparse array. - tup[2] : numpy array - An indexing array which maps the elements in the data array - to elements in the CSC data array. - """ - if 'csc' in mat: - # First handle the trivial case CSR->CSR - row_idx = mat['csc'][IROW] - col_p = mat['csc'][ICOL] - idx_data = numpy.s_[:] - return row_idx, col_p, idx_data - - num_rows = mat['shape'][0] - num_cols = mat['shape'][1] - - if 'csr' in mat: - # If given a CSR matrix, expand the row pointers so we - # effectively have a COO representation. - csr_rowp = mat['csr'][IROW] - cols = mat['csr'][ICOL] - nnz = csr_rowp[-1] - - # Allocate the COO maps - rows = numpy.zeros(nnz, dtype='intc') - - # We already have a full representation of the columns. - # We need to decompress the representation of the rows. - for j in range(num_rows): - rows[csr_rowp[j]:csr_rowp[j+1]] = j - - # Now we have rows and cols, proceed as if we started with a COO matrix - - elif 'coo' in mat: - rows = mat['coo'][IROW] - cols = mat['coo'][ICOL] - nnz = len(rows) - - else: - raise ValueError('Invalid matrix type') - - # Allocate the new column pointer - col_p = numpy.zeros(num_cols+1, dtype='intc') - - # Get the sort order that puts data in column-major form - idx_data = numpy.lexsort((rows, cols)) - - # Apply the column-major indexing to the COO column and row indices - row_idx = numpy.asarray(rows, dtype='intc')[idx_data] - cols_colmaj = numpy.asarray(cols, dtype='intc')[idx_data] - - # Now for i = 0 to num_cols-1, col_p[i] is the first occurrence - # of i in cols_colmaj - col_p[:-1] = numpy.digitize(numpy.arange(num_cols), cols_colmaj, right=True) - - # By convention store nnz in the last element of col_p - col_p[-1] = nnz - - return row_idx, col_p, idx_data - - -def convertToCOO(mat): - """ - Take a pyoptsparse sparse matrix definition of a COO, CSR or - CSC matrix or numpy array or scipy sparse matrix and return - the same matrix in COO format. - - Parameters - ---------- - mat : dict or numpy array - A sparse matrix representation or numpy array - - Returns - ------- - newMat : dict - A coo representation of the same matrix - """ - - if isinstance(mat, dict): - if 'coo' in mat: - return mat - if 'csr' in mat: - return _csr_to_coo(mat) - elif 'csc' in mat: - return _csc_to_coo(mat) - else: - # Try to do it with a scipy sparse matrix: - try: - from scipy import sparse - if sparse.issparse(mat): - warnings.warn("Using scipy.sparse matrices with pyOptSparse " - "in VERY STRONGLY discouraged. Please use the " - "simplified pyoptsparse format which allows for " - "fixed sparsity structure and explict zeros in " - "the matrix. There is no way to guarantee " - "a fixed sparsity structure with scipy " - "matrices which is what the underlying " - "optimizers require. Using scipy.sparse " - "matrices may cause unexpected errors.") - - mat = mat.tocoo() - return {'coo':[mat.row, mat.col, mat.data], 'shape':mat.shape} - except: - pass - - # Now try to do it with a numpy matrix: - try: - return _denseToCOO(numpy.atleast_2d(numpy.array(mat))) - except: - raise Error("Unknown matrix format. Must be a dense numpy " - "array or a pyoptsparse sparce matrix format of " - "COO, CSR or CSC. See documentation for correct " - "format. Supplied Matrix is: %s"% repr(mat)) - -def convertToCSR(mat): - """ - Take a pyoptsparse sparse matrix definition of a COO, CSR or - CSC matrix or numpy array and return the same matrix in CSR format - - Parameters - ---------- - mat : dict or numpy array - A sparse matrix representation or numpy array - - Returns - ------- - newMat : dict - A coo representation of the same matrix - """ - - if 'csr' in mat: - return mat - - mat = convertToCOO(mat) - n = mat['shape'][0] - m = mat['shape'][1] - rows = mat['coo'][IROW] - cols = mat['coo'][ICOL] - data = mat['coo'][IDATA] - - rowp = numpy.zeros(n+1, dtype='intc') - - # Count up the number of times things are index - for row in rows: - rowp[row+1] += 1 - - # Set up the array as a pointer - for i in range(1, n+1): - rowp[i] += rowp[i-1] - - ncols = numpy.zeros(rowp[-1], dtype='intc') - ndata = numpy.zeros(rowp[-1], dtype=type(data[0])) - - # Now, add all the values and the data - for i in range(len(rows)): - r = rows[i] - ncols[rowp[r]] = cols[i] - ndata[rowp[r]] = data[i] - rowp[r] += 1 - - # Readjust the pointer - for i in range(n, 0, -1): - rowp[i] = rowp[i-1] - rowp[0] = 0 - - return {'csr':[rowp, ncols, ndata], 'shape':[n, m]} - -def convertToCSC(mat): - """ - Take a pyoptsparse sparse matrix definition of a COO, CSR or - CSC matrix or numpy array and return the same matrix in CSR format - - Parameters - ---------- - mat : dict or numpy array - A sparse matrix representation or numpy array - - Returns - ------- - newMat : dict - A coo representation of the same matrix - """ - if 'csc' in mat: - return mat - - mat = convertToCSR(mat) - n = mat['shape'][0] - m = mat['shape'][1] - rowp = mat['csr'][IROWP] - cols = mat['csr'][ICOLIND] - data = mat['csr'][IDATA] - - # Allocate the new arrays - colp = numpy.zeros(m+1, 'intc') - rows = numpy.zeros(len(cols), 'intc') - - # Count up the number of references to each column - for col in cols: - colp[col+1] += 1 - - # Set colp so that it is now a pointer - for i in range(1, m): - colp[i] += colp[i-1] - - # Allocate data for the csc object - csc_data = numpy.zeros(len(data), dtype=type(data[0])) - - # Scan through the CSR data structure - for i in range(n): - for jp in range(rowp[i], rowp[i+1]): - # Set the new row location in the CSC data structure - j = cols[jp] - csc_data[colp[j]] = data[jp] - rows[colp[j]] = i - colp[j] += 1 - - # Reset the colp pointer - for j in range(m, 0, -1): - colp[j] = colp[j-1] - colp[0] = 0 - - return {'csc':[colp, rows, csc_data], 'shape':[n, m]} - -def convertToDense(mat): - """ - Take a pyopsparse sparse matrix definition and convert back to a dense - format. This is typically the final step for optimizers with dense constraint - jacibians. - - Parameters - ---------- - mat : dict - A sparse matrix representation. Should be in CSR format for best - efficiency - - Returns - ------- - newMat : array - A dense numpy array of the same matrix - """ - - mat = convertToCSR(mat) - newMat = numpy.zeros((mat['shape'])) - data = mat['csr'][IDATA] - colInd = mat['csr'][ICOLIND] - rowp = mat['csr'][IROWP] - for i in range(mat['shape'][0]): - for j in range(rowp[i], rowp[i+1]): - newMat[i, colInd[j]] = data[j] - return newMat - -def scaleColumns(mat, factor): - """ d= - Scale the columns of the matrix. Must be CSR format - """ - if not isinstance(mat, dict): - raise Error("mat for scaleColumbs must be pyoptsparse matrix format") - if 'csr' not in mat: - raise Error("scaleColumns only works for CSR pyoptsparse matrix format") - if mat['shape'][1] != len(factor): - raise Error("Length of factor is incorrect") - for i in range(mat['shape'][0]): - iStart = mat['csr'][IROWP][i] - iEnd = mat['csr'][IROWP][i+1] - mat['csr'][IDATA][iStart:iEnd] *= factor[mat['csr'][ICOLIND][iStart:iEnd]] - -def scaleRows(mat, factor): - """ - Scale the rows of the matrix. Must be CSR format - """ - if not isinstance(mat, dict): - raise Error("mat for scaleRows must be pyoptsparse matrix format") - if 'csr' not in mat: - raise Error("scaleRows only works for CSR pyoptsparse matrix format") - if mat['shape'][0] != len(factor): - raise Error("Length of factor is incorrect") - for i in range(mat['shape'][0]): - iStart = mat['csr'][IROWP][i] - iEnd = mat['csr'][IROWP][i+1] - mat['csr'][IDATA][iStart:iEnd] *= factor[i] - -def extractRows(mat, indices): - """ - Extract the rows defined by 'indices' and return - a new CSR matrix. - - Parameters - ---------- - mat : dict - pyoptsparse matrix CSR format - indices : list/array of integer - The rows the user wants to extract - - Returns - ------- - newMat : dic - pyoptsparse CSR matrix - """ - rowp = mat['csr'][IROWP] - cols = mat['csr'][ICOLIND] - data = mat['csr'][IDATA] - m = mat['shape'][1] - nn = len(indices) - nrowp = numpy.zeros(nn+1, 'intc') - - # Count up the size of everything - size = 0 - for i in range(nn): - size += rowp[indices[i]+1] - rowp[indices[i]] - nrowp[i+1] = size - - # Create the new columns and data arrays - ncols = numpy.zeros(size, 'intc') - ndata = numpy.zeros(size, dtype=type(data[0])) - - # Re-indices the new columns - for i in range(nn): - ncols[nrowp[i]:nrowp[i+1]] = cols[rowp[indices[i]]:rowp[indices[i]+1]] - ndata[nrowp[i]:nrowp[i+1]] = data[rowp[indices[i]]:rowp[indices[i]+1]] - - return {'csr':[nrowp, ncols, ndata], 'shape':[nn, m]} - -def _denseToCOO(arr): - """ - Return a COO array that is a COO representation of the dense numpy - array, arr - - Parameters - ---------- - arr : numpy array - - Returns - ------- - dict : mat - The pyoptsparse representation of a sparse matrix - """ - nRows = arr.shape[0] - nCols = arr.shape[1] - data = arr.flatten() - cols = numpy.mod(numpy.arange(nRows*nCols), nCols) - rows = numpy.arange(nRows*nCols)//nCols - return {'coo':[rows, cols, data], 'shape':[nRows, nCols]} - -def _csr_to_coo(mat): - """ - Convert the given CSR matrix to a COO format - - Parameters - ---------- - mat : dict - pyoptsparse matrix definition - """ - - # This is straight forward - just expand out the rows - rowp = mat['csr'][IROWP] - cols = mat['csr'][ICOLIND] - data = mat['csr'][IDATA] - coo_rows = numpy.zeros(len(cols), 'intc') - coo_cols = numpy.array(cols, 'intc') - - for i in range(mat['shape'][0]): - coo_rows[rowp[i]:rowp[i+1]] = i - - coo_data = numpy.array(data) - - return {'coo':[coo_rows, coo_cols, coo_data], 'shape':mat['shape']} - -def _csc_to_coo(mat): - """ - Convert the given CSC matrix to a COO format - - Parameters - ---------- - mat : dict - pyoptsparse matrix definition - """ - - # This is straight forward - just expand out the rows - colp = mat['csc'][ICOLP] - rows = mat['csc'][IROWIND] - data = mat['csc'][IDATA] - - # This is straight forward - just expand out the columns - coo_rows = numpy.array(rows, 'intc') - coo_cols = numpy.zeros(len(rows), 'intc') - - for j in range(mat['shape'][1]): - coo_cols[colp[j]:colp[j+1]] = j - - coo_data = numpy.array(data) - - return {'coo':[coo_rows, coo_cols, coo_data], 'shape':mat['shape']} diff --git a/pyoptsparse/pyoptsparse/pyOpt_variable.py b/pyoptsparse/pyoptsparse/pyOpt_variable.py deleted file mode 100644 index 19a89650f..000000000 --- a/pyoptsparse/pyoptsparse/pyOpt_variable.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python -""" -pyOpt_variable - -Holds the representation of a single pyOptSparse variable - -Copyright (c) 2008-2013 by pyOpt Developers -All rights reserved. - -Developers ----------- - Dr. Gaetan K.W. Kenway (GKK) - -History -------- - v. 1.0 - Initial Class Creation (GKK, 2013) -""" -from .pyOpt_error import Error -INFINITY=1e20 -# ============================================================================= -# Variable Class -# ============================================================================= -class Variable(object): - """ - Variable Class Initialization - """ - def __init__(self, name, type, value, lower, upper, scale, offset, - scalar=False, choices=None): - - self.name = name - self.type = type - self.scalar = scalar - self.choices = None - if self.type == 'c': - if lower is None: - self.lower = -INFINITY - else: - self.lower = (lower-offset)*scale - - if upper is None: - self.upper = INFINITY - else: - self.upper = (upper-offset)*scale - - self.value = (value-offset)*scale - self.scale = scale - self.offset = offset - elif self.type == 'i': - self.value = int(value) - self.lower = lower - self.upper = upper - self.scale = scale - elif self.type == 'd': - if choices is None: - raise Error("A discrete variable requires " - "to input an array of choices.") - self.choices = choices - self.value = self.choices[int(value)] - self.lower = 0 - self.upper = len(self.choices) - self.scale = scale - - def __eq__(self, other): - """ - Compare two variable objects - """ - if (self.name == other.name and self.type == other.type and - self.scalar == other.scalar and self.upper == other.upper and - self.lower == other.lower and self.choices == other.choices): - return True - else: - return False - - def __str__(self): - """ - Print Structured List of Variable - """ - - res = 'Name Type Value ' - res += 'Lower Bound Upper Bound\n' - - if self.type == 'd': - res += ' ' - res += str(self.name).center(15) - res += '%25s%20f %14.2e %12.2e \n'% ( - self.type, self.choices[int(self.value)], - min(self.choices), max(self.choices)) - else: - lower = self.lower - upper = self.upper - if self.lower is None: - lower = -1e20 - if self.upper is None: - upper = 1e20 - - res += ' ' - res += str(self.name).center(9) - res += '%5s %14f %14.2e %12.2e \n'% ( - self.type, self.value, lower, upper) - - return res diff --git a/pyoptsparse/pyoptsparse/pyPSQP/LICENSE b/pyoptsparse/pyoptsparse/pyPSQP/LICENSE deleted file mode 100644 index 1a0e242bf..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/LICENSE +++ /dev/null @@ -1,185 +0,0 @@ -PSQP - Preconditioned Sequential Quadratic Programming -Copyright (c) 2007, Ladislav Luksan (luksan@uivt.cas.cz) -Modified for pyOpt - 2010, Ruben E. Perez (Ruben.Perez@rmc.ca) - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as -published by the Free Software Foundation, either version 3 of -the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General -Public License along with this program. If not, see -. - ----------------------------------------------------------------------- - - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/pyoptsparse/pyoptsparse/pyPSQP/README b/pyoptsparse/pyoptsparse/pyPSQP/README deleted file mode 100644 index 8aeab875d..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the psqp class definition -and the psqp shared library, psqp.so or psqp.pyd. diff --git a/pyoptsparse/pyoptsparse/pyPSQP/__init__.py b/pyoptsparse/pyoptsparse/pyPSQP/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pyPSQP/pyPSQP.py b/pyoptsparse/pyoptsparse/pyPSQP/pyPSQP.py deleted file mode 100644 index 767d6a021..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/pyPSQP.py +++ /dev/null @@ -1,296 +0,0 @@ -#/bin/env python -""" -pyPSQP - the pyPSQP wrapper - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# PSQP Library -# ============================================================================= -try: - from . import psqp -except ImportError: - psqp = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -# ============================================================================= -# PSQP Optimizer Class -# ============================================================================= -class PSQP(Optimizer): - """ - PSQP Optimizer Class - Inherited from Optimizer Abstract Class - """ - def __init__(self, *args, **kwargs): - name = 'PSQP' - category = 'Local Optimizer' - defOpts = { - 'XMAX': [float, 1e16], # Maximum Stepsize - 'TOLX': [float, 1e-16], # Variable Change Tolerance - 'TOLC': [float, 1e-6], # Constraint Violation Tolerance - 'TOLG': [float, 1e-6], # Lagrangian Gradient Tolerance - 'RPF': [float, 1e-4], # Penalty Coefficient - 'MIT': [int, 1000], # Maximum Number of Iterations - 'MFV': [int, 2000], # Maximum Number of Function Evaluations - 'MET': [int, 2], # Variable Metric Update (1 - BFGS, 2 - Hoshino) - 'MEC': [int, 2], # Negative Curvature Correction (1 - None, 2 - Powell's Correction) - 'IPRINT': [int, 2], # Output Level (0 - None, 1 - Final, 2 - Iter) - 'IOUT': [int, 6], # Output Unit Number - 'IFILE': [str, 'PSQP.out'], # Output File Name - } - informs = { - 1 : 'Change in design variable was less than or equal to tolerance', - 2 : 'Change in objective function was less than or equal to tolerance', - 3 : 'Objective function less than or equal to tolerance', - 4 : 'Maximum constraint value is less than or equal to tolerance', - 11 : 'Maximum number of iterations exceeded', - 12 : 'Maximum number of function evaluations exceeded', - 13 : 'Maximum number of gradient evaluations exceeded', - -6 : 'Termination criterion not satisfied, but obtained point is acceptable', - - } - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - if psqp is None: - raise Error('There was an error importing the compiled \ - psqp module') - - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - # PSQP needs jacobians in dense format - self.jacType = 'dense2d' - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. To - explictly use pyOptSparse gradient class to do the - derivatives with finite differenes use 'FD'. 'sens' - may also be 'CS' which will cause pyOptSpare to compute - the derivatives using the complex step method. Finally, - 'sens' may be a python function handle which is expected - to compute the sensitivities directly. For expensive - function evaluations and/or problems with large numbers of - design variables this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is 'FD' and 1e-40j when sens is 'CS'. - - sensMode : str - Use 'pgc' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from PSQP does not match the history, function and - gradient evaluations revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if len(optProb.constraints) == 0: - self.unconstrained = True - optProb.dummyConstraint = False - - # Set optProb and finalize - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - self._setSens(sens, sensStep, sensMode) - blx, bux, xs = self._assembleContinuousVariables() - xi = 3*numpy.ones(len(xs), 'int') - xs = numpy.maximum(xs, blx) - xs = numpy.minimum(xs, bux) - nvar = len(xs) - ff = self._assembleObjective() - - # pSQP CAN handle two sided constraints, but need to know - # which ones are which. That is a little tricky to determine, - # so we will split them into one-sided <= zero constraints and - # equality=0 constraints such that it is simple to determine - # the type of constraints. Put the equality constraints frist. - - oneSided = True - # Set the number of nonlinear constraints snopt *thinks* we have: - if self.unconstrained: - ncon = 0 - cf = [0.0] - cl = [] - cu = [] - ic = [] - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne','le','ni','li'], oneSided=oneSided) - ncon = len(indices) - cl = numpy.zeros(ncon)#-self.getOption('XMAX')*numpy.ones(ncon) - cu = numpy.zeros(ncon) - cf = numpy.zeros(ncon+1) - ic = 2*numpy.ones(ncon, 'intc') - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - # Also figure out the number of equality and set the type - # of constraint to 5 - tmp0, __, __, __ = self.optProb.getOrdering( - ['ne', 'le'], oneSided=oneSided) - ic[0:len(tmp0)] = 5 - - if self.optProb.comm.rank == 0: - # Set history/hotstart - self._setHistory(storeHistory, hotStart) - - #====================================================================== - # PSQP - Objective Values Function - #====================================================================== - def pobj(n, x, f): - if self._checkEval(x): - self._internalEval(x) - - f = self.storedData['fobj'] - psqp.pyflush(self.getOption('IOUT')) - return f - - #====================================================================== - # PSQP - Constraint Values Function - #====================================================================== - def pcon(n, k, x, g): - if self._checkEval(x): - self._internalEval(x) - - g = self.storedData['fcon'][k-1] - psqp.pyflush(self.getOption('IOUT')) - return g - - #====================================================================== - # PSQP - Objective Gradients Function - #====================================================================== - def pdobj(n, x, df): - if self._checkEval(x): - self._internalEval(x) - - df = self.storedData['gobj'] - psqp.pyflush(self.getOption('IOUT')) - return df - - #====================================================================== - # PSQP - Constraint Gradients Function - #====================================================================== - def pdcon(n, k, x, dg): - if self._checkEval(x): - self._internalEval(x) - - dg = self.storedData['gcon'][k-1] - psqp.pyflush(self.getOption('IOUT')) - return dg - - # Setup argument list values - iterm = 0 - gmax = 0.0 - cmax = 0.0 - opt = self.getOption - - if not opt('IPRINT') <= 2: - raise Error('Incorrect output level setting (IPRINT) option. \ -Must be <= 2') - - if opt('IPRINT') != 0: - if os.path.isfile(opt('IFILE')): - os.remove(opt('IFILE')) - - # Run PSQP - t0 = time.time() - psqp.psqp_wrap(nvar, ncon, xs, xi, blx, bux, cf, ic, cl, cu, - opt('MIT'), opt('MFV'), opt('MET'), opt('MEC'), - opt('XMAX'), opt('TOLX'), opt('TOLC'), opt('TOLG'), - opt('RPF'), ff, gmax, cmax, opt('IPRINT'), - opt('IOUT'), opt('IFILE'), iterm, pobj, pdobj, - pcon, pdcon) - - optTime = time.time() - t0 - - if opt('IPRINT') > 0: - psqp.closeunit(opt('IPRINT')) - - # Broadcast a -1 to indcate SLSQP has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - # sol_inform['value'] = inform - # sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name): - pass - - - - diff --git a/pyoptsparse/pyoptsparse/pyPSQP/setup.py b/pyoptsparse/pyoptsparse/pyPSQP/setup.py deleted file mode 100644 index ec52109b4..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/setup.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyPSQP',parent_package,top_path) - - config.add_library('psqp', - sources=[os.path.join('source', '*.f'), - os.path.join('source', '*.f90')]), - config.add_extension('psqp', - sources=['source/f2py/psqp.pyf'], - libraries=['psqp']) - config.add_data_files('LICENSE','README') - - return config diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/README b/pyoptsparse/pyoptsparse/pyPSQP/source/README deleted file mode 100644 index cb8e09e69..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/README +++ /dev/null @@ -1,4 +0,0 @@ -This directory contains the Fortran 77 source for -PSQP, plus a pyOpt interfacing file called psqpw.f, -and two helper files called openunit.f and -closeunit.f to manipulate Fortran units from Python. diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/closeunit.f b/pyoptsparse/pyoptsparse/pyPSQP/source/closeunit.f deleted file mode 100644 index f1d9f8377..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/closeunit.f +++ /dev/null @@ -1,10 +0,0 @@ -C Helper subroutine to close files in the Fortran world - subroutine closeunit(unitnum) - - integer unitnum -Cf2py intent(in) unitnum - - close(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/f2py/README b/pyoptsparse/pyoptsparse/pyPSQP/source/f2py/README deleted file mode 100644 index 54e48d046..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/f2py/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the f2py signature file. -Do not edit these file unless you really know what you are doing. diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/f2py/psqp.pyf b/pyoptsparse/pyoptsparse/pyPSQP/source/f2py/psqp.pyf deleted file mode 100644 index b1ab0b544..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/f2py/psqp.pyf +++ /dev/null @@ -1,146 +0,0 @@ -! -*- f90 -*- -! Note: the context of this file is case sensitive. - -python module psqp__user__routines - interface psqp_user_interface - subroutine obj(nf,x,ff) - intent(callback) obj - external obj - integer intent(in) :: nf - double precision dimension(nf),intent(in),depend(nf) :: x - double precision intent(in,out) :: ff - end subroutine obj - subroutine dobj(nf,x,gf) - intent(callback) dobj - external dobj - integer intent(in) :: nf - double precision dimension(nf),intent(in),depend(nf) :: x - double precision dimension(nf),intent(in,out),depend(nf) :: gf - end subroutine dobj - subroutine con(nf,kc,x,fc) - intent(callback) con - external con - integer intent(in) :: nf - integer intent(in) :: kc - double precision dimension(nf),intent(in),depend(nf) :: x - double precision intent(in,out) :: fc - end subroutine con - subroutine dcon(nf,kc,x,gc) - intent(callback) dcon - external dcon - integer intent(in) :: nf - integer intent(in) :: kc - double precision dimension(nf),intent(in),depend(nf) :: x - double precision dimension(nf),intent(in,out),depend(nf) :: gc - end subroutine dcon - end interface psqp_user_interface -end python module psqp__user__routines -python module psqp ! in - interface ! in :psqp - subroutine psqp_wrap(nf,nc,x,ix,xl,xu,cf,ic,cl,cu,mit,mfv,met,mec,xmax,tolx,tolc,tolg,rpf,f,gmax,cmax,iprnt,iout,ifile,iterm) ! in :psqp:source/psqp_wrap.f - use psqp__user__routines - integer intent(in) :: nf - integer intent(in) :: nc - double precision dimension(nf),intent(inout),depend(nf) :: x - integer dimension(nf),intent(in),depend(nf) :: ix - double precision dimension(nf),intent(in),depend(nf) :: xl - double precision dimension(nf),intent(in),depend(nf) :: xu - double precision dimension(nc+1),intent(inout),depend(nc) :: cf - integer dimension(nc),intent(in),depend(nc) :: ic - double precision dimension(nc),intent(in),depend(nc) :: cl - double precision dimension(nc),intent(in),depend(nc) :: cu - integer intent(in) :: mit - integer intent(in) :: mfv - integer intent(in) :: met - integer intent(in) :: mec - double precision intent(in) :: xmax - double precision intent(in) :: tolx - double precision intent(in) :: tolc - double precision intent(in) :: tolg - double precision intent(in) :: rpf - double precision intent(inout) :: f - double precision intent(in) :: gmax - double precision intent(in) :: cmax - integer intent(in) :: iprnt - integer intent(in) :: iout - character*(*) intent(in) :: ifile - integer intent(inout) :: iterm - integer :: nres - integer :: ndec - integer :: nrem - integer :: nadd - integer :: nit - integer :: nfv - integer :: nfg - integer :: nfh - intent(callback) obj - external obj - intent(callback) dobj - external dobj - intent(callback) con - external con - intent(callback) dcon - external dcon - common /stat/ nres,ndec,nrem,nadd,nit,nfv,nfg,nfh - end subroutine psqp_wrap - subroutine pf1f01(nf,x,gf,g,ff,f,kd,ld,iext) ! in :psqp:wip/pqsubs.f - use psqp__user__routines - integer :: nf - double precision dimension(*) :: x - double precision dimension(*) :: gf - double precision dimension(*) :: g - double precision :: ff - double precision :: f - integer :: kd - integer :: ld - integer :: iext - integer :: nres - integer :: ndec - integer :: nrem - integer :: nadd - integer :: nit - integer :: nfv - integer :: nfg - integer :: nfh - intent(callback) obj - external obj - intent(callback) dobj - external dobj - common /stat/ nres,ndec,nrem,nadd,nit,nfv,nfg,nfh - end subroutine pf1f01 - subroutine pc1f01(nf,nc,x,fc,cf,cl,cu,ic,gc,cg,cmax,kd,ld) ! in :psqp:wip/pqsubs.f - use psqp__user__routines - integer :: nf - integer :: nc - double precision dimension(*) :: x - double precision :: fc - double precision dimension(*) :: cf - double precision dimension(*) :: cl - double precision dimension(*) :: cu - integer dimension(*) :: ic - double precision dimension(*) :: gc - double precision dimension(*) :: cg - double precision :: cmax - integer :: kd - integer :: ld - intent(callback) con - external con - intent(callback) dcon - external dcon - end subroutine pc1f01 - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) ! in :psqp:source/openunit.f - integer intent(in) :: unitnum - character*(*) intent(in) :: filename - character*(*) intent(in) :: filestatus - character*(*) intent(in) :: fileaction - integer intent(out) :: ierror - end subroutine openunit - subroutine pyflush(unitnum) - integer unitnum - return - end subroutine pyflush - subroutine closeunit(unitnum) ! in :psqp:source/closeunit.f - integer intent(in) :: unitnum - end subroutine closeunit - end interface -end python module psqp diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/mqsubs.f b/pyoptsparse/pyoptsparse/pyPSQP/source/mqsubs.f deleted file mode 100644 index 4e032eadc..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/mqsubs.f +++ /dev/null @@ -1,1953 +0,0 @@ -* SUBROUTINE MXDCMM ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* MULTIPLICATION OF A COLUMNWISE STORED DENSE RECTANGULAR MATRIX A -* BY A VECTOR X. -* -* PARAMETERS : -* II N NUMBER OF ROWS OF THE MATRIX A. -* II M NUMBER OF COLUMNS OF THE MATRIX A. -* RI A(N*M) RECTANGULAR MATRIX STORED COLUMNWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* RI X(M) INPUT VECTOR. -* RO Y(N) OUTPUT VECTOR EQUAL TO A*X. -* -* SUBPROGRAMS USED : -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE MXDCMM(N,M,A,X,Y) - INTEGER N,M - DOUBLE PRECISION A(*),X(*),Y(*) - INTEGER J,K - CALL MXVSET(N,0.0D 0,Y) - K=0 - DO 1 J=1,M - CALL MXVDIR(N,X(J),A(K+1),Y,Y) - K=K+N - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDPGB ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SOLUTION OF A SYSTEM OF LINEAR EQUATIONS WITH A DENSE SYMMETRIC -* POSITIVE DEFINITE MATRIX A+E USING THE FACTORIZATION A+E=L*D*TRANS(L) -* OBTAINED BY THE SUBROUTINE MXDPGF. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* RU X(N) ON INPUT THE RIGHT HAND SIDE OF A SYSTEM OF LINEAR -* EQUATIONS. ON OUTPUT THE SOLUTION OF A SYSTEM OF LINEAR -* EQUATIONS. -* II JOB OPTION. IF JOB=0 THEN X:=(A+E)**(-1)*X. IF JOB>0 THEN -* X:=L**(-1)*X. IF JOB<0 THEN X:=TRANS(L)**(-1)*X. -* -* METHOD : -* BACK SUBSTITUTION -* - SUBROUTINE MXDPGB(N,A,X,JOB) - INTEGER JOB,N - DOUBLE PRECISION A(*),X(*) - INTEGER I,II,IJ,J - IF (JOB.GE.0) THEN -* -* PHASE 1 : X:=L**(-1)*X -* - IJ = 0 - DO 20 I = 1,N - DO 10 J = 1,I - 1 - IJ = IJ + 1 - X(I) = X(I) - A(IJ)*X(J) - 10 CONTINUE - IJ = IJ + 1 - 20 CONTINUE - END IF - IF (JOB.EQ.0) THEN -* -* PHASE 2 : X:=D**(-1)*X -* - II = 0 - DO 30 I = 1,N - II = II + I - X(I) = X(I)/A(II) - 30 CONTINUE - END IF - IF (JOB.LE.0) THEN -* -* PHASE 3 : X:=TRANS(L)**(-1)*X -* - II = N* (N-1)/2 - DO 50 I = N - 1,1,-1 - IJ = II - DO 40 J = I + 1,N - IJ = IJ + J - 1 - X(I) = X(I) - A(IJ)*X(J) - 40 CONTINUE - II = II - I - 50 CONTINUE - END IF - RETURN - END -* SUBROUTINE MXDPGD ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF A DIRECTION OF NEGATIVE CURVATURE WITH RESPECT TO A -* DENSE SYMMETRIC MATRIX A USING THE FACTORIZATION A+E=L*D*TRANS(L) -* OBTAINED BY THE SUBROUTINE MXDPGF. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* RO X(N) COMPUTED DIRECTION OF NEGATIVE CURVATURE (I.E. -* TRANS(X)*A*X<0) IF IT EXISTS. -* II INF INFORMATION OBTAINED IN THE FACTORIZATION PROCESS. THE -* DIRECTION OF NEGATIVE CURVATURE EXISTS ONLY IF INF>0. -* -* METHOD : -* P.E.GILL, W.MURRAY : NEWTON TYPE METHODS FOR UNCONSTRAINED AND -* LINEARLY CONSTRAINED OPTIMIZATION, MATH. PROGRAMMING 28 (1974) -* PP. 311-350. -* - SUBROUTINE MXDPGD(N,A,X,INF) - INTEGER N, INF - DOUBLE PRECISION A(N*(N+1)/2), X(N) - INTEGER I, J, II, IJ - DOUBLE PRECISION ZERO, ONE - PARAMETER (ZERO = 0.0D0, ONE = 1.0D0) -C -C RIGHT HAND SIDE FORMATION -C - DO 1 I=1,N - X(I) = ZERO - 1 CONTINUE - IF (INF .LE. 0) RETURN - X(INF) = ONE -C -C BACK SUBSTITUTION -C - II = INF*(INF-1)/2 - DO 3 I = INF-1, 1, -1 - IJ = II - DO 2 J = I+1, INF - IJ = IJ + J - 1 - X(I) = X(I) - A(IJ)*X(J) - 2 CONTINUE - II = II - I - 3 CONTINUE - RETURN - END -* SUBROUTINE MXDPGF ALL SYSTEMS 89/12/01 -* PORTABILITY : ALL SYSTEMS -* 89/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* FACTORIZATION A+E=L*D*TRANS(L) OF A DENSE SYMMETRIC POSITIVE DEFINITE -* MATRIX A+E WHERE D AND E ARE DIAGONAL POSITIVE DEFINITE MATRICES AND -* L IS A LOWER TRIANGULAR MATRIX. IF A IS SUFFICIENTLY POSITIVE -* DEFINITE THEN E=0. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) ON INPUT A GIVEN DENSE SYMMETRIC (USUALLY POSITIVE -* DEFINITE) MATRIX A STORED IN THE PACKED FORM. ON OUTPUT THE -* COMPUTED FACTORIZATION A+E=L*D*TRANS(L). -* IO INF AN INFORMATION OBTAINED IN THE FACTORIZATION PROCESS. IF -* INF=0 THEN A IS SUFFICIENTLY POSITIVE DEFINITE AND E=0. IF -* INF<0 THEN A IS NOT SUFFICIENTLY POSITIVE DEFINITE AND E>0. IF -* INF>0 THEN A IS INDEFINITE AND INF IS AN INDEX OF THE -* MOST NEGATIVE DIAGONAL ELEMENT USED IN THE FACTORIZATION -* PROCESS. -* RU ALF ON INPUT A DESIRED TOLERANCE FOR POSITIVE DEFINITENESS. ON -* OUTPUT THE MOST NEGATIVE DIAGONAL ELEMENT USED IN THE -* FACTORIZATION PROCESS (IF INF>0). -* RO TAU MAXIMUM DIAGONAL ELEMENT OF THE MATRIX E. -* -* METHOD : -* P.E.GILL, W.MURRAY : NEWTON TYPE METHODS FOR UNCONSTRAINED AND -* LINEARLY CONSTRAINED OPTIMIZATION, MATH. PROGRAMMING 28 (1974) -* PP. 311-350. -* - SUBROUTINE MXDPGF(N,A,INF,ALF,TAU) - DOUBLE PRECISION ALF,TAU - INTEGER INF,N - DOUBLE PRECISION A(*) - DOUBLE PRECISION BET,DEL,GAM,RHO,SIG,TOL - INTEGER I,IJ,IK,J,K,KJ,KK,L - L = 0 - INF = 0 - TOL = ALF -* -* ESTIMATION OF THE MATRIX NORM -* - ALF = 0.0D0 - BET = 0.0D0 - GAM = 0.0D0 - TAU = 0.0D0 - KK = 0 - DO 20 K = 1,N - KK = KK + K - BET = MAX(BET,ABS(A(KK))) - KJ = KK - DO 10 J = K + 1,N - KJ = KJ + J - 1 - GAM = MAX(GAM,ABS(A(KJ))) - 10 CONTINUE - 20 CONTINUE - BET = MAX(TOL,BET,GAM/N) -* DEL = TOL*BET - DEL = TOL*MAX(BET,1.0D0) - KK = 0 - DO 60 K = 1,N - KK = KK + K -* -* DETERMINATION OF A DIAGONAL CORRECTION -* - SIG = A(KK) - IF (ALF.GT.SIG) THEN - ALF = SIG - L = K - END IF - GAM = 0.0D0 - KJ = KK - DO 30 J = K + 1,N - KJ = KJ + J - 1 - GAM = MAX(GAM,ABS(A(KJ))) - 30 CONTINUE - GAM = GAM*GAM - RHO = MAX(ABS(SIG),GAM/BET,DEL) - IF (TAU.LT.RHO-SIG) THEN - TAU = RHO - SIG - INF = -1 - END IF -* -* GAUSSIAN ELIMINATION -* - A(KK) = RHO - KJ = KK - DO 50 J = K + 1,N - KJ = KJ + J - 1 - GAM = A(KJ) - A(KJ) = GAM/RHO - IK = KK - IJ = KJ - DO 40 I = K + 1,J - IK = IK + I - 1 - IJ = IJ + 1 - A(IJ) = A(IJ) - A(IK)*GAM - 40 CONTINUE - 50 CONTINUE - 60 CONTINUE - IF (L.GT.0 .AND. ABS(ALF).GT.DEL) INF = L - RETURN - END -* SUBROUTINE MXDPGN ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* ESTIMATION OF THE MINIMUM EIGENVALUE AND THE CORRESPONDING EIGENVECTOR -* OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX A+E USING THE -* FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE SUBROUTINE MXDPGF. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* RO X(N) ESTIMATED EIGENVECTOR. -* RO ALF ESTIMATED EIGENVALUE. -* II JOB OPTION. IF JOB=0 THEN ONLY ESTIMATED EIGENVALUE IS -* COMPUTED. IS JOB>0 THEN BOTH ESTIMATED EIGENVALUE AND -* ESTIMATED EIGENVECTOR ARE COMPUTED BY JOB ITERATIONS. -* -* SUBPROGRAMS USED : -* S MXDPGB BACK SUBSTITUTION. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* -* METHOD : -* A.K.CLINE, C.B.MOLER, G.W.STEWART, J.H.WILKINSON : AN ESTIMATE -* FOR THE CONDITION NUMBER OF A MATRIX. SIAM J. NUMER. ANAL. 16 -* (1979) 368-373. -* - SUBROUTINE MXDPGN(N,A,X,ALF,JOB) - INTEGER N,JOB - DOUBLE PRECISION A(N*(N+1)/2),X(N),ALF - DOUBLE PRECISION XP,XM,FP,FM,MXVDOT - INTEGER I,K,IK,KK - DOUBLE PRECISION ZERO,ONE - PARAMETER (ZERO=0.0D 0,ONE=1.0D 0) -C -C COMPUTATION OF THE VECTOR V WITH POSSIBLE MAXIMUM NORM SUCH -C THAT L*D**(1/2)*V=U WHERE U HAS ELEMENTS +1 OR -1 -C - DO 2 I=1,N - X(I)=ZERO - 2 CONTINUE - KK=0 - DO 6 K=1,N - KK=KK+K - XP=-X(K)+ONE - XM=-X(K)-ONE - FP=ABS(XP) - FM=ABS(XM) - IK=KK - DO 3 I=K+1,N - IK=IK+I-1 - FP=FP+ABS(X(I)+A(IK)*XP) - FM=FM+ABS(X(I)+A(IK)*XM) - 3 CONTINUE - IF(FP.GE.FM) THEN - X(K)=XP - IK=KK - DO 4 I=K+1,N - IK=IK+I-1 - X(I)=X(I)+A(IK)*XP - 4 CONTINUE - ELSE - X(K)=XM - IK=KK - DO 5 I=K+1,N - IK=IK+I-1 - X(I)=X(I)+A(IK)*XM - 5 CONTINUE - ENDIF - 6 CONTINUE -C -C COMPUTATION OF THE VECTOR X SUCH THAT -C D**(1/2)*TRANS(L)*X=V -C - FM=ZERO - KK=0 - DO 7 K=1,N - KK=KK+K - IF (JOB.LE.0) THEN - FP=SQRT(A(KK)) - X(K)=X(K)/FP - FM=FM+X(K)*X(K) - ELSE - X(K)=X(K)/A(KK) - ENDIF - 7 CONTINUE - FP=DBLE(N) - IF (JOB.LE.0) THEN -C -C FIRST ESTIMATION OF THE MINIMUM EIGENVALUE BY THE FORMULA -C ALF=(TRANS(U)*U)/(TRANS(V)*V) -C - ALF=FP/FM - RETURN - ENDIF - FM=ZERO - KK=N*(N+1)/2 - DO 9 K=N,1,-1 - IK=KK - DO 8 I=K+1,N - IK=IK+I-1 - X(K)=X(K)-A(IK)*X(I) - 8 CONTINUE - FM=FM+X(K)*X(K) - KK=KK-K - 9 CONTINUE - FM=SQRT(FM) - IF (JOB.LE.1) THEN -C -C SECOND ESTIMATION OF THE MINIMUM EIGENVALUE BY THE FORMULA -C ALF=SQRT(TRANS(U)*U)/SQRT(TRANS(X)*X) -C - ALF=SQRT(FP)/FM - ELSE -C -C INVERSE ITERATIONS -C - DO 11 K=2,JOB -C -C SCALING THE VECTOR X BY ITS NORM -C - DO 10 I=1,N - X(I)=X(I)/FM - 10 CONTINUE - CALL MXDPGB(N,A,X,0) - FM=SQRT(MXVDOT(N,X,X)) - 11 CONTINUE - ALF=ONE/FM - ENDIF -C -C SCALING THE VECTOR X BY ITS NORM -C - DO 12 I=1,N - X(I)=X(I)/FM - 12 CONTINUE - RETURN - END -* FUNCTION MXDPGP ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF THE NUMBER MXDPGP=TRANS(X)*D**(-1)*Y WHERE D IS A -* DIAGONAL MATRIX IN THE FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* RI X(N) INPUT VECTOR. -* RI Y(N) INPUT VECTOR. -* RR MXDPGP COMPUTED NUMBER MXDPGP=TRANS(X)*D**(-1)*Y. -* - FUNCTION MXDPGP(N,A,X,Y) - INTEGER N - DOUBLE PRECISION A(*),X(*),Y(*),MXDPGP - DOUBLE PRECISION TEMP - INTEGER I,J - J = 0 - TEMP = 0.0D0 - DO 10 I = 1,N - J = J + I - TEMP = TEMP + X(I)*Y(I)/A(J) - 10 CONTINUE - MXDPGP = TEMP - RETURN - END -* SUBROUTINE MXDPGS ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SCALING OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX A+E USING THE -* FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE SUBROUTINE MXDPGF. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* RI ALF SCALING FACTOR. -* - SUBROUTINE MXDPGS(N,A,ALF) - DOUBLE PRECISION ALF - INTEGER N - DOUBLE PRECISION A(*) - INTEGER I,J - J = 0 - DO 10 I = 1,N - J = J + I - A(J) = A(J)*ALF - 10 CONTINUE - RETURN - END -* SUBROUTINE MXDPGU ALL SYSTEMS 89/12/01 -* PORTABILITY : ALL SYSTEMS -* 89/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* CORRECTION OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX A+E IN THE -* FACTORED FORM A+E=L*D*TRANS(L) OBTAINED BY THE SUBROUTINE MXDPGF. -* THE CORRECTION IS DEFINED AS A+E:=A+E+ALF*X*TRANS(X) WHERE ALF IS A -* GIVEN SCALING FACTOR AND X IS A GIVEN VECTOR. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) FACTORIZATION A+E=L*D*TRANS(L) OBTAINED BY THE -* SUBROUTINE MXDPGF. -* RI ALF SCALING FACTOR IN THE CORRECTION TERM. -* RI X(N) VECTOR IN THE CORRECTION TERM. -* RA Y(N) AUXILIARY VECTOR. -* -* METHOD : -* P.E.GILL, W.MURRAY, M.SAUNDERS: METHODS FOR COMPUTING AND MODIFYING -* THE LDV FACTORS OF A MATRIX, MATH. OF COMP. 29 (1974) PP. 1051-1077. -* - SUBROUTINE MXDPGU(N,A,ALF,X,Y) - DOUBLE PRECISION ZERO,ONE,FOUR,CON - PARAMETER (ZERO=0.0D0,ONE=1.0D0,FOUR=4.0D0,CON=1.0D-8) - DOUBLE PRECISION ALF,ALFR - INTEGER N - DOUBLE PRECISION A(*),X(*),Y(*) - DOUBLE PRECISION B,D,P,R,T,TO - INTEGER I,II,IJ,J - IF (ALF.GE.ZERO) THEN -* -* FORWARD CORRECTION IN CASE WHEN THE SCALING FACTOR IS NONNEGATIVE -* - ALFR = SQRT(ALF) - CALL MXVSCL(N,ALFR,X,Y) - TO = ONE - II = 0 - DO 30 I = 1,N - II = II + I - D = A(II) - P = Y(I) - T = TO + P*P/D - R = TO/T - A(II) = D/R - B = P/ (D*T) - IF (A(II).LE.FOUR*D) THEN -* -* AN EASY FORMULA FOR LIMITED DIAGONAL ELEMENT -* - IJ = II - DO 10 J = I + 1,N - IJ = IJ + J - 1 - D = A(IJ) - Y(J) = Y(J) - P*D - A(IJ) = D + B*Y(J) - 10 CONTINUE - ELSE -* -* A MORE COMPLICATE BUT NUMERICALLY STABLE FORMULA FOR UNLIMITED -* DIAGONAL ELEMENT -* - IJ = II - DO 20 J = I + 1,N - IJ = IJ + J - 1 - D = A(IJ) - A(IJ) = R*D + B*Y(J) - Y(J) = Y(J) - P*D - 20 CONTINUE - END IF - TO = T - 30 CONTINUE - ELSE -* -* BACKWARD CORRECTION IN CASE WHEN THE SCALING FACTOR IS NEGATIVE -* - ALFR = SQRT(-ALF) - CALL MXVSCL(N,ALFR,X,Y) - TO = ONE - IJ = 0 - DO 50 I = 1,N - D = Y(I) - DO 40 J = 1,I - 1 - IJ = IJ + 1 - D = D - A(IJ)*Y(J) - 40 CONTINUE - Y(I) = D - IJ = IJ + 1 - TO = TO - D*D/A(IJ) - 50 CONTINUE - IF (TO.LE.ZERO) TO = CON - II = N* (N+1)/2 - DO 70 I = N,1,-1 - D = A(II) - P = Y(I) - T = TO + P*P/D - A(II) = D*TO/T - B = -P/ (D*TO) - TO = T - IJ = II - DO 60 J = I + 1,N - IJ = IJ + J - 1 - D = A(IJ) - A(IJ) = D + B*Y(J) - Y(J) = Y(J) + P*D - 60 CONTINUE - II = II - I - 70 CONTINUE - END IF - RETURN - END -* SUBROUTINE MXDPRB ALL SYSTEMS 89/12/01 -* PORTABILITY : ALL SYSTEMS -* 89/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SOLUTION OF A SYSTEM OF LINEAR EQUATIONS WITH A DENSE SYMMETRIC -* POSITIVE DEFINITE MATRIX A USING THE FACTORIZATION A=TRANS(R)*R. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) FACTORIZATION A=TRANS(R)*R. -* RU X(N) ON INPUT THE RIGHT HAND SIDE OF A SYSTEM OF LINEAR -* EQUATIONS. ON OUTPUT THE SOLUTION OF A SYSTEM OF LINEAR -* EQUATIONS. -* II JOB OPTION. IF JOB=0 THEN X:=A**(-1)*X. IF JOB>0 THEN -* X:=TRANS(R)**(-1)*X. IF JOB<0 THEN X:=R**(-1)*X. -* -* METHOD : -* BACK SUBSTITUTION -* - SUBROUTINE MXDPRB(N,A,X,JOB) - INTEGER JOB,N - DOUBLE PRECISION A(*),X(*) - INTEGER I,II,IJ,J - IF (JOB.GE.0) THEN -* -* PHASE 1 : X:=TRANS(R)**(-1)*X -* - IJ = 0 - DO 20 I = 1,N - DO 10 J = 1,I - 1 - IJ = IJ + 1 - X(I) = X(I) - A(IJ)*X(J) - 10 CONTINUE - IJ = IJ + 1 - X(I) = X(I)/A(IJ) - 20 CONTINUE - END IF - IF (JOB.LE.0) THEN -* -* PHASE 2 : X:=R**(-1)*X -* - II = N* (N+1)/2 - DO 40 I = N,1,-1 - IJ = II - DO 30 J = I + 1,N - IJ = IJ + J - 1 - X(I) = X(I) - A(IJ)*X(J) - 30 CONTINUE - X(I) = X(I)/A(II) - II = II - I - 40 CONTINUE - END IF - RETURN - END -* SUBROUTINE MXDPRC ALL SYSTEMS 92/12/01 -* PORTABILITY : ALL SYSTEMS -* 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* CORRECTION OF A SINGULAR DENSE SYMMETRIC POSITIVE SEMIDEFINITE MATRIX -* A DECOMPOSED AS A=TRANS(R)*R. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* IO INF AN INFORMATION OBTAINED IN THE CORRECTION PROCESS. IF -* INF=0 THEN A IS SUFFICIENTLY POSITIVE DEFINITE. IF -* INF<0 THEN A IS NOT SUFFICIENTLY POSITIVE DEFINITE. -* PROCESS. -* RI TOL DESIRED TOLERANCE FOR POSITIVE DEFINITENESS. -* - SUBROUTINE MXDPRC(N,A,INF,TOL) - INTEGER N,INF - DOUBLE PRECISION A(N*(N+1)/2),TOL - DOUBLE PRECISION TOL1,TEMP - INTEGER L,I - DOUBLE PRECISION ZERO - PARAMETER (ZERO=0.0D 0) - INF=0 - TOL1=SQRT(TOL) - TEMP=TOL1 - DO 3 I=1,N*(N+1)/2 - TEMP=MAX(TEMP,ABS(A(I))) - 3 CONTINUE - TEMP=TEMP*TOL1 - L=0 - DO 1 I=1,N - L=L+I - IF (ABS(A(L)).LE.TEMP) THEN - A(L)=SIGN(TEMP,A(L)) - INF=-1 - ENDIF - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDPRM ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* MULTIPLICATION OF A GIVEN VECTOR X BY A DENSE SYMMETRIC POSITIVE -* DEFINITE MATRIX A USING THE FACTORIZATION A=TRANS(R)*R. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) FACTORIZATION A=TRANS(R)*R. -* RU X(N) ON INPUT THE GIVEN VECTOR. ON OUTPUT THE RESULT OF -* MULTIPLICATION. -* II JOB OPTION. IF JOB=0 THEN X:=A*X. IF JOB>0 THEN X:=R*X. -* IF JOB<0 THEN X:=TRANS(R)*X. -* - SUBROUTINE MXDPRM( N, A, X, JOB) - INTEGER N, JOB - DOUBLE PRECISION A(N*(N+1)/2), X(N) - INTEGER I, J, II, IJ - IF (JOB .GE. 0) THEN -C -C PHASE 1 : X:=R*X -C - II = 0 - DO 3 I = 1, N - II = II + I - X(I) = A(II) * X(I) - IJ = II - DO 2 J = I+1, N - IJ = IJ + J - 1 - X(I) = X(I) + A(IJ) * X(J) - 2 CONTINUE - 3 CONTINUE - ENDIF - IF (JOB .LE. 0) THEN -C -C PHASE 2 : X:=TRANS(R)*X -C - IJ = N*(N+1)/2 - DO 6 I = N, 1, -1 - X(I) = A(IJ) * X(I) - DO 5 J = I-1, 1, -1 - IJ = IJ - 1 - X(I) = X(I) + A(IJ) * X(J) - 5 CONTINUE - IJ = IJ - 1 - 6 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE MXDRGR ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* PLANE ROTATION IS APPLIED TO A ROWWISE STORED DENSE RECTANGULAR -* MATRIX A. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX A. -* RU A(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* II K FIRST INDEX OF THE PLANE ROTATION. -* II L SECOND INDEX OF THE PLANE ROTATION. -* RI CK DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* RI CL OFF-DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* II IER TYPE OF THE PLANE ROTATION. IER=0-GENERAL PLANE ROTATION. -* IER=1-PERMUTATION. IER=2-TRANSFORMATION SUPPRESSED. -* -* SUBPROGRAMS USED : -* S MXVROT PLANE ROTATION APPLIED TO TWO ELEMENTS. -* - SUBROUTINE MXDRGR(N,A,K,L,CK,CL,IER) - INTEGER N,K,L,IER - DOUBLE PRECISION A(*),CK,CL - INTEGER I,IK,IL - IF (IER.NE.0.AND.IER.NE.1) RETURN - IK=(K-1)*N - IL=(L-1)*N - DO 1 I=1,N - IK=IK+1 - IL=IL+1 - CALL MXVROT(A(IK),A(IL),CK,CL,IER) - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDRMD ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* MULTIPLICATION OF A ROWWISE STORED DENSE RECTANGULAR MATRIX A BY -* A VECTOR X AND ADDITION OF A SCALED VECTOR ALF*Y. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX A. -* II M NUMBER OF ROWS OF THE MATRIX A. -* RI A(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* RI X(N) INPUT VECTOR. -* RI ALF SCALING FACTOR. -* RI Y(M) INPUT VECTOR. -* RO Z(M) OUTPUT VECTOR EQUAL TO A*X+ALF*Y. -* - SUBROUTINE MXDRMD(N,M,A,X,ALF,Y,Z) - INTEGER N,M - DOUBLE PRECISION A(M*N),X(N),ALF,Y(M),Z(M) - DOUBLE PRECISION TEMP - INTEGER I,J,K - K=0 - DO 2 J=1,M - TEMP=ALF*Y(J) - DO 1 I=1,N - TEMP=TEMP+A(K+I)*X(I) - 1 CONTINUE - Z(J)=TEMP - K=K+N - 2 CONTINUE - RETURN - END -* SUBROUTINE MXDRMI ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* ROWWISE STORED DENSE RECTANGULAR MATRIX A IS SET TO BE A PART OF THE -* UNIT MATRIX. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX A. -* II M NUMBER OF ROWS OF THE MATRIX A. -* RO A(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE ONE-DIMENSIONAL -* ARRAY. THIS MATRIX IS SET TO TRANS([I,0]). -* - SUBROUTINE MXDRMI(N,M,A) - INTEGER N,M - DOUBLE PRECISION A(M*N) - INTEGER I,J,K - DOUBLE PRECISION ZERO,ONE - PARAMETER (ZERO=0.0D 0,ONE=1.0D 0) - K=0 - DO 2 J=1,M - DO 1 I=1,N - A(I+K)=ZERO - IF (I.EQ.J) A(I+K)=ONE - 1 CONTINUE - K=K+N - 2 CONTINUE - RETURN - END -* SUBROUTINE MXDRMM ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* MULTIPLICATION OF A ROWWISE STORED DENSE RECTANGULAR MATRIX A BY -* A VECTOR X. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX A. -* II M NUMBER OF ROWS OF THE MATRIX A. -* RI A(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* RI X(N) INPUT VECTOR. -* RO Y(M) OUTPUT VECTOR EQUAL TO A*X. -* - SUBROUTINE MXDRMM(N,M,A,X,Y) - INTEGER N,M - DOUBLE PRECISION A(*),X(*),Y(*) - DOUBLE PRECISION TEMP - INTEGER I,J,K - K=0 - DO 2 J=1,M - TEMP=0.0D 0 - DO 1 I=1,N - TEMP=TEMP+A(K+I)*X(I) - 1 CONTINUE - Y(J)=TEMP - K=K+N - 2 CONTINUE - RETURN - END -* FUNCTION MXDRMN ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* EUCLIDEAN NORM OF A PART OF THE I-TH COLUMN OF A ROWWISE STORED DENSE -* RECTANGULAR MATRIX A IS COMPUTED. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX A. -* II M NUMBER OF ROWS OF THE MATRIX A. -* RI A(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* II I INDEX OF THE COLUMN WHOSE NORM IS COMPUTED. -* II J INDEX OF THE FIRST ELEMENT FROM WHICH THE NORM IS COMPUTED. -* - FUNCTION MXDRMN(N,M,A,I,J) - INTEGER N,M,I,J - DOUBLE PRECISION A(M*N),MXDRMN - DOUBLE PRECISION POM,DEN - INTEGER K,L - DOUBLE PRECISION ZERO - PARAMETER (ZERO=0.0D 0) - DEN=ZERO - L=(J-1)*N - DO 1 K=J,M - DEN=MAX(DEN,ABS(A(L+I))) - L=L+N - 1 CONTINUE - POM=ZERO - IF (DEN.GT.ZERO) THEN - L=(J-1)*N - DO 2 K=J,M - POM=POM+(A(L+I)/DEN)**2 - L=L+N - 2 CONTINUE - ENDIF - MXDRMN=DEN*SQRT(POM) - RETURN - END -* SUBROUTINE MXDRMV ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* K-TH COLUMN OF A ROWWISE STORED DENSE RECTANGULAR MATRIX A IS COPIED -* TO THE VECTOR X. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX A. -* II M NUMBER OF ROWS OF THE MATRIX A. -* RI A(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* RO X(M) OUTPUT VECTOR SUCH THAT X(J)=A(J,K) FOR ALL J. -* II K INDEX OF THE ROW BEING COPIED TO THE OUTPUT VECTOR. -* - SUBROUTINE MXDRMV(N,M,A,X,K) - INTEGER N,M,K - DOUBLE PRECISION A(*),X(*) - INTEGER I,J - IF (K.LT.1.OR.K.GT.N) RETURN - I=K - DO 1 J=1,M - X(J)=A(I) - I=I+N - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDRQF ALL SYSTEMS 92/12/01 -* PORTABILITY : ALL SYSTEMS -* 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* QR DECOMPOSITION OF ROWWISE STORED DENSE RECTANGULAR MATRIX Q USING -* HOUSEHOLDER TRANSFORMATIONS WITHOUT PIVOTING. -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX Q. -* II M NUMBER OF ROWS OF THE MATRIX Q. -* RU Q(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY. -* RO R(N*(N+1)/2) UPPER TRIANGULAR MATRIX STORED IN THE PACKED FORM. -* -* SUBPROGRAMS USED : -* S MXDRMN EUCLIDEAN NORM OF A PART OF THE ROWWISE STORED -* RECTANGULAR MATRIX COLUMN. -* -* METHOD : -* P.A.BUSSINGER, G.H.GOLUB : LINEAR LEAST SQUARES SOLUTION BY -* HOUSEHOLDER TRANSFORMATION. NUMER. MATH. 7 (1965) 269-276. -* - SUBROUTINE MXDRQF(N,M,Q,R) - INTEGER N,M - DOUBLE PRECISION Q(M*N),R(N*(N+1)/2) - DOUBLE PRECISION ALF,POM,MXDRMN - INTEGER I,J,K,L,JP,KP,NM - DOUBLE PRECISION ZERO,ONE - PARAMETER (ZERO=0.0D 0,ONE=1.0D 0) - NM=MIN(N,M) -C -C QR DECOMPOSITION -C - L=0 - KP=0 - DO 6 K=1,NM - POM=MXDRMN(N,M,Q,K,K) - IF (Q(KP+K).NE.ZERO) POM=SIGN(POM,Q(KP+K)) - R(L+K)=-POM - JP=0 - DO 1 J=1,K-1 - R(L+J)=Q(JP+K) - Q(JP+K)=ZERO - JP=JP+N - 1 CONTINUE - IF (POM.NE.ZERO) THEN -C -C HOUSEHOLDER TRANSFORMATION -C - DO 2 J=K,M - Q(JP+K)=Q(JP+K)/POM - JP=JP+N - 2 CONTINUE - Q(KP+K)=Q(KP+K)+ONE - DO 5 I=K+1,N - ALF=ZERO - JP=KP - DO 3 J=K,M - ALF=ALF+Q(JP+K)*Q(JP+I) - JP=JP+N - 3 CONTINUE - ALF=ALF/Q(KP+K) - JP=KP - DO 4 J=K,M - Q(JP+I)=Q(JP+I)-ALF*Q(JP+K) - JP=JP+N - 4 CONTINUE - 5 CONTINUE - ENDIF - L=L+K - KP=KP+N - 6 CONTINUE -C -C EXPLICIT FORMULATION OF THE ORTHOGONAL MATRIX -C - KP=N*N - DO 11 K=N,1,-1 - KP=KP-N - IF (Q(KP+K).NE.ZERO) THEN - DO 9 I=K+1,N - ALF=ZERO - JP=KP - DO 7 J=K,M - ALF=ALF+Q(JP+K)*Q(JP+I) - JP=JP+N - 7 CONTINUE - ALF=ALF/Q(KP+K) - JP=KP - DO 8 J=K,M - Q(JP+I)=Q(JP+I)-ALF*Q(JP+K) - JP=JP+N - 8 CONTINUE - 9 CONTINUE - JP=KP - DO 10 J=K,M - Q(JP+K)=-Q(JP+K) - JP=JP+N - 10 CONTINUE - ENDIF - Q(KP+K)=Q(KP+K)+ONE - 11 CONTINUE - RETURN - END -* SUBROUTINE MXDRQU ALL SYSTEMS 92/12/01 -* PORTABILITY : ALL SYSTEMS -* 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* UPDATE OF A QR DECOMPOSITION. THIS QR DECOMPOSITION IS UPDATED -* BY THE RULE Q*R:=Q*R+ALF*X*TRANS(Y). -* -* PARAMETERS : -* II N NUMBER OF COLUMNS OF THE MATRIX Q. -* II M NUMBER OF ROWS OF THE MATRIX Q. -* RU Q(M*N) RECTANGULAR MATRIX STORED ROWWISE IN THE -* ONE-DIMENSIONAL ARRAY (PART OF THE ORTHOGONAL MATRIX). -* RU R(N*(N+1)/2) UPPER TRIANGULAR MATRIX STORED IN A PACKED FORM. -* RI ALF SCALAR PARAMETER. -* RI X(M) INPUT VECTOR. -* RI Y(N) INPUT VECTOR. -* RA Z(N) AUXILIARY VECTOR. -* IO INF INFORMATION. IF INF=0 THEN X LIES IN THE COLUMN SPACE OF Q. -* IF INF=1 THEN X DOES NOT LIE IN THE COLUMN SPACE OF Q. -* -* SUBPROGRAMS USED : -* RF MXVNOR EUCLIDEAN NORM OF A VECTOR. -* S MXVORT COMPUTATION OF THE PLANE ROTATION MATRIX. -* S MXVROT PLANE ROTATION IS APPLIED TO TWO NUMBERS. -* -* METHOD : -* J.W.DANIEL, W.B.GRAGG, L.KAUFMAN, G.W.STEWARD : REORTHOGONALIZATION -* AND STABLE ALGORITHMS FOR UPDATING THE GRAM-SCHMIDT QR FACTORIZATION. -* MATHEMATICS OF COMPUTATION 30 (1976) 772-795. - SUBROUTINE MXDRQU(N,M,Q,R,ALF,X,Y,Z,INF) - INTEGER N,M,INF - DOUBLE PRECISION Q(M*N),R(N*(N+1)/2),ALF,X(M),Y(N),Z(N) - DOUBLE PRECISION CK,CL,ZK,ZL,MXVNOR - INTEGER J,K,L,KJ,KK,IER - DOUBLE PRECISION ONE,CON - PARAMETER (ONE=1.0D 0,CON=1.0D-10) - INF=0 - KK=N*(N+1)/2 -C -C COMPUTATION OF THE VECTOR TRANS(Q)*X -C - CALL MXDCMM(N,M,Q,X,Z) - IF (M.GT.N) THEN -C -C IF X DOES NOT LIE IN THE COLUMN SPACE OF Q WE HAVE TO USE -C A SUBPROBLEM WHOSE DIMENSION IS BY ONE GREATER (INF=1). -C - ZK=MXVNOR(M,X) - CALL MXDRMD(N,M,Q,Z,-ONE,X,X) - ZL=MXVNOR(M,X) - IF (ZL.GT.CON*ZK) THEN - INF=1 - CALL MXVSCL(M,-ONE/ZL,X,X) - CALL MXVORT(Z(N),ZL,CK,CL,IER) - IF (IER.EQ.0.OR.IER.EQ.1) THEN - CALL MXVROT(R(KK),ZL,CK,CL,IER) - KJ=N - DO 1 J=1,M - CALL MXVROT(Q(KJ),X(J),CK,CL,IER) - KJ=KJ+N - 1 CONTINUE - ENDIF - ENDIF - ENDIF -C -C APPLICATION OF PLANE ROTATIONS TO THE VECTOR Z SO THAT -C TRANS(Q1)*Z=E1 WHERE Q1 IS AN ORTHOGONAL MATRIX (ACCUMULATION OF -C THE PLANE ROTATIONS) AND E1 IS THE FIRST COLUMN OF THE UNIT -C MATRIX. AT THE SAME TIME BOTH THE UPPER HESSENBERG MATRIX -C TRANS(Q1)*R AND THE ORTHOGONAL MATRIX Q*Q1 ARE CONSTRUCTED SO THAT -C Q*Q1*R1=Q*Q1*(TRANS(Q1)*R+ALF*E1*TRANS(Y)) WHERE R1 IS AN UPPER -C HESSENBERG MATRIX. -C - DO 4 L=N,2,-1 - K=L-1 - KK=KK-L - CALL MXVORT(Z(K),Z(L),CK,CL,IER) - IF (IER.EQ.0.OR.IER.EQ.1) THEN - CALL MXVROT(R(KK),Z(L),CK,CL,IER) - KJ=KK - DO 2 J=L,N - KJ=KJ+J-1 - CALL MXVROT(R(KJ),R(KJ+1),CK,CL,IER) - 2 CONTINUE - KJ=K - DO 3 J=1,M - CALL MXVROT(Q(KJ),Q(KJ+1),CK,CL,IER) - KJ=KJ+N - 3 CONTINUE - ENDIF - 4 CONTINUE - Z(1)=ALF*Z(1) - KJ=1 - DO 5 J=1,N - R(KJ)=R(KJ)+Z(1)*Y(J) - KJ=KJ+J - 5 CONTINUE -C -C APPLICATION OF PLANE ROTATIONS TO THE UPPER HESSENBERG MATRIX R1 -C GIVEN ABOVE SO THAT R2=TRANS(Q2)*R1 WHERE Q2 IS AN ORTHOGONAL -C MATRIX (ACCUMULATION OF THE PLANE ROTATIONS) AND R2 IS AN UPPER -C TRIANGULAR MATRIX. WE OBTAIN THE NEW QR DECOMPOSITION Q*Q1*Q2*R2. -C - KK=1 - DO 8 L=2,N - K=L-1 - CALL MXVORT(R(KK),Z(L),CK,CL,IER) - IF (IER.EQ.0.OR.IER.EQ.1) THEN - KJ=KK - DO 6 J=L,N - KJ=KJ+J-1 - CALL MXVROT(R(KJ),R(KJ+1),CK,CL,IER) - 6 CONTINUE - KJ=K - DO 7 J=1,M - CALL MXVROT(Q(KJ),Q(KJ+1),CK,CL,IER) - KJ=KJ+N - 7 CONTINUE - ENDIF - KK=KK+L - 8 CONTINUE -C -C BACK TRANSFORMATION OF THE GREATER SUBPROBLEM IF INF=1. -C - IF (INF.EQ.1) THEN - CALL MXVORT(R(KK),ZL,CK,CL,IER) - IF (IER.EQ.0.OR.IER.EQ.1) THEN - KJ=N - DO 9 J=1,M - CALL MXVROT(Q(KJ),X(J),CK,CL,IER) - KJ=KJ+N - 9 CONTINUE - ENDIF - ENDIF - RETURN - END -* SUBROUTINE MXDSDA ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* A DENSE SYMMETRIC MATRIX A IS AUGMENTED BY THE SCALED UNIT MATRIX -* SUCH THAT A:=A+ALF*I (I IS THE UNIT MATRIX OF ORDER N). -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RI ALF SCALING FACTOR. -* - SUBROUTINE MXDSDA(N,A,ALF) - INTEGER N - DOUBLE PRECISION A(*),ALF - INTEGER I,J - J = 0 - DO 1 I = 1, N - J = J + I - A(J)=A(J)+ALF - 1 CONTINUE - RETURN - END -* FUNCTION MXDSDL ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE MINIMUM DIAGONAL ELEMENT OF A DENSE SYMMETRIC -* MATRIX. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* IO INF INDEX OF THE MINIMUM DIAGONAL ELEMENT OF THE MATRIX A. -* RR MXDSDL MINIMUM DIAGONAL ELEMENT OF THE MATRIX A. -* - FUNCTION MXDSDL(N,A,INF) - INTEGER N,INF - DOUBLE PRECISION A(N*(N+1)/2),MXDSDL - DOUBLE PRECISION TEMP - INTEGER I,J - J=1 - INF=1 - TEMP=A(1) - DO 1 I=2,N - J=J+I - IF (TEMP.GT.A(J)) THEN - INF=J - TEMP=A(J) - ENDIF - 1 CONTINUE - MXDSDL=TEMP - RETURN - END -* SUBROUTINE MXDSMA ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DENSE SYMMETRIC MATRIX AUGMENTED BY THE SCALED DENSE SYMMETRIC MATRIX. -* -* PARAMETERS : -* II N ORDER OF THE MATRICES. -* RI ALF SCALING FACTOR. -* RI A(N*(N+1)/2) INPUT MATRIX. -* RI B(N*(N+1)/2) INPUT MATRIX. -* RO C(N*(N+1)/2) OUTPUT MATRIX WHERE C:=B+ALF*A. -* - SUBROUTINE MXDSMA(N,ALF,A,B,C) - INTEGER N - DOUBLE PRECISION ALF,A(N*(N+1)/2),B(N*(N+1)/2),C(N*(N+1)/2) - INTEGER I - DO 1 I=1,N*(N+1)/2 - C(I)=B(I)+ALF*A(I) - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDSMC ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COPYING OF A DENSE SYMMETRIC MATRIX. -* -* PARAMETERS : -* II N ORDER OF THE MATRICES A AND B. -* RI A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RO B(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM -* WHERE B:=A. -* - SUBROUTINE MXDSMC(N,A,B) - INTEGER N - DOUBLE PRECISION A(N*(N+1)/2), B(N*(N+1)/2) - INTEGER M,I - M = N * (N+1)/2 - DO 1 I = 1, M - B(I) = A(I) - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDSMG ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* GERSHGORIN BOUNDS FOR EIGENVALUES OF A DENSE SYMMETRIC MATRIX. -* AMIN .LE. ANY EIGENVALUE OF A .LE. AMAX. -* -* PARAMETERS : -* II N DIMENSION OF THE MATRIX A. -* RI A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RO AMIN LOWER BOUND FOR EIGENVALUES OF A. -* RO AMAX UPPER BOUND FOR EIGENVALUES OF A. -* - SUBROUTINE MXDSMG(N,A,AMIN,AMAX) - INTEGER N - DOUBLE PRECISION A(N*(N+1)/2),AMIN,AMAX - DOUBLE PRECISION TEMP - INTEGER I,J,K,L - DOUBLE PRECISION ZERO - PARAMETER (ZERO=0.0D 0) - AMAX=A(1) - AMIN=A(1) - K=0 - DO 3 I=1,N - TEMP=ZERO - L=K - DO 1 J=1,I-1 - L=L+1 - TEMP=TEMP+ABS(A(L)) - 1 CONTINUE - L=L+1 - DO 2 J=I+1,N - L=L+J-1 - TEMP=TEMP+ABS(A(L)) - 2 CONTINUE - K=K+I - AMAX=MAX(AMAX,A(K)+TEMP) - AMIN=MIN(AMIN,A(K)-TEMP) - 3 CONTINUE - RETURN - END -* SUBROUTINE MXDSMI ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DENSE SYMMETRIC MATRIX A IS SET TO THE UNIT MATRIX WITH THE SAME -* ORDER. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RO A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM -* WHICH IS SET TO THE UNIT MATRIX (I.E. A:=I). -* - SUBROUTINE MXDSMI(N,A) - INTEGER N - DOUBLE PRECISION A(*) - INTEGER I,M - M = N* (N+1)/2 - DO 10 I = 1,M - A(I) = 0.0D0 - 10 CONTINUE - M = 0 - DO 20 I = 1,N - M = M + I - A(M) = 1.0D0 - 20 CONTINUE - RETURN - END -* SUBROUTINE MXDSMM ALL SYSTEMS 89/12/01 -* PORTABILITY : ALL SYSTEMS -* 89/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* MULTIPLICATION OF A DENSE SYMMETRIC MATRIX A BY A VECTOR X. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RI X(N) INPUT VECTOR. -* RO Y(N) OUTPUT VECTOR EQUAL TO A*X. -* - SUBROUTINE MXDSMM(N,A,X,Y) - INTEGER N - DOUBLE PRECISION A(*),X(*),Y(*) - DOUBLE PRECISION TEMP - INTEGER I,J,K,L - K = 0 - DO 30 I = 1,N - TEMP = 0.0D0 - L = K - DO 10 J = 1,I - L = L + 1 - TEMP = TEMP + A(L)*X(J) - 10 CONTINUE - DO 20 J = I + 1,N - L = L + J - 1 - TEMP = TEMP + A(L)*X(J) - 20 CONTINUE - Y(I) = TEMP - K = K + I - 30 CONTINUE - RETURN - END -* FUNCTION MXDSMQ ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VALUE OF A QUADRATIC FORM WITH A DENSE SYMMETRIC MATRIX A. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RI X(N) GIVEN VECTOR. -* RI Y(N) GIVEN VECTOR. -* RR MXDSMQ VALUE OF THE QUADRATIC FORM MXDSMQ=TRANS(X)*A*Y. -* - DOUBLE PRECISION - + FUNCTION MXDSMQ(N,A,X,Y) - DOUBLE PRECISION ZERO - PARAMETER (ZERO=0.0D0) - INTEGER N - DOUBLE PRECISION A(*),X(*),Y(*) - DOUBLE PRECISION TEMP,TEMP1,TEMP2 - INTEGER I,J,K - TEMP = ZERO - K = 0 - DO 20 I = 1,N - TEMP1 = ZERO - TEMP2 = ZERO - DO 10 J = 1,I - 1 - K = K + 1 - TEMP1 = TEMP1 + A(K)*X(J) - TEMP2 = TEMP2 + A(K)*Y(J) - 10 CONTINUE - K = K + 1 - TEMP = TEMP + X(I)* (TEMP2+A(K)*Y(I)) + Y(I)*TEMP1 - 20 CONTINUE - MXDSMQ = TEMP - RETURN - END -* SUBROUTINE MXDSMR ALL SYSTEMS 92/12/01 -* PORTABILITY : ALL SYSTEMS -* 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* PLANE ROTATION IS APPLIED TO A DENSE SYMMETRIC MATRIX A. THE CASE -* K=L+1 IS REQUIRED. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* II K FIRST INDEX OF PLANE ROTATION. -* II L SECOND INDEX OF PLANE ROTATION. -* RO CK DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* RO CL OFF-DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* IO IER INFORMATION ON THE TRANSFORMATION. IER<0-K OR L OUT OF -* RANGE. IER=0-PLANE ROTATION. IER=1-PERMUTATION. -* IER=2-TRANSFORMATION SUPPRESSED. -* -* SUBPROGRAMS USED : -* S MXVROT PLANE ROTATION IS APPLIED TO TWO NUMBERS. -* - SUBROUTINE MXDSMR(N,A,K,L,CK,CL,IER) - INTEGER N,K,L,IER - DOUBLE PRECISION A(*),CK,CL - DOUBLE PRECISION AKK,AKL,ALL,CKK,CKL,CLL - INTEGER J,KJ,LJ,KK,KL,LL - IF (IER.NE.0.AND.IER.NE.1) RETURN - IF (K.NE.L+1) THEN - IER=-1 - RETURN - ENDIF - LJ=L*(L-1)/2 - DO 1 J=1,N - IF (J.LE.L) THEN - LJ=LJ+1 - KJ=LJ+L - ELSE - LJ=LJ+J-1 - KJ=LJ+1 - ENDIF - IF (J.NE.K.AND.J.NE.L) THEN - CALL MXVROT(A(KJ),A(LJ),CK,CL,IER) - ENDIF - 1 CONTINUE - IF (IER.EQ.0) THEN - CKK=CK**2 - CKL=CK*CL - CLL=CL**2 - LL=L*(L+1)/2 - KL=LL+L - KK=LL+K - AKL=(CKL+CKL)*A(KL) - AKK=CKK*A(KK)+CLL*A(LL)+AKL - ALL=CLL*A(KK)+CKK*A(LL)-AKL - A(KL)=(CLL-CKK)*A(KL)+CKL*(A(KK)-A(LL)) - A(KK)=AKK - A(LL)=ALL - ELSE - LL=L*(L+1)/2 - KK=LL+K - AKK=A(KK) - A(KK)=A(LL) - A(LL)=AKK - ENDIF - RETURN - END -* SUBROUTINE MXDSMS ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SCALING OF A DENSE SYMMETRIC MATRIX. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM -* WHICH IS SCALED BY THE VALUE ALF (I.E. A:=ALF*A). -* RI ALF SCALING FACTOR. -* - SUBROUTINE MXDSMS( N, A, ALF) - INTEGER N - DOUBLE PRECISION A(N*(N+1)/2), ALF - INTEGER I,M - M = N * (N+1) / 2 - DO 1 I = 1, M - A(I) = A(I) * ALF - 1 CONTINUE - RETURN - END -* SUBROUTINE MXDSMU ALL SYSTEMS 89/12/01 -C PORTABILITY : ALL SYSTEMS -C 89/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* UPDATE OF A DENSE SYMMETRIC MATRIX A. THIS UPDATE IS DEFINED AS -* A:=A+ALF*X*TRANS(X) WHERE ALF IS A GIVEN SCALING FACTOR AND X IS -* A GIVEN VECTOR. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RU A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RI ALF SCALING FACTOR IN THE CORRECTION TERM. -* RI X(N) VECTOR IN THE CORRECTION TERM. -* - SUBROUTINE MXDSMU( N, A, ALF, X) - INTEGER N - DOUBLE PRECISION A(N*(N+1)/2), X(N), ALF - DOUBLE PRECISION TEMP - INTEGER I, J, K - K = 0 - DO 2 I = 1, N - TEMP = ALF * X(I) - DO 1 J = 1, I - K = K + 1 - A(K) = A(K) + TEMP * X(J) - 1 CONTINUE - 2 CONTINUE - RETURN - END -* SUBROUTINE MXDSMV ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* K-TH ROW OF A DENSE SYMMETRIC MATRIX A IS COPIED TO THE VECTOR X. -* -* PARAMETERS : -* II N ORDER OF THE MATRIX A. -* RI A(N*(N+1)/2) DENSE SYMMETRIC MATRIX STORED IN THE PACKED FORM. -* RO X(N) OUTPUT VECTOR. -* II K INDEX OF COPIED ROW. -* - SUBROUTINE MXDSMV(N,A,X,K) - INTEGER K,N - DOUBLE PRECISION A(*),X(*) - INTEGER I,L - L = K* (K-1)/2 - DO 10 I = 1,N - IF (I.LE.K) THEN - L = L + 1 - ELSE - L = L + I - 1 - END IF - X(I) = A(L) - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVCOP ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COPYING OF A VECTOR. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RO Y(N) OUTPUT VECTOR WHERE Y:= X. -* - SUBROUTINE MXVCOP(N,X,Y) - INTEGER N - DOUBLE PRECISION X(*),Y(*) - INTEGER I - DO 10 I = 1,N - Y(I) = X(I) - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVDIF ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VECTOR DIFFERENCE. -* -* PARAMETERS : -* RI X(N) INPUT VECTOR. -* RI Y(N) INPUT VECTOR. -* RO Z(N) OUTPUT VECTOR WHERE Z:= X - Y. -* - SUBROUTINE MXVDIF(N,X,Y,Z) - INTEGER N - DOUBLE PRECISION X(*),Y(*),Z(*) - INTEGER I - DO 10 I = 1,N - Z(I) = X(I) - Y(I) - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVDIR ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VECTOR AUGMENTED BY THE SCALED VECTOR. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI A SCALING FACTOR. -* RI X(N) INPUT VECTOR. -* RI Y(N) INPUT VECTOR. -* RO Z(N) OUTPUT VECTOR WHERE Z:= Y + A*X. -* - SUBROUTINE MXVDIR(N,A,X,Y,Z) - DOUBLE PRECISION A - INTEGER N - DOUBLE PRECISION X(*),Y(*),Z(*) - INTEGER I - DO 10 I = 1,N - Z(I) = Y(I) + A*X(I) - 10 CONTINUE - RETURN - END -* FUNCTION MXVDOT ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DOT PRODUCT OF TWO VECTORS. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RI Y(N) INPUT VECTOR. -* RR MXVDOT VALUE OF DOT PRODUCT MXVDOT=TRANS(X)*Y. -* - FUNCTION MXVDOT(N,X,Y) - INTEGER N - DOUBLE PRECISION X(*),Y(*),MXVDOT - DOUBLE PRECISION TEMP - INTEGER I - TEMP = 0.0D0 - DO 10 I = 1,N - TEMP = TEMP + X(I)*Y(I) - 10 CONTINUE - MXVDOT = TEMP - RETURN - END -* SUBROUTINE MXVINA ALL SYSTEMS 90/12/01 -* PORTABILITY : ALL SYSTEMS -* 90/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* ELEMENTS OF THE INTEGER VECTOR ARE REPLACED BY THEIR ABSOLUTE VALUES. -* -* PARAMETERS : -* II N DIMENSION OF THE INTEGER VECTOR. -* IU IX(N) INTEGER VECTOR WHICH IS UPDATED SO THAT IX(I):=ABS(IX(I)) -* FOR ALL I. -* - SUBROUTINE MXVINA(N,IX) - INTEGER N - INTEGER IX(*) - INTEGER I - DO 10 I = 1,N - IX(I) = ABS(IX(I)) - IF (IX(I).GT.10) IX(I) = IX(I) - 10 - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVIND ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* CHANGE OF THE INTEGER VECTOR ELEMENT FOR THE CONSTRAINT ADDITION. -* -* PARAMETERS : -* IU IX(N) INTEGER VECTOR. -* II I INDEX OF THE CHANGED ELEMENT. -* II JOB CHANGE SPECIFICATION. IS JOB.EQ.0 THEN IX(I)=10-IX(I). -* - SUBROUTINE MXVIND(IX,I,JOB) - INTEGER IX(*),I,JOB - IF (JOB.EQ.0) IX(I)=10-IX(I) - RETURN - END -* SUBROUTINE MXVINS ALL SYSTEMS 90/12/01 -C PORTABILITY : ALL SYSTEMS -C 90/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* INITIATION OF THE INTEGER VECTOR. -* -* PARAMETERS : -* II N DIMENSION OF THE INTEGER VECTOR. -* II IP INTEGER PARAMETER. -* IO IX(N) INTEGER VECTOR SUCH THAT IX(I)=IP FOR ALL I. -* - SUBROUTINE MXVINS(N,IP,IX) - INTEGER N,IP,IX(N) - INTEGER I - DO 1 I=1,N - IX(I)=IP - 1 CONTINUE - RETURN - END -* SUBROUTINE MXVINV ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* CHANGE OF THE INTEGER VECTOR ELEMENT FOR THE CONSTRAINT ADDITION. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* IU IX(N) INTEGER VECTOR. -* II I INDEX OF THE CHANGED ELEMENT. -* II JOB CHANGE SPECIFICATION -* - SUBROUTINE MXVINV(IX,I,JOB) - INTEGER I,JOB - INTEGER IX(*) - IF ((IX(I).EQ.3.OR.IX(I).EQ.5) .AND. JOB.LT.0) IX(I) = IX(I) + 1 - IF ((IX(I).EQ.4.OR.IX(I).EQ.6) .AND. JOB.GT.0) IX(I) = IX(I) - 1 - IX(I) = -IX(I) - RETURN - END -* FUNCTION MXVMAX ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* L-INFINITY NORM OF A VECTOR. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RR MXVMAX L-INFINITY NORM OF THE VECTOR X. -* - FUNCTION MXVMAX(N,X) - INTEGER N - DOUBLE PRECISION X(*),MXVMAX - INTEGER I - MXVMAX = 0.0D0 - DO 10 I = 1,N - MXVMAX = MAX(MXVMAX,ABS(X(I))) - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVNEG ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* CHANGE THE SIGNS OF VECTOR ELEMENTS. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RO Y(N) OUTPUT VECTOR WHERE Y:= - X. -* - SUBROUTINE MXVNEG(N,X,Y) - INTEGER N - DOUBLE PRECISION X(*),Y(*) - INTEGER I - DO 10 I = 1,N - Y(I) = -X(I) - 10 CONTINUE - RETURN - END -* FUNCTION MXVNOR ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* EUCLIDEAN NORM OF A VECTOR. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RR MXVNOR EUCLIDEAN NORM OF X. -* - FUNCTION MXVNOR(N,X) - INTEGER N - DOUBLE PRECISION X(*),MXVNOR - DOUBLE PRECISION POM,DEN - INTEGER I - DOUBLE PRECISION ZERO - PARAMETER (ZERO=0.0D 0) - DEN=ZERO - DO 1 I=1,N - DEN=MAX(DEN,ABS(X(I))) - 1 CONTINUE - POM=ZERO - IF (DEN.GT.ZERO) THEN - DO 2 I=1,N - POM=POM+(X(I)/DEN)**2 - 2 CONTINUE - ENDIF - MXVNOR=DEN*SQRT(POM) - RETURN - END -* SUBROUTINE MXVORT ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF AN ELEMENTARY ORTHOGONAL MATRIX FOR PLANE ROTATION. -* -* PARAMETERS : -* RU XK FIRST VALUE FOR PLANE ROTATION (XK IS TRANSFORMED TO -* SQRT(XK**2+XL**2)) -* RU XL SECOND VALUE FOR PLANE ROTATION (XL IS TRANSFORMED TO -* ZERO) -* RO CK DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* RO CL OFF-DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* IO IER INFORMATION ON THE TRANSFORMATION. IER=0-GENERAL PLANE -* ROTATION. IER=1-PERMUTATION. IER=2-TRANSFORMATION SUPPRESSED. -* - SUBROUTINE MXVORT(XK,XL,CK,CL,IER) - DOUBLE PRECISION CK,CL,XK,XL - INTEGER IER - DOUBLE PRECISION DEN,POM - IF (XL.EQ.0.0D0) THEN - IER = 2 - ELSE IF (XK.EQ.0.0D0) THEN - XK = XL - XL = 0.0D0 - IER = 1 - ELSE - IF (ABS(XK).GE.ABS(XL)) THEN - POM = XL/XK - DEN = SQRT(1.0D0+POM*POM) - CK = 1.0D0/DEN - CL = POM/DEN - XK = XK*DEN - ELSE - POM = XK/XL - DEN = SQRT(1.0D0+POM*POM) - CL = 1.0D0/DEN - CK = POM/DEN - XK = XL*DEN - END IF - XL = 0.0D0 - IER = 0 - END IF - RETURN - END -* SUBROUTINE MXVROT ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* PLANE ROTATION IS APPLIED TO TWO VALUES. -* -* PARAMETERS : -* RU XK FIRST VALUE FOR PLANE ROTATION. -* RU XL SECOND VALUE FOR PLANE ROTATION. -* RI CK DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* RI CL OFF-DIAGONAL ELEMENT OF THE ELEMENTARY ORTHOGONAL MATRIX. -* II IER INFORMATION ON THE TRANSFORMATION. IER=0-GENERAL PLANE -* ROTATION. IER=1-PERMUTATION. IER=2-TRANSFORMATION SUPPRESSED. -* - SUBROUTINE MXVROT(XK,XL,CK,CL,IER) - DOUBLE PRECISION CK,CL,XK,XL - INTEGER IER - DOUBLE PRECISION YK,YL - IF (IER.EQ.0) THEN - YK = XK - YL = XL - XK = CK*YK + CL*YL - XL = CL*YK - CK*YL - ELSE IF (IER.EQ.1) THEN - YK = XK - XK = XL - XL = YK - END IF - RETURN - END -* SUBROUTINE MXVSAV ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DIFFERENCE OF TWO VECTORS RETURNED IN THE SUBSTRACTED ONE. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RU Y(N) UPDATE VECTOR WHERE Y:= X - Y. -* - SUBROUTINE MXVSAV(N,X,Y) - INTEGER N - DOUBLE PRECISION X(*),Y(*) - DOUBLE PRECISION TEMP - INTEGER I - DO 10 I = 1,N - TEMP = Y(I) - Y(I) = X(I) - Y(I) - X(I) = TEMP - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVSCL ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SCALING OF A VECTOR. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RI A SCALING FACTOR. -* RO Y(N) OUTPUT VECTOR WHERE Y:= A*X. -* - SUBROUTINE MXVSCL(N,A,X,Y) - DOUBLE PRECISION A - INTEGER N - DOUBLE PRECISION X(*),Y(*) - INTEGER I - DO 10 I = 1,N - Y(I) = A*X(I) - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVSET ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* A SCALAR IS SET TO ALL THE ELEMENTS OF A VECTOR. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI A INITIAL VALUE. -* RO X(N) OUTPUT VECTOR SUCH THAT X(I)=A FOR ALL I. -* - SUBROUTINE MXVSET(N,A,X) - DOUBLE PRECISION A - INTEGER N - DOUBLE PRECISION X(*) - INTEGER I - DO 10 I = 1,N - X(I) = A - 10 CONTINUE - RETURN - END -* SUBROUTINE MXVSUM ALL SYSTEMS 88/12/01 -* PORTABILITY : ALL SYSTEMS -* 88/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SUM OF TWO VECTORS. -* -* PARAMETERS : -* II N VECTOR DIMENSION. -* RI X(N) INPUT VECTOR. -* RI Y(N) INPUT VECTOR. -* RO Z(N) OUTPUT VECTOR WHERE Z:= X + Y. -* - SUBROUTINE MXVSUM(N,X,Y,Z) - INTEGER N - DOUBLE PRECISION X(*),Y(*),Z(*) - INTEGER I - DO 10 I = 1,N - Z(I) = X(I) + Y(I) - 10 CONTINUE - RETURN - END diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/openunit.f b/pyoptsparse/pyoptsparse/pyPSQP/source/openunit.f deleted file mode 100644 index e67f89660..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/openunit.f +++ /dev/null @@ -1,29 +0,0 @@ -C Helper subroutine to open files in the Fortran world - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) - - integer unitnum -Cf2py intent(in) unitnum - character*(*) filename -Cf2py intent(in) filename - character*(*) filestatus -Cf2py intent(in) filestatus - character*(*) fileaction -Cf2py intent(in) fileaction - integer ierror -Cf2py intent(out) ierror - - open(unit=unitnum,file=filename,status=filestatus, - > access=fileaction,iostat=ierror) - - return - end - -C Helper routine to flush buffers to files - subroutine pyflush(unitnum) - - integer unitnum - - call flush(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/pqsubs.f b/pyoptsparse/pyoptsparse/pyPSQP/source/pqsubs.f deleted file mode 100644 index 823450af9..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/pqsubs.f +++ /dev/null @@ -1,4895 +0,0 @@ -* SUBROUTINE PA0GS1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE: -* NUMERICAL COMPUTATION OF THE GRADIENT OF THE MODEL FUNCTION. -* -* PARAMETERS : -* II N NUMBER OF VARIABLES. -* II KA INDEF OF THE APPROXIMATED FUNCTION. -* RI X(N) VECTOR OF VARIABLES. -* RO GA(N) GRADIENT OF THE APPROXIMATED FUNCTION. -* RI FA VALUE OF THE APPROXIMATED FUNCTION. -* RI ETA1 PRECISION OF THE COMPUTED VALUES. -* IU NAV NUMBER OF APPROXIMATED FUNCTION EVALUATIONS. -* - SUBROUTINE PA0GS1(N,KA,X,GA,FA,ETA1,NAV) - INTEGER N,KA,NAV - DOUBLE PRECISION X(*),GA(*),FA,ETA1 - DOUBLE PRECISION XSTEP,XTEMP,FTEMP,ETA - INTEGER IVAR - ETA=SQRT(ETA1) - FTEMP=FA - DO 4 IVAR=1,N -C -C STEP SELECTION -C - XSTEP=1.0D 0 - XSTEP=ETA*MAX(ABS(X(IVAR)),XSTEP)*SIGN(1.0D 0,X(IVAR)) - XTEMP=X(IVAR) - X(IVAR)=X(IVAR)+XSTEP - XSTEP=X(IVAR)-XTEMP - NAV=NAV+1 - CALL FUN(N,KA,X,FA) -C -C NUMERICAL DIFFERENTIATION -C - GA(IVAR)=(FA-FTEMP)/XSTEP - X(IVAR)=XTEMP - 4 CONTINUE - FA=FTEMP - RETURN - END -* SUBROUTINE PA1SQ1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF THE VALUE AND THE GRADIENT OF THE OBJECTIVE FUNCTION -* WHICH IS DEFINED AS A SUM OF SQUARES. -* -* PARAMETERS: -* II N NUMBER OF VARIABLES. -* RI X(N) VECTOR OF VARIABLES. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* RO AF(N) VALUES OF THE APPROXIMATED FUNCTIONS. -* RI GA(NF) GRADIENT OF THE APPROXIMATED FUNCTION. -* RI AG(N*N) RECTANGULAR MATRIX WHICH IS USED FOR THE DIRECTION -* VECTOR DETERMINATION. -* RO G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RI ETA1 PRECISION OF THE COMPUTES FUNCTION VALUES. -* II KDA DEGREE OF COMPUTED DERIVATIVES. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* IU NFV NUMBER OF OBJECTIVE FUNCTION VALUES COMPUTED. -* IU NFG NUMBER OF OBJECTIVE FUNCTION GRADIENTS COMPUTED. -* -* SUBPROGRAMS USED : -* S MXVCOP COPYING OF A VECTOR. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PA1SQ1(N,X,F,AF,GA,AG,G,ETA1,KDA,KD,LD,NFV,NFG) - INTEGER N,KDA,KD,LD,NFV,NFG - DOUBLE PRECISION X(*),F,AF(*),GA(*),AG(*),G(*),ETA1 - INTEGER KA,NAV - DOUBLE PRECISION FA - IF (KD.LE.LD) RETURN - IF (KD.GE.0.AND.LD.LT.0) THEN - F=0.0D0 - NFV=NFV+1 - ENDIF - IF (KD.GE.1.AND.LD.LT.1) THEN - CALL MXVSET(N,0.0D0,G) - IF (KDA.GT.0) NFG=NFG+1 - ENDIF - NAV=0 - DO 30 KA=1,N - IF (KD.LT.0) GO TO 30 - IF (LD.GE.0) THEN - FA = AF(KA) - GO TO 10 - ELSE - CALL FUN(N,KA,X,FA) - AF(KA) = FA - ENDIF - IF (LD.GE.0) GO TO 10 - F=F+FA*FA - 10 IF (KD.LT.1) GO TO 30 - IF (KDA.GT.0) THEN - CALL DFUN(N,KA,X,GA) - ELSE - CALL PA0GS1(N,KA,X,GA,FA,ETA1,NAV) - ENDIF - CALL MXVDIR(N,FA,GA,G,G) - CALL MXVCOP(N,GA,AG((KA-1)*N+1)) - 30 CONTINUE - NFV=NFV+NAV/N - IF (KD.GE.0.AND.LD.LT.0) F=0.5D0*F - LD=KD - RETURN - END -* SUBROUTINE PA2SQ1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF THE VALUE AND THE GRADIENT AND THE HESSIAN MATRIX -* OF THE OBJECTIVE FUNCTION WHICH IS DEFINED AS A SUM OF SQUARES. -* -* PARAMETERS: -* II NF NUMBER OF VARIABLES. -* II NA NUMBER OF APPROXIMATED FUNCTIONS. -* RI GA(NF) GRADIENT OF THE APPROXIMATED FUNCTION. -* RO G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RI HA(NF*(NF+1)/2) HESSIAN MATRIX OF THE APPROXIMATED FUNCTION. -* RO H(NF*(NF+1)/2) HESSIAN MATRIX OF THE OBJECTIVE FUNCTION. -* RI FA VALUE OF THE SELECTED FUNCTION. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* -* COMMON DATA : -* II KDA DEGREE OF ANALYTICALLY COMPUTED DERIVATIVES. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* IU NAV NUMBER OF APPROXIMATED FUNCTION VALUES COMPUTED. -* IU NAG NUMBER OF APPROXIMATED FUNCTION GRADIENTS COMPUTED. -* IU NAH NUMBER OF APPROXIMATED FUNCTION HESSIAN MATRICES COMPUTED. -* IU NFV NUMBER OF OBJECTIVE FUNCTION VALUES COMPUTED. -* IU NFG NUMBER OF OBJECTIVE FUNCTION GRADIENTS COMPUTED. -* IU NFH NUMBER OF OBJECTIVE FUNCTION HESSIAN MATRICES COMPUTED. -* IU IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* -* STATUS VARIABLES : -* NS,ISP,TSS -* -* SUBPROGRAMS USED : -* S UYPRO1 PROLOGUE. -* S UYEPI1 EPILOGUE. -* S UYSET0 STATUS DEFINITION. -* S MXVSET INITIATION OF A VECTOR. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXDSMO INITIATION OF A DENSE SYMMETRIC MATRIX. -* S MXDSMA DENSE SYMMETRIC MATRIX AUGMENTED BY THE SCALED DENSE -* SYMMETRIC MATRIX. -* S MXDSMU CORRECTION OF A DENSE SYMMETRIC MATRIX. -* - SUBROUTINE PA2SQ1(NF,NA,X,F,AF,GA,G,H,ETA1,KDA,KD,LD,NFV,NFG) - INTEGER NF,NA,KDA,KD,LD,NFV,NFG - DOUBLE PRECISION X(*),F,AF(*),GA(*),G(*),H(*),ETA1 - INTEGER KA,NAV - DOUBLE PRECISION FA - IF (KD.LE.LD) RETURN - IF (KD.GE.0.AND.LD.LT.0) THEN - F=0.0D0 - NFV=NFV+1 - ENDIF - IF (KD.GE.1.AND.LD.LT.1) THEN - CALL MXVSET(NF,0.0D0,G) - IF (KDA.GT.0) NFG=NFG+1 - ENDIF - IF (KD.GE.2.AND.LD.LT.2) CALL MXVSET(NF*(NF+1)/2,0.0D0,H) - NAV=0 - DO 30 KA=1,NA - IF (KD.LT.0) GO TO 30 - IF (LD.GE.0) THEN - FA = AF(KA) - GO TO 10 - ELSE - CALL FUN(NF,KA,X,FA) - AF(KA) = FA - ENDIF - IF (LD.GE.0) GO TO 10 - F=F+FA*FA - 10 IF (KD.LT.1) GO TO 30 - IF (KDA.GT.0) THEN - CALL DFUN(NF,KA,X,GA) - ELSE - CALL PA0GS1(NF,KA,X,GA,FA,ETA1,NAV) - ENDIF - CALL MXVDIR(NF,FA,GA,G,G) - IF (KD.LT.2) GO TO 30 - CALL MXDSMU(NF,H,1.0D0,GA) - 30 CONTINUE - NFV=NFV+NAV/NA - IF (KD.GE.0.AND.LD.LT.0) F=0.5D0*F - LD=KD - RETURN - END -* SUBROUTINE PC1F01 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF THE VALUE AND THE GRADIENT OF THE CONSTRAINT FUNCTION. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* RI FC VALUE OF THE SELECTED CONSTRAINT FUNCTION. -* RI CF(NC) VECTOR CONTAINING VALUES OF CONSTRAINT FUNCTIONS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI GC(NF) GRADIENT OF THE SELECTED CONSTRAINT FUNCTION. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE GRADIENTS OF CONSTRAINT -* FUNCTIONS. -* RO CMAX MAXIMUM CONSTRAINT VIOLATION. -* II KD DEGREE OF REQUIRED DERVATIVES. -* II LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* -* SUBPROGRAMS USED : -* S MXVCOP COPYING OF A VECTOR. -* - SUBROUTINE PC1F01(NF,NC,X,FC,CF,CL,CU,IC,GC,CG,CMAX,KD,LD) - DOUBLE PRECISION FC,CMAX - INTEGER KD,LD,NC,NF - DOUBLE PRECISION CF(*),CG(*),CL(*),CU(*),GC(*),X(*) - INTEGER IC(*) - DOUBLE PRECISION POM,TEMP - INTEGER KC - IF (KD.LE.LD) RETURN - IF (LD.LT.0) CMAX = 0.0D0 - DO 20 KC = 1,NC - IF (KD.LT.0) GO TO 20 - IF (LD.GE.0) THEN - FC = CF(KC) - GO TO 10 - ELSE - CALL CON(NF,KC,X,FC) - CF(KC) = FC - END IF - IF (IC(KC).GT.0) THEN - POM = 0.0D0 - TEMP = CF(KC) - IF (IC(KC).EQ.1.OR.IC(KC).GE.3) POM = MIN(POM, - + TEMP - CL(KC)) - IF (IC(KC).EQ.2.OR.IC(KC).GE.3) POM = MIN(POM, - + CU(KC) - TEMP) - IF (POM.LT.0.0D0) THEN - CMAX = MAX(CMAX,-POM) - END IF - END IF - 10 IF (KD.LT.1) GO TO 20 - IF (LD.GE.1) THEN - CALL MXVCOP(NF,CG((KC - 1) * NF + 1),GC) - GO TO 20 - ELSE - CALL DCON(NF,KC,X,GC) - CALL MXVCOP(NF,GC,CG((KC - 1) * NF + 1)) - END IF - 20 CONTINUE - LD = KD - RETURN - END -* SUBROUTINE PF1F01 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF THE VALUE AND THE GRADIENT OF THE OBJECTIVE FUNCTION. -* -* PARAMETERS: -* II NF NUMBER OF VARIABLES. -* RI X(NF) VECTOR OF VARIABLES. -* RI GF(NF) GRADIENT OF THE MODEL FUNCTION. -* RO G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RI FF VALUE OF THE MODEL FUNCTION. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* II KD DEGREE OF REQUIRED DERIVATIVES. -* II LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* II IEXT TYPE OF EXTREMUM. IEXT=0-MINIMUM. IEXT=1-MAXIMUM. -* -* SUBPROGRAMS USED : -* S MXVCOP COPYING OF A VECTOR. -* S MXVNEG COPYING OF A VECTOR WITH CHANGE OF THE SIGN. -* - SUBROUTINE PF1F01(NF,X,GF,G,FF,F,KD,LD,IEXT) - DOUBLE PRECISION F,FF - INTEGER IEXT,KD,LD,NF - DOUBLE PRECISION GF(*),G(*),X(*) - INTEGER NADD,NDEC,NFG,NFH,NFV,NIT,NREM,NRES - COMMON /STAT/NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - IF (KD.LE.LD) RETURN - IF (LD.GE.0) GO TO 10 - NFV = NFV + 1 - CALL OBJ(NF,X,FF) - IF (IEXT.LE.0) THEN - F = FF - ELSE - F = -FF - END IF - 10 IF (KD.LT.1) GO TO 20 - IF (LD.GE.1) GO TO 20 - NFG = NFG + 1 - CALL DOBJ(NF,X,GF) - IF (IEXT.GT.0) THEN - CALL MXVNEG(NF,GF,G) - END IF - 20 LD = KD - RETURN - END -* SUBROUTINE PLADB0 ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* NEW LINEAR CONSTRAINT OR A NEW SIMPLE BOUND IS ADDED TO THE -* ACTIVE SET. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU N ACTUAL NUMBER OF VARIABLES. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RA S(NF) AUXILIARY VECTOR. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* II INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IU NADD NUMBER OF CONSTRAINT ADDITIONS. -* IO IER ERROR INDICATOR. -* -* SUBPROGRAMS USED : -* S PLADR0 CORRECTION OF KERNEL OF THE ORTHOGONAL PROJECTION -* AFTER CONSTRAINT ADDITION. -* S MXDRMM PREMULTIPLICATION OF A VECTOR BY A ROWWISE STORED DENSE -* RECTANGULAR MATRIX. -* S MXDRMV COPY OF THE SELECTED COLUMN OF A ROWWISE STORED DENSE -* RECTANGULAR MATRIX. -* S MXDRGR PLANE ROTATION OF A TRANSPOSED DENSE RECTANGULAR MATRIX. -* S MXVORT DETERMINATION OF AN ELEMENTARY ORTHOGONAL MATRIX FOR -* PLANE ROTATION. -* - SUBROUTINE PLADB0(NF,N,ICA,CG,CR,CZ,S,EPS7,GMAX,UMAX,INEW,NADD, - & IER) - INTEGER NF,N,ICA(*),INEW,NADD,IER - DOUBLE PRECISION CG(*),CR(*),CZ(*),S(*),EPS7,GMAX,UMAX - DOUBLE PRECISION CK,CL - INTEGER K,L,N1 - CALL PLADR0(NF,N,ICA,CG,CR,S,EPS7,GMAX,UMAX,INEW,NADD,IER) - IF (IER.NE.0) RETURN - IF (N.GT.0) THEN - N1=N+1 - IF (INEW.GT.0) THEN - CALL MXDRMM(NF,N1,CZ,CG((INEW-1)*NF+1),S) - ELSE - CALL MXDRMV(NF,N1,CZ,S,-INEW) - ENDIF - DO 1 L=1,N - K=L+1 - CALL MXVORT(S(K),S(L),CK,CL,IER) - CALL MXDRGR(NF,CZ,K,L,CK,CL,IER) - IF (IER.LT.0) RETURN - 1 CONTINUE - ENDIF - IER=0 - RETURN - END -* SUBROUTINE PLADB4 ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* NEW LINEAR CONSTRAINT OR A NEW SIMPLE BOUND IS ADDED TO THE ACTIVE -* SET. TRANSFORMED HESSIAN MATRIX APPROXIMATION OR ITS INVERSION -* IS UPDATED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU N ACTUAL NUMBER OF VARIABLES. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RU H(NF*(NF+1)/2) TRANSFORMED HESSIAN MATRIX APPROXIMATION OR -* ITS INVERSION. -* RA S(NF) AUXILIARY VECTOR. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* IU IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* IDECF=1-GILL-MURRAY DECOMPOSITION. IDECF=9-INVERSION. -* IDECF=10-DIAGONAL MATRIX. -* II INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IU NADD NUMBER OF CONSTRAINT ADDITIONS. -* IO IER ERROR INDICATOR. -* -* SUBPROGRAMS USED : -* S PLADR0 CORRECTION OF KERNEL OF THE ORTHOGONAL PROJECTION -* AFTER CONSTRAINT ADDITION. -* S MXDRMM PREMULTIPLICATION OF A VECTOR BY A ROWWISE STORED DENSE -* RECTANGULAR MATRIX. -* S MXDRMV COPY OF THE SELECTED COLUMN OF A ROWWISE STORED DENSE -* RECTANGULAR MATRIX. -* S MXDRGR PLANE ROTATION OF A TRANSPOSED DENSE RECTANGULAR MATRIX. -* RECTANGULAR MATRIX. -* S MXDSMR PLANE ROTATION OF A DENSE SYMMETRIC MATRIX. -* S MXVORT DETERMINATION OF AN ELEMENTARY ORTHOGONAL MATRIX FOR -* PLANE ROTATION. -* - SUBROUTINE PLADB4(NF,N,ICA,CG,CR,CZ,H,S,EPS7,GMAX,UMAX,IDECF, - & INEW,NADD,IER) - INTEGER NF,N,ICA(*),IDECF,INEW,NADD,IER - DOUBLE PRECISION CG(*),CR(*),CZ(*),H(*),S(*),EPS7,GMAX,UMAX - DOUBLE PRECISION CK,CL - INTEGER I,J,K,L,N1 - IF (IDECF.NE.0.AND.IDECF.NE.9) THEN - IER=-2 - RETURN - ENDIF - CALL PLADR0(NF,N,ICA,CG,CR,S,EPS7,GMAX,UMAX,INEW,NADD,IER) - IF (IER.NE.0) RETURN - IF (N.GT.0) THEN - N1=N+1 - IF (INEW.GT.0) THEN - CALL MXDRMM(NF,N1,CZ,CG((INEW-1)*NF+1),S) - ELSE - CALL MXDRMV(NF,N1,CZ,S,-INEW) - ENDIF - DO 1 L=1,N - K=L+1 - CALL MXVORT(S(K),S(L),CK,CL,IER) - CALL MXDRGR(NF,CZ,K,L,CK,CL,IER) - CALL MXDSMR(N1,H,K,L,CK,CL,IER) - IF (IER.LT.0) RETURN - 1 CONTINUE - IF (IDECF.EQ.9) THEN - L=N*(N+1)/2 - IF (H(L+N1).NE.0.0D 0) THEN - CL=1.0D 0/H(L+N1) - K=0 - DO 3 I=1,N - CK=CL*H(L+I) - DO 2 J=1,I - K=K+1 - H(K)=H(K)-CK*H(L+J) - 2 CONTINUE - 3 CONTINUE - ENDIF - ENDIF - ENDIF - IER=0 - RETURN - END -* SUBROUTINE PLADR0 ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TRIANGULAR DECOMPOSITION OF KERNEL OF THE ORTHOGONAL PROJECTION -* IS UPDATED AFTER CONSTRAINT ADDITION. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU N ACTUAL NUMBER OF VARIABLES. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RA S(NF) AUXILIARY VECTOR. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* II INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IU NADD NUMBER OF CONSTRAINT ADDITIONS. -* IO IER ERROR INDICATOR. -* -* SUBPROGRAMS USED : -* S MXSPRB SPARSE BACK SUBSTITUTION. -* S MXVCOP COPYING OF A VECTOR. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* - SUBROUTINE PLADR0(NF,N,ICA,CG,CR,S,EPS7,GMAX,UMAX,INEW,NADD,IER) - INTEGER NF,N,ICA(*),INEW,NADD,IER - DOUBLE PRECISION CG(*),CR(*),S(*),EPS7,GMAX,UMAX - DOUBLE PRECISION MXVDOT - INTEGER NCA,NCR,I,J,K,L - IER=0 - IF (N.LE.0) IER=2 - IF (INEW.EQ.0) IER=3 - IF (IER.NE.0) RETURN - NCA=NF-N - NCR=NCA*(NCA+1)/2 - IF (INEW.GT.0) THEN - CALL MXVCOP(NF,CG((INEW-1)*NF+1),S) - GMAX=MXVDOT(NF,CG((INEW-1)*NF+1),S) - DO 1 J=1,NCA - L=ICA(J) - IF (L.GT.0) THEN - CR(NCR+J)=MXVDOT(NF,CG((L-1)*NF+1),S) - ELSE - I=-L - CR(NCR+J)=S(I) - ENDIF - 1 CONTINUE - ELSE - K=-INEW - GMAX=1.0D 0 - DO 2 J=1,NCA - L=ICA(J) - IF (L.GT.0) THEN - CR(NCR+J)=CG((L-1)*NF+K)*GMAX - ELSE - CR(NCR+J)=0.0D 0 - ENDIF - 2 CONTINUE - ENDIF - IF (NCA.EQ.0) THEN - UMAX=GMAX - ELSE - CALL MXDPRB(NCA,CR,CR(NCR+1),1) - UMAX=GMAX-MXVDOT(NCA,CR(NCR+1),CR(NCR+1)) - ENDIF - IF (UMAX.LE.EPS7*GMAX) THEN - IER=1 - RETURN - ELSE - N=N-1 - NCA=NCA+1 - NCR=NCR+NCA - ICA(NCA)=INEW - CR(NCR)=SQRT(UMAX) - NADD=NADD+1 - ENDIF - RETURN - END -* SUBROUTINE PLLPB1 ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE INITIAL FEASIBLE POINT AND THE LINEAR PROGRAMMING -* SUBROUTINE. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II NC NUMBER OF LINEAR CONSTRAINTS. -* RU X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RO XO(NF) SAVED VECTOR OF VARIABLES. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RU CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* RA CFD(NF) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* IO ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RO CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RO CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RO GO(NF) SAVED GRADIENT OF THE OBJECTIVE FUNCTION. -* RA S(NF) DIRECTION VECTOR. -* II MFP TYPE OF FEASIBLE POINT. MFP=1-ARBITRARY FEASIBLE POINT. -* MFP=2-OPTIMUM FEASIBLE POINT. MFP=3-REPEATED SOLUTION. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* RI ETA9 MAXIMUM FOR REAL NUMBERS. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RI EPS9 TOLERANCE FOR ACTIVITY OF CONSTRAINTS. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* IO N DIMENSION OF THE MANIFOLD DEFINED BY ACTIVE CONSTRAINTS. -* IO ITERL TYPE OF FEASIBLE POINT. ITERL=1-ARBITRARY FEASIBLE POINT. -* ITERL=2-OPTIMUM FEASIBLE POINT. ITERL=-1 FEASIBLE POINT DOES -* NOT EXISTS. ITERL=-2 OPTIMUM FEASIBLE POINT DOES NOT EXISTS. -* -* SUBPROGRAMS USED : -* S PLINIT DETERMINATION OF INITIAL POINT SATISFYING SIMPLE BOUNDS. -* S PLMAXL MAXIMUM STEPSIZE USING LINEAR CONSTRAINTS. -* S PLMAXS MAXIMUM STEPSIZE USING SIMPLE BOUNDS. -* S PLMAXT MAXIMUM STEPSIZE USING TRUST REGION BOUNDS. -* S PLNEWL IDENTIFICATION OF ACTIVE LINEAR CONSTRAINTS. -* S PLNEWS IDENTIFICATION OF ACTIVE SIMPLE BOUNDS. -* S PLNEWT IDENTIFICATION OF ACTIVE TRUST REGION BOUNDS. -* S PLDIRL NEW VALUES OF CONSTRAINT FUNCTIONS. -* S PLDIRS NEW VALUES OF VARIABLES. -* S PLSETC INITIAL VALUES OF CONSTRAINT FUNCTIONS. -* S PLSETG DETERMINATION OF THE FIRST PHASE GRADIENT VECTOR. -* S PLTRBG DETERMINATION OF LAGRANGE MULTIPLIERS AND COMPUTATION -* S PLADB0 CONSTRAINT ADDITION. -* S PLRMB0 CONSTRAINT DELETION. -* S MXDCMM PREMULTIPLICATION OF A VECTOR BY A DENSE RECTANGULAR -* MATRIX STORED BY COLUMNS. -* S MXDRMM PREMULTIPLICATION OF A VECTOR BY A DENSE RECTANGULAR -* MATRIX STORED BY ROWS. -* S MXDSMI DETERMINATION OF THE INITIAL UNIT DENSE SYMMETRIC -* MATRIX. -* S MXVCOP COPYING OF A VECTOR. -* S MXVINA ABSOLUTE VALUES OF ELEMENTS OF AN INTEGER VECTOR. -* S MXVINC UPDATE OF AN INTEGER VECTOR. -* S MXVIND CHANGE OF THE INTEGER VECTOR FOR CONSTRAINT ADDITION. -* S MXVINT CHANGE OF THE INTEGER VECTOR FOR TRUST REGION BOUND -* ADDITION. -* S MXVMUL DIAGONAL PREMULTIPLICATION OF A VECTOR. -* S MXVNEG COPYING OF A VECTOR WITH CHANGE OF THE SIGN. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PLLPB1(NF,NC,X,IX,XO,XL,XU,CF,CFD,IC,ICA,CL,CU,CG, - & CR,CZ,G,GO,S,MFP,KBF,KBC,ETA9,EPS7,EPS9,UMAX,GMAX,N,ITERL) - INTEGER NF,NC,IX(*),IC(*),ICA(*),MFP,KBF,KBC,N,ITERL - DOUBLE PRECISION X(*),XO(*),XL(*),XU(*),CF(*),CFD(*),CL(*), - & CU(*),CG(*),CR(*),CZ(*),G(*),GO(*),S(*),ETA9,EPS7,EPS9, - & UMAX,GMAX - DOUBLE PRECISION POM,CON,DMAX - INTEGER NCA,NCR,NCZ,IPOM,I,K,IOLD,INEW,IER,KREM,KC,NRED - INTEGER NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - COMMON /STAT/ NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - CON=ETA9 -* -* INITIATION -* - CALL MXVCOP(NF,X,XO) - IPOM=0 - NRED=0 - KREM=0 - ITERL=1 - DMAX=0.0D 0 - IF (MFP.EQ.3) GO TO 5 - IF (KBF.GT.0) CALL MXVINA(NF,IX) -* -* SHIFT OF VARIABLES FOR SATISFYING SIMPLE BOUNDS -* - CALL PLINIT(NF,X,IX,XL,XU,EPS9,KBF,INEW,ITERL) - IF (ITERL.LT.0) THEN - GO TO 6 - ENDIF - N=0 - NCA=0 - NCZ=0 - DO 1 I=1,NF - IF (KBF.GT.0.AND.IX(I).LT.0) THEN - NCA=NCA+1 - ICA(NCA)=-I - ELSE - N=N+1 - CALL MXVSET(NF,0.0D 0,CZ(NCZ+1)) - CZ(NCZ+I)=1.0D 0 - NCZ=NCZ+NF - ENDIF - 1 CONTINUE - CALL MXDSMI(NCA,CR) - IF (NC.GT.0) THEN - CALL MXDRMM(NF,NC,CG,X,CF) -* -* ADDITION OF ACTIVE CONSTRAINTS AND INITIAL CHECK OF FEASIBILITY -* - CALL MXVINA(NC,IC) -C IF (NF.GT.N) CALL PLSETC(NF,NC,X,XO,CF,IC,CG,S) - DO 2 KC=1,NC - IF (IC(KC).NE.0) THEN - INEW=0 - CALL PLNEWL(KC,CF,IC,CL,CU,EPS9,INEW) - CALL PLADB0(NF,N,ICA,CG,CR,CZ,S,EPS7,GMAX,UMAX,INEW,NADD,IER) - CALL MXVIND(IC,KC,IER) - IF (IC(KC).LT.-10) IPOM=1 - ENDIF - 2 CONTINUE - ENDIF - 3 IF (IPOM.EQ.1) THEN -* -* CHECK OF FEASIBILITY AND UPDATE OF THE FIRST PHASE OBJECTIVE -* FUNCTION -* - CALL PLSETG(NF,NC,IC,CG,GO,INEW) - IF (INEW.EQ.0) IPOM=0 - ENDIF - IF (IPOM.EQ.0.AND.ITERL.EQ.0) THEN -* -* FEASIBILITY ACHIEVED -* - ITERL=1 - CALL MXVCOP(NF,G,GO) - IF (MFP.EQ.1) GO TO 6 - ENDIF -* -* LAGRANGE MULTIPLIERS AND REDUCED GRADIENT DETERMINATION -* - 5 CALL PLTRBG(NF,N,NC,IX,IC,ICA,CG,CR,CZ,GO,S,EPS7,GMAX,UMAX,IOLD) - INEW=0 - IF (GMAX.EQ.0.0D 0) THEN -* -* OPTIMUM ON A LINEAR MANIFOLD OBTAINED -* - IF (IOLD.EQ.0) THEN - IF (IPOM.EQ.0) THEN -* -* OPTIMAL SOLUTION ACHIEVED -* - ITERL= 2 - GO TO 6 - ELSE - IPOM=0 - DO 22 KC=1,NC - IF (IC(KC).LT.-10) THEN - INEW=0 - CALL PLNEWL(KC,CF,IC,CL,CU,EPS9,INEW) - IF (IC(KC).LT.-10) IPOM=1 - ENDIF - 22 CONTINUE - IF (IPOM.EQ.0) THEN -* -* OPTIMAL SOLUTION ACHIEVED -* - CALL MXVCOP(NF,GO,G) - ITERL= 2 - GO TO 6 - ELSE -* -* FEASIBLE SOLUTION DOES NOT EXIST -* - CALL MXVCOP(NF,GO,G) - ITERL=-1 - GO TO 6 - ENDIF - ENDIF - ELSE -* -* CONSTRAINT DELETION -* - CALL PLRMB0(NF,N,ICA,CG,CR,CZ,GO,S,IOLD,KREM,NREM,IER) - KC=ICA(NF-N+1) - IF (KC.GT.0) THEN - IC(KC)=-IC(KC) - ELSE - K=-KC - IX(K)=-IX(K) - ENDIF - DMAX=0.0D 0 - GO TO 5 - ENDIF - ELSE -* -* DIRECTION DETERMINATION -* - NCA=NF-N - NCR=NCA*(NCA+1)/2 - CALL MXDCMM(NF,N,CZ,S,CR(NCR+1)) - CALL MXVNEG(NF,CR(NCR+1),S) -* -* STEPSIZE SELECTION -* - POM=CON - CALL PLMAXL(NF,NC,CF,CFD,IC,CL,CU,CG,S,POM,KBC,KREM,INEW) - CALL PLMAXS(NF,X,IX,XL,XU,S,POM,KBF,KREM,INEW) - IF (INEW.EQ.0) THEN - IF (IPOM.EQ.0) THEN -* -* BOUNDED SOLUTION DOES NOT EXIST -* - ITERL=-2 - ELSE -* -* FEASIBLE SOLUTION DOES NOT EXIST -* - ITERL=-3 - ENDIF - GO TO 6 - ELSE -* -* STEP REALIZATION -* - CALL PLDIRS(NF,X,IX,S,POM,KBF) - CALL PLDIRL(NC,CF,CFD,IC,POM,KBC) -* -* CONSTRAINT ADDITION -* - IF (INEW.GT.0) THEN - KC=INEW - INEW=0 - CALL PLNEWL(KC,CF,IC,CL,CU,EPS9,INEW) - CALL PLADB0(NF,N,ICA,CG,CR,CZ,S,EPS7,GMAX,UMAX,INEW,NADD,IER) - CALL MXVIND(IC,KC,IER) - ELSE IF (INEW+NF.GE.0) THEN - I=-INEW - INEW=0 - CALL PLNEWS(X,IX,XL,XU,EPS9,I,INEW) - CALL PLADB0(NF,N,ICA,CG,CR,CZ,S,EPS7,GMAX,UMAX,INEW,NADD,IER) - CALL MXVIND(IX,I,IER) - ENDIF - DMAX=POM - IF (DMAX.GT.0.0D 0) NRED=NRED+1 - GO TO 3 - ENDIF - ENDIF - 6 CONTINUE - RETURN - END -* SUBROUTINE PLRMB0 ALL SYSTEMS 92/12/01 -* PORTABILITY : ALL SYSTEMS -* 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* OLD LINEAR CONSTRAINT OR AN OLD SIMPLE BOUND IS REMOVED FROM THE -* ACTIVE SET. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RU GN(NF) TRANSFORMED GRADIENT OF THE OBJECTIVE FUNCTION. -* II IOLD INDEX OF THE OLD ACTIVE CONSTRAINT. -* IO KREM AUXILIARY VARIABLE. -* IU NREM NUMBER OF CONSTRAINT DELETION. -* IO IER ERROR INDICATOR. -* -* SUBPROGRAMS USED : -* S PLRMR0 CORRECTION OF KERNEL OF THE ORTHOGONAL PROJECTION -* AFTER CONSTRAINT DELETION. -* S MXDPRB BACK SUBSTITUTION. -* S MXVCOP COPYING OF A VECTOR. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* S MXVMUL DIAGONAL PREMULTIPLICATION OF A VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PLRMB0(NF,N,ICA,CG,CR,CZ,G,GN,IOLD,KREM,NREM,IER) - INTEGER NF,N,ICA(*),IOLD,KREM,NREM,IER - DOUBLE PRECISION CG(*),CR(*),CZ(*),G(*),GN(*) - DOUBLE PRECISION MXVDOT - INTEGER NCA,NCR,NCZ,I,J,KC - IER=0 - IF (N.EQ.NF) IER=2 - IF (IOLD.EQ.0) IER=3 - IF (IER.NE.0) RETURN - NCA=NF-N - NCR=NCA*(NCA-1)/2 - NCZ=N*NF - CALL PLRMR0(NF,ICA,CR,CZ(NCZ+1),N,IOLD,KREM,IER) - CALL MXVSET(NCA,0.0D 0,CZ(NCZ+1)) - CZ(NCZ+NCA)=1.0D 0 - CALL MXDPRB(NCA,CR,CZ(NCZ+1),-1) - CALL MXVCOP(NCA,CZ(NCZ+1),CR(NCR+1)) - N=N+1 - CALL MXVSET(NF,0.0D 0,CZ(NCZ+1)) - DO 4 J=1,NCA - KC=ICA(J) - IF (KC.GT.0) THEN - CALL MXVDIR(NF,CR(NCR+J),CG((KC-1)*NF+1),CZ(NCZ+1),CZ(NCZ+1)) - ELSE - I=-KC - CZ(NCZ+I)=CZ(NCZ+I)+CR(NCR+J) - ENDIF - 4 CONTINUE - GN(N)=MXVDOT(NF,CZ(NCZ+1),G) - NREM=NREM+1 - IER=0 - RETURN - END -* SUBROUTINE PLQDB1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DUAL RANGE SPACE QUADRATIC PROGRAMMING METHOD. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* IO N DIMENSION OF THE MANIFOLD DEFINED BY ACTIVE CONSTRAINTS. -* II NC NUMBER OF LINEAR CONSTRAINTS. -* RU X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* II IXA(NF) VECTOR CONTAINING INFORMATION ON TRUST REGION ACTIVITY. -* RI XN(NF) VECTOR OF SCALING FACTORS. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* RO CFD(NC) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RO CZ(NF) VECTOR OF LAGRANGE MULTIPLIERS. -* RO G(NF) GRADIENT OF THE LAGRANGIAN FUNCTION. -* RO GO(NF) SAVED GRADIENT OF THE OBJECTIVE FUNCTION. -* RU H(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OR INVERSION OF THE -* HESSIAN MATRIX APPROXIMATION. -* RI S(NF) DIRECTION VECTOR. -* RI ETA2 TOLERANCE FOR POSITIVE DEFINITENESS OF THE HESSIAN MATRIX. -* RI ETA9 MAXIMUM FOR REAL NUMBERS. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RI EPS9 TOLERANCE FOR ACTIVITY OF CONSTRAINTS. -* RU XDEL TRUST REGION BOUND. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* II MFP TYPE OF FEASIBLE POINT. MFP=1-ARBITRARY FEASIBLE POINT. -* MFP=2-OPTIMUM FEASIBLE POINT. MFP=3-REPEATED SOLUTION. -* -* COMMON DATA : -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* II NORMF SCALING SPECIFICATION. NORMF=0-NO SCALING PERFORMED. -* NORMF=1-SCALING FACTORS ARE DETERMINED AUTOMATICALLY. -* NORMF=2-SCALING FACTORS ARE SUPPLIED BY USER. -* IU IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* IDECF=1-GILL-MURRAY DECOMPOSITION. IDECF=9-INVERSION. -* IDECF=10-DIAGONAL MATRIX. -* IU NDECF NUMBER OF DECOMPOSITIONS. -* IO ITERQ TYPE OF FEASIBLE POINT. ITERQ=1-ARBITRARY FEASIBLE POINT. -* ITERQ=2-OPTIMUM FEASIBLE POINT. ITERQ=-1 FEASIBLE POINT DOES -* NOT EXISTS. ITERQ=-2 OPTIMUM FEASIBLE POINT DOES NOT EXISTS. -* -* SUBPROGRAMS USED : -* S PLMINS DETERMINATION OF THE NEW ACTIVE SIMPLE BOUND. -* S PLMINL DETERMINATION OF THE NEW ACTIVE LINEAR CONSTRAINT. -* S PLMINT DETERMINATION OF THE NEW ACTIVE TRUST REGION BOUND. -* S PLADR1 ADDITION OF A NEW ACTIVE CONSTRAINT. -* S PLRMR0 CONSTRAIN DELETION. -* S PLSOB1 TRANSFORMATION OF THE LOCAL SOLUTION TO THE SOLUTION -* OF THE ORIGINAL QP PROBLEM. -* S MXDPGF GILL-MURRAY DECOMPOSITION OF A DENSE SYMMETRIC MATRIX. -* S MXDPGB BACK SUBSTITUTION AFTER GILL-MURRAY DECOMPOSITION. -* S MXDPRB BACK SUBSTITUTION. -* S MXDSMM MATRIX VECTOR PRODUCT. -* S MXVCOP COPYING OF A VECTOR. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXVINA ABSOLUTE VALUES OF ELEMENTS OF AN INTEGER VECTOR. -* S MXVINV CHANGE OF AN INTEGER VECTOR AFTER CONSTRAINT ADDITION. -* S MXVNEG COPYING OF A VECTOR WITH CHANGE OF THE SIGN. -* - SUBROUTINE PLQDB1(NF,NC,X,IX,XL,XU,CF,CFD,IC,ICA,CL,CU,CG,CR,CZ, - & G,GO,H,S,MFP,KBF,KBC,IDECF,ETA2,ETA9,EPS7,EPS9,UMAX,GMAX,N,ITERQ) - INTEGER NF,NC,IX(*),IC(*),ICA(*),MFP,KBF,KBC,IDECF,N,ITERQ - DOUBLE PRECISION X(*),XL(*),XU(*),CF(*),CFD(*),CL(*),CU(*),CG(*), - & CR(*),CZ(*),G(*),GO(*),H(*),S(*),ETA2,ETA9,EPS7,EPS9,UMAX,GMAX - DOUBLE PRECISION CON,TEMP,STEP,STEP1,STEP2,DMAX,PAR,SNORM - INTEGER NCA,NCR,I,J,K,IOLD,JOLD,INEW,JNEW,KNEW,INF,IER,KREM,KC, - & NRED - INTEGER NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - COMMON /STAT/ NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - CON=ETA9 - IF (IDECF.LT.0) IDECF=1 - IF (IDECF.EQ.0) THEN -C -C GILL-MURRAY DECOMPOSITION -C - TEMP=ETA2 - CALL MXDPGF(NF,H,INF,TEMP,STEP) - NDEC=NDEC+1 - IDECF=1 - ENDIF - IF (IDECF.GE.2.AND.IDECF.LE.8) THEN - ITERQ=-10 - RETURN - ENDIF -C -C INITIATION -C - NRED=0 - JOLD=0 - JNEW=0 - ITERQ=0 - DMAX=0.0D0 - IF (MFP.EQ.3) GO TO 1 - N=NF - NCA=0 - NCR=0 - IF (KBF.GT.0) CALL MXVINA(NF,IX) - IF (KBC.GT.0) CALL MXVINA(NC,IC) -C -C DIRECTION DETERMINATION -C - 1 CALL MXVNEG(NF,GO,S) - DO 2 J=1,NCA - KC=ICA(J) - IF (KC.GT.0) THEN - CALL MXVDIR(NF,CZ(J),CG((KC-1)*NF+1),S,S) - ELSE - K=-KC - S(K)=S(K)+CZ(J) - ENDIF - 2 CONTINUE - CALL MXVCOP(NF,S,G) - IF (IDECF.EQ.1) THEN - CALL MXDPGB(NF,H,S,0) - ELSE - CALL MXDSMM(NF,H,G,S) - ENDIF - IF (ITERQ.EQ.3) GO TO 7 -C -C CHECK OF FEASIBILITY -C - INEW=0 - PAR=0.0D0 - CALL PLMINN(NF,NC,CF,CFD,IC,CL,CU,CG,S,EPS9,PAR,KBC,INEW,KNEW) - CALL PLMINS(NF,IX,X,XL,XU,S,KBF,INEW,KNEW,EPS9,PAR) - IF (INEW.EQ.0) THEN -C -C SOLUTION ACHIEVED -C - CALL MXVNEG(NF,G,G) - ITERQ=2 - GO TO 7 - ELSE - SNORM=0.0D0 - ENDIF - 4 IER=0 -C -C STEPSIZE DETERMINATION -C - CALL PLADR1(NF,N,ICA,CG,CR,H,S,G,EPS7,GMAX,UMAX,IDECF,INEW, - & NADD,IER,1) - CALL MXDPRB(NCA,CR,G,-1) - IF (KNEW.LT.0) CALL MXVNEG(NCA,G,G) -C -C PRIMAL STEPSIZE -C - IF (IER.NE.0) THEN - STEP1=CON - ELSE - STEP1=-PAR/UMAX - ENDIF -C -C DUAL STEPSIZE -C - IOLD=0 - STEP2=CON - DO 5 J=1,NCA - KC=ICA(J) - IF (KC.GE.0) THEN - K=IC(KC) - ELSE - I=-KC - K=IX(I) - ENDIF - IF (K.LE.-5) THEN - ELSE IF ((K.EQ.-1.OR.K.EQ.-3.).AND.G(J).LE.0.0D0) THEN - ELSE IF ((K.EQ.-2.OR.K.EQ.-4.).AND.G(J).GE.0.0D0) THEN - ELSE - TEMP=CZ(J)/G(J) - IF (STEP2.GT.TEMP) THEN - IOLD=J - STEP2=TEMP - ENDIF - ENDIF - 5 CONTINUE -C -C FINAL STEPSIZE -C - STEP=MIN(STEP1,STEP2) - IF (STEP.GE.CON) THEN -C -C FEASIBLE SOLUTION DOES NOT EXIST -C - ITERQ=-1 - GO TO 7 - ENDIF -C -C NEW LAGRANGE MULTIPLIERS -C - DMAX=STEP - CALL MXVDIR(NCA,-STEP,G,CZ,CZ) - SNORM=SNORM+SIGN(1,KNEW)*STEP - PAR=PAR-(STEP/STEP1)*PAR - IF (STEP.EQ.STEP1) THEN - IF (N.LE.0) THEN -C -C IMPOSSIBLE SITUATION -C - ITERQ=-5 - GO TO 7 - ENDIF -C -C CONSTRAINT ADDITION -C - IF (IER.EQ.0) THEN - N=N-1 - NCA=NCA+1 - NCR=NCR+NCA - CZ(NCA)=SNORM - ENDIF - IF (INEW.GT.0) THEN - KC=INEW - CALL MXVINV(IC,KC,KNEW) - ELSE IF (ABS(KNEW).EQ.1) THEN - I=-INEW - CALL MXVINV(IX,I,KNEW) - ELSE - I=-INEW - IF (KNEW.GT.0) IX(I)=-3 - IF (KNEW.LT.0) IX(I)=-4 - ENDIF - NRED=NRED+1 - NADD=NADD+1 - JNEW=INEW - JOLD=0 - GO TO 1 - ELSE -C -C CONSTRAINT DELETION -C - DO 6 J=IOLD,NCA-1 - CZ(J)=CZ(J+1) - 6 CONTINUE - CALL PLRMF0(NF,NC,IX,IC,ICA,CR,IC,G,N,IOLD,KREM,IER) - NCR=NCR-NCA - NCA=NCA-1 - JOLD=IOLD - JNEW=0 - IF (KBC.GT.0) CALL MXVINA(NC,IC) - IF (KBF.GT.0) CALL MXVINA(NF,IX) - DO 8 J=1,NCA - KC=ICA(J) - IF (KC.GT.0) THEN - IC(KC)=-IC(KC) - ELSE - KC=-KC - IX(KC)=-IX(KC) - ENDIF - 8 CONTINUE - GO TO 4 - ENDIF - 7 CONTINUE - RETURN - END -* SUBROUTINE PLADR1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TRIANGULAR DECOMPOSITION OF KERNEL OF THE GENERAL PROJECTION -* IS UPDATED AFTER CONSTRAINT ADDITION. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU N ACTUAL NUMBER OF VARIABLES. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU H(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OR INVERSION OF THE -* HESSIAN MATRIX APPROXIMATION. -* RA S(NF) AUXILIARY VECTOR. -* RO G(NF) VECTOR USED IN THE DUAL RANGE SPACE QUADRATIC PROGRAMMING -* METHOD. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* RO E AUXILIARY VARIABLE. -* RI T AUXILIARY VARIABLE. -* IU IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* IDECF=1-GILL-MURRAY DECOMPOSITION. IDECF=9-INVERSION. -* IDECF=10-DIAGONAL MATRIX. -* II INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IU NADD NUMBER OF CONSTRAINT ADDITIONS. -* IO IER ERROR INDICATOR. -* II JOB SPECIFICATION OF COMPUTATION. OUTPUT VECTOR G IS NOT OR IS -* COMPUTED IN CASE WHEN N.LE.0 IF JOB=0 OR JOB=1 RESPECTIVELY. -* -* SUBPROGRAMS USED : -* S MXDPGB BACK SUBSTITUTION. -* S MXDPRB BACK SUBSTITUTION. -* S MXDSMM MATRIX-VECTOR PRODUCT. -* S MXDSMV COPYING OF A ROW OF DENSE SYMMETRIC MATRIX. -* S MXVCOP COPYING OF A VECTOR. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* - SUBROUTINE PLADR1(NF,N,ICA,CG,CR,H,S,G,EPS7,GMAX,UMAX,IDECF, - & INEW,NADD,IER,JOB) - INTEGER NF,N,ICA(*),IDECF,INEW,NADD,IER,JOB - DOUBLE PRECISION CG(*),CR(*),H(*),S(*),G(*),EPS7,GMAX,UMAX - DOUBLE PRECISION MXVDOT - INTEGER NCA,NCR,JCG,J,K,L - IER=0 - IF (JOB.EQ.0.AND.N.LE.0) IER=2 - IF (INEW.EQ.0) IER=3 - IF (IDECF.NE.1.AND.IDECF.NE.9) IER=-2 - IF (IER.NE.0) RETURN - NCA=NF-N - NCR=NCA*(NCA+1)/2 - IF (INEW.GT.0) THEN - JCG=(INEW-1)*NF+1 - IF (IDECF.EQ.1) THEN - CALL MXVCOP(NF,CG(JCG),S) - CALL MXDPGB(NF,H,S,0) - ELSE - CALL MXDSMM(NF,H,CG(JCG),S) - ENDIF - GMAX=MXVDOT(NF,CG(JCG),S) - ELSE - K=-INEW - IF (IDECF.EQ.1) THEN - CALL MXVSET(NF,0.0D0,S) - S(K)=1.0D 0 - CALL MXDPGB(NF,H,S,0) - ELSE - CALL MXDSMV(NF,H,S,K) - ENDIF - GMAX=S(K) - ENDIF - DO 1 J=1,NCA - L=ICA(J) - IF (L.GT.0) THEN - G(J)=MXVDOT(NF,CG((L-1)*NF+1),S) - ELSE - L=-L - G(J)=S(L) - ENDIF - 1 CONTINUE - IF (N.EQ.0) THEN - CALL MXDPRB(NCA,CR,G,1) - UMAX=0.0D0 - IER=2 - RETURN - ELSE IF (NCA.EQ.0) THEN - UMAX=GMAX - ELSE - CALL MXDPRB(NCA,CR,G,1) - UMAX=GMAX-MXVDOT(NCA,G,G) - CALL MXVCOP(NCA,G,CR(NCR+1)) - ENDIF - IF (UMAX.LE.EPS7*GMAX) THEN - IER=1 - RETURN - ELSE - NCA=NCA+1 - NCR=NCR+NCA - ICA(NCA)=INEW - CR(NCR)=SQRT(UMAX) - IF (JOB.EQ.0) THEN - N=N-1 - NADD=NADD+1 - ENDIF - ENDIF - RETURN - END -* SUBROUTINE PLDIRL ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE NEW VALUES OF THE CONSTRAINT FUNCTIONS. -* -* PARAMETERS : -* II NC NUMBER OF CONSTRAINTS. -* RU CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* RI CFD(NF) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI STEP CURRENT STEPSIZE. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* - SUBROUTINE PLDIRL(NC,CF,CFD,IC,STEP,KBC) - INTEGER NC,IC(*),KBC - DOUBLE PRECISION CF(*),CFD(*),STEP - INTEGER KC - IF (KBC.GT.0) THEN - DO 1 KC=1,NC - IF (IC(KC).GE.0.AND.IC(KC).LE.10) THEN - CF(KC)=CF(KC)+STEP*CFD(KC) - ELSE IF (IC(KC).LT.-10) THEN - CF(KC)=CF(KC)+STEP*CFD(KC) - ENDIF - 1 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PLDIRS ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE NEW VECTOR OF VARIABLES. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* RU X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RI S(NF) DIRECTION VECTOR. -* RI STEP CURRENT STEPSIZE. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* - SUBROUTINE PLDIRS(NF,X,IX,S,STEP,KBF) - INTEGER NF,IX(*),KBF - DOUBLE PRECISION X(*),S(*),STEP - INTEGER I - DO 1 I=1,NF - IF (KBF.LE.0) THEN - X(I)=X(I)+STEP*S(I) - ELSE IF (IX(I).GE.0.AND.IX(I).LE.10) THEN - X(I)=X(I)+STEP*S(I) - ELSE IF (IX(I).LT.-10) THEN - X(I)=X(I)+STEP*S(I) - ENDIF - 1 CONTINUE - RETURN - END -* SUBROUTINE PLINIT ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE INITIAL POINT WHICH SATISFIES SIMPLE BOUNDS. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* RU X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI EPS9 TOLERANCE FOR ACTIVE CONSTRAINTS. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IO IND INDICATOR. IF IND.NE.0 THEN TRUST REGION BOUNDS CANNOT -* BE SATISFIED. -* -* SUBPROGRAMS USED : -* S PLNEWS TEST ON ACTIVITY OF A GIVEN SIMPLE BOUND. -* - SUBROUTINE PLINIT(NF,X,IX,XL,XU,EPS9,KBF,INEW,IND) - INTEGER NF,IX(*),KBF,INEW,IND - DOUBLE PRECISION X(*),XL(*),XU(*),EPS9 - INTEGER I - IND=0 - IF (KBF.GT.0) THEN - DO 1 I=1,NF - CALL PLNEWS(X,IX,XL,XU,EPS9,I,INEW) - IF (IX(I).LT.5) THEN - ELSE IF (IX(I).EQ.5) THEN - IX(I)=-5 - ELSE IF (IX(I).EQ.11.OR.IX(I).EQ.13) THEN - X(I)=XL(I) - IX(I)=10-IX(I) - ELSE IF (IX(I).EQ.12.OR.IX(I).EQ.14) THEN - X(I)=XU(I) - IX(I)=10-IX(I) - ENDIF - 1 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PLMAXL ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE MAXIMUM STEPSIZE USING LINEAR CONSTRAINTS. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II NC NUMBER OF CURRENT LINEAR CONSTRAINTS. -* RI CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCYIONS. -* RO CFD(NF) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI S(NF) DIRECTION VECTOR. -* RO STEP MAXIMUM STEPSIZE. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* II KREM INDICATION OF LINEARLY DEPENDENT GRADIENTS. -* IO INEW INDEX OF THE NEW ACTIVE FUNCTION. -* -* SUBPROGRAMS USED : -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* - SUBROUTINE PLMAXL(NF,NC,CF,CFD,IC,CL,CU,CG,S,STEP,KBC,KREM,INEW) - INTEGER NF,NC,IC(*),KBC,KREM,INEW - DOUBLE PRECISION CF(*),CFD(*),CL(*),CU(*),CG(*),S(*),STEP - DOUBLE PRECISION TEMP,MXVDOT - INTEGER JCG,KC - IF (KBC.GT.0) THEN - JCG=1 - DO 1 KC=1,NC - IF (KREM.GT.0.AND.IC(KC).GT.10) IC(KC)=IC(KC)-10 - IF (IC(KC).GT.0.AND.IC(KC).LE.10) THEN - TEMP=MXVDOT(NF,CG(JCG),S) - CFD(KC)=TEMP - IF (TEMP.LT.0.0D 0) THEN - IF (IC(KC).EQ.1.OR.IC(KC).GE.3) THEN - TEMP=(CL(KC)-CF(KC))/TEMP - IF (TEMP.LE.STEP) THEN - INEW=KC - STEP=TEMP - ENDIF - ENDIF - ELSE IF (TEMP.GT.0.0D 0) THEN - IF (IC(KC).EQ.2.OR.IC(KC).GE.3) THEN - TEMP=(CU(KC)-CF(KC))/TEMP - IF (TEMP.LE.STEP) THEN - INEW=KC - STEP=TEMP - ENDIF - ENDIF - ENDIF - ELSE IF (IC(KC).LT.-10) THEN - TEMP=MXVDOT(NF,CG(JCG),S) - CFD(KC)=TEMP - IF (TEMP.GT.0.0D 0) THEN - IF (IC(KC).EQ.-11.OR.IC(KC).EQ.-13.OR.IC(KC).EQ.-15) THEN - TEMP=(CL(KC)-CF(KC))/TEMP - IF (TEMP.LE.STEP) THEN - INEW=KC - STEP=TEMP - ENDIF - ENDIF - ELSE IF (TEMP.LT.0.0D 0) THEN - IF (IC(KC).EQ.-12.OR.IC(KC).EQ.-14.OR.IC(KC).EQ.-16) THEN - TEMP=(CU(KC)-CF(KC))/TEMP - IF (TEMP.LE.STEP) THEN - INEW=KC - STEP=TEMP - ENDIF - ENDIF - ENDIF - ENDIF - JCG=JCG+NF - 1 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PLMAXS ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE MAXIMUM STEPSIZE USING THE SIMPLE BOUNDS -* FOR VARIABLES. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* RI X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI S(NF) DIRECTION VECTOR. -* RO STEP MAXIMUM STEPSIZE. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* IO KREM INDICATION OF LINEARLY DEPENDENT GRADIENTS. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* - SUBROUTINE PLMAXS(NF,X,IX,XL,XU,S,STEP,KBF,KREM,INEW) - INTEGER NF,IX(*),KBF,KREM,INEW - DOUBLE PRECISION X(*),XL(*),XU(*),S(*),STEP - DOUBLE PRECISION TEMP - INTEGER I - IF (KBF.GT.0) THEN - DO 1 I=1,NF - IF (KREM.GT.0.AND.IX(I).GT.10) IX(I)=IX(I)-10 - IF (IX(I).GT.0.AND.IX(I).LE.10) THEN - IF (S(I).LT.0.0D 0) THEN - IF (IX(I).EQ.1.OR.IX(I).GE.3) THEN - TEMP=(XL(I)-X(I))/S(I) - IF (TEMP.LE.STEP) THEN - INEW=-I - STEP=TEMP - ENDIF - ENDIF - ELSE IF (S(I).GT.0.0D 0) THEN - IF (IX(I).EQ.2.OR.IX(I).GE.3) THEN - TEMP=(XU(I)-X(I))/S(I) - IF (TEMP.LE.STEP) THEN - INEW=-I - STEP=TEMP - ENDIF - ENDIF - ENDIF - ENDIF - 1 CONTINUE - ENDIF - KREM=0 - RETURN - END -* SUBROUTINE PLNEWL ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TEST ON ACTIVITY OF A GIVEN LINEAR CONSTRAINT. -* -* PARAMETERS : -* II KC INDEX OF A GIVEN CONSTRAINT. -* RI CF(NC) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* IU IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI EPS9 TOLERANCE FOR ACTIVE CONSTRAINTS. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* - SUBROUTINE PLNEWL(KC,CF,IC,CL,CU,EPS9,INEW) - INTEGER KC,IC(*),INEW - DOUBLE PRECISION CF(*),CL(*),CU(*),EPS9 - DOUBLE PRECISION TEMP - IF (IC(KC).LT.-10) IC(KC)=-IC(KC)-10 - IF (IC(KC).LE.0) THEN - ELSE IF (IC(KC).EQ.1) THEN - TEMP=EPS9*MAX(ABS(CL(KC)),1.0D 0) - IF (CF(KC).GT.CL(KC)+TEMP) THEN - ELSE IF (CF(KC).GE.CL(KC)-TEMP) THEN - IC(KC)=11 - INEW=KC - ELSE - IC(KC)=-11 - ENDIF - ELSE IF (IC(KC).EQ.2) THEN - TEMP=EPS9*MAX(ABS(CU(KC)),1.0D 0) - IF (CF(KC).LT.CU(KC)-TEMP) THEN - ELSE IF (CF(KC).LE.CU(KC)+TEMP) THEN - IC(KC)=12 - INEW=KC - ELSE - IC(KC)=-12 - ENDIF - ELSE IF (IC(KC).EQ.3.OR.IC(KC).EQ.4) THEN - TEMP=EPS9*MAX(ABS(CL(KC)),1.0D 0) - IF (CF(KC).GT.CL(KC)+TEMP) THEN - TEMP=EPS9*MAX(ABS(CU(KC)),1.0D 0) - IF (CF(KC).LT.CU(KC)-TEMP) THEN - ELSE IF (CF(KC).LE.CU(KC)+TEMP) THEN - IC(KC)=14 - INEW=KC - ELSE - IC(KC)=-14 - ENDIF - ELSE IF (CF(KC).GE.CL(KC)-TEMP) THEN - IC(KC)=13 - INEW=KC - ELSE - IC(KC)=-13 - ENDIF - ELSE IF (IC(KC).EQ.5.OR.IC(KC).EQ.6) THEN - TEMP=EPS9*MAX(ABS(CL(KC)),1.0D 0) - IF (CF(KC).GT.CL(KC)+TEMP) THEN - TEMP=EPS9*MAX(ABS(CU(KC)),1.0D 0) - IF (CF(KC).LT.CU(KC)-TEMP) THEN - ELSE IF (CF(KC).LE.CU(KC)+TEMP) THEN - IC(KC)=16 - INEW=KC - ELSE - IC(KC)=-16 - ENDIF - ELSE IF (CF(KC).GE.CL(KC)-TEMP) THEN - IC(KC)=15 - INEW=KC - ELSE - IC(KC)=-15 - ENDIF - ENDIF - RETURN - END -* SUBROUTINE PLMINN ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE NEW ACTIVE LINEAR CONSTRAINT. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* RI CF(NC) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* RO CFD(NC) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI S(NF) DIRECTION VECTOR. -* RI EPS9 TOLERANCE FOR ACTIVE CONSTRAINTS. -* RA PAR AUXILIARY VARIABLE. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IO KNEW SIGNUM OF THE NEW ACTIVE NORMAL. -* -* SUBPROGRAMS USED : -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* - SUBROUTINE PLMINN(NF,NC,CF,CFD,IC,CL,CU,CG,S,EPS9,PAR,KBC,INEW, - & KNEW) - INTEGER NF,NC,IC(*),KBC,INEW,KNEW - DOUBLE PRECISION CF(*),CFD(*),CL(*),CU(*),CG(*),S(*),EPS9,PAR - DOUBLE PRECISION TEMP,POM,MXVDOT - INTEGER JCG,KC - IF (KBC.GT.0) THEN - JCG=1 - DO 1 KC=1,NC - IF (IC(KC).GT.0) THEN - TEMP=MXVDOT(NF,CG(JCG),S) - CFD(KC)=TEMP - TEMP=CF(KC)+TEMP - IF (IC(KC).EQ.1.OR.IC(KC).GE.3) THEN - POM=TEMP-CL(KC) - IF (POM.LT.MIN(PAR,-EPS9*MAX(ABS(CL(KC)),1.0D 0))) THEN - INEW=KC - KNEW= 1 - PAR=POM - ENDIF - ENDIF - IF (IC(KC).EQ.2.OR.IC(KC).GE.3) THEN - POM=CU(KC)-TEMP - IF (POM.LT.MIN(PAR,-EPS9*MAX(ABS(CU(KC)),1.0D 0))) THEN - INEW=KC - KNEW=-1 - PAR=POM - ENDIF - ENDIF - ENDIF - JCG=JCG+NF - 1 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PLMINS ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF THE NEW ACTIVE SIMPLE BOUND. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RI XO(NF) SAVED VECTOR OF VARIABLES. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI S(NF) DIRECTION VECTOR. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IO KNEW SIGNUM OF THE NEW NORMAL. -* RI EPS9 TOLERANCE FOR ACTIVE CONSTRAINTS. -* RA PAR AUXILIARY VARIABLE. -* - SUBROUTINE PLMINS(NF,IX,XO,XL,XU,S,KBF,INEW,KNEW,EPS9,PAR) - DOUBLE PRECISION EPS9,PAR - INTEGER INEW,KBF,KNEW,NF - DOUBLE PRECISION S(*),XL(*),XO(*),XU(*) - INTEGER IX(*) - DOUBLE PRECISION POM,TEMP - INTEGER I - IF (KBF.GT.0) THEN - DO 10 I = 1,NF - IF (IX(I).GT.0) THEN - TEMP = 1.0D0 - IF (IX(I).EQ.1 .OR. IX(I).GE.3) THEN - POM = XO(I) + S(I)*TEMP - XL(I) - IF (POM.LT.MIN(PAR,-EPS9*MAX(ABS(XL(I)), - + TEMP))) THEN - INEW = -I - KNEW = 1 - PAR = POM - END IF - END IF - IF (IX(I).EQ.2 .OR. IX(I).GE.3) THEN - POM = XU(I) - S(I)*TEMP - XO(I) - IF (POM.LT.MIN(PAR,-EPS9*MAX(ABS(XU(I)), - + TEMP))) THEN - INEW = -I - KNEW = -1 - PAR = POM - END IF - END IF - END IF - 10 CONTINUE - END IF - RETURN - END -* SUBROUTINE PLNEWS ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TEST ON ACTIVITY OF A GIVEN SIMPLE BOUND. -* -* PARAMETERS : -* RI X(NF) VECTOR OF VARIABLES. -* IU IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI EPS9 TOLERANCE FOR ACTIVE CONSTRAINTS. -* II I INDEX OF TESTED SIMPLE BOUND. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* - SUBROUTINE PLNEWS(X,IX,XL,XU,EPS9,I,INEW) - INTEGER IX(*),I,INEW - DOUBLE PRECISION X(*),XL(*),XU(*),EPS9 - DOUBLE PRECISION TEMP - TEMP=1.0D 0 - IF (IX(I).LE.0) THEN - ELSE IF (IX(I).EQ.1) THEN - IF (X(I).LE.XL(I)+EPS9*MAX(ABS(XL(I)),TEMP)) THEN - IX(I)=11 - INEW=-I - ENDIF - ELSE IF (IX(I).EQ.2) THEN - IF (X(I).GE.XU(I)-EPS9*MAX(ABS(XU(I)),TEMP)) THEN - IX(I)=12 - INEW=-I - ENDIF - ELSE IF (IX(I).EQ.3.OR.IX(I).EQ.4) THEN - IF (X(I).LE.XL(I)+EPS9*MAX(ABS(XL(I)),TEMP)) THEN - IX(I)=13 - INEW=-I - ENDIF - IF (X(I).GE.XU(I)-EPS9*MAX(ABS(XU(I)),TEMP)) THEN - IX(I)=14 - INEW=-I - ENDIF - ENDIF - RETURN - END -* SUBROUTINE PLREDL ALL SYSTEMS 98/12/01 -C PORTABILITY : ALL SYSTEMS -C 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TRANSFORMATION OF THE INCOMPATIBLE QUADRATIC PROGRAMMING SUBPROBLEM. -* -* PARAMETERS : -* II NC NUMBER OF CURRENT LINEAR CONSTRAINTS. -* RI CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* - SUBROUTINE PLREDL(NC,CF,IC,CL,CU,KBC) - INTEGER NC,IC(NC),KBC,K - DOUBLE PRECISION CF(*),CL(*),CU(*) - DOUBLE PRECISION TEMP - INTEGER KC - IF (KBC.GT.0) THEN - DO 1 KC=1,NC - K=IC(KC) - IF (ABS(K).EQ.1.OR.ABS(K).EQ.3.OR.ABS(K).EQ.4) THEN - TEMP=(CF(KC)-CL(KC)) - IF (TEMP.LT.0) CF(KC)=CL(KC)+0.1D 0*TEMP - ENDIF - IF (ABS(K).EQ.2.OR.ABS(K).EQ.3.OR.ABS(K).EQ.4) THEN - TEMP=(CF(KC)-CU(KC)) - IF (TEMP.GT.0) CF(KC)=CU(KC)+0.1D 0*TEMP - ENDIF - IF (ABS(K).EQ.5.OR.ABS(K).EQ.6) THEN - TEMP=(CF(KC)-CL(KC)) - CF(KC)=CL(KC)+0.1D 0*TEMP - ENDIF - 1 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PLRMF0 ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* OPERATIONS AFTER CONSTRAINT DELETION. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* II IA(NA) VECTOR CONTAINING TYPES OF DEVIATIONS. -* IU IAA(NF+1) VECTOR CONTAINING INDICES OF ACTIVE FUNCTIONS. -* RU AR((NF+1)*(NF+2)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RA S(NF+1) AUXILIARY VECTOR. -* II N ACTUAL NUMBER OF VARIABLES. -* II IOLD INDEX OF THE OLD ACTIVE CONSTRAINT. -* IO KREM AUXILIARY VARIABLE. -* IO IER ERROR INDICATOR. -* -* SUBPROGRAMS USED : -* S PLRMR0 CORRECTION OF KERNEL OF THE ORTHOGONAL PROJECTION -* AFTER CONSTRAINT DELETION. -* - SUBROUTINE PLRMF0(NF,NC,IX,IA,IAA,AR,IC,S,N,IOLD,KREM,IER) - INTEGER IER,IOLD,KREM,N,NC,NF - DOUBLE PRECISION AR(*),S(*) - INTEGER IA(*),IAA(*),IC(*),IX(*) - INTEGER NADD,NDEC,NFG,NFH,NFV,NIT,NREM,NRES - INTEGER L - COMMON /STAT/NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - CALL PLRMR0(NF,IAA,AR,S,N,IOLD,KREM,IER) - N = N + 1 - NREM = NREM + 1 - L = IAA(NF-N+1) - IF (L.GT.NC) THEN - L = L - NC - IA(L) = -IA(L) - ELSE IF (L.GT.0) THEN - IC(L) = -IC(L) - ELSE - L = -L - IX(L) = -IX(L) - END IF - RETURN - END -* SUBROUTINE PLRMR0 ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TRIANGULAR DECOMPOSITION OF KERNEL OF THE ORTHOGONAL PROJECTION IS -* UPDATED AFTER CONSTRAINT DELETION. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RA G(NF) AUXILIARY VECTOR. -* II N ACTUAL NUMBER OF VARIABLES. -* II IOLD INDEX OF THE OLD ACTIVE CONSTRAINT. -* IO KREM AUXILIARY VARIABLE. -* IO IER ERROR INDICATOR. -* -* SUBPROGRAMS USED : -* S MXVCOP COPYING OF A VECTOR. -* S MXVORT DETERMINATION OF AN ELEMENTARY ORTHOGONAL MATRIX FOR -* PLANE ROTATION. -* S MXVROT PLANE ROTATION OF A VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PLRMR0(NF,ICA,CR,G,N,IOLD,KREM,IER) - INTEGER IER,IOLD,KREM,N,NF - DOUBLE PRECISION CR(*),G(*) - INTEGER ICA(*) - DOUBLE PRECISION CK,CL - INTEGER I,J,K,KC,L,NCA - NCA = NF - N - IF (IOLD.LT.NCA) THEN - K = IOLD* (IOLD-1)/2 - KC = ICA(IOLD) - CALL MXVCOP(IOLD,CR(K+1),G) - CALL MXVSET(NCA-IOLD,0.0D0,G(IOLD+1)) - K = K + IOLD - DO 20 I = IOLD + 1,NCA - K = K + I - CALL MXVORT(CR(K-1),CR(K),CK,CL,IER) - CALL MXVROT(G(I-1),G(I),CK,CL,IER) - L = K - DO 10 J = I,NCA - 1 - L = L + J - CALL MXVROT(CR(L-1),CR(L),CK,CL,IER) - 10 CONTINUE - 20 CONTINUE - K = IOLD* (IOLD-1)/2 - DO 30 I = IOLD,NCA - 1 - L = K + I - ICA(I) = ICA(I+1) - CALL MXVCOP(I,CR(L+1),CR(K+1)) - K = L - 30 CONTINUE - ICA(NCA) = KC - CALL MXVCOP(NCA,G,CR(K+1)) - END IF - KREM = 1 - RETURN - END -* SUBROUTINE PLSETC ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF INITIAL VALUES OF THE CONSTRAINT FUNCTIONS. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II NC NUMBER OF CURRENT LINEAR CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* RI XO(NF) SAVED VECTOR OF VARIABLES. -* RU CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCYIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CG(NF*MCL) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RA S(NF) AUXILIARY VECTOR. -* -* SUBPROGRAMS USED : -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* S MXVMUL DIAGONAL PREMULTIPLICATION OF A VECTOR. -* - SUBROUTINE PLSETC(NF,NC,X,XO,CF,IC,CG,S) - INTEGER NF,NC,IC(*) - DOUBLE PRECISION X(*),XO(*),CF(*),CG(*),S(*) - DOUBLE PRECISION MXVDOT - INTEGER JCG,KC - CALL MXVDIF(NF,X,XO,S) - JCG=0 - DO 1 KC=1,NC - IF (IC(KC).NE.0) CF(KC)=CF(KC)+MXVDOT(NF,S,CG(JCG+1)) - JCG=JCG+NF - 1 CONTINUE - RETURN - END -* SUBROUTINE PLSETG ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* GRADIENT DETERMINATION IN THE FIRST PHASE OF LP SUBROUTINE. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RO G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* IO INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* -* SUBPROGRAMS USED : -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PLSETG(NF,NC,IC,CG,G,INEW) - INTEGER NF,NC,IC(*),INEW - DOUBLE PRECISION CG(*),G(*) - INTEGER KC - CALL MXVSET(NF,0.0D 0,G) - INEW=0 - DO 4 KC=1,NC - IF (IC(KC).GE.-10) THEN - ELSE IF (IC(KC).EQ.-11.OR.IC(KC).EQ.-13.OR.IC(KC).EQ.-15) THEN - CALL MXVDIR(NF,-1.0D 0,CG((KC-1)*NF+1),G,G) - INEW=1 - ELSE IF (IC(KC).EQ.-12.OR.IC(KC).EQ.-14.OR.IC(KC).EQ.-16) THEN - CALL MXVDIR(NF, 1.0D 0,CG((KC-1)*NF+1),G,G) - INEW=1 - ENDIF - 4 CONTINUE - RETURN - END -* SUBROUTINE PLTLAG ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* MAXIMUM ABSOLUTE VALUE OF THE NEGATIVE LAGRANGE MULTIPLIER IS -* COMPUTED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF LINEARIZED CONSTRAINTS. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* II IA(NA) VECTOR CONTAINING TYPES OF DEVIATIONS. -* II IAA(NF+1) VECTOR CONTAINING INDICES OF ACTIVE FUNCTIONS. -* RI AZ(NF+1) VECTOR OF LAGRANGE MULTIPLIERS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI EPS7 TOLERANCE FOR LINEAR AND QUADRATIC PROGRAMMING. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF THE NEGATIVE LAGRANGE MULTIPLIER. -* IO IOLD INDEX OF THE REMOVED CONSTRAINT. -* - SUBROUTINE PLTLAG(NF,N,NC,IX,IA,IAA,AZ,IC,EPS7,UMAX,IOLD) - INTEGER NF,N,NC,IX(*),IA(*),IAA(*),IC(*),IOLD - DOUBLE PRECISION AZ(*),EPS7,UMAX - DOUBLE PRECISION TEMP - INTEGER NAA,J,K,L - IOLD=0 - UMAX=0.0D 0 - NAA=NF-N - DO 2 J=1,NAA - TEMP=AZ(J) - L=IAA(J) - IF (L.GT.NC) THEN - L=L-NC - K=IA(L) - ELSE IF (L.GT.0) THEN - K=IC(L) - ELSE - L=-L - K=IX(L) - ENDIF - IF (K.LE.-5) THEN - ELSE IF ((K.EQ.-1.OR.K.EQ.-3).AND.UMAX+TEMP.GE.0.0D 0) THEN - ELSE IF ((K.EQ.-2.OR.K.EQ.-4).AND.UMAX-TEMP.GE.0.0D 0) THEN - ELSE - IOLD=J - UMAX=ABS(TEMP) - ENDIF - 2 CONTINUE - IF (UMAX.LE.EPS7) IOLD=0 - RETURN - END -* SUBROUTINE PLTRBG ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* GRADIENT OF THE OBJECTIVE FUNCTION IS SCALED AND REDUCED. LAGRANGE -* MULTIPLIERS ARE DETERMINED. TEST VALUES GMAX AND UMAX ARE COMPUTED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF CURRENT LINEAR CONSTRAINTS. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. VECTOR CZ(1,NF) CONTAINS LAGRANGE -* MULTIPLIERS BEING DETERMINED. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RO GN(NF) TRANSFORMED GRADIENT OF THE OBJECTIVE FUNCTION IF IT IS -* NONZERO. -* RI EPS7 TOLERANCE FOR LINEAR AND QUADRATIC PROGRAMMING. -* RO GMAX NORM OF THE TRANSFORMED GRADIENT. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF THE NEGATIVE LAGRANGE MULTIPLIER. -* IO IOLD INDEX OF THE REMOVED CONSTRAINT. -* -* SUBPROGRAMS USED : -* S PLVLAG GRADIENT IS PREMULTIPLIED BY THE MATRIX WHOSE COLUMNS -* ARE NORMALS OF THE ACTIVE CONSTRAINTS. -* S PLTLAG COMPUTATION OF THE MAXIMUM ABSOLUTE VALUE OF THE NEGATIVE -* LAGRANGE MULTIPLIER. -* S MXDRMM PREMULTIPLICATION OF A VECTOR BY A ROWWISE STORED DENSE -* RECTANGULAR MATRIX. -* S MXDPRB BACK SUBSTITUTION AFTER A CHOLESKI DECOMPOSITION. -* RF MXVMAX L-INFINITY NORM OF A VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PLTRBG(NF,N,NC,IX,IC,ICA,CG,CR,CZ,G,GN,EPS7,GMAX,UMAX, - & IOLD) - INTEGER NF,N,NC,IX(*),IC(*),ICA(*),IOLD - DOUBLE PRECISION CG(*),CR(*),CZ(*),G(*),GN(*),EPS7,GMAX,UMAX - DOUBLE PRECISION MXVMAX - INTEGER NCA,NCZ - GMAX=0.0D 0 - IF (N.GT.0) THEN - CALL MXDRMM(NF,N,CZ,G,GN) - GMAX=MXVMAX(N,GN) - ENDIF - IF (NF.GT.N.AND.GMAX.LE.EPS7) THEN - NCA=NF-N - NCZ=N*NF - CALL PLVLAG(NF,N,NC,ICA,CG,CG,G,CZ(NCZ+1)) - CALL MXDPRB(NCA,CR,CZ(NCZ+1),0) - CALL PLTLAG(NF,N,NC,IX,IC,ICA,CZ(NCZ+1),IC,EPS7,UMAX,IOLD) - IF (UMAX.LE.EPS7) IOLD=0 - CALL MXVSET(N,0.0D 0,GN) - GMAX=0.0D 0 - ELSE - IOLD=0 - UMAX=0.0D 0 - ENDIF - RETURN - END -* SUBROUTINE PLVLAG ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* GRADIENT OF THE OBJECTIVE FUNCTION IS PREMULTIPLIED BY TRANSPOSE -* OF THE MATRIX WHOSE COLUMNS ARE NORMALS OF CURRENT ACTIVE CONSTRAINTS -* AND GRADIENTS OF CURRENT ACTIVE FUNCTIONS. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF LINEARIZED CONSTRAINTS. -* II IAA(NF+1) VECTOR CONTAINING INDICES OF ACTIVE FUNCTIONS. -* RI AG(NF*NA) VECTOR CONTAINING SCALING PARAMETERS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RO GN(NF+1) OUTPUT VECTOR. -* -* SUBPROGRAMS USED : -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* - SUBROUTINE PLVLAG(NF,N,NC,IAA,AG,CG,G,GN) - INTEGER NF,N,NC,IAA(*) - DOUBLE PRECISION AG(*),CG(*),G(*),GN(*) - DOUBLE PRECISION MXVDOT - INTEGER NAA,J,L - NAA=NF-N - DO 1 J=1,NAA - L=IAA(J) - IF (L.GT.NC) THEN - L=L-NC - GN(J)=MXVDOT(NF,AG((L-1)*NF+1),G) - ELSE IF (L.GT.0) THEN - GN(J)=MXVDOT(NF,CG((L-1)*NF+1),G) - ELSE - L=-L - GN(J)=G(L) - ENDIF - 1 CONTINUE - RETURN - END -* SUBROUTINE PNINT1 ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* EXTRAPOLATION OR INTERPOLATION FOR LINE SEARCH WITH DIRECTIONAL -* DERIVATIVES. -* -* PARAMETERS : -* RI RL LOWER VALUE OF THE STEPSIZE PARAMETER. -* RI RU UPPER VALUE OF THE STEPSIZE PARAMETER. -* RI FL VALUE OF THE OBJECTIVE FUNCTION FOR R=RL. -* RI FU VALUE OF THE OBJECTIVE FUNCTION FOR R=RU. -* RI PL DIRECTIONAL DERIVATIVE FOR R=RL. -* RI PU DIRECTIONAL DERIVATIVE FOR R=RU. -* RO R VALUE OF THE STEPSIZE PARAMETER OBTAINED. -* II MODE MODE OF LINE SEARCH. -* II MTYP METHOD SELECTION. MTYP=1-BISECTION. MTYP=2-QUADRATIC -* INTERPOLATION (WITH ONE DIRECTIONAL DERIVATIVE). -* MTYP=3-QUADRATIC INTERPOLATION (WITH TWO DIRECTIONAL -* DERIVATIVES). MTYP=4-CUBIC INTERPOLATION. MTYP=5-CONIC -* INTERPOLATION. -* IO MERR ERROR INDICATOR. MERR=0 FOR NORMAL RETURN. -* -* METHOD : -* EXTRAPOLATION OR INTERPOLATION WITH STANDARD MODEL FUNCTIONS. -* - SUBROUTINE PNINT1(RL,RU,FL,FU,PL,PU,R,MODE,MTYP,MERR) - DOUBLE PRECISION RL, RU, FL, FU, PL, PU, R - INTEGER MODE,MTYP,MERR,NTYP - DOUBLE PRECISION A,B,C,D,DIS,DEN - DOUBLE PRECISION C1L,C1U,C2L,C2U,C3L - PARAMETER (C1L=1.1D 0,C1U=1.0D 3,C2L=1.0D-2,C2U=0.9D 0, - & C3L=0.1D 0) - MERR=0 - IF (MODE.LE.0) RETURN - IF (PL.GE.0.0D 0) THEN - MERR=2 - RETURN - ELSE IF (RU.LE.RL) THEN - MERR=3 - RETURN - ENDIF - DO 1 NTYP=MTYP,1,-1 - IF (NTYP.EQ.1) THEN -C -C BISECTION -C - IF (MODE.EQ.1) THEN - R=4.0D 0*RU - RETURN - ELSE - R=0.5D 0*(RL+RU) - RETURN - ENDIF - ELSE IF (NTYP.EQ.MTYP) THEN - A = (FU-FL)/(PL*(RU-RL)) - B = PU/PL - ENDIF - IF (NTYP.EQ.2) THEN -C -C QUADRATIC EXTRAPOLATION OR INTERPOLATION WITH ONE DIRECTIONAL -C DERIVATIVE -C - DEN = 2.0D 0*(1.0D 0-A) - ELSE IF (NTYP.EQ.3) THEN -C -C QUADRATIC EXTRAPOLATION OR INTERPOLATION WITH TWO DIRECTIONAL -C DERIVATIVES -C - DEN = 1.0D 0 - B - ELSE IF (NTYP.EQ.4) THEN -C -C CUBIC EXTRAPOLATION OR INTERPOLATION -C - C = B - 2.0D 0*A + 1.0D 0 - D = B - 3.0D 0*A + 2.0D 0 - DIS = D*D - 3.0D 0*C - IF (DIS.LT.0.0D 0) GO TO 1 - DEN = D + SQRT(DIS) - ELSE IF (NTYP.EQ.5) THEN -C -C CONIC EXTRAPOLATION OR INTERPOLATION -C - DIS = A*A - B - IF (DIS.LT.0.0D 0) GO TO 1 - DEN = A + SQRT(DIS) - IF (DEN.LE.0.0D 0) GO TO 1 - DEN = 1.0D 0 - B*(1.0D 0/DEN)**3 - ENDIF - IF (MODE.EQ.1.AND.DEN.GT.0.0D 0.AND.DEN.LT.1.0D 0) THEN -C -C EXTRAPOLATION ACCEPTED -C - R = RL + (RU-RL)/DEN - R = MAX(R,C1L*RU) - R = MIN(R,C1U*RU) - RETURN - ELSE IF (MODE.EQ.2.AND.DEN.GT.1.0D 0) THEN -C -C INTERPOLATION ACCEPTED -C - R = RL + (RU-RL)/DEN - IF (RL.EQ.0.0D 0) THEN - R = MAX(R,RL+C2L*(RU-RL)) - ELSE - R = MAX(R,RL+C3L*(RU-RL)) - ENDIF - R = MIN(R,RL+C2U*(RU-RL)) - RETURN - ENDIF - 1 CONTINUE - END -* SUBROUTINE PNINT3 ALL SYSTEMS 91/12/01 -* PORTABILITY : ALL SYSTEMS -* 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* EXTRAPOLATION OR INTERPOLATION FOR LINE SEARCH WITHOUT DIRECTIONAL -* DERIVATIVES. -* -* PARAMETERS : -* RI RO INITIAL VALUE OF THE STEPSIZE PARAMETER. -* RI RL LOWER VALUE OF THE STEPSIZE PARAMETER. -* RI RU UPPER VALUE OF THE STEPSIZE PARAMETER. -* RI RI INNER VALUE OF THE STEPSIZE PARAMETER. -* RI FO VALUE OF THE OBJECTIVE FUNCTION FOR R=RO. -* RI FL VALUE OF THE OBJECTIVE FUNCTION FOR R=RL. -* RI FU VALUE OF THE OBJECTIVE FUNCTION FOR R=RU. -* RI FI VALUE OF THE OBJECTIVE FUNCTION FOR R=RI. -* RO PO INITIAL VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO R VALUE OF THE STEPSIZE PARAMETER OBTAINED. -* II MODE MODE OF LINE SEARCH. -* II MTYP METHOD SELECTION. MTYP=1-BISECTION. MTYP=2-TWO POINT -* QUADRATIC INTERPOLATION. MTYP=2-THREE POINT QUADRATIC -* INTERPOLATION. -* IO MERR ERROR INDICATOR. MERR=0 FOR NORMAL RETURN. -* -* METHOD : -* EXTRAPOLATION OR INTERPOLATION WITH STANDARD MODEL FUNCTIONS. -* - SUBROUTINE PNINT3(RO,RL,RU,RI,FO,FL,FU,FI,PO,R,MODE,MTYP,MERR) - DOUBLE PRECISION ZERO,HALF,ONE,TWO,THREE,C1L,C1U,C2L,C2U,C3L - PARAMETER (ZERO=0.0D0,HALF=0.5D0,ONE=1.0D0,TWO=2.0D0, - + THREE=3.0D0,C1L=1.1D0,C1U=1.0D3,C2L=1.0D-2, - + C2U=0.9D0,C3L=1.0D-1) - DOUBLE PRECISION FI,FL,FO,FU,PO,R,RI,RL,RO,RU - INTEGER MERR,MODE,MTYP - DOUBLE PRECISION AI,AL,AU,DEN,DIS - INTEGER NTYP - LOGICAL L1,L2 - MERR = 0 - IF (MODE.LE.0) RETURN - IF (PO.GE.ZERO) THEN - MERR = 2 - RETURN - - ELSE IF (RU.LE.RL) THEN - MERR = 3 - RETURN - END IF - L1 = RL .LE. RO - L2 = RI .LE. RL - DO 10 NTYP = MTYP,1,-1 - IF (NTYP.EQ.1) THEN -* -* BISECTION -* - IF (MODE.EQ.1) THEN - R = TWO*RU - RETURN - ELSE IF (RI-RL.LE.RU-RI) THEN - R = HALF* (RI+RU) - RETURN - ELSE - R = HALF* (RL+RI) - RETURN - END IF - ELSE IF (NTYP.EQ.MTYP .AND. L1) THEN - IF (.NOT.L2) AI = (FI-FO)/ (RI*PO) - AU = (FU-FO)/ (RU*PO) - END IF - IF (L1 .AND. (NTYP.EQ.2.OR.L2)) THEN -* -* TWO POINT QUADRATIC EXTRAPOLATION OR INTERPOLATION -* - IF (AU.GE.ONE) GO TO 10 - R = HALF*RU/ (ONE-AU) - ELSE IF (.NOT.L1 .OR. .NOT.L2 .AND. NTYP.EQ.3) THEN -* -* THREE POINT QUADRATIC EXTRAPOLATION OR INTERPOLATION -* - AL = (FI-FL)/ (RI-RL) - AU = (FU-FI)/ (RU-RI) - DEN = AU - AL - IF (DEN.LE.ZERO) GO TO 10 - R = RI - HALF* (AU* (RI-RL)+AL* (RU-RI))/DEN - ELSE IF (L1 .AND. .NOT.L2 .AND. NTYP.EQ.4) THEN -* -* THREE POINT CUBIC EXTRAPOLATION OR INTERPOLATION -* - DIS = (AI-ONE)* (RU/RI) - DEN = (AU-ONE)* (RI/RU) - DIS - DIS = AU + AI - DEN - TWO* (ONE+DIS) - DIS = DEN*DEN - THREE*DIS - IF (DIS.LT.ZERO) GO TO 10 - DEN = DEN + SQRT(DIS) - IF (DEN.EQ.ZERO) GO TO 10 - R = (RU-RI)/DEN - ELSE - GO TO 10 - END IF - IF (MODE.EQ.1 .AND. R.GT.RU) THEN -* -* EXTRAPOLATION ACCEPTED -* - R = MAX(R,C1L*RU) - R = MIN(R,C1U*RU) - RETURN - ELSE IF (MODE.EQ.2 .AND. R.GT.RL .AND. R.LT.RU) THEN -* -* INTERPOLATION ACCEPTED -* - IF (RI.EQ.ZERO .AND. NTYP.NE.4) THEN - R = MAX(R,RL+C2L* (RU-RL)) - ELSE - R = MAX(R,RL+C3L* (RU-RL)) - END IF - R = MIN(R,RL+C2U* (RU-RL)) - IF (R.EQ.RI) GO TO 10 - RETURN - END IF - 10 CONTINUE - END -* SUBROUTINE PNSTEP ALL SYSTEMS 89/12/01 -* PORTABILITY : ALL SYSTEMS -* 89/01/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DETERMINATION OF A SCALING FACTOR FOR THE BOUNDARY STEP. -* -* PARAMETERS : -* RI DEL MAXIMUM STEPSIZE. -* RI A INPUT PARAMETER. -* RI B INPUT PARAMETER. -* RI C INPUT PARAMETER. -* RO ALF SCALING FACTOR FOR THE BOUNDARY STEP SUCH THAT -* A**2+2*B*ALF+C*ALF**2=DEL**2. -* - SUBROUTINE PNSTEP(DEL,A,B,C,ALF) - DOUBLE PRECISION DEL, A, B, C, ALF - DOUBLE PRECISION DEN, DIS - DOUBLE PRECISION ZERO - PARAMETER (ZERO = 0.0D 0) - ALF = ZERO - DEN = (DEL+A) * (DEL-A) - IF (DEN .LE. ZERO) RETURN - DIS = B*B + C*DEN - IF (B .GE. ZERO) THEN - ALF = DEN / (SQRT(DIS) + B) - ELSE - ALF = (SQRT(DIS) - B) / C - ENDIF - RETURN - END -* SUBROUTINE PP0AF8 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF VALUE OF THE AUGMENTED LAGRANGIAN FUNCTION. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II N DIMENSION OF THE CONSTRAINT NULL SPACE. -* II NC NUMBER OF CONSTRAINTS. -* RI CF(NC+1) VECTOR CONTAINING VALUES OF THE CONSTRAINTS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CZ(NC) VECTOR OF LAGRANGE MULTIPLIERS. -* RI RPF PENALTY COEFFICIENT. -* RO FC VALUE OF THE PENALTY TERM. -* RO F VALUE OF THE PENALTY FUNCTION. -* - SUBROUTINE PP0AF8(NF,N,NC,CF,IC,ICA,CL,CU,CZ,RPF,FC,F) - INTEGER NF,N,NC,IC(*),ICA(*) - DOUBLE PRECISION CF(*),CL(*),CU(*),CZ(*),RPF,FC,F - DOUBLE PRECISION POM,TEMP - INTEGER J,KC - FC=0.0D0 - DO 1 KC=1,NC - IF (IC(KC).GT.0) THEN - POM=0.0D0 - TEMP=CF(KC) - IF (IC(KC).EQ.1.OR.IC(KC).GE.3) POM=MIN(POM,TEMP-CL(KC)) - IF (IC(KC).EQ.2.OR.IC(KC).GE.3) POM=MIN(POM,CU(KC)-TEMP) - FC=FC+RPF*ABS(POM) - ENDIF - 1 CONTINUE - DO 2 J=1,NF-N - KC=ICA(J) - IF (KC.GT.0) THEN - POM=0.0D0 - TEMP=CF(KC) - IF (IC(KC).EQ.1.OR.IC(KC).EQ.3.OR.IC(KC).EQ.5) - & POM=MIN(POM,TEMP-CL(KC)) - IF (IC(KC).EQ.2.OR.IC(KC).EQ.4.OR.IC(KC).EQ.6) - & POM=MAX(POM,TEMP-CU(KC)) - FC=FC-CZ(J)*POM - ENDIF - 2 CONTINUE - F=CF(NC+1)+FC - RETURN - END -* SUBROUTINE PPSET2 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* COMPUTATION OF THE NEW PENALTY PARAMETERS. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CZ(NF) VECTOR OF LAGRANGE MULTIPLIERS. -* RI CP(NC) VECTOR CONTAINING PENALTY PARAMETERS. -* - SUBROUTINE PPSET2(NF,N,NC,ICA,CZ,CP) - INTEGER NF,N,NC,ICA(*) - DOUBLE PRECISION CZ(*),CP(*) - DOUBLE PRECISION TEMP - INTEGER J,L,KC - DO 1 KC=1,NC - CP(KC)=0.5D 0*CP(KC) - 1 CONTINUE - DO 2 J=1,NF-N - L=ICA(J) - IF (L.GT.0) THEN - TEMP=ABS(CZ(J)) - CP(L)=MAX(TEMP,CP(L)+0.5D 0*TEMP) - ENDIF - 2 CONTINUE - RETURN - END -* SUBROUTINE PS0G01 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SIMPLE SEARCH WITH TRUST REGION UPDATE. -* -* PARAMETERS : -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* RI FO INITIAL VALUE OF THE OBJECTIVE FUNCTION. -* RI PO INITIAL VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI PP QUADRATIC PART OF THE PREDICTED FUNCTION VALUE. -* RU XDEL TRUST REGION BOUND. -* RO XDELO PREVIOUS TRUST REGION BOUND. -* RI XMAX MAXIMUM STEPSIZE. -* RI RMAX MAXIMUM VALUE OF THE STEPSIZE PARAMETER. -* RI SNORM EUCLIDEAN NORM OF THE DIRECTION VECTOR. -* RI BET1 LOWER BOUND FOR STEPSIZE REDUCTION. -* RI BET2 UPPER BOUND FOR STEPSIZE REDUCTION. -* RI GAM1 LOWER BOUND FOR STEPSIZE EXPANSION. -* RI GAM2 UPPER BOUND FOR STEPSIZE EXPANSION. -* RI EPS4 FIRST TOLERANCE FOR RATIO DF/DFPRED. STEP BOUND IS -* DECREASED IF DF/DFPREDEPS5. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* IU IDIR INDICATOR FOR DIRECTION DETERMINATION. -* IDIR=0-BASIC DETERMINATION. IDIR=1-DETERMINATION -* AFTER STEPSIZE REDUCTION. IDIR=2-DETERMINATION AFTER -* STEPSIZE EXPANSION. -* IO ITERS TERMINATION INDICATOR. ITERS=0-ZERO STEP. ITERS=1-STEP -* BOUND WAS DECREASED. ITERS=2-STEP BOUND WAS UNCHANGED. -* ITERS=3-STEP BOUND WAS INCREASED. ITERS=6-FIRST STEPSIZE. -* II ITERD TERMINATION INDICATOR. ITERD<0-BAD DECOMPOSITION. -* ITERD=0-DESCENT DIRECTION. ITERD=1-NEWTON LIKE STEP. -* ITERD=2-INEXACT NEWTON LIKE STEP. ITERD=3-BOUNDARY STEP. -* ITERD=4-DIRECTION WITH THE NEGATIVE CURVATURE. -* ITERD=5-MARQUARDT STEP. -* IO MAXST MAXIMUM STEPSIZE INDICATOR. MAXST=0 OR MAXST=1 IF MAXIMUM -* STEPSIZE WAS NOT OR WAS REACHED. -* IO NRED ACTUAL NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* II MRED MAXIMUM NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* II KTERS TERMINATION SELECTION. KTERS=1-NORMAL TERMINATION. -* KTERS=6-FIRST STEPSIZE. -* II MES1 SWITCH FOR EXTRAPOLATION. MES1=1-CONSTANT INCREASING OF -* THE INTERVAL. MES1=2-EXTRAPOLATION SPECIFIED BY THE PARAMETER -* MES. MES1=3 SUPPRESSED EXTRAPOLATION. -* II MES2 SWITCH FOR TERMINATION. MES2=1-NORMAL TERMINATION. -* MES2=2-TERMINATION AFTER AT LEAST TWO STEPS (ASYMPTOTICALLY -* PERFECT LINE SEARCH). -* II MES3 SAFEGUARD AGAINST ROUNDING ERRORS. MES3=0-SAFEGUARD -* SUPPRESSED. MES3=1-FIRST LEVEL OF SAFEGUARD. MES3=2-SECOND -* LEVEL OF SAFEGUARD. -* IU ISYS CONTROL PARAMETER. -* -* COMMON DATA : -* -* METHOD : -* G.A.SCHULTZ, R.B.SCHNABEL, R.H.BYRD: A FAMILY OF TRUST-REGION-BASED -* ALGORITHMS FOR UNCONSTRAINED MINIMIZATION WITH STRONG GLOBAL -* CONVERGENCE PROPERTIES, SIAM J. NUMER.ANAL. 22 (1985) PP. 47-67. -* - SUBROUTINE PS0G01(R,F,FO,PO,PP,XDEL,XDELO,XMAX,RMAX,SNORM, - & BET1,BET2,GAM1,GAM2,EPS4,EPS5,KD,LD,IDIR,ITERS,ITERD, - & MAXST,NRED,MRED,KTERS,MES1,MES2,MES3,ISYS) - INTEGER KD,LD,IDIR,ITERS,ITERD,MAXST,NRED,MRED,KTERS, - & MES1,MES2,MES3,ISYS - DOUBLE PRECISION R,F,FO,PO,PP,XDEL,XDELO,XMAX,RMAX,SNORM,BET1, - & BET2,GAM1,GAM2,EPS4,EPS5 - DOUBLE PRECISION DF,DFPRED - INTEGER NRED1,NRED2 - SAVE NRED1,NRED2 - IF (ISYS.EQ.1) GO TO 2 -C GO TO (1,2) ISYS+1 - 1 CONTINUE - IF (IDIR.EQ.0) THEN - NRED1=0 - NRED2=0 - ENDIF - IDIR=0 - XDELO=XDEL -C -C COMPUTATION OF THE NEW FUNCTION VALUE -C - R=MIN(1.0D 0,RMAX) - KD= 0 - LD=-1 - ISYS=1 - RETURN - 2 CONTINUE - IF(KTERS.LT.0.OR.KTERS.GT.5) THEN - ITERS=6 - ELSE - DF=FO-F - DFPRED=-R*(PO+R*PP) - IF (DF.LT.EPS4*DFPRED) THEN -C -C STEP IS TOO LARGE, IT HAS TO BE REDUCED -C - IF (MES1.EQ.1) THEN - XDEL=BET2*SNORM - ELSE IF (MES1.EQ.2) THEN - XDEL=BET2*MIN(0.5D 0*XDEL,SNORM) - ELSE - XDEL=0.5D 0*PO*SNORM/(PO+DF) - XDEL=MAX(XDEL,BET1*SNORM) - XDEL=MIN(XDEL,BET2*SNORM) - ENDIF - ITERS=1 - IF (MES3.LE.1) THEN - NRED2=NRED2+1 - ELSE - IF (ITERD.GT.2) NRED2=NRED2+1 - ENDIF - ELSE IF (DF.LE.EPS5*DFPRED) THEN -C -C STEP IS SUITABLE -C - ITERS=2 - ELSE -C -C STEP IS TOO SMALL, IT HAS TO BE ENLARGED -C - IF (MES2.EQ.2) THEN - XDEL=MAX(XDEL,GAM1*SNORM) - ELSE IF (ITERD.GT.2) THEN - XDEL=GAM1*XDEL - ENDIF - ITERS=3 - ENDIF - XDEL=MIN(XDEL,XMAX,GAM2*SNORM) - IF (FO.LE.F) THEN - IF (NRED1.GE.MRED) THEN - ITERS=-1 - ELSE - IDIR=1 - ITERS=0 - NRED1=NRED1+1 - ENDIF - ENDIF - ENDIF - MAXST=0 - IF (XDEL.GE.XMAX) MAXST=1 - IF (MES3.EQ.0) THEN - NRED=NRED1 - ELSE - NRED=NRED2 - ENDIF - ISYS=0 - RETURN - END -* SUBROUTINE PS0L02 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* EXTENDED LINE SEARCH WITHOUT DIRECTIONAL DERIVATIVES. -* -* PARAMETERS : -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RO RO INITIAL VALUE OF THE STEPSIZE PARAMETER. -* RO RP PREVIOUS VALUE OF THE STEPSIZE PARAMETER. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* RI FO INITIAL VALUE OF THE OBJECTIVE FUNCTION. -* RO FP PREVIOUS VALUE OF THE OBJECTIVE FUNCTION. -* RI PO INITIAL VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO PP PREVIOUS VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI FMIN LOWER BOUND FOR VALUE OF THE OBJECTIVE FUNCTION. -* RI FMAX UPPER BOUND FOR VALUE OF THE OBJECTIVE FUNCTION. -* RI RMIN MINIMUM VALUE OF THE STEPSIZE PARAMETER -* RI RMAX MAXIMUM VALUE OF THE STEPSIZE PARAMETER -* RI TOLS TERMINATION TOLERANCE FOR LINE SEARCH (IN TEST ON THE -* CHANGE OF THE FUNCTION VALUE). -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* II NIT ACTUAL NUMBER OF ITERATIONS. -* II KIT NUMBER OF THE ITERATION AFTER LAST RESTART. -* IO NRED ACTUAL NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* II MRED MAXIMUM NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* IO MAXST MAXIMUM STEPSIZE INDICATOR. MAXST=0 OR MAXST=1 IF MAXIMUM -* STEPSIZE WAS NOT OR WAS REACHED. -* II IEST LOWER BOUND SPECIFICATION. IEST=0 OR IEST=1 IF LOWER BOUND -* IS NOT OR IS GIVEN. -* II INITS CHOICE OF THE INITIAL STEPSIZE. INITS=0-INITIAL STEPSIZE -* IS SPECIFIED IN THE CALLING PROGRAM. INITS=1-UNIT INITIAL -* STEPSIZE. INITS=2-COMBINED UNIT AND QUADRATICALLY ESTIMATED -* INITIAL STEPSIZE. INITS=3-QUADRATICALLY ESTIMATED INITIAL -* STEPSIZE. -* IO ITERS TERMINATION INDICATOR. ITERS=0-ZERO STEP. ITERS=1-PERFECT -* LINE SEARCH. ITERS=2 GOLDSTEIN STEPSIZE. ITERS=3-CURRY -* STEPSIZE. ITERS=4-EXTENDED CURRY STEPSIZE. -* ITERS=5-ARMIJO STEPSIZE. ITERS=6-FIRST STEPSIZE. -* ITERS=7-MAXIMUM STEPSIZE. ITERS=8-UNBOUNDED FUNCTION. -* ITERS=-1-MRED REACHED. ITERS=-2-POSITIVE DIRECTIONAL -* DERIVATIVE. ITERS=-3-ERROR IN INTERPOLATION. -* II KTERS TERMINATION SELECTION. KTERS=1-PERFECT LINE SEARCH. -* KTERS=2-GOLDSTEIN STEPSIZE. KTERS=3-CURRY STEPSIZE. -* KTERS=4-EXTENDED CURRY STEPSIZE. KTERS=5-ARMIJO STEPSIZE. -* KTERS=6-FIRST STEPSIZE. -* II MES METHOD SELECTION. MES=1-BISECTION. MES=2-QUADRATIC -* INTERPOLATION (WITH ONE DIRECTIONAL DERIVATIVE). -* MES=3-QUADRATIC INTERPOLATION (WITH TWO DIRECTIONAL -* DERIVATIVES). MES=4-CUBIC INTERPOLATION. MES=5-CONIC -* INTERPOLATION. -* IU ISYS CONTROL PARAMETER. -* -* SUBPROGRAM USED : -* S PNINT3 EXTRAPOLATION OR INTERPOLATION WITHOUT DIRECTIONAL -* DERIVATIVES. -* -* METHOD : -* SAFEGUARDED EXTRAPOLATION AND INTERPOLATION WITH EXTENDED TERMINATION -* CRITERIA. -* - SUBROUTINE PS0L02(R,RO,RP,F,FO,FP,PO,PP,FMIN,FMAX,RMIN,RMAX, - & TOLS,KD,LD,NIT,KIT,NRED,MRED,MAXST,IEST,INITS,ITERS,KTERS, - & MES,ISYS) - INTEGER KD,LD,NIT,KIT,NRED,MRED,MAXST,IEST,INITS,ITERS,KTERS, - & MES,ISYS - DOUBLE PRECISION R,RO,RP,F,FO,FP,PO,PP,FMIN,FMAX,RMIN,RMAX,TOLS - DOUBLE PRECISION RL,FL,RU,FU,RI,FI,RTEMP,TOL - INTEGER MTYP,MERR,MODE,INIT1,MES1,MES2 - LOGICAL L1,L2,L3,L4,L6,L7 - PARAMETER(TOL=1.0D-4) - SAVE MTYP,MODE,MES1,MES2 - SAVE RL,FL,RU,FU,RI,FI - IF (ISYS.EQ.1) GO TO 3 -C GO TO (1,3) ISYS+1 - 1 CONTINUE - MES1=2 - MES2=2 - ITERS=0 - IF (PO.GE.0.0D 0) THEN - R=0.0D 0 - ITERS=-2 - GO TO 4 - ENDIF - IF(RMAX.LE.0.0D 0) THEN - ITERS= 0 - GO TO 4 - ENDIF -C -C INITIAL STEPSIZE SELECTION -C - IF (INITS.GT.0) THEN - RTEMP=FMIN-F - ELSE IF (IEST.EQ.0) THEN - RTEMP=F-FP - ELSE - RTEMP=MAX(F-FP,1.0D 1*(FMIN-F)) - ENDIF - INIT1=ABS(INITS) - RP=0.0D 0 - FP=FO - PP=PO - IF (INIT1.EQ.0) THEN - ELSE IF (INIT1.EQ.1.OR.INITS.GE.1.AND.IEST.EQ.0) THEN - R=1.0D 0 - ELSE IF (INIT1.EQ.2) THEN - R=MIN(1.0D 0,4.0D 0*RTEMP/PO) - ELSE IF (INIT1.EQ.3) THEN - R=MIN(1.0D 0, 2.0D 0*RTEMP/PO) - ELSE IF (INIT1.EQ.4) THEN - R=2.0D 0*RTEMP/PO - ENDIF - RTEMP=R - R=MAX(R,RMIN) - R=MIN(R,RMAX) - MODE=0 - RL=0.0D 0 - FL=FO - RU=0.0D 0 - FU=FO - RI=0.0D 0 - FI=FO -C -C NEW STEPSIZE SELECTION (EXTRAPOLATION OR INTERPOLATION) -C - 2 CALL PNINT3(RO,RL,RU,RI,FO,FL,FU,FI,PO,R,MODE,MTYP,MERR) - IF (MERR.GT.0) THEN - ITERS=-MERR - GO TO 4 - ELSE IF (MODE.EQ.1) THEN - NRED=NRED-1 - R=MIN(R,RMAX) - ELSE IF (MODE.EQ.2) THEN - NRED=NRED+1 - ENDIF -C -C COMPUTATION OF THE NEW FUNCTION VALUE -C - KD= 0 - LD=-1 - ISYS=1 - RETURN - 3 CONTINUE - IF (ITERS.NE.0) GO TO 4 - IF (F.LE.FMIN) THEN - ITERS=7 - GO TO 4 - ELSE - L1=R.LE.RMIN.AND.NIT.NE.KIT - L2=R.GE.RMAX - L3=F-FO.LE.TOLS*R*PO.OR.F-FMIN.LE.(FO-FMIN)/1.0D 1 - L4=F-FO.GE.(1.0D 0-TOLS)*R*PO.OR.MES2.EQ.2.AND.MODE.EQ.2 - L6=RU-RL.LE.TOL*RU.AND.MODE.EQ.2 - L7=MES2.LE.2.OR.MODE.NE.0 - MAXST=0 - IF (L2) MAXST=1 - ENDIF -C -C TEST ON TERMINATION -C - IF (L1.AND..NOT.L3) THEN - ITERS=0 - GO TO 4 - ELSE IF (L2.AND..NOT.F.GE.FU) THEN - ITERS=7 - GO TO 4 - ELSE IF (L6) THEN - ITERS=1 - GO TO 4 - ELSE IF (L3.AND.L7.AND.KTERS.EQ.5) THEN - ITERS=5 - GO TO 4 - ELSE IF (L3.AND.L4.AND.L7.AND.(KTERS.EQ.2.OR.KTERS.EQ.3.OR. - * KTERS.EQ.4)) THEN - ITERS=2 - GO TO 4 - ELSE IF (KTERS.LT.0.OR.KTERS.EQ.6.AND.L7) THEN - ITERS=6 - GO TO 4 - ELSE IF(ABS(NRED).GE.MRED) THEN - ITERS=-1 - GO TO 4 - ELSE - RP=R - FP=F - MODE=MAX(MODE,1) - MTYP=ABS(MES) - IF(F.GE.FMAX) MTYP=1 - ENDIF - IF (MODE.EQ.1) THEN -C -C INTERVAL CHANGE AFTER EXTRAPOLATION -C - RL=RI - FL=FI - RI=RU - FI=FU - RU=R - FU=F - IF (F.GE.FI) THEN - NRED=0 - MODE=2 - ELSE IF ( MES1 .EQ. 1) THEN - MTYP=1 - ENDIF -C -C INTERVAL CHANGE AFTER INTERPOLATION -C - ELSE IF (R.LE.RI) THEN - IF (F.LE.FI) THEN - RU=RI - FU=FI - RI=R - FI=F - ELSE - RL=R - FL=F - ENDIF - ELSE - IF (F.LE.FI) THEN - RL=RI - FL=FI - RI=R - FI=F - ELSE - RU=R - FU=F - ENDIF - ENDIF - GO TO 2 - 4 ISYS=0 - RETURN - END -* SUBROUTINE PS1L01 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* STANDARD LINE SEARCH WITH DIRECTIONAL DERIVATIVES. -* -* PARAMETERS : -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RO RP PREVIOUS VALUE OF THE STEPSIZE PARAMETER. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* RI FO INITIAL VALUE OF THE OBJECTIVE FUNCTION. -* RO FP PREVIOUS VALUE OF THE OBJECTIVE FUNCTION. -* RO P VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI PO INITIAL VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO PP PREVIOUS VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI FMIN LOWER BOUND FOR VALUE OF THE OBJECTIVE FUNCTION. -* RI FMAX UPPER BOUND FOR VALUE OF THE OBJECTIVE FUNCTION. -* RI RMIN MINIMUM VALUE OF THE STEPSIZE PARAMETER -* RI RMAX MAXIMUM VALUE OF THE STEPSIZE PARAMETER -* RI TOLS TERMINATION TOLERANCE FOR LINE SEARCH (IN TEST ON THE -* CHANGE OF THE FUNCTION VALUE). -* RI TOLP TERMINATION TOLERANCE FOR LINE SEARCH (IN TEST ON THE -* CHANGE OF THE DIRECTIONAL DERIVATIVE). -* RO PAR1 PARAMETER FOR CONTROLLED SCALING OF VARIABLE METRIC -* UPDATES. -* RO PAR2 PARAMETER FOR CONTROLLED SCALING OF VARIABLE METRIC -* UPDATES. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* II NIT ACTUAL NUMBER OF ITERATIONS. -* II KIT NUMBER OF THE ITERATION AFTER LAST RESTART. -* IO NRED ACTUAL NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* II MRED MAXIMUM NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* IO MAXST MAXIMUM STEPSIZE INDICATOR. MAXST=0 OR MAXST=1 IF MAXIMUM -* STEPSIZE WAS NOT OR WAS REACHED. -* II IEST LOWER BOUND SPECIFICATION. IEST=0 OR IEST=1 IF LOWER BOUND -* IS NOT OR IS GIVEN. -* II INITS CHOICE OF THE INITIAL STEPSIZE. INITS=0-INITIAL STEPSIZE -* IS SPECIFIED IN THE CALLING PROGRAM. INITS=1-UNIT INITIAL -* STEPSIZE. INITS=2-COMBINED UNIT AND QUADRATICALLY ESTIMATED -* INITIAL STEPSIZE. INITS=3-QUADRATICALLY ESTIMATED INITIAL -* STEPSIZE. -* IO ITERS TERMINATION INDICATOR. ITERS=0-ZERO STEP. ITERS=1-PERFECT -* LINE SEARCH. ITERS=2 GOLDSTEIN STEPSIZE. ITERS=3-CURRY -* STEPSIZE. ITERS=4-EXTENDED CURRY STEPSIZE. -* ITERS=5-ARMIJO STEPSIZE. ITERS=6-FIRST STEPSIZE. -* ITERS=7-MAXIMUM STEPSIZE. ITERS=8-UNBOUNDED FUNCTION. -* ITERS=-1-MRED REACHED. ITERS=-2-POSITIVE DIRECTIONAL -* DERIVATIVE. ITERS=-3-ERROR IN INTERPOLATION. -* II KTERS TERMINATION SELECTION. KTERS=1-PERFECT LINE SEARCH. -* KTERS=2-GOLDSTEIN STEPSIZE. KTERS=3-CURRY STEPSIZE. -* KTERS=4-EXTENDED CURRY STEPSIZE. KTERS=5-ARMIJO STEPSIZE. -* KTERS=6-FIRST STEPSIZE. -* II MES METHOD SELECTION. MES=1-BISECTION. MES=2-QUADRATIC -* INTERPOLATION (WITH ONE DIRECTIONAL DERIVATIVE). -* MES=3-QUADRATIC INTERPOLATION (WITH TWO DIRECTIONAL -* DERIVATIVES). MES=4-CUBIC INTERPOLATION. MES=5-CONIC -* INTERPOLATION. -* IU ISYS CONTROL PARAMETER. -* -* SUBPROGRAM USED : -* S PNINT1 EXTRAPOLATION OR INTERPOLATION WITH DIRECTIONAL -* DERIVATIVES. -* -* METHOD : -* SAFEGUARDED EXTRAPOLATION AND INTERPOLATION WITH STANDARD TERMINATION -* CRITERIA. -* - SUBROUTINE PS1L01(R,RP,F,FO,FP,P,PO,PP,FMIN,FMAX,RMIN,RMAX, - & TOLS,TOLP,PAR1,PAR2,KD,LD,NIT,KIT,NRED,MRED,MAXST,IEST,INITS, - & ITERS,KTERS,MES,ISYS) - INTEGER KD,LD,NIT,KIT,NRED,MRED,MAXST,IEST,INITS,ITERS,KTERS, - & MES,ISYS - DOUBLE PRECISION R,RP,F,FO,FP,P,PO,PP,FMIN,FMAX,RMIN,RMAX, - & TOLS,TOLP,PAR1,PAR2 - DOUBLE PRECISION RL,FL,PL,RU,FU,PU,RTEMP - INTEGER MTYP,MERR,MODE,INIT1,MES1,MES2,MES3 - LOGICAL L1,L2,L3,L5,L7,M1,M2,M3 - DOUBLE PRECISION CON,CON1 - PARAMETER (CON=1.0D-2,CON1=1.0D-13) - SAVE MTYP,MODE,MES1,MES2,MES3 - SAVE RL,FL,PL,RU,FU,PU - IF (ISYS.EQ.1) GO TO 3 -C GO TO (1,3) ISYS+1 - 1 CONTINUE - MES1=2 - MES2=2 - MES3=2 - ITERS=0 - IF (PO.GE.0.0D 0) THEN - R=0.0D 0 - ITERS=-2 - GO TO 4 - ENDIF - IF(RMAX.LE.0.0D 0) THEN - ITERS=0 - GO TO 4 - ENDIF -C -C INITIAL STEPSIZE SELECTION -C - IF (INITS.GT.0) THEN - RTEMP=FMIN-F - ELSE IF (IEST.EQ.0) THEN - RTEMP=F-FP - ELSE - RTEMP=MAX(F-FP,1.0D 1*(FMIN-F)) - ENDIF - INIT1=ABS(INITS) - RP=0.0D 0 - FP=FO - PP=PO - IF (INIT1.EQ.0) THEN - ELSE IF (INIT1.EQ.1.OR.INITS.GE.1.AND.IEST.EQ.0) THEN - R=1.0D 0 - ELSE IF (INIT1.EQ.2) THEN - R=MIN(1.0D 0,4.0D 0*RTEMP/PO) - ELSE IF (INIT1.EQ.3) THEN - R=MIN(1.0D 0, 2.0D 0*RTEMP/PO) - ELSE IF (INIT1.EQ.4) THEN - R=2.0D 0*RTEMP/PO - ENDIF - R=MAX(R,RMIN) - R=MIN(R,RMAX) - MODE=0 - RU=0.0D 0 - FU=FO - PU=PO -C -C NEW STEPSIZE SELECTION (EXTRAPOLATION OR INTERPOLATION) -C - 2 CALL PNINT1(RL,RU,FL,FU,PL,PU,R,MODE,MTYP,MERR) - IF (MERR.GT.0) THEN - ITERS=-MERR - GO TO 4 - ELSE IF (MODE.EQ.1) THEN - NRED=NRED-1 - R=MIN(R,RMAX) - ELSE IF (MODE.EQ.2) THEN - NRED=NRED+1 - ENDIF -C -C COMPUTATION OF THE NEW FUNCTION VALUE AND THE NEW DIRECTIONAL -C DERIVATIVE -C - KD= 1 - LD=-1 - ISYS=1 - RETURN - 3 CONTINUE - IF (MODE.EQ.0) THEN - PAR1=P/PO - PAR2=F-FO - ENDIF - IF (ITERS.NE.0) GO TO 4 - IF (F.LE.FMIN) THEN - ITERS=7 - GO TO 4 - ELSE - L1=R.LE.RMIN.AND.NIT.NE.KIT - L2=R.GE.RMAX - L3=F-FO.LE.TOLS*R*PO - L5=P.GE.TOLP*PO.OR.MES2.EQ.2.AND.MODE.EQ.2 - L7=MES2.LE.2.OR.MODE.NE.0 - M1=.FALSE. - M2=.FALSE. - M3=L3 - IF(MES3.GE.1) THEN - M1=ABS(P).LE.CON*ABS(PO).AND.FO-F.GE.(CON1/CON)*ABS(FO) - L3=L3.OR.M1 - ENDIF - IF(MES3.GE.2) THEN - M2=ABS(P).LE.0.5D 0*ABS(PO).AND.ABS(FO-F).LE.2.0D 0*CON1*ABS(FO) - L3=L3.OR.M2 - ENDIF - MAXST=0 - IF (L2) MAXST=1 - ENDIF -C -C TEST ON TERMINATION -C - IF (L1.AND..NOT.L3) THEN - ITERS=0 - GO TO 4 - ELSE IF (L2.AND.L3.AND..NOT.L5) THEN - ITERS=7 - GO TO 4 - ELSE IF (M3.AND.MES1.EQ.3) THEN - ITERS=5 - GO TO 4 - ELSE IF (L3.AND.L5.AND.L7) THEN - ITERS=4 - GO TO 4 - ELSE IF (KTERS.LT.0.OR.KTERS.EQ.6.AND.L7) THEN - ITERS=6 - GO TO 4 - ELSE IF (ABS(NRED).GE.MRED) THEN - ITERS=-1 - GO TO 4 - ELSE - RP=R - FP=F - PP=P - MODE=MAX(MODE,1) - MTYP=ABS(MES) - IF(F.GE.FMAX) MTYP=1 - ENDIF - IF (MODE.EQ.1) THEN -C -C INTERVAL CHANGE AFTER EXTRAPOLATION -C - RL=RU - FL=FU - PL=PU - RU=R - FU=F - PU=P - IF (.NOT.L3) THEN - NRED=0 - MODE=2 - ELSE IF ( MES1 .EQ. 1) THEN - MTYP=1 - ENDIF - ELSE -C -C INTERVAL CHANGE AFTER INTERPOLATION -C - IF (.NOT.L3) THEN - RU=R - FU=F - PU=P - ELSE - RL=R - FL=F - PL=P - ENDIF - ENDIF - GO TO 2 - 4 ISYS=0 - RETURN - END -* SUBROUTINE PUDBG1 ALL SYSTEMS 92/12/01 -* PORTABILITY : ALL SYSTEMS -* 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VARIABLE METRIC UPDATE OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX -* USING THE FACTORIZATION B=L*D*TRANS(L). -* -* PARAMETERS : -* II N ACTUAL NUMBER OF VARIABLES. -* RU H(M) FACTORIZATION B=L*D*TRANS(L) OF A POSITIVE -* DEFINITE APPROXIMATION OF THE HESSIAN MATRIX. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RA S(NF) AUXILIARY VECTOR. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI GO(NF) GRADIENTS DIFFERENCE. -* RI R VALUE OF THE STEPSIZE PARAMETER. -* RI PO OLD VALUE OF THE DIRECTIONAL DERIVATIVE. -* II NIT ACTUAL NUMBER OF ITERATIONS. -* II KIT NUMBER OF THE ITERATION AFTER LAST RESTART. -* IO ITERH TERMINATION INDICATOR. ITERH<0-BAD DECOMPOSITION. -* ITERH=0-SUCCESSFUL UPDATE. ITERH>0-NONPOSITIVE PARAMETERS. -* II MET1 SELECTION OF SELF SCALING. MET1=1-SELF SCALING SUPPRESSED. -* MET1=2 INITIAL SELF SCALING. -* II MEC CORRECTION IF THE NEGATIVE CURVATURE OCCURS. -* MEC=1-CORRECTION SUPPRESSED. MEC=2-POWELL'S CORRECTION. -* -* SUBPROGRAMS USED : -* S MXDPGU CORRECTION OF A DENSE SYMMETRIC POSITIVE DEFINITE -* MATRIX IN THE FACTORED FORM B=L*D*TRANS(L). -* S MXDPGS SCALING OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX -* IN THE FACTORED FORM B=L*D*TRANS(L). -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* RF MXVDOT DOT PRODUCT OF VECTORS. -* S MXVSCL SCALING OF A VECTOR. -* -* METHOD : -* BFGS VARIABLE METRIC METHOD. -* - SUBROUTINE PUDBG1(N,H,G,S,XO,GO,R,PO,NIT,KIT,ITERH,MET,MET1,MEC) - DOUBLE PRECISION PO,R - INTEGER ITERH,KIT,MET,MET1,MEC,N,NIT - DOUBLE PRECISION G(*),GO(*),H(*),S(*),XO(*) - DOUBLE PRECISION A,B,C,GAM,PAR,DEN,DIS - LOGICAL L1,L3 - DOUBLE PRECISION MXVDOT,MXDPGP - L1 = MET1 .GE. 3 .OR. MET1 .EQ. 2 .AND. NIT .EQ. KIT - L3 = .NOT. L1 -* -* DETERMINATION OF THE PARAMETERS B, C -* - B = MXVDOT(N,XO,GO) - A = 0.0D0 - IF (L1) THEN - CALL MXVCOP(N,GO,S) - CALL MXDPGB(N,H,S,1) - A=MXDPGP(N,H,S,S) - IF (A.LE.0.0D0) THEN - ITERH=1 - RETURN - END IF - END IF - CALL MXVDIF(N,GO,G,S) - CALL MXVSCL(N,R,S,S) - C = -R*PO - IF (C.LE.0.0D0) THEN - ITERH = 3 - RETURN - END IF - IF (MEC.GT.1) THEN - IF (B.LE.1.0D-4*C) THEN -* -* POWELL'S CORRECTION -* - DIS=(1.0D0-0.1D0)*C/(C-B) - CALL MXVDIF(N,GO,S,GO) - CALL MXVDIR(N,DIS,GO,S,GO) - B=C+DIS*(B-C) - IF (L1) A=C+2.0D0*(1.0D0-DIS)*(B-C)+DIS*DIS*(A-C) - ENDIF - ELSE - IF (B.LE.1.0D-4*C) THEN - ITERH = 2 - RETURN - ENDIF - ENDIF - IF (L1) THEN -* -* DETERMINATION OF THE PARAMETER GAM (SELF SCALING) -* - IF (MET.EQ.1) THEN - PAR = C/B - ELSE IF (A.LE.0.0D 0) THEN - PAR = C/B - ELSE - PAR=SQRT(C/A) - ENDIF - GAM = PAR - IF (MET1.GT.1) THEN - IF (NIT.NE.KIT) THEN - L3=GAM.LT.0.5D0.OR.GAM.GT.4.0D0 - ENDIF - ENDIF - ENDIF - IF (L3) THEN - GAM = 1.0D0 - PAR = GAM - END IF - IF (MET.EQ.1) THEN -* -* BFGS UPDATE -* - CALL MXDPGU(N,H,PAR/B,GO,XO) - CALL MXDPGU(N,H,-1.0D0/C,S,XO) - ELSE -* -* HOSHINO UPDATE -* - DEN=PAR*B+C - DIS=0.5D0*B - CALL MXVDIR(N,PAR,GO,S,S) - CALL MXDPGU(N,H,PAR/DIS,GO,XO) - CALL MXDPGU(N,H,-1.0D0/DEN,S,XO) - ENDIF - ITERH = 0 - IF (GAM.EQ.1.0D0) RETURN - CALL MXDPGS(N,H,1.0D0/GAM) - RETURN - END -* SUBROUTINE PUDBI1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VARIABLE METRIC UPDATES. -* -* PARAMETERS : -* II N NUMBER OF VARIABLES. -* RU H(N*(N+1)/2) UPDATED APPROXIMATION OF THE INVERSE HESSIAN -* MATRIX. -* RA S(N) AUXILIARY VECTOR. -* RI XO(N) VECTOR OF VARIABLES DIFFERENCE. -* RI GO(N) GRADIENT DIFFERENCE. -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RI PO INITIAL VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO PAR1 PARAMETER FOR CONTROL SCALING. -* RO PAR2 PARAMETER FOR CONTROL SCALING. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* RI FO INITIAL VALUE OF THE OBJECTIVE FUNCTION. -* RI P CURRENT VALUE OF THE DIRECTIONAL DERIVATIVE. -* II NIT NUMBER OF ITERATIONS. -* II KIT INDEX OF THE ITERATION WITH THE LAST RESTART. -* II MET VARIABLE METRIC UPDATE. -* II MET1 SCALING STRATEGY. -* II MET2 CORRECTION RULE. -* IU IDECF DECOMPOSITION INDICATOR. -* II ITERD TERMINATION INDICATOR. ITERD<0-BAD DECOMPOSITION. -* ITERD=0-DESCENT DIRECTION. ITERD=1-NEWTON LIKE STEP. -* ITERD=2-INEXACT NEWTON LIKE STEP. ITERD=3-BOUNDARY STEP. -* ITERD=4-DIRECTION WITH THE NEGATIVE CURVATURE. -* ITERD=5-MARQUARDT STEP. -* IO ITERH UPDATE INDICATOR. ITERH=0-SUCCESSFUL UPDATE. -* ITERH>0-UNSUCCESSFUL UPDATE. -* -* METHOD : -* VARIOUS VARIABLE METRIC UPDATES INCLUDING BFGS UPDATE. -* - SUBROUTINE PUDBI1(N,H,S,XO,GO,R,PO,PAR1,PAR2,F,FO,P,NIT,KIT, - & MET,MET1,MET2,IDECF,ITERD,ITERH) - INTEGER N,NIT,KIT,MET,MET1,MET2,IDECF,ITERD,ITERH - DOUBLE PRECISION H(*),S(*),XO(*),GO(*),R,PO - DOUBLE PRECISION PAR1,PAR2 - DOUBLE PRECISION F,FO,P - DOUBLE PRECISION AA,CC - DOUBLE PRECISION MXVDOT - DOUBLE PRECISION DIS,POM,POM3,POM4,A,B,C,GAM,RHO,PAR - DOUBLE PRECISION DEN - LOGICAL L1,L2,L3 - IF (MET.LE.0) GO TO 22 - IF (IDECF.NE.9) THEN - ITERH=-1 - GO TO 22 - ENDIF - L1=ABS(MET1).GE.3.OR.ABS(MET1).EQ.2.AND.NIT.EQ.KIT - L3=.NOT.L1 -* -* DETERMINATION OF THE PARAMETERS A, B, C -* - B=MXVDOT(N,XO,GO) - IF (B.LE.0.0D 0) THEN - ITERH=2 - GO TO 22 - ENDIF - CALL MXDSMM(N,H,GO,S) - A=MXVDOT(N,GO,S) - IF (A.LE.0.0D 0) THEN - ITERH=1 - GO TO 22 - ENDIF - IF(MET.NE.1.OR.L1) THEN - IF (ITERD.NE.1) THEN - C=0.0D 0 - ELSE - C=-R*PO - IF (C.LE.0.0D 0) THEN - ITERH=3 - GO TO 22 - ENDIF - ENDIF - ELSE - C=0.0D 0 - ENDIF -* -* DETERMINATION OF THE PARAMETER RHO (NONQUADRATIC PROPERTIES) -* - IF (MET2.EQ.1) THEN - RHO=1.0D 0 - ELSE IF (FO-F+P.EQ.0) THEN - RHO=1.0D 0 - ELSE - RHO=0.5D 0*B/(FO-F+P) - ENDIF - IF(RHO.LE.1.0D-2) RHO=1.0D 0 - IF(RHO.GE.1.0D 2) RHO=1.0D 0 - AA=A/B - CC=C/B - IF (L1) THEN -* -* DETERMINATION OF THE PARAMETER GAM (SELF SCALING) -* - PAR=A/B - POM3=0.7D 0 - POM4=6.0D 0 - GAM=RHO/PAR - IF (NIT.NE.KIT) THEN - IF (MET1.EQ.3) THEN - L2=PAR2.LE.0.0D 0 - L3=L2.AND.ABS(PAR1).LE.0.2D 0 - L3=L3.OR.(.NOT.L2.AND.GAM.GT.1.0D 0) - L3=L3.OR.(L2.AND.PAR1.LT.0.0D 0.AND.GAM.GT.1.0D 0) - L3=L3.OR.(L2.AND.PAR1.GT.0.0D 0.AND.GAM.LT.1.0D 0) - L3=L3.OR.GAM.LT.POM3 - L3=L3.OR.GAM.GT.POM4 - ELSE IF (MET1.EQ.4) THEN - L3=GAM.LT.POM3.OR.GAM.GT.POM4 - ENDIF - ENDIF - ENDIF - IF (L3) THEN - GAM=1.0D 0 - PAR=RHO/GAM - ENDIF - IF (MET.EQ.1) GO TO 17 -* -* NEW UPDATE -* - POM=1.0D 0/(AA*CC) - IF (POM.LT.1.0D 0) THEN - POM=MAX(1.0D-15,(SQRT(C/A)-POM)/(1.0D 0-POM)) - GO TO 20 - ENDIF - 17 CONTINUE -* -* BFGS UPDATE -* - POM=1.0D 0 - DIS=PAR+AA - CALL MXVDIR(N,-DIS,XO,S,XO) - DIS=1.0D 0/(B*DIS) - CALL MXDSMU(N,H,DIS,XO) - CALL MXDSMU(N,H,-DIS,S) - GO TO 21 - 20 CONTINUE -* -* GENERAL UPDATE -* - DEN=PAR+POM*AA - DIS=POM/DEN - CALL MXDSMU(N,H,(PAR*DIS-1.0D 0)/A,S) - CALL MXVDIR(N,-DIS,S,XO,S) - CALL MXDSMU(N,H,DEN/B,S) - 21 CONTINUE - IF (GAM.EQ.1.0D 0) GO TO 22 -* -* SCALING -* - CALL MXDSMS(N,H,GAM) - 22 CONTINUE - ITERH=0 - RETURN - END -* SUBROUTINE PUDBM2 ALL SYSTEMS 92/12/01 -C PORTABILITY : ALL SYSTEMS -C 92/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VARIABLE METRIC UPDATE OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX. -* -* PARAMETERS : -* RU H(M) POSITIVE DEFINITE APPROXIMATION OF THE HESSIAN -* MATRIX. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RA S(NF) AUXILIARY VECTOR. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI GO(NF) GRADIENTS DIFFERENCE. -* -* COMMON DATA : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II M NUMBER OF NONZERO ELEMENTS OF THE MATRIX. -* II MET METHOD SELECTION. MET=1-BFGS UPDATE. MET=2-DFP UPDATE. -* MET=3-HOSHINO UPDATE. -* II MET1 SELECTION OF SELF SCALING. MET1=1-SELF SCALING SUPPRESSED. -* MET1=2-INITIAL SELF SCALING. -* II MET2 SELECTION OF THE LINE SEARCH MODEL. MET2=1-QUADRATIC MODEL. -* MET2=2 USE OF TAYLOR EXPANSION. -* II MET3 METHOD CORRECTION. MET3=1-NO CORRECTION. -* MET3=2-POWELL'S CORRECTION. -* II ITERD TERMINATION INDICATOR. ITERD<0-BAD DECOMPOSITION. -* ITERD=0-DESCENT DIRECTION. ITERD=1-NEWTON LIKE STEP. -* ITERD=2-INEXACT NEWTON LIKE STEP. ITERD=3-BOUNDARY STEP. -* ITERD=4-DIRECTION WITH THE NEGATIVE CURVATURE. -* ITERD=5-MARQUARDT STEP. -* IO ITERH TERMINATION INDICATOR. ITERH<0-BAD DECOMPOSITION. -* ITERH=0-SUCCESSFUL UPDATE. ITERH>0-NONPOSITIVE PARAMETERS. -* II IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* IDECF=1-GILL-MURRAY DECOMPOSITION. IDECF=2-BUNCH-PARLETT -* DECOMPOSITION. IDECF=3-INVERSION. -* II ITRAN TRANSFORMATION INDICATOR. ITRAN=0 OR ITRAN=1 IF -* TRANSFORMATION IS NOT OR IS USED. -* II NIT ACTUAL NUMBER OF ITERATIONS. -* II KIT NUMBER OF THE ITERATION AFTER LAST RESTART. -* RI R VALUE OF THE STEPSIZE PARAMETER. -* RI F NEW VALUE OF THE OBJECTIVE FUNCTION. -* RI FO OLD VALUE OF THE OBJECTIVE FUNCTION. -* RI P NEW VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI PO OLD VALUE OF THE DIRECTIONAL DERIVATIVE. -* TO TUXX TEXT INFORMATION ON THE CORRECTION USED. -* -* SUBPROGRAMS USED : -* S MXDSMM MATRIX-VECTOR PRODUCT. -* S MXDSMU CORRECTION OF A DENSE SYMMETRIC MATRIX. -* S MXDSMS SCALING OF A DENSE SYMMETRIC MATRIX. -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* RF MXVDOT DOT PRODUCT OF VECTORS. -* S MXVNEG COPYING OF A VECTOR WITH THE CHANGE OF THE SIGN. -* S MXVSCL SCALING OF A VECTOR. -* S UOU1D1 PRINT OF ENTRY TO VARIABLE METRIC UPDATE. -* S UOU1D2 PRINT OF EXIT FROM VARIABLE METRIC UPDATE. -* -* METHOD : -* BASIC VARIABLE METRIC METHODS. -* - SUBROUTINE PUDBM2(NF,N,H,HH,S,XO,GO,SO,FO,PAR,MET1,MET3,IDECF, - & ITERH) - INTEGER NF,N,MET1,MET3,IDECF,ITERH - DOUBLE PRECISION H(NF*(NF+1)/2),HH(NF*(NF+1)/2),S(NF),XO(NF), - & GO(NF),SO(NF),FO,PAR - DOUBLE PRECISION DEN,A,B,C,GAM,POM,MXVDOT - LOGICAL L1 - DOUBLE PRECISION CON - PARAMETER (CON=1.0D-8) - IF (IDECF.NE.0) THEN - ITERH=-1 - RETURN - ENDIF - L1=MET1.GE.2 -C -C DETERMINATION OF THE PARAMETERS B, C -C - CALL MXDSMM(N,H,XO,S) - CALL MXVDIF(N,GO,S,SO) - IF (MET3.EQ.2) CALL MXVSCL(N,1.0D0/SQRT(FO),SO,SO) - B=MXVDOT(N,XO,SO) - IF (B.LE.0.0D0) L1=.FALSE. - A=0.0D0 - CALL MXDSMM(N,HH,XO,S) - C=MXVDOT(N,XO,S) - IF (C.LE.0.0D0) L1=.FALSE. - IF (L1) THEN -C -C DETERMINATION OF THE PARAMETER GAM (SELF SCALING) -C - GAM=C/B - ELSE - GAM=1.0D0 - ENDIF - PAR=GAM -C -C RANK ONE UPDATE -C - DEN=PAR*B-C - IF (ABS(DEN).LE.CON*MAX(CON,ABS(PAR*B),ABS(C))) THEN - IF (B.GT.0.0D0.AND.C.GT.0.0D0) GO TO 1 - ITERH=4 - RETURN - ENDIF - POM=PAR*B/DEN - CALL MXVDIR(N,-PAR,SO,S,S) - CALL MXDSMU(N,HH,1.0D0/DEN,S) - GO TO 5 -C -C BFGS UPDATE -C - 1 POM=0.0D0 - CALL MXDSMU(N,HH,PAR/B,SO) - IF (C.GT.0.0D0) CALL MXDSMU(N,HH,-1.0D0/C,S) - GO TO 5 - 5 ITERH=0 - IF (GAM.NE.1.0D0) THEN - CALL MXDSMS(N,HH,1.0D0/GAM) - ENDIF - RETURN - END -* SUBROUTINE PUDBQ1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* BROYDEN GOOD UPDATE OF A RECTANGULAR MATRIX AFTER THE QR -* DECOMPOSITION. -* -* PARAMETERS : -* II N NUMBER OF VARIABLES. -* II NA NUMBER OF EQUATIONS. -* RU H(N*(N+1)/2) UPDATED UPPER TRIANGULAR MATRIX. -* RI ETA2 PARAMETER WHICH CONTROLS A NONSINGULARITY -* RU AG(N*NA) UPDATED RECTANGULAR MATRIX. -* RA S(N) AUXILIARY VECTOR. -* RI XO(N) VECTOR OF VARIABLES DIFFERENCE. -* RI AFO(NA) RIGHT HAND SIDES DIFFERENCE. -* II MET VARIABLE METRIC UPDATE. -* IO ITERH UPDATE INDICATOR. ITERH=0-SUCCESSFUL UPDATE. -* ITERH>0-UNSUCCESSFUL UPDATE. -* IU IDECA DECOMPOSITION INDICATOR. -* II NDECA NUMBER OF DECOMPOSITIONS. -* -* METHOD : -* VARIOUS VARIABLE METRIC UPDATES INCLUDING BFGS UPDATE. -* - SUBROUTINE PUDBQ1(N,NA,H,ETA2,AG,S,XO,AFO,MET,ITERH,IDECA, - & NDECA) - INTEGER N,NA,MET,INF,ITERH,IDECA,NDECA - DOUBLE PRECISION H(*),ETA2,AG(*),S(*),XO(*),AFO(*) - DOUBLE PRECISION DEN,MXVDOT - IF (MET.LE.0) RETURN - IF (IDECA.EQ.0) THEN -* -* QR DECOMPOSITION -* - DEN=ETA2 - CALL MXDRQF(N,NA,AG,H) - CALL MXDPRC(N,H,INF,DEN) - NDECA=NDECA+1 - IDECA=1 - ELSE IF (IDECA.NE.1) THEN - ITERH=-1 - GO TO 22 - ENDIF -* -* THE GOOD BROYDEN UPDATE -* - DEN=MXVDOT(N,XO,XO) - IF (DEN.LE.0.0D 0) THEN - ITERH=2 - GO TO 22 - ENDIF - CALL MXVCOP(N,XO,S) - 21 CONTINUE - CALL MXVNEG(N,XO,XO) - CALL MXDPRM(N,H,XO,1) - CALL MXDRMD(N,NA,AG,XO,1.0D 0,AFO,AFO) - CALL MXDRQU(N,NA,AG,H,1.0D 0/DEN,AFO,S,XO,INF) - ITERH=0 - 22 CONTINUE - RETURN - END -* SUBROUTINE PUDFM1 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VARIABLE METRIC UPDATE OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX. -* -* PARAMETERS : -* II N ACTUAL NUMBER OF VARIABLES. -* RU B(M) POSITIVE DEFINITE APPROXIMATION OF THE HESSIAN MATRIX. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RA S(NF) AUXILIARY VECTOR. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI GO(NF) GRADIENTS DIFFERENCE. -* RI F CURRENT VALUE OF THE OBJECTIVE FUNCTION. -* RI FO PREVIOUS VALUE OF THE OBJECTIVE FUNCTION. -* RI ETA5 TOLERANCE FOR A HYBRID METHOD. -* RI ETA9 MAXIMUM FOR REAL NUMBERS. -* II IPOM1 METHOD INDICATOR. -* IO IPOM2 INDICATOR FOR SCALING. -* II MET METHOD SELECTION. MET=0-NO UPDATE. MET=1-BFGS UPDATE. -* II MET1 SELECTION OF SELF SCALING. MET1=1-SELF SCALING SUPPRESSED. -* MET1=2 SELF SCALING IN THE FIRST ITERATION AFTER RESTART. -* MET1=3-SELF SCALING IN EACH ITERATION. -* -* COMMON DATA : -* IO ITERH TERMINATION INDICATOR. ITERH<0-BAD DECOMPOSITION. -* ITERH=0-SUCCESSFUL UPDATE. ITERH>0-NONPOSITIVE PARAMETERS. -* II IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* TO TUXX TEXT INFORMATION ON THE CORRECTION USED. -* -* SUBPROGRAMS USED : -* S MXDSMM MATRIX-VECTOR PRODUCT. -* S MXDSMU CORRECTION OF A DENSE SYMMETRIC MATRIX. -* S MXDSMS SCALING OF A DENSE SYMMETRIC MATRIX. -* RF MXVDOT DOT PRODUCT OF VECTORS. -* S UOERR1 ERROR MESAGES. -* S UOU1D1 PRINT OF ENTRY TO VARIABLE METRIC UPDATE. -* S UOU1D2 PRINT OF EXIT FROM VARIABLE METRIC UPDATE. -* -* METHOD : -* FLETCHER'S COMBINATION OF THE GAUSS-NEWTON AND THE BFGS METHODS. -* - SUBROUTINE PUDFM1(N,B,S,XO,GO,F,FO,ETA5,IPOM1,IPOM2,MET1,IDECF, - & ITERH) - INTEGER N,IPOM1,IPOM2,MET1,IDECF,ITERH - DOUBLE PRECISION B(N*(N+1)/2),S(N),XO(N),GO(N),F,FO,ETA5 - DOUBLE PRECISION MXVDOT - DOUBLE PRECISION AB,BB,CB,GAM,PAR - LOGICAL L1 - IF (IDECF.NE.0) THEN - ITERH=-1 - RETURN - ENDIF - PAR=0.0D0 -C -C DETERMINATION OF THE PARAMETERS A,B,C -C - BB=MXVDOT(N,XO,GO) - IF (BB.LE.0.0D0) THEN - ITERH=2 - IPOM1=0 - RETURN - ENDIF - AB=0.0D0 - CALL MXDSMM(N,B,XO,S) - CB=MXVDOT(N,XO,S) - IF (CB.LE.0.0D0) THEN - ITERH=3 - RETURN - ENDIF - L1=MET1.EQ.4.OR.MET1.EQ.3.AND.IPOM2.GE.1.OR.MET1.EQ.2 - & .AND.IPOM2.EQ.1 - IF (FO-F.GE.ETA5*FO) THEN - IPOM1=0 - ELSE - IPOM1=1 - ENDIF - IF (L1) THEN -C -C DETERMINATION OF THE PARAMETER GAM (SELF SCALING) -C - GAM=CB/BB - ELSE - GAM=1.0D0 - ENDIF -C -C BFGS UPDATE -C - CALL MXDSMU(N,B,GAM/BB,GO) - CALL MXDSMU(N,B,-1.0D0/CB,S) - ITERH=0 - IPOM2=0 - IF (L1) THEN - CALL MXDSMS(N,B,1.0D0/GAM) - ENDIF - RETURN - END -* SUBROUTINE PUDRV1 ALL SYSTEMS 97/12/01 -* PORTABILITY : ALL SYSTEMS -* 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DRIVER FOR HYBRID QUASI-NEWTON UPDATES. -* -* PARAMETERS: -* RI R VALUE OF THE STEPSIZE PARAMETER. -* RI FO PREVIOUS VALUE OF THE OBJECTIVE FUNCTION. -* RI F CURRENT VALUE OF THE OBJECTIVE FUNCTION. -* RI PO PREVIOUS VALUE OF THE DIRECTIONAL DERIVATIVE. -* II IPOM1 UPDATE SELECTION. -* II IPOM2 METHOD SELECTION. -* IO NRED ACTUAL NUMBER OF EXTRAPOLATIONS OR INTERPOLATIONS. -* II IREST RESTART SPECIFICATION. IF IREST=0 DOES NOT HOLD THEN A -* RESTART IS PERFORMED. -* - SUBROUTINE PUDRV1(R,FO,F,PO,IPOM1,IPOM2,NRED,IREST) - INTEGER IPOM1,IPOM2,NRED,IREST - DOUBLE PRECISION R,FO,F,PO - DOUBLE PRECISION POM - DOUBLE PRECISION CON1,CON2 - PARAMETER(CON1=1.0D-1,CON2=1.0D-2) - POM=(FO-F)/FO - GO TO (1,2,3,4) IPOM2 - 1 IREST=1 - IF (NRED.LE.0) THEN - IPOM1=2 - IREST=0 - ELSE - IPOM1=0 - ENDIF - GO TO 5 - 2 IREST=1 - IF(POM.GE.CON2) THEN - IPOM1=0 - ELSE IF (F-FO.LE.R*PO) THEN - IPOM1=0 - ELSE - IPOM1=1 - IREST=0 - ENDIF - GO TO 5 - 3 IREST=1 - IF (NRED.LE.0) THEN - IF (IPOM1.NE.1) THEN - IPOM1=2 - IREST=0 - ELSE - IPOM1=0 - ENDIF - ELSE IF (POM.GE.CON2) THEN - IPOM1=0 - ELSE IF (IPOM1.NE.2) THEN - IPOM1=1 - IREST=0 - ELSE - IPOM1=0 - ENDIF - GO TO 5 - 4 IREST=1 - IPOM1=0 - 5 CONTINUE - RETURN - END -* SUBROUTINE PUDSD2 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* INITIATION OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX -* -* PARAMETERS : -* II N ACTUAL NUMBER OF VARIABLES. -* RU H(N*(N+1)/2) POSITIVE DEFINITE APPROXIMATION OF THE HESSIAN -* MATRIX -* RU B(N*(N+1)/2) POSITIVE DEFINITE APPROXIMATION OF THE HESSIAN -* MATRIX -* RI F CURRENT VALUE OF THE OBJECTIVE FUNCTION. -* RI FO PREVIOUS VALUE OF THE OBJECTIVE FUNCTION. -* RI ETA5 TOLERANCE FOR A HYBRID METHOD. -* II MET3 TYPE OF STRUCTURED UPDATE. MET3=1-STANDARD STRUCTURED -* UPDATE. MET3=2-TOTALLY STRUCTURED UPDATE. -* -* COMMON DATA : -* RU RAN RANDOM NUMBER. -* II IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* II IREST RESTART SPECIFICATION. IF IREST=0 DOES NOT HOLD THEN A -* RESTART IS PERFORMED. -* II IDIR INDICATOR OF DIRECTION DETERMINATION. IDIR=0-BASIC -* DETERMINATION. IDIR=1-DETERMINATION AFTER STEPSIZE -* REDUCTION. IDIR=2-DETERMINATION AFTER STEPSIZE EXPANSION. -* IU LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* TO TUXX TEXT INFORMATION ON THE RESTART USED. -* -* SUBPROGRAMS USED : -* S MXDSMI GENERATION OF THE UNIT MATRIX. -* S MXDSDO INITIATION OF A DIAGONAL MATRIX. -* S MXDSMA DENSE SYMMETRIC MATRIX AUGMENTED -* BY THE SCALED DENSE SYMMETRIC MATRIX. -* S MXDSMO A SCALAR IS SET TO ALL ELEMENTS -* OF A DENSE SYMMETRIC MATRIX. -* S MXDSMS SCALING OF A DENSE SYMMETRIC MATRIX. -* S UYSET3 DEFINITION OF THE RESTART VARIABLES. -* - SUBROUTINE PUDSD2(N,H,B,F,FO,ETA5,MET3,LD,IDIR,IDECF,IREST,IND) - INTEGER N,MET3,LD,IDIR,IDECF,IREST,IND - DOUBLE PRECISION H(N*(N+1)/2),B(N*(N+1)/2),F,FO,ETA5 - INTEGER IUDSD - SAVE IUDSD - IND=0 - IF (IREST.LT.0) THEN - CALL MXDSMI(N,B) - IF (F.LT.1.0D0) CALL MXDSMS(N,B,SQRT(F)) - IUDSD=1 - ELSE IF (IREST.EQ.0) THEN - IF (IDIR.LE.0) THEN - IF (FO-F.LE.ETA5*FO) THEN - IF (MET3.EQ.2) THEN - CALL MXDSMA(N,SQRT(F),B,H,H) - ELSE - CALL MXDSMA(N,1.0D0,B,H,H) - ENDIF - LD=MIN(LD,1) - IUDSD=0 - ENDIF - ENDIF - ELSEIF(IUDSD.EQ.0) THEN - IF (MET3.EQ.2) THEN - CALL MXDSMA(N,-SQRT(F),B,H,H) - ELSE - CALL MXDSMA(N,-1.0D0,B,H,H) - ENDIF - CALL MXDSMI(N,B) - IF (F.LT.1.0D0) CALL MXDSMS(N,B,SQRT(F)) - IUDSD=1 - ELSE - CALL MXDSMI(N,H) - LD=MIN(LD,1) - IUDSD=1 - IND=1 - ENDIF - IDECF=0 - RETURN - END -* SUBROUTINE PUDSD3 ALL SYSTEMS 97/12/01 -C PORTABILITY : ALL SYSTEMS -C 97/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* INITIATION OF A DENSE SYMMETRIC POSITIVE DEFINITE MATRIX -* -* PARAMETERS : -* II N ACTUAL NUMBER OF VARIABLES. -* RU H(N*(N+1)/2) FACTORIZATION H=L*D*TRANS(L) OF A POSITIVE -* SEMIDEFINITE HESSIAN MATRIX. -* RU B(N*(N+1)/2) FACTORIZATION B=L*D*TRANS(L) OF A POSITIVE -* DEFINITE APPROXIMATION OF THE HESSIAN MATRIX. -* IU IPOM1 METHOD INDICATOR. -* IU IPOM2 INDICATOR FOR SCALING. -* -* COMMON DATA : -* RU RAN RANDOM NUMBER. -* II IDECF DECOMPOSITION INDICATOR. IDECF=0-NO DECOMPOSITION. -* II IREST RESTART SPECIFICATION. IF IREST=0 DOES NOT HOLD THEN A -* RESTART IS PERFORMED. -* II ITERS TERMINATION INDICATOR. ITERS=0-ZERO STEP. -* IU LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* -* SUBPROGRAMS USED : -* S MXDSMI GENERATION OF THE UNIT MATRIX. -* S MXDSDO INITIATION OF A DIAGONAL MATRIX. -* S UUDSMC COPYING OF A DENSE SYMMETRIC MATRIX. -* RF UNRAN1 RANDOM NUMBER GENERATOR. -* S UYSET3 DEFINITION OF THE RESTART VARIABLES. -* - SUBROUTINE PUDSD3(N,H,B,IPOM1,IPOM2,LD,IDECF,ITERS,IREST,IND) - INTEGER N,IPOM1,IPOM2,LD,IDECF,ITERS,IREST,IND - DOUBLE PRECISION H(N*(N+1)/2),B(N*(N+1)/2) - INTEGER KDECF - SAVE KDECF - IND=0 - IF (IREST.EQ.0.OR.IREST.GT.0.AND.IPOM1.EQ.0) THEN - ELSE - CALL MXDSMI(N,B) - IPOM2= 1 - KDECF=-1 - ENDIF - IF (IPOM1.EQ.1) THEN - IF (ITERS.GT.0.OR.IREST.GT.0) THEN - CALL MXDSMC(N,B,H) - LD=MIN(LD,1) - IF (IPOM2.EQ.1) IDECF=KDECF - IF (IREST.GT.0) IND=1 - ENDIF - ELSE - IF (IREST.LE.0) THEN - ELSE - IPOM1= 1 - CALL MXDSMC(N,B,H) - LD=MIN(LD,1) - IF (IPOM2.EQ.1) IDECF=KDECF - ENDIF - ENDIF - RETURN - END -* SUBROUTINE PYADB4 ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* NEW LINEAR CONSTRAINTS OR NEW SIMPLE BOUNDS ARE ADDED TO THE ACTIVE -* SET. GILL-MURRAY FACTORIZATION OF THE TRANSFORMED HESSIAN MATRIX -* APPROXIMATION IS UPDATED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF LINEARIZED CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* IU IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI CF(NC) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* RI CFD(NC) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT FUNCTIONS. -* IU IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RU H(NF*(NF+1)/2) GILL-MURRAY FACTORIZATION OF THE TRANSFORMED -* HESSIAN MATRIX APPROXIMATION. -* RA S(NF) AUXILIARY VECTOR. -* RI R VALUE OF THE STEPSIZE PARAMETER. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RI EPS9 TOLERANCE FOR ACTIVE CONSTRAINTS. -* RO GMAX MAXIMUM ABSOLUTE VALUE OF A PARTIAL DERIVATIVE. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF A NEGATIVE LAGRANGE MULTIPLIER. -* II KBF TYPE OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. KBF=1-ONE -* SIDED SIMPLE BOUNDS. KBF=2-TWO SIDED SIMPLE BOUNDS. -* II KBC TYPE OF CONSTRAINTS. KBC=0-NO CONSTRAINTS. KBC=1-CONSTRAINTS -* WITH ONE SIDED BOUNDS. KBC=2-CONSTRAINTS WITH TWO SIDED -* BOUNDS. -* IU INEW INDEX OF THE NEW ACTIVE CONSTRAINT. -* IO IER ERROR INDICATOR. -* IO ITERM TERMINATION INDICATOR. -* -* COMMON DATA : -* IU NADD NUMBER OF CONSTRAINT ADDITIONS. -* -* SUBPROGRAMS USED : -* S PLADB4 ADDITION OF A NEW ACTIVE CONSTRAINT. -* S PLNEWS IDENTIFICATION OF ACTIVE UPPER BOUNDS. -* S PLNEWL IDENTIFICATION OF ACTIVE LINEAR CONSTRAINRS. -* S PLDIRL NEW VALUES OF CONSTRAINT FUNCTIONS. -* S MXVIND CHANGE OF THE INTEGER VECTOR FOR CONSTRAINT ADDITION. -* - SUBROUTINE PYADB4(NF,N,NC,X,IX,XL,XU,CF,CFD,IC,ICA,CL,CU,CG, - & CR,CZ,H,S,R,EPS7,EPS9,GMAX,UMAX,KBF,KBC,INEW,IER,ITERM) - INTEGER NF,N,NC,IX(*),IC(*),ICA(*),KBF,KBC,INEW,IER,ITERM - DOUBLE PRECISION X(*),XL(*),XU(*),CF(*),CFD(*),CL(*),CU(*), - & CG(*),CR(*),CZ(*),H(*),S(*),R,EPS7,EPS9,GMAX,UMAX - INTEGER I,J,K,L,IJ,IK,KC,KJ,KK,LL - DOUBLE PRECISION DEN,TEMP - INTEGER NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - COMMON /STAT/ NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - IF (KBC.GT.0) THEN - IF (R.NE.0.0D 0) CALL PLDIRL(NC,CF,CFD,IC,R,KBC) - IF (INEW.NE.0) THEN - IF (KBF.GT.0) THEN - DO 1 I=1,NF - INEW=0 - CALL PLNEWS(X,IX,XL,XU,EPS9,I,INEW) - CALL PLADB4(NF,N,ICA,CG,CR,CZ,H,S,EPS7,GMAX,UMAX,9,INEW, - & NADD,IER) - CALL MXVIND(IX,I,IER) - IF (IER.LT.0) THEN - ITERM=-15 - RETURN - ENDIF - 1 CONTINUE - ENDIF - DO 2 KC=1,NC - INEW=0 - CALL PLNEWL(KC,CF,IC,CL,CU,EPS9,INEW) - CALL PLADB4(NF,N,ICA,CG,CR,CZ,H,S,EPS7,GMAX,UMAX,9,INEW, - & NADD,IER) - CALL MXVIND(IC,KC,IER) - IF (IER.LT.0) THEN - ITERM=-15 - RETURN - ENDIF - 2 CONTINUE - ENDIF - ELSE IF (KBF.GT.0) THEN - K=0 - DO 7 L=1,NF - IF (IX(L).GE.0) K=K+1 - INEW=0 - CALL PLNEWS(X,IX,XL,XU,EPS9,L,INEW) - IF (INEW.NE.0) THEN - IX(L)=10-IX(L) - KK=K*(K-1)/2 - DEN=H(KK+K) - IF (DEN.NE.0.0D 0) THEN - IJ=0 - KJ=KK - DO 4 J=1,N - IF (J.LE.K) THEN - KJ=KJ+1 - ELSE - KJ=KJ+J-1 - ENDIF - IF (J.NE.K) TEMP=H(KJ)/DEN - IK=KK - DO 3 I=1,J - IF (I.LE.K) THEN - IK=IK+1 - ELSE - IK=IK+I-1 - ENDIF - IJ=IJ+1 - IF (I.NE.K.AND.J.NE.K) H(IJ)=H(IJ)+TEMP*H(IK) - 3 CONTINUE - 4 CONTINUE - ENDIF - LL=KK+K - DO 6 I=K+1,N - DO 5 J=1,I - LL=LL+1 - IF (J.NE.K) THEN - KK=KK+1 - H(KK)=H(LL) - ENDIF - 5 CONTINUE - 6 CONTINUE - N=N-1 - ENDIF - 7 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PYFUT1 ALL SYSTEMS 98/12/01 -C PORTABILITY : ALL SYSTEMS -C 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* TERMINATION CRITERIA AND TEST ON RESTART. -* -* PARAMETERS : -* II N ACTUAL NUMBER OF VARIABLES. -* RI F NEW VALUE OF THE OBJECTIVE FUNCTION. -* RI FO OLD VALUE OF THE OBJECTIVE FUNCTION. -* RI UMAX MAXIMUN ABSOLUTE VALUE OF THE NEGATIVE LAGRANGE MULTIPLIER. -* RO GMAX NORM OF THE TRANSFORMED GRADIENT. -* RI DMAX MAXIMUM RELATIVE DIFFERENCE OF VARIABLES. -* RI TOLX LOWER BOUND FOR STEPLENGTH. -* RI TOLF LOWER BOUND FOR FUNCTION DECREASE. -* RI TOLB LOWER BOUND FOR FUNCTION VALUE. -* RI TOLG LOWER BOUND FOR GRADIENT. -* II KD DEGREE OF REQUIRED DERIVATIVES. -* IU NIT ACTUAL NUMBER OF ITERATIONS. -* II KIT NUMBER OF THE ITERATION AFTER RESTART. -* II MIT MAXIMUM NUMBER OF ITERATIONS. -* IU NFV ACTUAL NUMBER OF COMPUTED FUNCTION VALUES. -* II MFV MAXIMUM NUMBER OF COMPUTED FUNCTION VALUES. -* IU NFG ACTUAL NUMBER OF COMPUTED GRADIENT VALUES. -* II MFG MAXIMUM NUMBER OF COMPUTED GRADIENT VALUES. -* IU NTESX ACTUAL NUMBER OF TESTS ON STEPLENGTH. -* II MTESX MAXIMUM NUMBER OF TESTS ON STEPLENGTH. -* IU NTESF ACTUAL NUMBER OF TESTS ON FUNCTION DECREASE. -* II MTESF MAXIMUM NUMBER OF TESTS ON FUNCTION DECREASE. -* II ITES SYSTEM VARIBLE WHICH SPECIFIES TERMINATION. IF ITES=0 -* THEN TERMINATION IS SUPPRESSED. -* II IRES1 RESTART SPECIFICATION. RESTART IS PERFORMED AFTER -* IRES1*N+IRES2 ITERATIONS. -* II IRES2 RESTART SPECIFICATION. RESTART IS PERFORMED AFTER -* IRES1*N+IRES2 ITERATIONS. -* IU IREST RESTART INDICATOR. RESTART IS PERFORMED IF IREST>0. -* II ITERS TERMINATION INDICATOR FOR STEPLENGTH DETERMINATION. -* ITERS=0 FOR ZERO STEP. -* IO ITERM TERMINATION INDICATOR. ITERM=1-TERMINATION AFTER MTESX -* UNSUFFICIENT STEPLENGTHS. ITERM=2-TERMINATION AFTER MTESF -* UNSUFFICIENT FUNCTION DECREASES. ITERM=3-TERMINATION ON LOWER -* BOUND FOR FUNCTION VALUE. ITERM=4-TERMINATION ON LOWER BOUND -* FOR GRADIENT. ITERM=11-TERMINATION AFTER MAXIMUM NUMBER OF -* ITERATIONS. ITERM=12-TERMINATION AFTER MAXIMUM NUMBER OF -* COMPUTED FUNCTION VALUES. -* - SUBROUTINE PYFUT1(N,F,FO,UMAX,GMAX,DMAX,TOLX,TOLF,TOLB,TOLG,KD, - & NIT,KIT,MIT,NFV,MFV,NFG,MFG,NTESX,MTESX,NTESF,MTESF,ITES,IRES1, - & IRES2,IREST,ITERS,ITERM) - INTEGER N,KD,NIT,KIT,MIT,NFV,MFV,NFG,MFG,NTESX,MTESX,NTESF,MTESF, - & ITES,IRES1,IRES2,IREST,ITERS,ITERM - DOUBLE PRECISION F,FO,UMAX,GMAX,DMAX,TOLX,TOLF,TOLG,TOLB - DOUBLE PRECISION TEMP - IF (ITERM.LT.0) RETURN - IF (ITES .LE.0) GO TO 2 - IF (ITERS.EQ.0) GO TO 1 - IF (NIT.LE.0) FO=F+MIN(SQRT(ABS(F)),ABS(F)/1.0D 1) - IF (F.LE.TOLB) THEN - ITERM = 3 - RETURN - ENDIF - IF (KD.GT.0) THEN - IF (GMAX.LE.TOLG.AND.UMAX.LE.TOLG) THEN - ITERM = 4 - RETURN - ENDIF - ENDIF - IF (NIT.LE.0) THEN - NTESX = 0 - NTESF = 0 - ENDIF - IF (DMAX.LE.TOLX) THEN - ITERM = 1 - NTESX = NTESX + 1 - IF (NTESX .GE. MTESX) RETURN - ELSE - NTESX = 0 - ENDIF - TEMP=ABS(FO-F)/MAX(ABS(F),1.0D 0) - IF (TEMP.LE.TOLF) THEN - ITERM = 2 - NTESF = NTESF+1 - IF (NTESF.GE.MTESF) RETURN - ELSE - NTESF = 0 - ENDIF - 1 IF (NIT.GE.MIT) THEN - ITERM = 11 - RETURN - ENDIF - IF (NFV.GE.MFV) THEN - ITERM = 12 - RETURN - ENDIF - IF (NFG.GE.MFG) THEN - ITERM = 13 - RETURN - ENDIF - 2 ITERM = 0 - IF (N.GT.0.AND.NIT-KIT.GE.IRES1*N+IRES2) THEN - IREST=MAX(IREST,1) - ENDIF - NIT = NIT + 1 - RETURN - END -* SUBROUTINE PYRMB1 ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* OLD LINEAR CONSTRAINT OR AN OLD SIMPLE BOUND IS REMOVED FROM THE -* ACTIVE SET. TRANSFORMED GRADIENT OF THE OBJECTIVE FUNCTION AND -* TRANSFORMED HESSIAN MATRIX APPROXIMATION ARE UPDATED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* IU IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* IU IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* IU ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RU CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RU GN(NF) TRANSFORMED GRADIENT OF THE OBJECTIVE FUNCTION. -* RU H(NF*(NF+1)/2) TRANSFORMED HESSIAN MATRIX APPROXIMATION. -* RI EPS8 TOLERANCE FOR CONSTRAINT TO BE REMOVED. -* RI UMAX MAXIMUN ABSOLUTE VALUE OF THE NEGATIVE LAGRANGE MULTIPLIER. -* RI GMAX NORM OF THE TRANSFORMED GRADIENT. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* II IOLD INDEX OF THE REMOVED CONSTRAINT. -* IA KOLD AUXILIARY VARIABLE. -* IA KREM AUXILIARY VARIABLE. -* IO IER ERROR INDICATOR. -* IO ITERM TERMINATION INDICATOR. -* -* COMMON DATA : -* IU NREM NUMBER OF CONSTRAINT DELETIONS. -* -* SUBPROGRAMS USED : -* S PLRMB0 CONSTRAINT DELETION. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PYRMB1(NF,N,IX,IC,ICA,CG,CR,CZ,G,GN,H,EPS8,UMAX, - & GMAX,KBF,KBC,IOLD,KOLD,KREM,IER,ITERM) - INTEGER NF,N,IX(*),IC(*),ICA(*),KBF,KBC,IOLD,KOLD,KREM,IER, - $ ITERM - DOUBLE PRECISION CG(*),CR(*),CZ(*),G(*),GN(*),H(*),EPS8,UMAX, - & GMAX - INTEGER I,J,K,KC,L - INTEGER NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - COMMON /STAT/ NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - IF (KBC.GT.0) THEN - IF (UMAX.GT.EPS8*GMAX) THEN - CALL PLRMB0(NF,N,ICA,CG,CR,CZ,G,GN,IOLD,KREM,NREM,IER) - IF (IER.LT.0) THEN - ITERM=-16 - ELSE IF (IER.GT.0) THEN - IOLD=0 - ELSE - K=N*(N-1)/2 - CALL MXVSET(N,0.0D 0,H(K+1)) - H(K+N)=1.0D 0 - KC=ICA(NF-N+1) - IF (KC.GT.0) THEN - IC(KC)=-IC(KC) - ELSE - K=-KC - IX(K)=-IX(K) - ENDIF - ENDIF - ELSE - IOLD=0 - ENDIF - ELSE IF (KBF.GT.0) THEN - IF (UMAX.GT.EPS8*GMAX) THEN - IX(IOLD)=MIN(ABS(IX(IOLD)),3) - DO 1 I=N,KOLD,-1 - GN(I+1)=GN(I) - 1 CONTINUE - GN(KOLD)=G(IOLD) - N=N+1 - K=N*(N-1)/2 - L=K+N - DO 3 I=N,KOLD,-1 - DO 2 J=I,1,-1 - IF (I.NE.KOLD.AND.J.NE.KOLD) THEN - H(L)=H(K) - K=K-1 - L=L-1 - ELSE IF (I.EQ.KOLD.AND.J.EQ.KOLD) THEN - H(L)=1.0D 0 - L=L-1 - ELSE - H(L)=0.0D 0 - L=L-1 - ENDIF - 2 CONTINUE - 3 CONTINUE - ELSE - IOLD=0 - KOLD=0 - ENDIF - ENDIF - RETURN - END -* SUBROUTINE PYTRBD ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VECTORS OF VARIABLES DIFFERENCE AND GRADIENTS DIFFERENCE ARE COMPUTED -* AND TRANSFORMED. TEST VALUE DMAX IS DETERMINED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* RI X(NF) VECTOR OF VARIABLES. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RU GO(NF) GRADIENTS DIFFERENCE. -* RI CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM CURRENT -* REDUCED SUBSPACE. -* RU SN(NF) TRANSFORMED DIRECTION VECTOR. -* RI R VALUE OF THE STEPSIZE PARAMETER. -* RU F NEW VALUE OF THE OBJECTIVE FUNCTION. -* RI FO OLD VALUE OF THE OBJECTIVE FUNCTION. -* RU P NEW VALUE OF THE DIRECTIONAL DERIVATIVE. -* RU PO OLD VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO DMAX MAXIMUM RELATIVE DIFFERENCE OF VARIABLES. -* II ITERS TERMINATION INDICATOR FOR STEPLENGTH DETERMINATION. -* ITERS=0 FOR ZERO STEP. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* -* SUBPROGRAMS USED : -* S MXDRMM PREMULTIPLICATION OF A VECTOR BY TRANSPOSE OF A DENSE -* RECTANGULAR MATRIX. -* S MXVCOP COPYING OF A VECTOR. -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* S MXVMUL DIAGONAL PREMULTIPLICATION OF A VECTOR. -* S MXVSAV DIFFERENCE OF TWO VECTORS WITH COPYING AND SAVING THE -* SUBSTRACTED ONE. -* S MXVSCL SCALING OF A VECTOR. -* - SUBROUTINE PYTRBD(NF,N,X,IX,XO,G,GO,CZ,SN,R,F,FO,P,PO,DMAX,ITERS, - & KBF,KBC) - INTEGER NF,N,IX(*),ITERS,KBF,KBC - DOUBLE PRECISION X(*),XO(*),G(*),GO(*),CZ(*),SN(*),R,F,FO,P,PO, - & DMAX - INTEGER I,K - IF (ITERS.GT.0) THEN - CALL MXVDIF(NF,X,XO,XO) - CALL MXVDIF(NF,G,GO,GO) - PO=R*PO - P=R*P - ELSE - F = FO - P = PO - CALL MXVSAV(NF,X,XO) - CALL MXVSAV(NF,G,GO) - ENDIF - DMAX = 0.0D 0 - IF (KBC.GT.0) THEN - DO 1 I=1,NF - DMAX=MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D 0)) - 1 CONTINUE - IF (N.GT.0) THEN - CALL MXVSCL(N,R,SN,XO) - CALL MXVCOP(NF,GO,SN) - CALL MXDRMM(NF,N,CZ,SN,GO) - ENDIF - ELSE IF (KBF.GT.0) THEN - K=0 - DO 2 I=1,NF - IF (IX(I).LT.0) GO TO 2 - K=K+1 - DMAX=MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D 0)) - XO(K)=XO(I) - GO(K)=GO(I) - 2 CONTINUE - ELSE - DO 3 I=1,NF - DMAX=MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D 0)) - 3 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PYTRBG ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* GRADIENT OF THE OBJECTIVE FUNCTION IS SCALED AND REDUCED. -* TEST VALUES GMAX AND UMAX ARE COMPUTED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RU CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RO GN(NF) TRANSFORMED GRADIENT OF THE OBJECTIVE FUNCTION. -* RI EPS7 TOLERANCE FOR LINEAR INDEPENDENCE OF CONSTRAINTS. -* RO UMAX MAXIMUM ABSOLUTE VALUE OF THE NEGATIVE LAGRANGE MULTIPLIER. -* RO GMAX NORM OF THE TRANSFORMED GRADIENT. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* II IOLD INDEX OF THE REMOVED CONSTRAINT. -* IA KOLD AUXILIARY VARIABLE. -* -* SUBPROGRAMS USED : -* S MXDRMM PREMULTIPLICATION OF A VECTOR BY A ROWWISE STORED DENSE -* RECTANGULAR MATRIX. -* S MXDPRB BACK SUBSTITUTION. -* S MXVCOP COPYING OF A VECTOR. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* RF MXVMAX L-INFINITY NORM OF A VECTOR. -* S MXVMUL DIAGONAL PREMULTIPLICATION OF A VECTOR. -* - SUBROUTINE PYTRBG(NF,N,IX,IC,ICA,CG,CR,CZ,G,GN,UMAX,GMAX, - & KBF,KBC,IOLD,KOLD) - INTEGER NF,N,IX(*),IC(*),ICA(*),KBF,KBC,IOLD,KOLD - DOUBLE PRECISION CG(*),CR(*),CZ(*),G(*),GN(*),UMAX,GMAX - DOUBLE PRECISION TEMP,MXVMAX,MXVDOT - INTEGER NCA,NCZ,I,J,K,KC - IOLD=0 - KOLD=0 - UMAX=0.0D 0 - GMAX=0.0D 0 - IF (KBC.GT.0) THEN - IF (NF.GT.N) THEN - NCA=NF-N - NCZ=N*NF - CALL MXVCOP(NF,G,GN) - DO 1 J=1,NCA - K=ICA(J) - IF (K.GT.0) THEN - CZ(NCZ+J)=MXVDOT(NF,CG((K-1)*NF+1),GN) - ELSE - I=-K - CZ(NCZ+J)=GN(I) - ENDIF - 1 CONTINUE - CALL MXDPRB(NCA,CR,CZ(NCZ+1),0) - DO 2 J=1,NCA - TEMP=CZ(NCZ+J) - KC=ICA(J) - IF (KC.GT.0) THEN - K=IC(KC) - ELSE - I=-KC - K=IX(I) - ENDIF - IF (K.LE.-5) THEN - ELSE IF ((K.EQ.-1.OR.K.EQ.-3).AND.UMAX+TEMP.GE.0.0D 0) THEN - ELSE IF ((K.EQ.-2.OR.K.EQ.-4).AND.UMAX-TEMP.GE.0.0D 0) THEN - ELSE - IOLD=J - UMAX=ABS(TEMP) - ENDIF - 2 CONTINUE - ENDIF - IF (N.GT.0) THEN - CALL MXDRMM(NF,N,CZ,G,GN) - GMAX=MXVMAX(N,GN) - ENDIF - ELSE IF (KBF.GT.0) THEN - J=0 - IOLD=0 - KOLD=0 - DO 3 I=1,NF - TEMP=G(I) - K=IX(I) - IF (K.GE.0) THEN - J=J+1 - GN(J)=TEMP - GMAX=MAX(GMAX,ABS(TEMP)) - ELSE IF (K.LE.-5) THEN - ELSE IF ((K.EQ.-1.OR.K.EQ.-3).AND.UMAX+TEMP.GE.0.0D 0) THEN - ELSE IF ((K.EQ.-2.OR.K.EQ.-4).AND.UMAX-TEMP.GE.0.0D 0) THEN - ELSE - IOLD=I - KOLD=J+1 - UMAX=ABS(TEMP) - ENDIF - 3 CONTINUE - N=J - ELSE - DO 4 I=1,NF - TEMP=G(I) - GMAX=MAX(GMAX,ABS(TEMP)) - 4 CONTINUE - N=NF - ENDIF - RETURN - END -* SUBROUTINE PYTRBH ALL SYSTEMS 98/12/01 -C PORTABILITY : ALL SYSTEMS -C 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* HESSIAN MATRIX OF THE OBJECTIVE FUNCTION OR ITS APPROXIMATION IS -* SCALED AND REDUCED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* RI CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RI CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RI H(NF*(NF+1)/2) HESSIAN MATRIX OR ITS APPROXIMATION. -* RA S(NF) AUXILIARY VECTOR. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* II LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* II ITERS TERMINATION INDICATOR FOR STEPLENGTH DETERMINATION. -* -* SUBPROGRAMS USED : -* S MXDSMM MATRIX VECTOR PRODUCT. -* S MXVCOP COPYING OF A VECTOR. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* - SUBROUTINE PYTRBH(NF,N,IX,CR,CZ,H,S,KBF,KBC,LD,ITERS) - INTEGER NF,N,IX(*),KBF,KBC,LD,ITERS - DOUBLE PRECISION CR(*),CZ(*),H(*),S(*) - DOUBLE PRECISION MXVDOT - INTEGER NCA,NCR,ICZ,JCZ,I,J,K,L - IF (LD.NE.2.OR.ITERS.EQ.0) RETURN - IF (KBC.GT.0) THEN - IF (N.LE.0) RETURN - NCA=NF-N - NCR=NCA*(NCA+1)/2 - K=NCR - JCZ=1 - DO 4 J=1,N - CALL MXDSMM(NF,H,CZ(JCZ),S) - ICZ=1 - DO 3 I=1,J - K=K+1 - CR(K)=MXVDOT(NF,CZ(ICZ),S) - ICZ=ICZ+NF - 3 CONTINUE - JCZ=JCZ+NF - 4 CONTINUE - CALL MXVCOP(N*(N+1)/2,CR(NCR+1),H) - ELSE IF (KBF.GT.0) THEN - K=0 - L=0 - DO 2 I=1,NF - DO 1 J=1,I - K=K+1 - IF(IX(I).LT.0.OR.IX(J).LT.0) GO TO 1 - L=L+1 - H(L)=H(K) - 1 CONTINUE - 2 CONTINUE - ENDIF - RETURN - END -* SUBROUTINE PYTRBS ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* SCALED AND REDUCED DIRECTION VECTOR IS BACK TRANSFORMED. -* VECTORS X,G AND VALUES F,P ARE SAVED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* IU N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF LINEARIZED CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. -* RO XO(NF) SAVED VECTOR OF VARIABLES. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RO GO(NF) SAVED GRADIENT OF THE OBJECTIVE FUNCTION. -* RI CF(NF) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCYIONS. -* RO CFD(NF) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI CZ(NF*NF) MATRIX WHOSE COLUMNS ARE BASIC VECTORS FROM THE -* CURRENT REDUCED SUBSPACE. -* RI SN(NF) TRANSFORMED DIRECTION VECTOR. -* RO S(NF) DIRECTION VECTOR. -* RO RO SAVED VALUE OF THE STEPSIZE PARAMETER. -* RO FP PREVIOUS VALUE OF THE OBJECTIVE FUNCTION. -* RU FO SAVED VALUE OF THE OBJECTIVE FUNCTION. -* RI F VALUE OF THE OBJECTIVE FUNCTION. -* RO PO SAVED VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI P VALUE OF THE DIRECTIONAL DERIVATIVE. -* RU RMAX MAXIMUM VALUE OF THE STEPSIZE PARAMETER. -* II KBF SPECIFICATION OF SIMPLE BOUNDS. KBF=0-NO SIMPLE BOUNDS. -* KBF=1-ONE SIDED SIMPLE BOUNDS. KBF=2=TWO SIDED SIMPLE BOUNDS. -* II KBC SPECIFICATION OF LINEAR CONSTRAINTS. KBC=0-NO LINEAR -* CONSTRAINTS. KBC=1-ONE SIDED LINEAR CONSTRAINTS. KBC=2=TWO -* SIDED LINEAR CONSTRAINTS. -* IO KREM INDICATION OF LINEARLY DEPENDENT GRADIENTS. -* IO INEW INDEX OF THE NEW ACTIVE FUNCTION. -* -* SUBPROGRAMS USED : -* S PLMAXS DETERMINATION OF THE MAXIMUM STEPSIZE USING SIMPLE -* BOUNDS. -* S PLMAXL DETERMINATION OF THE MAXIMUM STEPSIZE USING LINEAR -* CONSTRAINTS. -* S MXDCMM MATRIX VECTOR PRODUCT. -* S MXVCOP COPYING OF A VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* - SUBROUTINE PYTRBS(NF,N,NC,X,IX,XO,XL,XU,G,GO,CF,CFD,IC,CL,CU,CG, - & CZ,SN,S,RO,FP,FO,F,PO,P,RMAX,KBF,KBC,KREM,INEW) - INTEGER NF,N,NC,IX(*),IC(*),KBF,KBC,KREM,INEW - DOUBLE PRECISION X(*),XO(*),XL(*),XU(*),G(*),GO(*),CF(*),CFD(*), - & CL(*),CU(*),CG(*),CZ(*),SN(*),S(*),RO,FP,FO,F,PO,P,RMAX - INTEGER I,K - FP = FO - RO = 0.0D 0 - FO = F - PO = P - CALL MXVCOP(NF,X,XO) - CALL MXVCOP(NF,G,GO) - IF (KBC.GT.0) THEN - IF (N.GT.0) THEN - CALL MXDCMM(NF,N,CZ,SN,S) - INEW=0 - CALL PLMAXL(NF,NC,CF,CFD,IC,CL,CU,CG,S,RMAX,KBC,KREM,INEW) - CALL PLMAXS(NF,X,IX,XL,XU,S,RMAX,KBF,KREM,INEW) - ELSE - CALL MXVSET(NF,0.0D 0,S) - ENDIF - ELSE IF (KBF.GT.0) THEN - K=N+1 - DO 1 I=NF,1,-1 - IF (IX(I).LT.0) THEN - S(I)=0.0D 0 - ELSE - K=K-1 - S(I)=SN(K) - ENDIF - 1 CONTINUE - INEW=0 - CALL PLMAXS(NF,X,IX,XL,XU,S,RMAX,KBF,KREM,INEW) - ENDIF - RETURN - END -* SUBROUTINE PYTRFD ALL SYSTEMS 90/12/01 -* PORTABILITY : ALL SYSTEMS -* 90/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* PREPARATION OF VARIABLE METRIC UPDATE. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* RU XO(NF) SAVED VECTOR OF VARIABLES. -* II IAA(NF+1) VECTOR CONTAINING INDICES OF ACTIVE FUNCTIONS. -* RI AG(NF*NA) MATRIX WHOSE COLUMNS ARE GRADIENTS OF THE LINEAR -* APPROXIMATED FUNCTIONS. -* RI AZ(NF+1) VECTOR OF LAGRANGE MULTIPLIERS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RI G(NF) GRADIENT OF THE LAGRANGIAN FUNCTION. -* RU GO(NF) SAVED GRADIENT OF THE LAGRANGIAN FUNCTION. -* II N ACTUAL NUMBER OF VARIABLES. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IU LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* RU R VALUE OF THE STEPSIZE PARAMETER. -* RU F VALUE OF THE OBJECTIVE FUNCTION. -* RI FO SAVED VALUE OF THE OBJECTIVE FUNCTION. -* RU P VALUE OF THE DIRECTIONAL DERIVATIVE. -* RU PO SAVED VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO DMAX RELATIVE STEPSIZE. -* IO ITERS TERMINATION INDICATOR. ITERS=0-ZERO STEP. ITERS=1-PERFECT -* LINE SEARCH. ITERS=2 GOLDSTEIN STEPSIZE. ITERS=3-CURRY -* STEPSIZE. ITERS=4-EXTENDED CURRY STEPSIZE. -* ITERS=5-ARMIJO STEPSIZE. ITERS=6-FIRST STEPSIZE. -* ITERS=7-MAXIMUM STEPSIZE. ITERS=8-UNBOUNDED FUNCTION. -* ITERS=-1-MRED REACHED. ITERS=-2-POSITIVE DIRECTIONAL -* DERIVATIVE. ITERS=-3-ERROR IN INTERPOLATION. -* -* SUBPROGRAMS USED : -* S MXVCOP COPYING OF A VECTOR. -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* S MXVSAV DIFFERENCE OF TWO VECTORS WITH COPYING AND SAVING THE -* SUBSTRACTED ONE. -* - SUBROUTINE PYTRFD(NF,NC,X,XO,IAA,AG,AZ,CG,G,GO,N,KD,LD,R,F,FO,P, - + PO,DMAX,ITERS) - DOUBLE PRECISION DMAX,F,FO,P,PO,R - INTEGER ITERS,KD,LD,N,NC,NF - DOUBLE PRECISION AG(*),AZ(*),CG(*),G(*),GO(*),X(*),XO(*) - INTEGER IAA(*) - INTEGER I,J,L - CALL MXVSET(NF,0.0D0,G) - DO 10 J = 1,NF - N - L = IAA(J) - IF (L.GT.NC) THEN - L = L - NC - CALL MXVDIR(NF,-AZ(J),AG((L-1)*NF+1),G,G) - ELSE IF (L.GT.0) THEN - CALL MXVDIR(NF,-AZ(J),CG((L-1)*NF+1),G,G) - ELSE - L = -L - G(L) = G(L) - AZ(J) - END IF - 10 CONTINUE - IF (ITERS.GT.0) THEN - CALL MXVDIF(NF,X,XO,XO) - CALL MXVDIF(NF,G,GO,GO) - PO = R*PO - P = R*P - ELSE - R = 0.0D0 - F = FO - P = PO - CALL MXVSAV(NF,X,XO) - CALL MXVSAV(NF,G,GO) - LD = KD - END IF - DMAX = 0.0D0 - DO 20 I = 1,NF - DMAX = MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D0)) - 20 CONTINUE - N = NF - RETURN - END -* SUBROUTINE PYTRND ALL SYSTEMS 91/12/01 -C PORTABILITY : ALL SYSTEMS -C 91/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* DUAL RANGE SPACE QUADRATIC PROGRAMMING METHOD FOR MINIMAX -* APPROXIMATION. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II N ACTUAL NUMBER OF VARIABLES. -* II NC NUMBER OF CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* RI XN(NF) VECTOR OF SCALING FACTORS. -* RO XO(NF) SAVED VECTOR OF VARIABLES. -* II ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RO CZ(NF) VECTOR OF LAGRANGE MULTIPLIERS. -* RO CZS(NF) SAVED VECTOR OF LAGRANGE MULTIPLIERS. -* RI G(NF) GRADIENT OF THE LAGRANGIAN FUNCTION. -* RI GO(NF) SAVED GRADIENT OF THE LAGRANGIAN FUNCTION. -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RO F NEW VALUE OF THE OBJECTIVE FUNCTION. -* RI FO OLD VALUE OF THE OBJECTIVE FUNCTION. -* RO P NEW VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI PO OLD VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI CMAX VALUE OF THE CONSTRAINT VIOLATION. -* RO CMAXO SAVED VALUE OF THE CONSTRAINT VIOLATION. -* RO DMAX MAXIMUM RELATIVE DIFFERENCE OF VARIABLES. -* -* COMMON DATA : -* II NORMF SCALING SPECIFICATION. NORMF=0-NO SCALING PERFORMED. -* NORMF=1-SCALING FACTORS ARE DETERMINED AUTOMATICALLY. -* NORMF=2-SCALING FACTORS ARE SUPPLIED BY USER. -* II ITERS TERMINATION INDICATOR FOR STEPLENGTH DETERMINATION. -* ITERS=0 FOR ZERO STEP. -* -* SUBPROGRAMS USED : -* S MXVCOP COPYING OF A VECTOR. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* S MXVSAV DIFFERENCE OF TWO VECTORS WITH COPYING AND SAVING THE -* SUBSTRACTED ONE. -* - SUBROUTINE PYTRND(NF,N,X,XO,ICA,CG,CZ,G,GO,R,F,FO,P,PO,CMAX,CMAXO, - & DMAX,KD,LD,ITERS) - INTEGER NF,N,KD,LD,ITERS - INTEGER ICA(*) - DOUBLE PRECISION X(*),XO(*),CG(*),CZ(*),G(*),GO(*),R,F,FO,P,PO, - & CMAX,CMAXO,DMAX - INTEGER I,J,L - DO 2 J=1,NF-N - L=ICA(J) - IF (L.GT.0) THEN - CALL MXVDIR(NF,-CZ(J),CG((L-1)*NF+1),G,G) - ELSE - L=-L - G(L)=G(L)-CZ(J) - ENDIF - 2 CONTINUE - IF (ITERS.GT.0) THEN - CALL MXVDIF(NF,X,XO,XO) - CALL MXVDIF(NF,G,GO,GO) - PO=R*PO - P=R*P - ELSE - F = FO - P = PO - CMAX = CMAXO - CALL MXVSAV(NF,X,XO) - CALL MXVSAV(NF,G,GO) - LD = KD - ENDIF - DMAX = 0.0D0 - DO 1 I=1,NF - DMAX=MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D0)) - 1 CONTINUE - N=NF - RETURN - END -* SUBROUTINE PYTRUD ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VECTORS OF VARIABLES DIFFERENCE AND GRADIENTS DIFFERENCE ARE COMPUTED -* AND SCALED. TEST VALUE DMAX IS DETERMINED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* RI X(NF) VECTOR OF VARIABLES. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RU GO(NF) GRADIENTS DIFFERENCE. -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RO F NEW VALUE OF THE OBJECTIVE FUNCTION. -* RI FO OLD VALUE OF THE OBJECTIVE FUNCTION. -* RO P NEW VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI PO OLD VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO DMAX MAXIMUM RELATIVE DIFFERENCE OF VARIABLES. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* II ITERS TERMINATION INDICATOR FOR STEPLENGTH DETERMINATION. -* ITERS=0 FOR ZERO STEP. -* -* SUBPROGRAMS USED : -* S PYSET1 DEGREE DEFINITION OF THE COMPUTED DERIVATIVES. -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* S MXVSAV DIFFERENCE OF TWO VECTORS WITH COPYING AND SAVING THE -* SUBSTRACTED ONE. -* - SUBROUTINE PYTRUD(NF,X,XO,G,GO,R,F,FO,P,PO,DMAX,KD,LD,ITERS) - INTEGER NF,KD,LD,ITERS - DOUBLE PRECISION X(*),XO(*),G(*),GO(*),R,F,FO,P,PO,DMAX - INTEGER I - IF (ITERS.GT.0) THEN - CALL MXVDIF(NF,X,XO,XO) - CALL MXVDIF(NF,G,GO,GO) - PO=R*PO - P=R*P - ELSE - F = FO - P = PO - CALL MXVSAV(NF,X,XO) - CALL MXVSAV(NF,G,GO) - LD=KD - ENDIF - DMAX = 0.0D 0 - DO 1 I=1,NF - DMAX=MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D 0)) - 1 CONTINUE - RETURN - END -* SUBROUTINE PYTRUF ALL SYSTEMS 98/12/01 -* PORTABILITY : ALL SYSTEMS -* 98/12/01 LU : ORIGINAL VERSION -* -* PURPOSE : -* VECTORS OF VARIABLES DIFFERENCE AND RIGHT HAND SIDES DIFFERENCE ARE -* COMPUTED AND SCALED. TEST VALUE DMAX IS DETERMINED. -* -* PARAMETERS : -* II NF DECLARED NUMBER OF VARIABLES. -* II NA NUMBER OF APPROXIMATED FUNCTIONS. -* RI X(NF) VECTOR OF VARIABLES. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI AF(NA) VECTOR OF RIGHT HAND SIDES. -* RI AFO(NA) VECTOR OF RIGHT HAND SIDES DIFFERENCE. -* RO R VALUE OF THE STEPSIZE PARAMETER. -* RO F NEW VALUE OF THE OBJECTIVE FUNCTION. -* RI FO OLD VALUE OF THE OBJECTIVE FUNCTION. -* RO P NEW VALUE OF THE DIRECTIONAL DERIVATIVE. -* RI PO OLD VALUE OF THE DIRECTIONAL DERIVATIVE. -* RO DMAX MAXIMUM RELATIVE DIFFERENCE OF VARIABLES. -* II KD DEGREE OF REQUIRED DERVATIVES. -* IO LD DEGREE OF PREVIOUSLY COMPUTED DERIVATIVES. -* II ITERS TERMINATION INDICATOR FOR STEPLENGTH DETERMINATION. -* ITERS=0 FOR ZERO STEP. -* -* SUBPROGRAMS USED : -* S PYSET1 DEGREE DEFINITION OF THE COMPUTED DERIVATIVES. -* S MXVDIF DIFFERENCE OF TWO VECTORS. -* S MXVSAV DIFFERENCE OF TWO VECTORS WITH COPYING AND SAVING THE -* SUBSTRACTED ONE. -* - SUBROUTINE PYTRUF(NF,NA,X,XO,AF,AFO,R,F,FO,P,PO,DMAX,KD,LD, - & ITERS) - INTEGER NF,NA,KD,LD,ITERS - DOUBLE PRECISION X(*),XO(*),AF(*),AFO(*),R,F,FO,P,PO,DMAX - INTEGER I - IF (ITERS.GT.0) THEN - CALL MXVDIF(NF,X,XO,XO) - CALL MXVDIF(NA,AF,AFO,AFO) - PO=R*PO - P=R*P - ELSE - R = 0.0D 0 - F = FO - P = PO - CALL MXVSAV(NF,X,XO) - CALL MXVSAV(NA,AF,AFO) - LD=KD - ENDIF - DMAX = 0.0D 0 - DO 1 I=1,NF - DMAX=MAX(DMAX,ABS(XO(I))/MAX(ABS(X(I)),1.0D 0)) - 1 CONTINUE - RETURN - END diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/psqp.f b/pyoptsparse/pyoptsparse/pyPSQP/source/psqp.f deleted file mode 100644 index 4aa2e45a3..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/psqp.f +++ /dev/null @@ -1,590 +0,0 @@ -************************************************************************ -* SUBROUTINE PSQPN ALL SYSTEMS 97/01/22 -* PURPOSE : -* EASY TO USE SUBROUTINE FOR GENERAL NONLINEAR PROGRAMMING PROBLEMS. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II NB CHOICE OF SIMPLE BOUNDS. NB=0-SIMPLE BOUNDS SUPPRESSED. -* NB>0-SIMPLE BOUNDS ACCEPTED. -* II NC NUMBER OF LINEAR CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. IX(I)=0-VARIABLE -* X(I) IS UNBOUNDED. IX(I)=1-LOVER BOUND XL(I).LE.X(I). -* IX(I)=2-UPPER BOUND X(I).LE.XU(I). IX(I)=3-TWO SIDE BOUND -* XL(I).LE.X(I).LE.XU(I). IX(I)=5-VARIABLE X(I) IS FIXED. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RI CF(NC+1) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* IC(KC)=0-CONSTRAINT CF(KC) IS NOT USED. IC(KC)=1-LOVER -* CONSTRAINT CL(KC).LE.CF(KC). IC(KC)=2-UPPER CONSTRAINT -* CF(KC).LE.CU(KC). IC(KC)=3-TWO SIDE CONSTRAINT -* CL(KC).LE.CF(KC).LE.CU(KC). IC(KC)=5-EQUALITY CONSTRAINT -* CF(KC).EQ.CL(KC). -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* II IPAR(6) INTEGER PAREMETERS: -* IPAR(1) MAXIMUM NUMBER OF ITERATIONS. -* IPAR(2) MAXIMUM NUMBER OF FUNCTION EVALUATIONS. -* IPAR(3) THIS PARAMETER IS NOT USED IN THE SUBROUTINE PSQP. -* IPAR(4) THIS PARAMETER IS NOT USED IN THE SUBROUTINE PSQP. -* IPAR(5) VARIABLE METRIC UPDATE USED. IPAR(5)=1-THE BFGS UPDATE. -* IPAR(5)-THE HOSHINO UPDATE. -* IPAR(6) CORRECTION OF THE VARIABLE METRIC UPDATE IF A NEGATIVE -* CURVATURE OCCURS. IPAR(6)=1-NO CORRECTION. IPAR(6)=2-POWELL'S -* CORRECTION. -* RI RPAR(5) REAL PARAMETERS: -* RPAR(1) MAXIMUM STEPSIZE. -* RPAR(2) TOLERANCE FOR CHANGE OF VARIABLES. -* RPAR(3) TOLERANCE FOR CONSTRAINT VIOLATIONS. -* RPAR(4) TOLERANCE FOR THE GRADIENT OF THE LAGRANGIAN FUNCTION. -* RPAR(5) PENALTY COEFFICIENT. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* RO GMAX MAXIMUM PARTIAL DERIVATIVE OF THE LAGRANGIAN FUNCTION. -* RO CMAX MAXIMUM CONSTRAINT VIOLATION. -* II IPRNT PRINT SPECIFICATION. IPRNT=0-NO PRINT. -* ABS(IPRNT)=1-PRINT OF FINAL RESULTS. -* ABS(IPRNT)=2-PRINT OF FINAL RESULTS AND ITERATIONS. -* IPRNT>0-BASIC FINAL RESULTS. IPRNT<0-EXTENDED FINAL -* RESULTS. -* IO ITERM VARIABLE THAT INDICATES THE CAUSE OF TERMINATION. -* ITERM=1-IF ABS(X-XO) WAS LESS THAN OR EQUAL TO TOLX IN -* MTESX (USUALLY TWO) SUBSEQUEBT ITERATIONS. -* ITERM=2-IF ABS(F-FO) WAS LESS THAN OR EQUAL TO TOLF IN -* MTESF (USUALLY TWO) SUBSEQUEBT ITERATIONS. -* ITERM=3-IF F IS LESS THAN OR EQUAL TO TOLB. -* ITERM=4-IF GMAX IS LESS THAN OR EQUAL TO TOLG. -* ITERM=11-IF NIT EXCEEDED MIT. ITERM=12-IF NFV EXCEEDED MFV. -* ITERM=13-IF NFG EXCEEDED MFG. ITERM<0-IF THE METHOD FAILED. -* IF ITERM=-6, THEN THE TERMINATION CRITERION HAS NOT BEEN -* SATISFIED, BUT THE POINT OBTAINED IF USUALLY ACCEPTABLE. -* -* VARIABLES IN COMMON /STAT/ (STATISTICS) : -* IO NRES NUMBER OF RESTARTS. -* IO NDEC NUMBER OF MATRIX DECOMPOSITION. -* IO NREM NUMBER OF CONSTRAINT DELETIONS. -* IO NADD NUMBER OF CONSTRAINT ADDITIONS. -* IO NIT NUMBER OF ITERATIONS. -* IO NFV NUMBER OF FUNCTION EVALUATIONS. -* IO NFG NUMBER OF GRADIENT EVALUATIONS. -* IO NFH NUMBER OF HESSIAN EVALUATIONS. -* -* SUBPROGRAMS USED : -* S PSQP RECURSIVE QUADRATIC PROGRAMMING METHOD WITH THE BFGS -* VARIABLE METRIC UPDATE. -* -* EXTERNAL SUBROUTINES : -* SE OBJ COMPUTATION OF THE VALUE OF THE OBJECTIVE FUNCTION. -* CALLING SEQUENCE: CALL OBJ(NF,X,FF) WHERE NF IS THE NUMBER -* OF VARIABLES, X(NF) IS A VECTOR OF VARIABLES AND FF IS THE -* VALUE OF THE OBJECTIVE FUNCTION. -* SE DOBJ COMPUTATION OF THE GRADIENT OF THE OBJECTIVE FUNCTION. -* CALLING SEQUENCE: CALL DOBJ(NF,X,GF) WHERE NF IS THE NUMBER -* OF VARIABLES, X(NF) IS A VECTOR OF VARIABLES AND GC(NF) IS -* THE GRADIENT OF THE OBJECTIVE FUNCTION. -* SE CON COMPUTATION OF THE VALUE OF THE CONSTRAINT FUNCTION. -* CALLING SEQUENCE: CALL CON(NF,KC,X,FC) WHERE NF IS THE -* NUMBER OF VARIABLES, KC IS THE INDEX OF THE CONSTRAINT -* FUNCTION, X(NF) IS A VECTOR OF VARIABLES AND FC IS THE -* VALUE OF THE CONSTRAINT FUNCTION. -* SE DCON COMPUTATION OF THE GRADIENT OF THE CONSTRAINT FUNCTION. -* CALLING SEQUENCE: CALL DCON(NF,KC,X,GC) WHERE NF IS THE -* NUMBER OF VARIABLES, KC IS THE INDEX OF THE CONSTRAINT -* FUNCTION, X(NF) IS A VECTOR OF VARIABLES AND GC(NF) IS THE -* GRADIENT OF THE CONSTRAINT FUNCTION. -* -c$$$ SUBROUTINE PSQPN(NF,NB,NC,X,IX,XL,XU,CF,IC,CL,CU,IPAR,RPAR, -c$$$ + F,GMAX,CMAX,IPRNT,ITERM) -c$$$* -c$$$* POINTERS FOR AUXILIARY ARRAYS -c$$$* -c$$$ DOUBLE PRECISION F,CMAX,GMAX -c$$$ INTEGER IPRNT,ITERM,NB,NC,NF -c$$$ DOUBLE PRECISION CF(*),CL(*),CU(*),RPAR(5),X(*),XL(*),XU(*) -c$$$ INTEGER IC(*),IPAR(6),IX(*) -c$$$ INTEGER NADD,NDEC,NFG,NFH,NFV,NIT,NREM,NRES -c$$$ INTEGER LCFD,LCFO,LCG,LCP,LCR,LCZ,LG,LGC,LGF,LGO,LH,LIA, -c$$$ + LS,LXO -c$$$ COMMON /STAT/NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH -c$$$ INTEGER IA(:) -c$$$ DOUBLE PRECISION RA(:) -c$$$ ALLOCATABLE IA,RA -c$$$ ALLOCATE (IA(NF),RA((NF+NC+8)*NF+3*NC+1)) -c$$$ LCG = 1 -c$$$ LCFO = LCG + NF*NC -c$$$ LCFD = LCFO + NC + 1 -c$$$ LGC = LCFD + NC -c$$$ LCR = LGC + NF -c$$$ LCZ = LCR + NF*(NF+1)/2 -c$$$ LCP = LCZ + NF -c$$$ LGF = LCP + NC -c$$$ LG = LGF + NF -c$$$ LH = LG + NF -c$$$ LS = LH + NF* (NF+1)/2 -c$$$ LXO = LS + NF -c$$$ LGO = LXO + NF -c$$$ LIA = 1 -c$$$ CALL PSQP(NF,NB,NC,X,IX,XL,XU,CF,IC,CL,CU,RA,RA(LCFO),RA(LCFD), -c$$$ + RA(LGC),IA,RA(LCR),RA(LCZ),RA(LCP),RA(LGF),RA(LG), -c$$$ + RA(LH),RA(LS),RA(LXO),RA(LGO),RPAR(1),RPAR(2),RPAR(3), -c$$$ + RPAR(4),RPAR(5),CMAX,GMAX,F,IPAR(1),IPAR(2),IPAR(5), -c$$$ + IPAR(6),IPRNT,ITERM) -c$$$ DEALLOCATE(IA,RA) -c$$$ RETURN -c$$$ END -************************************************************************ -* SUBROUTINE PSQP ALL SYSTEMS 97/01/22 -* PURPOSE : -* RECURSIVE QUADRATIC PROGRAMMING METHOD WITH THE BFGS VARIABLE METRIC -* UPDATE FOR GENERAL NONLINEAR PROGRAMMING PROBLEMS. -* -* PARAMETERS : -* II NF NUMBER OF VARIABLES. -* II NB CHOICE OF SIMPLE BOUNDS. NB=0-SIMPLE BOUNDS SUPPRESSED. -* NB>0-SIMPLE BOUNDS ACCEPTED. -* II NC NUMBER OF LINEAR CONSTRAINTS. -* RI X(NF) VECTOR OF VARIABLES. -* II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. IX(I)=0-VARIABLE -* X(I) IS UNBOUNDED. IX(I)=1-LOVER BOUND XL(I).LE.X(I). -* IX(I)=2-UPPER BOUND X(I).LE.XU(I). IX(I)=3-TWO SIDE BOUND -* XL(I).LE.X(I).LE.XU(I). IX(I)=5-VARIABLE X(I) IS FIXED. -* RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -* RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -* RO CF(NC+1) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -* II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -* IC(KC)=0-CONSTRAINT CF(KC) IS NOT USED. IC(KC)=1-LOVER -* CONSTRAINT CL(KC).LE.CF(KC). IC(KC)=2-UPPER CONSTRAINT -* CF(KC).LE.CU(KC). IC(KC)=3-TWO SIDE CONSTRAINT -* CL(KC).LE.CF(KC).LE.CU(KC). IC(KC)=5-EQUALITY CONSTRAINT -* CF(KC).EQ.CL(KC). -* RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -* RI CG(NF*NC) MATRIX WHOSE COLUMNS ARE NORMALS OF THE LINEAR -* CONSTRAINTS. -* RA CFO(NC) VECTOR CONTAINING SAVED VALUES OF THE CONSTRAINT -* FUNCTIONS. -* RA CFD(NC) VECTOR CONTAINING INCREMENTS OF THE CONSTRAINT -* FUNCTIONS. -* RA GC(NF) GRADIENT OF THE SELECTED CONSTRAINT FUNCTION. -* IO ICA(NF) VECTOR CONTAINING INDICES OF ACTIVE CONSTRAINTS. -* RO CR(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OF KERNEL OF THE -* ORTHOGONAL PROJECTION. -* RO CZ(NF) VECTOR OF LAGRANGE MULTIPLIERS. -* RO GF(NF) GRADIENT OF THE MODEL FUNCTION. -* RO G(NF) GRADIENT OF THE OBJECTIVE FUNCTION. -* RU H(NF*(NF+1)/2) TRIANGULAR DECOMPOSITION OR INVERSION OF THE -* HESSIAN MATRIX APPROXIMATION. -* RO S(NF) DIRECTION VECTOR. -* RU XO(NF) VECTORS OF VARIABLES DIFFERENCE. -* RI GO(NF) GRADIENTS DIFFERENCE. -* RI XMAX MAXIMUM STEPSIZE. -* RI TOLX TOLERANCE FOR CHANGE OF VARIABLES. -* RI TOLC TOLERANCE FOR CONSTRAINT VIOLATIONS. -* RI TOLG TOLERANCE FOR THE GRADIENT OF THE LAGRANGIAN FUNCTION. -* RI RPF PENALTY COEFFICIENT. -* RO CMAX MAXIMUM CONSTRAINT VIOLATION. -* RO GMAX MAXIMUM PARTIAL DERIVATIVE OF THE LAGRANGIAN FUNCTION. -* RO F VALUE OF THE OBJECTIVE FUNCTION. -* FUNCTIONS. -* II MIT MAXIMUN NUMBER OF ITERATIONS. -* II MFV MAXIMUN NUMBER OF FUNCTION EVALUATIONS. -* II MET VARIABLE METRIC UPDATE USED. MET=1-THE BFGS UPDATE. -* MET=2-THE HOSHINO UPDATE. -* II MEC CORRECTION IF THE NEGATIVE CURVATURE OCCURS. -* MEC=1-CORRECTION SUPPRESSED. MEC=2-POWELL'S CORRECTION. -* II IPRNT PRINT SPECIFICATION. IPRNT=0-NO PRINT. -* ABS(IPRNT)=1-PRINT OF FINAL RESULTS. -* ABS(IPRNT)=2-PRINT OF FINAL RESULTS AND ITERATIONS. -* IPRNT>0-BASIC FINAL RESULTS. IPRNT<0-EXTENDED FINAL -* RESULTS. -* II IOUT PRINT OUTPUT UNIT NUMBER. -* IO ITERM VARIABLE THAT INDICATES THE CAUSE OF TERMINATION. -* ITERM=1-IF ABS(X-XO) WAS LESS THAN OR EQUAL TO TOLX IN -* MTESX (USUALLY TWO) SUBSEQUEBT ITERATIONS. -* ITERM=2-IF ABS(F-FO) WAS LESS THAN OR EQUAL TO TOLF IN -* MTESF (USUALLY TWO) SUBSEQUEBT ITERATIONS. -* ITERM=3-IF F IS LESS THAN OR EQUAL TO TOLB. -* ITERM=4-IF GMAX IS LESS THAN OR EQUAL TO TOLG. -* ITERM=11-IF NIT EXCEEDED MIT. ITERM=12-IF NFV EXCEEDED MFV. -* ITERM=13-IF NFG EXCEEDED MFG. ITERM<0-IF THE METHOD FAILED. -* IF ITERM=-6, THEN THE TERMINATION CRITERION HAS NOT BEEN -* SATISFIED, BUT THE POINT OBTAINED IF USUALLY ACCEPTABLE. -* -* VARIABLES IN COMMON /STAT/ (STATISTICS) : -* IO NRES NUMBER OF RESTARTS. -* IO NDEC NUMBER OF MATRIX DECOMPOSITION. -* IO NREM NUMBER OF CONSTRAINT DELETIONS. -* IO NADD NUMBER OF CONSTRAINT ADDITIONS. -* IO NIT NUMBER OF ITERATIONS. -* IO NFV NUMBER OF FUNCTION EVALUATIONS. -* IO NFG NUMBER OF GRADIENT EVALUATIONS. -* IO NFH NUMBER OF HESSIAN EVALUATIONS. -* -* SUBPROGRAMS USED : -* S PC1F01 COMPUTATION OF THE VALUE AND THE GRADIENT OF THE -* CONSTRAINT FUNCTION. -* S PF1F01 COMPUTATION OF THE VALUE AND THE GRADIENT OF THE -* OBJECTIVE FUNCTION. -* S PLQDB1 GENERAL QUADRATIC PROGRAMMING SUBROUTINE BASED ON THE -* GOLDFARB-IDNANI DUAL METHOD. -* S PLNEWS IDENTIFICATION OF ACTIVE SIMPLE BOUNDS. -* S PLREDL TRANSFORMATION OF THE INCOMPATIBLE QUADRATIC PROGRAMMING -* SUBPROBLEM. -* S PP0AF8 COMPUTATION OF VALUE OF THE AUGMENTED LAGRANGIAN -* FUNCTION. -* S PPSET2 COMPUTATION OF THE NEW PENALTY PARAMETERS. -* S PS0L02 LINE SEARCH USING ONLY FUNCTION VALUES. -* S PYTRND DETERMINATION OF DIFFERENCES FOR VARIABLE METRIC -* UPDATES. -* S PUDBG1 VARIABLE METRIC UPDATE AFTER GILL-MURRAY DECOMPOSITION. -* S MXDSMI SYMMETRIC MATRIX IS REPLACED BY THE UNIT MATRIX. -* S MXVDIR VECTOR AUGMENTED BY THE SCALED VECTOR. -* RF MXVDOT DOT PRODUCT OF TWO VECTORS. -* S MXVCOP COPYING OF A VECTOR. -* S MXVINA ABSOLUTE VALUES OF ELEMENTS OF AN INTEGER VECTOR. -* RF MXVMAX L-INFINITY NORM OF A VECTOR. -* S MXVSET INITIATION OF A VECTOR. -* -* EXTERNAL SUBROUTINES : -* SE OBJ COMPUTATION OF THE VALUE OF THE OBJECTIVE FUNCTION. -* CALLING SEQUENCE: CALL OBJ(NF,X,FF) WHERE NF IS THE NUMBER -* OF VARIABLES, X(NF) IS A VECTOR OF VARIABLES AND FF IS THE -* VALUE OF THE OBJECTIVE FUNCTION. -* SE DOBJ COMPUTATION OF THE GRADIENT OF THE OBJECTIVE FUNCTION. -* CALLING SEQUENCE: CALL DOBJ(NF,X,GF) WHERE NF IS THE NUMBER -* OF VARIABLES, X(NF) IS A VECTOR OF VARIABLES AND GC(NF) IS -* THE GRADIENT OF THE OBJECTIVE FUNCTION. -* SE CON COMPUTATION OF THE VALUE OF THE CONSTRAINT FUNCTION. -* CALLING SEQUENCE: CALL CON(NF,KC,X,FC) WHERE NF IS THE -* NUMBER OF VARIABLES, KC IS THE INDEX OF THE CONSTRAINT -* FUNCTION, X(NF) IS A VECTOR OF VARIABLES AND FC IS THE -* VALUE OF THE CONSTRAINT FUNCTION. -* SE DCON COMPUTATION OF THE GRADIENT OF THE CONSTRAINT FUNCTION. -* CALLING SEQUENCE: CALL DCON(NF,KC,X,GC) WHERE NF IS THE -* NUMBER OF VARIABLES, KC IS THE INDEX OF THE CONSTRAINT -* FUNCTION, X(NF) IS A VECTOR OF VARIABLES AND GC(NF) IS THE -* GRADIENT OF THE CONSTRAINT FUNCTION. -* -* METHOD : -* RECURSIVE QUADRATIC PROGRAMMING METHOD WITH THE BFGS VARIABLE METRIC -* UPDATE. -* - SUBROUTINE PSQP(NF,NB,NC,X,IX,XL,XU,CF,IC,CL,CU,CG,CFO,CFD,GC, - + ICA,CR,CZ,CP,GF,G,H,S,XO,GO,XMAX,TOLX,TOLC,TOLG, - + RPF,CMAX,GMAX,F,MIT,MFV,MET,MEC,IPRNT,IOUT,ITERM) - DOUBLE PRECISION F,CMAX,GMAX,RPF,TOLC,TOLD,TOLG,TOLS,TOLX,XMAX - INTEGER IPRNT,ITERM,MET,MET1,MEC,MES,MFV,MIT,NB,NC,NF - DOUBLE PRECISION CF(*),CFD(*),CFO(*),CG(*),CL(*),CP(*),CR(*), - + CZ(*),CU(*),G(*),GC(*),GF(*),GO(*),H(*),S(*), - + X(*),XL(*),XO(*),XU(*) - INTEGER IC(*),ICA(*),IX(*) - INTEGER NADD,NDEC,NFG,NFH,NFV,NIT,NREM,NRES - DOUBLE PRECISION ALF1,ALF2,CMAXO,DMAX,EPS7,EPS9,ETA0,ETA2,ETA9, - + FMAX,FMIN,FO,GNORM,P,PO,R,RMAX,RMIN,RO,SNORM, - + TOLB,TOLF,UMAX,RP,FP,PP,FF,FC - INTEGER I,IDECF,IEXT,IREST,ITERD,ITERL,ITERH,ITERQ,ITERS, - + KBC,KBF,KC,KD,KIT,LD,MRED,MTESF,MTESX,N,K, - + NTESX,IEST,INITS,KTERS,MAXST,ISYS,MFP,NRED,IPOM, - + LDS - DOUBLE PRECISION MXVDOT, MXVMAX - COMMON /STAT/NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - IF (ABS(IPRNT).GT.1) WRITE (IOUT,'(1X,''ENTRY TO PSQP :'')') -* -* INITIATION -* - KBF = 0 - KBC = 0 - IF (NB.GT.0) KBF = 2 - IF (NC.GT.0) KBC = 2 - NRES = 0 - NDEC = 0 - NREM = 0 - NADD = 0 - NIT = 0 - NFV = 0 - NFG = 0 - NFH = 0 - ISYS = 0 - IEST = 0 - IEXT = 0 - MTESX = 2 - MTESF = 2 - INITS = 1 - ITERM = 0 - ITERS = 0 - ITERD = 0 - ITERQ = 0 - MRED = 20 - IREST = 1 - ITERS = 2 - KTERS = 5 - IDECF = 1 - ETA0 = 1.0D-15 - ETA2 = 1.0D-15 - ETA9 = 1.0D60 - EPS7 = 1.0D-15 - EPS9 = 1.0D-8 - ALF1 = 1.0D-10 - ALF2 = 1.0D10 - FMAX = 1.0D60 - FMIN = -FMAX - TOLB = -FMAX - DMAX = ETA9 - TOLF = 1.0D-16 - IF (XMAX.LE.0.0D0) XMAX = 1.0D+16 - IF (TOLX.LE.0.0D0) TOLX = 1.0D-16 - IF (TOLG.LE.0.0D0) TOLG = 1.0D-6 - IF (TOLC.LE.0.0D0) TOLC = 1.0D-6 - TOLD = 1.0D-8 - TOLS = 1.0D-4 - IF (RPF.LE.0.0D0) RPF = 1.0D-4 - IF (MET.LE.0) MET = 1 - MET1 = 2 - IF (MEC.LE.0) MEC = 2 - MES = 1 - IF (MIT.LE.0) MIT = 1000 - IF (MFV.LE.0) MFV = 2000 - KD = 1 - LD = -1 - KIT = 0 - CALL MXVSET(NC,0.0D0,CP) -* -* INITIAL OPERATIONS WITH SIMPLE BOUNDS -* - IF (KBF.GT.0) THEN - DO 20 I = 1,NF - IF ((IX(I).EQ.3.OR.IX(I).EQ.4) .AND. XU(I).LE.XL(I)) THEN - XU(I) = XL(I) - IX(I) = 5 - ELSE IF (IX(I).EQ.5 .OR. IX(I).EQ.6) THEN - XL(I) = X(I) - XU(I) = X(I) - IX(I) = 5 - END IF - IF (IX(I).EQ.1 .OR. IX(I).EQ.3) X(I) = MAX(X(I),XL(I)) - IF (IX(I).EQ.2 .OR. IX(I).EQ.3) X(I) = MIN(X(I),XU(I)) - 20 CONTINUE - END IF -* INITIAL OPERATIONS WITH GENERAL CONSTRAINTS -* - IF (KBC.GT.0) THEN - K = 0 - DO 30 KC = 1,NC - IF ((IC(KC).EQ.3.OR.IC(KC).EQ.4) .AND. - + CU(KC).LE.CL(KC)) THEN - CU(KC) = CL(KC) - IC(KC) = 5 - ELSE IF (IC(KC).EQ.5 .OR. IC(KC).EQ.6) THEN - CU(KC) = CL(KC) - IC(KC) = 5 - END IF - K = K + NF - 30 CONTINUE - END IF - IF (KBF.GT.0) THEN - DO 31 I = 1,NF - IF (IX(I).GE.5) IX(I) = -IX(I) - IF (IX(I).LE.0) THEN - ELSE IF ((IX(I).EQ.1.OR.IX(I).EQ.3).AND.X(I).LE.XL(I)) - + THEN - X(I) = XL(I) - ELSE IF ((IX(I).EQ.2.OR.IX(I).EQ.3).AND.X(I).GE.XU(I)) - + THEN - X(I) = XU(I) - END IF - CALL PLNEWS(X,IX,XL,XU,EPS9,I,ITERL) - IF (IX(I).GT.10) IX(I) = 10 - IX(I) - 31 CONTINUE - END IF - FO = FMIN - GMAX = ETA9 - DMAX = ETA9 - 40 CONTINUE - LDS=LD - CALL PF1F01(NF,X,GF,GF,FF,F,KD,LD,IEXT) - LD=LDS - CALL PC1F01(NF,NC,X,FC,CF,CL,CU,IC,GC,CG,CMAX,KD,LD) - CF(NC+1)=F - IF (ABS(IPRNT).GT.1) - + WRITE (IOUT,'(1X,''NIT='',I4,2X,''NFV='',I4,2X,''NFG='',I4,2X, - + ''F='',G12.6,2X,''C='',E7.1,2X,''G='',E7.1)') - + NIT,NFV,NFG,F,CMAX,GMAX -* -* START OF THE ITERATION WITH TESTS FOR TERMINATION. -* - IF (ITERM.LT.0) GO TO 80 - IF (ITERS.EQ.0) GO TO 50 - IF (F.LE.TOLB) THEN - ITERM = 3 - GO TO 80 - END IF - IF (DMAX.LE.TOLX) THEN - ITERM = 1 - NTESX = NTESX + 1 - IF (NTESX.GE.MTESX) GO TO 80 - ELSE - NTESX = 0 - END IF - 50 IF (NIT.GE.MIT) THEN - ITERM = 11 - GO TO 80 - END IF - IF (NFV.GE.MFV) THEN - ITERM = 12 - GO TO 80 - END IF - ITERM = 0 - NIT = NIT + 1 - 60 CONTINUE -* -* RESTART -* - N = NF - IF (IREST.GT.0) THEN - CALL MXDSMI(N,H) - LD = MIN(LD,1) - IDECF = 1 - IF (KIT.LT.NIT) THEN - NRES = NRES + 1 - KIT = NIT - ELSE - ITERM = -10 - IF (ITERS.LT.0) ITERM = ITERS - 5 - GO TO 80 - END IF - END IF -* -* DIRECTION DETERMINATION USING A QUADRATIC PROGRAMMING PROCEDURE -* - CALL MXVCOP(NC+1,CF,CFO) - MFP=2 - IPOM=0 - 61 CONTINUE - CALL PLQDB1(NF,NC,X,IX,XL,XU,CF,CFD,IC,ICA,CL,CU,CG,CR,CZ,G,GF, - & H,S,MFP,KBF,KBC,IDECF,ETA2,ETA9,EPS7,EPS9,UMAX,GMAX, - & N,ITERQ) - IF (ITERQ.LT.0) THEN - IF (IPOM.LT.10) THEN - IPOM=IPOM+1 - CALL PLREDL(NC,CF,IC,CL,CU,KBC) - GO TO 61 - END IF - ITERD=ITERQ-10 - GO TO 62 - END IF - IPOM=0 - ITERD=1 - GMAX=MXVMAX(NF,G) - GNORM=SQRT(MXVDOT(NF,G,G)) - SNORM=SQRT(MXVDOT(NF,S,S)) - 62 CONTINUE - IF (ITERD.LT.0) ITERM = ITERD - IF (ITERM.NE.0) GO TO 80 - CALL MXVCOP(NC+1,CFO,CF) -* -* TEST FOR SUFFICIENT DESCENT -* - P = MXVDOT(NF,G,S) - IREST = 1 - IF (SNORM.LE.0.0D0) THEN - ELSE IF (P+TOLD*GNORM*SNORM.LE.0.0D0) THEN - IREST = 0 - END IF - IF (IREST.EQ.0) THEN - NRED = 0 - RMIN = ALF1*GNORM/SNORM - RMAX = MIN(ALF2*GNORM/SNORM,XMAX/SNORM) - ELSE - GO TO 60 - END IF - IF (GMAX.LE.TOLG.AND.CMAX.LE.TOLC) THEN - ITERM=4 - GO TO 80 - ENDIF - CALL PPSET2(NF,N,NC,ICA,CZ,CP) - CALL MXVINA(NC,IC) - CALL PP0AF8(NF,N,NC,CF,IC,ICA,CL,CU,CZ,RPF,FC,F) -* -* PREPARATION OF LINE SEARCH -* - RO = 0.0D0 - FO = F - PO = P - CMAXO = CMAX - CALL MXVCOP(NF,X,XO) - CALL MXVCOP(NF,G,GO) - CALL MXVCOP(NF,GF,CR) - CALL MXVCOP(NC+1,CF,CFO) -* -* LINE SEARCH WITHOUT DIRECTIONAL DERIVATIVES -* -11170 CONTINUE - CALL PS0L02(R,RO,RP,F,FO,FP,PO,PP,FMIN,FMAX,RMIN,RMAX, - & TOLS,KD,LD,NIT,KIT,NRED,MRED,MAXST,IEST,INITS,ITERS,KTERS, - & MES,ISYS) - IF (ISYS.EQ.0) GO TO 11174 -C GO TO (11174,11172) ISYS+1 -11172 CONTINUE - CALL MXVDIR(NF,R,S,XO,X) - LDS=LD - CALL PF1F01(NF,X,GF,G,FF,F,KD,LD,IEXT) - LD=LDS - CALL PC1F01(NF,NC,X,FC,CF,CL,CU,IC,GC,CG,CMAX,KD,LD) - CF(NC+1)=F - CALL PP0AF8(NF,N,NC,CF,IC,ICA,CL,CU,CZ,RPF,FC,F) - GO TO 11170 -11174 CONTINUE - KD=1 -* -* DECISION AFTER UNSUCCESSFUL LINE SEARCH -* - IF (ITERS.LE.0) THEN - R = 0.0D0 - F = FO - P = PO - CALL MXVCOP(NF,XO,X) - CALL MXVCOP(NF,CR,GF) - CALL MXVCOP(NC+1,CFO,CF) - IREST = 1 - LD = KD - GO TO 60 - END IF -* -* COMPUTATION OF THE VALUE AND THE GRADIENT OF THE OBJECTIVE -* FUNCTION TOGETHER WITH THE VALUES AND THE GRADIENTS OF THE -* APPROXIMATED FUNCTIONS -* - IF (KD.GT.LD) THEN - LDS=LD - CALL PF1F01(NF,X,GF,GF,FF,F,KD,LD,IEXT) - LD=LDS - CALL PC1F01(NF,NC,X,FC,CF,CL,CU,IC,GC,CG,CMAX,KD,LD) - END IF -* -* PREPARATION OF VARIABLE METRIC UPDATE -* - CALL MXVCOP(NF,GF,G) - CALL PYTRND(NF,N,X,XO,ICA,CG,CZ,G,GO,R,F,FO,P,PO,CMAX,CMAXO, - + DMAX,KD,LD,ITERS) -* -* VARIABLE METRIC UPDATE -* - CALL PUDBG1(N,H,G,S,XO,GO,R,PO,NIT,KIT,ITERH,MET,MET1,MEC) -C IF (MER.GT.0.AND.ITERH.GT.0) IREST=1 -* -* END OF THE ITERATION -* - GO TO 40 - - 80 IF (IPRNT.GT.1 .OR. IPRNT.LT.0) - + WRITE (IOUT,'(1X,''EXIT FROM PSQP :'')') - IF (IPRNT.NE.0) - + WRITE (IOUT,'(1X,''NIT='',I4,2X,''NFV='',I4,2X,''NFG='',I4,2X, - + ''F='',G12.6,2X,''C='',E7.1,2X,''G='',E7.1,2X,''ITERM='',I3)') - + NIT,NFV,NFG,F,CMAX,GMAX,ITERM - IF (IPRNT.LT.0) - + WRITE (IOUT,'(1X,''X='',5(G14.7,1X):/(3X,5(G14.7,1X)))') - + (X(I),I=1,NF) - RETURN - END diff --git a/pyoptsparse/pyoptsparse/pyPSQP/source/psqp_wrap.f90 b/pyoptsparse/pyoptsparse/pyPSQP/source/psqp_wrap.f90 deleted file mode 100644 index b42eb456b..000000000 --- a/pyoptsparse/pyoptsparse/pyPSQP/source/psqp_wrap.f90 +++ /dev/null @@ -1,170 +0,0 @@ -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -! SUBROUTINE PSQP_WRAP ALL SYSTEMS 2013/02/06 -! PURPOSE : -! WRAPPING SUBROUTINE FOR PSQP. -! -! PARAMETERS : -! II NF NUMBER OF VARIABLES. -! II NC NUMBER OF LINEAR CONSTRAINTS. -! RI X(NF) VECTOR OF VARIABLES. -! II IX(NF) VECTOR CONTAINING TYPES OF BOUNDS. IX(I)=0-VARIABLE -! X(I) IS UNBOUNDED. IX(I)=1-LOVER BOUND XL(I).LE.X(I). -! IX(I)=2-UPPER BOUND X(I).LE.XU(I). IX(I)=3-TWO SIDE BOUND -! XL(I).LE.X(I).LE.XU(I). IX(I)=5-VARIABLE X(I) IS FIXED. -! RI XL(NF) VECTOR CONTAINING LOWER BOUNDS FOR VARIABLES. -! RI XU(NF) VECTOR CONTAINING UPPER BOUNDS FOR VARIABLES. -! RI CF(NC+1) VECTOR CONTAINING VALUES OF THE CONSTRAINT FUNCTIONS. -! II IC(NC) VECTOR CONTAINING TYPES OF CONSTRAINTS. -! IC(KC)=0-CONSTRAINT CF(KC) IS NOT USED. IC(KC)=1-LOVER -! CONSTRAINT CL(KC).LE.CF(KC). IC(KC)=2-UPPER CONSTRAINT -! CF(KC).LE.CU(KC). IC(KC)=3-TWO SIDE CONSTRAINT -! CL(KC).LE.CF(KC).LE.CU(KC). IC(KC)=5-EQUALITY CONSTRAINT -! CF(KC).EQ.CL(KC). -! RI CL(NC) VECTOR CONTAINING LOWER BOUNDS FOR CONSTRAINT FUNCTIONS. -! RI CU(NC) VECTOR CONTAINING UPPER BOUNDS FOR CONSTRAINT FUNCTIONS. -! II MIT MAXIMUN NUMBER OF ITERATIONS. -! II MFV MAXIMUN NUMBER OF FUNCTION EVALUATIONS. -! II MET VARIABLE METRIC UPDATE USED. MET=1-THE BFGS UPDATE. -! MET=2-THE HOSHINO UPDATE. -! II MEC CORRECTION IF THE NEGATIVE CURVATURE OCCURS. -! MEC=1-CORRECTION SUPPRESSED. MEC=2-POWELL'S CORRECTION. -! RI XMAX MAXIMUM STEPSIZE. -! RI TOLX TOLERANCE FOR CHANGE OF VARIABLES. -! RI TOLC TOLERANCE FOR CONSTRAINT VIOLATIONS. -! RI TOLG TOLERANCE FOR THE GRADIENT OF THE LAGRANGIAN FUNCTION. -! RI RPF PENALTY COEFFICIENT. -! RO F VALUE OF THE OBJECTIVE FUNCTION. -! RO GMAX MAXIMUM PARTIAL DERIVATIVE OF THE LAGRANGIAN FUNCTION. -! RO CMAX MAXIMUM CONSTRAINT VIOLATION. -! II IPRNT PRINT SPECIFICATION. IPRNT=0-NO PRINT. -! ABS(IPRNT)=1-PRINT OF FINAL RESULTS. -! ABS(IPRNT)=2-PRINT OF FINAL RESULTS AND ITERATIONS. -! IPRNT>0-BASIC FINAL RESULTS. IPRNT<0-EXTENDED FINAL -! RESULTS. -! II IOUT PRINT OUTPUT UNIT NUMBER. -! II IFILE PRINT OUTPUT FILENAME. -! IO ITERM VARIABLE THAT INDICATES THE CAUSE OF TERMINATION. -! ITERM=1-IF ABS(X-XO) WAS LESS THAN OR EQUAL TO TOLX IN -! MTESX (USUALLY TWO) SUBSEQUEBT ITERATIONS. -! ITERM=2-IF ABS(F-FO) WAS LESS THAN OR EQUAL TO TOLF IN -! MTESF (USUALLY TWO) SUBSEQUEBT ITERATIONS. -! ITERM=3-IF F IS LESS THAN OR EQUAL TO TOLB. -! ITERM=4-IF GMAX IS LESS THAN OR EQUAL TO TOLG. -! ITERM=11-IF NIT EXCEEDED MIT. ITERM=12-IF NFV EXCEEDED MFV. -! ITERM=13-IF NFG EXCEEDED MFG. ITERM<0-IF THE METHOD FAILED. -! IF ITERM=-6, THEN THE TERMINATION CRITERION HAS NOT BEEN -! SATISFIED, BUT THE POINT OBTAINED IF USUALLY ACCEPTABLE. -! -! VARIABLES IN COMMON /STAT/ (STATISTICS) : -! IO NRES NUMBER OF RESTARTS. -! IO NDEC NUMBER OF MATRIX DECOMPOSITION. -! IO NREM NUMBER OF CONSTRAINT DELETIONS. -! IO NADD NUMBER OF CONSTRAINT ADDITIONS. -! IO NIT NUMBER OF ITERATIONS. -! IO NFV NUMBER OF FUNCTION EVALUATIONS. -! IO NFG NUMBER OF GRADIENT EVALUATIONS. -! IO NFH NUMBER OF HESSIAN EVALUATIONS. -! -! SUBPROGRAMS USED : -! S PSQP RECURSIVE QUADRATIC PROGRAMMING METHOD WITH THE BFGS -! VARIABLE METRIC UPDATE. -! -! EXTERNAL SUBROUTINES : -! SE OBJ COMPUTATION OF THE VALUE OF THE OBJECTIVE FUNCTION. -! CALLING SEQUENCE: CALL OBJ(NF,X,FF) WHERE NF IS THE NUMBER -! OF VARIABLES, X(NF) IS A VECTOR OF VARIABLES AND FF IS THE -! VALUE OF THE OBJECTIVE FUNCTION. -! SE DOBJ COMPUTATION OF THE GRADIENT OF THE OBJECTIVE FUNCTION. -! CALLING SEQUENCE: CALL DOBJ(NF,X,GF) WHERE NF IS THE NUMBER -! OF VARIABLES, X(NF) IS A VECTOR OF VARIABLES AND GC(NF) IS -! THE GRADIENT OF THE OBJECTIVE FUNCTION. -! SE CON COMPUTATION OF THE VALUE OF THE CONSTRAINT FUNCTION. -! CALLING SEQUENCE: CALL CON(NF,KC,X,FC) WHERE NF IS THE -! NUMBER OF VARIABLES, KC IS THE INDEX OF THE CONSTRAINT -! FUNCTION, X(NF) IS A VECTOR OF VARIABLES AND FC IS THE -! VALUE OF THE CONSTRAINT FUNCTION. -! SE DCON COMPUTATION OF THE GRADIENT OF THE CONSTRAINT FUNCTION. -! CALLING SEQUENCE: CALL DCON(NF,KC,X,GC) WHERE NF IS THE -! NUMBER OF VARIABLES, KC IS THE INDEX OF THE CONSTRAINT -! FUNCTION, X(NF) IS A VECTOR OF VARIABLES AND GC(NF) IS THE -! GRADIENT OF THE CONSTRAINT FUNCTION. -! -SUBROUTINE PSQP_WRAP(NF,NC,X,IX,XL,XU,CF,IC,CL,CU, & - MIT,MFV,MET,MEC,XMAX,TOLX,TOLC,TOLG,RPF, & - F,GMAX,CMAX,IPRNT,IOUT,IFILE,ITERM) - ! - ! POINTERS FOR AUXILIARY ARRAYS - ! - DOUBLE PRECISION XMAX,TOLX,TOLC,TOLG,RPF,F,CMAX,GMAX - INTEGER MIT,MFV,MET,MEC,IPRNT,IOUT,ITERM,NB,NC,NF - CHARACTER*(*) IFILE - DOUBLE PRECISION CF(NC+1),CL(NC),CU(NC) - DOUBLE PRECISION X(NF),XL(NF),XU(NF) - INTEGER IC(NC),IX(NF) - INTEGER NADD,NDEC,NFG,NFH,NFV,NIT,NREM,NRES - INTEGER LCFD,LCFO,LCG,LCP,LCR,LCZ,LG,LGC,LGF,LGO,LH,LIA,LS,LXO - COMMON /STAT/NRES,NDEC,NREM,NADD,NIT,NFV,NFG,NFH - ! - ! ALLOCATE WORKING ARRAYS - ! - INTEGER IA(:) - DOUBLE PRECISION RA(:) - ALLOCATABLE IA,RA - ALLOCATE (IA(NF),RA((NF+NC+8)*NF+3*NC+1)) - LCG = 1 - LCFO = LCG + NF*NC - LCFD = LCFO + NC + 1 - LGC = LCFD + NC - LCR = LGC + NF - LCZ = LCR + NF*(NF+1)/2 - LCP = LCZ + NF - LGF = LCP + NC - LG = LGF + NF - LH = LG + NF - LS = LH + NF* (NF+1)/2 - LXO = LS + NF - LGO = LXO + NF - LIA = 1 - ! - ! OPEN WRITE FILE - ! - IF (IPRNT.NE.0) THEN - OPEN(UNIT=IOUT,FILE=IFILE,STATUS='UNKNOWN') - END IF - ! - ! CALL PSQP - ! - NB = 1 - CALL PSQP(NF,NB,NC,X,IX,XL,XU,CF,IC,CL,CU,RA,RA(LCFO),RA(LCFD),& - RA(LGC),IA,RA(LCR),RA(LCZ),RA(LCP),RA(LGF),RA(LG),& - RA(LH),RA(LS),RA(LXO),RA(LGO),XMAX,TOLX,TOLC,& - TOLG,RPF,CMAX,GMAX,F,MIT,MFV,MET,& - MEC,IPRNT,IOUT,ITERM) - ! - ! CLOSE WRITE FILE - ! - IF (IPRNT.NE.0) THEN - CLOSE(IOUT) - END IF - ! - ! DEALLOCATE WORKING ARRAYS - ! - DEALLOCATE(IA,RA) - ! - -END SUBROUTINE PSQP_WRAP - -SUBROUTINE FUN(NF,KA,X,FA) - INTEGER KA,NF - DOUBLE PRECISION FA,X(*) - KA=NF - FA=X(1) - -end SUBROUTINE FUN - -SUBROUTINE DFUN(NF,KA,X,GA) - INTEGER KA,NF - DOUBLE PRECISION GA(*),X(*) - KA=NF - GA(1)=X(1) -end SUBROUTINE DFUN diff --git a/pyoptsparse/pyoptsparse/pySLSQP/LICENSE b/pyoptsparse/pyoptsparse/pySLSQP/LICENSE deleted file mode 100644 index 5043ebbe0..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -SLSQP - Sequential Least Squares Programming -Copyright (c) 1988, Dieter Kraft (kraft@hm.edu) -Copyright (c) 1994, Association for Computing Machinery -Patched for pyOpt - 2008, Ruben E. Perez (Ruben.Perez@rmc.ca) - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pyoptsparse/pyoptsparse/pySLSQP/README b/pyoptsparse/pyoptsparse/pySLSQP/README deleted file mode 100644 index facf7ffac..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the slsqp class definition -and the slsqp shared library, slsqp.so or slsqp.pyd. diff --git a/pyoptsparse/pyoptsparse/pySLSQP/__init__.py b/pyoptsparse/pyoptsparse/pySLSQP/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pySLSQP/pySLSQP.py b/pyoptsparse/pyoptsparse/pySLSQP/pySLSQP.py deleted file mode 100644 index b8531370f..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/pySLSQP.py +++ /dev/null @@ -1,291 +0,0 @@ -#/bin/env python -""" -pySLSQP - A variation of the pySLSQP wrapper specificially designed to -work with sparse optimization problems. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) - -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# SLSQP Library -# ============================================================================= -try: - from . import slsqp -except: - slsqp = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# =========================================================================== -# Extension modules -# =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -# ============================================================================= -# SLSQP Optimizer Class -# ============================================================================= -class SLSQP(Optimizer): - """ - SLSQP Optimizer Class - Inherited from Optimizer Abstract Class - """ - def __init__(self, *args, **kwargs): - name = 'SLSQP' - category = 'Local Optimizer' - defOpts = { - # SLSQP Options - 'ACC': [float, 1e-6], # Convergence Accurancy - 'MAXIT': [int, 500], # Maximum Iterations - 'IPRINT': [int, 1], # Output Level (<0 - None, 0 - Screen, 1 - File) - 'IOUT': [int, 6], # Output Unit Number - 'IFILE': [str, 'SLSQP.out'], # Output File Name - } - informs = { - -1 : "Gradient evaluation required (g & a)", - 0 : "Optimization terminated successfully.", - 1 : "Function evaluation required (f & c)", - 2 : "More equality constraints than independent variables", - 3 : "More than 3*n iterations in LSQ subproblem", - 4 : "Inequality constraints incompatible", - 5 : "Singular matrix E in LSQ subproblem", - 6 : "Singular matrix C in LSQ subproblem", - 7 : "Rank-deficient equality constraint subproblem HFTI", - 8 : "Positive directional derivative for linesearch", - 9 : "Iteration limit exceeded", - } - if slsqp is None: - raise Error('There was an error importing the compiled \ - slsqp module') - - self.set_options = [] - Optimizer.__init__(self, name, category, defOpts, informs, *args, - **kwargs) - - # SLSQP needs jacobians in dense format - self.jacType = 'dense2d' - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. To - explictly use pyOptSparse gradient class to do the - derivatives with finite differenes use \'FD\'. \'sens\' - may also be \'CS\' which will cause pyOptSpare to compute - the derivatives using the complex step method. Finally, - \'sens\' may be a python function handle which is expected - to compute the sensitivities directly. For expensive - function evaluations and/or problems with large numbers of - design variables this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is \'FD\' and 1e-40j when sens is \'CS\'. - - sensMode : str - Use \'pgc\' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in \'hotStart\' must be - **IDENTICAL** to the currently supplied \'optProb\'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from SLSQP does not match the history, function and - gradient evaluations revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - if len(optProb.constraints) == 0: - # If the user *actually* has an unconstrained problem, - # slsqp sort of chokes with that....it has to have at - # least one constraint. So we will add one - # automatically here: - self.unconstrained = True - optProb.dummyConstraint = True - - # Save the optimization problem and finalize constraint - # jacobian, in general can only do on root proc - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - self._setInitialCacheValues() - self._setSens(sens, sensStep, sensMode) - blx, bux, xs = self._assembleContinuousVariables() - xs = numpy.maximum(xs, blx) - xs = numpy.minimum(xs, bux) - n = len(xs) - ff = self._assembleObjective() - - oneSided = True - # Set the number of nonlinear constraints snopt *thinks* we have: - if self.unconstrained: - m = 0 - meq = 0 - else: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'le', 'ni', 'li'], oneSided=oneSided) - m = len(indices) - - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = buc - - # Also figure out the number of equality: - tmp0, __, __, __ = self.optProb.getOrdering( - ['ne', 'le'], oneSided=oneSided) - meq = len(tmp0) - - if self.optProb.comm.rank == 0: - # Set history/hotstart - self._setHistory(storeHistory, hotStart) - - #================================================================= - # SLSQP - Objective/Constraint Values Function - #================================================================= - def slfunc(m, me, la, n, f, g, x): - fobj, fcon, fail = self._masterFunc(x, ['fobj', 'fcon']) - f = fobj - g[0:m] = -fcon - slsqp.pyflush(self.getOption('IOUT')) - return f, g - - #================================================================= - # SLSQP - Objective/Constraint Gradients Function - #================================================================= - def slgrad(m, me, la, n, f, g, df, dg, x): - gobj, gcon, fail = self._masterFunc(x, ['gobj', 'gcon']) - df[0:n] = gobj.copy() - dg[0:m, 0:n] = -gcon.copy() - slsqp.pyflush(self.getOption('IOUT')) - return df, dg - - # Setup argument list values - la = max(m, 1) - gg = numpy.zeros([la], numpy.float) - n1 = numpy.array([n+1], numpy.int) - df = numpy.zeros([n+1], numpy.float) - dg = numpy.zeros([la, n+1], numpy.float) - acc = numpy.array([self.getOption('ACC')], numpy.float) - maxit = self.getOption('MAXIT') - iprint = self.getOption('IPRINT') - iout = self.getOption('IOUT') - ifile = self.getOption('IFILE') - if iprint >= 0: - if os.path.isfile(ifile): - os.remove(ifile) - - mode = 0 - mineq = m - meq + 2*(n+1) - lsq = (n+1)*((n+1)+1) + meq*((n+1)+1) + mineq*((n+1)+1) - lsi = ((n+1)-meq+1)*(mineq+2) + 2*mineq - lsei = ((n+1)+mineq)*((n+1)-meq) + 2*meq + (n+1) - slsqpb = (n+1)*(n/2) + 2*m + 3*n + 3*(n+1) + 1 - lwM = lsq + lsi + lsei + slsqpb + n + m - lw = numpy.array([lwM], numpy.int) - w = numpy.zeros(lw, numpy.float) - ljwM = max(mineq, (n+1)-meq) - ljw = numpy.array([ljwM], numpy.int) - jw = numpy.zeros(ljw, numpy.intc) - nfunc = numpy.array([0], numpy.int) - ngrad = numpy.array([0], numpy.int) - - # Run SLSQP - t0 = time.time() - slsqp.slsqp(m, meq, la, n, xs, blx, bux, ff, gg, df, dg, acc, maxit, - iprint, iout, ifile, mode, w, lw, jw, ljw, nfunc, - ngrad, slfunc, slgrad) - optTime = time.time() - t0 - - #some entries of W include the lagrange multipliers - # for each constraint, there are two entries (lower, upper). - # if only one is active, look for the nonzero. If both are active, take the first one - pi = [] - idx = 0 - - for c_name in optProb.constraints: - c = optProb.constraints[c_name] - for j in range(c.ncon): - pi_lower = w[2*idx] - pi_upper = w[2*idx+1] - if abs(pi_lower) > 1e-100: - pi.append(pi_lower) - else: - pi.append(pi_upper) - idx += 1 - - - - - if self.storeHistory: - self.hist.close() - - if iprint > 0: - slsqp.closeunit(self.getOption('IOUT')) - - # Broadcast a -1 to indcate SLSQP has finished - self.optProb.comm.bcast(-1, root=0) - - # Store Results - sol_inform = {} - #sol_inform['value'] = inform - #sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - sol.pi = pi - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _on_setOption(self, name, value): - pass - - def _on_getOption(self, name, value): - pass diff --git a/pyoptsparse/pyoptsparse/pySLSQP/setup.py b/pyoptsparse/pyoptsparse/pySLSQP/setup.py deleted file mode 100644 index 77b0157c3..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/setup.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pySLSQP',parent_package,top_path) - - config.add_library('slsqp', - sources=[os.path.join('source', '*.f')]) - config.add_extension('slsqp', - sources=['source/f2py/slsqp.pyf'], - libraries=['slsqp']) - config.add_data_files('LICENSE','README') - - return config - - -if __name__ == '__main__': - from numpy.distutils.core import setup - setup(**configuration(top_path='').todict()) - diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/README b/pyoptsparse/pyoptsparse/pySLSQP/source/README deleted file mode 100644 index 9b85b0b97..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains the Fortran 77 source for -SLSQP, plus two helper files called openunit.f and -closeunit.f to manipulate Fortran units from Python. diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/closeunit.f b/pyoptsparse/pyoptsparse/pySLSQP/source/closeunit.f deleted file mode 100644 index f1d9f8377..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/closeunit.f +++ /dev/null @@ -1,10 +0,0 @@ -C Helper subroutine to close files in the Fortran world - subroutine closeunit(unitnum) - - integer unitnum -Cf2py intent(in) unitnum - - close(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/daxpy.f b/pyoptsparse/pyoptsparse/pySLSQP/source/daxpy.f deleted file mode 100644 index e21693c07..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/daxpy.f +++ /dev/null @@ -1,47 +0,0 @@ - SUBROUTINE DAXPY(N,DA,DX,INCX,DY,INCY) - -C CONSTANT TIMES A VECTOR PLUS A VECTOR. -C USES UNROLLED LOOPS FOR INCREMENTS EQUAL TO ONE. -C JACK DONGARRA, LINPACK, 3/11/78. - - DOUBLE PRECISION DX(*),DY(*),DA - INTEGER I,INCX,INCY,IX,IY,M,MP1,N - - IF(N.LE.0)RETURN - IF(DA.EQ.0.0D0)RETURN - IF(INCX.EQ.1.AND.INCY.EQ.1)GO TO 20 - -C CODE FOR UNEQUAL INCREMENTS OR EQUAL INCREMENTS -C NOT EQUAL TO 1 - - IX = 1 - IY = 1 - IF(INCX.LT.0)IX = (-N+1)*INCX + 1 - IF(INCY.LT.0)IY = (-N+1)*INCY + 1 - DO 10 I = 1,N - DY(IY) = DY(IY) + DA*DX(IX) - IX = IX + INCX - IY = IY + INCY - 10 CONTINUE - RETURN - -C CODE FOR BOTH INCREMENTS EQUAL TO 1 - -C CLEAN-UP LOOP - - 20 M = MOD(N,4) - IF( M .EQ. 0 ) GO TO 40 - DO 30 I = 1,M - DY(I) = DY(I) + DA*DX(I) - 30 CONTINUE - IF( N .LT. 4 ) RETURN - 40 MP1 = M + 1 - DO 50 I = MP1,N,4 - DY(I) = DY(I) + DA*DX(I) - DY(I + 1) = DY(I + 1) + DA*DX(I + 1) - DY(I + 2) = DY(I + 2) + DA*DX(I + 2) - DY(I + 3) = DY(I + 3) + DA*DX(I + 3) - 50 CONTINUE - RETURN - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/dcopy.f b/pyoptsparse/pyoptsparse/pySLSQP/source/dcopy.f deleted file mode 100644 index b9aa02b60..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/dcopy.f +++ /dev/null @@ -1,254 +0,0 @@ - SUBROUTINE DCOPY(N,DX,INCX,DY,INCY) - -C COPIES A VECTOR, X, TO A VECTOR, Y. -C USES UNROLLED LOOPS FOR INCREMENTS EQUAL TO ONE. -C JACK DONGARRA, LINPACK, 3/11/78. - - DOUBLE PRECISION DX(*),DY(*) - INTEGER I,INCX,INCY,IX,IY,M,MP1,N - - IF(N.LE.0)RETURN - IF(INCX.EQ.1.AND.INCY.EQ.1)GO TO 20 - -C CODE FOR UNEQUAL INCREMENTS OR EQUAL INCREMENTS -C NOT EQUAL TO 1 - - IX = 1 - IY = 1 - IF(INCX.LT.0)IX = (-N+1)*INCX + 1 - IF(INCY.LT.0)IY = (-N+1)*INCY + 1 - DO 10 I = 1,N - DY(IY) = DX(IX) - IX = IX + INCX - IY = IY + INCY - 10 CONTINUE - RETURN - -C CODE FOR BOTH INCREMENTS EQUAL TO 1 - -C CLEAN-UP LOOP - - 20 M = MOD(N,7) - IF( M .EQ. 0 ) GO TO 40 - DO 30 I = 1,M - DY(I) = DX(I) - 30 CONTINUE - IF( N .LT. 7 ) RETURN - 40 MP1 = M + 1 - DO 50 I = MP1,N,7 - DY(I) = DX(I) - DY(I + 1) = DX(I + 1) - DY(I + 2) = DX(I + 2) - DY(I + 3) = DX(I + 3) - DY(I + 4) = DX(I + 4) - DY(I + 5) = DX(I + 5) - DY(I + 6) = DX(I + 6) - 50 CONTINUE - RETURN - END - - DOUBLE PRECISION FUNCTION DDOT(N,DX,INCX,DY,INCY) - -C FORMS THE DOT PRODUCT OF TWO VECTORS. -C USES UNROLLED LOOPS FOR INCREMENTS EQUAL TO ONE. -C JACK DONGARRA, LINPACK, 3/11/78. - - DOUBLE PRECISION DX(*),DY(*),DTEMP - INTEGER I,INCX,INCY,IX,IY,M,MP1,N - - DDOT = 0.0D0 - DTEMP = 0.0D0 - IF(N.LE.0)RETURN - IF(INCX.EQ.1.AND.INCY.EQ.1)GO TO 20 - -C CODE FOR UNEQUAL INCREMENTS OR EQUAL INCREMENTS -C NOT EQUAL TO 1 - - IX = 1 - IY = 1 - IF(INCX.LT.0)IX = (-N+1)*INCX + 1 - IF(INCY.LT.0)IY = (-N+1)*INCY + 1 - DO 10 I = 1,N - DTEMP = DTEMP + DX(IX)*DY(IY) - IX = IX + INCX - IY = IY + INCY - 10 CONTINUE - DDOT = DTEMP - RETURN - -C CODE FOR BOTH INCREMENTS EQUAL TO 1 - -C CLEAN-UP LOOP - - 20 M = MOD(N,5) - IF( M .EQ. 0 ) GO TO 40 - DO 30 I = 1,M - DTEMP = DTEMP + DX(I)*DY(I) - 30 CONTINUE - IF( N .LT. 5 ) GO TO 60 - 40 MP1 = M + 1 - DO 50 I = MP1,N,5 - DTEMP = DTEMP + DX(I)*DY(I) + DX(I + 1)*DY(I + 1) + - * DX(I + 2)*DY(I + 2) + DX(I + 3)*DY(I + 3) + DX(I + 4)*DY(I + 4) - 50 CONTINUE - 60 DDOT = DTEMP - RETURN - END - - DOUBLE PRECISION FUNCTION DNRM1(N,X,I,J) - INTEGER N, I, J, K - DOUBLE PRECISION SNORMX, SUM, X(N), ZERO, ONE, SCALE, TEMP - DATA ZERO/0.0D0/, ONE/1.0D0/ - -C DNRM1 - COMPUTES THE I-NORM OF A VECTOR -C BETWEEN THE ITH AND THE JTH ELEMENTS - -C INPUT - -C N LENGTH OF VECTOR -C X VECTOR OF LENGTH N -C I INITIAL ELEMENT OF VECTOR TO BE USED -C J FINAL ELEMENT TO USE - -C OUTPUT - -C DNRM1 NORM - - SNORMX=ZERO - DO 10 K=I,J - 10 SNORMX=MAX(SNORMX,ABS(X(K))) - DNRM1 = SNORMX - IF (SNORMX.EQ.ZERO) RETURN - SCALE = SNORMX - IF (SNORMX.GE.ONE) SCALE=SQRT(SNORMX) - SUM=ZERO - DO 20 K=I,J - TEMP=ZERO - IF (ABS(X(K))+SCALE .NE. SCALE) TEMP = X(K)/SNORMX - IF (ONE+TEMP.NE.ONE) SUM = SUM+TEMP*TEMP - 20 CONTINUE - SUM=SQRT(SUM) - DNRM1=SNORMX*SUM - RETURN - END - - DOUBLE PRECISION FUNCTION DNRM2 ( N, DX, INCX) - INTEGER N, I, J, NN, NEXT, INCX - DOUBLE PRECISION DX(*), CUTLO, CUTHI, HITEST, SUM, XMAX, ZERO, ONE - DATA ZERO, ONE /0.0D0, 1.0D0/ - -C EUCLIDEAN NORM OF THE N-VECTOR STORED IN DX() WITH STORAGE -C INCREMENT INCX . -C IF N .LE. 0 RETURN WITH RESULT = 0. -C IF N .GE. 1 THEN INCX MUST BE .GE. 1 - -C C.L.LAWSON, 1978 JAN 08 - -C FOUR PHASE METHOD USING TWO BUILT-IN CONSTANTS THAT ARE -C HOPEFULLY APPLICABLE TO ALL MACHINES. -C CUTLO = MAXIMUM OF SQRT(U/EPS) OVER ALL KNOWN MACHINES. -C CUTHI = MINIMUM OF SQRT(V) OVER ALL KNOWN MACHINES. -C WHERE -C EPS = SMALLEST NO. SUCH THAT EPS + 1. .GT. 1. -C U = SMALLEST POSITIVE NO. (UNDERFLOW LIMIT) -C V = LARGEST NO. (OVERFLOW LIMIT) - -C BRIEF OUTLINE OF ALGORITHM.. - -C PHASE 1 SCANS ZERO COMPONENTS. -C MOVE TO PHASE 2 WHEN A COMPONENT IS NONZERO AND .LE. CUTLO -C MOVE TO PHASE 3 WHEN A COMPONENT IS .GT. CUTLO -C MOVE TO PHASE 4 WHEN A COMPONENT IS .GE. CUTHI/M -C WHERE M = N FOR X() REAL AND M = 2*N FOR COMPLEX. - -C VALUES FOR CUTLO AND CUTHI.. -C FROM THE ENVIRONMENTAL PARAMETERS LISTED IN THE IMSL CONVERTER -C DOCUMENT THE LIMITING VALUES ARE AS FOLLOWS.. -C CUTLO, S.P. U/EPS = 2**(-102) FOR HONEYWELL. CLOSE SECONDS ARE -C UNIVAC AND DEC AT 2**(-103) -C THUS CUTLO = 2**(-51) = 4.44089E-16 -C CUTHI, S.P. V = 2**127 FOR UNIVAC, HONEYWELL, AND DEC. -C THUS CUTHI = 2**(63.5) = 1.30438E19 -C CUTLO, D.P. U/EPS = 2**(-67) FOR HONEYWELL AND DEC. -C THUS CUTLO = 2**(-33.5) = 8.23181D-11 -C CUTHI, D.P. SAME AS S.P. CUTHI = 1.30438D19 -C DATA CUTLO, CUTHI / 8.232D-11, 1.304D19 / -C DATA CUTLO, CUTHI / 4.441E-16, 1.304E19 / - DATA CUTLO, CUTHI / 8.232D-11, 1.304D19 / - - IF(N .GT. 0) GO TO 10 - DNRM2 = ZERO - GO TO 300 - - 10 ASSIGN 30 TO NEXT - SUM = ZERO - NN = N * INCX -C BEGIN MAIN LOOP - I = 1 - 20 GO TO NEXT,(30, 50, 70, 110) - 30 IF( ABS(DX(I)) .GT. CUTLO) GO TO 85 - ASSIGN 50 TO NEXT - XMAX = ZERO - -C PHASE 1. SUM IS ZERO - - 50 IF( DX(I) .EQ. ZERO) GO TO 200 - IF( ABS(DX(I)) .GT. CUTLO) GO TO 85 - -C PREPARE FOR PHASE 2. - - ASSIGN 70 TO NEXT - GO TO 105 - -C PREPARE FOR PHASE 4. - - 100 I = J - ASSIGN 110 TO NEXT - SUM = (SUM / DX(I)) / DX(I) - 105 XMAX = ABS(DX(I)) - GO TO 115 - -C PHASE 2. SUM IS SMALL. -C SCALE TO AVOID DESTRUCTIVE UNDERFLOW. - - 70 IF( ABS(DX(I)) .GT. CUTLO ) GO TO 75 - -C COMMON CODE FOR PHASES 2 AND 4. -C IN PHASE 4 SUM IS LARGE. SCALE TO AVOID OVERFLOW. - - 110 IF( ABS(DX(I)) .LE. XMAX ) GO TO 115 - SUM = ONE + SUM * (XMAX / DX(I))**2 - XMAX = ABS(DX(I)) - GO TO 200 - - 115 SUM = SUM + (DX(I)/XMAX)**2 - GO TO 200 - -C PREPARE FOR PHASE 3. - - 75 SUM = (SUM * XMAX) * XMAX - -C FOR REAL OR D.P. SET HITEST = CUTHI/N -C FOR COMPLEX SET HITEST = CUTHI/(2*N) - - 85 HITEST = CUTHI/FLOAT( N ) - -C PHASE 3. SUM IS MID-RANGE. NO SCALING. - - DO 95 J =I,NN,INCX - IF(ABS(DX(J)) .GE. HITEST) GO TO 100 - 95 SUM = SUM + DX(J)**2 - DNRM2 = SQRT( SUM ) - GO TO 300 - - 200 CONTINUE - I = I + INCX - IF ( I .LE. NN ) GO TO 20 - -C END OF MAIN LOOP. - -C COMPUTE SQUARE ROOT AND ADJUST FOR SCALING. - - DNRM2 = XMAX * SQRT(SUM) - 300 CONTINUE - RETURN - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/drot.f b/pyoptsparse/pyoptsparse/pySLSQP/source/drot.f deleted file mode 100644 index 77df1e46c..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/drot.f +++ /dev/null @@ -1,37 +0,0 @@ - SUBROUTINE DROT (N,DX,INCX,DY,INCY,C,S) - -C APPLIES A PLANE ROTATION. -C JACK DONGARRA, LINPACK, 3/11/78. - - DOUBLE PRECISION DX(*),DY(*),DTEMP,C,S - INTEGER I,INCX,INCY,IX,IY,N - - IF(N.LE.0)RETURN - IF(INCX.EQ.1.AND.INCY.EQ.1)GO TO 20 - -C CODE FOR UNEQUAL INCREMENTS OR EQUAL INCREMENTS NOT EQUAL -C TO 1 - - IX = 1 - IY = 1 - IF(INCX.LT.0)IX = (-N+1)*INCX + 1 - IF(INCY.LT.0)IY = (-N+1)*INCY + 1 - DO 10 I = 1,N - DTEMP = C*DX(IX) + S*DY(IY) - DY(IY) = C*DY(IY) - S*DX(IX) - DX(IX) = DTEMP - IX = IX + INCX - IY = IY + INCY - 10 CONTINUE - RETURN - -C CODE FOR BOTH INCREMENTS EQUAL TO 1 - - 20 DO 30 I = 1,N - DTEMP = C*DX(I) + S*DY(I) - DY(I) = C*DY(I) - S*DX(I) - DX(I) = DTEMP - 30 CONTINUE - RETURN - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/drotg.f b/pyoptsparse/pyoptsparse/pySLSQP/source/drotg.f deleted file mode 100644 index 30fa7c1b6..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/drotg.f +++ /dev/null @@ -1,28 +0,0 @@ - SUBROUTINE DROTG(DA,DB,C,S) - -C CONSTRUCT GIVENS PLANE ROTATION. -C JACK DONGARRA, LINPACK, 3/11/78. -C MODIFIED 9/27/86. - - DOUBLE PRECISION DA,DB,C,S,ROE,SCALE,R,Z,ONE,ZERO - DATA ONE, ZERO /1.0D+00, 0.0D+00/ - - ROE = DB - IF( ABS(DA) .GT. ABS(DB) ) ROE = DA - SCALE = ABS(DA) + ABS(DB) - IF( SCALE .NE. ZERO ) GO TO 10 - C = ONE - S = ZERO - R = ZERO - GO TO 20 - 10 R = SCALE*SQRT((DA/SCALE)**2 + (DB/SCALE)**2) - R = SIGN(ONE,ROE)*R - C = DA/R - S = DB/R - 20 Z = S - IF( ABS(C) .GT. ZERO .AND. ABS(C) .LE. S ) Z = ONE/C - DA = R - DB = Z - RETURN - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/dscal.f b/pyoptsparse/pyoptsparse/pySLSQP/source/dscal.f deleted file mode 100644 index 2e7811cfb..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/dscal.f +++ /dev/null @@ -1,41 +0,0 @@ - SUBROUTINE DSCAL(N,DA,DX,INCX) - -C SCALES A VECTOR BY A CONSTANT. -C USES UNROLLED LOOPS FOR INCREMENT EQUAL TO ONE. -C JACK DONGARRA, LINPACK, 3/11/78. - - DOUBLE PRECISION DA,DX(*) - INTEGER I,INCX,M,MP1,N,NINCX - - IF(N.LE.0)RETURN - IF(INCX.EQ.1)GO TO 20 - -C CODE FOR INCREMENT NOT EQUAL TO 1 - - NINCX = N*INCX - DO 10 I = 1,NINCX,INCX - DX(I) = DA*DX(I) - 10 CONTINUE - RETURN - -C CODE FOR INCREMENT EQUAL TO 1 - -C CLEAN-UP LOOP - - 20 M = MOD(N,5) - IF( M .EQ. 0 ) GO TO 40 - DO 30 I = 1,M - DX(I) = DA*DX(I) - 30 CONTINUE - IF( N .LT. 5 ) RETURN - 40 MP1 = M + 1 - DO 50 I = MP1,N,5 - DX(I) = DA*DX(I) - DX(I + 1) = DA*DX(I + 1) - DX(I + 2) = DA*DX(I + 2) - DX(I + 3) = DA*DX(I + 3) - DX(I + 4) = DA*DX(I + 4) - 50 CONTINUE - RETURN - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/README b/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/README deleted file mode 100644 index 54e48d046..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the f2py signature file. -Do not edit these file unless you really know what you are doing. diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/slsqp.pyf b/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/slsqp.pyf deleted file mode 100644 index 14edad205..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/slsqp.pyf +++ /dev/null @@ -1,72 +0,0 @@ -! -*- f90 -*- -! Note: the context of this file is case sensitive. - -python module slsqp__user__routines - interface slsqp_user_interface - subroutine slfunc(m,meq,la,n,f,c,x) - integer intent(in) :: m - integer intent(in) :: meq - integer intent(in) :: la - integer intent(in) :: n - double precision intent(in,out) :: f - double precision dimension(la),intent(in,out),depend(la) :: c - double precision dimension(n),intent(in),depend(n) :: x - end subroutine slfunc - subroutine slgrad(m,meq,la,n,f,c,g,a,x) - integer intent(in) :: m - integer intent(in) :: meq - integer intent(in) :: la - integer intent(in) :: n - double precision intent(in) :: f - double precision dimension(la),intent(in),depend(la) :: c - double precision dimension(n+1),depend(n),intent(in,out) :: g - double precision dimension(la,n+1),depend(la,n),intent(in,out) :: a - double precision dimension(n),depend(n),intent(in) :: x - end subroutine slgrad - end interface slsqp_user_interface -end python module slsqp__user__routines -python module slsqp ! in - interface ! in :slsqp - subroutine slsqp(m,meq,la,n,x,xl,xu,f,c,g,a,acc,iter,iprint,iout,ifile,mode,w,l_w,jw,l_jw,nfunc,ngrad,slfunc,slgrad) ! in :slsqp:source/slsqp.f - use slsqp__user__routines - integer intent(in) :: m - integer intent(in) :: meq - integer intent(in) :: la - integer intent(in) :: n - double precision dimension(n),intent(inout),depend(n) :: x - double precision dimension(n),intent(in),depend(n) :: xl - double precision dimension(n),intent(in),depend(n) :: xu - double precision intent(inout) :: f - double precision dimension(la),depend(la),intent(inout) :: c - double precision dimension(n+1),depend(n),intent(inout) :: g - double precision dimension(la,n+1),depend(la,n),intent(in,out) :: a - double precision intent(in) :: acc - integer intent(inout) :: iter - integer intent(in) :: iprint - integer intent(in) :: iout - character*(*) intent(in) :: ifile - integer intent(inout) :: mode - double precision dimension(l_w),intent(inout),depend(l_w) :: w - integer intent(in) :: l_w - integer dimension(l_jw),intent(inout),depend(l_jw) :: jw - integer intent(in) :: l_jw - integer intent(inout) :: nfunc - integer intent(inout) :: ngrad - external slfunc - external slgrad - end subroutine slsqp - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) ! in :slsqp:source/openunit.f - integer intent(in) :: unitnum - character*(*) intent(in) :: filename - character*(*) intent(in) :: filestatus - character*(*) intent(in) :: fileaction - integer intent(out) :: ierror - end subroutine openunit - subroutine pyflush(unitnum) ! in :slsqp:source/openunit.f - integer :: unitnum - end subroutine pyflush - subroutine closeunit(unitnum) ! in :slsqp:source/closeunit.f - integer intent(in) :: unitnum - end subroutine closeunit - end interface -end python module slsqp diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/slsqpmodule.c b/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/slsqpmodule.c deleted file mode 100644 index ed847c455..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/f2py/slsqpmodule.c +++ /dev/null @@ -1,1622 +0,0 @@ -/* File: slsqpmodule.c - * This file is auto-generated with f2py (version:2). - * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition, - * written by Pearu Peterson . - * See http://cens.ioc.ee/projects/f2py2e/ - * Generation date: Thu Jan 16 20:14:53 2014 - * $Revision:$ - * $Date:$ - * Do not edit this file directly unless you know what you are doing!!! - */ -#ifdef __cplusplus -extern "C" { -#endif - -/*********************** See f2py2e/cfuncs.py: includes ***********************/ -#include "Python.h" -#include -#include "fortranobject.h" -#include -#include - -/**************** See f2py2e/rules.py: mod_rules['modulebody'] ****************/ -static PyObject *slsqp_error; -static PyObject *slsqp_module; - -/*********************** See f2py2e/cfuncs.py: typedefs ***********************/ -typedef char * string; -typedef signed char signed_char; - -/****************** See f2py2e/cfuncs.py: typedefs_generated ******************/ -typedef void(*cb_slgrad_in_slsqp__user__routines_typedef)(int *,int *,int *,int *,double *,double *,double *,double *,double *); -typedef void(*cb_slfunc_in_slsqp__user__routines_typedef)(int *,int *,int *,int *,double *,double *,double *); - -/********************** See f2py2e/cfuncs.py: cppmacros **********************/ -#ifndef max -#define max(a,b) ((a > b) ? (a) : (b)) -#endif -#ifndef min -#define min(a,b) ((a < b) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a,b) ((a > b) ? (a) : (b)) -#endif -#ifndef MIN -#define MIN(a,b) ((a < b) ? (a) : (b)) -#endif - -#define STRINGMALLOC(str,len)\ - if ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\ - PyErr_SetString(PyExc_MemoryError, "out of memory");\ - goto capi_fail;\ - } else {\ - (str)[len] = '\0';\ - } - -#define PRINTPYOBJERR(obj)\ - fprintf(stderr,"slsqp.error is related to ");\ - PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\ - fprintf(stderr,"\n"); - -\ -#define FAILNULL(p) do { \ - if ((p) == NULL) { \ - PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \ - goto capi_fail; \ - } \ -} while (0) - -#define pyobj_from_int1(v) (PyInt_FromLong(v)) -#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\ - if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\ - if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\ - goto capi_fail;\ - } - -#define pyobj_from_double1(v) (PyFloat_FromDouble(v)) -#define MEMCOPY(to,from,n)\ - do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0) - -#ifdef DEBUGCFUNCS -#define CFUNCSMESS(mess) fprintf(stderr,"debug-capi:"mess); -#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \ - PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\ - fprintf(stderr,"\n"); -#else -#define CFUNCSMESS(mess) -#define CFUNCSMESSPY(mess,obj) -#endif - -#if defined(PREPEND_FORTRAN) -#if defined(NO_APPEND_FORTRAN) -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) _##F -#else -#define F_FUNC(f,F) _##f -#endif -#else -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) _##F##_ -#else -#define F_FUNC(f,F) _##f##_ -#endif -#endif -#else -#if defined(NO_APPEND_FORTRAN) -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) F -#else -#define F_FUNC(f,F) f -#endif -#else -#if defined(UPPERCASE_FORTRAN) -#define F_FUNC(f,F) F##_ -#else -#define F_FUNC(f,F) f##_ -#endif -#endif -#endif -#if defined(UNDERSCORE_G77) -#define F_FUNC_US(f,F) F_FUNC(f##_,F##_) -#else -#define F_FUNC_US(f,F) F_FUNC(f,F) -#endif - -#define rank(var) var ## _Rank -#define shape(var,dim) var ## _Dims[dim] -#define old_rank(var) (((PyArrayObject *)(capi_ ## var ## _tmp))->nd) -#define old_shape(var,dim) (((PyArrayObject *)(capi_ ## var ## _tmp))->dimensions[dim]) -#define fshape(var,dim) shape(var,rank(var)-dim-1) -#define len(var) shape(var,0) -#define flen(var) fshape(var,0) -#define old_size(var) PyArray_SIZE((PyArrayObject *)(capi_ ## var ## _tmp)) -/* #define index(i) capi_i ## i */ -#define slen(var) capi_ ## var ## _len -#define size(var, ...) f2py_size((PyArrayObject *)(capi_ ## var ## _tmp), ## __VA_ARGS__, -1) - -#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0) - -#define SWAP(a,b,t) {\ - t *c;\ - c = a;\ - a = b;\ - b = c;} - -#define STRINGCOPYN(to,from,buf_size) \ - do { \ - int _m = (buf_size); \ - char *_to = (to); \ - char *_from = (from); \ - FAILNULL(_to); FAILNULL(_from); \ - (void)strncpy(_to, _from, sizeof(char)*_m); \ - _to[_m-1] = '\0'; \ - /* Padding with spaces instead of nulls */ \ - for (_m -= 2; _m >= 0 && _to[_m] == '\0'; _m--) { \ - _to[_m] = ' '; \ - } \ - } while (0) - -/* New SciPy */ -#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(arr->data)=*v; break; -#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(arr->data)=*v; break; -#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_ ## ctype ## 1(*v),arr->data); break; - -#define TRYPYARRAYTEMPLATE(ctype,typecode) \ - PyArrayObject *arr = NULL;\ - if (!obj) return -2;\ - if (!PyArray_Check(obj)) return -1;\ - if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,"TRYPYARRAYTEMPLATE:");PRINTPYOBJERR(obj);return 0;}\ - if (arr->descr->type==typecode) {*(ctype *)(arr->data)=*v; return 1;}\ - switch (arr->descr->type_num) {\ - case NPY_DOUBLE: *(double *)(arr->data)=*v; break;\ - case NPY_INT: *(int *)(arr->data)=*v; break;\ - case NPY_LONG: *(long *)(arr->data)=*v; break;\ - case NPY_FLOAT: *(float *)(arr->data)=*v; break;\ - case NPY_CDOUBLE: *(double *)(arr->data)=*v; break;\ - case NPY_CFLOAT: *(float *)(arr->data)=*v; break;\ - case NPY_BOOL: *(npy_bool *)(arr->data)=(*v!=0); break;\ - case NPY_UBYTE: *(unsigned char *)(arr->data)=*v; break;\ - case NPY_BYTE: *(signed char *)(arr->data)=*v; break;\ - case NPY_SHORT: *(short *)(arr->data)=*v; break;\ - case NPY_USHORT: *(npy_ushort *)(arr->data)=*v; break;\ - case NPY_UINT: *(npy_uint *)(arr->data)=*v; break;\ - case NPY_ULONG: *(npy_ulong *)(arr->data)=*v; break;\ - case NPY_LONGLONG: *(npy_longlong *)(arr->data)=*v; break;\ - case NPY_ULONGLONG: *(npy_ulonglong *)(arr->data)=*v; break;\ - case NPY_LONGDOUBLE: *(npy_longdouble *)(arr->data)=*v; break;\ - case NPY_CLONGDOUBLE: *(npy_longdouble *)(arr->data)=*v; break;\ - case NPY_OBJECT: (arr->descr->f->setitem)(pyobj_from_ ## ctype ## 1(*v),arr->data, arr); break;\ - default: return -2;\ - };\ - return 1 - - -/************************ See f2py2e/cfuncs.py: cfuncs ************************/ -static int f2py_size(PyArrayObject* var, ...) -{ - npy_int sz = 0; - npy_int dim; - npy_int rank; - va_list argp; - va_start(argp, var); - dim = va_arg(argp, npy_int); - if (dim==-1) - { - sz = PyArray_SIZE(var); - } - else - { - rank = PyArray_NDIM(var); - if (dim>=1 && dim<=rank) - sz = PyArray_DIM(var, dim-1); - else - fprintf(stderr, "f2py_size: 2nd argument value=%d fails to satisfy 1<=value<=%d. Result will be 0.\n", dim, rank); - } - va_end(argp); - return sz; -} - -static int double_from_pyobj(double* v,PyObject *obj,const char *errmess) { - PyObject* tmp = NULL; - if (PyFloat_Check(obj)) { -#ifdef __sgi - *v = PyFloat_AsDouble(obj); -#else - *v = PyFloat_AS_DOUBLE(obj); -#endif - return 1; - } - tmp = PyNumber_Float(obj); - if (tmp) { -#ifdef __sgi - *v = PyFloat_AsDouble(tmp); -#else - *v = PyFloat_AS_DOUBLE(tmp); -#endif - Py_DECREF(tmp); - return 1; - } - if (PyComplex_Check(obj)) - tmp = PyObject_GetAttrString(obj,"real"); - else if (PyString_Check(obj) || PyUnicode_Check(obj)) - /*pass*/; - else if (PySequence_Check(obj)) - tmp = PySequence_GetItem(obj,0); - if (tmp) { - PyErr_Clear(); - if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} - Py_DECREF(tmp); - } - { - PyObject* err = PyErr_Occurred(); - if (err==NULL) err = slsqp_error; - PyErr_SetString(err,errmess); - } - return 0; -} - -static int try_pyarr_from_double(PyObject* obj,double* v) { - TRYPYARRAYTEMPLATE(double,'d'); -} - -static int try_pyarr_from_int(PyObject* obj,int* v) { - TRYPYARRAYTEMPLATE(int,'i'); -} - -static int int_from_pyobj(int* v,PyObject *obj,const char *errmess) { - PyObject* tmp = NULL; - if (PyInt_Check(obj)) { - *v = (int)PyInt_AS_LONG(obj); - return 1; - } - tmp = PyNumber_Int(obj); - if (tmp) { - *v = PyInt_AS_LONG(tmp); - Py_DECREF(tmp); - return 1; - } - if (PyComplex_Check(obj)) - tmp = PyObject_GetAttrString(obj,"real"); - else if (PyString_Check(obj) || PyUnicode_Check(obj)) - /*pass*/; - else if (PySequence_Check(obj)) - tmp = PySequence_GetItem(obj,0); - if (tmp) { - PyErr_Clear(); - if (int_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} - Py_DECREF(tmp); - } - { - PyObject* err = PyErr_Occurred(); - if (err==NULL) err = slsqp_error; - PyErr_SetString(err,errmess); - } - return 0; -} - -static int string_from_pyobj(string *str,int *len,const string inistr,PyObject *obj,const char *errmess) { - PyArrayObject *arr = NULL; - PyObject *tmp = NULL; -#ifdef DEBUGCFUNCS -fprintf(stderr,"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\n",(char*)str,*len,(char *)inistr,obj); -#endif - if (obj == Py_None) { - if (*len == -1) - *len = strlen(inistr); /* Will this cause problems? */ - STRINGMALLOC(*str,*len); - STRINGCOPYN(*str,inistr,*len+1); - return 1; - } - if (PyArray_Check(obj)) { - if ((arr = (PyArrayObject *)obj) == NULL) - goto capi_fail; - if (!ISCONTIGUOUS(arr)) { - PyErr_SetString(PyExc_ValueError,"array object is non-contiguous."); - goto capi_fail; - } - if (*len == -1) - *len = (arr->descr->elsize)*PyArray_SIZE(arr); - STRINGMALLOC(*str,*len); - STRINGCOPYN(*str,arr->data,*len+1); - return 1; - } - if (PyString_Check(obj)) { - tmp = obj; - Py_INCREF(tmp); - } -#if PY_VERSION_HEX >= 0x03000000 - else if (PyUnicode_Check(obj)) { - tmp = PyUnicode_AsASCIIString(obj); - } - else { - PyObject *tmp2; - tmp2 = PyObject_Str(obj); - if (tmp2) { - tmp = PyUnicode_AsASCIIString(tmp2); - Py_DECREF(tmp2); - } - else { - tmp = NULL; - } - } -#else - else { - tmp = PyObject_Str(obj); - } -#endif - if (tmp == NULL) goto capi_fail; - if (*len == -1) - *len = PyString_GET_SIZE(tmp); - STRINGMALLOC(*str,*len); - STRINGCOPYN(*str,PyString_AS_STRING(tmp),*len+1); - Py_DECREF(tmp); - return 1; -capi_fail: - Py_XDECREF(tmp); - { - PyObject* err = PyErr_Occurred(); - if (err==NULL) err = slsqp_error; - PyErr_SetString(err,errmess); - } - return 0; -} - -static int create_cb_arglist(PyObject* fun,PyTupleObject* xa,const int maxnofargs,const int nofoptargs,int *nofargs,PyTupleObject **args,const char *errmess) { - PyObject *tmp = NULL; - PyObject *tmp_fun = NULL; - int tot,opt,ext,siz,i,di=0; - CFUNCSMESS("create_cb_arglist\n"); - tot=opt=ext=siz=0; - /* Get the total number of arguments */ - if (PyFunction_Check(fun)) - tmp_fun = fun; - else { - di = 1; - if (PyObject_HasAttrString(fun,"im_func")) { - tmp_fun = PyObject_GetAttrString(fun,"im_func"); - } - else if (PyObject_HasAttrString(fun,"__call__")) { - tmp = PyObject_GetAttrString(fun,"__call__"); - if (PyObject_HasAttrString(tmp,"im_func")) - tmp_fun = PyObject_GetAttrString(tmp,"im_func"); - else { - tmp_fun = fun; /* built-in function */ - tot = maxnofargs; - if (xa != NULL) - tot += PyTuple_Size((PyObject *)xa); - } - Py_XDECREF(tmp); - } - else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) { - tot = maxnofargs; - if (xa != NULL) - tot += PyTuple_Size((PyObject *)xa); - tmp_fun = fun; - } - else if (F2PyCapsule_Check(fun)) { - tot = maxnofargs; - if (xa != NULL) - ext = PyTuple_Size((PyObject *)xa); - if(ext>0) { - fprintf(stderr,"extra arguments tuple cannot be used with CObject call-back\n"); - goto capi_fail; - } - tmp_fun = fun; - } - } -if (tmp_fun==NULL) { -fprintf(stderr,"Call-back argument must be function|instance|instance.__call__|f2py-function but got %s.\n",(fun==NULL?"NULL":Py_TYPE(fun)->tp_name)); -goto capi_fail; -} -#if PY_VERSION_HEX >= 0x03000000 - if (PyObject_HasAttrString(tmp_fun,"__code__")) { - if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,"__code__"),"co_argcount")) -#else - if (PyObject_HasAttrString(tmp_fun,"func_code")) { - if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,"func_code"),"co_argcount")) -#endif - tot = PyInt_AsLong(PyObject_GetAttrString(tmp,"co_argcount")) - di; - Py_XDECREF(tmp); - } - /* Get the number of optional arguments */ -#if PY_VERSION_HEX >= 0x03000000 - if (PyObject_HasAttrString(tmp_fun,"__defaults__")) - if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,"__defaults__"))) -#else - if (PyObject_HasAttrString(tmp_fun,"func_defaults")) - if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,"func_defaults"))) -#endif - opt = PyTuple_Size(tmp); - Py_XDECREF(tmp); - /* Get the number of extra arguments */ - if (xa != NULL) - ext = PyTuple_Size((PyObject *)xa); - /* Calculate the size of call-backs argument list */ - siz = MIN(maxnofargs+ext,tot); - *nofargs = MAX(0,siz-ext); -#ifdef DEBUGCFUNCS - fprintf(stderr,"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),tot,opt,ext,siz,nofargs=%d(-%d),%d,%d,%d,%d,%d\n",maxnofargs,nofoptargs,tot,opt,ext,siz,*nofargs); -#endif - if (sizcapi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(m))) - goto capi_fail; - if (cb_slfunc_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(meq))) - goto capi_fail; - if (cb_slfunc_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(la))) - goto capi_fail; - if (cb_slfunc_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(n))) - goto capi_fail; - if (cb_slfunc_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_double1(f))) - goto capi_fail; - if (cb_slfunc_in_slsqp__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,c_Dims,NPY_DOUBLE,NULL,(char*)c,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_slfunc_in_slsqp__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,x_Dims,NPY_DOUBLE,NULL,(char*)x,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - CFUNCSMESSPY("cb:capi_arglist=",capi_arglist); - CFUNCSMESS("cb:Call-back calling Python function slfunc.\n"); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_call_clock(); -#endif - capi_return = PyObject_CallObject(cb_slfunc_in_slsqp__user__routines_capi,(PyObject *)capi_arglist); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_call_clock(); -#endif - CFUNCSMESSPY("cb:capi_return=",capi_return); - if (capi_return == NULL) { - fprintf(stderr,"capi_return is NULL\n"); - goto capi_fail; - } - if (capi_return == Py_None) { - Py_DECREF(capi_return); - capi_return = Py_BuildValue("()"); - } - else if (!PyTuple_Check(capi_return)) { - capi_return = Py_BuildValue("(N)",capi_return); - } - capi_j = PyTuple_Size(capi_return); - capi_i = 0; -/*frompyobj*/ - if (capi_j>capi_i) - GETSCALARFROMPYTUPLE(capi_return,capi_i++,f_cb_capi,double,"double_from_pyobj failed in converting argument f of call-back function cb_slfunc_in_slsqp__user__routines to C double\n"); - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_DOUBLE,c_Dims,1,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(c,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - CFUNCSMESS("cb:cb_slfunc_in_slsqp__user__routines:successful\n"); - Py_DECREF(capi_return); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_clock(); -#endif - goto capi_return_pt; -capi_fail: - fprintf(stderr,"Call-back cb_slfunc_in_slsqp__user__routines failed.\n"); - Py_XDECREF(capi_return); - if (capi_longjmp_ok) - longjmp(cb_slfunc_in_slsqp__user__routines_jmpbuf,-1); -capi_return_pt: - ; -return; -} -/***************** end of cb_slfunc_in_slsqp__user__routines *****************/ - - -/********************* cb_slgrad_in_slsqp__user__routines *********************/ -PyObject *cb_slgrad_in_slsqp__user__routines_capi = NULL;/*was Py_None*/ -PyTupleObject *cb_slgrad_in_slsqp__user__routines_args_capi = NULL; -int cb_slgrad_in_slsqp__user__routines_nofargs = 0; -jmp_buf cb_slgrad_in_slsqp__user__routines_jmpbuf; -/*typedef void(*cb_slgrad_in_slsqp__user__routines_typedef)(int *,int *,int *,int *,double *,double *,double *,double *,double *);*/ -static void cb_slgrad_in_slsqp__user__routines (int *m_cb_capi,int *meq_cb_capi,int *la_cb_capi,int *n_cb_capi,double *f_cb_capi,double *c,double *g,double *a,double *x) { - PyTupleObject *capi_arglist = cb_slgrad_in_slsqp__user__routines_args_capi; - PyObject *capi_return = NULL; - PyObject *capi_tmp = NULL; - int capi_j,capi_i = 0; - int capi_longjmp_ok = 1; -/*decl*/ - int m=(*m_cb_capi); - int meq=(*meq_cb_capi); - int la=(*la_cb_capi); - int n=(*n_cb_capi); - double f=(*f_cb_capi); - npy_intp a_Dims[2] = {-1, -1}; - npy_intp c_Dims[1] = {-1}; - npy_intp g_Dims[1] = {-1}; - npy_intp x_Dims[1] = {-1}; -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_clock(); -#endif - CFUNCSMESS("cb:Call-back function cb_slgrad_in_slsqp__user__routines (maxnofargs=9(-0))\n"); - CFUNCSMESSPY("cb:cb_slgrad_in_slsqp__user__routines_capi=",cb_slgrad_in_slsqp__user__routines_capi); - if (cb_slgrad_in_slsqp__user__routines_capi==NULL) { - capi_longjmp_ok = 0; - cb_slgrad_in_slsqp__user__routines_capi = PyObject_GetAttrString(slsqp_module,"slgrad"); - } - if (cb_slgrad_in_slsqp__user__routines_capi==NULL) { - PyErr_SetString(slsqp_error,"cb: Callback slgrad not defined (as an argument or module slsqp attribute).\n"); - goto capi_fail; - } - if (F2PyCapsule_Check(cb_slgrad_in_slsqp__user__routines_capi)) { - cb_slgrad_in_slsqp__user__routines_typedef cb_slgrad_in_slsqp__user__routines_cptr; - cb_slgrad_in_slsqp__user__routines_cptr = F2PyCapsule_AsVoidPtr(cb_slgrad_in_slsqp__user__routines_capi); - (*cb_slgrad_in_slsqp__user__routines_cptr)(m_cb_capi,meq_cb_capi,la_cb_capi,n_cb_capi,f_cb_capi,c,g,a,x); - return; - } - if (capi_arglist==NULL) { - capi_longjmp_ok = 0; - capi_tmp = PyObject_GetAttrString(slsqp_module,"slgrad_extra_args"); - if (capi_tmp) { - capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp); - if (capi_arglist==NULL) { - PyErr_SetString(slsqp_error,"Failed to convert slsqp.slgrad_extra_args to tuple.\n"); - goto capi_fail; - } - } else { - PyErr_Clear(); - capi_arglist = (PyTupleObject *)Py_BuildValue("()"); - } - } - if (capi_arglist == NULL) { - PyErr_SetString(slsqp_error,"Callback slgrad argument list is not set.\n"); - goto capi_fail; - } -/*setdims*/ - a_Dims[0]=la,a_Dims[1]=n + 1; - c_Dims[0]=la; - g_Dims[0]=n + 1; - x_Dims[0]=n; -/*pyobjfrom*/ - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(m))) - goto capi_fail; - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(meq))) - goto capi_fail; - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(la))) - goto capi_fail; - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_int1(n))) - goto capi_fail; - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,pyobj_from_double1(f))) - goto capi_fail; - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,c_Dims,NPY_DOUBLE,NULL,(char*)c,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,g_Dims,NPY_DOUBLE,NULL,(char*)g,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,2,a_Dims,NPY_DOUBLE,NULL,(char*)a,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - if (cb_slgrad_in_slsqp__user__routines_nofargs>capi_i) { - PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,1,x_Dims,NPY_DOUBLE,NULL,(char*)x,0,NPY_FARRAY,NULL); /*XXX: Hmm, what will destroy this array??? */ - - - if (tmp_arr==NULL) - goto capi_fail; - if (PyTuple_SetItem((PyObject *)capi_arglist,capi_i++,(PyObject *)tmp_arr)) - goto capi_fail; -} - CFUNCSMESSPY("cb:capi_arglist=",capi_arglist); - CFUNCSMESS("cb:Call-back calling Python function slgrad.\n"); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_start_call_clock(); -#endif - capi_return = PyObject_CallObject(cb_slgrad_in_slsqp__user__routines_capi,(PyObject *)capi_arglist); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_call_clock(); -#endif - CFUNCSMESSPY("cb:capi_return=",capi_return); - if (capi_return == NULL) { - fprintf(stderr,"capi_return is NULL\n"); - goto capi_fail; - } - if (capi_return == Py_None) { - Py_DECREF(capi_return); - capi_return = Py_BuildValue("()"); - } - else if (!PyTuple_Check(capi_return)) { - capi_return = Py_BuildValue("(N)",capi_return); - } - capi_j = PyTuple_Size(capi_return); - capi_i = 0; -/*frompyobj*/ - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_DOUBLE,g_Dims,1,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(g,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - if (capi_j>capi_i) { - PyArrayObject *rv_cb_arr = NULL; - if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; - rv_cb_arr = array_from_pyobj(NPY_DOUBLE,a_Dims,2,F2PY_INTENT_IN -,capi_tmp); - if (rv_cb_arr == NULL) { - fprintf(stderr,"rv_cb_arr is NULL\n"); - goto capi_fail; - } - MEMCOPY(a,rv_cb_arr->data,PyArray_NBYTES(rv_cb_arr)); - if (capi_tmp != (PyObject *)rv_cb_arr) { - Py_DECREF(rv_cb_arr); - } - } - CFUNCSMESS("cb:cb_slgrad_in_slsqp__user__routines:successful\n"); - Py_DECREF(capi_return); -#ifdef F2PY_REPORT_ATEXIT -f2py_cb_stop_clock(); -#endif - goto capi_return_pt; -capi_fail: - fprintf(stderr,"Call-back cb_slgrad_in_slsqp__user__routines failed.\n"); - Py_XDECREF(capi_return); - if (capi_longjmp_ok) - longjmp(cb_slgrad_in_slsqp__user__routines_jmpbuf,-1); -capi_return_pt: - ; -return; -} -/***************** end of cb_slgrad_in_slsqp__user__routines *****************/ - - -/*********************** See f2py2e/rules.py: buildapi ***********************/ - -/*********************************** slsqp ***********************************/ -static char doc_f2py_rout_slsqp_slsqp[] = "\ -Function signature:\n\ - a = slsqp(m,meq,la,n,x,xl,xu,f,c,g,a,acc,iter,iprint,iout,ifile,mode,w,l_w,jw,l_jw,nfunc,ngrad,slfunc,slgrad,[slfunc_extra_args,slgrad_extra_args])\n\ -Required arguments:\n" -" m : input int\n" -" meq : input int\n" -" la : input int\n" -" n : input int\n" -" x : in/output rank-1 array('d') with bounds (n)\n" -" xl : input rank-1 array('d') with bounds (n)\n" -" xu : input rank-1 array('d') with bounds (n)\n" -" f : in/output rank-0 array(float,'d')\n" -" c : in/output rank-1 array('d') with bounds (la)\n" -" g : in/output rank-1 array('d') with bounds (n + 1)\n" -" a : input rank-2 array('d') with bounds (la,n + 1)\n" -" acc : input float\n" -" iter : in/output rank-0 array(int,'i')\n" -" iprint : input int\n" -" iout : input int\n" -" ifile : input string(len=-1)\n" -" mode : in/output rank-0 array(int,'i')\n" -" w : in/output rank-1 array('d') with bounds (l_w)\n" -" l_w : input int\n" -" jw : in/output rank-1 array('i') with bounds (l_jw)\n" -" l_jw : input int\n" -" nfunc : in/output rank-0 array(int,'i')\n" -" ngrad : in/output rank-0 array(int,'i')\n" -" slfunc : call-back function\n" -" slgrad : call-back function\n" -"Optional arguments:\n" -" slfunc_extra_args := () input tuple\n" -" slgrad_extra_args := () input tuple\n" -"Return objects:\n" -" a : rank-2 array('d') with bounds (la,n + 1)\n" -"Call-back functions:\n" -" def slfunc(m,meq,la,n,f,c,x): return f,c\n\ - Required arguments:\n" -" m : input int\n" -" meq : input int\n" -" la : input int\n" -" n : input int\n" -" f : input float\n" -" c : input rank-1 array('d') with bounds (la)\n" -" x : input rank-1 array('d') with bounds (n)\n" -" Return objects:\n" -" f : float\n" -" c : rank-1 array('d') with bounds (la)\n" -" def slgrad(m,meq,la,n,f,c,g,a,x): return g,a\n\ - Required arguments:\n" -" m : input int\n" -" meq : input int\n" -" la : input int\n" -" n : input int\n" -" f : input float\n" -" c : input rank-1 array('d') with bounds (la)\n" -" g : input rank-1 array('d') with bounds (n + 1)\n" -" a : input rank-2 array('d') with bounds (la,n + 1)\n" -" x : input rank-1 array('d') with bounds (n)\n" -" Return objects:\n" -" g : rank-1 array('d') with bounds (n + 1)\n" -" a : rank-2 array('d') with bounds (la,n + 1)"; -/* extern void F_FUNC(slsqp,SLSQP)(int*,int*,int*,int*,double*,double*,double*,double*,double*,double*,double*,double*,int*,int*,int*,string,int*,double*,int*,int*,int*,int*,int*,cb_slfunc_in_slsqp__user__routines_typedef,cb_slgrad_in_slsqp__user__routines_typedef,size_t); */ -static PyObject *f2py_rout_slsqp_slsqp(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*,int*,int*,int*,double*,double*,double*,double*,double*,double*,double*,double*,int*,int*,int*,string,int*,double*,int*,int*,int*,int*,int*,cb_slfunc_in_slsqp__user__routines_typedef,cb_slgrad_in_slsqp__user__routines_typedef,size_t)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int m = 0; - PyObject *m_capi = Py_None; - int meq = 0; - PyObject *meq_capi = Py_None; - int la = 0; - PyObject *la_capi = Py_None; - int n = 0; - PyObject *n_capi = Py_None; - double *x = NULL; - npy_intp x_Dims[1] = {-1}; - const int x_Rank = 1; - PyArrayObject *capi_x_tmp = NULL; - int capi_x_intent = 0; - PyObject *x_capi = Py_None; - double *xl = NULL; - npy_intp xl_Dims[1] = {-1}; - const int xl_Rank = 1; - PyArrayObject *capi_xl_tmp = NULL; - int capi_xl_intent = 0; - PyObject *xl_capi = Py_None; - double *xu = NULL; - npy_intp xu_Dims[1] = {-1}; - const int xu_Rank = 1; - PyArrayObject *capi_xu_tmp = NULL; - int capi_xu_intent = 0; - PyObject *xu_capi = Py_None; - double f = 0; - PyObject *f_capi = Py_None; - double *c = NULL; - npy_intp c_Dims[1] = {-1}; - const int c_Rank = 1; - PyArrayObject *capi_c_tmp = NULL; - int capi_c_intent = 0; - PyObject *c_capi = Py_None; - double *g = NULL; - npy_intp g_Dims[1] = {-1}; - const int g_Rank = 1; - PyArrayObject *capi_g_tmp = NULL; - int capi_g_intent = 0; - PyObject *g_capi = Py_None; - double *a = NULL; - npy_intp a_Dims[2] = {-1, -1}; - const int a_Rank = 2; - PyArrayObject *capi_a_tmp = NULL; - int capi_a_intent = 0; - PyObject *a_capi = Py_None; - double acc = 0; - PyObject *acc_capi = Py_None; - int iter = 0; - PyObject *iter_capi = Py_None; - int iprint = 0; - PyObject *iprint_capi = Py_None; - int iout = 0; - PyObject *iout_capi = Py_None; - string ifile = NULL; - int slen(ifile); - PyObject *ifile_capi = Py_None; - int mode = 0; - PyObject *mode_capi = Py_None; - double *w = NULL; - npy_intp w_Dims[1] = {-1}; - const int w_Rank = 1; - PyArrayObject *capi_w_tmp = NULL; - int capi_w_intent = 0; - PyObject *w_capi = Py_None; - int l_w = 0; - PyObject *l_w_capi = Py_None; - int *jw = NULL; - npy_intp jw_Dims[1] = {-1}; - const int jw_Rank = 1; - PyArrayObject *capi_jw_tmp = NULL; - int capi_jw_intent = 0; - PyObject *jw_capi = Py_None; - int l_jw = 0; - PyObject *l_jw_capi = Py_None; - int nfunc = 0; - PyObject *nfunc_capi = Py_None; - int ngrad = 0; - PyObject *ngrad_capi = Py_None; - PyObject *slfunc_capi = Py_None; - PyTupleObject *slfunc_xa_capi = NULL; - PyTupleObject *slfunc_args_capi = NULL; - int slfunc_nofargs_capi = 0; - cb_slfunc_in_slsqp__user__routines_typedef slfunc_cptr; - PyObject *slgrad_capi = Py_None; - PyTupleObject *slgrad_xa_capi = NULL; - PyTupleObject *slgrad_args_capi = NULL; - int slgrad_nofargs_capi = 0; - cb_slgrad_in_slsqp__user__routines_typedef slgrad_cptr; - static char *capi_kwlist[] = {"m","meq","la","n","x","xl","xu","f","c","g","a","acc","iter","iprint","iout","ifile","mode","w","l_w","jw","l_jw","nfunc","ngrad","slfunc","slgrad","slfunc_extra_args","slgrad_extra_args",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "OOOOOOOOOOOOOOOOOOOOOOOOO|O!O!:slsqp.slsqp",\ - capi_kwlist,&m_capi,&meq_capi,&la_capi,&n_capi,&x_capi,&xl_capi,&xu_capi,&f_capi,&c_capi,&g_capi,&a_capi,&acc_capi,&iter_capi,&iprint_capi,&iout_capi,&ifile_capi,&mode_capi,&w_capi,&l_w_capi,&jw_capi,&l_jw_capi,&nfunc_capi,&ngrad_capi,&slfunc_capi,&slgrad_capi,&PyTuple_Type,&slfunc_xa_capi,&PyTuple_Type,&slgrad_xa_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable l_jw */ - f2py_success = int_from_pyobj(&l_jw,l_jw_capi,"slsqp.slsqp() 21st argument (l_jw) can't be converted to int"); - if (f2py_success) { - /* Processing variable iout */ - f2py_success = int_from_pyobj(&iout,iout_capi,"slsqp.slsqp() 15th argument (iout) can't be converted to int"); - if (f2py_success) { - /* Processing variable nfunc */ - f2py_success = int_from_pyobj(&nfunc,nfunc_capi,"slsqp.slsqp() 22nd argument (nfunc) can't be converted to int"); - if (f2py_success) { - /* Processing variable meq */ - f2py_success = int_from_pyobj(&meq,meq_capi,"slsqp.slsqp() 2nd argument (meq) can't be converted to int"); - if (f2py_success) { - /* Processing variable ngrad */ - f2py_success = int_from_pyobj(&ngrad,ngrad_capi,"slsqp.slsqp() 23rd argument (ngrad) can't be converted to int"); - if (f2py_success) { - /* Processing variable acc */ - f2py_success = double_from_pyobj(&acc,acc_capi,"slsqp.slsqp() 12nd argument (acc) can't be converted to double"); - if (f2py_success) { - /* Processing variable ifile */ - slen(ifile) = -1; - f2py_success = string_from_pyobj(&ifile,&slen(ifile),"",ifile_capi,"string_from_pyobj failed in converting 16th argument `ifile' of slsqp.slsqp to C string"); - if (f2py_success) { - /* Processing variable l_w */ - f2py_success = int_from_pyobj(&l_w,l_w_capi,"slsqp.slsqp() 19th argument (l_w) can't be converted to int"); - if (f2py_success) { - /* Processing variable la */ - f2py_success = int_from_pyobj(&la,la_capi,"slsqp.slsqp() 3rd argument (la) can't be converted to int"); - if (f2py_success) { - /* Processing variable iprint */ - f2py_success = int_from_pyobj(&iprint,iprint_capi,"slsqp.slsqp() 14th argument (iprint) can't be converted to int"); - if (f2py_success) { - /* Processing variable f */ - f2py_success = double_from_pyobj(&f,f_capi,"slsqp.slsqp() 8th argument (f) can't be converted to double"); - if (f2py_success) { - /* Processing variable m */ - f2py_success = int_from_pyobj(&m,m_capi,"slsqp.slsqp() 1st argument (m) can't be converted to int"); - if (f2py_success) { - /* Processing variable iter */ - f2py_success = int_from_pyobj(&iter,iter_capi,"slsqp.slsqp() 13rd argument (iter) can't be converted to int"); - if (f2py_success) { - /* Processing variable slgrad */ -if(F2PyCapsule_Check(slgrad_capi)) { - slgrad_cptr = F2PyCapsule_AsVoidPtr(slgrad_capi); -} else { - slgrad_cptr = cb_slgrad_in_slsqp__user__routines; -} - - slgrad_nofargs_capi = cb_slgrad_in_slsqp__user__routines_nofargs; - if (create_cb_arglist(slgrad_capi,slgrad_xa_capi,9,0,&cb_slgrad_in_slsqp__user__routines_nofargs,&slgrad_args_capi,"failed in processing argument list for call-back slgrad.")) { - jmp_buf slgrad_jmpbuf; - CFUNCSMESS("Saving jmpbuf for `slgrad`.\n"); - SWAP(slgrad_capi,cb_slgrad_in_slsqp__user__routines_capi,PyObject); - SWAP(slgrad_args_capi,cb_slgrad_in_slsqp__user__routines_args_capi,PyTupleObject); - memcpy(&slgrad_jmpbuf,&cb_slgrad_in_slsqp__user__routines_jmpbuf,sizeof(jmp_buf)); - /* Processing variable n */ - f2py_success = int_from_pyobj(&n,n_capi,"slsqp.slsqp() 4th argument (n) can't be converted to int"); - if (f2py_success) { - /* Processing variable mode */ - f2py_success = int_from_pyobj(&mode,mode_capi,"slsqp.slsqp() 17th argument (mode) can't be converted to int"); - if (f2py_success) { - /* Processing variable slfunc */ -if(F2PyCapsule_Check(slfunc_capi)) { - slfunc_cptr = F2PyCapsule_AsVoidPtr(slfunc_capi); -} else { - slfunc_cptr = cb_slfunc_in_slsqp__user__routines; -} - - slfunc_nofargs_capi = cb_slfunc_in_slsqp__user__routines_nofargs; - if (create_cb_arglist(slfunc_capi,slfunc_xa_capi,7,0,&cb_slfunc_in_slsqp__user__routines_nofargs,&slfunc_args_capi,"failed in processing argument list for call-back slfunc.")) { - jmp_buf slfunc_jmpbuf; - CFUNCSMESS("Saving jmpbuf for `slfunc`.\n"); - SWAP(slfunc_capi,cb_slfunc_in_slsqp__user__routines_capi,PyObject); - SWAP(slfunc_args_capi,cb_slfunc_in_slsqp__user__routines_args_capi,PyTupleObject); - memcpy(&slfunc_jmpbuf,&cb_slfunc_in_slsqp__user__routines_jmpbuf,sizeof(jmp_buf)); - /* Processing variable a */ - a_Dims[0]=la,a_Dims[1]=n + 1; - capi_a_intent |= F2PY_INTENT_OUT|F2PY_INTENT_IN; - capi_a_tmp = array_from_pyobj(NPY_DOUBLE,a_Dims,a_Rank,capi_a_intent,a_capi); - if (capi_a_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 11st argument `a' of slsqp.slsqp to C/Fortran array" ); - } else { - a = (double *)(capi_a_tmp->data); - - /* Processing variable xl */ - xl_Dims[0]=n; - capi_xl_intent |= F2PY_INTENT_IN; - capi_xl_tmp = array_from_pyobj(NPY_DOUBLE,xl_Dims,xl_Rank,capi_xl_intent,xl_capi); - if (capi_xl_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 6th argument `xl' of slsqp.slsqp to C/Fortran array" ); - } else { - xl = (double *)(capi_xl_tmp->data); - - /* Processing variable jw */ - jw_Dims[0]=l_jw; - capi_jw_intent |= F2PY_INTENT_INOUT; - capi_jw_tmp = array_from_pyobj(NPY_INT,jw_Dims,jw_Rank,capi_jw_intent,jw_capi); - if (capi_jw_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 20th argument `jw' of slsqp.slsqp to C/Fortran array" ); - } else { - jw = (int *)(capi_jw_tmp->data); - - /* Processing variable c */ - c_Dims[0]=la; - capi_c_intent |= F2PY_INTENT_INOUT; - capi_c_tmp = array_from_pyobj(NPY_DOUBLE,c_Dims,c_Rank,capi_c_intent,c_capi); - if (capi_c_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 9th argument `c' of slsqp.slsqp to C/Fortran array" ); - } else { - c = (double *)(capi_c_tmp->data); - - /* Processing variable x */ - x_Dims[0]=n; - capi_x_intent |= F2PY_INTENT_INOUT; - capi_x_tmp = array_from_pyobj(NPY_DOUBLE,x_Dims,x_Rank,capi_x_intent,x_capi); - if (capi_x_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 5th argument `x' of slsqp.slsqp to C/Fortran array" ); - } else { - x = (double *)(capi_x_tmp->data); - - /* Processing variable xu */ - xu_Dims[0]=n; - capi_xu_intent |= F2PY_INTENT_IN; - capi_xu_tmp = array_from_pyobj(NPY_DOUBLE,xu_Dims,xu_Rank,capi_xu_intent,xu_capi); - if (capi_xu_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 7th argument `xu' of slsqp.slsqp to C/Fortran array" ); - } else { - xu = (double *)(capi_xu_tmp->data); - - /* Processing variable g */ - g_Dims[0]=n + 1; - capi_g_intent |= F2PY_INTENT_INOUT; - capi_g_tmp = array_from_pyobj(NPY_DOUBLE,g_Dims,g_Rank,capi_g_intent,g_capi); - if (capi_g_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 10th argument `g' of slsqp.slsqp to C/Fortran array" ); - } else { - g = (double *)(capi_g_tmp->data); - - /* Processing variable w */ - w_Dims[0]=l_w; - capi_w_intent |= F2PY_INTENT_INOUT; - capi_w_tmp = array_from_pyobj(NPY_DOUBLE,w_Dims,w_Rank,capi_w_intent,w_capi); - if (capi_w_tmp == NULL) { - if (!PyErr_Occurred()) - PyErr_SetString(slsqp_error,"failed in converting 18th argument `w' of slsqp.slsqp to C/Fortran array" ); - } else { - w = (double *)(capi_w_tmp->data); - -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - if ((setjmp(cb_slfunc_in_slsqp__user__routines_jmpbuf)) || (setjmp(cb_slgrad_in_slsqp__user__routines_jmpbuf))) { - f2py_success = 0; - } else { - (*f2py_func)(&m,&meq,&la,&n,x,xl,xu,&f,c,g,a,&acc,&iter,&iprint,&iout,ifile,&mode,w,&l_w,jw,&l_jw,&nfunc,&ngrad,slfunc_cptr,slgrad_cptr,slen(ifile)); - } -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ - f2py_success = try_pyarr_from_double(f_capi,&f); - if (f2py_success) { - f2py_success = try_pyarr_from_int(iter_capi,&iter); - if (f2py_success) { - f2py_success = try_pyarr_from_int(mode_capi,&mode); - if (f2py_success) { - f2py_success = try_pyarr_from_int(nfunc_capi,&nfunc); - if (f2py_success) { - f2py_success = try_pyarr_from_int(ngrad_capi,&ngrad); - if (f2py_success) { -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue("N",capi_a_tmp); -/*closepyobjfrom*/ - } /*if (f2py_success) of ngrad pyobjfrom*/ - } /*if (f2py_success) of nfunc pyobjfrom*/ - } /*if (f2py_success) of mode pyobjfrom*/ - } /*if (f2py_success) of iter pyobjfrom*/ - } /*if (f2py_success) of f pyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - if((PyObject *)capi_w_tmp!=w_capi) { - Py_XDECREF(capi_w_tmp); } - } /*if (capi_w_tmp == NULL) ... else of w*/ - /* End of cleaning variable w */ - if((PyObject *)capi_g_tmp!=g_capi) { - Py_XDECREF(capi_g_tmp); } - } /*if (capi_g_tmp == NULL) ... else of g*/ - /* End of cleaning variable g */ - if((PyObject *)capi_xu_tmp!=xu_capi) { - Py_XDECREF(capi_xu_tmp); } - } /*if (capi_xu_tmp == NULL) ... else of xu*/ - /* End of cleaning variable xu */ - if((PyObject *)capi_x_tmp!=x_capi) { - Py_XDECREF(capi_x_tmp); } - } /*if (capi_x_tmp == NULL) ... else of x*/ - /* End of cleaning variable x */ - if((PyObject *)capi_c_tmp!=c_capi) { - Py_XDECREF(capi_c_tmp); } - } /*if (capi_c_tmp == NULL) ... else of c*/ - /* End of cleaning variable c */ - if((PyObject *)capi_jw_tmp!=jw_capi) { - Py_XDECREF(capi_jw_tmp); } - } /*if (capi_jw_tmp == NULL) ... else of jw*/ - /* End of cleaning variable jw */ - if((PyObject *)capi_xl_tmp!=xl_capi) { - Py_XDECREF(capi_xl_tmp); } - } /*if (capi_xl_tmp == NULL) ... else of xl*/ - /* End of cleaning variable xl */ - } /*if (capi_a_tmp == NULL) ... else of a*/ - /* End of cleaning variable a */ - CFUNCSMESS("Restoring jmpbuf for `slfunc`.\n"); - cb_slfunc_in_slsqp__user__routines_capi = slfunc_capi; - Py_DECREF(cb_slfunc_in_slsqp__user__routines_args_capi); - cb_slfunc_in_slsqp__user__routines_args_capi = slfunc_args_capi; - cb_slfunc_in_slsqp__user__routines_nofargs = slfunc_nofargs_capi; - memcpy(&cb_slfunc_in_slsqp__user__routines_jmpbuf,&slfunc_jmpbuf,sizeof(jmp_buf)); - } - /* End of cleaning variable slfunc */ - } /*if (f2py_success) of mode*/ - /* End of cleaning variable mode */ - } /*if (f2py_success) of n*/ - /* End of cleaning variable n */ - CFUNCSMESS("Restoring jmpbuf for `slgrad`.\n"); - cb_slgrad_in_slsqp__user__routines_capi = slgrad_capi; - Py_DECREF(cb_slgrad_in_slsqp__user__routines_args_capi); - cb_slgrad_in_slsqp__user__routines_args_capi = slgrad_args_capi; - cb_slgrad_in_slsqp__user__routines_nofargs = slgrad_nofargs_capi; - memcpy(&cb_slgrad_in_slsqp__user__routines_jmpbuf,&slgrad_jmpbuf,sizeof(jmp_buf)); - } - /* End of cleaning variable slgrad */ - } /*if (f2py_success) of iter*/ - /* End of cleaning variable iter */ - } /*if (f2py_success) of m*/ - /* End of cleaning variable m */ - } /*if (f2py_success) of f*/ - /* End of cleaning variable f */ - } /*if (f2py_success) of iprint*/ - /* End of cleaning variable iprint */ - } /*if (f2py_success) of la*/ - /* End of cleaning variable la */ - } /*if (f2py_success) of l_w*/ - /* End of cleaning variable l_w */ - STRINGFREE(ifile); - } /*if (f2py_success) of ifile*/ - /* End of cleaning variable ifile */ - } /*if (f2py_success) of acc*/ - /* End of cleaning variable acc */ - } /*if (f2py_success) of ngrad*/ - /* End of cleaning variable ngrad */ - } /*if (f2py_success) of meq*/ - /* End of cleaning variable meq */ - } /*if (f2py_success) of nfunc*/ - /* End of cleaning variable nfunc */ - } /*if (f2py_success) of iout*/ - /* End of cleaning variable iout */ - } /*if (f2py_success) of l_jw*/ - /* End of cleaning variable l_jw */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/******************************** end of slsqp ********************************/ - -/********************************** openunit **********************************/ -static char doc_f2py_rout_slsqp_openunit[] = "\ -Function signature:\n\ - ierror = openunit(unitnum,filename,filestatus,fileaction)\n\ -Required arguments:\n" -" unitnum : input int\n" -" filename : input string(len=-1)\n" -" filestatus : input string(len=-1)\n" -" fileaction : input string(len=-1)\n" -"Return objects:\n" -" ierror : int"; -/* extern void F_FUNC(openunit,OPENUNIT)(int*,string,string,string,int*,size_t,size_t,size_t); */ -static PyObject *f2py_rout_slsqp_openunit(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*,string,string,string,int*,size_t,size_t,size_t)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int unitnum = 0; - PyObject *unitnum_capi = Py_None; - string filename = NULL; - int slen(filename); - PyObject *filename_capi = Py_None; - string filestatus = NULL; - int slen(filestatus); - PyObject *filestatus_capi = Py_None; - string fileaction = NULL; - int slen(fileaction); - PyObject *fileaction_capi = Py_None; - int ierror = 0; - static char *capi_kwlist[] = {"unitnum","filename","filestatus","fileaction",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "OOOO:slsqp.openunit",\ - capi_kwlist,&unitnum_capi,&filename_capi,&filestatus_capi,&fileaction_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable filestatus */ - slen(filestatus) = -1; - f2py_success = string_from_pyobj(&filestatus,&slen(filestatus),"",filestatus_capi,"string_from_pyobj failed in converting 3rd argument `filestatus' of slsqp.openunit to C string"); - if (f2py_success) { - /* Processing variable filename */ - slen(filename) = -1; - f2py_success = string_from_pyobj(&filename,&slen(filename),"",filename_capi,"string_from_pyobj failed in converting 2nd argument `filename' of slsqp.openunit to C string"); - if (f2py_success) { - /* Processing variable unitnum */ - f2py_success = int_from_pyobj(&unitnum,unitnum_capi,"slsqp.openunit() 1st argument (unitnum) can't be converted to int"); - if (f2py_success) { - /* Processing variable fileaction */ - slen(fileaction) = -1; - f2py_success = string_from_pyobj(&fileaction,&slen(fileaction),"",fileaction_capi,"string_from_pyobj failed in converting 4th argument `fileaction' of slsqp.openunit to C string"); - if (f2py_success) { - /* Processing variable ierror */ -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - (*f2py_func)(&unitnum,filename,filestatus,fileaction,&ierror,slen(filename),slen(filestatus),slen(fileaction)); -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue("i",ierror); -/*closepyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - /* End of cleaning variable ierror */ - STRINGFREE(fileaction); - } /*if (f2py_success) of fileaction*/ - /* End of cleaning variable fileaction */ - } /*if (f2py_success) of unitnum*/ - /* End of cleaning variable unitnum */ - STRINGFREE(filename); - } /*if (f2py_success) of filename*/ - /* End of cleaning variable filename */ - STRINGFREE(filestatus); - } /*if (f2py_success) of filestatus*/ - /* End of cleaning variable filestatus */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/****************************** end of openunit ******************************/ - -/********************************** pyflush **********************************/ -static char doc_f2py_rout_slsqp_pyflush[] = "\ -Function signature:\n\ - pyflush(unitnum)\n\ -Required arguments:\n" -" unitnum : input int"; -/* extern void F_FUNC(pyflush,PYFLUSH)(int*); */ -static PyObject *f2py_rout_slsqp_pyflush(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int unitnum = 0; - PyObject *unitnum_capi = Py_None; - static char *capi_kwlist[] = {"unitnum",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "O:slsqp.pyflush",\ - capi_kwlist,&unitnum_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable unitnum */ - f2py_success = int_from_pyobj(&unitnum,unitnum_capi,"slsqp.pyflush() 1st argument (unitnum) can't be converted to int"); - if (f2py_success) { -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - (*f2py_func)(&unitnum); -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue(""); -/*closepyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - } /*if (f2py_success) of unitnum*/ - /* End of cleaning variable unitnum */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/******************************* end of pyflush *******************************/ - -/********************************* closeunit *********************************/ -static char doc_f2py_rout_slsqp_closeunit[] = "\ -Function signature:\n\ - closeunit(unitnum)\n\ -Required arguments:\n" -" unitnum : input int"; -/* extern void F_FUNC(closeunit,CLOSEUNIT)(int*); */ -static PyObject *f2py_rout_slsqp_closeunit(const PyObject *capi_self, - PyObject *capi_args, - PyObject *capi_keywds, - void (*f2py_func)(int*)) { - PyObject * volatile capi_buildvalue = NULL; - volatile int f2py_success = 1; -/*decl*/ - - int unitnum = 0; - PyObject *unitnum_capi = Py_None; - static char *capi_kwlist[] = {"unitnum",NULL}; - -/*routdebugenter*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_clock(); -#endif - if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\ - "O:slsqp.closeunit",\ - capi_kwlist,&unitnum_capi)) - return NULL; -/*frompyobj*/ - /* Processing variable unitnum */ - f2py_success = int_from_pyobj(&unitnum,unitnum_capi,"slsqp.closeunit() 1st argument (unitnum) can't be converted to int"); - if (f2py_success) { -/*end of frompyobj*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_start_call_clock(); -#endif -/*callfortranroutine*/ - (*f2py_func)(&unitnum); -if (PyErr_Occurred()) - f2py_success = 0; -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_call_clock(); -#endif -/*end of callfortranroutine*/ - if (f2py_success) { -/*pyobjfrom*/ -/*end of pyobjfrom*/ - CFUNCSMESS("Building return value.\n"); - capi_buildvalue = Py_BuildValue(""); -/*closepyobjfrom*/ -/*end of closepyobjfrom*/ - } /*if (f2py_success) after callfortranroutine*/ -/*cleanupfrompyobj*/ - } /*if (f2py_success) of unitnum*/ - /* End of cleaning variable unitnum */ -/*end of cleanupfrompyobj*/ - if (capi_buildvalue == NULL) { -/*routdebugfailure*/ - } else { -/*routdebugleave*/ - } - CFUNCSMESS("Freeing memory.\n"); -/*freemem*/ -#ifdef F2PY_REPORT_ATEXIT -f2py_stop_clock(); -#endif - return capi_buildvalue; -} -/****************************** end of closeunit ******************************/ -/*eof body*/ - -/******************* See f2py2e/f90mod_rules.py: buildhooks *******************/ -/*need_f90modhooks*/ - -/************** See f2py2e/rules.py: module_rules['modulebody'] **************/ - -/******************* See f2py2e/common_rules.py: buildhooks *******************/ - -/*need_commonhooks*/ - -/**************************** See f2py2e/rules.py ****************************/ - -static FortranDataDef f2py_routine_defs[] = { - {"slsqp",-1,{{-1}},0,(char *)F_FUNC(slsqp,SLSQP),(f2py_init_func)f2py_rout_slsqp_slsqp,doc_f2py_rout_slsqp_slsqp}, - {"openunit",-1,{{-1}},0,(char *)F_FUNC(openunit,OPENUNIT),(f2py_init_func)f2py_rout_slsqp_openunit,doc_f2py_rout_slsqp_openunit}, - {"pyflush",-1,{{-1}},0,(char *)F_FUNC(pyflush,PYFLUSH),(f2py_init_func)f2py_rout_slsqp_pyflush,doc_f2py_rout_slsqp_pyflush}, - {"closeunit",-1,{{-1}},0,(char *)F_FUNC(closeunit,CLOSEUNIT),(f2py_init_func)f2py_rout_slsqp_closeunit,doc_f2py_rout_slsqp_closeunit}, - -/*eof routine_defs*/ - {NULL} -}; - -static PyMethodDef f2py_module_methods[] = { - - {NULL,NULL} -}; - -#if PY_VERSION_HEX >= 0x03000000 -static struct PyModuleDef moduledef = { - PyModuleDef_HEAD_INIT, - "slsqp", - NULL, - -1, - f2py_module_methods, - NULL, - NULL, - NULL, - NULL -}; -#endif - -#if PY_VERSION_HEX >= 0x03000000 -#define RETVAL m -PyObject *PyInit_slsqp(void) { -#else -#define RETVAL -PyMODINIT_FUNC initslsqp(void) { -#endif - int i; - PyObject *m,*d, *s; -#if PY_VERSION_HEX >= 0x03000000 - m = slsqp_module = PyModule_Create(&moduledef); -#else - m = slsqp_module = Py_InitModule("slsqp", f2py_module_methods); -#endif - Py_TYPE(&PyFortran_Type) = &PyType_Type; - import_array(); - if (PyErr_Occurred()) - {PyErr_SetString(PyExc_ImportError, "can't initialize module slsqp (failed to import numpy)"); return RETVAL;} - d = PyModule_GetDict(m); - s = PyString_FromString("$Revision: $"); - PyDict_SetItemString(d, "__version__", s); -#if PY_VERSION_HEX >= 0x03000000 - s = PyUnicode_FromString( -#else - s = PyString_FromString( -#endif - "This module 'slsqp' is auto-generated with f2py (version:2).\nFunctions:\n" -" a = slsqp(m,meq,la,n,x,xl,xu,f,c,g,a,acc,iter,iprint,iout,ifile,mode,w,l_w,jw,l_jw,nfunc,ngrad,slfunc,slgrad,slfunc_extra_args=(),slgrad_extra_args=())\n" -" ierror = openunit(unitnum,filename,filestatus,fileaction)\n" -" pyflush(unitnum)\n" -" closeunit(unitnum)\n" -"."); - PyDict_SetItemString(d, "__doc__", s); - slsqp_error = PyErr_NewException ("slsqp.error", NULL, NULL); - Py_DECREF(s); - for(i=0;f2py_routine_defs[i].name!=NULL;i++) - PyDict_SetItemString(d, f2py_routine_defs[i].name,PyFortranObject_NewAsAttr(&f2py_routine_defs[i])); - - - - -/*eof initf2pywraphooks*/ -/*eof initf90modhooks*/ - -/*eof initcommonhooks*/ - - -#ifdef F2PY_REPORT_ATEXIT - if (! PyErr_Occurred()) - on_exit(f2py_report_on_exit,(void*)"slsqp"); -#endif - - return RETVAL; -} -#ifdef __cplusplus -} -#endif diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/h12.f b/pyoptsparse/pyoptsparse/pySLSQP/source/h12.f deleted file mode 100644 index 7ed74def2..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/h12.f +++ /dev/null @@ -1,81 +0,0 @@ - SUBROUTINE H12 (MODE,LPIVOT,L1,M,U,IUE,UP,C,ICE,ICV,NCV) - -C C.L.LAWSON AND R.J.HANSON, JET PROPULSION LABORATORY, 1973 JUN 12 -C TO APPEAR IN 'SOLVING LEAST SQUARES PROBLEMS', PRENTICE-HALL, 1974 - -C CONSTRUCTION AND/OR APPLICATION OF A SINGLE -C HOUSEHOLDER TRANSFORMATION Q = I + U*(U**T)/B - -C MODE = 1 OR 2 TO SELECT ALGORITHM H1 OR H2 . -C LPIVOT IS THE INDEX OF THE PIVOT ELEMENT. -C L1,M IF L1 <= M THE TRANSFORMATION WILL BE CONSTRUCTED TO -C ZERO ELEMENTS INDEXED FROM L1 THROUGH M. -C IF L1 > M THE SUBROUTINE DOES AN IDENTITY TRANSFORMATION. -C U(),IUE,UP -C ON ENTRY TO H1 U() STORES THE PIVOT VECTOR. -C IUE IS THE STORAGE INCREMENT BETWEEN ELEMENTS. -C ON EXIT FROM H1 U() AND UP STORE QUANTITIES DEFINING -C THE VECTOR U OF THE HOUSEHOLDER TRANSFORMATION. -C ON ENTRY TO H2 U() AND UP -C SHOULD STORE QUANTITIES PREVIOUSLY COMPUTED BY H1. -C THESE WILL NOT BE MODIFIED BY H2. -C C() ON ENTRY TO H1 OR H2 C() STORES A MATRIX WHICH WILL BE -C REGARDED AS A SET OF VECTORS TO WHICH THE HOUSEHOLDER -C TRANSFORMATION IS TO BE APPLIED. -C ON EXIT C() STORES THE SET OF TRANSFORMED VECTORS. -C ICE STORAGE INCREMENT BETWEEN ELEMENTS OF VECTORS IN C(). -C ICV STORAGE INCREMENT BETWEEN VECTORS IN C(). -C NCV NUMBER OF VECTORS IN C() TO BE TRANSFORMED. -C IF NCV <= 0 NO OPERATIONS WILL BE DONE ON C(). - - INTEGER INCR, ICE, ICV, IUE, LPIVOT, L1, MODE, NCV - INTEGER I, I2, I3, I4, J, M - DOUBLE PRECISION U,UP,C,CL,CLINV,B,SM,ONE,ZERO - DIMENSION U(IUE,*), C(*) - DATA ONE/1.0D+00/, ZERO/0.0D+00/ - - IF (0.GE.LPIVOT.OR.LPIVOT.GE.L1.OR.L1.GT.M) GOTO 80 - CL=ABS(U(1,LPIVOT)) - IF (MODE.EQ.2) GOTO 30 - -C ****** CONSTRUCT THE TRANSFORMATION ****** - - DO 10 J=L1,M - SM=ABS(U(1,J)) - 10 CL=MAX(SM,CL) - IF (CL.LE.ZERO) GOTO 80 - CLINV=ONE/CL - SM=(U(1,LPIVOT)*CLINV)**2 - DO 20 J=L1,M - 20 SM=SM+(U(1,J)*CLINV)**2 - CL=CL*SQRT(SM) - IF (U(1,LPIVOT).GT.ZERO) CL=-CL - UP=U(1,LPIVOT)-CL - U(1,LPIVOT)=CL - GOTO 40 -C ****** APPLY THE TRANSFORMATION I+U*(U**T)/B TO C ****** - - 30 IF (CL.LE.ZERO) GOTO 80 - 40 IF (NCV.LE.0) GOTO 80 - B=UP*U(1,LPIVOT) - IF (B.GE.ZERO) GOTO 80 - B=ONE/B - I2=1-ICV+ICE*(LPIVOT-1) - INCR=ICE*(L1-LPIVOT) - DO 70 J=1,NCV - I2=I2+ICV - I3=I2+INCR - I4=I3 - SM=C(I2)*UP - DO 50 I=L1,M - SM=SM+C(I3)*U(1,I) - 50 I3=I3+ICE - IF (SM.EQ.ZERO) GOTO 70 - SM=SM*B - C(I2)=C(I2)+SM*UP - DO 60 I=L1,M - C(I4)=C(I4)+SM*U(1,I) - 60 I4=I4+ICE - 70 CONTINUE - 80 END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/hfti.f b/pyoptsparse/pyoptsparse/pySLSQP/source/hfti.f deleted file mode 100644 index b677c620c..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/hfti.f +++ /dev/null @@ -1,128 +0,0 @@ - SUBROUTINE HFTI(A,MDA,M,N,B,MDB,NB,TAU,KRANK,RNORM,H,G,IP) - -C RANK-DEFICIENT LEAST SQUARES ALGORITHM AS DESCRIBED IN: -C C.L.LAWSON AND R.J.HANSON, JET PROPULSION LABORATORY, 1973 JUN 12 -C TO APPEAR IN 'SOLVING LEAST SQUARES PROBLEMS', PRENTICE-HALL, 1974 - -C A(*,*),MDA,M,N THE ARRAY A INITIALLY CONTAINS THE M x N MATRIX A -C OF THE LEAST SQUARES PROBLEM AX = B. -C THE FIRST DIMENSIONING PARAMETER MDA MUST SATISFY -C MDA >= M. EITHER M >= N OR M < N IS PERMITTED. -C THERE IS NO RESTRICTION ON THE RANK OF A. -C THE MATRIX A WILL BE MODIFIED BY THE SUBROUTINE. -C B(*,*),MDB,NB IF NB = 0 THE SUBROUTINE WILL MAKE NO REFERENCE -C TO THE ARRAY B. IF NB > 0 THE ARRAY B() MUST -C INITIALLY CONTAIN THE M x NB MATRIX B OF THE -C THE LEAST SQUARES PROBLEM AX = B AND ON RETURN -C THE ARRAY B() WILL CONTAIN THE N x NB SOLUTION X. -C IF NB>1 THE ARRAY B() MUST BE DOUBLE SUBSCRIPTED -C WITH FIRST DIMENSIONING PARAMETER MDB>=MAX(M,N), -C IF NB=1 THE ARRAY B() MAY BE EITHER SINGLE OR -C DOUBLE SUBSCRIPTED. -C TAU ABSOLUTE TOLERANCE PARAMETER FOR PSEUDORANK -C DETERMINATION, PROVIDED BY THE USER. -C KRANK PSEUDORANK OF A, SET BY THE SUBROUTINE. -C RNORM ON EXIT, RNORM(J) WILL CONTAIN THE EUCLIDIAN -C NORM OF THE RESIDUAL VECTOR FOR THE PROBLEM -C DEFINED BY THE J-TH COLUMN VECTOR OF THE ARRAY B. -C H(), G() ARRAYS OF WORKING SPACE OF LENGTH >= N. -C IP() INTEGER ARRAY OF WORKING SPACE OF LENGTH >= N -C RECORDING PERMUTATION INDICES OF COLUMN VECTORS - - INTEGER I,J,JB,K,KP1,KRANK,L,LDIAG,LMAX,M, - . MDA,MDB,N,NB,IP(N) - DOUBLE PRECISION A(MDA,N),B(MDB,NB),H(N),G(N),RNORM(NB),FACTOR, - . TAU,ZERO,HMAX,DIFF,TMP,DDOT,DNRM2,U,V - DIFF(U,V)= U-V - DATA ZERO/0.0D0/, FACTOR/1.0D-3/ - - K=0 - LDIAG=MIN(M,N) - IF(LDIAG.LE.0) GOTO 270 - -C COMPUTE LMAX - - DO 80 J=1,LDIAG - IF(J.EQ.1) GOTO 20 - LMAX=J - DO 10 L=J,N - H(L)=H(L)-A(J-1,L)**2 - 10 IF(H(L).GT.H(LMAX)) LMAX=L - IF(DIFF(HMAX+FACTOR*H(LMAX),HMAX).GT.ZERO) - . GOTO 50 - 20 LMAX=J - DO 40 L=J,N - H(L)=ZERO - DO 30 I=J,M - 30 H(L)=H(L)+A(I,L)**2 - 40 IF(H(L).GT.H(LMAX)) LMAX=L - HMAX=H(LMAX) - -C COLUMN INTERCHANGES IF NEEDED - - 50 IP(J)=LMAX - IF(IP(J).EQ.J) GOTO 70 - DO 60 I=1,M - TMP=A(I,J) - A(I,J)=A(I,LMAX) - 60 A(I,LMAX)=TMP - H(LMAX)=H(J) - -C J-TH TRANSFORMATION AND APPLICATION TO A AND B - - 70 I=MIN(J+1,N) - CALL H12(1,J,J+1,M,A(1,J),1,H(J),A(1,I),1,MDA,N-J) - 80 CALL H12(2,J,J+1,M,A(1,J),1,H(J),B,1,MDB,NB) - -C DETERMINE PSEUDORANK - - DO 90 J=1,LDIAG - 90 IF(ABS(A(J,J)).LE.TAU) GOTO 100 - K=LDIAG - GOTO 110 - 100 K=J-1 - 110 KP1=K+1 - -C NORM OF RESIDUALS - - DO 130 JB=1,NB - 130 RNORM(JB)=DNRM2(M-K,B(KP1,JB),1) - IF(K.GT.0) GOTO 160 - DO 150 JB=1,NB - DO 150 I=1,N - 150 B(I,JB)=ZERO - GOTO 270 - 160 IF(K.EQ.N) GOTO 180 - -C HOUSEHOLDER DECOMPOSITION OF FIRST K ROWS - - DO 170 I=K,1,-1 - 170 CALL H12(1,I,KP1,N,A(I,1),MDA,G(I),A,MDA,1,I-1) - 180 DO 250 JB=1,NB - -C SOLVE K*K TRIANGULAR SYSTEM - - DO 210 I=K,1,-1 - J=MIN(I+1,N) - 210 B(I,JB)=(B(I,JB)-DDOT(K-I,A(I,J),MDA,B(J,JB),1))/A(I,I) - -C COMPLETE SOLUTION VECTOR - - IF(K.EQ.N) GOTO 240 - DO 220 J=KP1,N - 220 B(J,JB)=ZERO - DO 230 I=1,K - 230 CALL H12(2,I,KP1,N,A(I,1),MDA,G(I),B(1,JB),1,MDB,1) - -C REORDER SOLUTION ACCORDING TO PREVIOUS COLUMN INTERCHANGES - - 240 DO 250 J=LDIAG,1,-1 - IF(IP(J).EQ.J) GOTO 250 - L=IP(J) - TMP=B(L,JB) - B(L,JB)=B(J,JB) - B(J,JB)=TMP - 250 CONTINUE - 270 KRANK=K - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/ldl.f b/pyoptsparse/pyoptsparse/pySLSQP/source/ldl.f deleted file mode 100644 index 5ad16dffa..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/ldl.f +++ /dev/null @@ -1,253 +0,0 @@ - SUBROUTINE LDL (N,A,Z,SIGMA,W) -C LDL LDL' - RANK-ONE - UPDATE - -C PURPOSE: -C UPDATES THE LDL' FACTORS OF MATRIX A BY RANK-ONE MATRIX -C SIGMA*Z*Z' - -C INPUT ARGUMENTS: (* MEANS PARAMETERS ARE CHANGED DURING EXECUTION) -C N : ORDER OF THE COEFFICIENT MATRIX A -C * A : POSITIVE DEFINITE MATRIX OF DIMENSION N; -C ONLY THE LOWER TRIANGLE IS USED AND IS STORED COLUMN BY -C COLUMN AS ONE DIMENSIONAL ARRAY OF DIMENSION N*(N+1)/2. -C * Z : VECTOR OF DIMENSION N OF UPDATING ELEMENTS -C SIGMA : SCALAR FACTOR BY WHICH THE MODIFYING DYADE Z*Z' IS -C MULTIPLIED - -C OUTPUT ARGUMENTS: -C A : UPDATED LDL' FACTORS - -C WORKING ARRAY: -C W : VECTOR OP DIMENSION N (USED ONLY IF SIGMA .LT. ZERO) - -C METHOD: -C THAT OF FLETCHER AND POWELL AS DESCRIBED IN : -C FLETCHER,R.,(1974) ON THE MODIFICATION OF LDL' FACTORIZATION. -C POWELL,M.J.D. MATH.COMPUTATION 28, 1067-1078. - -C IMPLEMENTED BY: -C KRAFT,D., DFVLR - INSTITUT FUER DYNAMIK DER FLUGSYSTEME -C D-8031 OBERPFAFFENHOFEN - -C STATUS: 15. JANUARY 1980 - -C SUBROUTINES REQUIRED: NONE - - INTEGER I, IJ, J, N - DOUBLE PRECISION A(*), T, V, W(*), Z(*), U, TP, ONE, BETA, FOUR, - * ZERO, ALPHA, DELTA, GAMMA, SIGMA, EPMACH - DATA ZERO, ONE, FOUR, EPMACH /0.0D0, 1.0D0, 4.0D0, 2.22D-16/ - - IF(SIGMA.EQ.ZERO) GOTO 280 - IJ=1 - T=ONE/SIGMA - IF(SIGMA.GT.ZERO) GOTO 220 -C PREPARE NEGATIVE UPDATE - DO 150 I=1,N - 150 W(I)=Z(I) - DO 170 I=1,N - V=W(I) - T=T+V*V/A(IJ) - DO 160 J=I+1,N - IJ=IJ+1 - 160 W(J)=W(J)-V*A(IJ) - 170 IJ=IJ+1 - IF(T.GE.ZERO) T=EPMACH/SIGMA - DO 210 I=1,N - J=N+1-I - IJ=IJ-I - U=W(J) - W(J)=T - 210 T=T-U*U/A(IJ) - 220 CONTINUE -C HERE UPDATING BEGINS - DO 270 I=1,N - V=Z(I) - DELTA=V/A(IJ) - IF(SIGMA.LT.ZERO) TP=W(I) - IF(SIGMA.GT.ZERO) TP=T+DELTA*V - ALPHA=TP/T - A(IJ)=ALPHA*A(IJ) - IF(I.EQ.N) GOTO 280 - BETA=DELTA/TP - IF(ALPHA.GT.FOUR) GOTO 240 - DO 230 J=I+1,N - IJ=IJ+1 - Z(J)=Z(J)-V*A(IJ) - 230 A(IJ)=A(IJ)+BETA*Z(J) - GOTO 260 - 240 GAMMA=T/TP - DO 250 J=I+1,N - IJ=IJ+1 - U=A(IJ) - A(IJ)=GAMMA*U+BETA*Z(J) - 250 Z(J)=Z(J)-V*U - 260 IJ=IJ+1 - 270 T=TP - 280 RETURN -C END OF LDL - END - - DOUBLE PRECISION FUNCTION LINMIN (MODE, AX, BX, F, TOL) -C LINMIN LINESEARCH WITHOUT DERIVATIVES - -C PURPOSE: - -C TO FIND THE ARGUMENT LINMIN WHERE THE FUNCTION F TAKES IT'S MINIMUM -C ON THE INTERVAL AX, BX. -C COMBINATION OF GOLDEN SECTION AND SUCCESSIVE QUADRATIC INTERPOLATION. - -C INPUT ARGUMENTS: (* MEANS PARAMETERS ARE CHANGED DURING EXECUTION) - -C *MODE SEE OUTPUT ARGUMENTS -C AX LEFT ENDPOINT OF INITIAL INTERVAL -C BX RIGHT ENDPOINT OF INITIAL INTERVAL -C F FUNCTION VALUE AT LINMIN WHICH IS TO BE BROUGHT IN BY -C REVERSE COMMUNICATION CONTROLLED BY MODE -C TOL DESIRED LENGTH OF INTERVAL OF UNCERTAINTY OF FINAL RESULT - -C OUTPUT ARGUMENTS: - -C LINMIN ABSCISSA APPROXIMATING THE POINT WHERE F ATTAINS A MINIMUM -C MODE CONTROLS REVERSE COMMUNICATION -C MUST BE SET TO 0 INITIALLY, RETURNS WITH INTERMEDIATE -C VALUES 1 AND 2 WHICH MUST NOT BE CHANGED BY THE USER, -C ENDS WITH CONVERGENCE WITH VALUE 3. - -C WORKING ARRAY: - -C NONE - -C METHOD: - -C THIS FUNCTION SUBPROGRAM IS A SLIGHTLY MODIFIED VERSION OF THE -C ALGOL 60 PROCEDURE LOCALMIN GIVEN IN -C R.P. BRENT: ALGORITHMS FOR MINIMIZATION WITHOUT DERIVATIVES, -C PRENTICE-HALL (1973). - -C IMPLEMENTED BY: - -C KRAFT, D., DFVLR - INSTITUT FUER DYNAMIK DER FLUGSYSTEME -C D-8031 OBERPFAFFENHOFEN - -C STATUS: 31. AUGUST 1984 - -C SUBROUTINES REQUIRED: NONE - - INTEGER MODE - DOUBLE PRECISION F, TOL, A, B, C, D, E, P, Q, R, U, V, W, X, M, - & FU, FV, FW, FX, EPS, TOL1, TOL2, ZERO, AX, BX - DATA C /0.381966011D0/, EPS /1.5D-8/, ZERO /0.0D0/ - -C EPS = SQUARE - ROOT OF MACHINE PRECISION -C C = GOLDEN SECTION RATIO = (3-SQRT(5))/2 - - GOTO (10, 55), MODE - -C INITIALIZATION - - A = AX - B = BX - E = ZERO - V = A + C*(B - A) - W = V - X = W - LINMIN = X - MODE = 1 - GOTO 100 - -C MAIN LOOP STARTS HERE - - 10 FX = F - FV = FX - FW = FV - 20 M = 0.5D0*(A + B) - TOL1 = EPS*ABS(X) + TOL - TOL2 = TOL1 + TOL1 - -C TEST CONVERGENCE - - IF (ABS(X - M) .LE. TOL2 - 0.5D0*(B - A)) GOTO 90 - R = ZERO - Q = R - P = Q - IF (ABS(E) .LE. TOL1) GOTO 30 - -C FIT PARABOLA - - R = (X - W)*(FX - FV) - Q = (X - V)*(FX - FW) - P = (X - V)*Q - (X - W)*R - Q = Q - R - Q = Q + Q - IF (Q .GT. ZERO) P = -P - IF (Q .LT. ZERO) Q = -Q - R = E - E = D - -C IS PARABOLA ACCEPTABLE - - 30 IF (ABS(P) .GE. 0.5D0*ABS(Q*R) .OR. - & P .LE. Q*(A - X) .OR. P .GE. Q*(B-X)) GOTO 40 - -C PARABOLIC INTERPOLATION STEP - - D = P/Q - -C F MUST NOT BE EVALUATED TOO CLOSE TO A OR B - - IF (U - A .LT. TOL2) D = SIGN(TOL1, M - X) - IF (B - U .LT. TOL2) D = SIGN(TOL1, M - X) - GOTO 50 - -C GOLDEN SECTION STEP - - 40 IF (X .GE. M) E = A - X - IF (X .LT. M) E = B - X - D = C*E - -C F MUST NOT BE EVALUATED TOO CLOSE TO X - - 50 IF (ABS(D) .LT. TOL1) D = SIGN(TOL1, D) - U = X + D - LINMIN = U - MODE = 2 - GOTO 100 - 55 FU = F - -C UPDATE A, B, V, W, AND X - - IF (FU .GT. FX) GOTO 60 - IF (U .GE. X) A = X - IF (U .LT. X) B = X - V = W - FV = FW - W = X - FW = FX - X = U - FX = FU - GOTO 85 - 60 IF (U .LT. X) A = U - IF (U .GE. X) B = U - IF (FU .LE. FW .OR. W .EQ. X) GOTO 70 - IF (FU .LE. FV .OR. V .EQ. X .OR. V .EQ. W) GOTO 80 - GOTO 85 - 70 V = W - FV = FW - W = U - FW = FU - GOTO 85 - 80 V = U - FV = FU - 85 GOTO 20 - -C END OF MAIN LOOP - - 90 LINMIN = X - MODE = 3 - 100 RETURN - -C END OF LINMIN - - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/ldp.f b/pyoptsparse/pyoptsparse/pySLSQP/source/ldp.f deleted file mode 100644 index c1b9a836f..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/ldp.f +++ /dev/null @@ -1,98 +0,0 @@ - SUBROUTINE LDP(G,MG,M,N,H,X,XNORM,W,INDEX,MODE) - -C T -C MINIMIZE 1/2 X X SUBJECT TO G * X >= H. - -C C.L. LAWSON, R.J. HANSON: 'SOLVING LEAST SQUARES PROBLEMS' -C PRENTICE HALL, ENGLEWOOD CLIFFS, NEW JERSEY, 1974. - -C PARAMETER DESCRIPTION: - -C G(),MG,M,N ON ENTRY G() STORES THE M BY N MATRIX OF -C LINEAR INEQUALITY CONSTRAINTS. G() HAS FIRST -C DIMENSIONING PARAMETER MG -C H() ON ENTRY H() STORES THE M VECTOR H REPRESENTING -C THE RIGHT SIDE OF THE INEQUALITY SYSTEM - -C REMARK: G(),H() WILL NOT BE CHANGED DURING CALCULATIONS BY LDP - -C X() ON ENTRY X() NEED NOT BE INITIALIZED. -C ON EXIT X() STORES THE SOLUTION VECTOR X IF MODE=1. -C XNORM ON EXIT XNORM STORES THE EUCLIDIAN NORM OF THE -C SOLUTION VECTOR IF COMPUTATION IS SUCCESSFUL -C W() W IS A ONE DIMENSIONAL WORKING SPACE, THE LENGTH -C OF WHICH SHOULD BE AT LEAST (M+2)*(N+1) + 2*M -C ON EXIT W() STORES THE LAGRANGE MULTIPLIERS -C ASSOCIATED WITH THE CONSTRAINTS -C AT THE SOLUTION OF PROBLEM LDP -C INDEX() INDEX() IS A ONE DIMENSIONAL INTEGER WORKING SPACE -C OF LENGTH AT LEAST M -C MODE MODE IS A SUCCESS-FAILURE FLAG WITH THE FOLLOWING -C MEANINGS: -C MODE=1: SUCCESSFUL COMPUTATION -C 2: ERROR RETURN BECAUSE OF WRONG DIMENSIONS (N.LE.0) -C 3: ITERATION COUNT EXCEEDED BY NNLS -C 4: INEQUALITY CONSTRAINTS INCOMPATIBLE - - DOUBLE PRECISION G,H,X,XNORM,W,U,V, - . ZERO,ONE,FAC,RNORM,DNRM2,DDOT,DIFF - INTEGER INDEX,I,IF,IW,IWDUAL,IY,IZ,J,M,MG,MODE,N,N1 - DIMENSION G(MG,N),H(M),X(N),W(*),INDEX(M) - DIFF(U,V)= U-V - DATA ZERO,ONE/0.0D0,1.0D0/ - - MODE=2 - IF(N.LE.0) GOTO 50 - -C STATE DUAL PROBLEM - - MODE=1 - X(1)=ZERO - CALL DCOPY(N,X(1),0,X,1) - XNORM=ZERO - IF(M.EQ.0) GOTO 50 - IW=0 - DO 20 J=1,M - DO 10 I=1,N - IW=IW+1 - 10 W(IW)=G(J,I) - IW=IW+1 - 20 W(IW)=H(J) - IF=IW+1 - DO 30 I=1,N - IW=IW+1 - 30 W(IW)=ZERO - W(IW+1)=ONE - N1=N+1 - IZ=IW+2 - IY=IZ+N1 - IWDUAL=IY+M - -C SOLVE DUAL PROBLEM - - CALL NNLS (W,N1,N1,M,W(IF),W(IY),RNORM,W(IWDUAL),W(IZ),INDEX,MODE) - - IF(MODE.NE.1) GOTO 50 - MODE=4 - IF(RNORM.LE.ZERO) GOTO 50 - -C COMPUTE SOLUTION OF PRIMAL PROBLEM - - FAC=ONE-DDOT(M,H,1,W(IY),1) - IF(DIFF(ONE+FAC,ONE).LE.ZERO) GOTO 50 - MODE=1 - FAC=ONE/FAC - DO 40 J=1,N - 40 X(J)=FAC*DDOT(M,G(1,J),1,W(IY),1) - XNORM=DNRM2(N,X,1) - -C COMPUTE LAGRANGE MULTIPLIERS FOR PRIMAL PROBLEM - - W(1)=ZERO - CALL DCOPY(M,W(1),0,W,1) - CALL DAXPY(M,FAC,W(IY),1,W,1) - -C END OF SUBROUTINE LDP - - 50 END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/lsei.f b/pyoptsparse/pyoptsparse/pySLSQP/source/lsei.f deleted file mode 100644 index 1b1788ee4..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/lsei.f +++ /dev/null @@ -1,132 +0,0 @@ - SUBROUTINE LSEI(C,D,E,F,G,H,LC,MC,LE,ME,LG,MG,N,X,XNRM,W,JW,MODE) - -C FOR MODE=1, THE SUBROUTINE RETURNS THE SOLUTION X OF -C EQUALITY & INEQUALITY CONSTRAINED LEAST SQUARES PROBLEM LSEI : - -C MIN ||E*X - F|| -C X - -C S.T. C*X = D, -C G*X >= H. - -C USING QR DECOMPOSITION & ORTHOGONAL BASIS OF NULLSPACE OF C -C CHAPTER 23.6 OF LAWSON & HANSON: SOLVING LEAST SQUARES PROBLEMS. - -C THE FOLLOWING DIMENSIONS OF THE ARRAYS DEFINING THE PROBLEM -C ARE NECESSARY -C DIM(E) : FORMAL (LE,N), ACTUAL (ME,N) -C DIM(F) : FORMAL (LE ), ACTUAL (ME ) -C DIM(C) : FORMAL (LC,N), ACTUAL (MC,N) -C DIM(D) : FORMAL (LC ), ACTUAL (MC ) -C DIM(G) : FORMAL (LG,N), ACTUAL (MG,N) -C DIM(H) : FORMAL (LG ), ACTUAL (MG ) -C DIM(X) : FORMAL (N ), ACTUAL (N ) -C DIM(W) : 2*MC+ME+(ME+MG)*(N-MC) for LSEI -C +(N-MC+1)*(MG+2)+2*MG for LSI -C DIM(JW): MAX(MG,L) -C ON ENTRY, THE USER HAS TO PROVIDE THE ARRAYS C, D, E, F, G, AND H. -C ON RETURN, ALL ARRAYS WILL BE CHANGED BY THE SUBROUTINE. -C X STORES THE SOLUTION VECTOR -C XNORM STORES THE RESIDUUM OF THE SOLUTION IN EUCLIDIAN NORM -C W STORES THE VECTOR OF LAGRANGE MULTIPLIERS IN ITS FIRST -C MC+MG ELEMENTS -C MODE IS A SUCCESS-FAILURE FLAG WITH THE FOLLOWING MEANINGS: -C MODE=1: SUCCESSFUL COMPUTATION -C 2: ERROR RETURN BECAUSE OF WRONG DIMENSIONS (N<1) -C 3: ITERATION COUNT EXCEEDED BY NNLS -C 4: INEQUALITY CONSTRAINTS INCOMPATIBLE -C 5: MATRIX E IS NOT OF FULL RANK -C 6: MATRIX C IS NOT OF FULL RANK -C 7: RANK DEFECT IN HFTI - -C 18.5.1981, DIETER KRAFT, DFVLR OBERPFAFFENHOFEN -C 20.3.1987, DIETER KRAFT, DFVLR OBERPFAFFENHOFEN - - INTEGER JW(*),I,IE,IF,IG,IW,J,K,KRANK,L,LC,LE,LG, - . MC,MC1,ME,MG,MODE,N - DOUBLE PRECISION C(LC,N),E(LE,N),G(LG,N),D(LC),F(LE),H(LG),X(N), - . W(*),T,DDOT,XNRM,DNRM2,EPMACH,ZERO - DATA EPMACH/2.22D-16/,ZERO/0.0D+00/ - - MODE=2 - IF(MC.GT.N) GOTO 75 - L=N-MC - MC1=MC+1 - IW=(L+1)*(MG+2)+2*MG+MC - IE=IW+MC+1 - IF=IE+ME*L - IG=IF+ME - -C TRIANGULARIZE C AND APPLY FACTORS TO E AND G - - DO 10 I=1,MC - J=MIN(I+1,LC) - CALL H12(1,I,I+1,N,C(I,1),LC,W(IW+I),C(J,1),LC,1,MC-I) - CALL H12(2,I,I+1,N,C(I,1),LC,W(IW+I),E ,LE,1,ME) - 10 CALL H12(2,I,I+1,N,C(I,1),LC,W(IW+I),G ,LG,1,MG) - -C SOLVE C*X=D AND MODIFY F - - MODE=6 - DO 15 I=1,MC - IF(ABS(C(I,I)).LT.EPMACH) GOTO 75 - X(I)=(D(I)-DDOT(I-1,C(I,1),LC,X,1))/C(I,I) - 15 CONTINUE - MODE=1 - W(MC1) = ZERO - CALL DCOPY (MG-MC,W(MC1),0,W(MC1),1) - - IF(MC.EQ.N) GOTO 50 - - DO 20 I=1,ME - 20 W(IF-1+I)=F(I)-DDOT(MC,E(I,1),LE,X,1) - -C STORE TRANSFORMED E & G - - DO 25 I=1,ME - 25 CALL DCOPY(L,E(I,MC1),LE,W(IE-1+I),ME) - DO 30 I=1,MG - 30 CALL DCOPY(L,G(I,MC1),LG,W(IG-1+I),MG) - - IF(MG.GT.0) GOTO 40 - -C SOLVE LS WITHOUT INEQUALITY CONSTRAINTS - - MODE=7 - K=MAX(LE,N) - T=SQRT(EPMACH) - CALL HFTI (W(IE),ME,ME,L,W(IF),K,1,T,KRANK,XNRM,W,W(L+1),JW) - CALL DCOPY(L,W(IF),1,X(MC1),1) - IF(KRANK.NE.L) GOTO 75 - MODE=1 - GOTO 50 -C MODIFY H AND SOLVE INEQUALITY CONSTRAINED LS PROBLEM - - 40 DO 45 I=1,MG - 45 H(I)=H(I)-DDOT(MC,G(I,1),LG,X,1) - CALL LSI - . (W(IE),W(IF),W(IG),H,ME,ME,MG,MG,L,X(MC1),XNRM,W(MC1),JW,MODE) - IF(MC.EQ.0) GOTO 75 - T=DNRM2(MC,X,1) - XNRM=SQRT(XNRM*XNRM+T*T) - IF(MODE.NE.1) GOTO 75 - -C SOLUTION OF ORIGINAL PROBLEM AND LAGRANGE MULTIPLIERS - - 50 DO 55 I=1,ME - 55 F(I)=DDOT(N,E(I,1),LE,X,1)-F(I) - DO 60 I=1,MC - 60 D(I)=DDOT(ME,E(1,I),1,F,1)-DDOT(MG,G(1,I),1,W(MC1),1) - - DO 65 I=MC,1,-1 - 65 CALL H12(2,I,I+1,N,C(I,1),LC,W(IW+I),X,1,1,1) - - DO 70 I=MC,1,-1 - J=MIN(I+1,LC) - W(I)=(D(I)-DDOT(MC-I,C(J,I),1,W(J),1))/C(I,I) - 70 CONTINUE - -C END OF SUBROUTINE LSEI - - 75 END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/lsi.f b/pyoptsparse/pyoptsparse/pySLSQP/source/lsi.f deleted file mode 100644 index f668f568d..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/lsi.f +++ /dev/null @@ -1,78 +0,0 @@ - SUBROUTINE LSI(E,F,G,H,LE,ME,LG,MG,N,X,XNORM,W,JW,MODE) - -C FOR MODE=1, THE SUBROUTINE RETURNS THE SOLUTION X OF -C INEQUALITY CONSTRAINED LINEAR LEAST SQUARES PROBLEM: - -C MIN ||E*X-F|| -C X - -C S.T. G*X >= H - -C THE ALGORITHM IS BASED ON QR DECOMPOSITION AS DESCRIBED IN -C CHAPTER 23.5 OF LAWSON & HANSON: SOLVING LEAST SQUARES PROBLEMS - -C THE FOLLOWING DIMENSIONS OF THE ARRAYS DEFINING THE PROBLEM -C ARE NECESSARY -C DIM(E) : FORMAL (LE,N), ACTUAL (ME,N) -C DIM(F) : FORMAL (LE ), ACTUAL (ME ) -C DIM(G) : FORMAL (LG,N), ACTUAL (MG,N) -C DIM(H) : FORMAL (LG ), ACTUAL (MG ) -C DIM(X) : N -C DIM(W) : (N+1)*(MG+2) + 2*MG -C DIM(JW): LG -C ON ENTRY, THE USER HAS TO PROVIDE THE ARRAYS E, F, G, AND H. -C ON RETURN, ALL ARRAYS WILL BE CHANGED BY THE SUBROUTINE. -C X STORES THE SOLUTION VECTOR -C XNORM STORES THE RESIDUUM OF THE SOLUTION IN EUCLIDIAN NORM -C W STORES THE VECTOR OF LAGRANGE MULTIPLIERS IN ITS FIRST -C MG ELEMENTS -C MODE IS A SUCCESS-FAILURE FLAG WITH THE FOLLOWING MEANINGS: -C MODE=1: SUCCESSFUL COMPUTATION -C 2: ERROR RETURN BECAUSE OF WRONG DIMENSIONS (N<1) -C 3: ITERATION COUNT EXCEEDED BY NNLS -C 4: INEQUALITY CONSTRAINTS INCOMPATIBLE -C 5: MATRIX E IS NOT OF FULL RANK - -C 03.01.1980, DIETER KRAFT: CODED -C 20.03.1987, DIETER KRAFT: REVISED TO FORTRAN 77 - - INTEGER I,J,LE,LG,ME,MG,MODE,N,JW(LG) - DOUBLE PRECISION E(LE,N),F(LE),G(LG,N),H(LG),X(N),W(*), - . DDOT,XNORM,DNRM2,EPMACH,T,ONE - DATA EPMACH/2.22D-16/,ONE/1.0D+00/ - -C QR-FACTORS OF E AND APPLICATION TO F - - DO 10 I=1,N - J=MIN(I+1,N) - CALL H12(1,I,I+1,ME,E(1,I),1,T,E(1,J),1,LE,N-I) - 10 CALL H12(2,I,I+1,ME,E(1,I),1,T,F ,1,1 ,1 ) - -C TRANSFORM G AND H TO GET LEAST DISTANCE PROBLEM - - MODE=5 - DO 30 I=1,MG - DO 20 J=1,N - IF (ABS(E(J,J)).LT.EPMACH) GOTO 50 - 20 G(I,J)=(G(I,J)-DDOT(J-1,G(I,1),LG,E(1,J),1))/E(J,J) - 30 H(I)=H(I)-DDOT(N,G(I,1),LG,F,1) - -C SOLVE LEAST DISTANCE PROBLEM - - CALL LDP(G,LG,MG,N,H,X,XNORM,W,JW,MODE) - IF (MODE.NE.1) GOTO 50 - -C SOLUTION OF ORIGINAL PROBLEM - - CALL DAXPY(N,ONE,F,1,X,1) - DO 40 I=N,1,-1 - J=MIN(I+1,N) - 40 X(I)=(X(I)-DDOT(N-I,E(I,J),LE,X(J),1))/E(I,I) - J=MIN(N+1,ME) - T=DNRM2(ME-N,F(J),1) - XNORM=SQRT(XNORM*XNORM+T*T) - -C END OF SUBROUTINE LSI - - 50 END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/lsq.f b/pyoptsparse/pyoptsparse/pySLSQP/source/lsq.f deleted file mode 100644 index 00a673d09..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/lsq.f +++ /dev/null @@ -1,184 +0,0 @@ - SUBROUTINE LSQ(M,MEQ,N,NL,LA,L,G,A,B,XL,XU,X,Y,W,JW,MODE) - -C MINIMIZE with respect to X - -C ||E*X - F|| -C 1/2 T -C WITH UPPER TRIANGULAR MATRIX E = +D *L , - -C -1/2 -1 -C AND VECTOR F = -D *L *G, - -C WHERE THE UNIT LOWER TRIDIANGULAR MATRIX L IS STORED COLUMNWISE -C DENSE IN THE N*(N+1)/2 ARRAY L WITH VECTOR D STORED IN ITS -C 'DIAGONAL' THUS SUBSTITUTING THE ONE-ELEMENTS OF L - -C SUBJECT TO - -C A(J)*X - B(J) = 0 , J=1,...,MEQ, -C A(J)*X - B(J) >=0, J=MEQ+1,...,M, -C XL(I) <= X(I) <= XU(I), I=1,...,N, -C ON ENTRY, THE USER HAS TO PROVIDE THE ARRAYS L, G, A, B, XL, XU. -C WITH DIMENSIONS: L(N*(N+1)/2), G(N), A(LA,N), B(M), XL(N), XU(N) -C THE WORKING ARRAY W MUST HAVE AT LEAST THE FOLLOWING DIMENSION: -c DIM(W) = (3*N+M)*(N+1) for LSQ -c +(N-MEQ+1)*(MINEQ+2) + 2*MINEQ for LSI -c +(N+MINEQ)*(N-MEQ) + 2*MEQ + N for LSEI -c with MINEQ = M - MEQ + 2*N -C ON RETURN, NO ARRAY WILL BE CHANGED BY THE SUBROUTINE. -C X STORES THE N-DIMENSIONAL SOLUTION VECTOR -C Y STORES THE VECTOR OF LAGRANGE MULTIPLIERS OF DIMENSION -C M+N+N (CONSTRAINTS+LOWER+UPPER BOUNDS) -C MODE IS A SUCCESS-FAILURE FLAG WITH THE FOLLOWING MEANINGS: -C MODE=1: SUCCESSFUL COMPUTATION -C 2: ERROR RETURN BECAUSE OF WRONG DIMENSIONS (N<1) -C 3: ITERATION COUNT EXCEEDED BY NNLS -C 4: INEQUALITY CONSTRAINTS INCOMPATIBLE -C 5: MATRIX E IS NOT OF FULL RANK -C 6: MATRIX C IS NOT OF FULL RANK -C 7: RANK DEFECT IN HFTI - -c coded Dieter Kraft, april 1987 -c revised march 1989 - - DOUBLE PRECISION L,G,A,B,W,XL,XU,X,Y, - . DIAG,ZERO,ONE,DDOT,XNORM - - INTEGER JW(*),I,IC,ID,IE,IF,IG,IH,IL,IM,IP,IU,IW, - . I1,I2,I3,I4,LA,M,MEQ,MINEQ,MODE,M1,N,NL,N1,N2,N3 - - DIMENSION A(LA,N), B(LA), G(N), L(NL), - . W(*), X(N), XL(N), XU(N), Y(M+N+N) - - DATA ZERO/0.0D0/, ONE/1.0D0/ - - N1 = N + 1 - MINEQ = M - MEQ - M1 = MINEQ + N + N - -c determine whether to solve problem -c with inconsistent linerarization (n2=1) -c or not (n2=0) - - N2 = N1*N/2 + 1 - IF (N2.EQ.NL) THEN - N2 = 0 - ELSE - N2 = 1 - ENDIF - N3 = N-N2 - -C RECOVER MATRIX E AND VECTOR F FROM L AND G - - I2 = 1 - I3 = 1 - I4 = 1 - IE = 1 - IF = N*N+1 - DO 10 I=1,N3 - I1 = N1-I - DIAG = SQRT (L(I2)) - W(I3) = ZERO - CALL DCOPY (I1 , W(I3), 0, W(I3), 1) - CALL DCOPY (I1-N2, L(I2), 1, W(I3), N) - CALL DSCAL (I1-N2, DIAG, W(I3), N) - W(I3) = DIAG - W(IF-1+I) = (G(I) - DDOT (I-1, W(I4), 1, W(IF), 1))/DIAG - I2 = I2 + I1 - N2 - I3 = I3 + N1 - I4 = I4 + N - 10 CONTINUE - IF (N2.EQ.1) THEN - W(I3) = L(NL) - W(I4) = ZERO - CALL DCOPY (N3, W(I4), 0, W(I4), 1) - W(IF-1+N) = ZERO - ENDIF - CALL DSCAL (N, - ONE, W(IF), 1) - - IC = IF + N - ID = IC + MEQ*N - - IF (MEQ .GT. 0) THEN - -C RECOVER MATRIX C FROM UPPER PART OF A - - DO 20 I=1,MEQ - CALL DCOPY (N, A(I,1), LA, W(IC-1+I), MEQ) - 20 CONTINUE - -C RECOVER VECTOR D FROM UPPER PART OF B - - CALL DCOPY (MEQ, B(1), 1, W(ID), 1) - CALL DSCAL (MEQ, - ONE, W(ID), 1) - - ENDIF - - IG = ID + MEQ - - IF (MINEQ .GT. 0) THEN - -C RECOVER MATRIX G FROM LOWER PART OF A - - DO 30 I=1,MINEQ - CALL DCOPY (N, A(MEQ+I,1), LA, W(IG-1+I), M1) - 30 CONTINUE - - ENDIF - -C AUGMENT MATRIX G BY +I AND -I - - IP = IG + MINEQ - DO 40 I=1,N - W(IP-1+I) = ZERO - CALL DCOPY (N, W(IP-1+I), 0, W(IP-1+I), M1) - 40 CONTINUE - W(IP) = ONE - CALL DCOPY (N, W(IP), 0, W(IP), M1+1) - - IM = IP + N - DO 50 I=1,N - W(IM-1+I) = ZERO - CALL DCOPY (N, W(IM-1+I), 0, W(IM-1+I), M1) - 50 CONTINUE - W(IM) = -ONE - CALL DCOPY (N, W(IM), 0, W(IM), M1+1) - - IH = IG + M1*N - - IF (MINEQ .GT. 0) THEN - -C RECOVER H FROM LOWER PART OF B - - CALL DCOPY (MINEQ, B(MEQ+1), 1, W(IH), 1) - CALL DSCAL (MINEQ, - ONE, W(IH), 1) - - ENDIF - -C AUGMENT VECTOR H BY XL AND XU - - IL = IH + MINEQ - CALL DCOPY (N, XL, 1, W(IL), 1) - IU = IL + N - CALL DCOPY (N, XU, 1, W(IU), 1) - CALL DSCAL (N, - ONE, W(IU), 1) - - IW = IU + N - - CALL LSEI (W(IC), W(ID), W(IE), W(IF), W(IG), W(IH), MAX(1,MEQ), - . MEQ, N, N, M1, M1, N, X, XNORM, W(IW), JW, MODE) - - IF (MODE .EQ. 1) THEN - -c restore Lagrange multipliers - - CALL DCOPY (M, W(IW), 1, Y(1), 1) - CALL DCOPY (N3, W(IW+M), 1, Y(M+1), 1) - CALL DCOPY (N3, W(IW+M+N), 1, Y(M+N3+1), 1) - - ENDIF - -C END OF SUBROUTINE LSQ - - END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/nnls.f b/pyoptsparse/pyoptsparse/pySLSQP/source/nnls.f deleted file mode 100644 index 3b9aed2a9..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/nnls.f +++ /dev/null @@ -1,195 +0,0 @@ - SUBROUTINE NNLS (A, MDA, M, N, B, X, RNORM, W, Z, INDEX, MODE) - -C C.L.LAWSON AND R.J.HANSON, JET PROPULSION LABORATORY: -C 'SOLVING LEAST SQUARES PROBLEMS'. PRENTICE-HALL.1974 - -C ********** NONNEGATIVE LEAST SQUARES ********** - -C GIVEN AN M BY N MATRIX, A, AND AN M-VECTOR, B, COMPUTE AN -C N-VECTOR, X, WHICH SOLVES THE LEAST SQUARES PROBLEM - -C A*X = B SUBJECT TO X >= 0 - -C A(),MDA,M,N -C MDA IS THE FIRST DIMENSIONING PARAMETER FOR THE ARRAY,A(). -C ON ENTRY A() CONTAINS THE M BY N MATRIX,A. -C ON EXIT A() CONTAINS THE PRODUCT Q*A, -C WHERE Q IS AN M BY M ORTHOGONAL MATRIX GENERATED -C IMPLICITLY BY THIS SUBROUTINE. -C EITHER M>=N OR M access=fileaction,iostat=ierror) - - return - end - -C Helper routine to flush buffers to files - subroutine pyflush(unitnum) - - integer unitnum - - call flush(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/slsqp.f b/pyoptsparse/pyoptsparse/pySLSQP/source/slsqp.f deleted file mode 100644 index 07c25a555..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/slsqp.f +++ /dev/null @@ -1,316 +0,0 @@ - SUBROUTINE SLSQP (M,MEQ,LA,N,X,XL,XU,F,C,G,A,ACC,ITER, - 1 IPRINT,IOUT,IFILE,MODE,W,L_W,JW,L_JW,NFUNC,NGRAD, - 2 SLFUNC,SLGRAD) - -C SLSQP S EQUENTIAL L EAST SQ UARES P ROGRAMMING -C TO SOLVE GENERAL NONLINEAR OPTIMIZATION PROBLEMS - -C*********************************************************************** -C* * -C* * -C* A NONLINEAR PROGRAMMING METHOD WITH * -C* QUADRATIC PROGRAMMING SUBPROBLEMS * -C* * -C* * -C* THIS SUBROUTINE SOLVES THE GENERAL NONLINEAR PROGRAMMING PROBLEM * -C* * -C* MINIMIZE F(X) * -C* * -C* SUBJECT TO C (X) .EQ. 0 , J = 1,...,MEQ * -C* J * -C* * -C* C (X) .GE. 0 , J = MEQ+1,...,M * -C* J * -C* * -C* XL .LE. X .LE. XU , I = 1,...,N. * -C* I I I * -C* * -C* THE ALGORITHM IMPLEMENTS THE METHOD OF HAN AND POWELL * -C* WITH BFGS-UPDATE OF THE B-MATRIX AND L1-TEST FUNCTION * -C* WITHIN THE STEPLENGTH ALGORITHM. * -C* * -C* PARAMETER DESCRIPTION: * -C* ( * MEANS THIS PARAMETER WILL BE CHANGED DURING CALCULATION ) * -C* * -C* M IS THE TOTAL NUMBER OF CONSTRAINTS, M .GE. 0 * -C* MEQ IS THE NUMBER OF EQUALITY CONSTRAINTS, MEQ .GE. 0 * -C* LA SEE A, LA .GE. MAX(M,1) * -C* N IS THE NUMBER OF VARIBLES, N .GE. 1 * -C* * X() X() STORES THE CURRENT ITERATE OF THE N VECTOR X * -C* ON ENTRY X() MUST BE INITIALIZED. ON EXIT X() * -C* STORES THE SOLUTION VECTOR X IF MODE = 0. * -C* XL() XL() STORES AN N VECTOR OF LOWER BOUNDS XL TO X. * -C* XU() XU() STORES AN N VECTOR OF UPPER BOUNDS XU TO X. * -C* F IS THE VALUE OF THE OBJECTIVE FUNCTION. * -C* C() C() STORES THE M VECTOR C OF CONSTRAINTS, * -C* EQUALITY CONSTRAINTS (IF ANY) FIRST. * -C* DIMENSION OF C MUST BE GREATER OR EQUAL LA, * -C* which must be GREATER OR EQUAL MAX(1,M). * -C* G() G() STORES THE N VECTOR G OF PARTIALS OF THE * -C* OBJECTIVE FUNCTION; DIMENSION OF G MUST BE * -C* GREATER OR EQUAL N+1. * -C* A(),LA,M,N THE LA BY N + 1 ARRAY A() STORES * -C* THE M BY N MATRIX A OF CONSTRAINT NORMALS. * -C* A() HAS FIRST DIMENSIONING PARAMETER LA, * -C* WHICH MUST BE GREATER OR EQUAL MAX(1,M). * -C* F,C,G,A MUST ALL BE SET BY THE USER BEFORE EACH CALL. * -C* * ACC ABS(ACC) CONTROLS THE FINAL ACCURACY. * -C* IF ACC .LT. ZERO AN EXACT LINESEARCH IS PERFORMED,* -C* OTHERWISE AN ARMIJO-TYPE LINESEARCH IS USED. * -C* * ITER PRESCRIBES THE MAXIMUM NUMBER OF ITERATIONS. * -C* ON EXIT ITER INDICATES THE NUMBER OF ITERATIONS. * -C* * MODE MODE CONTROLS CALCULATION: * -C* REVERSE COMMUNICATION IS USED IN THE SENSE THAT * -C* THE PROGRAM IS INITIALIZED BY MODE = 0; THEN IT IS* -C* TO BE CALLED REPEATEDLY BY THE USER UNTIL A RETURN* -C* WITH MODE .NE. IABS(1) TAKES PLACE. * -C* IF MODE = -1 GRADIENTS HAVE TO BE CALCULATED, * -C* WHILE WITH MODE = 1 FUNCTIONS HAVE TO BE CALCULATED -C* MODE MUST NOT BE CHANGED BETWEEN SUBSEQUENT CALLS * -C* OF SQP. * -C* EVALUATION MODES: * -C* MODE = -1: GRADIENT EVALUATION, (G&A) * -C* 0: ON ENTRY: INITIALIZATION, (F,G,C&A) * -C* ON EXIT : REQUIRED ACCURACY FOR SOLUTION OBTAINED * -C* 1: FUNCTION EVALUATION, (F&C) * -C* * -C* FAILURE MODES: * -C* 2: NUMBER OF EQUALITY CONTRAINTS LARGER THAN N * -C* 3: MORE THAN 3*N ITERATIONS IN LSQ SUBPROBLEM * -C* 4: INEQUALITY CONSTRAINTS INCOMPATIBLE * -C* 5: SINGULAR MATRIX E IN LSQ SUBPROBLEM * -C* 6: SINGULAR MATRIX C IN LSQ SUBPROBLEM * -C* 7: RANK-DEFICIENT EQUALITY CONSTRAINT SUBPROBLEM HFTI* -C* 8: POSITIVE DIRECTIONAL DERIVATIVE FOR LINESEARCH * -C* 9: MORE THAN ITER ITERATIONS IN SQP * -C* >=10: WORKING SPACE W OR JW TOO SMALL, * -C* W SHOULD BE ENLARGED TO L_W=MODE/1000 * -C* JW SHOULD BE ENLARGED TO L_JW=MODE-1000*L_W * -C* * W(), L_W W() IS A ONE DIMENSIONAL WORKING SPACE, * -C* THE LENGTH L_W OF WHICH SHOULD BE AT LEAST * -C* (3*N1+M)*(N1+1) for LSQ * -C* +(N1-MEQ+1)*(MINEQ+2) + 2*MINEQ for LSI * -C* +(N1+MINEQ)*(N1-MEQ) + 2*MEQ + N1 for LSEI * -C* + N1*N/2 + 2*M + 3*N + 3*N1 + 1 for SLSQPB * -C* with MINEQ = M - MEQ + 2*N1 & N1 = N+1 * -C* NOTICE: FOR PROPER DIMENSIONING OF W IT IS RECOMMENDED TO * -C* COPY THE FOLLOWING STATEMENTS INTO THE HEAD OF * -C* THE CALLING PROGRAM (AND REMOVE THE COMMENT C) * -c####################################################################### -C INTEGER LEN_W, LEN_JW, M, N, N1, MEQ, MINEQ -C PARAMETER (M=... , MEQ=... , N=... ) -C PARAMETER (N1= N+1, MINEQ= M-MEQ+N1+N1) -C PARAMETER (LEN_W= -c $ (3*N1+M)*(N1+1) -c $ +(N1-MEQ+1)*(MINEQ+2) + 2*MINEQ -c $ +(N1+MINEQ)*(N1-MEQ) + 2*MEQ + N1 -c $ +(N+1)*N/2 + 2*M + 3*N + 3*N1 + 1, -c $ LEN_JW=MINEQ) -C DOUBLE PRECISION W(LEN_W) -C INTEGER JW(LEN_JW) -c####################################################################### -C* THE FIRST M+N+N*N1/2 ELEMENTS OF W MUST NOT BE * -C* CHANGED BETWEEN SUBSEQUENT CALLS OF SLSQP. * -C* ON RETURN W(1) ... W(M) CONTAIN THE MULTIPLIERS * -C* ASSOCIATED WITH THE GENERAL CONSTRAINTS, WHILE * -C* W(M+1) ... W(M+N(N+1)/2) STORE THE CHOLESKY FACTOR* -C* L*D*L(T) OF THE APPROXIMATE HESSIAN OF THE * -C* LAGRANGIAN COLUMNWISE DENSE AS LOWER TRIANGULAR * -C* UNIT MATRIX L WITH D IN ITS 'DIAGONAL' and * -C* W(M+N(N+1)/2+N+2 ... W(M+N(N+1)/2+N+2+M+2N) * -C* CONTAIN THE MULTIPLIERS ASSOCIATED WITH ALL * -C* ALL CONSTRAINTS OF THE QUADRATIC PROGRAM FINDING * -C* THE SEARCH DIRECTION TO THE SOLUTION X* * -C* * JW(), L_JW JW() IS A ONE DIMENSIONAL INTEGER WORKING SPACE * -C* THE LENGTH L_JW OF WHICH SHOULD BE AT LEAST * -C* MINEQ * -C* with MINEQ = M - MEQ + 2*N1 & N1 = N+1 * -C* * -C* THE USER HAS TO PROVIDE THE FOLLOWING SUBROUTINES: * -C* LDL(N,A,Z,SIG,W) : UPDATE OF THE LDL'-FACTORIZATION. * -C* LINMIN(A,B,F,TOL) : LINESEARCH ALGORITHM IF EXACT = 1 * -C* LSQ(M,MEQ,LA,N,NC,C,D,A,B,XL,XU,X,LAMBDA,W,....) : * -C* * -C* SOLUTION OF THE QUADRATIC PROGRAM * -C* QPSOL IS RECOMMENDED: * -C* PE GILL, W MURRAY, MA SAUNDERS, MH WRIGHT: * -C* USER'S GUIDE FOR SOL/QPSOL: * -C* A FORTRAN PACKAGE FOR QUADRATIC PROGRAMMING, * -C* TECHNICAL REPORT SOL 83-7, JULY 1983 * -C* DEPARTMENT OF OPERATIONS RESEARCH, STANFORD UNIVERSITY * -C* STANFORD, CA 94305 * -C* QPSOL IS THE MOST ROBUST AND EFFICIENT QP-SOLVER * -C* AS IT ALLOWS WARM STARTS WITH PROPER WORKING SETS * -C* * -C* IF IT IS NOT AVAILABLE USE LSEI, A CONSTRAINT LINEAR LEAST * -C* SQUARES SOLVER IMPLEMENTED USING THE SOFTWARE HFTI, LDP, NNLS * -C* FROM C.L. LAWSON, R.J.HANSON: SOLVING LEAST SQUARES PROBLEMS, * -C* PRENTICE HALL, ENGLEWOOD CLIFFS, 1974. * -C* LSEI COMES WITH THIS PACKAGE, together with all necessary SR's. * -C* * -C* TOGETHER WITH A COUPLE OF SUBROUTINES FROM BLAS LEVEL 1 * -C* * -C* SQP IS HEAD SUBROUTINE FOR BODY SUBROUTINE SQPBDY * -C* IN WHICH THE ALGORITHM HAS BEEN IMPLEMENTED. * -C* * -C* IMPLEMENTED BY: DIETER KRAFT, DFVLR OBERPFAFFENHOFEN * -C* as described in Dieter Kraft: A Software Package for * -C* Sequential Quadratic Programming * -C* DFVLR-FB 88-28, 1988 * -C* which should be referenced if the user publishes results of SLSQP * -C* * -C* DATE: APRIL - OCTOBER, 1981. * -C* STATUS: DECEMBER, 31-ST, 1984. * -C* STATUS: MARCH , 21-ST, 1987, REVISED TO FORTAN 77 * -C* STATUS: MARCH , 20-th, 1989, REVISED TO MS-FORTRAN * -C* STATUS: APRIL , 14-th, 1989, HESSE in-line coded * -C* STATUS: FEBRUARY, 28-th, 1991, FORTRAN/2 Version 1.04 * -C* accepts Statement Functions * -C* STATUS: MARCH , 1-st, 1991, tested with SALFORD * -C* FTN77/386 COMPILER VERS 2.40* -C* in protected mode * -C* * -C*********************************************************************** -C* * -C* Copyright 1991: Dieter Kraft, FHM * -C* * -C*********************************************************************** - - INTEGER IL, IM, IR, IS, ITER, IU, IV, IW, IX, L_W, L_JW, - 1 JW(L_JW), LA, M, MEQ, MINEQ, MODE, N, N1, IPRINT, IOUT, - 2 NFUNC, NGRAD, - 3 IEXACT, INCONS, IRESET, ITERMX, LINE, N2, N3 - - DOUBLE PRECISION ACC, A(LA,N+1), C(LA), F, G(N+1), - * X(N), XL(N), XU(N), W(L_W), - * ALPHA, F0, GS, H1, H2, H3, H4, T, T0, TOL - - EXTERNAL SLFUNC,SLGRAD - - CHARACTER*(*) IFILE - -c dim(W) = N1*(N1+1) + MEQ*(N1+1) + MINEQ*(N1+1) for LSQ -c +(N1-MEQ+1)*(MINEQ+2) + 2*MINEQ for LSI -c +(N1+MINEQ)*(N1-MEQ) + 2*MEQ + N1 for LSEI -c + N1*N/2 + 2*M + 3*N +3*N1 + 1 for SLSQPB -c with MINEQ = M - MEQ + 2*N1 & N1 = N+1 - -C -C CHECK LENGTH OF WORKING ARRAYS -C - N1 = N+1 - MINEQ = M-MEQ+N1+N1 - IL = (3*N1+M)*(N1+1) + - .(N1-MEQ+1)*(MINEQ+2) + 2*MINEQ + - .(N1+MINEQ)*(N1-MEQ) + 2*MEQ + - .N1*N/2 + 2*M + 3*N + 4*N1 + 1 - IM = MAX(MINEQ, N1-MEQ) - IF (L_W .LT. IL .OR. L_JW .LT. IM) THEN - MODE = 1000*MAX(10,IL) - MODE = MODE+MAX(10,IM) - RETURN - ENDIF -C -C PRINT PARAMETERS -C - IF(IPRINT.LT.0) GOTO 50 - IF(IPRINT.EQ.0) THEN - WRITE(*,1000) - WRITE(*,1100) ACC,ITER,IPRINT,IOUT - ENDIF - IF(IPRINT.GT.0) THEN - OPEN(UNIT=IOUT,FILE=IFILE(1:LEN_TRIM(IFILE)), - * STATUS='UNKNOWN') - WRITE(IOUT,1000) - WRITE(IOUT,1100) ACC,ITER,IPRINT,IOUT - ENDIF - 50 CONTINUE -C -C INITIAL COUNTERS -C - NFUNC=0 - NGRAD=0 -C -C CALL OF SQPBDY -C - 4 CONTINUE -C -C EVALUATE AND PRINT -C - IF (MODE.EQ.0.OR.MODE.EQ. 1) THEN - CALL SLFUNC(M, MEQ, LA, N, F, C, X) - NFUNC=NFUNC+1 - ENDIF - IF (IPRINT.LT.0) GOTO 60 - IF (MODE.EQ.0.OR.MODE.EQ. 1) GOTO 55 - IF(IPRINT.EQ.0) THEN - WRITE(*,1200) ITER,F - DO 10 I=1,N - 10 WRITE (*,1400) X(I) - ENDIF - IF(IPRINT.GT.0) THEN - WRITE(IOUT,1200) ITER,F -c$$$ DO 12 I=1,N -c$$$ 12 WRITE (IOUT,1400) X(I) - ENDIF - 55 CONTINUE - 60 CONTINUE - IF (MODE.EQ.0.OR.MODE.EQ.-1) THEN - CALL SLGRAD(M, MEQ, LA, N, F, C, G, A, X) - NGRAD=NGRAD+1 - ENDIF -C -C PREPARE DATA FOR CALLING SQPBDY - INITIAL ADDRESSES IN W -C - IM = 1 - IL = IM + MAX(1,M) - IL = IM + LA - IX = IL + N1*N/2 + 1 - IR = IX + N - IS = IR + N + N + MAX(1,M) - IS = IR + N + N + LA - IU = IS + N1 - IV = IU + N1 - IW = IV + N1 -C - CALL SLSQPB (M,MEQ,LA,N,X,XL,XU,F,C,G,A,ACC,ITER,MODE, - * W(IR),W(IL),W(IX),W(IM),W(IS),W(IU),W(IV),W(IW),JW, - * ALPHA,F0,GS,H1,H2,H3,H4,T,T0,TOL,IEXACT,INCONS,IRESET, - * ITERMX,LINE,N1,N2,N3) -C - IF (ABS(MODE).EQ.1) GOTO 4 -C - 3 CONTINUE - -C -C PRINT FINAL -C - IF(IPRINT.GT.0) THEN - WRITE(IOUT,1450) NFUNC - WRITE(IOUT,1460) NGRAD - ENDIF -C -C END OF SLSQP -C - RETURN -C -C ------------------------------------------------------------------ -C FORMATS -C ------------------------------------------------------------------ -C - 1000 FORMAT(////,3X, - 1 60H------------------------------------------------------------, - 2 15H---------------, - 3 /,5X,59HSTART OF THE SEQUENTIAL LEAST SQUARES PROGRAMMING ALGORITHM, - 4 /,3X, - 5 60H------------------------------------------------------------, - 6 15H---------------) - 1100 FORMAT(/,5X,11HPARAMETERS:,/,8X,5HACC =,D13.4,/,8X,9HMAXITER =, - 1 I3,/,8X,8HIPRINT =,I4,/,6HIOUT =,I4//) - 1200 FORMAT(5X,6HITER =,I5,5X,5HOBJ =,7E16.8,5X,10HX-VECTOR =) - 1400 FORMAT (3X,7E13.4) - 1450 FORMAT(8X,30HNUMBER OF FUNC-CALLS: NFUNC =,I4) - 1460 FORMAT(8X,30HNUMBER OF GRAD-CALLS: NGRAD =,I4) -C - END - diff --git a/pyoptsparse/pyoptsparse/pySLSQP/source/slsqpb.f b/pyoptsparse/pyoptsparse/pySLSQP/source/slsqpb.f deleted file mode 100644 index 70c7e736a..000000000 --- a/pyoptsparse/pyoptsparse/pySLSQP/source/slsqpb.f +++ /dev/null @@ -1,292 +0,0 @@ - SUBROUTINE SLSQPB (M, MEQ, LA, N, X, XL, XU, F, C, G, A, ACC, - * ITER, MODE, R, L, X0, MU, S, U, V, W, IW, - * ALPHA, F0, GS, H1, H2, H3, H4, T, T0, TOL, - * IEXACT, INCONS, IRESET, ITERMX, LINE, N1, - * N2, N3) - -C NONLINEAR PROGRAMMING BY SOLVING SEQUENTIALLY QUADRATIC PROGRAMS - -C - L1 - LINE SEARCH, POSITIVE DEFINITE BFGS UPDATE - - -C BODY SUBROUTINE FOR SLSQP - - INTEGER IW(*), I, IEXACT, INCONS, IRESET, ITER, ITERMX, - * K, J, LA, LINE, M, MEQ, MODE, N, N1, N2, N3 - - DOUBLE PRECISION A(LA,N+1), C(LA), G(N+1), L((N+1)*(N+2)/2), - * MU(LA), R(M+N+N+2), S(N+1), U(N+1), V(N+1), W(*), - * X(N), XL(N), XU(N), X0(N), - * DDOT, DNRM2, LINMIN, - * ACC, ALFMIN, ALPHA, F, F0, GS, H1, H2, H3, H4, - * HUN, ONE, T, T0, TEN, TOL, TWO, ZERO - -c dim(W) = N1*(N1+1) + MEQ*(N1+1) + MINEQ*(N1+1) for LSQ -c +(N1-MEQ+1)*(MINEQ+2) + 2*MINEQ -c +(N1+MINEQ)*(N1-MEQ) + 2*MEQ + N1 for LSEI -c with MINEQ = M - MEQ + 2*N1 & N1 = N+1 - - DATA ZERO /0.0D0/, ONE /1.0D0/, ALFMIN /1.0D-1/, - * HUN /1.0D+2/, TEN /1.0D+1/, TWO /2.0D0/ - - IF (MODE) 260, 100, 220 - - 100 ITERMX = ITER - IF (ACC.GE.ZERO) THEN - IEXACT = 0 - ELSE - IEXACT = 1 - ENDIF - ACC = ABS(ACC) - TOL = TEN*ACC - ITER = 0 - IRESET = 0 - N1 = N + 1 - N2 = N1*N/2 - N3 = N2 + 1 - S(1) = ZERO - MU(1) = ZERO - CALL DCOPY(N, S(1), 0, S, 1) - CALL DCOPY(M, MU(1), 0, MU, 1) - -C RESET BFGS MATRIX - - 110 IRESET = IRESET + 1 - IF (IRESET.GT.5) GO TO 255 - L(1) = ZERO - CALL DCOPY(N2, L(1), 0, L, 1) - J = 1 - DO 120 I=1,N - L(J) = ONE - J = J + N1 - I - 120 CONTINUE - -C MAIN ITERATION : SEARCH DIRECTION, STEPLENGTH, LDL'-UPDATE - - 130 ITER = ITER + 1 - MODE = 9 - IF (ITER.GT.ITERMX) GO TO 330 - -C SEARCH DIRECTION AS SOLUTION OF QP - SUBPROBLEM - - CALL DCOPY(N, XL, 1, U, 1) - CALL DCOPY(N, XU, 1, V, 1) - CALL DAXPY(N, -ONE, X, 1, U, 1) - CALL DAXPY(N, -ONE, X, 1, V, 1) - H4 = ONE - CALL LSQ (M, MEQ, N , N3, LA, L, G, A, C, U, V, S, R, W, IW, MODE) - -C AUGMENTED PROBLEM FOR INCONSISTENT LINEARIZATION - - IF (MODE.EQ.6) THEN - IF (N.EQ.MEQ) THEN - MODE = 4 - ENDIF - ENDIF - IF (MODE.EQ.4) THEN - DO 140 J=1,M - IF (J.LE.MEQ) THEN - A(J,N1) = -C(J) - ELSE - A(J,N1) = MAX(-C(J),ZERO) - ENDIF - 140 CONTINUE - S(1) = ZERO - CALL DCOPY(N, S(1), 0, S, 1) - H3 = ZERO - G(N1) = ZERO - L(N3) = HUN - S(N1) = ONE - U(N1) = ZERO - V(N1) = ONE - INCONS = 0 - 150 CALL LSQ (M, MEQ, N1, N3, LA, L, G, A, C, U, V, S, R, - * W, IW, MODE) - H4 = ONE - S(N1) - IF (MODE.EQ.4) THEN - L(N3) = TEN*L(N3) - INCONS = INCONS + 1 - IF (INCONS.GT.5) GO TO 330 - GOTO 150 - ELSE IF (MODE.NE.1) THEN - GOTO 330 - ENDIF - ELSE IF (MODE.NE.1) THEN - GOTO 330 - ENDIF - -C UPDATE MULTIPLIERS FOR L1-TEST - - DO 160 I=1,N - V(I) = G(I) - DDOT(M,A(1,I),1,R,1) - 160 CONTINUE - F0 = F - CALL DCOPY(N, X, 1, X0, 1) - GS = DDOT(N, G, 1, S, 1) - H1 = ABS(GS) - H2 = ZERO - DO 170 J=1,M - IF (J.LE.MEQ) THEN - H3 = C(J) - ELSE - H3 = ZERO - ENDIF - H2 = H2 + MAX(-C(J),H3) - H3 = ABS(R(J)) - MU(J) = MAX(H3,(MU(J)+H3)/TWO) - H1 = H1 + H3*ABS(C(J)) - 170 CONTINUE - -C CHECK CONVERGENCE - - MODE = 0 - IF (H1.LT.ACC .AND. H2.LT.ACC) GO TO 330 - H1 = ZERO - DO 180 J=1,M - IF (J.LE.MEQ) THEN - H3 = C(J) - ELSE - H3 = ZERO - ENDIF - H1 = H1 + MU(J)*MAX(-C(J),H3) - 180 CONTINUE - T0 = F + H1 - H3 = GS - H1*H4 - MODE = 8 - IF (H3.GE.ZERO) GO TO 110 - -C LINE SEARCH WITH AN L1-TESTFUNCTION - - LINE = 0 - ALPHA = ONE - IF (IEXACT.EQ.1) GOTO 210 - -C INEXACT LINESEARCH - - 190 LINE = LINE + 1 - H3 = ALPHA*H3 - CALL DSCAL(N, ALPHA, S, 1) - CALL DCOPY(N, X0, 1, X, 1) - CALL DAXPY(N, ONE, S, 1, X, 1) - MODE = 1 - GO TO 330 - 200 IF (H1.LE.H3/TEN .OR. LINE.GT.10) GO TO 240 - ALPHA = MAX(H3/(TWO*(H3-H1)),ALFMIN) - GO TO 190 - -C EXACT LINESEARCH - - 210 IF (LINE.NE.3) THEN - ALPHA = LINMIN(LINE,ALFMIN,ONE,T,TOL) - CALL DCOPY(N, X0, 1, X, 1) - CALL DAXPY(N, ALPHA, S, 1, X, 1) - MODE = 1 - GOTO 330 - ENDIF - CALL DSCAL(N, ALPHA, S, 1) - GOTO 240 - -C CALL FUNCTIONS AT CURRENT X - - 220 T = F - DO 230 J=1,M - IF (J.LE.MEQ) THEN - H1 = C(J) - ELSE - H1 = ZERO - ENDIF - T = T + MU(J)*MAX(-C(J),H1) - 230 CONTINUE - H1 = T - T0 - GOTO (200, 210) IEXACT+1 - -C CHECK CONVERGENCE - - 240 H3 = ZERO - DO 250 J=1,M - IF (J.LE.MEQ) THEN - H1 = C(J) - ELSE - H1 = ZERO - ENDIF - H3 = H3 + MAX(-C(J),H1) - 250 CONTINUE - IF ((ABS(F-F0).LT.ACC .OR. DNRM2(N,S,1).LT.ACC) .AND. H3.LT.ACC) - * THEN - MODE = 0 - ELSE - MODE = -1 - ENDIF - GO TO 330 - -C CHECK relaxed CONVERGENCE in case of positive directional derivative - - 255 CONTINUE - IF ((ABS(F-F0).LT.TOL .OR. DNRM2(N,S,1).LT.TOL) .AND. H3.LT.TOL) - * THEN - MODE = 0 - ELSE - MODE = 8 - ENDIF - GO TO 330 - -C CALL JACOBIAN AT CURRENT X - -C UPDATE CHOLESKY-FACTORS OF HESSIAN MATRIX BY MODIFIED BFGS FORMULA - - 260 DO 270 I=1,N - U(I) = G(I) - DDOT(M,A(1,I),1,R,1) - V(I) - 270 CONTINUE - -C L'*S - - K = 0 - DO 290 I=1,N - H1 = ZERO - K = K + 1 - DO 280 J=I+1,N - K = K + 1 - H1 = H1 + L(K)*S(J) - 280 CONTINUE - V(I) = S(I) + H1 - 290 CONTINUE - -C D*L'*S - - K = 1 - DO 300 I=1,N - V(I) = L(K)*V(I) - K = K + N1 - I - 300 CONTINUE - -C L*D*L'*S - - DO 320 I=N,1,-1 - H1 = ZERO - K = I - DO 310 J=1,I - 1 - H1 = H1 + L(K)*V(J) - K = K + N - J - 310 CONTINUE - V(I) = V(I) + H1 - 320 CONTINUE - - H1 = DDOT(N,S,1,U,1) - H2 = DDOT(N,S,1,V,1) - H3 = 0.2D0*H2 - IF (H1.LT.H3) THEN - H4 = (H2-H3)/(H2-H1) - H1 = H3 - CALL DSCAL(N, H4, U, 1) - CALL DAXPY(N, ONE-H4, V, 1, U, 1) - ENDIF - CALL LDL(N, L, U, +ONE/H1, V) - CALL LDL(N, L, V, -ONE/H2, U) - -C END OF MAIN ITERATION - - GO TO 130 - -C END OF SLSQPB - - 330 END - \ No newline at end of file diff --git a/pyoptsparse/pyoptsparse/pySNOPT/LICENSE b/pyoptsparse/pyoptsparse/pySNOPT/LICENSE deleted file mode 100644 index ec47e53c0..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -SNOPT - Sparse NOlinear OPTimizer -Copyright (c) 2008, Philip Gill (pgill@ucsd.edu), - Walter Murray (walter@leland.stanford.edu), - and Michael Saunders (saunders@stanford.edu) - -SNOPT is a licensed software, to obtain the program sources and for -term and conditions of use please refer to the specific commercial -or academic agreement with Stanford Business Software Inc. diff --git a/pyoptsparse/pyoptsparse/pySNOPT/README b/pyoptsparse/pyoptsparse/pySNOPT/README deleted file mode 100644 index 5863c11d4..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the snopt class definition -and the snopt shared library, snopt.so or snopt.pyd. diff --git a/pyoptsparse/pyoptsparse/pySNOPT/__init__.py b/pyoptsparse/pyoptsparse/pySNOPT/__init__.py deleted file mode 100644 index e467adb20..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# This file is blank diff --git a/pyoptsparse/pyoptsparse/pySNOPT/pySNOPT.py b/pyoptsparse/pyoptsparse/pySNOPT/pySNOPT.py deleted file mode 100644 index 523a93552..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/pySNOPT.py +++ /dev/null @@ -1,689 +0,0 @@ -#/bin/env python -""" -pySNOPT - A variation of the pySNOPT wrapper specificially designed to -work with sparse optimization problems. - -Copyright (c) 2013-2014 by Dr. Gaetan Kenway -All rights reserved. - -Tested on: ---------- -Linux with intel - -Developers: ------------ -- Dr. Gaetan Kenway (GKK) -- Dr. Graeme Kennedy (GJK) -History -------- - v. 0.1 - Initial Wrapper Creation -""" -from __future__ import absolute_import -from __future__ import print_function -# ============================================================================= -# SNOPT Library -# ============================================================================= -try: - from . import snopt -except ImportError: - snopt = None -# ============================================================================= -# Standard Python modules -# ============================================================================= -import os -import time -# ============================================================================= -# External Python modules -# ============================================================================= -import numpy -# # =========================================================================== -# # Extension modules -# # =========================================================================== -from ..pyOpt_optimizer import Optimizer -from ..pyOpt_error import Error -from ..pyOpt_utils import convertToCSC, ICOL, IDATA, IROW, IROWIND, ICOLP, \ - extractRows, mapToCSC, scaleRows -# ============================================================================= -# SNOPT Optimizer Class -# ============================================================================= -class SNOPT(Optimizer): - """ - SNOPT Optimizer Class - Inherited from Optimizer Abstract Class - """ - - def __init__(self, *args, **kwargs): - """ - SNOPT Optimizer Class Initialization - """ - - name = 'SNOPT' - category = 'Local Optimizer' - defOpts = { - # SNOPT Printing Options - 'Major print level':[int,1], # Majors Print (1 - line major iteration log) - 'Minor print level':[int,1], # Minors Print (1 - line minor iteration log) - 'Print file':[str,'SNOPT_print.out'],# Print File Name (specified by subroutine snInit) - 'iPrint':[int,18], # Print File Output Unit (override internally in snopt?) - 'Summary file':[str,'SNOPT_summary.out'], # Summary File Name (specified by subroutine snInit) - 'iSumm':[int,19], # Summary File Output Unit (override internally in snopt?) - 'Print frequency':[int,100], # Minors Log Frequency on Print File - 'Summary frequency':[int,100], # Minors Log Frequency on Summary File - 'Solution':[str,'Yes'], # Print Solution on the Print File - 'Suppress options listing':[type(None),None], # (options are normally listed) - 'System information':[str,'No'], # Print System Information on the Print File - # SNOPT Problem Specification Options - 'Problem Type':[str,'Minimize'], # Or 'Maximize', or 'Feasible point' - 'Objective row':[int,1], # (has precedence over ObjRow (snOptA)) - 'Infinite bound':[float,1.0e+20], # Infinite Bound Value - # SNOPT Convergence Tolerances Options - 'Major feasibility tolerance':[float,1.0e-6], # Target Nonlinear Constraint Violation - 'Major optimality tolerance':[float,1.0e-6], # Target Complementarity Gap - 'Minor feasibility tolerance':[float,1.0e-6], # For Satisfying the QP Bounds - # SNOPT Derivative Checking Options - 'Verify level':[int,0], # Gradients Check Flag - 'Start objective check at column':[int, 1], # Start the gradient verification at this column - 'Start constraint check at column':[int, 1], - # SNOPT Scaling Options - 'Scale option':[int,1], # Scaling (1 - linear constraints and variables) - 'Scale tolerance':[float,0.9], # Scaling Tolerance - 'Scale Print':[type(None),None], # Default: scales are not printed - # SNOPT Other Tolerances Options - 'Crash tolerance':[float,0.1], - 'Linesearch tolerance':[float,0.9], # smaller for more accurate search - 'Pivot tolerance':[float,3.7e-11], # epsilon^(2/3) - # SNOPT QP subproblems Options - 'QPSolver':[str,'Cholesky'], # Default: Cholesky - 'Crash option':[int,3], # (3 - first basis is essentially triangular) - 'Elastic mode':[str,'No'], # (start with elastic mode until necessary) - 'Elastic weight':[float,1.0e+4], # (used only during elastic mode) - 'Iterations limit':[int,10000], # (or 20*ncons if that is more) - 'Partial price':[int,1], # (10 for large LPs) - 'Start':[str,'Cold'], # has precedence over argument start, ('Warm': alternative to a cold start) - # SNOPT SQP method Options - 'Major iterations limit':[int,1000], # or ncons if that is more - 'Minor iterations limit':[int,500], # or 3*ncons if that is more - 'Major step limit':[float,2.0], - 'Superbasics limit':[int,None], # (n1 + 1, n1 = number of nonlinear variables) - 'Derivative level':[int,3], # (NOT ALLOWED IN snOptA) - 'Derivative option':[int,1], # (ONLY FOR snOptA) - 'Derivative linesearch':[type(None),None], - 'Nonderivative linesearch':[type(None),None], - 'Function precision':[float,3.0e-13], # epsilon^0.8 (almost full accuracy) - 'Difference interval':[float,5.5e-7], # Function precision^(1/2) - 'Central difference interval':[float,6.7e-5], # Function precision^(1/3) - 'New superbasics limit':[int,99], # controls early termination of QPs - 'Objective row':[int,1], # row number of objective in F(x) - 'Penalty parameter':[float,0.0], # initial penalty parameter - 'Proximal point method':[int,1], # (1 - satisfies linear constraints near x0) - 'Reduced Hessian dimension':[int,2000], # (or Superbasics limit if that is less) - 'Violation limit':[float,10.0], # (unscaled constraint violation limit) - 'Unbounded step size':[float,1.0e+18], - 'Unbounded objective':[float,1.0e+15], - # SNOPT Hessian approximation Options - 'Hessian full memory':[type(None),None], # default if n1 <= 75 - 'Hessian limited memory':[type(None),None], # default if n1 > 75 - 'Hessian frequency':[int,999999],# for full Hessian (never reset) - 'Hessian updates':[int,10], # for limited memory Hessian - 'Hessian flush':[int,999999], # no flushing - # SNOPT Frequencies Options - 'Check frequency':[int,60], # test row residuals ||Ax - sk|| - 'Expand frequency':[int,10000], # for anti-cycling procedure - 'Factorization frequency':[int,50], # 100 for LPs - 'Save frequency':[int,100], # save basis map - # SNOPT LUSOL Options - 'LU factor tolerance':[float,3.99], # for NP (100.0 for LP) - 'LU update tolerance':[float,3.99], # for NP ( 10.0 for LP) - 'LU singularity tolerance':[float,3.2e-11], - 'LU partial pivoting':[type(None),None], # default threshold pivoting strategy - 'LU rook pivoting':[type(None),None], # threshold rook pivoting - 'LU complete pivoting':[type(None),None], # threshold complete pivoting - # SNOPT Basis files Options - 'Old basis file':[int,0], # input basis map - 'New basis file':[int,0], # output basis map - 'Backup basis file':[int,0], # output extra basis map - 'Insert file':[int,0], # input in industry format - 'Punch file':[int,0], # output Insert data - 'Load file':[int,0], # input names and values - 'Dump file':[int,0], # output Load data - 'Solution file':[int,0], # different from printed solution - # SNOPT Partitions of cw, iw, rw Options - 'Total character workspace':[int,500], # lencw: 500 - 'Total integer workspace':[int,None], # leniw: 500 + 100 * (m+n) - 'Total real workspace':[int,None], # lenrw: 500 + 200 * (m+n) - 'User character workspace':[int,500], - 'User integer workspace':[int,500], - 'User real workspace':[int,500], - #SNOPT Miscellaneous Options - 'Debug level':[int,1], # (0 - Normal, 1 - for developers) - 'Timing level':[int,3], # (3 - print cpu times) - } - informs = { - 0 : 'finished successfully', - 1 : 'optimality conditions satisfied', - 2 : 'feasible point found', - 3 : 'requested accuracy could not be achieved', - 4 : 'weak QP minimizer', - 10 : 'the problem appears to be infeasible', - 11 : 'infeasible linear constraints', - 12 : 'infeasible linear equalities', - 13 : 'nonlinear infeasibilities minimized', - 14 : 'infeasibilities minimized', - 15 : 'infeasible linear constraints in QP subproblem', - 20 : 'the problem appears to be unbounded', - 21 : 'unbounded objective', - 22 : 'constraint violation limit reached', - 30 : 'resource limit error', - 31 : 'iteration limit reached', - 32 : 'major iteration limit reached', - 33 : 'the superbasics limit is too small', - 40 : 'terminated after numerical difficulties', - 41 : 'current point cannot be improved', - 42 : 'singular basis', - 43 : 'cannot satisfy the general constraints', - 44 : 'ill-conditioned null-space basis', - 50 : 'error in the user-supplied functions', - 51 : 'incorrect objective derivatives', - 52 : 'incorrect constraint derivatives', - 53 : 'the QP Hessian is indefinite', - 54 : 'incorrect second derivatives', - 55 : 'incorrect derivatives', - 60 : 'undefined user-supplied functions', - 61 : 'undefined function at the first feasible point', - 62 : 'undefined function at the initial point', - 63 : 'unable to proceed into undefined region', - 70 : 'user requested termination', - 71 : 'terminated during function evaluation', - 72 : 'terminated during constraint evaluation', - 73 : 'terminated during objective evaluation', - 74 : 'terminated from monitor routine', - 80 : 'insufficient storage allocated', - 81 : 'work arrays must have at least 500 elements', - 82 : 'not enough character storage', - 83 : 'not enough integer storage', - 84 : 'not enough real storage', - 90 : 'input arguments out of range', - 91 : 'invalid input argument', - 92 : 'basis file dimensions do not match this problem', - 93 : 'the QP Hessian is indefinite', - 100 : 'finished successfully', - 101 : 'SPECS file read', - 102 : 'Jacobian structure estimated', - 103 : 'MPS file read', - 104 : 'memory requirements estimated', - 105 : 'user-supplied derivatives appear to be correct', - 106 : 'no derivatives were checked', - 107 : 'some SPECS keywords were not recognized', - 110 : 'errors while processing MPS data', - 111 : 'no MPS file specified', - 112 : 'problem-size estimates too small', - 113 : 'fatal error in the MPS file', - 120 : 'errors while estimating Jacobian structure', - 121 : 'cannot find Jacobian structure at given point', - 130 : 'fatal errors while reading the SP', - 131 : 'no SPECS file (iSpecs le 0 or iSpecs gt 99)', - 132 : 'End-of-file while looking for a BEGIN', - 133 : 'End-of-file while reading SPECS file', - 134 : 'ENDRUN found before any valid SPECS', - 140 : 'system error', - 141 : 'wrong no of basic variables', - 142 : 'error in basis package', - 142 : 'Problem dimensions are too large' - } - - if snopt is None: - raise Error('There was an error importing the compiled \ - snopt module') - - self.set_options = [] - Optimizer.__init__(self, name, category, defOpts, informs, *args, **kwargs) - - # Snopt need jacobians in csc format - self.jacType = 'csc' - - # Snopt specific jacobian map - self._snopt_jac_map_csr_to_csc = None - - # Check if we have numpy version 1.13.1. This version broke the callback in snopt. - if numpy.__version__ == '1.13.1': - raise Error('SNOPT is not compatible with numpy 1.13.1. Please use a different' - 'numpy version') - - - def __call__(self, optProb, sens=None, sensStep=None, sensMode=None, - storeHistory=None, hotStart=None, storeSens=True, - timeLimit=None): - """ - This is the main routine used to solve the optimization - problem. - - Parameters - ---------- - optProb : Optimization or Solution class instance - This is the complete description of the optimization problem - to be solved by the optimizer - - sens : str or python Function. - Specifiy method to compute sensitivities. The default is - None which will use SNOPT's own finite differences which - are vastly superiour to the pyOptSparse implementation. To - explictly use pyOptSparse gradient class to do the - derivatives with finite differenes use 'FD'. 'sens' - may also be 'CS' which will cause pyOptSpare to compute - the derivatives using the complex step method. Finally, - 'sens' may be a python function handle which is expected - to compute the sensitivities directly. For expensive - function evaluations and/or problems with large numbers of - design variables this is the preferred method. - - sensStep : float - Set the step size to use for design variables. Defaults to - 1e-6 when sens is 'FD' and 1e-40j when sens is 'CS'. - - sensMode : str - Use 'pgc' for parallel gradient computations. Only - available with mpi4py and each objective evaluation is - otherwise serial - - storeHistory : str - File name of the history file into which the history of - this optimization will be stored - - hotStart : str - File name of the history file to "replay" for the - optimziation. The optimization problem used to generate - the history file specified in 'hotStart' must be - **IDENTICAL** to the currently supplied 'optProb'. By - identical we mean, **EVERY SINGLE PARAMETER MUST BE - IDENTICAL**. As soon as he requested evaluation point - from SNOPT does not match the history, function and - gradient evaluations revert back to normal evaluations. - - storeSens : bool - Flag sepcifying if sensitivities are to be stored in hist. - This is necessay for hot-starting only. - - timeLimit : float - Specify the maximum amount of time for optimizer to run. - Must be in seconds. This can be useful on queue systems when - you want an optimization to cleanly finish before the - job runs out of time. - """ - - self.callCounter = 0 - self.storeSens = storeSens - - # Store the starting time if the keyword timeLimit is given: - self.timeLimit = timeLimit - self.startTime = None - if self.timeLimit is not None: - self.startTime = time.time() - - if len(optProb.constraints) == 0: - # If the user *actually* has an unconstrained problem, - # snopt sort of chokes with that....it has to have at - # least one constraint. So we will add one - # automatically here: - self.unconstrained = True - optProb.dummyConstraint = True - - self.optProb = optProb - self.optProb.finalizeDesignVariables() - self.optProb.finalizeConstraints() - - self._setInitialCacheValues() - self._setSens(sens, sensStep, sensMode) - blx, bux, xs = self._assembleContinuousVariables() - ff = self._assembleObjective() - - oneSided = False - # Set the number of nonlinear constraints snopt *thinks* we have: - if self.unconstrained: - nnCon = 1 - else: - indices, tmp1, tmp2, fact = self.optProb.getOrdering( - ['ne', 'ni'], oneSided=oneSided) - nnCon = len(indices) - self.optProb.jacIndices = indices - self.optProb.fact = fact - self.optProb.offset = numpy.zeros_like(fact) - - # Again, make SNOPT think we have a nonlinear constraint when all - # our constraints are linear - if nnCon == 0: - nnCon = 1 - self.optProb.jacIndices = [0] - self.optProb.fact = numpy.array([1.0]) - self.optProb.offset = numpy.zeros_like(self.optProb.fact) - - # We make a split here: If the rank is zero we setup the - # problem and run SNOPT, otherwise we go to the waiting loop: - if self.optProb.comm.rank == 0: - - # Determine the sparsity structure of the full jacobian - # ----------------------------------------------------- - - # Gather dummy data and process jacobian: - gcon = {} - for iCon in self.optProb.constraints: - gcon[iCon] = self.optProb.constraints[iCon].jac - - jac = self.optProb.processConstraintJacobian(gcon) - - if self.optProb.nCon > 0: - # We need to reorder this full jacobian...so get ordering: - indices, blc, buc, fact = self.optProb.getOrdering( - ['ne', 'ni', 'le', 'li'], oneSided=oneSided) - jac = extractRows(jac, indices) # Does reordering - scaleRows(jac, fact) # Perform logical scaling - else: - blc = [-1e20] - buc = [1e20] - - if self._snopt_jac_map_csr_to_csc is None: - self._snopt_jac_map_csr_to_csc = mapToCSC(jac) - - # # CSC data is the csr data with the csc_indexing applied - Acol = jac['csr'][IDATA][self._snopt_jac_map_csr_to_csc[IDATA]] - # # CSC Row indices are just the row indices information from the map - indA = self._snopt_jac_map_csr_to_csc[IROW] + 1 - # # CSC Column pointers are the column information from the map - locA = self._snopt_jac_map_csr_to_csc[ICOL] + 1 - - if self.optProb.nCon == 0: - ncon = 1 - else: - ncon = len(indices) - - # Initialize the Print and Summary files - # -------------------------------------- - iPrint = self.getOption('iPrint') - PrintFile = os.path.join(self.getOption('Print file')) - if iPrint != 0 and iPrint != 6: - ierror = snopt.openunit(iPrint, PrintFile, "replace", - "sequential") - if ierror != 0: - raise Error('Failed to properly open %s, ierror = %3d'% - (PrintFile,ierror)) - - iSumm = self.getOption('iSumm') - SummFile = os.path.join(self.getOption('Summary file')) - if iSumm != 0 and iSumm != 6: - ierror = snopt.openunit(iSumm, SummFile, "replace", - "sequential") - if ierror != 0: - raise Error('Failed to properly open %s, ierror = %3d'% - (SummFile, ierror)) - - # Calculate the length of the work arrays - # -------------------------------------- - nvar = self.optProb.ndvs - lencw = 500 - leniw = 500 + 100*(ncon+nvar) - lenrw = 500 + 200*(ncon+nvar) - - self.options['Total integer workspace'][1] = leniw - self.options['Total real workspace'][1] = lenrw - - cw = numpy.empty((lencw, 8), 'c') - iw = numpy.zeros(leniw, numpy.intc) - rw = numpy.zeros(lenrw, numpy.float) - snopt.sninit(iPrint, iSumm, cw, iw, rw) - - # Memory allocation - nnObj = nvar - nnJac = nvar - iObj = numpy.array(0, numpy.intc) - neA = len(indA) - neGcon = neA # The nonlinear Jacobian and A are the same - iExit = 0 - - # Set the options into the SNOPT instance - self._set_snopt_options(iPrint, iSumm, cw, iw, rw) - - mincw, miniw, minrw, cw = snopt.snmemb( - iExit, ncon, nvar, neA, neGcon, nnCon, nnJac, nnObj, - cw, iw, rw) - - if (minrw > lenrw) or (miniw > leniw) or (mincw > lencw): - if mincw > lencw: - lencw = mincw - cw = numpy.array((lencw, 8), 'c') - cw[:] = ' ' - if miniw > leniw: - leniw = miniw - iw = numpy.zeros(leniw, numpy.intc) - if (minrw > lenrw): - lenrw = minrw - rw = numpy.zeros(lenrw, numpy.float) - - snopt.sninit(iPrint, iSumm, cw, iw, rw) - - # snInit resets all the options to the defaults. - # Set them again! - self._set_snopt_options(iPrint, iSumm, cw, iw, rw) - - # Setup argument list values - start = numpy.array(self.options['Start'][1]) - ObjAdd = numpy.array([0.], numpy.float) - ProbNm = numpy.array(self.optProb.name) - xs = numpy.concatenate((xs, numpy.zeros(ncon, numpy.float))) - bl = numpy.concatenate((blx, blc)) - bu = numpy.concatenate((bux, buc)) - lencu = 1 - leniu = 2 - lenru = 3 - cu = numpy.array([" "], 'c') - iu = numpy.zeros(leniu, numpy.intc) - ru = numpy.zeros(lenru, numpy.float) - hs = numpy.zeros(nvar+ncon, numpy.intc) - - Names = numpy.array([" "], 'c') - pi = numpy.zeros(ncon, numpy.float) - rc = numpy.zeros(nvar+ncon, numpy.float) - inform = numpy.array([-1], numpy.intc) - mincw = numpy.array([0], numpy.intc) - miniw = numpy.array([0], numpy.intc) - minrw = numpy.array([0], numpy.intc) - nS = numpy.array([0], numpy.intc) - ninf = numpy.array([0], numpy.intc) - sinf = numpy.array([0.], numpy.float) - - # Set history/hotstart - self._setHistory(storeHistory, hotStart) - - # The snopt c interface - timeA = time.time() - snopt.snoptc(start, nnCon, nnObj, nnJac, iObj, ObjAdd, ProbNm, - self._userfg_wrap, Acol, indA, locA, bl, bu, - Names, hs, xs, pi, rc, inform, mincw, miniw, minrw, - nS, ninf, sinf, ff, cu, iu, ru, cw, iw, rw) - optTime = time.time()-timeA - - # Indicate solution finished - self.optProb.comm.bcast(-1, root=0) - - if self.storeHistory: - # Record the full state of variables, xs and hs such - # that we could perform a warm start. - self.hist.writeData('xs', xs) - self.hist.writeData('hs', hs) - self.hist.close() - - if iPrint != 0 and iPrint != 6: - snopt.closeunit(self.options['iPrint'][1]) - if iSumm != 0 and iSumm != 6: - snopt.closeunit(self.options['iSumm'][1]) - - # Store Results - sol_inform = {} - sol_inform['value'] = inform - sol_inform['text'] = self.informs[inform[0]] - - # Create the optimization solution - sol = self._createSolution(optTime, sol_inform, ff, xs) - - sol.pi = pi # store the lagrange multipliers in the solution - - else: # We are not on the root process so go into waiting loop: - self._waitLoop() - sol = None - - # Communication solution and return - sol = self._communicateSolution(sol) - - return sol - - def _userfg_wrap(self, mode, nnJac, x, fobj, gobj, fcon, gcon, - nState, cu, iu, ru): - """ - The snopt user function. This is what is actually called from snopt. - - Essentially nothing is done in this function, but this funcion - has to precisely match the signature from fortran so must look - EXACTLY like this. - - All we do here is call the generic masterFunc in the baseclass - which will take care of everything else. - """ - # nState >=2 means this is the final call which is redundant - # here we just return without doing anything since we don't - # need to do any cleanup or anything - if nState >= 2: - return - - fail = False - self.iu0 = iu[0] - if mode == 0 or mode == 2: - fobj, fcon, fail = self._masterFunc(x, ['fobj', 'fcon']) - if not fail: - if mode == 1: - if self.getOption('Derivative level') != 0: - gobj, gcon, fail = self._masterFunc(x, ['gobj', 'gcon']) - if mode == 2: - if self.getOption('Derivative level') != 0: - gobj, gcon, fail2 = self._masterFunc(x, ['gobj', 'gcon']) - fail = fail or fail2 - - if fail: - mode = -1 - - # Flush the files to the buffer for all the people who like to - # monitor the residual - snopt.pyflush(self.getOption('iPrint')) - snopt.pyflush(self.getOption('iSumm')) - - # Check if we've exceeded the timeLimit - if self.timeLimit is not None: - if time.time() - self.startTime > self.timeLimit: - mode = -2 # User requested termination - - return mode, fobj, gobj, fcon, gcon - - def _set_snopt_options(self, iPrint, iSumm, cw, iw, rw): - """ - Set all the options into SNOPT that have been assigned - by the user - """ - - # Set Options from the local options dictionary - # --------------------------------------------- - inform = numpy.array([-1], numpy.intc) - for item in self.set_options: - name = item[0] - value = item[1] - - if name == 'iPrint' or name == 'iSumm': - continue - - if isinstance(value, str): - if (name == 'Start'): - if (value == 'Cold'): - snopt.snset('Cold start', iPrint, iSumm, inform, - cw, iw, rw) - elif (value == 'Warm'): - snopt.snset('Warm start', iPrint, iSumm, inform, - cw, iw, rw) - elif (name == 'Problem Type'): - if (value == 'Minimize'): - snopt.snset('Minimize', iPrint, iSumm, inform, - cw, iw, rw) - elif (value == 'Maximize'): - snopt.snset('Maximize', iPrint, iSumm, inform, - cw, iw, rw) - elif (value == 'Feasible point'): - snopt.snset('Feasible point', iPrint, iSumm, inform, - cw, iw, rw) - elif (name == 'Print file'): - snopt.snset(name+' '+'%d'% iPrint, iPrint, iSumm, inform, - cw, iw, rw) - elif (name == 'Summary file'): - snopt.snset(name+' '+'%d'% iSumm, iPrint, iSumm, inform, - cw, iw, rw) - else: - snopt.snset(name+' '+value, iPrint, iSumm, inform, - cw, iw, rw) - elif isinstance(value, float): - snopt.snsetr(name, value, iPrint, iSumm, inform, cw, iw, rw) - elif isinstance(value, int): - snopt.snseti(name, value, iPrint, iSumm, inform, cw, iw, rw) - elif isinstance(value, type(None)): - snopt.snset(name, iPrint, iSumm, inform, cw, iw, rw) - - return - - def _on_setOption(self, name, value): - """ - Set Optimizer Option Value (Optimizer Specific Routine) - - Documentation last updated: May. 07, 2008 - Ruben E. Perez - """ - - self.set_options.append([name, value]) - - - def _on_getOption(self, name): - """ - Get Optimizer Option Value (Optimizer Specific Routine) - - Documentation last updated: May. 07, 2008 - Ruben E. Perez - """ - - pass - - def _on_getInform(self, infocode): - """ - Get Optimizer Result Information (Optimizer Specific Routine) - - Keyword arguments: - ----------------- - id -> STRING: Option Name - - Documentation last updated: May. 07, 2008 - Ruben E. Perez - """ - - # - mjr_code = (infocode[0]/10)*10 - #mnr_code = infocode[0] - 10*mjr_code - try: - inform_text = self.informs[mjr_code] - except: - inform_text = 'Unknown Exit Status' - # end try - - return inform_text - - def _on_flushFiles(self): - """ - Flush the Output Files (Optimizer Specific Routine) - - Documentation last updated: August. 09, 2009 - Ruben E. Perez - """ - - # - iPrint = self.options['iPrint'][1] - iSumm = self.options['iSumm'][1] - if (iPrint != 0): - snopt.pyflush(iPrint) - - if (iSumm != 0): - snopt.pyflush(iSumm) diff --git a/pyoptsparse/pyoptsparse/pySNOPT/setup.py b/pyoptsparse/pyoptsparse/pySNOPT/setup.py deleted file mode 100644 index 290e48fd8..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python - -import os,sys - - -def configuration(parent_package='',top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pySNOPT', parent_package, top_path) - config.add_data_files('LICENSE','README') - - # Since snopt has a bunch of source files, we will just check if - # snoptc.c exists. If so, we will assume all the rest of the files - # are present. - - snoptc = os.path.join('pyoptsparse/pySNOPT/source', 'snoptc.f') - if os.path.exists(snoptc): - config.add_library('snopt', sources=[os.path.join('source', '*.f')]) - config.add_extension('snopt', sources=['source/f2py/snopt.pyf'], - libraries=['snopt']) - return config - diff --git a/pyoptsparse/pyoptsparse/pySNOPT/source/README b/pyoptsparse/pyoptsparse/pySNOPT/source/README deleted file mode 100644 index d4dc3d2fb..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/source/README +++ /dev/null @@ -1,3 +0,0 @@ -This directory contains the Fortran 77 source for -SNOPT, plus two helper files called openunit.f and -closeunit.f to manipulate Fortran units from Python. diff --git a/pyoptsparse/pyoptsparse/pySNOPT/source/closeunit.f b/pyoptsparse/pyoptsparse/pySNOPT/source/closeunit.f deleted file mode 100644 index f1d9f8377..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/source/closeunit.f +++ /dev/null @@ -1,10 +0,0 @@ -C Helper subroutine to close files in the Fortran world - subroutine closeunit(unitnum) - - integer unitnum -Cf2py intent(in) unitnum - - close(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/pySNOPT/source/f2py/README b/pyoptsparse/pyoptsparse/pySNOPT/source/f2py/README deleted file mode 100644 index 54e48d046..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/source/f2py/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory contains the f2py signature file. -Do not edit these file unless you really know what you are doing. diff --git a/pyoptsparse/pyoptsparse/pySNOPT/source/f2py/snopt.pyf b/pyoptsparse/pyoptsparse/pySNOPT/source/f2py/snopt.pyf deleted file mode 100644 index 023ec5a96..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/source/f2py/snopt.pyf +++ /dev/null @@ -1,210 +0,0 @@ -! -*- f90 -*- -! -! Originally written by Joaquim R. R. A. Martins 2000 -! Updates by Patrick LeGresley 2003-2005 -! Last updated: February 13, 2005 -! Tested to work with F2PY Version 2.45.241_1926 on: -! Mac OS X with xlf -! Modified for Snopt 7 by C. Marriage 2007 -! -python module snoptc__user__routines - interface snoptc_user_interface - subroutine userfg( mode, nnObj, nnCon, nnJac, nnL, neJac, x, fObj, gObj, fCon, gCon, nState, cu, lencu, iu, leniu, ru, lenru ) - integer intent(in,out) :: mode - integer intent(in) :: nnObj - integer intent(in) :: nnCon - integer intent(in) :: nnJac - integer intent(in) :: nnL - integer intent(in) :: neJac - integer intent(in) :: nState - double precision intent(in) :: x(nnL) - double precision intent(in, out) :: fObj - double precision intent(in, out) :: gObj(nnObj) - double precision intent(in, out) :: fCon(nnCon) - double precision intent(in, out) :: gCon(neJac) - character*8 intent(in) :: cu(lencu) - integer intent(in) :: lencu - integer intent(in) :: iu(leniu) - integer intent(in) :: leniu - double precision intent(in) :: ru(lenru) - integer intent(in) :: lenru - end subroutine userfg - end interface snoptc_user_interface -end python module snoptc__user__routines -python module snopt ! in - interface ! in :snopt - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) ! in :snopt:openunit.f - integer intent(in) :: unitnum - character*(*) intent(in) :: filename - character*(*) intent(in) :: filestatus - character*(*) intent(in) :: fileaction - integer intent(out) :: ierror - end subroutine openunit - subroutine pyflush(unitnum) - integer unitnum - return - end subroutine pyflush - subroutine closeunit(unitnum) ! in :snopt:closeunit.f - integer intent(in) :: unitnum - end subroutine closeunit - subroutine sninit(iprint,isumm,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - integer :: iprint - integer :: isumm - character*8 intent(in,out), dimension(lencw) :: cw - !integer optional,check(shape(cw,1)==lencw),depend(cw) :: lencw=shape(cw,1) - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine sninit - subroutine snspec(ispecs,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - integer :: ispecs - integer intent(out) :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine snspec - subroutine snmemb(iexit,m,n,ne,negcon,nncon,nnjac,nnobj,mincw,miniw,minrw,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - integer :: iexit - integer :: m - integer :: n - integer :: ne - integer :: negcon - integer :: nncon - integer :: nnjac - integer :: nnobj - integer intent(out) :: mincw - integer intent(out) :: miniw - integer intent(out) :: minrw - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine snmemb - subroutine snset(buffer,iprint,isumm,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - character*(*) :: buffer - integer :: iprint - integer :: isumm - integer :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine snset - subroutine snseti(buffer,ivalue,iprint,isumm,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - character*(*) :: buffer - integer :: ivalue - integer :: iprint - integer :: isumm - integer :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine snseti - subroutine snsetr(buffer,rvalue,iprint,isumm,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - character*(*) :: buffer - double precision :: rvalue - integer :: iprint - integer :: isumm - integer :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine snsetr - subroutine sngetc(buffer,cvalue,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - character*(*) :: buffer - character*8 intent(out) :: cvalue - integer :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine sngetc - subroutine sngeti(buffer,ivalue,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - character*(*) :: buffer - integer intent(out) :: ivalue - integer :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine sngeti - subroutine sngetr(buffer,rvalue,inform,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:sn02lib.f - character*(*) :: buffer - double precision intent(out) :: rvalue - integer :: inform - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine sngetr - subroutine snoptc(start,m,n,ne,nname,nncon,nnobj,nnjac,iobj,objadd,prob,userfg,jcol,indj,locj,bl,bu,names,hs,x,pi,rc,inform,mincw,miniw,minrw,ns,ninf,sinf,obj,cu,lencu,iu,leniu,ru,lenru,cw,lencw,iw,leniw,rw,lenrw) ! in :snopt:snoptc.f - use snoptc__user__routines - character*(*) intent(inout) :: start - integer optional,check(len(pi)>=m),depend(pi) :: m=len(pi) - integer optional,check((len(locj)-1)>=n),depend(locj) :: n=(len(locj)-1) - integer optional,check(len(jcol)>=ne),depend(jcol) :: ne=len(jcol) - integer :: nncon - integer :: nnobj - integer :: nnjac - integer :: iobj - double precision :: objadd - character*8 :: prob - external userfg - double precision dimension(ne) :: jcol - integer intent(inout), dimension(ne),depend(ne) :: indj - integer intent(inout), dimension(n + 1) :: locj - double precision intent(inout), dimension(n+m),depend(m,n) :: bl - double precision intent(inout), dimension(n+m),depend(m,n) :: bu - character*8 intent(in), dimension(nname) :: names - integer optional,check(len(names)==nname),depend(names) :: nname=len(names) - integer intent(inout), dimension(n+m),depend(m,n) :: hs - double precision intent(inout), dimension(n+m),depend(m,n) :: x - double precision intent(inout), dimension(m) :: pi - double precision intent(inout), dimension(n+m),depend(m,n) :: rc - integer intent(inout) :: inform - integer intent(inout) :: mincw - integer intent(inout) :: miniw - integer intent(inout) :: minrw - integer :: ns - integer :: ninf - double precision :: sinf - double precision intent(inout) :: obj - character*8 intent(in,out), dimension(lencu) :: cu - integer optional,check(len(cu)==lencu),depend(cu) :: lencu=len(cu) - integer dimension(leniu) :: iu - integer optional,check(len(iu)>=leniu),depend(iu) :: leniu=len(iu) - double precision dimension(lenru) :: ru - integer optional,check(len(ru)>=lenru),depend(ru) :: lenru=len(ru) - character*8 intent(in,out), dimension(lencw) :: cw - integer optional,check(len(cw)==lencw),depend(cw) :: lencw=len(cw) - integer intent(inout), dimension(leniw) :: iw - integer optional,check(len(iw)>=leniw),depend(iw) :: leniw=len(iw) - double precision dimension(lenrw) :: rw - integer optional,check(len(rw)>=lenrw),depend(rw) :: lenrw=len(rw) - end subroutine snoptc - end interface -end python module snopt - -! This file was auto-generated with f2py (version:2.37.233-1545). -! See http://cens.ioc.ee/projects/f2py2e/ diff --git a/pyoptsparse/pyoptsparse/pySNOPT/source/openunit.f b/pyoptsparse/pyoptsparse/pySNOPT/source/openunit.f deleted file mode 100644 index e67f89660..000000000 --- a/pyoptsparse/pyoptsparse/pySNOPT/source/openunit.f +++ /dev/null @@ -1,29 +0,0 @@ -C Helper subroutine to open files in the Fortran world - subroutine openunit(unitnum,filename,filestatus,fileaction,ierror) - - integer unitnum -Cf2py intent(in) unitnum - character*(*) filename -Cf2py intent(in) filename - character*(*) filestatus -Cf2py intent(in) filestatus - character*(*) fileaction -Cf2py intent(in) fileaction - integer ierror -Cf2py intent(out) ierror - - open(unit=unitnum,file=filename,status=filestatus, - > access=fileaction,iostat=ierror) - - return - end - -C Helper routine to flush buffers to files - subroutine pyflush(unitnum) - - integer unitnum - - call flush(unitnum) - - return - end diff --git a/pyoptsparse/pyoptsparse/setup.py b/pyoptsparse/pyoptsparse/setup.py deleted file mode 100644 index 08eeacfe9..000000000 --- a/pyoptsparse/pyoptsparse/setup.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python - -import os,sys - -def configuration(parent_package='', top_path=None): - - from numpy.distutils.misc_util import Configuration - - config = Configuration('pyoptsparse', parent_package, top_path) - - # need: auto add_subpackage from source availability - config.add_subpackage('pySNOPT') - config.add_subpackage('pyIPOPT') - config.add_subpackage('pySLSQP') - config.add_subpackage('pyCONMIN') - # config.add_subpackage('pyFSQP') - config.add_subpackage('pyNLPQLP') - config.add_subpackage('pyNSGA2') - config.add_subpackage('pyPSQP') - config.add_subpackage('pyNLPY_AUGLAG') - config.add_subpackage('pyALPSO') - # config.add_subpackage('pyNOMAD') - config.add_subpackage('sqlitedict') - config.add_data_files('LICENSE') - - return config - diff --git a/pyoptsparse/pyoptsparse/sqlitedict/Apache_License_2.0.txt b/pyoptsparse/pyoptsparse/sqlitedict/Apache_License_2.0.txt deleted file mode 100644 index d64569567..000000000 --- a/pyoptsparse/pyoptsparse/sqlitedict/Apache_License_2.0.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/pyoptsparse/pyoptsparse/sqlitedict/README.rst b/pyoptsparse/pyoptsparse/sqlitedict/README.rst deleted file mode 100644 index 57f8e107a..000000000 --- a/pyoptsparse/pyoptsparse/sqlitedict/README.rst +++ /dev/null @@ -1,131 +0,0 @@ -================================================================= -sqlitedict -- persistent ``dict``, backed-up by SQLite and pickle -================================================================= - -|Travis|_ -|Downloads|_ -|License|_ - -.. |Travis| image:: https://img.shields.io/travis/piskvorky/sqlitedict.svg -.. |Downloads| image:: https://img.shields.io/pypi/dm/sqlitedict.svg -.. |License| image:: https://img.shields.io/pypi/l/sqlitedict.svg -.. _Travis: https://travis-ci.org/piskvorky/sqlitedict -.. _Downloads: https://pypi.python.org/pypi/sqlitedict -.. _License: https://pypi.python.org/pypi/sqlitedict - -A lightweight wrapper around Python's sqlite3 database with a simple, Pythonic -dict-like interface and support for multi-thread access: - -.. code-block:: python - - >>> from sqlitedict import SqliteDict - >>> mydict = SqliteDict('./my_db.sqlite', autocommit=True) - >>> mydict['some_key'] = any_picklable_object - >>> print mydict['some_key'] # prints the new value - >>> for key, value in mydict.iteritems(): - >>> print key, value - >>> print len(mydict) # etc... all dict functions work - >>> mydict.close() - -Pickle is used internally to (de)serialize the values. Keys are arbitrary strings, -values arbitrary pickle-able objects. - -If you don't use autocommit (default is no autocommit for performance), then -don't forget to call ``mydict.commit()`` when done with a transaction: - -.. code-block:: python - - >>> # using SqliteDict as context manager works too (RECOMMENDED) - >>> with SqliteDict('./my_db.sqlite') as mydict: # note no autocommit=True - ... mydict['some_key'] = u"first value" - ... mydict['another_key'] = range(10) - ... mydict.commit() - ... mydict['some_key'] = u"new value" - ... # no explicit commit here - >>> with SqliteDict('./my_db.sqlite') as mydict: # re-open the same DB - ... print mydict['some_key'] # outputs 'first value', not 'new value' - - -Features --------- - -* Values can be **any picklable objects** (uses ``cPickle`` with the highest protocol). -* Support for **multiple tables** (=dicts) living in the same database file. -* Support for **access from multiple threads** to the same connection (needed by e.g. Pyro). - Vanilla sqlite3 gives you ``ProgrammingError: SQLite objects created in a thread can - only be used in that same thread.`` - -Concurrent requests are still serialized internally, so this "multithreaded support" -**doesn't** give you any performance benefits. It is a work-around for sqlite limitations in Python. - -Installation ------------- - -The module has no dependencies beyond Python itself. The minimum Python version is 2.5, continuously tested on Python 2.6, 2.7, 3.3 and 3.4 `on Travis `_. - -Install or upgrade with:: - - easy_install -U sqlitedict - -or from the `source tar.gz `_:: - - python setup.py install - -Documentation -------------- - -Standard Python document strings are inside the module: - -.. code-block:: python - - >>> import sqlitedict - >>> help(sqlitedict) - -(but it's just ``dict`` with a commit, really). - -**Beware**: because of Python semantics, ``sqlitedict`` cannot know when a mutable -SqliteDict-backed entry was modified in RAM. For example, ``mydict.setdefault('new_key', []).append(1)`` -will leave ``mydict['new_key']`` equal to empty list, not ``[1]``. You'll need to -explicitly assign the mutated object back to SqliteDict to achieve the same effect: - -.. code-block:: python - - >>> val = mydict.get('new_key', []) - >>> val.append(1) # sqlite DB not updated here! - >>> mydict['new_key'] = val # now updated - - -For developers --------------- - -Install:: - - # pip install nose - # pip install coverage - -To perform all tests:: - - # make test-all - -To perform all tests with coverage:: - - # make test-all-with-coverage - - -Comments, bug reports ---------------------- - -``sqlitedict`` resides on `github `_. You can file -issues or pull requests there. - -History -------- - -1.3.0: improve error handling in multithreading (`PR #28 `_); 100% test coverage. - -1.2.0: full python 3 support, continuous testing via `Travis CI `_. - ----- - -``sqlitedict`` is open source software released under the `Apache 2.0 license `_. -Copyright (c) 2011-now `Radim Řehůřek `_ and contributors. diff --git a/pyoptsparse/pyoptsparse/sqlitedict/__init__.py b/pyoptsparse/pyoptsparse/sqlitedict/__init__.py deleted file mode 100644 index 1699d7fe4..000000000 --- a/pyoptsparse/pyoptsparse/sqlitedict/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# this file is blank diff --git a/pyoptsparse/pyoptsparse/sqlitedict/sqlitedict.py b/pyoptsparse/pyoptsparse/sqlitedict/sqlitedict.py deleted file mode 100644 index 9956cde7c..000000000 --- a/pyoptsparse/pyoptsparse/sqlitedict/sqlitedict.py +++ /dev/null @@ -1,461 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# This code is distributed under the terms and conditions -# from the Apache License, Version 2.0 -# -# http://opensource.org/licenses/apache2.0.php -# -# This code was inspired by: -# * http://code.activestate.com/recipes/576638-draft-for-an-sqlite3-based-dbm/ -# * http://code.activestate.com/recipes/526618/ - -""" -A lightweight wrapper around Python's sqlite3 database, with a dict-like interface -and multi-thread access support:: - ->>> mydict = SqliteDict('some.db', autocommit=True) # the mapping will be persisted to file `some.db` ->>> mydict['some_key'] = any_picklable_object ->>> print mydict['some_key'] ->>> print len(mydict) # etc... all dict functions work - -Pickle is used internally to serialize the values. Keys are strings. - -If you don't use autocommit (default is no autocommit for performance), then -don't forget to call `mydict.commit()` when done with a transaction. - -""" - -import sqlite3 -import os -import sys -import tempfile -import random -import logging -import traceback - -from threading import Thread - -_major_version = sys.version_info[0] -if _major_version < 3: # py <= 2.x - if sys.version_info[1] < 5: # py <= 2.4 - raise ImportError("sqlitedict requires python 2.5 or higher (python 3.3 or higher supported)") - - # necessary to use exec()_ as this would be a SyntaxError in python3. - # this is an exact port of six.reraise(): - def exec_(_code_, _globs_=None, _locs_=None): - """Execute code in a namespace.""" - if _globs_ is None: - frame = sys._getframe(1) - _globs_ = frame.f_globals - if _locs_ is None: - _locs_ = frame.f_locals - del frame - elif _locs_ is None: - _locs_ = _globs_ - exec("""exec _code_ in _globs_, _locs_""") - - exec_("def reraise(tp, value, tb=None):\n" - " raise tp, value, tb\n") -else: - def reraise(tp, value, tb=None): - if value is None: - value = tp() - if value.__traceback__ is not tb: - raise value.with_traceback(tb) - raise value - -try: - from cPickle import dumps, loads, HIGHEST_PROTOCOL as PICKLE_PROTOCOL -except ImportError: - from pickle import dumps, loads, HIGHEST_PROTOCOL as PICKLE_PROTOCOL - -# some Python 3 vs 2 imports -try: - from collections import UserDict as DictClass -except ImportError: - from UserDict import DictMixin as DictClass - -try: - from queue import Queue -except ImportError: - from Queue import Queue - - - -logger = logging.getLogger(__name__) - - -def open(*args, **kwargs): - """See documentation of the SqliteDict class.""" - return SqliteDict(*args, **kwargs) - - -def encode(obj): - """Serialize an object using pickle to a binary format accepted by SQLite.""" - return sqlite3.Binary(dumps(obj, protocol=PICKLE_PROTOCOL)) - - -def decode(obj): - """Deserialize objects retrieved from SQLite.""" - return loads(bytes(obj)) - - -class SqliteDict(DictClass): - def __init__(self, filename=None, tablename='unnamed', flag='c', - autocommit=False, journal_mode="DELETE"): - """ - Initialize a thread-safe sqlite-backed dictionary. The dictionary will - be a table `tablename` in database file `filename`. A single file (=database) - may contain multiple tables. - - If no `filename` is given, a random file in temp will be used (and deleted - from temp once the dict is closed/deleted). - - If you enable `autocommit`, changes will be committed after each operation - (more inefficient but safer). Otherwise, changes are committed on `self.commit()`, - `self.clear()` and `self.close()`. - - Set `journal_mode` to 'OFF' if you're experiencing sqlite I/O problems - or if you need performance and don't care about crash-consistency. - - The `flag` parameter: - 'c': default mode, open for read/write, creating the db/table if necessary. - 'w': open for r/w, but drop `tablename` contents first (start with empty table) - 'n': create a new database (erasing any existing tables, not just `tablename`!). - - """ - self.in_temp = filename is None - if self.in_temp: - randpart = hex(random.randint(0, 0xffffff))[2:] - filename = os.path.join(tempfile.gettempdir(), 'sqldict' + randpart) - if flag == 'n': - if os.path.exists(filename): - os.remove(filename) - - dirname = os.path.dirname(filename) - if dirname: - if not os.path.exists(dirname): - raise RuntimeError('Error! The directory does not exist, %s' % dirname) - - self.filename = filename - self.tablename = tablename - - logger.info("opening Sqlite table %r in %s" % (tablename, filename)) - MAKE_TABLE = 'CREATE TABLE IF NOT EXISTS %s (key TEXT PRIMARY KEY, value BLOB)' % self.tablename - self.conn = SqliteMultithread(filename, autocommit=autocommit, journal_mode=journal_mode) - self.conn.execute(MAKE_TABLE) - self.conn.commit() - if flag == 'w': - self.clear() - - def __enter__(self): - return self - - def __exit__(self, *exc_info): - self.close() - - def __str__(self): - return "SqliteDict(%s)" % (self.conn.filename) - - def __repr__(self): - return str(self) # no need of something complex - - def __len__(self): - # `select count (*)` is super slow in sqlite (does a linear scan!!) - # As a result, len() is very slow too once the table size grows beyond trivial. - # We could keep the total count of rows ourselves, by means of triggers, - # but that seems too complicated and would slow down normal operation - # (insert/delete etc). - GET_LEN = 'SELECT COUNT(*) FROM %s' % self.tablename - rows = self.conn.select_one(GET_LEN)[0] - return rows if rows is not None else 0 - - def __bool__(self): - # No elements is False, otherwise True - GET_MAX = 'SELECT MAX(ROWID) FROM %s' % self.tablename - m = self.conn.select_one(GET_MAX)[0] - # Explicit better than implicit and bla bla - return True if m is not None else False - - def keys(self): - GET_KEYS = 'SELECT key FROM %s ORDER BY rowid' % self.tablename - return [key[0] for key in self.conn.select(GET_KEYS)] - - def values(self): - GET_VALUES = 'SELECT value FROM %s ORDER BY rowid' % self.tablename - return [decode(value[0]) for value in self.conn.select(GET_VALUES)] - - def items(self): - GET_ITEMS = 'SELECT key, value FROM %s ORDER BY rowid' % self.tablename - return [(key,decode(value)) for key,value in self.conn.select(GET_ITEMS)] - - def __contains__(self, key): - HAS_ITEM = 'SELECT 1 FROM %s WHERE key = ?' % self.tablename - return self.conn.select_one(HAS_ITEM, (key,)) is not None - - def __getitem__(self, key): - GET_ITEM = 'SELECT value FROM %s WHERE key = ?' % self.tablename - item = self.conn.select_one(GET_ITEM, (key,)) - if item is None: - raise KeyError(key) - return decode(item[0]) - - def __setitem__(self, key, value): - ADD_ITEM = 'REPLACE INTO %s (key, value) VALUES (?,?)' % self.tablename - self.conn.execute(ADD_ITEM, (key, encode(value))) - - def __delitem__(self, key): - if key not in self: - raise KeyError(key) - DEL_ITEM = 'DELETE FROM %s WHERE key = ?' % self.tablename - self.conn.execute(DEL_ITEM, (key,)) - - def update(self, items=(), **kwds): - try: - items = [(k, encode(v)) for k, v in items.items()] - except AttributeError: - pass - - UPDATE_ITEMS = 'REPLACE INTO %s (key, value) VALUES (?, ?)' % self.tablename - self.conn.executemany(UPDATE_ITEMS, items) - if kwds: - self.update(kwds) - - def __iter__(self): - return iter(self.keys()) - - def clear(self): - CLEAR_ALL = 'DELETE FROM %s;' % self.tablename # avoid VACUUM, as it gives "OperationalError: database schema has changed" - self.conn.commit() - self.conn.execute(CLEAR_ALL) - self.conn.commit() - - def commit(self, blocking=True): - """ - Persist all data to disk. - - When `blocking` is False, the commit command is queued, but the data is - not guaranteed persisted (default implication when autocommit=True). - """ - if self.conn is not None: - self.conn.commit(blocking) - sync = commit - - def close(self, do_log=True): - if do_log: - logger.debug("closing %s" % self) - if hasattr(self, 'conn') and self.conn is not None: - if self.conn.autocommit: - # typically calls to commit are non-blocking when autocommit is - # used. However, we need to block on close() to ensure any - # awaiting exceptions are handled and that all data is - # persisted to disk before returning. - self.conn.commit(blocking=True) - self.conn.close() - self.conn = None - if self.in_temp: - try: - os.remove(self.filename) - except: - pass - - def terminate(self): - """Delete the underlying database file. Use with care.""" - self.close() - - if self.filename == ':memory:': - return - - logger.info("deleting %s" % self.filename) - try: - os.remove(self.filename) - except (OSError, IOError): - logger.exception("failed to delete %s" % (self.filename)) - - def __del__(self): - # like close(), but assume globals are gone by now (do not log!) - self.close(do_log=False) - -# Adding extra methods for python 2 compatibility (at import time) -if _major_version == 2: - setattr(SqliteDict, "iterkeys", lambda self: self.keys()) - setattr(SqliteDict, "itervalues", lambda self: self.values()) - setattr(SqliteDict, "iteritems", lambda self: self.items()) - SqliteDict.__nonzero__ = SqliteDict.__bool__ - del SqliteDict.__bool__ # not needed and confusing -#endclass SqliteDict - - -class SqliteMultithread(Thread): - """ - Wrap sqlite connection in a way that allows concurrent requests from multiple threads. - - This is done by internally queueing the requests and processing them sequentially - in a separate thread (in the same order they arrived). - - """ - def __init__(self, filename, autocommit, journal_mode): - super(SqliteMultithread, self).__init__() - self.filename = filename - self.autocommit = autocommit - self.journal_mode = journal_mode - # use request queue of unlimited size - self.reqs = Queue() - self.setDaemon(True) # python2.5-compatible - self.exception = None - self.log = logging.getLogger('sqlitedict.SqliteMultithread') - self.start() - - def run(self): - if self.autocommit: - conn = sqlite3.connect(self.filename, isolation_level=None, check_same_thread=False) - else: - conn = sqlite3.connect(self.filename, check_same_thread=False) - conn.execute('PRAGMA journal_mode = %s' % self.journal_mode) - conn.text_factory = str - cursor = conn.cursor() - cursor.execute('PRAGMA synchronous=OFF') - - res = None - while True: - req, arg, res, outer_stack = self.reqs.get() - if req == '--close--': - assert res, ('--close-- without return queue', res) - break - elif req == '--commit--': - conn.commit() - if res: - res.put('--no more--') - else: - try: - cursor.execute(req, arg) - except Exception as err: - self.exception = (e_type, e_value, e_tb) = sys.exc_info() - inner_stack = traceback.extract_stack() - - # An exception occurred in our thread, but we may not - # immediately able to throw it in our calling thread, if it has - # no return `res` queue: log as level ERROR both the inner and - # outer exception immediately. - # - # Any iteration of res.get() or any next call will detect the - # inner exception and re-raise it in the calling Thread; though - # it may be confusing to see an exception for an unrelated - # statement, an ERROR log statement from the 'sqlitedict.*' - # namespace contains the original outer stack location. - self.log.error('Inner exception:') - for item in traceback.format_list(inner_stack): - self.log.error(item) - self.log.error('') # deliniate traceback & exception w/blank line - for item in traceback.format_exception_only(e_type, e_value): - self.log.error(item) - - self.log.error('') # exception & outer stack w/blank line - self.log.error('Outer stack:') - for item in traceback.format_list(outer_stack): - self.log.error(item) - self.log.error('Exception will be re-raised at next call.') - - - if res: - for rec in cursor: - res.put(rec) - res.put('--no more--') - - if self.autocommit: - conn.commit() - - self.log.debug('received: %s, send: --no more--', req) - conn.close() - res.put('--no more--') - - def check_raise_error(self): - """ - Check for and raise exception for any previous sqlite query. - - For the `execute*` family of method calls, such calls are non-blocking and any - exception raised in the thread cannot be handled by the calling Thread (usually - MainThread). This method is called on `close`, and prior to any subsequent - calls to the `execute*` methods to check for and raise an exception in a - previous call to the MainThread. - """ - if self.exception: - e_type, e_value, e_tb = self.exception - - # clear self.exception, if the caller decides to handle such - # exception, we should not repeatedly re-raise it. - self.exception = None - - self.log.error('An exception occurred from a previous statement, view ' - 'the logging namespace "sqlitedict" for outer stack.') - - # The third argument to raise is the traceback object, and it is - # substituted instead of the current location as the place where - # the exception occurred, this is so that when using debuggers such - # as `pdb', or simply evaluating the naturally raised traceback, we - # retain the original (inner) location of where the exception - # occurred. - reraise(e_type, e_value, e_tb) - - - def execute(self, req, arg=None, res=None): - """ - `execute` calls are non-blocking: just queue up the request and return immediately. - """ - self.check_raise_error() - - # NOTE: This might be a lot of information to pump into an input - # queue, affecting performance. I've also seen earlier versions of - # jython take a severe performance impact for throwing exceptions - # so often. - stack = traceback.extract_stack()[:-1] - self.reqs.put((req, arg or tuple(), res, stack)) - - def executemany(self, req, items): - for item in items: - self.execute(req, item) - self.check_raise_error() - - def select(self, req, arg=None): - """ - Unlike sqlite's native select, this select doesn't handle iteration efficiently. - - The result of `select` starts filling up with values as soon as the - request is dequeued, and although you can iterate over the result normally - (`for res in self.select(): ...`), the entire result will be in memory. - """ - res = Queue() # results of the select will appear as items in this queue - self.execute(req, arg, res) - while True: - rec = res.get() - self.check_raise_error() - if rec == '--no more--': - break - yield rec - - def select_one(self, req, arg=None): - """Return only the first row of the SELECT, or None if there are no matching rows.""" - try: - return next(iter(self.select(req, arg))) - except StopIteration: - return None - - def commit(self, blocking=True): - if blocking: - # by default, we await completion of commit() unless - # blocking=False. This ensures any available exceptions for any - # previous statement are thrown before returning, and that the - # data has actually persisted to disk! - self.select_one('--commit--') - else: - # otherwise, we fire and forget as usual. - self.execute('--commit--') - - def close(self): - # we abuse 'select' to "iter" over a "--close--" statement so that we - # can confirm the completion of close before joining the thread and - # returning (by semaphore '--no more--' - self.select_one('--close--') - self.join() -#endclass SqliteMultithread diff --git a/pyoptsparse/setup.py b/pyoptsparse/setup.py deleted file mode 100644 index 2b648f170..000000000 --- a/pyoptsparse/setup.py +++ /dev/null @@ -1,76 +0,0 @@ -from __future__ import print_function - -import os -import sys - -os.environ['NPY_DISTUTILS_APPEND_FLAGS'] = '1' - -# Check if we have numpy: -try: - from numpy.distutils.misc_util import Configuration - import numpy.distutils.core - from setuptools import setup -except: - raise ImportError('pyOptSparse requires numpy version 1.0 or later') - -# HACK to make bdist_wheel command usable when using numpy.distutils.core.setup -try: - from wheel import bdist_wheel -except ImportError: - if 'bdist_wheel' in sys.argv: - print("\nThe bdist_wheel option requires the 'wheel' package to be installed.\n" - "Install it using 'pip install wheel'.") - sys.exit(-1) -else: - numpy.distutils.core.numpy_cmdclass['bdist_wheel'] = bdist_wheel.bdist_wheel - - -if len(sys.argv) == 1: - print("\nTo install, run: python setup.py install --user\n\n" - "To build, run: python setup.py build_ext --inplace\n\n" - "For help on C-compiler options run: python setup.py build --help-compiler\n\n" - "For help on Fortran-compiler options run: python setup.py build --help-fcompiler\n\n" - "To specify a Fortran compiler to use run: python setup.py install --user --fcompiler=\n\n" - "For further help run: python setup.py build --help" - ) - sys.exit(-1) - - -def configuration(parent_package='', top_path=None): - config = Configuration(None, parent_package, top_path) - config.set_options(ignore_setup_xxx_py=True, - assume_default_configuration=True, - delegate_options_to_subpackages=True, - quiet=True) - config.add_subpackage('pyoptsparse') - return config - - -setup( - name = 'pyoptsparse', - version = '1.0.0', - author = 'Dr. Gaetan Kenway', - author_email = 'gaetank@gmail.com', - maintainer = 'Dr. Gaetan Kenway', - maintainer_email = 'gaetank@gmail.com', - description = 'Python package for formulating and solving nonlinear constrained optimization problems', - long_description = 'pyOptSparse is a Python package for formulating and solving nonlinear constrained optimization problems', - keywords = 'optimization', - license = 'GNU LGPL', - platforms = ['Windows','Linux','Solaris','Mac OS-X','Unix'], - classifiers = ['Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Science/Research', - 'Intended Audience :: Developers', - 'Intended Audience :: Education', - 'License :: LGPL', - 'Operating System :: Microsoft :: Windows', - 'Operating System :: POSIX :: Linux', - 'Operating System :: Unix', - 'Operating System :: MacOS', - 'Programming Language :: Python', - 'Topic :: Scientific/Engineering', - 'Topic :: Software Development', - 'Topic :: Education'], - configuration = configuration, -) diff --git a/pyoptsparse/test/test_hs015.py b/pyoptsparse/test/test_hs015.py deleted file mode 100644 index a19a80b90..000000000 --- a/pyoptsparse/test/test_hs015.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Test solution of problem HS15 from the Hock & Schittkowski collection""" -from __future__ import print_function - -import unittest - -import numpy -from pyoptsparse import Optimization, OPT - - -class TestHS15(unittest.TestCase): - - ## Solve test problem HS15 from the Hock & Schittkowski collection. - # - # min 100 (x2 - x1^2)^2 + (1 - x1)^2 - # s.t. x1 x2 >= 1 - # x1 + x2^2 >= 0 - # x1 <= 0.5 - # - # The standard start point (-2, 1) usually converges to the standard - # minimum at (0.5, 2.0), with final objective = 306.5. - # Sometimes the solver converges to another local minimum - # at (-0.79212, -1.26243), with final objective = 360.4. - ## - - def objfunc(self, xdict): - x = xdict['xvars'] - funcs = {} - funcs['obj'] = [100*(x[1] - x[0]**2)**2 + (1-x[0])**2] - conval = numpy.zeros(2, 'D') - conval[0] = x[0]*x[1] - conval[1] = x[0] + x[1]**2 - funcs['con'] = conval - fail = False - return funcs, fail - - def sens(self, xdict, funcs): - x = xdict['xvars'] - funcsSens = {} - funcsSens['obj'] = {'xvars': [2*100*(x[1]-x[0]**2)*(-2*x[0]) - 2*(1-x[0]), - 2*100*(x[1]-x[0]**2)]} - funcsSens['con'] = {'xvars': [[x[1], x[0]], - [1, 2*x[1]]]} - fail = False - - return funcsSens, fail - - def optimize(self, optName, optOptions={}, storeHistory=False): - # Optimization Object - optProb = Optimization('HS15 Constraint Problem', self.objfunc) - - # Design Variables - lower = [-5.0, -5.0] - upper = [0.5, 5.0] - value = [-2, 1.0] - optProb.addVarGroup('xvars', 2, lower=lower, upper=upper, value=value) - - # Constraints - lower = [1.0, 0.0] - upper = [None, None] - optProb.addConGroup('con', 2, lower=lower, upper=upper) - - # Objective - optProb.addObj('obj') - - # Check optimization problem: - # print(optProb) - - # Optimizer - try: - opt = OPT(optName, options=optOptions) - except: - raise unittest.SkipTest('Optimizer not available:', optName) - - # Solution - if storeHistory: - histFileName = '%s_hs015_Hist.hst' % (optName.lower()) - else: - histFileName = None - - sol = opt(optProb, sens=self.sens, storeHistory=histFileName) - - # Check Solution - self.assertAlmostEqual(sol.objectives['obj'].value, 306.5, places=5) - - self.assertAlmostEqual(sol.variables['xvars'][0].value, 0.5) - self.assertAlmostEqual(sol.variables['xvars'][1].value, 2.0) - - def test_snopt(self): - self.optimize('snopt') - - def test_slsqp(self): - self.optimize('slsqp') - - def test_nlpqlp(self): - self.optimize('nlpqlp') - - def test_fsqp(self): - self.optimize('fsqp') - - def test_ipopt(self): - self.optimize('ipopt') - - def test_conmin(self): - opts = {'DELFUN' : 1e-9, - 'DABFUN' : 1e-9} - self.optimize('conmin', optOptions=opts) - - def test_psqp(self): - self.optimize('psqp') - - -if __name__ == "__main__": - unittest.main() diff --git a/pyoptsparse/test/test_hs071.py b/pyoptsparse/test/test_hs071.py deleted file mode 100644 index a33e1e8f5..000000000 --- a/pyoptsparse/test/test_hs071.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Test solution of problem HS71 from the Hock & Schittkowski collection""" -from __future__ import print_function - -import unittest - -import numpy -from pyoptsparse import Optimization, OPT - - -def objfunc(xdict): - x = xdict['xvars'] - funcs = {} - funcs['obj'] = x[0] * x[3] * (x[0] + x[1] + x[2]) + x[2] - funcs['con'] = [x[0] * x[1] * x[2] * x[3], - x[0]*x[0] + x[1]*x[1] + x[2]*x[2] + x[3]*x[3]] - fail = False - return funcs, fail - - -def sens(xdict, funcs): - x = xdict['xvars'] - funcsSens = {} - funcsSens['obj'] = {'xvars': numpy.array( - [x[0] * x[3] + x[3] * (x[0] + x[1] + x[2]) , - x[0] * x[3], - x[0] * x[3] + 1.0, - x[0] * (x[0] + x[1] + x[2]) - ])} - jac = [[x[1]*x[2]*x[3], x[0]*x[2]*x[3], x[0]*x[1]*x[3], x[0]*x[1]*x[2]], - [2.0*x[0], 2.0*x[1], 2.0*x[2], 2.0*x[3]]] - funcsSens['con'] = {'xvars': jac} - fail = False - return funcsSens, fail - - -class TestHS71(unittest.TestCase): - - def optimize(self, optName, optOptions={}, storeHistory=False, places=5): - # Optimization Object - optProb = Optimization('HS071 Constraint Problem', objfunc) - - # Design Variables - x0 = [1.0, 5.0, 5.0, 1.0] - optProb.addVarGroup('xvars', 4, lower=1, upper=5, value=x0) - - # Constraints - optProb.addConGroup('con', 2, lower=[25, 40], upper=[1e19, 40]) - - # Objective - optProb.addObj('obj') - - # Optimizer - try: - opt = OPT(optName, options=optOptions) - except: - raise unittest.SkipTest('Optimizer not available:', optName) - - sol = opt(optProb, sens=sens) - - # Check Solution - self.assertAlmostEqual(sol.objectives['obj'].value, 17.0140172, places=places) - - self.assertAlmostEqual(sol.variables['xvars'][0].value, 1.0, places=places) - self.assertAlmostEqual(sol.variables['xvars'][1].value, 4.743, places=places) - self.assertAlmostEqual(sol.variables['xvars'][2].value, 3.82115, places=places) - self.assertAlmostEqual(sol.variables['xvars'][3].value, 1.37941, places=places) - - def test_snopt(self): - self.optimize('snopt') - - def test_slsqp(self): - self.optimize('slsqp') - - def test_nlpqlp(self): - self.optimize('nlpqlp') - - def test_fsqp(self): - self.optimize('fsqp') - - def test_ipopt(self): - self.optimize('ipopt') - - def test_conmin(self): - opts = {'DELFUN' : 1e-9, - 'DABFUN' : 1e-9} - self.optimize('conmin', optOptions=opts, places=2) - - def test_psqp(self): - self.optimize('psqp') - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/pyoptsparse/test/test_large_sparse.py b/pyoptsparse/test/test_large_sparse.py deleted file mode 100644 index eebd95d37..000000000 --- a/pyoptsparse/test/test_large_sparse.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -This example is taken from the OpenOpt Examples website. - -http://trac.openopt.org/openopt/browser/PythonPackages/FuncDesigner/FuncDesigner/examples/nlpSparse.py - -Only testing with SNOPT, which supports sparse formats. -""" -from __future__ import print_function - -import unittest - -import numpy -from numpy import arange -from scipy import sparse - -from pyoptsparse import Optimization, OPT - -N = 50000 - -def objfunc(xdict): - x = xdict['x']; y = xdict['y']; z = xdict['z'] - funcs = {} - funcs['obj'] = x**2 + 2*numpy.sum(y**2) + 3*numpy.sum(z) - funcs['con1'] = x + 1e-3*abs(x)**2.05 - funcs['con2'] = x**4 + numpy.sum(y) + numpy.sum(z**2) - funcs['con3'] = x + numpy.sum(z) - - return funcs, False - -def sens(xdict, funcs): - x = xdict['x']; y = xdict['y']; z = xdict['z'] - funcsSens = {} - funcsSens = {('obj', 'x') : [2*x], - ('obj', 'y') : 4*y, - ('obj', 'z') : 3*numpy.ones(2*N), - ('con1', 'x') : 2.05*x*(x*x)**0.025, - ('con2', 'x') : 4*x**3, - ('con2', 'y') : numpy.ones(N), - ('con2', 'z') : 2*z, - ('con3', 'x') : 1.0, - ('con3', 'z') : numpy.ones(2*N)} - - return funcsSens, False - -class TestLargeSparse(unittest.TestCase): - - def optimize(self, optName, optOptions={}, storeHistory=False, places=5): - # Optimization Object - optProb = Optimization('large and sparse', objfunc) - - # Design Variables - optProb.addVar('x', lower=-100, upper=150, value=0) - optProb.addVarGroup('y', N, lower=-10-arange(N), upper=arange(N), value=0) - optProb.addVarGroup('z', 2*N, upper=arange(2*N), lower=-100-arange(2*N), value=0) - - # Constraints - optProb.addCon('con1', upper=100, wrt=['x']) - optProb.addCon('con2', upper=100) - optProb.addCon('con3', lower=4, wrt=['x','z']) - optProb.addConGroup('lincon', N, lower=2-3*arange(N), linear=True, - wrt=['x','y'], - jac={'x': numpy.ones((N, 1)), - 'y':sparse.spdiags(numpy.ones(N), 0, N, N)}) - optProb.addObj('obj') - - # Optimizer - try: - opt = OPT(optName, options=optOptions) - except: - raise unittest.SkipTest('Optimizer not available:', optName) - - sol = opt(optProb, sens=sens) - - # Check Solution - self.assertAlmostEqual(sol.objectives['obj'].value, 10.0, places=places) - - self.assertAlmostEqual(sol.variables['x'][0].value, 2.0, places=places) - - def test_snopt(self): - self.optimize('snopt') - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/pyoptsparse/test/test_nsga2_multi_objective.py b/pyoptsparse/test/test_nsga2_multi_objective.py deleted file mode 100644 index ca9f8d19f..000000000 --- a/pyoptsparse/test/test_nsga2_multi_objective.py +++ /dev/null @@ -1,53 +0,0 @@ -""" Test NSGA2.""" -from __future__ import print_function - -import unittest - -from pyoptsparse import Optimization, NSGA2 - - -def objfunc(xdict): - x = xdict['x'] - y = xdict['y'] - - funcs = {} - funcs['obj1'] = (x - 0.0)**2 + (y - 0.0)**2 - funcs['obj2'] = (x - 1.0)**2 + (y - 1.0)**2 - - fail = False - - return funcs, fail - - -class TestNSGA2(unittest.TestCase): - - def test_opt(self): - # Instantiate Optimization Problem - optProb = Optimization('Rosenbrock function', objfunc) - optProb.addVar('x', 'c', value=0, lower=-600, upper=600) - optProb.addVar('y', 'c', value=0, lower=-600, upper=600) - - optProb.addObj('obj1') - optProb.addObj('obj2') - - #300 generations will find x=(0,0), 200 or less will find x=(1,1) - options = { - 'maxGen':200 - } - - # Optimizer - try: - opt = NSGA2(options=options) - except: - raise unittest.SkipTest('Optimizer not available:', optName) - - sol = opt(optProb) - - # Check Solution - self.assertAlmostEqual(sol.variables['x'][0].value, 1.0, places=2) - - self.assertAlmostEqual(sol.variables['y'][0].value, 1.0, places=2) - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/pyoptsparse/test/test_snopt_bugfix.py b/pyoptsparse/test/test_snopt_bugfix.py deleted file mode 100644 index 0e74fd875..000000000 --- a/pyoptsparse/test/test_snopt_bugfix.py +++ /dev/null @@ -1,83 +0,0 @@ -# This example shows a bug where pySNOPT wouldn't optimize a model that has -# only equality constraints because it thought the problem was trivial. The -# problem is a simple paraboloid. The minimum should be at (7.166667, -# -7.833334), but with the bug, x and y stay at zero. - -from __future__ import print_function -import unittest - -import numpy as np - -from pyoptsparse import Optimization, SNOPT - - -def objfunc(xdict): - """ Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 """ - x = xdict['x'] - y = xdict['y'] - funcs = {} - - funcs['obj'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0 - conval = -x + y - funcs['con'] = conval - - fail = False - return funcs, fail - -def sens(xdict, funcs): - """f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 - """ - x = xdict['x'] - y = xdict['y'] - funcsSens = {} - - funcsSens['obj', 'x'] = 2.0*x - 6.0 + y - funcsSens['obj', 'y'] = 2.0*y + 8.0 + x - #funcsSens['con', 'x'] = -1.0 - #funcsSens['con', 'y'] = 1.0 - - fail = False - return funcsSens, fail - - -con_jac = {} -con_jac['x'] = np.array(-1.0) -con_jac['y'] = np.array(1.0) - - -class TestSNOPTBug(unittest.TestCase): - - def test_opt(self): - # Optimization Object - optProb = Optimization('Paraboloid', objfunc) - - # Design Variables - optProb.addVarGroup('x', 1, type='c', lower=-50.0, upper=50.0, value=0.0) - optProb.addVarGroup('y', 1, type='c', lower=-50.0, upper=50.0, value=0.0) - optProb.finalizeDesignVariables() - - # Objective - optProb.addObj('obj') - - # Equality Constraint - optProb.addConGroup('con', 1, lower=-15.0, upper=-15.0, wrt=['x', 'y'], linear=True, jac=con_jac) - - # Check optimization problem: - print(optProb) - - - # Optimizer - try: - opt = SNOPT(optOptions = {'Major feasibility tolerance' : 1e-1}) - except: - raise unittest.SkipTest('Optimizer not available: SNOPT') - - sol = opt(optProb, sens=sens) - - # Check Solution 7.166667, -7.833334 - self.assertAlmostEqual(sol.variables['x'][0].value, 7.166667, places=6) - self.assertAlmostEqual(sol.variables['y'][0].value, -7.833333, places=6) - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/pyoptsparse/test/test_tp109.py b/pyoptsparse/test/test_tp109.py deleted file mode 100644 index e0129ed48..000000000 --- a/pyoptsparse/test/test_tp109.py +++ /dev/null @@ -1,174 +0,0 @@ -""" -Test uses Schittkowski's TP109 constraint problem. - - min 3.0*x1+1.*10**(-6)*x1**3+0.522074*10**(-6)*x2**3+2.0*x2 - s.t. -(x4-x3+0.550) <= 0 - -(x3-x4+0.550) <= 0 - -(2.25*10**(+6)-x1**2-x8**2) <= 0 - -(2.25*10**(+6)-x2**2-x9**2) <= 0 - -(x5*x6*sin(-x3-0.250) + +x5*x7*sin(-x4-0.250)+2.0*x5**2*b)*ra+400.0-x1 = 0 - -((x5*x6*sin(x3-0.250)+x6*x7*sin(x3-x4-0.250)+2.0*x6**2*b)*ra+400.0-x2) = 0 - -((x5*x7*sin(x4-0.250)+x6*x7*sin(x4-x3-0.250)+2.0*x7**2*b)*ra+881.7790) = 0 - -(x8+(x5*x6*cos(-x3-0.250)+x5*x7*cos(-x4-0.250)-2.0*x5**2*c)*ra+0.7533*10**(-3)*x5**2-200.00) = 0 - -(x9+(x5*x6*cos(x3-0.250)+x7*x6*cos(x3-x4-0.250)-2.0*x6**2*c)*ra+0.7533*10**(-3)*x(6)**2-200.00) = 0 - -((x5*x7*cos(x4-0.250)+x6*x7*cos(x4-x3-0.250)-2.0*x7**2*c)*ra+0.7533*10**(-3)*x7**2-22.9380) = 0 - 0 <= xi, i = 1,2 - -0.55 <= xi <= 0.55, i = 3,4 - 196.0 <= xi <= 252.0, i = 5,6,7 - -400.0 <= xi <= 800.0, i = 8,9 - where a = 50.176 - b = sin(0.25) - c = cos(0.25) - ra = 1.0/50.176 - - - f*1 = 0.536206927538e+04 - x*1 = [0.674888100445e+03, 0.113417039470e+04, 0.133569060261e+00, -0.371152592466e+00, 0.252e+03, 0.252e+03, 0.201464535316e+03, 0.426660777226e+03, 0.368494083867e+03] -""" -from __future__ import print_function -import unittest - -import numpy -from numpy import sin, cos - -from pyoptsparse import Optimization, OPT - -USE_LINEAR = True - - -def objfunc(xdict): - x = xdict['xvars'] - - a = 50.1760 - b = sin(0.250) - c = cos(0.250) - funcs = {} - funcs['obj'] = 3.0*x[0] + (1e-6)*x[0]**3 + 0.522074e-6*x[1]**3 + 2*x[1] - fcon = numpy.zeros(10,'D') - fcon[0] = 2250000 - x[0]**2 - x[7]**2 - fcon[1] = 2250000 - x[1]**2 - x[8]**2 - fcon[2] = x[4]*x[5]*sin(-x[2]-0.25) + x[4]*x[6]*sin(-x[3] - 0.25) + 2*b*x[4]**2 - a*x[0] + 400*a - fcon[3] = x[4]*x[5]*sin(x[2] - 0.25) + x[5]*x[6]*sin(x[2] - x[3] - 0.25) + 2*b*x[5]**2 - a*x[1] + 400*a - fcon[4] = x[4]*x[6]*sin(x[3] - 0.25) + x[5]*x[6]*sin(x[3] - x[2] - 0.25) + 2*b*x[6]**2 + 881.779*a - fcon[5] = a*x[7] + x[4]*x[5]*cos(-x[2] - 0.25) + x[4]*x[6]*cos(-x[3] - 0.25) - 200*a - 2*c*x[4]**2 + 0.7533e-3*a*x[4]**2 - fcon[6] = a*x[8] + x[4]*x[5]*cos(x[2]-0.25) + x[5]*x[6]*cos(x[2] - x[3] - 0.25) - 2*c*x[5]**2 + 0.7533e-3*a*x[5]**2 - 200*a - fcon[7] = x[4]*x[6]*cos(x[3] - 0.25) + x[5]*x[6]*cos(x[3] - x[2] - 0.25) - 2*c*x[6]**2 - 22.938*a + 0.7533e-3*a*x[6]**2 - fcon[8] = x[3] - x[2] + 0.55 - fcon[9] = x[2] - x[3] + 0.55 - - if USE_LINEAR: - funcs['con'] = fcon[0:8] - else: - funcs['con'] = fcon[0:10] - fail = False - - return funcs, fail - - -class TestTP109(unittest.TestCase): - - def optimize(self, optName, optOptions={}, places=2): - # Optimization Object - optProb = Optimization('TP109 Constraint Problem', objfunc) - - # Design Variables - lower = [0.0, 0.0, -0.55, -0.55, 196, 196, 196, -400, -400] - upper = [None, None, 0.55, 0.55, 252, 252, 252, 800, 800] - value = [0, 0, 0, 0, 0, 0, 0, 0, 0] - optProb.addVarGroup('xvars', 9, lower=lower, upper=upper, value=value) - - # Constraints - lower = [0, 0, 0, 0, 0, 0, 0, 0] - upper = [None, None, 0, 0, 0, 0, 0, 0] - if not USE_LINEAR: - lower.extend([0, 0]) - upper.extend([None, None]) - - optProb.addConGroup('con', len(lower), lower=lower, upper=upper) - - # And the 2 linear constriants - if USE_LINEAR: - jac = numpy.zeros((1, 9)) - jac[0, 3] = 1.0 - jac[0, 2] = -1.0 - optProb.addConGroup('lin_con', 1, lower=-.55, upper=0.55, - wrt=['xvars'], jac={'xvars':jac}, linear=True) - - # Objective - optProb.addObj('obj') - - # Check optimization problem: - #optProb.printSparsity() - - # Optimizer - try: - opt = OPT(optName, options=optOptions) - except: - raise unittest.SkipTest('Optimizer not available:', optName) - - # Solution - sol = opt(optProb, sens='CS') - - # Check Solution - self.assertAlmostEqual(sol.objectives['obj'].value, 0.536206927538e+04, places=places) - - def test_snopt(self): - self.optimize('snopt') - - def test_slsqp(self): - self.optimize('slsqp') - - def test_autorefine(self): - # Optimization Object - optProb = Optimization('TP109 Constraint Problem',objfunc) - - # Design Variables (Removed infinite bounds for ALPSO) - lower = [0.0, 0.0, -0.55, -0.55, 196, 196, 196, -400, -400] - upper = [2000, 2000, 0.55, 0.55, 252, 252, 252, 800, 800] - value = [0,0,0,0,0,0,0,0,0] - optProb.addVarGroup('xvars', 9, lower=lower, upper=upper, value=value) - - # Constraints - lower = [0, 0 , 0, 0, 0, 0, 0, 0] - upper = [None, None, 0, 0, 0, 0, 0, 0] - if not USE_LINEAR: - lower.extend([0,0]) - upper.extend([None, None]) - - optProb.addConGroup('con', len(lower), lower=lower, upper=upper) - - # And the 2 linear constriants - if USE_LINEAR: - jac = numpy.zeros((1, 9)) - jac[0, 3] = 1.0; jac[0, 2] = -1.0 - optProb.addConGroup('lin_con',1, lower=-.55, upper=0.55, - wrt=['xvars'], jac ={'xvars':jac}, linear=True) - - # Objective - optProb.addObj('obj') - - # Check optimization problem: - #optProb.printSparsity() - - # Global Optimizer: ALPSO - try: - opt1 = OPT('ALPSO') - except: - raise unittest.SkipTest('Optimizer not available:', 'ALPSO') - - # Get first Solution - sol1 = opt1(optProb) - - # Now run the previous solution with SNOPT - try: - opt2 = OPT('SNOPT') - except: - raise unittest.SkipTest('Optimizer not available:', 'SNOPT') - - sol2 = opt2(sol1) - - # Check Solution - self.assertAlmostEqual(sol2.objectives['obj'].value, 0.536206927538e+04, places=2) - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/pyoptsparse/travis_deploy_rsa.enc b/pyoptsparse/travis_deploy_rsa.enc deleted file mode 100644 index 96f3ba1b7..000000000 Binary files a/pyoptsparse/travis_deploy_rsa.enc and /dev/null differ diff --git a/setup.py b/setup.py index 4516836d9..8f982a3f8 100644 --- a/setup.py +++ b/setup.py @@ -129,13 +129,9 @@ def build_extension(self, ext): # Install the python sub-packages print(sys.argv) -for pkg in ['WISDEM','ROSCO','pCrunch','pyHAMS','MoorPy','RAFT','pyoptsparse','dtqpy']: +for pkg in ['WISDEM','ROSCO','pCrunch','pyHAMS','MoorPy','RAFT','dtqpy']: os.chdir(pkg) - if pkg == 'pyoptsparse': - # Build pyOptSparse specially - subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", "."]) - else: - run_setup('setup.py', script_args=sys.argv[1:], stop_after='run') + run_setup('setup.py', script_args=sys.argv[1:], stop_after='run') # subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", "."]) # This option runs `pip install -e .` on each package os.chdir('..')