diff --git a/.github/img/mealpy-3.0.0.png b/.github/img/mealpy-3.0.0.png deleted file mode 100644 index 194d819c..00000000 Binary files a/.github/img/mealpy-3.0.0.png and /dev/null differ diff --git a/.github/img/mealpy-logo-2.png b/.github/img/mealpy-logo-2.png deleted file mode 100644 index 0d23d626..00000000 Binary files a/.github/img/mealpy-logo-2.png and /dev/null differ diff --git a/.github/img/mealpy-logo-3.png b/.github/img/mealpy-logo-3.png deleted file mode 100644 index ec1cf83d..00000000 Binary files a/.github/img/mealpy-logo-3.png and /dev/null differ diff --git a/.github/img/mealpy-logo-4.png b/.github/img/mealpy-logo-4.png deleted file mode 100644 index 0133718b..00000000 Binary files a/.github/img/mealpy-logo-4.png and /dev/null differ diff --git a/.github/img/mealpy-logo.png b/.github/img/mealpy-logo.png deleted file mode 100644 index 4268feb8..00000000 Binary files a/.github/img/mealpy-logo.png and /dev/null differ diff --git a/.github/img/rtc.png b/.github/img/rtc.png deleted file mode 100644 index c262ac87..00000000 Binary files a/.github/img/rtc.png and /dev/null differ diff --git a/.github/workflows/publish-package.yaml b/.github/workflows/publish-package.yaml deleted file mode 100644 index 8771752c..00000000 --- a/.github/workflows/publish-package.yaml +++ /dev/null @@ -1,103 +0,0 @@ -name: Tests & Publishes to PyPI - -on: - release: - types: [published] - push: - branches: - - master - pull_request: - branches: - - "*" - -env: - PROJECT_NAME: mealpy - -jobs: - build: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] - - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 9 - submodules: false - - - name: Use Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - - uses: actions/cache@v3 - id: depcache - with: - path: deps - key: requirements-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }} - - - name: Download dependencies - if: steps.depcache.outputs.cache-hit != 'true' - run: | - pip download --dest=deps -r requirements.txt - - - name: Install dependencies - run: | - pip install -U --no-index --find-links=deps deps/* - pip install pytest pytest-cov flake8 - - - name: Run tests - run: | - pytest --doctest-modules --junitxml=junit/pytest-results-${{ matrix.python-version }}.xml --cov=$PROJECT_NAME --cov-report=xml tests/ - flake8 tests/ - - - name: Upload pytest test results - uses: actions/upload-artifact@v4 - with: - name: pytest-results-${{ matrix.python-version }} - path: junit/pytest-results-${{ matrix.python-version }}.xml - if: always() - - - name: Install distribution dependencies - run: pip install --upgrade twine setuptools wheel - if: matrix.python-version == 3.11 - - - name: Create distribution package - run: python setup.py sdist bdist_wheel - if: matrix.python-version == 3.11 - - - name: Upload distribution package - uses: actions/upload-artifact@v4 - with: - name: dist-package-${{ matrix.python-version }} - path: dist - if: matrix.python-version == 3.11 - - publish: - runs-on: ubuntu-latest - needs: build - if: github.event_name == 'release' - permissions: - id-token: write - contents: read - steps: - - name: Download a distribution artifact - uses: actions/download-artifact@v4 - with: - name: dist-package-3.11 - path: dist - - - name: Publish distribution 📦 to Test PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://test.pypi.org/legacy/ - skip-existing: true - attestations: false - - - name: Publish distribution 📦 to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - with: - skip-existing: true - attestations: true \ No newline at end of file diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..a9e044f9 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,53 @@ +name: Upload Python Package + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + release-build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Build release distributions + run: | + python -m pip install build + python -m build + + - name: Upload distributions + uses: actions/upload-artifact@v4 + with: + name: release-dists + path: dist/ + + pypi-publish: + runs-on: ubuntu-latest + needs: + - release-build + permissions: + id-token: write + + environment: + name: pypi + url: https://pypi.org/p/mealpy-lts + + steps: + - name: Retrieve release distributions + uses: actions/download-artifact@v4 + with: + name: release-dists + path: dist/ + + - name: Publish release distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: dist/ diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 00000000..980c0bb5 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,40 @@ +name: Testing code + +on: + pull_request: + branches: + - master + +jobs: + test-cpython: + name: pytest / ${{ matrix.python-version }} / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - windows-latest + - macos-latest + python-version: + - "3.10" + - "3.11" + - "3.12" + - "3.13" + - "3.14" + + steps: + - uses: actions/checkout@v6 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install ".[dev]" + + - name: Run pytest + run: pytest \ No newline at end of file diff --git a/.github/workflows/type.yml b/.github/workflows/type.yml new file mode 100644 index 00000000..60c0b3f4 --- /dev/null +++ b/.github/workflows/type.yml @@ -0,0 +1,33 @@ +name: Type & check + +on: + pull_request: + branches: + - master + +jobs: + type-check: + name: mypy + runs-on: ubuntu-latest + continue-on-error: true + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + + steps: + - uses: actions/checkout@v6 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install ".[dev]" + + - name: Run mypy + run: mypy --config-file pyproject.toml diff --git a/.gitignore b/.gitignore index 948b7042..59e777d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,204 @@ -run.py -mealpy/swarm_based/ChOA.py -mealpy/swarm_based/DSO.py -mealpy/swarm_based/OPA.py -mealpy/swarm_based/WSO.py -mealpy/swarm_based/FHO.py -mealpy/human_based/PO.py -mealpy/human_based/ILA.py -examples/utils/history* -examples/history* +### Mealpy ### +# History history* -*$.ipynd_checkpoint* +### C ### +# Prerequisites +*.d -# Pycharm -.github/DUMMY.md -.idea/ -drafts/ -.github/commands.md -.github/ga_exam.py -.github/tut_upcode.md -.github/levy_flight.py -docs/build/ -testcase/ +# Object files +*.o +*.ko +*.obj +*.elf +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +### C++ ### +# Prerequisites + +# Compiled Object files +*.slo + +# Precompiled Headers + +# Compiled Dynamic libraries + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai + +# Executables + +### Fortran ### +# Prerequisites + +# Compiled Object files + +# Precompiled Headers + +# Compiled Dynamic libraries + +# Fortran module files + +# Compiled Static libraries + +# Executables + +### JupyterNotebooks ### +# gitignore template for Jupyter Notebooks +# website: http://jupyter.org/ + +.ipynb_checkpoints +*/.ipynb_checkpoints/* + +# IPython +profile_default/ +ipython_config.py + +# Remove previous ipynb_checkpoints +# git rm -r .ipynb_checkpoints/ + +### PyCharm+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### PyCharm+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions -*.so # Distribution / packaging .Python @@ -45,7 +214,6 @@ parts/ sdist/ var/ wheels/ -pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg @@ -75,6 +243,7 @@ coverage.xml *.py,cover .hypothesis/ .pytest_cache/ +cover/ # Translations *.mo @@ -94,20 +263,20 @@ instance/ .scrapy # Sphinx documentation -../whatisthis/sphinx-mealpy/real/docs/_build/ +docs/_build/ # PyBuilder +.pybuilder/ target/ # Jupyter Notebook -.ipynb_checkpoints # IPython -profile_default/ -ipython_config.py # pyenv -.python-version +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. @@ -116,7 +285,22 @@ ipython_config.py # install all needed dependencies. #Pipfile.lock -# PEP 582; used by e.g. github.com/David-OConnor/pyflow +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff @@ -152,3 +336,29 @@ dmypy.json # Pyre type checker .pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +# Sphinx documentation +docs/build/ \ No newline at end of file diff --git a/ChangeLog.md b/CHANGELOG.md similarity index 99% rename from ChangeLog.md rename to CHANGELOG.md index 4c8cfd3c..d7035ef0 100644 --- a/ChangeLog.md +++ b/CHANGELOG.md @@ -1,18 +1,9 @@ +# Version 3.0.4.1 -Different versions of mealpy in terms of passing hyper-parameters. So please careful check your version before - using this library. (All releases can be found here: [Link](https://pypi.org/project/mealpy/#history)) - * mealpy < 1.0.5 - * 1.1.0 < mealpy < 1.2.2 - * 2.0.0 <= mealpy <= 2.1.2 - * mealpy == 2.2.0 - * mealpy == 2.3.0 - * 2.4.0 <= mealpy <= 2.4.2 (From this version, algorithms can solve discrete problem) - * mealpy >= 2.5.1 <= 2.5.4 (Define model 1 time, solve multiple problems) - * mealpy >= 3.0.0 (Everything is wrapped inside class and object) - - ++ Maintenance version, with dependency updates +--- # Version 3.0.4 diff --git a/PAPERS.md b/PAPERS.md new file mode 100644 index 00000000..6ee6c7ab --- /dev/null +++ b/PAPERS.md @@ -0,0 +1,57 @@ +# List of papers used MEALPY + +- Min, J., Oh, M., Kim, W., Seo, H., & Paek, J. (2022, October). Evaluation of Metaheuristic Algorithms for TAS Scheduling in Time-Sensitive Networking. In 2022 13th International Conference on Information and Communication Technology Convergence (ICTC) (pp. 809-812). IEEE. +- Khozeimeh, F., Sharifrazi, D., Izadi, N. H., Joloudari, J. H., Shoeibi, A., Alizadehsani, R., ... & Islam, S. M. S. (2021). Combining a convolutional neural network with autoencoders to predict the survival chance of COVID-19 patients. Scientific Reports, 11(1), 15343. +- Rajesh, K., Jain, E., & Kotecha, P. (2022). A Multi-Objective approach to the Electric Vehicle Routing Problem. arXiv preprint arXiv:2208.12440. +- Sánchez, A. J. H., & Upegui, F. R. (2022). Una herramienta para el diseño de redes MSMN de banda ancha en líneas de transmisión basada en algoritmos heurísticos de optimización comparados. Revista Ingeniería UC, 29(2), 106-123. +- Khanmohammadi, M., Armaghani, D. J., & Sabri Sabri, M. M. (2022). Prediction and Optimization of Pile Bearing Capacity Considering Effects of Time. Mathematics, 10(19), 3563. +- Kudela, J. (2023). The Evolutionary Computation Methods No One Should Use. arXiv preprint arXiv:2301.01984. +- Vieira, M., Faia, R., Pinto, T., & Vale, Z. (2022, September). Schedule Peer-to-Peer Transactions of an Energy Community Using Particle Swarm. In 2022 18th International Conference on the European Energy Market (EEM) (pp. 1-6). IEEE. +- Bui, X. N., Nguyen, H., Le, Q. T., & Le, T. N. Forecasting PM. MINING SCIENCE ANDTECHNOLOGY (Russia), 111. +- Bui, X. N., Nguyen, H., Le, Q. T., & Le, T. N. (2022). Forecasting PM 2.5 emissions in open-pit minesusing a functional link neural network optimized by various optimization algorithms. Gornye nauki i tekhnologii= Mining Science and Technology (Russia), 7(2), 111-125. +- Doğan, E., & Yörükeren, N. (2022). Enhancement of Transmission System Security with Archimedes Optimization Algorithm. +- Ayub, N., Aurangzeb, K., Awais, M., & Ali, U. (2020, November). Electricity theft detection using CNN-GRU and manta ray foraging optimization algorithm. In 2020 IEEE 23Rd international multitopic conference (INMIC) (pp. 1-6). IEEE. +- Pintilie, L., Nechita, M. T., Suditu, G. D., Dafinescu, V., & Drăgoi, E. N. (2022). Photo-decolorization of Eriochrome Black T: process optimization with Differential Evolution algorithm. In PASEW-22, MESSH-22 & CABES-22 April 19–21, 2022 Paris (France). Eminent Association of Pioneers. +- LaTorre, A., Molina, D., Osaba, E., Poyatos, J., Del Ser, J., & Herrera, F. (2021). A prescription of methodological guidelines for comparing bio-inspired optimization algorithms. Swarm and Evolutionary Computation, 67, 100973. +- Gottam, S., Nanda, S. J., & Maddila, R. K. (2021, December). A CNN-LSTM Model Trained with Grey Wolf Optimizer for Prediction of Household Power Consumption. In 2021 IEEE International Symposium on Smart Electronic Systems (iSES)(Formerly iNiS) (pp. 355-360). IEEE. +- Darius, P. S., Devadason, J., & Solomon, D. G. (2022, December). Prospects of Ant Colony Optimization (ACO) in Various Domains. In 2022 4th International Conference on Circuits, Control, Communication and Computing (I4C) (pp. 79-84). IEEE. +- Ayub, N., Irfan, M., Awais, M., Ali, U., Ali, T., Hamdi, M., ... & Muhammad, F. (2020). Big data analytics for short and medium-term electricity load forecasting using an AI techniques ensembler. Energies, 13(19), 5193. +- Biundini, I. Z., Melo, A. G., Coelho, F. O., Honório, L. M., Marcato, A. L., & Pinto, M. F. (2022). Experimentation and Simulation with Autonomous Coverage Path Planning for UAVs. Journal of Intelligent & Robotic Systems, 105(2), 46. +- Yousaf, I., Anwar, F., Imtiaz, S., Almadhor, A. S., Ishmanov, F., & Kim, S. W. (2022). An Optimized Hyperparameter of Convolutional Neural Network Algorithm for Bug Severity Prediction in Alzheimer’s-Based IoT System. Computational Intelligence and Neuroscience, 2022. +- Xu, L., Yan, W., & Ji, J. (2023). The research of a novel WOG-YOLO algorithm for autonomous driving object detection. Scientific reports, 13(1), 3699. +- Costache, R. D., Arabameri, A., Islam, A. R. M. T., Abba, S. I., Pandey, M., Ajin, R. S., & Pham, B. T. (2022). Flood susceptibility computation using state-of-the-art machine learning and optimization algorithms. +- Del Ser, J., Osaba, E., Martinez, A. D., Bilbao, M. N., Poyatos, J., Molina, D., & Herrera, F. (2021, December). More is not always better: insights from a massive comparison of meta-heuristic algorithms over real-parameter optimization problems. In 2021 IEEE Symposium Series on Computational Intelligence (SSCI) (pp. 1-7). IEEE. +- Rustam, F., Aslam, N., De La Torre Díez, I., Khan, Y. D., Mazón, J. L. V., Rodríguez, C. L., & Ashraf, I. (2022, November). White Blood Cell Classification Using Texture and RGB Features of Oversampled Microscopic Images. In Healthcare (Vol. 10, No. 11, p. 2230). MDPI. +- Neupane, D., Kafle, S., Gurung, S., Neupane, S., & Bhattarai, N. (2021). Optimal sizing and financial analysis of a stand-alone SPV-micro-hydropower hybrid system considering generation uncertainty. International Journal of Low-Carbon Technologies, 16(4), 1479-1491. +- Liang, R., Le-Hung, T., & Nguyen-Thoi, T. (2022). Energy consumption prediction of air-conditioning systems in eco-buildings using hunger games search optimization-based artificial neural network model. Journal of Building Engineering, 59, 105087. +- He, Z., Nguyen, H., Vu, T. H., Zhou, J., Asteris, P. G., & Mammou, A. (2022). Novel integrated approaches for predicting the compressibility of clay using cascade forward neural networks optimized by swarm-and evolution-based algorithms. Acta Geotechnica, 1-16. +- Xu, L., Yan, W., & Ji, J. (2022). The research of a novel WOG-YOLO algorithm forautonomous driving object detection. +- Nasir Ayub, M. I., Awais, M., Ali, U., Ali, T., Hamdi, M., Alghamdi, A., & Muhammad, F. Big Data Analytics for Short and Medium Term Electricity Load Forecasting using AI Techniques Ensembler. +- Xie, C., Nguyen, H., Choi, Y., & Armaghani, D. J. (2022). Optimized functional linked neural network for predicting diaphragm wall deflection induced by braced excavations in clays. Geoscience Frontiers, 13(2), 101313. +- Hakemi, S., Houshmand, M., & Hosseini, S. A. (2022). A Dynamic Quantum-Inspired Genetic Algorithm with Lengthening Chromosome Size. +- Kashifi, M. T. City-Wide Crash Risk Prediction and Interpretation Using Deep Learning Model with Multi-Source Big Data. Available at SSRN 4329686. +- Nguyen, H., & Hoang, N. D. (2022). Computer vision-based classification of concrete spall severity using metaheuristic-optimized Extreme Gradient Boosting Machine and Deep Convolutional Neural Network. Automation in Construction, 140, 104371. +- Zheng, J., Lu, Z., Wu, K., Ning, G. H., & Li, D. (2020). Coinage-metal-based cyclic trinuclear complexes with metal–metal interactions: Theories to experiments and structures to functions. Chemical Reviews, 120(17), 9675-9742. +- Van Thieu, N., Barma, S. D., Van Lam, T., Kisi, O., & Mahesha, A. (2023). Groundwater level modeling using Augmented Artificial Ecosystem Optimization. Journal of Hydrology, 617, 129034. +- Mo, Z., Zhang, Z., Miao, Q., & Tsui, K. L. (2022). Intelligent Informative Frequency Band Searching Assisted by a Dynamic Bandit Tree Method for Machine Fault Diagnosis. IEEE/ASME Transactions on Mechatronics. +- Dangi, D., Chandel, S. T., Dixit, D. K., Sharma, S., & Bhagat, A. (2023). An Efficient Model for Sentiment Analysis using Artificial Rabbits Optimized Vector Functional Link Network. Expert Systems with Applications, 119849. +- Dey, S., Roychoudhury, R., Malakar, S., & Sarkar, R. (2022). An optimized fuzzy ensemble of convolutional neural networks for detecting tuberculosis from Chest X-ray images. Applied Soft Computing, 114, 108094. +- Mousavirad, S. J., & Alexandre, L. A. (2022). Population-based JPEG Image Compression: Problem Re-Formulation. arXiv preprint arXiv:2212.06313. +- Tsui, K. L. Intelligent Informative Frequency Band Searching Assisted by A Dynamic Bandit Tree Method for Machine Fault Diagnosis. +- Neupane, D. (2020). Optimal Sizing and Performance Analysis of Solar PV-Micro hydropower Hybrid System in the Context of Rural Area of Nepal (Doctoral dissertation, Pulchowk Campus). +- LaTorre, A., Molina, D., Osaba, E., Poyatos, J., Del Ser, J., & Herrera, F. Swarm and Evolutionary Computation. +- Vieira, M. A. (2022). Otimização dos custos operacionais de uma comunidade energética considerando transações locais em “peer-to-peer” (Doctoral dissertation). +- Toğaçar, M. (2022). Using DarkNet models and metaheuristic optimization methods together to detect weeds growing along with seedlings. Ecological Informatics, 68, 101519. +- Toğaçar, M. (2021). Detection of segmented uterine cancer images by Hotspot Detection method using deep learning models, Pigeon-Inspired Optimization, types-based dominant activation selection approaches. Computers in Biology and Medicine, 136, 104659. +- Khan, N. A Short Term Electricity Load and Price Forecasting Model Based on BAT Algorithm in Logistic Regression and CNN-GRU with WOA. +- Yelisetti, S., Saini, V. K., Kumar, R., & Lamba, R. (2022, May). Energy Consumption Cost Benefits through Smart Home Energy Management in Residential Buildings: An Indian Case Study. In 2022 IEEE IAS Global Conference on Emerging Technologies (GlobConET) (pp. 930-935). IEEE. +- Nguyen, H., Cao, M. T., Tran, X. L., Tran, T. H., & Hoang, N. D. (2022). A novel whale optimization algorithm optimized XGBoost regression for estimating bearing capacity of concrete piles. Neural Computing and Applications, 1-28. +- Hirsching, C., de Jongh, S., Eser, D., Suriyah, M., & Leibfried, T. (2022). Meta-heuristic optimization of control structure and design for MMC-HVdc applications. Electric Power Systems Research, 213, 108371. +- Amelin, V., Gatiyatullin, E., Romanov, N., Samarkhanov, R., Vasilyev, R., & Yanovich, Y. (2022). Black-Box for Blockchain Parameters Adjustment. IEEE Access, 10, 101795-101802. +- Ngo, T. Q., Nguyen, L. Q., & Tran, V. Q. (2022). Novel hybrid machine learning models including support vector machine with meta-heuristic algorithms in predicting unconfined compressive strength of organic soils stabilised with cement and lime. International Journal of Pavement Engineering, 1-18. +- Zhu, Y., & Iiduka, H. (2021). Unified Algorithm Framework for Nonconvex Stochastic Optimization in Deep Neural Networks. IEEE Access, 9, 143807-143823. +- Hakemi, S., Houshmand, M., KheirKhah, E., & Hosseini, S. A. (2022). A review of recent advances in quantum-inspired metaheuristics. Evolutionary Intelligence, 1-16. +- Das, A., Das, S. R., Panda, J. P., Dey, A., Gajrani, K. K., Somani, N., & Gupta, N. (2022). Machine learning based modelling and optimization in hard turning of AISI D6 steel with newly developed AlTiSiN coated carbide tool. arXiv preprint arXiv:2202.00596. +- Yelisetti, S., Saini, V. K., Kumar, R., Lamba, R., & Saxena, A. (2022). Optimal energy management system for residential buildings considering the time of use price with swarm intelligence algorithms. Journal of Building Engineering, 59, 105062. +- Valdés, G. T. (2022). Algoritmo para la detección de vehículos y peatones combinando CNN´ sy técnicas de búsqueda. +- Sallam, N. M., Saleh, A. I., Ali, H. A., & Abdelsalam, M. M. (2023). An efficient EGWO algorithm as feature selection for B-ALL diagnoses and its subtypes classification using peripheral blood smear images. Alexandria Engineering Journal, 68, 39-66. diff --git a/README.md b/README.md index 47f94383..06c56644 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,27 @@ -

- -

+# mealpy-lts ---- +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +![PyPI - Version](https://img.shields.io/pypi/v/mealpy-lts?style=flat-square) +![PyPI - Implementation](https://img.shields.io/pypi/implementation/mealpy-lts?style=flat-square) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mealpy-lts?style=flat-square) +![PyPI - Wheel](https://img.shields.io/pypi/wheel/mealpy-lts?style=flat-square) +![GitHub Release Date](https://img.shields.io/github/release-date/ltsim/mealpy-lts.svg?style=flat-square) +![PyPI - Downloads](https://img.shields.io/pypi/dm/mealpy-lts?style=flat-square) +![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/ltsim/mealpy-lts/publish.yml?style=flat-square&logo=pypi&label=Publish) +![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/ltsim/mealpy-lts/test.yml?style=flat-square&logo=pytest&label=Testing) -[![GitHub release](https://img.shields.io/badge/release-3.0.3-yellow.svg)](https://github.com/thieu1995/mealpy/releases) -[![Wheel](https://img.shields.io/pypi/wheel/gensim.svg)](https://pypi.python.org/pypi/mealpy) -[![PyPI version](https://badge.fury.io/py/mealpy.svg)](https://badge.fury.io/py/mealpy) -![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mealpy.svg) -[![Downloads](https://static.pepy.tech/badge/mealpy)](https://pepy.tech/project/mealpy) -[![Tests & Publishes to PyPI](https://github.com/thieu1995/mealpy/actions/workflows/publish-package.yaml/badge.svg)](https://github.com/thieu1995/mealpy/actions/workflows/publish-package.yaml) -![GitHub Release Date](https://img.shields.io/github/release-date/thieu1995/mealpy.svg) -[![Chat](https://img.shields.io/badge/Chat-on%20Telegram-blue)](https://t.me/+fRVCJGuGJg1mNDg1) -[![Documentation Status](https://readthedocs.org/projects/mealpy/badge/?version=latest)](https://mealpy.readthedocs.io/en/latest/?badge=latest) -[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3711948.svg)](https://doi.org/10.1016/j.sysarc.2023.102871) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +This is a maintenance release, a fork of [MEALPY](https://github.com/thieu1995/mealpy), which offers a collection of cutting-edge metaheuristic algorithms. These include nature-inspired algorithms, bio-inspired algorithms, black-box optimization, global search optimizers, iterative learning algorithms, continuous optimization, derivative-free optimization, gradient-free optimization, zero-order optimization, stochastic search optimization, and random search optimization. ---- +All of these methods fall under the category of population-based metaheuristics (PBM), which are among the most popular algorithms in the field of approximate optimization. -MEALPY is the world's largest Python library, offering a comprehensive collection of cutting-edge meta-heuristic algorithms. -These include nature-inspired algorithms, bio-inspired algorithms, black-box optimization, global search optimizers, iterative learning algorithms, -continuous optimization, derivative-free optimization, gradient-free optimization, zeroth-order optimization, -stochastic search optimization, and random search optimization. All these methods fall under the category of -population-based metaheuristics (PBMs), which are among the most popular algorithms in the field of approximate optimization. -For detailed updates in each new version, please refer to the [ChangeLog](/ChangeLog.md) file. +For detailed information about the updates in each new version, see the [ChangeLog](/CHANGELOG.md) file. * **Free software:** MIT license * **Total algorithms**: 233 (206 official (original, hybrid, variants), 27 developed) * **Documentation:** https://mealpy.readthedocs.io/en/latest/ -* **Python versions:** >=3.8x -* **Dependencies:** numpy, scipy, pandas, matplotlib, tqdm - -## 📌 Goals +## Goals Our goals are to implement all classical as well as the state-of-the-art nature-inspired algorithms, create a simple interface that helps researchers access optimization algorithms as quickly as possible, and share knowledge of the optimization field with everyone without a fee. What you can do with mealpy: @@ -48,7 +34,7 @@ Our goals are to implement all classical as well as the state-of-the-art nature- - **Solve any optimization problem** -## 📄 Citation Request +## Citation Request Please include these citations if you plan to use this library: @@ -85,31 +71,25 @@ Please include these citations if you plan to use this library: } ``` +# Usage -# ⚙️ Usage - -

🛠️ Installation

+## Installation -* Install the stable (latest) version from [PyPI release](https://pypi.python.org/pypi/mealpy): +* Install the stable (latest) version from [PyPI release](https://pypi.python.org/pypi/mealpy-lts): ```bash -$ pip install mealpy --upgrade -``` - -* Install the alpha/beta version from PyPi -```bash -$ pip install mealpy==2.5.4a6 +$ pip install mealpy-lts --upgrade ``` * Install the pre-release version directly from the source code: ```bash -$ git clone https://github.com/thieu1995/mealpy.git -$ cd mealpy +$ git clone https://github.com/ltsim/mealpy-lts.git +$ cd mealpy-lts $ python setup.py install ``` * In case, you want to install the development version from Github: ```bash -$ pip install git+https://github.com/thieu1995/mealpy +$ pip install git+https://github.com/ltsim/mealpy-lts ``` After installation, check the version to ensure successful installation: @@ -123,10 +103,7 @@ $ python >>> model = mealpy.get_optimizer_by_name("OriginalWOA")(epoch=100, pop_size=50) ``` -
- - -## 💬 Decision Variables +## Decision Variables Before we dive into some examples, let's briefly consider the type of problem you're aiming to solve with MEALPY. Understanding your specific problem and its desired solution can help you select the most appropriate approach. @@ -134,8 +111,6 @@ Understanding your specific problem and its desired solution can help you select To assist you in choosing the right tools, refer to the table below. It outlines different types of **decision variables** available in MEALPY, along with their syntax and common problem applications. This will guide you in defining your search space effectively. -
- | Class | Syntax | Problem Types | |-------------------|-----------------------------------------------------------------------------------------------------------------|-----------------------------| | FloatVar | `FloatVar(lb=(-10., )*7, ub=(10., )*7, name="delta")` | Continuous Problem | @@ -149,10 +124,7 @@ along with their syntax and common problem applications. This will guide you in | TransferBoolVar | `TransferBoolVar(n_vars=11, name="delta", tf_func="sstf_02")` | ML, AI-optimize, Feature | | TransferBinaryVar | `TransferBinaryVar(n_vars=11, name="delta", tf_func="vstf_04")` | Networks, Feature Selection | -
- - -## 📚 Optimizer Classification Table +## Optimizer Classification Table * Meta-heuristic Categories: ([Based on this article](https://doi.org/10.1016/j.procs.2020.09.075)) + Evolutionary-based: Algorithms inspired by Darwin's law of natural selection and evolutionary computing principles @@ -164,9 +136,6 @@ along with their syntax and common problem applications. This will guide you in + Math-based: Algorithms developed from mathematical forms or laws (e.g., sine-cosine functions). + Music-based: Algorithms drawing inspiration from musical instruments or compositions. -![MEALPY3-0-0](.github/img/mealpy-classification.png) - - * Difficulty - Difficulty Level (Personal Opinion): **Objective observation from author**. Depend on the number of parameters, number of equations, the original ideas, time spend for coding, source lines of code (SLOC). + Easy: A few paras, few equations, SLOC very short @@ -176,2061 +145,7 @@ along with their syntax and common problem applications. This will guide you in ** For newbie, we recommend to read the paper of algorithms which difficulty is "easy" or "medium" difficulty level. - -[//]: # (
GroupNameModuleClassYearParasDifficulty
EvolutionaryEvolutionary ProgrammingEPOriginalEP19643easy
Evolutionary**LevyEP*3easy
EvolutionaryEvolution StrategiesESOriginalES19713easy
Evolutionary**LevyES*3easy
Evolutionary**CMA_ES20032hard
Evolutionary**Simple_CMA_ES20232medium
EvolutionaryMemetic AlgorithmMAOriginalMA19897easy
EvolutionaryGenetic AlgorithmGABaseGA19924easy
Evolutionary**SingleGA*7easy
Evolutionary**MultiGA*7easy
Evolutionary**EliteSingleGA*10easy
Evolutionary**EliteMultiGA*10easy
EvolutionaryDifferential EvolutionDEBaseDE19975easy
Evolutionary**JADE20096medium
Evolutionary**SADE20052medium
Evolutionary**SAP_DE20063medium
EvolutionarySuccess-History Adaptation Differential EvolutionSHADEOriginalSHADE20134medium
Evolutionary**L_SHADE20144medium
EvolutionaryFlower Pollination AlgorithmFPAOriginalFPA20144medium
EvolutionaryCoral Reefs OptimizationCROOriginalCRO201411medium
Evolutionary**OCRO201912medium
*********************
SwarmParticle Swarm OptimizationPSOOriginalPSO19956easy
Swarm**PPSO20192medium
Swarm**HPSO_TVAC20174medium
Swarm**C_PSO20156medium
Swarm**CL_PSO20066medium
SwarmBacterial Foraging OptimizationBFOOriginalBFO200210hard
Swarm**ABFO20198medium
SwarmBees AlgorithmBeesAOriginalBeesA20058medium
Swarm**ProbBeesA20155medium
Swarm**CleverBookBeesA20068medium
SwarmCat Swarm OptimizationCSOOriginalCSO200611hard
SwarmArtificial Bee ColonyABCOriginalABC20078medium
SwarmAnt Colony OptimizationACOROriginalACOR20085easy
SwarmCuckoo Search AlgorithmCSAOriginalCSA20093medium
SwarmFirefly Algorithm FFAOriginalFFA20098easy
SwarmFireworks AlgorithmFAOriginalFA20107medium
SwarmBat AlgorithmBAOriginalBA20106medium
Swarm**AdaptiveBA20108medium
Swarm**ModifiedBA*5medium
SwarmFruit-fly Optimization AlgorithmFOAOriginalFOA20122easy
Swarm**BaseFOA*2easy
Swarm**WhaleFOA20202medium
SwarmSocial Spider OptimizationSSpiderOOriginalSSpiderO20184hard*
SwarmGrey Wolf OptimizerGWOOriginalGWO20142easy
Swarm**RW_GWO20192easy
SwarmSocial Spider AlgorithmSSpiderAOriginalSSpiderA20155medium
SwarmAnt Lion OptimizerALOOriginalALO20152easy
Swarm**BaseALO*2easy
SwarmMoth Flame OptimizationMFOOriginalMFO20152easy
Swarm**BaseMFO*2easy
SwarmElephant Herding OptimizationEHOOriginalEHO20155easy
SwarmJaya AlgorithmJAOriginalJA20162easy
Swarm**BaseJA*2easy
Swarm**LevyJA20212easy
SwarmWhale Optimization AlgorithmWOAOriginalWOA20162medium
Swarm**HI_WOA20193medium
SwarmDragonfly OptimizationDOOriginalDO20162medium
SwarmBird Swarm AlgorithmBSAOriginalBSA20169medium
SwarmSpotted Hyena OptimizerSHOOriginalSHO20174medium
SwarmSalp Swarm OptimizationSSOOriginalSSO20172easy
SwarmSwarm Robotics Search And RescueSRSROriginalSRSR20172hard*
SwarmGrasshopper Optimisation AlgorithmGOAOriginalGOA20174easy
SwarmCoyote Optimization AlgorithmCOAOriginalCOA20183medium
SwarmMoth Search AlgorithmMSAOriginalMSA20185easy
SwarmSea Lion OptimizationSLOOriginalSLO20192medium
Swarm**ModifiedSLO*2medium
Swarm**ImprovedSLO20224medium
SwarmNake Mole*Rat AlgorithmNMRAOriginalNMRA20193easy
Swarm**ImprovedNMRA*4medium
SwarmPathfinder AlgorithmPFAOriginalPFA20192medium
SwarmSailfish OptimizerSFOOriginalSFO20195easy
Swarm**ImprovedSFO*3medium
SwarmHarris Hawks OptimizationHHOOriginalHHO20192medium
SwarmManta Ray Foraging OptimizationMRFOOriginalMRFO20203medium
SwarmBald Eagle SearchBESOriginalBES20207easy
SwarmSparrow Search AlgorithmSSAOriginalSSA20205medium
Swarm**BaseSSA*5medium
SwarmHunger Games SearchHGSOriginalHGS20214medium
SwarmAquila OptimizerAOOriginalAO20212easy
SwarmHybrid Grey Wolf * Whale Optimization AlgorithmGWOGWO_WOA20222easy
SwarmMarine Predators AlgorithmMPAOriginalMPA20202medium
SwarmHoney Badger AlgorithmHBAOriginalHBA20222easy
SwarmSand Cat Swarm OptimizationSCSOOriginalSCSO20222easy
SwarmTuna Swarm OptimizationTSOOriginalTSO20212medium
SwarmAfrican Vultures Optimization AlgorithmAVOAOriginalAVOA20227medium
SwarmArtificial Gorilla Troops OptimizationAGTOOriginalAGTO20215medium
Swarm**MGTO20233medium
SwarmArtificial Rabbits OptimizationAROOriginalARO20222easy
Swarm**LARO20222easy
Swarm**IARO20222easy
SwarmEgret Swarm Optimization AlgorithmESOAOriginalESOA20222medium
SwarmFox OptimizerFOXOriginalFOX20234easy
SwarmGolden Jackal OptimizationGJOOriginalGJO20222easy
SwarmGiant Trevally OptimizationGTOOriginalGTO20224medium
Swarm**Matlab101GTO20222medium
Swarm**Matlab102GTO20232hard
SwarmMountain Gazelle OptimizerMGOOriginalMGO20222easy
SwarmSea-Horse OptimizationSeaHOOriginalSeaHO20222medium
*********************
PhysicsSimulated AnneallingSAOriginalSA19839medium
Physics**GaussianSA*5medium
Physics**SwarmSA19879medium
PhysicsWind Driven OptimizationWDOOriginalWDO20137easy
PhysicsMulti*Verse OptimizerMVOOriginalMVO20164easy
Physics**BaseMVO*4easy
PhysicsTug of War OptimizationTWOOriginalTWO20162easy
Physics**OppoTWO*2medium
Physics**LevyTWO*2medium
Physics**EnhancedTWO20202medium
PhysicsElectromagnetic Field OptimizationEFOOriginalEFO20166easy
Physics**BaseEFO*6medium
PhysicsNuclear Reaction OptimizationNROOriginalNRO20192hard*
PhysicsHenry Gas Solubility OptimizationHGSOOriginalHGSO20193medium
PhysicsAtom Search OptimizationASOOriginalASO20194medium
PhysicsEquilibrium OptimizerEOOriginalEO20192easy
Physics**ModifiedEO20202medium
Physics**AdaptiveEO20202medium
PhysicsArchimedes Optimization AlgorithmArchOAOriginalArchOA20218medium
PhysicsChernobyl Disaster OptimizationCDOOriginalCDO20232easy
PhysicsEnergy Valley OptimizationEVOOriginalEVO20232medium
PhysicsFick's Law AlgorithmFLAOriginalFLA20238hard
PhysicsPhysical Phenomenon of RIME-iceRIMEOriginalRIME20233easy
*********************
HumanCulture AlgorithmCAOriginalCA19943easy
HumanImperialist Competitive AlgorithmICAOriginalICA20078hard*
HumanTeaching Learning*based OptimizationTLOOriginalTLO20112easy
Human**BaseTLO20122easy
Human**ITLO20133medium
HumanBrain Storm OptimizationBSOOriginalBSO20118medium
Human**ImprovedBSO20177medium
HumanQueuing Search AlgorithmQSAOriginalQSA20192hard
Human**BaseQSA*2hard
Human**OppoQSA*2hard
Human**LevyQSA*2hard
Human**ImprovedQSA20212hard
HumanSearch And Rescue OptimizationSAROOriginalSARO20194medium
Human**BaseSARO*4medium
HumanLife Choice*Based Optimization LCOOriginalLCO20193easy
Human**BaseLCO*3easy
Human**ImprovedLCO*2easy
HumanSocial Ski*Driver OptimizationSSDOOriginalSSDO20192easy
HumanGaining Sharing Knowledge*based AlgorithmGSKAOriginalGSKA20196medium
Human**BaseGSKA*4medium
HumanCoronavirus Herd Immunity OptimizationCHIOOriginalCHIO20204medium
Human**BaseCHIO*4medium
HumanForensic*Based Investigation OptimizationFBIOOriginalFBIO20202medium
Human**BaseFBIO*2medium
HumanBattle Royale OptimizationBROOriginalBRO20203medium
Human**BaseBRO*3medium
HumanStudent Psychology Based OptimizationSPBOOriginalSPBO20202medium
Human**DevSPBO*2medium
HumanHeap-based OptimizationHBOOriginalHBO20203medium
HumanHuman Conception OptimizationHCOOriginalHCO20226medium
HumanDwarf Mongoose Optimization AlgorithmDMOAOriginalDMOA20224medium
Human**DevDMOA*3medium
HumanWar Strategy OptimizationWarSOOriginalWarSO20223easy
*********************
BioInvasive Weed OptimizationIWOOriginalIWO20067easy
BioBiogeography*Based OptimizationBBOOriginalBBO20084easy
Bio**BaseBBO*4easy
BioVirus Colony SearchVCSOriginalVCS20164hard*
Bio**BaseVCS*4hard*
BioSatin Bowerbird OptimizerSBOOriginalSBO20175easy
Bio**BaseSBO*5easy
BioEarthworm Optimisation AlgorithmEOAOriginalEOA20188medium
BioWildebeest Herd OptimizationWHOOriginalWHO201912hard
BioSlime Mould AlgorithmSMAOriginalSMA20203easy
Bio**BaseSMA*3easy
BioBarnacles Mating OptimizerBMOOriginalBMO20183easy
BioTunicate Swarm AlgorithmTSAOriginalTSA20202easy
BioSymbiotic Organisms SearchSOSOriginalSOS20142medium
BioSeagull Optimization AlgorithmSOAOriginalSOA20193easy
Bio**DevSOA*3easy
BioBrown-Bear Optimization AlgorithmBBOAOriginalBBOA20232medium
BioTree Physiology OptimizationTPOOriginalTPO20175medium
*********************
SystemGerminal Center OptimizationGCOOriginalGCO20184medium
System**BaseGCO*4medium
SystemWater Cycle AlgorithmWCAOriginalWCA20125medium
SystemArtificial Ecosystem*based OptimizationAEOOriginalAEO20192easy
System**EnhancedAEO20202medium
System**ModifiedAEO20202medium
System**ImprovedAEO20212medium
System**AugmentedAEO20222medium
*********************
MathHill ClimbingHCOriginalHC19933easy
Math**SwarmHC*3easy
MathCross-Entropy Method CEMOriginalCEM19974easy
MathTabu SearchTSOriginalTS20045easy
MathSine Cosine AlgorithmSCAOriginalSCA20162easy
Math**BaseSCA*2easy
Math**QLE-SCA20224hard
MathGradient-Based OptimizerGBOOriginalGBO20205medium
MathArithmetic Optimization AlgorithmAOAOrginalAOA20216easy
MathChaos Game OptimizationCGOOriginalCGO20212easy
MathPareto-like Sequential SamplingPSSOriginalPSS20214medium
MathweIghted meaN oF vectOrsINFOOriginalINFO20222medium
MathRUNge Kutta optimizerRUNOriginalRUN20212hard
MathCircle Search AlgorithmCircleSAOriginalCircleSA20223easy
MathSuccess History Intelligent OptimizationSHIOOriginalSHIO20222easy
*********************
MusicHarmony SearchHSOriginalHS20014easy
Music**BaseHS*4easy
+++++++++++++++++++++
WARNINGPLEASE CHECK PLAGIARISM BEFORE USING BELOW ALGORITHMS*****
SwarmCoati Optimization AlgorithmCoatiOAOriginalCoatiOA20232easy
SwarmFennec For OptimizationFFOOriginalFFO20222easy
SwarmNorthern Goshawk OptimizationNGOOriginalNGO20212easy
SwarmOsprey Optimization AlgorithmOOAOriginalOOA20232easy
SwarmPelican Optimization Algorithm POAOriginalPOA20232easy
SwarmServal Optimization AlgorithmServalOAOriginalServalOA20222easy
SwarmSiberian Tiger OptimizationSTOOriginalSTO20222easy
SwarmTasmanian Devil OptimizationTDOOriginalTDO20222easy
SwarmWalrus Optimization AlgorithmWaOAOriginalWaOA20222easy
SwarmZebra Optimization Algorithm ZOAOriginalZOA20222easy
HumanTeamwork Optimization AlgorithmTOAOriginalTOA20212easy
) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupNameModuleClassYearParasDifficulty
EvolutionaryEvolutionary ProgrammingEPOriginalEP19643easy
Evolutionary**LevyEP*3easy
EvolutionaryEvolution StrategiesESOriginalES19713easy
Evolutionary**LevyES*3easy
Evolutionary**CMA_ES20032hard
Evolutionary**Simple_CMA_ES20232medium
EvolutionaryMemetic AlgorithmMAOriginalMA19897easy
EvolutionaryGenetic AlgorithmGABaseGA19924easy
Evolutionary**SingleGA*7easy
Evolutionary**MultiGA*7easy
Evolutionary**EliteSingleGA*10easy
Evolutionary**EliteMultiGA*10easy
EvolutionaryDifferential EvolutionDEBaseDE19975easy
Evolutionary**JADE20096medium
Evolutionary**SADE20052medium
Evolutionary**SAP_DE20063medium
EvolutionarySuccess-History Adaptation Differential EvolutionSHADEOriginalSHADE20134medium
Evolutionary**L_SHADE20144medium
EvolutionaryFlower Pollination AlgorithmFPAOriginalFPA20144medium
EvolutionaryCoral Reefs OptimizationCROOriginalCRO201411medium
Evolutionary**OCRO201912medium
*********************
SwarmParticle Swarm OptimizationPSOOriginalPSO19956easy
Swarm**PPSO20192medium
Swarm**HPSO_TVAC20174medium
Swarm**C_PSO20156medium
Swarm**CL_PSO20066medium
SwarmBacterial Foraging OptimizationBFOOriginalBFO200210hard
Swarm**ABFO20198medium
SwarmBees AlgorithmBeesAOriginalBeesA20058medium
Swarm**ProbBeesA20155medium
Swarm**CleverBookBeesA20068medium
SwarmCat Swarm OptimizationCSOOriginalCSO200611hard
SwarmArtificial Bee ColonyABCOriginalABC20078medium
SwarmAnt Colony OptimizationACOROriginalACOR20085easy
SwarmCuckoo Search AlgorithmCSAOriginalCSA20093medium
SwarmFirefly Algorithm FFAOriginalFFA20098easy
SwarmFireworks AlgorithmFAOriginalFA20107medium
SwarmBat AlgorithmBAOriginalBA20106medium
Swarm**AdaptiveBA20108medium
Swarm**ModifiedBA*5medium
SwarmFruit-fly Optimization AlgorithmFOAOriginalFOA20122easy
Swarm**BaseFOA*2easy
Swarm**WhaleFOA20202medium
SwarmSocial Spider OptimizationSSpiderOOriginalSSpiderO20184hard*
SwarmSpider Monkey OptimizationSMODevSMO20144hard
SwarmGrey Wolf OptimizerGWOOriginalGWO20142easy
Swarm**RW_GWO20192easy
Swarm**GWO_WOA20222easy
Swarm**IGWO20184easy
Swarm**ChaoticGWO20184easy
Swarm**FuzzyGWO20173medium
Swarm**IncrementalGWO20213medium
Swarm**ExGWO20212medium
Swarm**DS_GWO20224medium
Swarm**IOBL_GWO20212medium
Swarm**OGWO20214medium
Swarm**ER_GWO20205medium
Swarm**CG_GWO20222hard
SwarmSocial Spider AlgorithmSSpiderAOriginalSSpiderA20155medium
SwarmAnt Lion OptimizerALOOriginalALO20152easy
Swarm**BaseALO*2easy
SwarmMoth Flame OptimizationMFOOriginalMFO20152easy
Swarm**BaseMFO*2easy
SwarmElephant Herding OptimizationEHOOriginalEHO20155easy
SwarmJaya AlgorithmJAOriginalJA20162easy
Swarm**BaseJA*2easy
Swarm**LevyJA20212easy
SwarmWhale Optimization AlgorithmWOAOriginalWOA20162medium
Swarm**HI_WOA20193medium
SwarmDragonfly OptimizationDOOriginalDO20162medium
SwarmBird Swarm AlgorithmBSAOriginalBSA20169medium
SwarmSpotted Hyena OptimizerSHOOriginalSHO20174medium
SwarmSalp Swarm OptimizationSSOOriginalSSO20172easy
SwarmSwarm Robotics Search And RescueSRSROriginalSRSR20172hard*
SwarmGrasshopper Optimisation AlgorithmGOAOriginalGOA20174easy
SwarmCoyote Optimization AlgorithmCOAOriginalCOA20183medium
SwarmMoth Search AlgorithmMSAOriginalMSA20185easy
SwarmSquirrel Search AlgorithmSquirrelSAOriginalSquirrelSA20197medium
SwarmFitness Dependent OptimizerFDOOriginalFDO20193medium
SwarmSea Lion OptimizationSLOOriginalSLO20192medium
Swarm**ModifiedSLO*2medium
Swarm**ImprovedSLO20224medium
SwarmEmperor Penguins Colony/td> - EPCDevEPC20196hard
SwarmNake Mole*Rat AlgorithmNMRAOriginalNMRA20193easy
Swarm**ImprovedNMRA*4medium
SwarmPathfinder AlgorithmPFAOriginalPFA20192medium
SwarmSailfish OptimizerSFOOriginalSFO20195easy
Swarm**ImprovedSFO*3medium
SwarmHarris Hawks OptimizationHHOOriginalHHO20192medium
SwarmManta Ray Foraging OptimizationMRFOOriginalMRFO20203medium
SwarmBald Eagle SearchBESOriginalBES20207easy
SwarmSparrow Search AlgorithmSSAOriginalSSA20205medium
Swarm**BaseSSA*5medium
SwarmHunger Games SearchHGSOriginalHGS20214medium
SwarmAquila OptimizerAOOriginalAO20212easy
Swarm**AAO20244easy
SwarmHybrid Grey Wolf * Whale Optimization AlgorithmGWOGWO_WOA20222easy
SwarmMarine Predators AlgorithmMPAOriginalMPA20202medium
SwarmHoney Badger AlgorithmHBAOriginalHBA20222easy
SwarmSand Cat Swarm OptimizationSCSOOriginalSCSO20222easy
SwarmTuna Swarm OptimizationTSOOriginalTSO20212medium
SwarmAfrican Vultures Optimization AlgorithmAVOAOriginalAVOA20227medium
SwarmArtificial Gorilla Troops OptimizationAGTOOriginalAGTO20215medium
Swarm**MGTO20233medium
SwarmArtificial Rabbits OptimizationAROOriginalARO20222easy
Swarm**LARO20222easy
Swarm**IARO20222easy
SwarmEgret Swarm Optimization AlgorithmESOAOriginalESOA20222medium
SwarmFox OptimizerFOXOriginalFOX20234easy
SwarmGolden Jackal OptimizationGJOOriginalGJO20222easy
SwarmGiant Trevally OptimizationGTOOriginalGTO20224medium
Swarm**Matlab101GTO20222medium
Swarm**Matlab102GTO20232hard
SwarmMountain Gazelle OptimizerMGOOriginalMGO20222easy
SwarmSea-Horse OptimizationSeaHOOriginalSeaHO20222medium
*********************
PhysicsSimulated AnneallingSAOriginalSA19839medium
Physics**GaussianSA*5medium
Physics**SwarmSA19879medium
PhysicsWind Driven OptimizationWDOOriginalWDO20137easy
PhysicsMulti*Verse OptimizerMVOOriginalMVO20164easy
Physics**BaseMVO*4easy
PhysicsTug of War OptimizationTWOOriginalTWO20162easy
Physics**OppoTWO*2medium
Physics**LevyTWO*2medium
Physics**EnhancedTWO20202medium
PhysicsElectromagnetic Field OptimizationEFOOriginalEFO20166easy
Physics**BaseEFO*6medium
PhysicsNuclear Reaction OptimizationNROOriginalNRO20192hard*
PhysicsHenry Gas Solubility OptimizationHGSOOriginalHGSO20193medium
PhysicsAtom Search OptimizationASOOriginalASO20194medium
PhysicsEquilibrium OptimizerEOOriginalEO20192easy
Physics**ModifiedEO20202medium
Physics**AdaptiveEO20202medium
PhysicsArchimedes Optimization AlgorithmArchOAOriginalArchOA20218medium
PhysicsChernobyl Disaster OptimizationCDOOriginalCDO20232easy
PhysicsEnergy Valley OptimizationEVOOriginalEVO20232medium
PhysicsFick's Law AlgorithmFLAOriginalFLA20238hard
PhysicsPhysical Phenomenon of RIME-iceRIMEOriginalRIME20233easy
PhysicsElectrical Storm OptimizationESOOriginalESO20252hard
*********************
HumanCulture AlgorithmCAOriginalCA19943easy
HumanImperialist Competitive AlgorithmICAOriginalICA20078hard*
HumanTeaching Learning*based OptimizationTLOOriginalTLO20112easy
Human**BaseTLO20122easy
Human**ITLO20133medium
HumanBrain Storm OptimizationBSOOriginalBSO20118medium
Human**ImprovedBSO20177medium
HumanQueuing Search AlgorithmQSAOriginalQSA20192hard
Human**BaseQSA*2hard
Human**OppoQSA*2hard
Human**LevyQSA*2hard
Human**ImprovedQSA20212hard
HumanSearch And Rescue OptimizationSAROOriginalSARO20194medium
Human**BaseSARO*4medium
HumanLife Choice*Based Optimization LCOOriginalLCO20193easy
Human**BaseLCO*3easy
Human**ImprovedLCO*2easy
HumanSocial Ski*Driver OptimizationSSDOOriginalSSDO20192easy
HumanGaining Sharing Knowledge*based AlgorithmGSKAOriginalGSKA20196medium
Human**BaseGSKA*4medium
HumanCoronavirus Herd Immunity OptimizationCHIOOriginalCHIO20204medium
Human**BaseCHIO*4medium
HumanForensic*Based Investigation OptimizationFBIOOriginalFBIO20202medium
Human**BaseFBIO*2medium
HumanBattle Royale OptimizationBROOriginalBRO20203medium
Human**BaseBRO*3medium
HumanStudent Psychology Based OptimizationSPBOOriginalSPBO20202medium
Human**DevSPBO*2medium
HumanHeap-based OptimizationHBOOriginalHBO20203medium
HumanHuman Conception OptimizationHCOOriginalHCO20226medium
HumanAli baba and the Forty ThievesAFTOriginalAFT20222easy
HumanChild Drawing Development OptimizationCDDOOriginalCDDO20224easy
HumanDwarf Mongoose Optimization AlgorithmDMOAOriginalDMOA20224medium
Human**DevDMOA*3medium
HumanWar Strategy OptimizationWarSOOriginalWarSO20223easy
*********************
BioInvasive Weed OptimizationIWOOriginalIWO20067easy
BioBiogeography*Based OptimizationBBOOriginalBBO20084easy
Bio**BaseBBO*4easy
BioVirus Colony SearchVCSOriginalVCS20164hard*
Bio**BaseVCS*4hard*
BioSatin Bowerbird OptimizerSBOOriginalSBO20175easy
Bio**BaseSBO*5easy
BioEarthworm Optimisation AlgorithmEOAOriginalEOA20188medium
BioWildebeest Herd OptimizationWHOOriginalWHO201912hard
BioSlime Mould AlgorithmSMAOriginalSMA20203easy
Bio**BaseSMA*3easy
BioBarnacles Mating OptimizerBMOOriginalBMO20183easy
BioTunicate Swarm AlgorithmTSAOriginalTSA20202easy
BioSymbiotic Organisms SearchSOSOriginalSOS20142medium
BioSeagull Optimization AlgorithmSOAOriginalSOA20193easy
Bio**DevSOA*3easy
BioBrown-Bear Optimization AlgorithmBBOAOriginalBBOA20232medium
BioTree Physiology OptimizationTPOOriginalTPO20175medium
*********************
SystemGerminal Center OptimizationGCOOriginalGCO20184medium
System**BaseGCO*4medium
SystemWater Cycle AlgorithmWCAOriginalWCA20125medium
SystemArtificial Ecosystem*based OptimizationAEOOriginalAEO20192easy
System**EnhancedAEO20202medium
System**ModifiedAEO20202medium
System**ImprovedAEO20212medium
System**AugmentedAEO20222medium
*********************
MathHill ClimbingHCOriginalHC19933easy
Math**SwarmHC*3easy
MathCross-Entropy Method CEMOriginalCEM19974easy
MathTabu SearchTSOriginalTS20045easy
MathSine Cosine AlgorithmSCAOriginalSCA20162easy
Math**BaseSCA*2easy
Math**QLE-SCA20224hard
MathGradient-Based OptimizerGBOOriginalGBO20205medium
MathArithmetic Optimization AlgorithmAOAOrginalAOA20216easy
MathChaos Game OptimizationCGOOriginalCGO20212easy
MathPareto-like Sequential SamplingPSSOriginalPSS20214medium
MathweIghted meaN oF vectOrsINFOOriginalINFO20222medium
MathRUNge Kutta optimizerRUNOriginalRUN20212hard
MathCircle Search AlgorithmCircleSAOriginalCircleSA20223easy
MathSuccess History Intelligent OptimizationSHIOOriginalSHIO20222easy
*********************
MusicHarmony SearchHSOriginalHS20014easy
Music**BaseHS*4easy
SOTAEnsemble sinusoidal differential covariance matrix adaptation with Euclidean neighborhoodLSHADEcnEpSinOriginalLSHADEcnEpSin20179hard
SOTAImproved Multi-operator Differential Evolution AlgorithmIMODEOriginalIMODE20204hard
- -### ❌ Warning: Algorithms Suspected of Plagiarism +### Warning: Algorithms Suspected of Plagiarism During our implementation and classification of metaheuristic optimization algorithms, we identified a set of methods that raise serious concerns regarding **scientific integrity and originality**. These algorithms are typically published under **different names**, @@ -2249,408 +164,15 @@ comparative studies, or any applications unless their originality is transparent and likely cases of plagiarism. For this reason, I will no longer spend time coding such algorithms in the future. This warning is intended to help others avoid using or relying on these methods in their work.** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GroupNameModuleClassYearParasDifficulty
SwarmCoati Optimization AlgorithmCoatiOAOriginalCoatiOA20232easy
SwarmFennec For OptimizationFFOOriginalFFO20222easy
SwarmNorthern Goshawk OptimizationNGOOriginalNGO20212easy
SwarmOsprey Optimization AlgorithmOOAOriginalOOA20232easy
SwarmPelican Optimization Algorithm POAOriginalPOA20232easy
SwarmServal Optimization AlgorithmServalOAOriginalServalOA20222easy
SwarmSiberian Tiger OptimizationSTOOriginalSTO20222easy
SwarmTasmanian Devil OptimizationTDOOriginalTDO20222easy
SwarmWalrus Optimization AlgorithmWaOAOriginalWaOA20222easy
SwarmZebra Optimization Algorithm ZOAOriginalZOA20222easy
HumanTeamwork Optimization AlgorithmTOAOriginalTOA20212easy
- -### ⚠️ Ethical Reminder +### Ethical Reminder Researchers and students are urged to **exercise caution** when referencing or applying the algorithms listed above. Using unoriginal or unethical work can compromise the **scientific credibility** of any downstream research and introduce **misleading experimental results**. -> 🔗 **Check [PubPeer1](https://pubpeer.com/publications/1F5DCE5BC42BF2D77A1B0C281A5295)** and [PubPeer2](https://pubpeer.com/publications/D47357D409AE273F9E03C7CBE30EB7) to +> **Check [PubPeer1](https://pubpeer.com/publications/1F5DCE5BC42BF2D77A1B0C281A5295)** and [PubPeer2](https://pubpeer.com/publications/D47357D409AE273F9E03C7CBE30EB7) to > find ongoing discussions and critiques from the academic community. ---- - - -

💻 Define All Optimizers

- -```python - -from mealpy import (StringVar, FloatVar, BoolVar, PermutationVar, CategoricalVar, IntegerVar, BinaryVar, - TransferBinaryVar, TransferBoolVar) -from mealpy import Tuner, Multitask, Problem, Optimizer, Termination, ParameterGrid -from mealpy import get_all_optimizers, get_optimizer_by_name - -from mealpy import BBO, PSO, GA, ALO, AO, ARO, AVOA, BA, BBOA, BMO, EOA, IWO -from mealpy import GJO, FOX, FOA, FFO, FFA, FA, ESOA, EHO, DO, DMOA, CSO, CSA, CoatiOA, COA, BSA -from mealpy import HCO, ICA, LCO, WarSO, TOA, TLO, SSDO, SPBO, SARO, QSA, ArchOA, ASO, CDO, EFO, EO, EVO, FLA -from mealpy import HGSO, MVO, NRO, RIME, SA, WDO, TWO, ABC, ACOR, AGTO, BeesA, BES, BFO, ZOA, WOA, WaOA, TSO -from mealpy import PFA, OOA, NGO, NMRA, MSA, MRFO, MPA, MGO, MFO, JA, HHO, HGS, HBA, GWO, GTO, GOA -from mealpy import SBO, SMA, SOA, SOS, TPO, TSA, VCS, WHO, AOA, CEM, CGO, CircleSA, GBO, HC, INFO, PSS, RUN, SCA -from mealpy import SHIO, TS, HS, AEO, GCO, WCA, CRO, DE, EP, ES, FPA, MA, SHADE, BRO, BSO, CA, CHIO, FBIO, GSKA, HBO -from mealpy import TDO, STO, SSpiderO, SSpiderA, SSO, SSA, SRSR, SLO, SHO, SFO, ServalOA, SeaHO, SCSO, POA - -## Newly added module in version 3.0.3 -from mealpy import ESO, EPC, SMO, AFT, CDDO, SquirrelSA, FDO, LSHADEcnEpSin, IMODE - - -if __name__ == "__main__": - model = BBO.OriginalBBO(epoch=10, pop_size=30, p_m=0.01, n_elites=2) - model = PSO.OriginalPSO(epoch=100, pop_size=50, c1=2.05, c2=20.5, w=0.4) - model = PSO.LDW_PSO(epoch=100, pop_size=50, c1=2.05, c2=20.5, w_min=0.4, w_max=0.9) - model = PSO.AIW_PSO(epoch=100, pop_size=50, c1=2.05, c2=20.5, alpha=0.4) - model = PSO.P_PSO(epoch=100, pop_size=50) - model = PSO.HPSO_TVAC(epoch=100, pop_size=50, ci=0.5, cf=0.1) - model = PSO.C_PSO(epoch=100, pop_size=50, c1=2.05, c2=2.05, w_min=0.4, w_max=0.9) - model = PSO.CL_PSO(epoch=100, pop_size=50, c_local=1.2, w_min=0.4, w_max=0.9, max_flag=7) - model = GA.BaseGA(epoch=100, pop_size=50, pc=0.9, pm=0.05, selection="tournament", k_way=0.4, crossover="multi_points", mutation="swap") - model = GA.SingleGA(epoch=100, pop_size=50, pc=0.9, pm=0.8, selection="tournament", k_way=0.4, crossover="multi_points", mutation="swap") - model = GA.MultiGA(epoch=100, pop_size=50, pc=0.9, pm=0.8, selection="tournament", k_way=0.4, crossover="multi_points", mutation="swap") - model = GA.EliteSingleGA(epoch=100, pop_size=50, pc=0.95, pm=0.8, selection="roulette", crossover="uniform", mutation="swap", k_way=0.2, elite_best=0.1, - elite_worst=0.3, strategy=0) - model = GA.EliteMultiGA(epoch=100, pop_size=50, pc=0.95, pm=0.8, selection="roulette", crossover="uniform", mutation="swap", k_way=0.2, elite_best=0.1, - elite_worst=0.3, strategy=0) - model = ABC.OriginalABC(epoch=1000, pop_size=50, n_limits=50) - model = ACOR.OriginalACOR(epoch=1000, pop_size=50, sample_count=25, intent_factor=0.5, zeta=1.0) - model = AGTO.OriginalAGTO(epoch=1000, pop_size=50, p1=0.03, p2=0.8, beta=3.0) - model = AGTO.MGTO(epoch=1000, pop_size=50, pp=0.03) - model = ALO.OriginalALO(epoch=100, pop_size=50) - model = ALO.DevALO(epoch=100, pop_size=50) - model = AO.OriginalAO(epoch=100, pop_size=50) - model = ARO.OriginalARO(epoch=100, pop_size=50) - model = ARO.LARO(epoch=100, pop_size=50) - model = ARO.IARO(epoch=100, pop_size=50) - model = AVOA.OriginalAVOA(epoch=100, pop_size=50, p1=0.6, p2=0.4, p3=0.6, alpha=0.8, gama=2.5) - model = BA.OriginalBA(epoch=100, pop_size=50, loudness=0.8, pulse_rate=0.95, pf_min=0.1, pf_max=10.0) - model = BA.AdaptiveBA(epoch=100, pop_size=50, loudness_min=1.0, loudness_max=2.0, pr_min=-2.5, pr_max=0.85, pf_min=0.1, pf_max=10.) - model = BA.DevBA(epoch=100, pop_size=50, pulse_rate=0.95, pf_min=0., pf_max=10.) - model = BBOA.OriginalBBOA(epoch=100, pop_size=50) - model = BMO.OriginalBMO(epoch=100, pop_size=50, pl=4) - model = EOA.OriginalEOA(epoch=100, pop_size=50, p_c=0.9, p_m=0.01, n_best=2, alpha=0.98, beta=0.9, gama=0.9) - model = IWO.OriginalIWO(epoch=100, pop_size=50, seed_min=3, seed_max=9, exponent=3, sigma_start=0.6, sigma_end=0.01) - model = SBO.DevSBO(epoch=100, pop_size=50, alpha=0.9, p_m=0.05, psw=0.02) - model = SBO.OriginalSBO(epoch=100, pop_size=50, alpha=0.9, p_m=0.05, psw=0.02) - model = SMA.OriginalSMA(epoch=100, pop_size=50, p_t=0.03) - model = SMA.DevSMA(epoch=100, pop_size=50, p_t=0.03) - model = SOA.OriginalSOA(epoch=100, pop_size=50, fc=2) - model = SOA.DevSOA(epoch=100, pop_size=50, fc=2) - model = SOS.OriginalSOS(epoch=100, pop_size=50) - model = TPO.DevTPO(epoch=100, pop_size=50, alpha=0.3, beta=50., theta=0.9) - model = TSA.OriginalTSA(epoch=100, pop_size=50) - model = VCS.OriginalVCS(epoch=100, pop_size=50, lamda=0.5, sigma=0.3) - model = VCS.DevVCS(epoch=100, pop_size=50, lamda=0.5, sigma=0.3) - model = WHO.OriginalWHO(epoch=100, pop_size=50, n_explore_step=3, n_exploit_step=3, eta=0.15, p_hi=0.9, local_alpha=0.9, local_beta=0.3, global_alpha=0.2, - global_beta=0.8, delta_w=2.0, delta_c=2.0) - model = AOA.OriginalAOA(epoch=100, pop_size=50, alpha=5, miu=0.5, moa_min=0.2, moa_max=0.9) - model = CEM.OriginalCEM(epoch=100, pop_size=50, n_best=20, alpha=0.7) - model = CGO.OriginalCGO(epoch=100, pop_size=50) - model = CircleSA.OriginalCircleSA(epoch=100, pop_size=50, c_factor=0.8) - model = GBO.OriginalGBO(epoch=100, pop_size=50, pr=0.5, beta_min=0.2, beta_max=1.2) - model = HC.OriginalHC(epoch=100, pop_size=50, neighbour_size=50) - model = HC.SwarmHC(epoch=100, pop_size=50, neighbour_size=10) - model = INFO.OriginalINFO(epoch=100, pop_size=50) - model = PSS.OriginalPSS(epoch=100, pop_size=50, acceptance_rate=0.8, sampling_method="LHS") - model = RUN.OriginalRUN(epoch=100, pop_size=50) - model = SCA.OriginalSCA(epoch=100, pop_size=50) - model = SCA.DevSCA(epoch=100, pop_size=50) - model = SCA.QleSCA(epoch=100, pop_size=50, alpha=0.1, gama=0.9) - model = SHIO.OriginalSHIO(epoch=100, pop_size=50) - model = TS.OriginalTS(epoch=100, pop_size=50, tabu_size=5, neighbour_size=20, perturbation_scale=0.05) - model = HS.OriginalHS(epoch=100, pop_size=50, c_r=0.95, pa_r=0.05) - model = HS.DevHS(epoch=100, pop_size=50, c_r=0.95, pa_r=0.05) - model = AEO.OriginalAEO(epoch=100, pop_size=50) - model = AEO.EnhancedAEO(epoch=100, pop_size=50) - model = AEO.ModifiedAEO(epoch=100, pop_size=50) - model = AEO.ImprovedAEO(epoch=100, pop_size=50) - model = AEO.AugmentedAEO(epoch=100, pop_size=50) - model = GCO.OriginalGCO(epoch=100, pop_size=50, cr=0.7, wf=1.25) - model = GCO.DevGCO(epoch=100, pop_size=50, cr=0.7, wf=1.25) - model = WCA.OriginalWCA(epoch=100, pop_size=50, nsr=4, wc=2.0, dmax=1e-6) - model = CRO.OriginalCRO(epoch=100, pop_size=50, po=0.4, Fb=0.9, Fa=0.1, Fd=0.1, Pd=0.5, GCR=0.1, gamma_min=0.02, gamma_max=0.2, n_trials=5) - model = CRO.OCRO(epoch=100, pop_size=50, po=0.4, Fb=0.9, Fa=0.1, Fd=0.1, Pd=0.5, GCR=0.1, gamma_min=0.02, gamma_max=0.2, n_trials=5, restart_count=50) - model = DE.OriginalDE(epoch=100, pop_size=50, wf=0.7, cr=0.9, strategy=0) - model = DE.JADE(epoch=100, pop_size=50, miu_f=0.5, miu_cr=0.5, pt=0.1, ap=0.1) - model = DE.SADE(epoch=100, pop_size=50) - model = DE.SAP_DE(epoch=100, pop_size=50, branch="ABS") - model = EP.OriginalEP(epoch=100, pop_size=50, bout_size=0.05) - model = EP.LevyEP(epoch=100, pop_size=50, bout_size=0.05) - model = ES.OriginalES(epoch=100, pop_size=50, lamda=0.75) - model = ES.LevyES(epoch=100, pop_size=50, lamda=0.75) - model = ES.CMA_ES(epoch=100, pop_size=50) - model = ES.Simple_CMA_ES(epoch=100, pop_size=50) - model = FPA.OriginalFPA(epoch=100, pop_size=50, p_s=0.8, levy_multiplier=0.2) - model = MA.OriginalMA(epoch=100, pop_size=50, pc=0.85, pm=0.15, p_local=0.5, max_local_gens=10, bits_per_param=4) - model = SHADE.OriginalSHADE(epoch=100, pop_size=50, miu_f=0.5, miu_cr=0.5) - model = SHADE.L_SHADE(epoch=100, pop_size=50, miu_f=0.5, miu_cr=0.5) - model = BRO.OriginalBRO(epoch=100, pop_size=50, threshold=3) - model = BRO.DevBRO(epoch=100, pop_size=50, threshold=3) - model = BSO.OriginalBSO(epoch=100, pop_size=50, m_clusters=5, p1=0.2, p2=0.8, p3=0.4, p4=0.5, slope=20) - model = BSO.ImprovedBSO(epoch=100, pop_size=50, m_clusters=5, p1=0.25, p2=0.5, p3=0.75, p4=0.6) - model = CA.OriginalCA(epoch=100, pop_size=50, accepted_rate=0.15) - model = CHIO.OriginalCHIO(epoch=100, pop_size=50, brr=0.15, max_age=10) - model = CHIO.DevCHIO(epoch=100, pop_size=50, brr=0.15, max_age=10) - model = FBIO.OriginalFBIO(epoch=100, pop_size=50) - model = FBIO.DevFBIO(epoch=100, pop_size=50) - model = GSKA.OriginalGSKA(epoch=100, pop_size=50, pb=0.1, kf=0.5, kr=0.9, kg=5) - model = GSKA.DevGSKA(epoch=100, pop_size=50, pb=0.1, kr=0.9) - model = HBO.OriginalHBO(epoch=100, pop_size=50, degree=3) - model = HCO.OriginalHCO(epoch=100, pop_size=50, wfp=0.65, wfv=0.05, c1=1.4, c2=1.4) - model = ICA.OriginalICA(epoch=100, pop_size=50, empire_count=5, assimilation_coeff=1.5, revolution_prob=0.05, revolution_rate=0.1, revolution_step_size=0.1, - zeta=0.1) - model = LCO.OriginalLCO(epoch=100, pop_size=50, r1=2.35) - model = LCO.ImprovedLCO(epoch=100, pop_size=50) - model = LCO.DevLCO(epoch=100, pop_size=50, r1=2.35) - model = WarSO.OriginalWarSO(epoch=100, pop_size=50, rr=0.1) - model = TOA.OriginalTOA(epoch=100, pop_size=50) - model = TLO.OriginalTLO(epoch=100, pop_size=50) - model = TLO.ImprovedTLO(epoch=100, pop_size=50, n_teachers=5) - model = TLO.DevTLO(epoch=100, pop_size=50) - model = SSDO.OriginalSSDO(epoch=100, pop_size=50) - model = SPBO.OriginalSPBO(epoch=100, pop_size=50) - model = SPBO.DevSPBO(epoch=100, pop_size=50) - model = SARO.OriginalSARO(epoch=100, pop_size=50, se=0.5, mu=50) - model = SARO.DevSARO(epoch=100, pop_size=50, se=0.5, mu=50) - model = QSA.OriginalQSA(epoch=100, pop_size=50) - model = QSA.DevQSA(epoch=100, pop_size=50) - model = QSA.OppoQSA(epoch=100, pop_size=50) - model = QSA.LevyQSA(epoch=100, pop_size=50) - model = QSA.ImprovedQSA(epoch=100, pop_size=50) - model = ArchOA.OriginalArchOA(epoch=100, pop_size=50, c1=2, c2=5, c3=2, c4=0.5, acc_max=0.9, acc_min=0.1) - model = ASO.OriginalASO(epoch=100, pop_size=50, alpha=50, beta=0.2) - model = CDO.OriginalCDO(epoch=100, pop_size=50) - model = EFO.OriginalEFO(epoch=100, pop_size=50, r_rate=0.3, ps_rate=0.85, p_field=0.1, n_field=0.45) - model = EFO.DevEFO(epoch=100, pop_size=50, r_rate=0.3, ps_rate=0.85, p_field=0.1, n_field=0.45) - model = EO.OriginalEO(epoch=100, pop_size=50) - model = EO.AdaptiveEO(epoch=100, pop_size=50) - model = EO.ModifiedEO(epoch=100, pop_size=50) - model = EVO.OriginalEVO(epoch=100, pop_size=50) - model = FLA.OriginalFLA(epoch=100, pop_size=50, C1=0.5, C2=2.0, C3=0.1, C4=0.2, C5=2.0, DD=0.01) - model = HGSO.OriginalHGSO(epoch=100, pop_size=50, n_clusters=3) - model = MVO.OriginalMVO(epoch=100, pop_size=50, wep_min=0.2, wep_max=1.0) - model = MVO.DevMVO(epoch=100, pop_size=50, wep_min=0.2, wep_max=1.0) - model = NRO.OriginalNRO(epoch=100, pop_size=50) - model = RIME.OriginalRIME(epoch=100, pop_size=50, sr=5.0) - model = SA.OriginalSA(epoch=100, pop_size=50, temp_init=100, step_size=0.1) - model = SA.GaussianSA(epoch=100, pop_size=50, temp_init=100, cooling_rate=0.99, scale=0.1) - model = SA.SwarmSA(epoch=100, pop_size=50, max_sub_iter=5, t0=1000, t1=1, move_count=5, mutation_rate=0.1, mutation_step_size=0.1, - mutation_step_size_damp=0.99) - model = WDO.OriginalWDO(epoch=100, pop_size=50, RT=3, g_c=0.2, alp=0.4, c_e=0.4, max_v=0.3) - model = TWO.OriginalTWO(epoch=100, pop_size=50) - model = TWO.EnhancedTWO(epoch=100, pop_size=50) - model = TWO.OppoTWO(epoch=100, pop_size=50) - model = TWO.LevyTWO(epoch=100, pop_size=50) - model = ABC.OriginalABC(epoch=100, pop_size=50, n_limits=50) - model = ACOR.OriginalACOR(epoch=100, pop_size=50, sample_count=25, intent_factor=0.5, zeta=1.0) - model = AGTO.OriginalAGTO(epoch=100, pop_size=50, p1=0.03, p2=0.8, beta=3.0) - model = AGTO.MGTO(epoch=100, pop_size=50, pp=0.03) - model = BeesA.OriginalBeesA(epoch=100, pop_size=50, selected_site_ratio=0.5, elite_site_ratio=0.4, selected_site_bee_ratio=0.1, elite_site_bee_ratio=2.0, - dance_radius=0.1, dance_reduction=0.99) - model = BeesA.CleverBookBeesA(epoch=100, pop_size=50, n_elites=16, n_others=4, patch_size=5.0, patch_reduction=0.985, n_sites=3, n_elite_sites=1) - model = BeesA.ProbBeesA(epoch=100, pop_size=50, recruited_bee_ratio=0.1, dance_radius=0.1, dance_reduction=0.99) - model = BES.OriginalBES(epoch=100, pop_size=50, a_factor=10, R_factor=1.5, alpha=2.0, c1=2.0, c2=2.0) - model = BFO.OriginalBFO(epoch=100, pop_size=50, Ci=0.01, Ped=0.25, Nc=5, Ns=4, d_attract=0.1, w_attract=0.2, h_repels=0.1, w_repels=10) - model = BFO.ABFO(epoch=100, pop_size=50, C_s=0.1, C_e=0.001, Ped=0.01, Ns=4, N_adapt=2, N_split=40) - model = ZOA.OriginalZOA(epoch=100, pop_size=50) - model = WOA.OriginalWOA(epoch=100, pop_size=50) - model = WOA.HI_WOA(epoch=100, pop_size=50, feedback_max=10) - model = WaOA.OriginalWaOA(epoch=100, pop_size=50) - model = TSO.OriginalTSO(epoch=100, pop_size=50) - model = TDO.OriginalTDO(epoch=100, pop_size=50) - model = STO.OriginalSTO(epoch=100, pop_size=50) - model = SSpiderO.OriginalSSpiderO(epoch=100, pop_size=50, fp_min=0.65, fp_max=0.9) - model = SSpiderA.OriginalSSpiderA(epoch=100, pop_size=50, r_a=1.0, p_c=0.7, p_m=0.1) - model = SSO.OriginalSSO(epoch=100, pop_size=50) - model = SSA.OriginalSSA(epoch=100, pop_size=50, ST=0.8, PD=0.2, SD=0.1) - model = SSA.DevSSA(epoch=100, pop_size=50, ST=0.8, PD=0.2, SD=0.1) - model = SRSR.OriginalSRSR(epoch=100, pop_size=50) - model = SLO.OriginalSLO(epoch=100, pop_size=50) - model = SLO.ModifiedSLO(epoch=100, pop_size=50) - model = SLO.ImprovedSLO(epoch=100, pop_size=50, c1=1.2, c2=1.5) - model = SHO.OriginalSHO(epoch=100, pop_size=50, h_factor=5.0, n_trials=10) - model = SFO.OriginalSFO(epoch=100, pop_size=50, pp=0.1, AP=4.0, epsilon=0.0001) - model = SFO.ImprovedSFO(epoch=100, pop_size=50, pp=0.1) - model = ServalOA.OriginalServalOA(epoch=100, pop_size=50) - model = SeaHO.OriginalSeaHO(epoch=100, pop_size=50) - model = SCSO.OriginalSCSO(epoch=100, pop_size=50) - model = POA.OriginalPOA(epoch=100, pop_size=50) - model = PFA.OriginalPFA(epoch=100, pop_size=50) - model = OOA.OriginalOOA(epoch=100, pop_size=50) - model = NGO.OriginalNGO(epoch=100, pop_size=50) - model = NMRA.OriginalNMRA(epoch=100, pop_size=50, pb=0.75) - model = NMRA.ImprovedNMRA(epoch=100, pop_size=50, pb=0.75, pm=0.01) - model = MSA.OriginalMSA(epoch=100, pop_size=50, n_best=5, partition=0.5, max_step_size=1.0) - model = MRFO.OriginalMRFO(epoch=100, pop_size=50, somersault_range=2.0) - model = MRFO.WMQIMRFO(epoch=100, pop_size=50, somersault_range=2.0, pm=0.5) - model = MPA.OriginalMPA(epoch=100, pop_size=50) - model = MGO.OriginalMGO(epoch=100, pop_size=50) - model = MFO.OriginalMFO(epoch=100, pop_size=50) - model = JA.OriginalJA(epoch=100, pop_size=50) - model = JA.LevyJA(epoch=100, pop_size=50) - model = JA.DevJA(epoch=100, pop_size=50) - model = HHO.OriginalHHO(epoch=100, pop_size=50) - model = HGS.OriginalHGS(epoch=100, pop_size=50, PUP=0.08, LH=10000) - model = HBA.OriginalHBA(epoch=100, pop_size=50) - model = GWO.OriginalGWO(epoch=100, pop_size=50) - model = GWO.RW_GWO(epoch=100, pop_size=50) - model = GTO.OriginalGTO(epoch=100, pop_size=50, A=0.4, H=2.0) - model = GTO.Matlab101GTO(epoch=100, pop_size=50) - model = GTO.Matlab102GTO(epoch=100, pop_size=50) - model = GOA.OriginalGOA(epoch=100, pop_size=50, c_min=0.00004, c_max=1.0) - model = GJO.OriginalGJO(epoch=100, pop_size=50) - model = FOX.OriginalFOX(epoch=100, pop_size=50, c1=0.18, c2=0.82) - model = FOA.OriginalFOA(epoch=100, pop_size=50) - model = FOA.WhaleFOA(epoch=100, pop_size=50) - model = FOA.DevFOA(epoch=100, pop_size=50) - model = FFO.OriginalFFO(epoch=100, pop_size=50) - model = FFA.OriginalFFA(epoch=100, pop_size=50, gamma=0.001, beta_base=2, alpha=0.2, alpha_damp=0.99, delta=0.05, exponent=2) - model = FA.OriginalFA(epoch=100, pop_size=50, max_sparks=50, p_a=0.04, p_b=0.8, max_ea=40, m_sparks=50) - model = ESOA.OriginalESOA(epoch=100, pop_size=50) - model = EHO.OriginalEHO(epoch=100, pop_size=50, alpha=0.5, beta=0.5, n_clans=5) - model = DO.OriginalDO(epoch=100, pop_size=50) - model = DMOA.OriginalDMOA(epoch=100, pop_size=50, n_baby_sitter=3, peep=2) - model = DMOA.DevDMOA(epoch=100, pop_size=50, peep=2) - model = CSO.OriginalCSO(epoch=100, pop_size=50, mixture_ratio=0.15, smp=5, spc=False, cdc=0.8, srd=0.15, c1=0.4, w_min=0.4, w_max=0.9) - model = CSA.OriginalCSA(epoch=100, pop_size=50, p_a=0.3) - model = CoatiOA.OriginalCoatiOA(epoch=100, pop_size=50) - model = COA.OriginalCOA(epoch=100, pop_size=50, n_coyotes=5) - model = BSA.OriginalBSA(epoch=100, pop_size=50, ff=10, pff=0.8, c1=1.5, c2=1.5, a1=1.0, a2=1.0, fc=0.5) - - ## Newly added algorithms in version 3.0.3 - model = GWO.GWO_WOA(epoch=100, pop_size=50) - model = GWO.IGWO(epoch=1000, pop_size=50, a_min = 0.02, a_max = 2.2) - model = GWO.ChaoticGWO(epoch=1000, pop_size=50, chaotic_name="chebyshev", initial_chaotic_value=0.7) - model = GWO.FuzzyGWO(epoch=1000, pop_size=50, fuzzy_name="increase") - model = GWO.IncrementalGWO(epoch=1000, pop_size=50, explore_factor=1.5) - model = GWO.ExGWO(epoch=1000, pop_size=50) - model = GWO.DS_GWO(epoch=1000, pop_size=50, explore_ratio=0.4, n_groups=5) - model = GWO.IOBL_GWO(epoch=1000, pop_size=50) - model = GWO.OGWO(epoch=1000, pop_size=50, miu_factor=2.0, jumping_rate=0.05) - model = GWO.ER_GWO(epoch=1000, pop_size=50, a_initial=2.0, a_final=0.0, miu_factor=1.0001) - model = GWO.CG_GWO(epoch=1000, pop_size=50) - - model = ESO.OriginalESO(epoch=1000, pop_size=50) - model = AO.AAO(epoch=1000, pop_size=50, sharpness=10.0, sigmoid_midpoint=0.5) - model = EPC.DevEPC(epoch=1000, pop_size=50, heat_damping_factor=0.95, mutation_factor=0.1, spiral_a=1.0, spiral_b=0.5) - model = SMO.DevSMO(epoch=1000, pop_size=50, max_groups = 5, perturbation_rate = 0.7) - model = SquirrelSA.OriginalSquirrelSA(epoch=1000, pop_size=50, n_food_sources=4, predator_prob=0.1, gliding_constant=1.9, scaling_factor=18, beta=1.5) - model = AFT.OriginalAFT(epoch=1000, pop_size=50) - model = CDDO.OriginalCDDO(epoch=1000, pop_size=50, pattern_size=10, creativity_rate=0.1) - model = FDO.OriginalFDO(epoch=1000, pop_size=50, weight_factor=0.1) - model = LSHADEcnEpSin.OriginalLSHADEcnEpSin(epoch=1000, pop_size=50, miu_f = 0.5, miu_cr = 0.5, freq = 0.5, memory_size = 5, ps = 0.5, pc = 0.4, pop_size_min = 10) - model = IMODE.OriginalIMODE(epoch=1000, pop_size=50, memory_size=5, archive_size=20) - - -``` - -
- - -## ✅ Examples +## Examples ### Simple Benchmark Function @@ -2737,672 +259,9 @@ print(model.problem.lb) print(model.problem.ub) ``` - We provide many examples for complicated applications that can use Mealpy to solve. - -## 🚀 Mealpy Applications - -MEALPY is a versatile library capable of solving a wide array of complex optimization problems across various domains. Below are examples showcasing its diverse applications. - -### 1. General Optimization Problems - -These examples demonstrate MEALPY's use in common optimization scenarios. - -1. Large-Scale Optimization [example](/examples/applications/run_large_scale_optimization.py) -2. Distributed Optimization / Parallelization Optimization [example](/examples/applications/run_distributed_optimization.py) -3. Constrained Benchmark Function [example](/examples/applications/run_constraint_functions.py) -4. Multi-objective Benchmark Function [example](/examples/applications/run_multi_objective_functions.py) - -### 2. Machine Learning & AI Optimization - -MEALPY can be effectively used to optimize various aspects of Machine Learning and AI models. - -1. Optimize Machine Learning Model (SVM) Hyperparameters [example](/examples/applications/sklearn/svm_hyperparameter_optimization.py) -2. Optimize Linear Regression Model with Pytorch: [example](/examples/applications/pytorch/linear_regression.py) - -### 3. Combinatorial Optimization Problems - -MEALPY excels at solving complex combinatorial problems, which involve finding an optimal object from a finite set of objects. - -1. Traveling Salesman Problem (TSP) [example](/examples/applications/discrete-problems/traveling_salesman_problem.py) -2. Job Shop Scheduling Problem [example](/examples/applications/discrete-problems/job_shop_scheduling.py) -3. Shortest Path Problem [example](/examples/applications/discrete-problems/shortest_path_problem.py) -4. Location Optimization [example](/examples/applications/discrete-problems/location_optimization.py) -5. Supply Chain Optimization [example](/examples/applications/discrete-problems/supply_chain_optimization.py) -6. Healthcare Workflow Optimization Problem [example](/examples/applications/discrete-problems/workflow_optimization.py) -7. Production Optimization Problem [example](/examples/applications/discrete-problems/production_optimization.py) -8. Employee Rostering Problem [example](/examples/applications/discrete-problems/employee_rostering.py) -9. Maintenance Scheduling [example](/examples/applications/discrete-problems/maintenance_scheduling.py) -10. Cloud task scheduling [example](/examples/applications/discrete-problems/cloud_task_scheduling.py) - -### 4. Advanced Integration Examples - -MEALPY's flexibility allows for integration into more specialized systems and workflows. - -#### MEALPY + Neural Networks (Replacing Gradient Descent) - -* Time-series Problem: - * Traditional MLP [Link](/examples/applications/keras/traditional-mlp-time-series.py) - * Hybrid code (Mealpy + MLP): [Link](/examples/applications/keras/mha-hybrid-mlp-time-series.py) -* Classification Problem: - * Traditional MLP [Link](/examples/applications/keras/traditional-mlp-classification.py) - * Hybrid code (Mealpy + MLP): [Link](/examples/applications/keras/mha-hybrid-mlp-classification.py) - -#### MEALPY + Neural Network (Optimize Neural Network Hyper-parameter) - -Code: [Link](https://github.com/thieu1995/mealpy/blob/master/examples/applications/keras/mha-hyper-parameter-mlp-time-series.py) - - -### 5. Dedicated Utility Classes - -MEALPY includes specialized classes to streamline common optimization tasks. - -1. Tuner class (GridSearchCV/ParameterSearch, Hyper-parameter tuning) [example](/examples/run_tuner.py) -2. Multitask class (Multitask solver) [example](/examples/run_multitask.py) -3. Visualization [Tutorials](/examples/utils/visualize/all_charts.py) - -### 6. External Projects & More Examples - -Explore additional advanced examples and dedicated projects showcasing MEALPY's capabilities. - -* Travelling Salesman Problem: [link](https://github.com/thieu1995/MHA-TSP) -* Feature selection problem: [link](https://github.com/thieu1995/MHA-FS) - -For more usage examples please look at [examples](/examples) folder. -More advanced examples can also be found in the [Mealpy-examples repository](https://github.com/thieu1995/mealpy_examples). - - -### 7. Tutorial Videos & Resources - -All tutorial videos: [Link](https://mealpy.readthedocs.io/en/latest/pages/general/video_tutorials.html) - -All code examples: [Link](/examples) - -All visualization examples: [Link](https://mealpy.readthedocs.io/en/latest/pages/visualization.html) - - -# 📚 Documents - -## 📎 Official channels - -* 🔗 [Official source code repository](https://github.com/thieu1995/mealpy) -* 📘 [Official document](https://mealpy.readthedocs.io/) -* 📦 [Download releases](https://pypi.org/project/mealpy/) -* 🐞 [Issue tracker](https://github.com/thieu1995/mealpy/issues) -* 📝 [Notable changes log](/ChangeLog.md) -* 📝 [Examples with different meapy version](/examples/EXAMPLES.md) -* 💬 [Official discussion group](https://t.me/+fRVCJGuGJg1mNDg1) - - -## 🌟 MEALPY ecosystem - -* [Mealpy + Multi-Layer Perceptron](https://github.com/thieu1995/MetaPerceptron) -* [Mealpy + Extreme Learning Machine](https://github.com/thieu1995/IntelELM) -* [Mealpy + Random Vector Functional Link Neural Network](https://github.com/thieu1995/GrafoRVFL) -* [Mealpy + KMeans clustering](https://github.com/thieu1995/MetaCluster) -* [Mealpy + Cascade-Forward Neural Network](https://github.com/thieu1995/deforce) -* [Mealpy + Higher Order Functional Link Neural Network](https://github.com/thieu1995/reflame) -* [Mealpy + Radial Basis Function](https://github.com/thieu1995/EvoRBF) -* [Mealpy + Adaptive Neuro Fuzzy Inference System](https://github.com/thieu1995/X-ANFIS) -* [Mealpy + Wavelet Neural Network](https://github.com/thieu1995/WaveletML) -* [Mealpy + Kolmogorov–Arnold Network](https://github.com/thieu1995/MetaKan) -* [Mealpy + Feature Selection](https://github.com/thieu1995/mafese) -* [Mealpy + Scikit-Learn](https://github.com/thieu1995/MetaSklearn) -* [Mealpy + Immune Algorithm-Inspired Neural Network](https://github.com/thieu1995/IMAINET) - - - -

References

- -### A - -* **ABC - Artificial Bee Colony** - * **OriginalABC**: Karaboga, D. (2005). An idea based on honey bee swarm for numerical optimization (Vol. 200, pp. 1-10). Technical report-tr06, Erciyes university, engineering faculty, computer engineering department. - -* **ACOR - Ant Colony Optimization**. - * **OriginalACOR**: Socha, K., & Dorigo, M. (2008). Ant colony optimization for continuous domains. European journal of operational research, 185(3), 1155-1173. - -* **ALO - Ant Lion Optimizer** - * **OriginalALO**: Mirjalili S (2015). “The Ant Lion Optimizer.” Advances in Engineering Software, 83, 80-98. doi: [10.1016/j.advengsoft.2015.01.010](https://doi.org/10.1016/j.advengsoft.2015.01.010) - * **BaseALO**: The developed version - -* **AEO - Artificial Ecosystem-based Optimization** - * **OriginalAEO**: Zhao, W., Wang, L., & Zhang, Z. (2019). Artificial ecosystem-based optimization: a novel nature-inspired meta-heuristic algorithm. Neural Computing and Applications, 1-43. - * **AugmentedAEO**: Van Thieu, N., Barma, S. D., Van Lam, T., Kisi, O., & Mahesha, A. (2022). Groundwater level modeling using Augmented Artificial Ecosystem Optimization. Journal of Hydrology, 129034. - * **ImprovedAEO**: Rizk-Allah, R. M., & El-Fergany, A. A. (2020). Artificial ecosystem optimizer for parameters identification of proton exchange membrane fuel cells model. International Journal of Hydrogen Energy. - * **EnhancedAEO**: Eid, A., Kamel, S., Korashy, A., & Khurshaid, T. (2020). An Enhanced Artificial Ecosystem-Based Optimization for Optimal Allocation of Multiple Distributed Generations. IEEE Access, 8, 178493-178513. - * **ModifiedAEO**: Menesy, A. S., Sultan, H. M., Korashy, A., Banakhr, F. A., Ashmawy, M. G., & Kamel, S. (2020). Effective parameter extraction of different polymer electrolyte membrane fuel cell stack models using a modified artificial ecosystem optimization algorithm. IEEE Access, 8, 31892-31909. - -* **ASO - Atom Search Optimization** - * **OriginalASO**: Zhao, W., Wang, L., & Zhang, Z. (2019). Atom search optimization and its application to solve a hydrogeologic parameter estimation problem. Knowledge-Based Systems, 163, 283-304. - -* **ArchOA - Archimedes Optimization Algorithm** - * **OriginalArchOA**: Hashim, F. A., Hussain, K., Houssein, E. H., Mabrouk, M. S., & Al-Atabany, W. (2021). Archimedes optimization algorithm: a new metaheuristic algorithm for solving optimization problems. Applied Intelligence, 51(3), 1531-1551. - -* **AOA - Arithmetic Optimization Algorithm** - * **OriginalAOA**: Abualigah, L., Diabat, A., Mirjalili, S., Abd Elaziz, M., & Gandomi, A. H. (2021). The arithmetic optimization algorithm. Computer methods in applied mechanics and engineering, 376, 113609. - -* **AO - Aquila Optimizer** - * **OriginalAO**: Abualigah, L., Yousri, D., Abd Elaziz, M., Ewees, A. A., Al-qaness, M. A., & Gandomi, A. H. (2021). Aquila Optimizer: A novel meta-heuristic optimization Algorithm. Computers & Industrial Engineering, 157, 107250. - * **AAO**: Al-Selwi, S. M., Hassan, M. F., Abdulkadir, S. J., Ragab, M. G., Alqushaibi, A., & Sumiea, E. H. (2024). Smart grid stability prediction using adaptive aquila optimizer and ensemble stacked bilstm. Results in Engineering, 24, 103261. - -* **AVOA - African Vultures Optimization Algorithm** - * **OriginalAVOA**: Abdollahzadeh, B., Gharehchopogh, F. S., & Mirjalili, S. (2021). African vultures optimization algorithm: A new nature-inspired metaheuristic algorithm for global optimization problems. Computers & Industrial Engineering, 158, 107408. - -* **AGTO - Artificial Gorilla Troops Optimization** - * **OriginalAGTO**: Abdollahzadeh, B., Soleimanian Gharehchopogh, F., & Mirjalili, S. (2021). Artificial gorilla troops optimizer: a new nature‐inspired metaheuristic algorithm for global optimization problems. International Journal of Intelligent Systems, 36(10), 5887-5958. - -* **ARO - Artificial Rabbits Optimization**: - * **OriginalARO**: Wang, L., Cao, Q., Zhang, Z., Mirjalili, S., & Zhao, W. (2022). Artificial rabbits optimization: A new bio-inspired meta-heuristic algorithm for solving engineering optimization problems. Engineering Applications of Artificial Intelligence, 114, 105082. - -* **AFT - Ali baba and the Forty Thieves**: - * **OriginalAFT**: Braik, M., Ryalat, M. H., & Al-Zoubi, H. (2022). A novel meta-heuristic algorithm for solving numerical optimization problems: Ali Baba and the forty thieves. Neural Computing and Applications, 34(1), 409-455. - - -### B - - -* **BFO - Bacterial Foraging Optimization** - * **OriginalBFO**: Passino, K. M. (2002). Biomimicry of bacterial foraging for distributed optimization and control. IEEE control systems magazine, 22(3), 52-67. - * **ABFO**: Nguyen, T., Nguyen, B. M., & Nguyen, G. (2019, April). Building resource auto-scaler with functional-link neural network and adaptive bacterial foraging optimization. In International Conference on Theory and Applications of Models of Computation (pp. 501-517). Springer, Cham. - -* **BeesA - Bees Algorithm** - * **OriginalBeesA**: Pham, D. T., Ghanbarzadeh, A., Koc, E., Otri, S., Rahim, S., & Zaidi, M. (2005). The bees algorithm. Technical Note, Manufacturing Engineering Centre, Cardiff University, UK. - * **ProbBeesA**: The probabilitic version of: Pham, D. T., Ghanbarzadeh, A., Koç, E., Otri, S., Rahim, S., & Zaidi, M. (2006). The bees algorithm—a novel tool for complex optimisation problems. In Intelligent production machines and systems (pp. 454-459). Elsevier Science Ltd. - -* **BBO - Biogeography-Based Optimization** - * **OriginalBBO**: Simon, D. (2008). Biogeography-based optimization. IEEE transactions on evolutionary computation, 12(6), 702-713. - * **BaseBBO**: The developed version - -* **BA - Bat Algorithm** - * **OriginalBA**: Yang, X. S. (2010). A new metaheuristic bat-inspired algorithm. In Nature inspired cooperative strategies for optimization (NICSO 2010) (pp. 65-74). Springer, Berlin, Heidelberg. - * **AdaptiveBA**: Wang, X., Wang, W. and Wang, Y., 2013, July. An adaptive bat algorithm. In International Conference on Intelligent Computing(pp. 216-223). Springer, Berlin, Heidelberg. - * **ModifiedBA**: Dong, H., Li, T., Ding, R. and Sun, J., 2018. A novel hybrid genetic algorithm with granular information for feature selection and optimization. Applied Soft Computing, 65, pp.33-46. - -* **BSO - Brain Storm Optimization** - * **OriginalBSO**: . Shi, Y. (2011, June). Brain storm optimization algorithm. In International conference in swarm intelligence (pp. 303-309). Springer, Berlin, Heidelberg. - * **ImprovedBSO**: El-Abd, M., 2017. Global-best brain storm optimization algorithm. Swarm and evolutionary computation, 37, pp.27-44. - -* **BSA - Bird Swarm Algorithm** - * **OriginalBSA**: Meng, X. B., Gao, X. Z., Lu, L., Liu, Y., & Zhang, H. (2016). A new bio-inspired optimisation algorithm:Bird Swarm Algorithm. Journal of Experimental & Theoretical Artificial Intelligence, 28(4), 673-687. - -* **BMO - Barnacles Mating Optimizer**: - * **OriginalBMO**: Sulaiman, M. H., Mustaffa, Z., Saari, M. M., Daniyal, H., Daud, M. R., Razali, S., & Mohamed, A. I. (2018, June). Barnacles mating optimizer: a bio-inspired algorithm for solving optimization problems. In 2018 19th IEEE/ACIS International Conference on Software Engineering, Artificial Intelligence, Networking and Parallel/Distributed Computing (SNPD) (pp. 265-270). IEEE. - -* **BES - Bald Eagle Search** - * **OriginalBES**: Alsattar, H. A., Zaidan, A. A., & Zaidan, B. B. (2019). Novel meta-heuristic bald eagle search optimisation algorithm. Artificial Intelligence Review, 1-28. - -* **BRO - Battle Royale Optimization** - * **OriginalBRO**: Rahkar Farshi, T. (2020). Battle royale optimization algorithm. Neural Computing and Applications, 1-19. - * **BaseBRO**: The developed version - -### C - -* **CA - Culture Algorithm** - * **OriginalCA**: Reynolds, R.G., 1994, February. An introduction to cultural algorithms. In Proceedings of the third annual conference on evolutionary programming (Vol. 24, pp. 131-139). River Edge, NJ: World Scientific. - -* **CEM - Cross Entropy Method** - * **OriginalCEM**: Rubinstein, R. (1999). The cross-entropy method for combinatorial and continuous optimization. Methodology and computing in applied probability, 1(2), 127-190. - -* **CSO - Cat Swarm Optimization** - * **OriginalCSO**: Chu, S. C., Tsai, P. W., & Pan, J. S. (2006, August). Cat swarm optimization. In Pacific Rim international conference on artificial intelligence (pp. 854-858). Springer, Berlin, Heidelberg. - -* **CSA - Cuckoo Search Algorithm** - * **OriginalCSA**: Yang, X. S., & Deb, S. (2009, December). Cuckoo search via Lévy flights. In 2009 World congress on nature & biologically inspired computing (NaBIC) (pp. 210-214). Ieee. - -* **CRO - Coral Reefs Optimization** - * **OriginalCRO**: Salcedo-Sanz, S., Del Ser, J., Landa-Torres, I., Gil-López, S., & Portilla-Figueras, J. A. (2014). The coral reefs optimization algorithm: a novel metaheuristic for efficiently solving optimization problems. The Scientific World Journal, 2014. - * **OCRO**: Nguyen, T., Nguyen, T., Nguyen, B. M., & Nguyen, G. (2019). Efficient time-series forecasting using neural network and opposition-based coral reefs optimization. International Journal of Computational Intelligence Systems, 12(2), 1144-1161. - -* **COA - Coyote Optimization Algorithm** - * **OriginalCOA**: Pierezan, J., & Coelho, L. D. S. (2018, July). Coyote optimization algorithm: a new metaheuristic for global optimization problems. In 2018 IEEE congress on evolutionary computation (CEC) (pp. 1-8). IEEE. - -* **CHIO - Coronavirus Herd Immunity Optimization** - * **OriginalCHIO**: Al-Betar, M. A., Alyasseri, Z. A. A., Awadallah, M. A., & Abu Doush, I. (2021). Coronavirus herd immunity optimizer (CHIO). Neural Computing and Applications, 33(10), 5011-5042. - * **BaseCHIO**: The developed version - -* **CGO - Chaos Game Optimization** - * **OriginalCGO**: Talatahari, S., & Azizi, M. (2021). Chaos Game Optimization: a novel metaheuristic algorithm. Artificial Intelligence Review, 54(2), 917-1004. - -* **CSA - Circle Search Algorithm** - * **OriginalCSA**: Qais, M. H., Hasanien, H. M., Turky, R. A., Alghuwainem, S., Tostado-Véliz, M., & Jurado, F. (2022). Circle Search Algorithm: A Geometry-Based Metaheuristic Optimization Algorithm. Mathematics, 10(10), 1626. - -* **CDDO - Child Drawing Development Optimization** - * **OriginalCDDO**: Abdulhameed, S., Rashid, T.A. Child Drawing Development Optimization Algorithm Based on Child’s Cognitive Development. Arab J Sci Eng 47, 1337–1351 (2022). https://doi.org/10.1007/s13369-021-05928-6 - - -### D - -* **DE - Differential Evolution** - * **BaseDE**: Storn, R., & Price, K. (1997). Differential evolution–a simple and efficient heuristic for global optimization over continuous spaces. Journal of global optimization, 11(4), 341-359. - * **JADE**: Zhang, J., & Sanderson, A. C. (2009). JADE: adaptive differential evolution with optional external archive. IEEE Transactions on evolutionary computation, 13(5), 945-958. - * **SADE**: Qin, A. K., & Suganthan, P. N. (2005, September). Self-adaptive differential evolution algorithm for numerical optimization. In 2005 IEEE congress on evolutionary computation (Vol. 2, pp. 1785-1791). IEEE. - * **SHADE**: Tanabe, R., & Fukunaga, A. (2013, June). Success-history based parameter adaptation for differential evolution. In 2013 IEEE congress on evolutionary computation (pp. 71-78). IEEE. - * **L_SHADE**: Tanabe, R., & Fukunaga, A. S. (2014, July). Improving the search performance of SHADE using linear population size reduction. In 2014 IEEE congress on evolutionary computation (CEC) (pp. 1658-1665). IEEE. - * **SAP_DE**: Teo, J. (2006). Exploring dynamic cls-adaptive populations in differential evolution. Soft Computing, 10(8), 673-686. - -* **DSA - Differential Search Algorithm (not done)** - * **BaseDSA**: Civicioglu, P. (2012). Transforming geocentric cartesian coordinates to geodetic coordinates by using differential search algorithm. Computers & Geosciences, 46, 229-247. - -* **DO - Dragonfly Optimization** - * **OriginalDO**: Mirjalili, S. (2016). Dragonfly algorithm: a new meta-heuristic optimization technique for solving single-objective, discrete, and multi-objective problems. Neural Computing and Applications, 27(4), 1053-1073. - -* **DMOA - Dwarf Mongoose Optimization Algorithm** - * **OriginalDMOA**: Agushaka, J. O., Ezugwu, A. E., & Abualigah, L. (2022). Dwarf mongoose optimization algorithm. Computer methods in applied mechanics and engineering, 391, 114570. - * **DevDMOA**: The developed version - -### E - -* **ES - Evolution Strategies** . - * **OriginalES**: Schwefel, H. P. (1984). Evolution strategies: A family of non-linear optimization techniques based on imitating some principles of organic evolution. Annals of Operations Research, 1(2), 165-167. - * **LevyES**: Zhang, S., & Salari, E. (2005). Competitive learning vector quantization with evolution strategies for image compression. Optical Engineering, 44(2), 027006. - -* **EP - Evolutionary programming** . - * **OriginalEP**: Fogel, L. J. (1994). Evolutionary programming in perspective: The top-down view. Computational intelligence: Imitating life. - * **LevyEP**: Lee, C.Y. and Yao, X., 2001, May. Evolutionary algorithms with adaptive lévy mutations. In Proceedings of the 2001 congress on evolutionary computation (IEEE Cat. No. 01TH8546) (Vol. 1, pp. 568-575). IEEE. - -* **EHO - Elephant Herding Optimization** . - * **OriginalEHO**: Wang, G. G., Deb, S., & Coelho, L. D. S. (2015, December). Elephant herding optimization. In 2015 3rd International Symposium on Computational and Business Intelligence (ISCBI) (pp. 1-5). IEEE. - -* **EFO - Electromagnetic Field Optimization** . - * **OriginalEFO**:Abedinpourshotorban, H., Shamsuddin, S. M., Beheshti, Z., & Jawawi, D. N. (2016). Electromagnetic field optimization: A physics-inspired metaheuristic optimization algorithm. Swarm and Evolutionary Computation, 26, 8-22. - * **BaseEFO**: The developed version - -* **EOA - Earthworm Optimisation Algorithm** . - * **OriginalEOA**: Wang, G. G., Deb, S., & dos Santos Coelho, L. (2018). Earthworm optimisation algorithm: a bio-inspired metaheuristic algorithm for global optimisation problems. IJBIC, 12(1), 1-22. - -* **EO - Equilibrium Optimizer** . - * **OriginalEO**: Faramarzi, A., Heidarinejad, M., Stephens, B., & Mirjalili, S. (2019). Equilibrium optimizer: A novel optimization algorithm. Knowledge-Based Systems. - * **ModifiedEO**: Gupta, S., Deep, K., & Mirjalili, S. (2020). An efficient equilibrium optimizer with mutation strategy for numerical optimization. Applied Soft Computing, 96, 106542. - * **AdaptiveEO**: Wunnava, A., Naik, M. K., Panda, R., Jena, B., & Abraham, A. (2020). A novel interdependence based multilevel thresholding technique using adaptive equilibrium optimizer. Engineering Applications of Artificial Intelligence, 94, 103836. - -* **ESO - Electrical Storm Optimization** . - * **OriginalESO**: Soto Calvo, M., & Lee, H. S. (2025). Electrical Storm Optimization (ESO) Algorithm: Theoretical Foundations, Analysis, and Application to Engineering Problems. Machine Learning and Knowledge Extraction, 7(1), 24. https://doi.org/10.3390/make7010024 - -* **EPC - Emperor Penguins Colony** . - * **DevEPC**: Harifi, S., Khalilian, M., Mohammadzadeh, J. and Ebrahimnejad, S., 2019. Emperor Penguins Colony: a new metaheuristic algorithm for optimization. Evolutionary intelligence, 12(2), pp.211-226. - - -### F - -* **FFA - Firefly Algorithm** - * **OriginalFFA**: Łukasik, S., & Żak, S. (2009, October). Firefly algorithm for continuous constrained optimization tasks. In International conference on computational collective intelligence (pp. 97-106). Springer, Berlin, Heidelberg. - -* **FA - Fireworks algorithm** - * **OriginalFA**: Tan, Y., & Zhu, Y. (2010, June). Fireworks algorithm for optimization. In International conference in swarm intelligence (pp. 355-364). Springer, Berlin, Heidelberg. - -* **FPA - Flower Pollination Algorithm** - * **OriginalFPA**: Yang, X. S. (2012, September). Flower pollination algorithm for global optimization. In International conference on unconventional computing and natural computation (pp. 240-249). Springer, Berlin, Heidelberg. - -* **FOA - Fruit-fly Optimization Algorithm** - * **OriginalFOA**: Pan, W. T. (2012). A new fruit fly optimization algorithm: taking the financial distress model as an example. Knowledge-Based Systems, 26, 69-74. - * **BaseFOA**: The developed version - * **WhaleFOA**: Fan, Y., Wang, P., Heidari, A. A., Wang, M., Zhao, X., Chen, H., & Li, C. (2020). Boosted hunting-based fruit fly optimization and advances in real-world problems. Expert Systems with Applications, 159, 113502. - -* **FDO - Fitness Dependent Optimizer** - * **OriginalFDO**: Abdullah, J. M., & Ahmed, T. (2019). Fitness dependent optimizer: inspired by the bee swarming reproductive process. IEEe Access, 7, 43473-43486. - -* **FBIO - Forensic-Based Investigation Optimization** - * **OriginalFBIO**: Chou, J.S. and Nguyen, N.M., 2020. FBI inspired meta-optimization. Applied Soft Computing, p.106339. - * **BaseFBIO**: Fathy, A., Rezk, H. and Alanazi, T.M., 2021. Recent approach of forensic-based investigation algorithm for optimizing fractional order PID-based MPPT with proton exchange membrane fuel cell.IEEE Access,9, pp.18974-18992. - -* **FHO - Fire Hawk Optimization** - * **OriginalFHO**: Azizi, M., Talatahari, S., & Gandomi, A. H. (2022). Fire Hawk Optimizer: a novel metaheuristic algorithm. Artificial Intelligence Review, 1-77. - -### G - -* **GA - Genetic Algorithm** - * **BaseGA**: Holland, J. H. (1992). Genetic algorithms. Scientific american, 267(1), 66-73. - * **SingleGA**: De Falco, I., Della Cioppa, A. and Tarantino, E., 2002. Mutation-based genetic algorithm: performance evaluation. Applied Soft Computing, 1(4), pp.285-299. - * **MultiGA**: De Jong, K.A. and Spears, W.M., 1992. A formal analysis of the role of multi-point crossover in genetic algorithms. Annals of mathematics and Artificial intelligence, 5(1), pp.1-26. - * **EliteSingleGA**: Elite version of Single-point mutation GA - * **EliteMultiGA**: Elite version of Multiple-point mutation GA - -* **GWO - Grey Wolf Optimizer** - * **OriginalGWO**: Mirjalili, S., Mirjalili, S. M., & Lewis, A. (2014). Grey wolf optimizer. Advances in engineering software, 69, 46-61. - * **RW_GWO**: Gupta, S., & Deep, K. (2019). A novel random walk grey wolf optimizer. Swarm and evolutionary computation, 44, 101-112. - * **GWO_WOA**: Obadina, O. O., Thaha, M. A., Althoefer, K., & Shaheed, M. H. (2022). Dynamic characterization of a master–slave robotic manipulator using a hybrid grey wolf–whale optimization algorithm. Journal of Vibration and Control, 28(15-16), 1992-2003. - * **IGWO**: Kaveh, A. & Zakian, P.. (2018). Improved GWO algorithm for optimal design of truss structures. Engineering with Computers. 34. 10.1007/s00366-017-0567-1. - * **ChaoticGWO**: Kohli, M., & Arora, S. (2018). Chaotic grey wolf optimization algorithm for constrained optimization problems. Journal of computational design and engineering, 5(4), 458-472. - * **FuzzyGWO**: Rodríguez, Luis, Oscar Castillo, José Soria, Patricia Melin, Fevrier Valdez, Claudia I. Gonzalez, Gabriela E. Martinez, and Jesus Soto. "A fuzzy hierarchical operator in the grey wolf optimizer algorithm." Applied Soft Computing 57 (2017): 315-328. - * **IncrementalGWO**: Seyyedabbasi, A., & Kiani, F. (2021). I-GWO and Ex-GWO: improved algorithms of the Grey Wolf Optimizer to solve global optimization problems. Engineering with Computers, 37(1), 509-532. - * **ExGWO**: Seyyedabbasi, A., & Kiani, F. (2021). I-GWO and Ex-GWO: improved algorithms of the Grey Wolf Optimizer to solve global optimization problems. Engineering with Computers, 37(1), 509-532. - * **DS_GWO**: Jiang, Jianhua, Ziying Zhao, Yutong Liu, Weihua Li, and Huan Wang. "DSGWO: An improved grey wolf optimizer with diversity enhanced strategy based on group-stage competition and balance mechanisms." Knowledge-Based Systems 250 (2022): 109100. - * **IOBL_GWO**: Bansal, J. C., & Singh, S. (2021). A better exploration strategy in Grey Wolf Optimizer. Journal of Ambient Intelligence and Humanized Computing, 12(1), 1099-1118. - * **OGWO**: Yu, X., Xu, W., & Li, C. (2021). Opposition-based learning grey wolf optimizer for global optimization. Knowledge-Based Systems, 226, 107139. - * **ER_GWO**: Long, W., Cai, S., Jiao, J. et al. An efficient and robust grey wolf optimizer algorithm for large-scale numerical optimization. Soft Comput 24, 997–1026 (2020). - * **CG_GWO**: Li, K., Li, S., Huang, Z. et al. Grey Wolf Optimization algorithm based on Cauchy-Gaussian mutation and improved search strategy. Sci Rep 12, 18961 (2022). - -* **GOA - Grasshopper Optimisation Algorithm** - * **OriginalGOA**: Saremi, S., Mirjalili, S., & Lewis, A. (2017). Grasshopper optimisation algorithm: theory and application. Advances in Engineering Software, 105, 30-47. - -* **GCO - Germinal Center Optimization** - * **OriginalGCO**: Villaseñor, C., Arana-Daniel, N., Alanis, A. Y., López-Franco, C., & Hernandez-Vargas, E. A. (2018). Germinal center optimization algorithm. International Journal of Computational Intelligence Systems, 12(1), 13-27. - * **BaseGCO**: The developed version - -* **GSKA - Gaining Sharing Knowledge-based Algorithm** - * **OriginalGSKA**: Mohamed, A. W., Hadi, A. A., & Mohamed, A. K. (2019). Gaining-sharing knowledge based algorithm for solving optimization problems: a novel nature-inspired algorithm. International Journal of Machine Learning and Cybernetics, 1-29. - * **BaseGSKA**: Mohamed, A.W., Hadi, A.A., Mohamed, A.K. and Awad, N.H., 2020, July. Evaluating the performance of adaptive GainingSharing knowledge based algorithm on CEC 2020 benchmark problems. In 2020 IEEE Congress on Evolutionary Computation (CEC) (pp. 1-8). IEEE. - -* **GBO - Gradient-Based Optimizer** - * **OriginalGBO**: Ahmadianfar, I., Bozorg-Haddad, O., & Chu, X. (2020). Gradient-based optimizer: A new metaheuristic optimization algorithm. Information Sciences, 540, 131-159. - -### H - -* **HC - Hill Climbing** . - * **OriginalHC**: Talbi, E. G., & Muntean, T. (1993, January). Hill-climbing, simulated annealing and genetic algorithms: a comparative study and application to the mapping problem. In [1993] Proceedings of the Twenty-sixth Hawaii International Conference on System Sciences (Vol. 2, pp. 565-573). IEEE. - * **SwarmHC**: The developed version based on swarm-based idea (Original is single-solution based method) - -* **HS - Harmony Search** . - * **OriginalHS**: Geem, Z. W., Kim, J. H., & Loganathan, G. V. (2001). A new heuristic optimization algorithm:harmony search. simulation, 76(2), 60-68. - * **BaseHS**: The developed version - -* **HHO - Harris Hawks Optimization** . - * **OriginalHHO**: Heidari, A. A., Mirjalili, S., Faris, H., Aljarah, I., Mafarja, M., & Chen, H. (2019). Harris hawks optimization: Algorithm and applications. Future Generation Computer Systems, 97, 849-872. - -* **HGSO - Henry Gas Solubility Optimization** . - * **OriginalHGSO**: Hashim, F. A., Houssein, E. H., Mabrouk, M. S., Al-Atabany, W., & Mirjalili, S. (2019). Henry gas solubility optimization: A novel physics-based algorithm. Future Generation Computer Systems, 101, 646-667. - -* **HGS - Hunger Games Search** . - * **OriginalHGS**: Yang, Y., Chen, H., Heidari, A. A., & Gandomi, A. H. (2021). Hunger games search:Visions, conception, implementation, deep analysis, perspectives, and towards performance shifts. Expert Systems with Applications, 177, 114864. - -* **HHOA - Horse Herd Optimization Algorithm (not done)** . - * **BaseHHOA**: MiarNaeimi, F., Azizyan, G., & Rashki, M. (2021). Horse herd optimization algorithm: A nature-inspired algorithm for high-dimensional optimization problems. Knowledge-Based Systems, 213, 106711. - -* **HBA - Honey Badger Algorithm**: - * **OriginalHBA**: Hashim, F. A., Houssein, E. H., Hussain, K., Mabrouk, M. S., & Al-Atabany, W. (2022). Honey Badger Algorithm: New metaheuristic algorithm for solving optimization problems. Mathematics and Computers in Simulation, 192, 84-110. - - -### I - -* **IWO - Invasive Weed Optimization** . - * **OriginalIWO**: Mehrabian, A. R., & Lucas, C. (2006). A novel numerical optimization algorithm inspired from weed colonization. Ecological informatics, 1(4), 355-366. - -* **ICA - Imperialist Competitive Algorithm** - * **OriginalICA**: Atashpaz-Gargari, E., & Lucas, C. (2007, September). Imperialist competitive algorithm: an algorithm for optimization inspired by imperialistic competition. In 2007 IEEE congress on evolutionary computation (pp. 4661-4667). Ieee. - -* **IMODE - Improved Multi-operator Differential Evolution Algorithm**: - * **OriginalIMODE**: Sallam, K. M., Elsayed, S. M., Chakrabortty, R. K., & Ryan, M. J. (2020, July). Improved multi-operator differential evolution algorithm for solving unconstrained problems. In 2020 IEEE congress on evolutionary computation (CEC) (pp. 1-8). IEEE. - -* **INFO - weIghted meaN oF vectOrs**: - * **OriginalINFO**: Ahmadianfar, I., Heidari, A. A., Gandomi, A. H., Chu, X., & Chen, H. (2021). RUN beyond the metaphor: An efficient optimization algorithm based on Runge Kutta method. Expert Systems with Applications, 181, 115079. - -### J - -* **JA - Jaya Algorithm** - * **OriginalJA**: Rao, R. (2016). Jaya: A simple and new optimization algorithm for solving constrained and unconstrained optimization problems. International Journal of Industrial Engineering Computations, 7(1), 19-34. - * **BaseJA**: The developed version - * **LevyJA**: Iacca, G., dos Santos Junior, V. C., & de Melo, V. V. (2021). An improved Jaya optimization algorithm with Levy flight. Expert Systems with Applications, 165, 113902. - -### K - -### L - -* **LSHADEcnEpSin - Ensemble sinusoidal differential covariance matrix adaptation with Euclidean neighborhood** - * **OriginalLSHADEcnEpSin**: Awad, N. H., Ali, M. Z., & Suganthan, P. N. (2017, June). Ensemble sinusoidal differential covariance matrix adaptation with Euclidean neighborhood for solving CEC2017 benchmark problems. In 2017 IEEE congress on evolutionary computation (CEC) (pp. 372-379). IEEE. - -* **LCO - Life Choice-based Optimization** - * **OriginalLCO**: Khatri, A., Gaba, A., Rana, K. P. S., & Kumar, V. (2019). A novel life choice-based optimizer. Soft Computing, 1-21. - * **BaseLCO**: The developed version - * **ImprovedLCO**: The improved version using Gaussian distribution and Mutation Mechanism - - -### M - -* **MA - Memetic Algorithm** - * **OriginalMA**: Moscato, P. (1989). On evolution, search, optimization, genetic algorithms and martial arts: Towards memetic algorithms. Caltech concurrent computation program, C3P Report, 826, 1989. - -* **MFO - Moth Flame Optimization** - * **OriginalMFO**: Mirjalili, S. (2015). Moth-flame optimization algorithm: A novel nature-inspired heuristic paradigm. Knowledge-based systems, 89, 228-249. - * **BaseMFO**: The developed version - -* **MVO - Multi-Verse Optimizer** - * **OriginalMVO**: Mirjalili, S., Mirjalili, S. M., & Hatamlou, A. (2016). Multi-verse optimizer: a nature-inspired algorithm for global optimization. Neural Computing and Applications, 27(2), 495-513. - * **BaseMVO**: The developed version - -* **MSA - Moth Search Algorithm** - * **OriginalMSA**: Wang, G. G. (2018). Moth search algorithm: a bio-inspired metaheuristic algorithm for global optimization problems. Memetic Computing, 10(2), 151-164. - -* **MRFO - Manta Ray Foraging Optimization** - * **OriginalMRFO**: Zhao, W., Zhang, Z., & Wang, L. (2020). Manta ray foraging optimization: An effective bio-inspired optimizer for engineering applications. Engineering Applications of Artificial Intelligence, 87, 103300. - -* **MPA - Marine Predators Algorithm**: - * **OriginalMPA**: Faramarzi, A., Heidarinejad, M., Mirjalili, S., & Gandomi, A. H. (2020). Marine Predators Algorithm: A nature-inspired metaheuristic. Expert systems with applications, 152, 113377. - - -### N - - -* **NRO - Nuclear Reaction Optimization** - * **OriginalNRO**: Wei, Z., Huang, C., Wang, X., Han, T., & Li, Y. (2019). Nuclear Reaction Optimization: A novel and powerful physics-based algorithm for global optimization. IEEE Access. - -* **NMRA - Nake Mole-Rat Algorithm** - * **OriginalNMRA**: Salgotra, R., & Singh, U. (2019). The naked mole-rat algorithm. Neural Computing and Applications, 31(12), 8837-8857. - * **ImprovedNMRA**: Singh, P., Mittal, N., Singh, U. and Salgotra, R., 2021. Naked mole-rat algorithm with improved exploration and exploitation capabilities to determine 2D and 3D coordinates of sensor nodes in WSNs. Arabian Journal for Science and Engineering, 46(2), pp.1155-1178. - - -### O - -### P - -* **PSO - Particle Swarm Optimization** - * **OriginalPSO**: Eberhart, R., & Kennedy, J. (1995, October). A new optimizer using particle swarm theory. In MHS'95. Proceedings of the Sixth International Symposium on Micro Machine and Human Science (pp. 39-43). Ieee. - * **PPSO**: Ghasemi, M., Akbari, E., Rahimnejad, A., Razavi, S. E., Ghavidel, S., & Li, L. (2019). Phasor particle swarm optimization: a simple and efficient variant of PSO. Soft Computing, 23(19), 9701-9718. - * **HPSO_TVAC**: Ghasemi, M., Aghaei, J., & Hadipour, M. (2017). New cls-organising hierarchical PSO with jumping time-varying acceleration coefficients. Electronics Letters, 53(20), 1360-1362. - * **C_PSO**: Liu, B., Wang, L., Jin, Y. H., Tang, F., & Huang, D. X. (2005). Improved particle swarm optimization combined with chaos. Chaos, Solitons & Fractals, 25(5), 1261-1271. - * **CL_PSO**: Liang, J. J., Qin, A. K., Suganthan, P. N., & Baskar, S. (2006). Comprehensive learning particle swarm optimizer for global optimization of multimodal functions. IEEE transactions on evolutionary computation, 10(3), 281-295. - -* **PFA - Pathfinder Algorithm** - * **OriginalPFA**: Yapici, H., & Cetinkaya, N. (2019). A new meta-heuristic optimizer: Pathfinder algorithm. Applied Soft Computing, 78, 545-568. - -* **PSS - Pareto-like Sequential Sampling** - * **OriginalPSS**: Shaqfa, M., & Beyer, K. (2021). Pareto-like sequential sampling heuristic for global optimisation. Soft Computing, 25(14), 9077-9096. - - -### Q - -* **QSA - Queuing Search Algorithm** - * **OriginalQSA**: Zhang, J., Xiao, M., Gao, L., & Pan, Q. (2018). Queuing search algorithm: A novel metaheuristic algorithm for solving engineering optimization problems. Applied Mathematical Modelling, 63, 464-490. - * **BaseQSA**: The developed version - * **OppoQSA**: Zheng, X. and Nguyen, H., 2022. A novel artificial intelligent model for predicting water treatment efficiency of various biochar systems based on artificial neural network and queuing search algorithm. Chemosphere, 287, p.132251. - * **LevyQSA**: Abderazek, H., Hamza, F., Yildiz, A.R., Gao, L. and Sait, S.M., 2021. A comparative analysis of the queuing search algorithm, the sine-cosine algorithm, the ant lion algorithm to determine the optimal weight design problem of a spur gear drive system. Materials Testing, 63(5), pp.442-447. - * **ImprovedQSA**: Nguyen, B.M., Hoang, B., Nguyen, T. and Nguyen, G., 2021. nQSV-Net: a novel queuing search variant for global space search and workload modeling. Journal of Ambient Intelligence and Humanized Computing, 12(1), pp.27-46. - -### R - -* **RUN - RUNge Kutta optimizer**: - * **OriginalRUN**: Ahmadianfar, I., Heidari, A. A., Gandomi, A. H., Chu, X., & Chen, H. (2021). RUN beyond the metaphor: An efficient optimization algorithm based on Runge Kutta method. Expert Systems with Applications, 181, 115079. - -### S - -* **SA - Simulated Annealling** - **OriginalSA**: Kirkpatrick, S., Gelatt Jr, C. D., & Vecchi, M. P. (1983). Optimization by simulated annealing. science, 220(4598), 671-680. - **GaussianSA**: Van Laarhoven, P. J., Aarts, E. H., van Laarhoven, P. J., & Aarts, E. H. (1987). Simulated annealing (pp. 7-15). Springer Netherlands. - **SwarmSA**: My developed version - -* **SSpiderO - Social Spider Optimization** - * **OriginalSSpiderO**: Cuevas, E., Cienfuegos, M., ZaldíVar, D., & Pérez-Cisneros, M. (2013). A swarm optimization algorithm inspired in the behavior of the social-spider. Expert Systems with Applications, 40(16), 6374-6384. - -* **SMO - Spider Monkey Optimization** - * **DevSMO**: Bansal, J. C., Sharma, H., Jadon, S. S., & Clerc, M. (2014). Spider monkey optimization algorithm for numerical optimization. Memetic computing, 6(1), 31-47. - -* **SOS - Symbiotic Organisms Search**: - * **OriginalSOS**: Cheng, M. Y., & Prayogo, D. (2014). Symbiotic organisms search: a new metaheuristic optimization algorithm. Computers & Structures, 139, 98-112. - -* **SSpiderA - Social Spider Algorithm** - * **OriginalSSpiderA**: James, J. Q., & Li, V. O. (2015). A social spider algorithm for global optimization. Applied Soft Computing, 30, 614-627. - -* **SCA - Sine Cosine Algorithm** - * **OriginalSCA**: Mirjalili, S. (2016). SCA: a sine cosine algorithm for solving optimization problems. Knowledge-Based Systems, 96, 120-133. - * **BaseSCA**: Attia, A.F., El Sehiemy, R.A. and Hasanien, H.M., 2018. Optimal power flow solution in power systems using a novel Sine-Cosine algorithm. International Journal of Electrical Power & Energy Systems, 99, pp.331-343. - -* **SRSR - Swarm Robotics Search And Rescue** - * **OriginalSRSR**: Bakhshipour, M., Ghadi, M. J., & Namdari, F. (2017). Swarm robotics search & rescue: A novel artificial intelligence-inspired optimization approach. Applied Soft Computing, 57, 708-726. - -* **SBO - Satin Bowerbird Optimizer** - * **OriginalSBO**: Moosavi, S. H. S., & Bardsiri, V. K. (2017). Satin bowerbird optimizer: a new optimization algorithm to optimize ANFIS for software development effort estimation. Engineering Applications of Artificial Intelligence, 60, 1-15. - * **BaseSBO**: The developed version - -* **SHO - Spotted Hyena Optimizer** - * **OriginalSHO**: Dhiman, G., & Kumar, V. (2017). Spotted hyena optimizer: a novel bio-inspired based metaheuristic technique for engineering applications. Advances in Engineering Software, 114, 48-70. - -* **SSO - Salp Swarm Optimization** - * **OriginalSSO**: Mirjalili, S., Gandomi, A. H., Mirjalili, S. Z., Saremi, S., Faris, H., & Mirjalili, S. M. (2017). Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software, 114, 163-191. - -* **SFO - Sailfish Optimizer** - * **OriginalSFO**: Shadravan, S., Naji, H. R., & Bardsiri, V. K. (2019). The Sailfish Optimizer: A novel nature-inspired metaheuristic algorithm for solving constrained engineering optimization problems. Engineering Applications of Artificial Intelligence, 80, 20-34. - * **ImprovedSFO**: Li, L.L., Shen, Q., Tseng, M.L. and Luo, S., 2021. Power system hybrid dynamic economic emission dispatch with wind energy based on improved sailfish algorithm. Journal of Cleaner Production, 316, p.128318. - -* **SARO - Search And Rescue Optimization** - * **OriginalSARO**: Shabani, A., Asgarian, B., Gharebaghi, S. A., Salido, M. A., & Giret, A. (2019). A New Optimization Algorithm Based on Search and Rescue Operations. Mathematical Problems in Engineering, 2019. - * **BaseSARO**: The developed version using Levy-flight - -* **SSDO - Social Ski-Driver Optimization** - * **OriginalSSDO**: Tharwat, A., & Gabel, T. (2019). Parameters optimization of support vector machines for imbalanced data using social ski driver algorithm. Neural Computing and Applications, 1-14. - -* **SLO - Sea Lion Optimization** - * **OriginalSLO**: Masadeh, R., Mahafzah, B. A., & Sharieh, A. (2019). Sea Lion Optimization Algorithm. Sea, 10(5). - * **ImprovedSLO**: The developed version - * **ModifiedSLO**: Masadeh, R., Alsharman, N., Sharieh, A., Mahafzah, B.A. and Abdulrahman, A., 2021. Task scheduling on cloud computing based on sea lion optimization algorithm. International Journal of Web Information Systems. - -* **Seagull Optimization Algorithm** - * **OriginalSOA**: Dhiman, G., & Kumar, V. (2019). Seagull optimization algorithm: Theory and its applications for large-scale industrial engineering problems. Knowledge-based systems, 165, 169-196. - * **DevSOA**: The developed version - -* **Squirrel Search Algorithm** - * **OriginalSquirrelSA**: Jain, M., Singh, V., & Rani, A. (2019). A novel nature-inspired algorithm for optimization: Squirrel search algorithm. Swarm and evolutionary computation, 44, 148-175. - -* **SMA - Slime Mould Algorithm** - * **OriginalSMA**: Li, S., Chen, H., Wang, M., Heidari, A. A., & Mirjalili, S. (2020). Slime mould algorithm: A new method for stochastic optimization. Future Generation Computer Systems. - * **BaseSMA**: The developed version - -* **SSA - Sparrow Search Algorithm** - * **OriginalSSA**: Jiankai Xue & Bo Shen (2020) A novel swarm intelligence optimization approach: sparrow search algorithm, Systems Science & Control Engineering, 8:1, 22-34, DOI: 10.1080/21642583.2019.1708830 - * **BaseSSA**: The developed version - -* **SPBO - Student Psychology Based Optimization** - * **OriginalSPBO**: Das, B., Mukherjee, V., & Das, D. (2020). Student psychology based optimization algorithm: A new population based optimization algorithm for solving optimization problems. Advances in Engineering software, 146, 102804. - * **DevSPBO**: The developed version - -* **SCSO - Sand Cat Swarm Optimization** - * **OriginalSCSO**: Seyyedabbasi, A., & Kiani, F. (2022). Sand Cat swarm optimization: a nature-inspired algorithm to solve global optimization problems. Engineering with Computers, 1-25. - -### T - -* **TLO - Teaching Learning Optimization** - * **OriginalTLO**: Rao, R. V., Savsani, V. J., & Vakharia, D. P. (2011). Teaching–learning-based optimization: a novel method for constrained mechanical design optimization problems. Computer-Aided Design, 43(3), 303-315. - * **BaseTLO**: Rao, R., & Patel, V. (2012). An elitist teaching-learning-based optimization algorithm for solving complex constrained optimization problems. International Journal of Industrial Engineering Computations, 3(4), 535-560. - * **ImprovedTLO**: Rao, R. V., & Patel, V. (2013). An improved teaching-learning-based optimization algorithm for solving unconstrained optimization problems. Scientia Iranica, 20(3), 710-720. - -* **TWO - Tug of War Optimization** - * **OriginalTWO**: Kaveh, A., & Zolghadr, A. (2016). A novel meta-heuristic algorithm: tug of war optimization. Iran University of Science & Technology, 6(4), 469-492. - * **OppoTWO**: Kaveh, A., Almasi, P. and Khodagholi, A., 2022. Optimum Design of Castellated Beams Using Four Recently Developed Meta-heuristic Algorithms. Iranian Journal of Science and Technology, Transactions of Civil Engineering, pp.1-13. - * **LevyTWO**: The developed version using Levy-flight - * **ImprovedTWO**: Nguyen, T., Hoang, B., Nguyen, G., & Nguyen, B. M. (2020). A new workload prediction model using extreme learning machine and enhanced tug of war optimization. Procedia Computer Science, 170, 362-369. - -* **TSA - Tunicate Swarm Algorithm** - * **OriginalTSA**: Kaur, S., Awasthi, L. K., Sangal, A. L., & Dhiman, G. (2020). Tunicate Swarm Algorithm: A new bio-inspired based metaheuristic paradigm for global optimization. Engineering Applications of Artificial Intelligence, 90, 103541. - -* **TSO - Tuna Swarm Optimization** - * **OriginalTSO**: Xie, L., Han, T., Zhou, H., Zhang, Z. R., Han, B., & Tang, A. (2021). Tuna swarm optimization: a novel swarm-based metaheuristic algorithm for global optimization. Computational intelligence and Neuroscience, 2021. - - -### U - -### V - -* **VCS - Virus Colony Search** - * **OriginalVCS**: Li, M. D., Zhao, H., Weng, X. W., & Han, T. (2016). A novel nature-inspired algorithm for optimization: Virus colony search. Advances in Engineering Software, 92, 65-88. - * **BaseVCS**: The developed version - -### W - -* **WCA - Water Cycle Algorithm** - * **OriginalWCA**: Eskandar, H., Sadollah, A., Bahreininejad, A., & Hamdi, M. (2012). Water cycle algorithm–A novel metaheuristic optimization method for solving constrained engineering optimization problems. Computers & Structures, 110, 151-166. - -* **WOA - Whale Optimization Algorithm** - * **OriginalWOA**: Mirjalili, S., & Lewis, A. (2016). The whale optimization algorithm. Advances in engineering software, 95, 51-67. - * **HI_WOA**: Tang, C., Sun, W., Wu, W., & Xue, M. (2019, July). A hybrid improved whale optimization algorithm. In 2019 IEEE 15th International Conference on Control and Automation (ICCA) (pp. 362-367). IEEE. - -* **WHO - Wildebeest Herd Optimization** - * **OriginalWHO**: Amali, D., & Dinakaran, M. (2019). Wildebeest herd optimization: A new global optimization algorithm inspired by wildebeest herding behaviour. Journal of Intelligent & Fuzzy Systems, (Preprint), 1-14. - -* **WDO - Wind Driven Optimization** - * **OriginalWDO**: Bayraktar, Z., Komurcu, M., Bossard, J.A. and Werner, D.H., 2013. The wind driven optimization technique and its application in electromagnetics. IEEE transactions on antennas and propagation, 61(5), pp.2745-2757. - - -### X - -### Y - -### Z - -
- - - - -

List of papers used MEALPY

- -- Min, J., Oh, M., Kim, W., Seo, H., & Paek, J. (2022, October). Evaluation of Metaheuristic Algorithms for TAS Scheduling in Time-Sensitive Networking. In 2022 13th International Conference on Information and Communication Technology Convergence (ICTC) (pp. 809-812). IEEE. -- Khozeimeh, F., Sharifrazi, D., Izadi, N. H., Joloudari, J. H., Shoeibi, A., Alizadehsani, R., ... & Islam, S. M. S. (2021). Combining a convolutional neural network with autoencoders to predict the survival chance of COVID-19 patients. Scientific Reports, 11(1), 15343. -- Rajesh, K., Jain, E., & Kotecha, P. (2022). A Multi-Objective approach to the Electric Vehicle Routing Problem. arXiv preprint arXiv:2208.12440. -- Sánchez, A. J. H., & Upegui, F. R. (2022). Una herramienta para el diseño de redes MSMN de banda ancha en líneas de transmisión basada en algoritmos heurísticos de optimización comparados. Revista Ingeniería UC, 29(2), 106-123. -- Khanmohammadi, M., Armaghani, D. J., & Sabri Sabri, M. M. (2022). Prediction and Optimization of Pile Bearing Capacity Considering Effects of Time. Mathematics, 10(19), 3563. -- Kudela, J. (2023). The Evolutionary Computation Methods No One Should Use. arXiv preprint arXiv:2301.01984. -- Vieira, M., Faia, R., Pinto, T., & Vale, Z. (2022, September). Schedule Peer-to-Peer Transactions of an Energy Community Using Particle Swarm. In 2022 18th International Conference on the European Energy Market (EEM) (pp. 1-6). IEEE. -- Bui, X. N., Nguyen, H., Le, Q. T., & Le, T. N. Forecasting PM. MINING SCIENCE ANDTECHNOLOGY (Russia), 111. -- Bui, X. N., Nguyen, H., Le, Q. T., & Le, T. N. (2022). Forecasting PM 2.5 emissions in open-pit minesusing a functional link neural network optimized by various optimization algorithms. Gornye nauki i tekhnologii= Mining Science and Technology (Russia), 7(2), 111-125. -- Doğan, E., & Yörükeren, N. (2022). Enhancement of Transmission System Security with Archimedes Optimization Algorithm. -- Ayub, N., Aurangzeb, K., Awais, M., & Ali, U. (2020, November). Electricity theft detection using CNN-GRU and manta ray foraging optimization algorithm. In 2020 IEEE 23Rd international multitopic conference (INMIC) (pp. 1-6). IEEE. -- Pintilie, L., Nechita, M. T., Suditu, G. D., Dafinescu, V., & Drăgoi, E. N. (2022). Photo-decolorization of Eriochrome Black T: process optimization with Differential Evolution algorithm. In PASEW-22, MESSH-22 & CABES-22 April 19–21, 2022 Paris (France). Eminent Association of Pioneers. -- LaTorre, A., Molina, D., Osaba, E., Poyatos, J., Del Ser, J., & Herrera, F. (2021). A prescription of methodological guidelines for comparing bio-inspired optimization algorithms. Swarm and Evolutionary Computation, 67, 100973. -- Gottam, S., Nanda, S. J., & Maddila, R. K. (2021, December). A CNN-LSTM Model Trained with Grey Wolf Optimizer for Prediction of Household Power Consumption. In 2021 IEEE International Symposium on Smart Electronic Systems (iSES)(Formerly iNiS) (pp. 355-360). IEEE. -- Darius, P. S., Devadason, J., & Solomon, D. G. (2022, December). Prospects of Ant Colony Optimization (ACO) in Various Domains. In 2022 4th International Conference on Circuits, Control, Communication and Computing (I4C) (pp. 79-84). IEEE. -- Ayub, N., Irfan, M., Awais, M., Ali, U., Ali, T., Hamdi, M., ... & Muhammad, F. (2020). Big data analytics for short and medium-term electricity load forecasting using an AI techniques ensembler. Energies, 13(19), 5193. -- Biundini, I. Z., Melo, A. G., Coelho, F. O., Honório, L. M., Marcato, A. L., & Pinto, M. F. (2022). Experimentation and Simulation with Autonomous Coverage Path Planning for UAVs. Journal of Intelligent & Robotic Systems, 105(2), 46. -- Yousaf, I., Anwar, F., Imtiaz, S., Almadhor, A. S., Ishmanov, F., & Kim, S. W. (2022). An Optimized Hyperparameter of Convolutional Neural Network Algorithm for Bug Severity Prediction in Alzheimer’s-Based IoT System. Computational Intelligence and Neuroscience, 2022. -- Xu, L., Yan, W., & Ji, J. (2023). The research of a novel WOG-YOLO algorithm for autonomous driving object detection. Scientific reports, 13(1), 3699. -- Costache, R. D., Arabameri, A., Islam, A. R. M. T., Abba, S. I., Pandey, M., Ajin, R. S., & Pham, B. T. (2022). Flood susceptibility computation using state-of-the-art machine learning and optimization algorithms. -- Del Ser, J., Osaba, E., Martinez, A. D., Bilbao, M. N., Poyatos, J., Molina, D., & Herrera, F. (2021, December). More is not always better: insights from a massive comparison of meta-heuristic algorithms over real-parameter optimization problems. In 2021 IEEE Symposium Series on Computational Intelligence (SSCI) (pp. 1-7). IEEE. -- Rustam, F., Aslam, N., De La Torre Díez, I., Khan, Y. D., Mazón, J. L. V., Rodríguez, C. L., & Ashraf, I. (2022, November). White Blood Cell Classification Using Texture and RGB Features of Oversampled Microscopic Images. In Healthcare (Vol. 10, No. 11, p. 2230). MDPI. -- Neupane, D., Kafle, S., Gurung, S., Neupane, S., & Bhattarai, N. (2021). Optimal sizing and financial analysis of a stand-alone SPV-micro-hydropower hybrid system considering generation uncertainty. International Journal of Low-Carbon Technologies, 16(4), 1479-1491. -- Liang, R., Le-Hung, T., & Nguyen-Thoi, T. (2022). Energy consumption prediction of air-conditioning systems in eco-buildings using hunger games search optimization-based artificial neural network model. Journal of Building Engineering, 59, 105087. -- He, Z., Nguyen, H., Vu, T. H., Zhou, J., Asteris, P. G., & Mammou, A. (2022). Novel integrated approaches for predicting the compressibility of clay using cascade forward neural networks optimized by swarm-and evolution-based algorithms. Acta Geotechnica, 1-16. -- Xu, L., Yan, W., & Ji, J. (2022). The research of a novel WOG-YOLO algorithm forautonomous driving object detection. -- Nasir Ayub, M. I., Awais, M., Ali, U., Ali, T., Hamdi, M., Alghamdi, A., & Muhammad, F. Big Data Analytics for Short and Medium Term Electricity Load Forecasting using AI Techniques Ensembler. -- Xie, C., Nguyen, H., Choi, Y., & Armaghani, D. J. (2022). Optimized functional linked neural network for predicting diaphragm wall deflection induced by braced excavations in clays. Geoscience Frontiers, 13(2), 101313. -- Hakemi, S., Houshmand, M., & Hosseini, S. A. (2022). A Dynamic Quantum-Inspired Genetic Algorithm with Lengthening Chromosome Size. -- Kashifi, M. T. City-Wide Crash Risk Prediction and Interpretation Using Deep Learning Model with Multi-Source Big Data. Available at SSRN 4329686. -- Nguyen, H., & Hoang, N. D. (2022). Computer vision-based classification of concrete spall severity using metaheuristic-optimized Extreme Gradient Boosting Machine and Deep Convolutional Neural Network. Automation in Construction, 140, 104371. -- Zheng, J., Lu, Z., Wu, K., Ning, G. H., & Li, D. (2020). Coinage-metal-based cyclic trinuclear complexes with metal–metal interactions: Theories to experiments and structures to functions. Chemical Reviews, 120(17), 9675-9742. -- Van Thieu, N., Barma, S. D., Van Lam, T., Kisi, O., & Mahesha, A. (2023). Groundwater level modeling using Augmented Artificial Ecosystem Optimization. Journal of Hydrology, 617, 129034. -- Mo, Z., Zhang, Z., Miao, Q., & Tsui, K. L. (2022). Intelligent Informative Frequency Band Searching Assisted by a Dynamic Bandit Tree Method for Machine Fault Diagnosis. IEEE/ASME Transactions on Mechatronics. -- Dangi, D., Chandel, S. T., Dixit, D. K., Sharma, S., & Bhagat, A. (2023). An Efficient Model for Sentiment Analysis using Artificial Rabbits Optimized Vector Functional Link Network. Expert Systems with Applications, 119849. -- Dey, S., Roychoudhury, R., Malakar, S., & Sarkar, R. (2022). An optimized fuzzy ensemble of convolutional neural networks for detecting tuberculosis from Chest X-ray images. Applied Soft Computing, 114, 108094. -- Mousavirad, S. J., & Alexandre, L. A. (2022). Population-based JPEG Image Compression: Problem Re-Formulation. arXiv preprint arXiv:2212.06313. -- Tsui, K. L. Intelligent Informative Frequency Band Searching Assisted by A Dynamic Bandit Tree Method for Machine Fault Diagnosis. -- Neupane, D. (2020). Optimal Sizing and Performance Analysis of Solar PV-Micro hydropower Hybrid System in the Context of Rural Area of Nepal (Doctoral dissertation, Pulchowk Campus). -- LaTorre, A., Molina, D., Osaba, E., Poyatos, J., Del Ser, J., & Herrera, F. Swarm and Evolutionary Computation. -- Vieira, M. A. (2022). Otimização dos custos operacionais de uma comunidade energética considerando transações locais em “peer-to-peer” (Doctoral dissertation). -- Toğaçar, M. (2022). Using DarkNet models and metaheuristic optimization methods together to detect weeds growing along with seedlings. Ecological Informatics, 68, 101519. -- Toğaçar, M. (2021). Detection of segmented uterine cancer images by Hotspot Detection method using deep learning models, Pigeon-Inspired Optimization, types-based dominant activation selection approaches. Computers in Biology and Medicine, 136, 104659. -- Khan, N. A Short Term Electricity Load and Price Forecasting Model Based on BAT Algorithm in Logistic Regression and CNN-GRU with WOA. -- Yelisetti, S., Saini, V. K., Kumar, R., & Lamba, R. (2022, May). Energy Consumption Cost Benefits through Smart Home Energy Management in Residential Buildings: An Indian Case Study. In 2022 IEEE IAS Global Conference on Emerging Technologies (GlobConET) (pp. 930-935). IEEE. -- Nguyen, H., Cao, M. T., Tran, X. L., Tran, T. H., & Hoang, N. D. (2022). A novel whale optimization algorithm optimized XGBoost regression for estimating bearing capacity of concrete piles. Neural Computing and Applications, 1-28. -- Hirsching, C., de Jongh, S., Eser, D., Suriyah, M., & Leibfried, T. (2022). Meta-heuristic optimization of control structure and design for MMC-HVdc applications. Electric Power Systems Research, 213, 108371. -- Amelin, V., Gatiyatullin, E., Romanov, N., Samarkhanov, R., Vasilyev, R., & Yanovich, Y. (2022). Black-Box for Blockchain Parameters Adjustment. IEEE Access, 10, 101795-101802. -- Ngo, T. Q., Nguyen, L. Q., & Tran, V. Q. (2022). Novel hybrid machine learning models including support vector machine with meta-heuristic algorithms in predicting unconfined compressive strength of organic soils stabilised with cement and lime. International Journal of Pavement Engineering, 1-18. -- Zhu, Y., & Iiduka, H. (2021). Unified Algorithm Framework for Nonconvex Stochastic Optimization in Deep Neural Networks. IEEE Access, 9, 143807-143823. -- Hakemi, S., Houshmand, M., KheirKhah, E., & Hosseini, S. A. (2022). A review of recent advances in quantum-inspired metaheuristics. Evolutionary Intelligence, 1-16. -- Das, A., Das, S. R., Panda, J. P., Dey, A., Gajrani, K. K., Somani, N., & Gupta, N. (2022). Machine learning based modelling and optimization in hard turning of AISI D6 steel with newly developed AlTiSiN coated carbide tool. arXiv preprint arXiv:2202.00596. -- Yelisetti, S., Saini, V. K., Kumar, R., Lamba, R., & Saxena, A. (2022). Optimal energy management system for residential buildings considering the time of use price with swarm intelligence algorithms. Journal of Building Engineering, 59, 105062. -- Valdés, G. T. (2022). Algoritmo para la detección de vehículos y peatones combinando CNN´ sy técnicas de búsqueda. -- Sallam, N. M., Saleh, A. I., Ali, H. A., & Abdelsalam, M. M. (2023). An efficient EGWO algorithm as feature selection for B-ALL diagnoses and its subtypes classification using peripheral blood smear images. Alexandria Engineering Journal, 68, 39-66. - -
- --- -Developed by: [Thieu](mailto:nguyenthieu2102@gmail.com?Subject=MEALPY_QUESTIONS) @ 2022 \ No newline at end of file +* Maintained by: [LTSIM](mailto:tsim@cucei.udg.mx) @ 2026 +* Developed by: [Thieu](mailto:nguyenthieu2102@gmail.com?Subject=Opfunu_QUESTIONS) @ 2023 \ No newline at end of file diff --git a/REFERENCES.md b/REFERENCES.md new file mode 100644 index 00000000..fef51a0d --- /dev/null +++ b/REFERENCES.md @@ -0,0 +1,475 @@ +## References + +### A + +* **ABC - Artificial Bee Colony** + * **OriginalABC**: Karaboga, D. (2005). An idea based on honey bee swarm for numerical optimization (Vol. 200, pp. 1-10). Technical report-tr06, Erciyes university, engineering faculty, computer engineering department. + +* **ACOR - Ant Colony Optimization**. + * **OriginalACOR**: Socha, K., & Dorigo, M. (2008). Ant colony optimization for continuous domains. European journal of operational research, 185(3), 1155-1173. + +* **ALO - Ant Lion Optimizer** + * **OriginalALO**: Mirjalili S (2015). “The Ant Lion Optimizer.” Advances in Engineering Software, 83, 80-98. doi: [10.1016/j.advengsoft.2015.01.010](https://doi.org/10.1016/j.advengsoft.2015.01.010) + * **BaseALO**: The developed version + +* **AEO - Artificial Ecosystem-based Optimization** + * **OriginalAEO**: Zhao, W., Wang, L., & Zhang, Z. (2019). Artificial ecosystem-based optimization: a novel nature-inspired meta-heuristic algorithm. Neural Computing and Applications, 1-43. + * **AugmentedAEO**: Van Thieu, N., Barma, S. D., Van Lam, T., Kisi, O., & Mahesha, A. (2022). Groundwater level modeling using Augmented Artificial Ecosystem Optimization. Journal of Hydrology, 129034. + * **ImprovedAEO**: Rizk-Allah, R. M., & El-Fergany, A. A. (2020). Artificial ecosystem optimizer for parameters identification of proton exchange membrane fuel cells model. International Journal of Hydrogen Energy. + * **EnhancedAEO**: Eid, A., Kamel, S., Korashy, A., & Khurshaid, T. (2020). An Enhanced Artificial Ecosystem-Based Optimization for Optimal Allocation of Multiple Distributed Generations. IEEE Access, 8, 178493-178513. + * **ModifiedAEO**: Menesy, A. S., Sultan, H. M., Korashy, A., Banakhr, F. A., Ashmawy, M. G., & Kamel, S. (2020). Effective parameter extraction of different polymer electrolyte membrane fuel cell stack models using a modified artificial ecosystem optimization algorithm. IEEE Access, 8, 31892-31909. + +* **ASO - Atom Search Optimization** + * **OriginalASO**: Zhao, W., Wang, L., & Zhang, Z. (2019). Atom search optimization and its application to solve a hydrogeologic parameter estimation problem. Knowledge-Based Systems, 163, 283-304. + +* **ArchOA - Archimedes Optimization Algorithm** + * **OriginalArchOA**: Hashim, F. A., Hussain, K., Houssein, E. H., Mabrouk, M. S., & Al-Atabany, W. (2021). Archimedes optimization algorithm: a new metaheuristic algorithm for solving optimization problems. Applied Intelligence, 51(3), 1531-1551. + +* **AOA - Arithmetic Optimization Algorithm** + * **OriginalAOA**: Abualigah, L., Diabat, A., Mirjalili, S., Abd Elaziz, M., & Gandomi, A. H. (2021). The arithmetic optimization algorithm. Computer methods in applied mechanics and engineering, 376, 113609. + +* **AO - Aquila Optimizer** + * **OriginalAO**: Abualigah, L., Yousri, D., Abd Elaziz, M., Ewees, A. A., Al-qaness, M. A., & Gandomi, A. H. (2021). Aquila Optimizer: A novel meta-heuristic optimization Algorithm. Computers & Industrial Engineering, 157, 107250. + * **AAO**: Al-Selwi, S. M., Hassan, M. F., Abdulkadir, S. J., Ragab, M. G., Alqushaibi, A., & Sumiea, E. H. (2024). Smart grid stability prediction using adaptive aquila optimizer and ensemble stacked bilstm. Results in Engineering, 24, 103261. + +* **AVOA - African Vultures Optimization Algorithm** + * **OriginalAVOA**: Abdollahzadeh, B., Gharehchopogh, F. S., & Mirjalili, S. (2021). African vultures optimization algorithm: A new nature-inspired metaheuristic algorithm for global optimization problems. Computers & Industrial Engineering, 158, 107408. + +* **AGTO - Artificial Gorilla Troops Optimization** + * **OriginalAGTO**: Abdollahzadeh, B., Soleimanian Gharehchopogh, F., & Mirjalili, S. (2021). Artificial gorilla troops optimizer: a new nature‐inspired metaheuristic algorithm for global optimization problems. International Journal of Intelligent Systems, 36(10), 5887-5958. + +* **ARO - Artificial Rabbits Optimization**: + * **OriginalARO**: Wang, L., Cao, Q., Zhang, Z., Mirjalili, S., & Zhao, W. (2022). Artificial rabbits optimization: A new bio-inspired meta-heuristic algorithm for solving engineering optimization problems. Engineering Applications of Artificial Intelligence, 114, 105082. + +* **AFT - Ali baba and the Forty Thieves**: + * **OriginalAFT**: Braik, M., Ryalat, M. H., & Al-Zoubi, H. (2022). A novel meta-heuristic algorithm for solving numerical optimization problems: Ali Baba and the forty thieves. Neural Computing and Applications, 34(1), 409-455. + + +### B + + +* **BFO - Bacterial Foraging Optimization** + * **OriginalBFO**: Passino, K. M. (2002). Biomimicry of bacterial foraging for distributed optimization and control. IEEE control systems magazine, 22(3), 52-67. + * **ABFO**: Nguyen, T., Nguyen, B. M., & Nguyen, G. (2019, April). Building resource auto-scaler with functional-link neural network and adaptive bacterial foraging optimization. In International Conference on Theory and Applications of Models of Computation (pp. 501-517). Springer, Cham. + +* **BeesA - Bees Algorithm** + * **OriginalBeesA**: Pham, D. T., Ghanbarzadeh, A., Koc, E., Otri, S., Rahim, S., & Zaidi, M. (2005). The bees algorithm. Technical Note, Manufacturing Engineering Centre, Cardiff University, UK. + * **ProbBeesA**: The probabilitic version of: Pham, D. T., Ghanbarzadeh, A., Koç, E., Otri, S., Rahim, S., & Zaidi, M. (2006). The bees algorithm—a novel tool for complex optimisation problems. In Intelligent production machines and systems (pp. 454-459). Elsevier Science Ltd. + +* **BBO - Biogeography-Based Optimization** + * **OriginalBBO**: Simon, D. (2008). Biogeography-based optimization. IEEE transactions on evolutionary computation, 12(6), 702-713. + * **BaseBBO**: The developed version + +* **BA - Bat Algorithm** + * **OriginalBA**: Yang, X. S. (2010). A new metaheuristic bat-inspired algorithm. In Nature inspired cooperative strategies for optimization (NICSO 2010) (pp. 65-74). Springer, Berlin, Heidelberg. + * **AdaptiveBA**: Wang, X., Wang, W. and Wang, Y., 2013, July. An adaptive bat algorithm. In International Conference on Intelligent Computing(pp. 216-223). Springer, Berlin, Heidelberg. + * **ModifiedBA**: Dong, H., Li, T., Ding, R. and Sun, J., 2018. A novel hybrid genetic algorithm with granular information for feature selection and optimization. Applied Soft Computing, 65, pp.33-46. + +* **BSO - Brain Storm Optimization** + * **OriginalBSO**: . Shi, Y. (2011, June). Brain storm optimization algorithm. In International conference in swarm intelligence (pp. 303-309). Springer, Berlin, Heidelberg. + * **ImprovedBSO**: El-Abd, M., 2017. Global-best brain storm optimization algorithm. Swarm and evolutionary computation, 37, pp.27-44. + +* **BSA - Bird Swarm Algorithm** + * **OriginalBSA**: Meng, X. B., Gao, X. Z., Lu, L., Liu, Y., & Zhang, H. (2016). A new bio-inspired optimisation algorithm:Bird Swarm Algorithm. Journal of Experimental & Theoretical Artificial Intelligence, 28(4), 673-687. + +* **BMO - Barnacles Mating Optimizer**: + * **OriginalBMO**: Sulaiman, M. H., Mustaffa, Z., Saari, M. M., Daniyal, H., Daud, M. R., Razali, S., & Mohamed, A. I. (2018, June). Barnacles mating optimizer: a bio-inspired algorithm for solving optimization problems. In 2018 19th IEEE/ACIS International Conference on Software Engineering, Artificial Intelligence, Networking and Parallel/Distributed Computing (SNPD) (pp. 265-270). IEEE. + +* **BES - Bald Eagle Search** + * **OriginalBES**: Alsattar, H. A., Zaidan, A. A., & Zaidan, B. B. (2019). Novel meta-heuristic bald eagle search optimisation algorithm. Artificial Intelligence Review, 1-28. + +* **BRO - Battle Royale Optimization** + * **OriginalBRO**: Rahkar Farshi, T. (2020). Battle royale optimization algorithm. Neural Computing and Applications, 1-19. + * **BaseBRO**: The developed version + +### C + +* **CA - Culture Algorithm** + * **OriginalCA**: Reynolds, R.G., 1994, February. An introduction to cultural algorithms. In Proceedings of the third annual conference on evolutionary programming (Vol. 24, pp. 131-139). River Edge, NJ: World Scientific. + +* **CEM - Cross Entropy Method** + * **OriginalCEM**: Rubinstein, R. (1999). The cross-entropy method for combinatorial and continuous optimization. Methodology and computing in applied probability, 1(2), 127-190. + +* **CSO - Cat Swarm Optimization** + * **OriginalCSO**: Chu, S. C., Tsai, P. W., & Pan, J. S. (2006, August). Cat swarm optimization. In Pacific Rim international conference on artificial intelligence (pp. 854-858). Springer, Berlin, Heidelberg. + +* **CSA - Cuckoo Search Algorithm** + * **OriginalCSA**: Yang, X. S., & Deb, S. (2009, December). Cuckoo search via Lévy flights. In 2009 World congress on nature & biologically inspired computing (NaBIC) (pp. 210-214). Ieee. + +* **CRO - Coral Reefs Optimization** + * **OriginalCRO**: Salcedo-Sanz, S., Del Ser, J., Landa-Torres, I., Gil-López, S., & Portilla-Figueras, J. A. (2014). The coral reefs optimization algorithm: a novel metaheuristic for efficiently solving optimization problems. The Scientific World Journal, 2014. + * **OCRO**: Nguyen, T., Nguyen, T., Nguyen, B. M., & Nguyen, G. (2019). Efficient time-series forecasting using neural network and opposition-based coral reefs optimization. International Journal of Computational Intelligence Systems, 12(2), 1144-1161. + +* **COA - Coyote Optimization Algorithm** + * **OriginalCOA**: Pierezan, J., & Coelho, L. D. S. (2018, July). Coyote optimization algorithm: a new metaheuristic for global optimization problems. In 2018 IEEE congress on evolutionary computation (CEC) (pp. 1-8). IEEE. + +* **CHIO - Coronavirus Herd Immunity Optimization** + * **OriginalCHIO**: Al-Betar, M. A., Alyasseri, Z. A. A., Awadallah, M. A., & Abu Doush, I. (2021). Coronavirus herd immunity optimizer (CHIO). Neural Computing and Applications, 33(10), 5011-5042. + * **BaseCHIO**: The developed version + +* **CGO - Chaos Game Optimization** + * **OriginalCGO**: Talatahari, S., & Azizi, M. (2021). Chaos Game Optimization: a novel metaheuristic algorithm. Artificial Intelligence Review, 54(2), 917-1004. + +* **CSA - Circle Search Algorithm** + * **OriginalCSA**: Qais, M. H., Hasanien, H. M., Turky, R. A., Alghuwainem, S., Tostado-Véliz, M., & Jurado, F. (2022). Circle Search Algorithm: A Geometry-Based Metaheuristic Optimization Algorithm. Mathematics, 10(10), 1626. + +* **CDDO - Child Drawing Development Optimization** + * **OriginalCDDO**: Abdulhameed, S., Rashid, T.A. Child Drawing Development Optimization Algorithm Based on Child’s Cognitive Development. Arab J Sci Eng 47, 1337–1351 (2022). https://doi.org/10.1007/s13369-021-05928-6 + + +### D + +* **DE - Differential Evolution** + * **BaseDE**: Storn, R., & Price, K. (1997). Differential evolution–a simple and efficient heuristic for global optimization over continuous spaces. Journal of global optimization, 11(4), 341-359. + * **JADE**: Zhang, J., & Sanderson, A. C. (2009). JADE: adaptive differential evolution with optional external archive. IEEE Transactions on evolutionary computation, 13(5), 945-958. + * **SADE**: Qin, A. K., & Suganthan, P. N. (2005, September). Self-adaptive differential evolution algorithm for numerical optimization. In 2005 IEEE congress on evolutionary computation (Vol. 2, pp. 1785-1791). IEEE. + * **SHADE**: Tanabe, R., & Fukunaga, A. (2013, June). Success-history based parameter adaptation for differential evolution. In 2013 IEEE congress on evolutionary computation (pp. 71-78). IEEE. + * **L_SHADE**: Tanabe, R., & Fukunaga, A. S. (2014, July). Improving the search performance of SHADE using linear population size reduction. In 2014 IEEE congress on evolutionary computation (CEC) (pp. 1658-1665). IEEE. + * **SAP_DE**: Teo, J. (2006). Exploring dynamic cls-adaptive populations in differential evolution. Soft Computing, 10(8), 673-686. + +* **DSA - Differential Search Algorithm (not done)** + * **BaseDSA**: Civicioglu, P. (2012). Transforming geocentric cartesian coordinates to geodetic coordinates by using differential search algorithm. Computers & Geosciences, 46, 229-247. + +* **DO - Dragonfly Optimization** + * **OriginalDO**: Mirjalili, S. (2016). Dragonfly algorithm: a new meta-heuristic optimization technique for solving single-objective, discrete, and multi-objective problems. Neural Computing and Applications, 27(4), 1053-1073. + +* **DMOA - Dwarf Mongoose Optimization Algorithm** + * **OriginalDMOA**: Agushaka, J. O., Ezugwu, A. E., & Abualigah, L. (2022). Dwarf mongoose optimization algorithm. Computer methods in applied mechanics and engineering, 391, 114570. + * **DevDMOA**: The developed version + +### E + +* **ES - Evolution Strategies** . + * **OriginalES**: Schwefel, H. P. (1984). Evolution strategies: A family of non-linear optimization techniques based on imitating some principles of organic evolution. Annals of Operations Research, 1(2), 165-167. + * **LevyES**: Zhang, S., & Salari, E. (2005). Competitive learning vector quantization with evolution strategies for image compression. Optical Engineering, 44(2), 027006. + +* **EP - Evolutionary programming** . + * **OriginalEP**: Fogel, L. J. (1994). Evolutionary programming in perspective: The top-down view. Computational intelligence: Imitating life. + * **LevyEP**: Lee, C.Y. and Yao, X., 2001, May. Evolutionary algorithms with adaptive lévy mutations. In Proceedings of the 2001 congress on evolutionary computation (IEEE Cat. No. 01TH8546) (Vol. 1, pp. 568-575). IEEE. + +* **EHO - Elephant Herding Optimization** . + * **OriginalEHO**: Wang, G. G., Deb, S., & Coelho, L. D. S. (2015, December). Elephant herding optimization. In 2015 3rd International Symposium on Computational and Business Intelligence (ISCBI) (pp. 1-5). IEEE. + +* **EFO - Electromagnetic Field Optimization** . + * **OriginalEFO**:Abedinpourshotorban, H., Shamsuddin, S. M., Beheshti, Z., & Jawawi, D. N. (2016). Electromagnetic field optimization: A physics-inspired metaheuristic optimization algorithm. Swarm and Evolutionary Computation, 26, 8-22. + * **BaseEFO**: The developed version + +* **EOA - Earthworm Optimisation Algorithm** . + * **OriginalEOA**: Wang, G. G., Deb, S., & dos Santos Coelho, L. (2018). Earthworm optimisation algorithm: a bio-inspired metaheuristic algorithm for global optimisation problems. IJBIC, 12(1), 1-22. + +* **EO - Equilibrium Optimizer** . + * **OriginalEO**: Faramarzi, A., Heidarinejad, M., Stephens, B., & Mirjalili, S. (2019). Equilibrium optimizer: A novel optimization algorithm. Knowledge-Based Systems. + * **ModifiedEO**: Gupta, S., Deep, K., & Mirjalili, S. (2020). An efficient equilibrium optimizer with mutation strategy for numerical optimization. Applied Soft Computing, 96, 106542. + * **AdaptiveEO**: Wunnava, A., Naik, M. K., Panda, R., Jena, B., & Abraham, A. (2020). A novel interdependence based multilevel thresholding technique using adaptive equilibrium optimizer. Engineering Applications of Artificial Intelligence, 94, 103836. + +* **ESO - Electrical Storm Optimization** . + * **OriginalESO**: Soto Calvo, M., & Lee, H. S. (2025). Electrical Storm Optimization (ESO) Algorithm: Theoretical Foundations, Analysis, and Application to Engineering Problems. Machine Learning and Knowledge Extraction, 7(1), 24. https://doi.org/10.3390/make7010024 + +* **EPC - Emperor Penguins Colony** . + * **DevEPC**: Harifi, S., Khalilian, M., Mohammadzadeh, J. and Ebrahimnejad, S., 2019. Emperor Penguins Colony: a new metaheuristic algorithm for optimization. Evolutionary intelligence, 12(2), pp.211-226. + + +### F + +* **FFA - Firefly Algorithm** + * **OriginalFFA**: Łukasik, S., & Żak, S. (2009, October). Firefly algorithm for continuous constrained optimization tasks. In International conference on computational collective intelligence (pp. 97-106). Springer, Berlin, Heidelberg. + +* **FA - Fireworks algorithm** + * **OriginalFA**: Tan, Y., & Zhu, Y. (2010, June). Fireworks algorithm for optimization. In International conference in swarm intelligence (pp. 355-364). Springer, Berlin, Heidelberg. + +* **FPA - Flower Pollination Algorithm** + * **OriginalFPA**: Yang, X. S. (2012, September). Flower pollination algorithm for global optimization. In International conference on unconventional computing and natural computation (pp. 240-249). Springer, Berlin, Heidelberg. + +* **FOA - Fruit-fly Optimization Algorithm** + * **OriginalFOA**: Pan, W. T. (2012). A new fruit fly optimization algorithm: taking the financial distress model as an example. Knowledge-Based Systems, 26, 69-74. + * **BaseFOA**: The developed version + * **WhaleFOA**: Fan, Y., Wang, P., Heidari, A. A., Wang, M., Zhao, X., Chen, H., & Li, C. (2020). Boosted hunting-based fruit fly optimization and advances in real-world problems. Expert Systems with Applications, 159, 113502. + +* **FDO - Fitness Dependent Optimizer** + * **OriginalFDO**: Abdullah, J. M., & Ahmed, T. (2019). Fitness dependent optimizer: inspired by the bee swarming reproductive process. IEEe Access, 7, 43473-43486. + +* **FBIO - Forensic-Based Investigation Optimization** + * **OriginalFBIO**: Chou, J.S. and Nguyen, N.M., 2020. FBI inspired meta-optimization. Applied Soft Computing, p.106339. + * **BaseFBIO**: Fathy, A., Rezk, H. and Alanazi, T.M., 2021. Recent approach of forensic-based investigation algorithm for optimizing fractional order PID-based MPPT with proton exchange membrane fuel cell.IEEE Access,9, pp.18974-18992. + +* **FHO - Fire Hawk Optimization** + * **OriginalFHO**: Azizi, M., Talatahari, S., & Gandomi, A. H. (2022). Fire Hawk Optimizer: a novel metaheuristic algorithm. Artificial Intelligence Review, 1-77. + +### G + +* **GA - Genetic Algorithm** + * **BaseGA**: Holland, J. H. (1992). Genetic algorithms. Scientific american, 267(1), 66-73. + * **SingleGA**: De Falco, I., Della Cioppa, A. and Tarantino, E., 2002. Mutation-based genetic algorithm: performance evaluation. Applied Soft Computing, 1(4), pp.285-299. + * **MultiGA**: De Jong, K.A. and Spears, W.M., 1992. A formal analysis of the role of multi-point crossover in genetic algorithms. Annals of mathematics and Artificial intelligence, 5(1), pp.1-26. + * **EliteSingleGA**: Elite version of Single-point mutation GA + * **EliteMultiGA**: Elite version of Multiple-point mutation GA + +* **GWO - Grey Wolf Optimizer** + * **OriginalGWO**: Mirjalili, S., Mirjalili, S. M., & Lewis, A. (2014). Grey wolf optimizer. Advances in engineering software, 69, 46-61. + * **RW_GWO**: Gupta, S., & Deep, K. (2019). A novel random walk grey wolf optimizer. Swarm and evolutionary computation, 44, 101-112. + * **GWO_WOA**: Obadina, O. O., Thaha, M. A., Althoefer, K., & Shaheed, M. H. (2022). Dynamic characterization of a master–slave robotic manipulator using a hybrid grey wolf–whale optimization algorithm. Journal of Vibration and Control, 28(15-16), 1992-2003. + * **IGWO**: Kaveh, A. & Zakian, P.. (2018). Improved GWO algorithm for optimal design of truss structures. Engineering with Computers. 34. 10.1007/s00366-017-0567-1. + * **ChaoticGWO**: Kohli, M., & Arora, S. (2018). Chaotic grey wolf optimization algorithm for constrained optimization problems. Journal of computational design and engineering, 5(4), 458-472. + * **FuzzyGWO**: Rodríguez, Luis, Oscar Castillo, José Soria, Patricia Melin, Fevrier Valdez, Claudia I. Gonzalez, Gabriela E. Martinez, and Jesus Soto. "A fuzzy hierarchical operator in the grey wolf optimizer algorithm." Applied Soft Computing 57 (2017): 315-328. + * **IncrementalGWO**: Seyyedabbasi, A., & Kiani, F. (2021). I-GWO and Ex-GWO: improved algorithms of the Grey Wolf Optimizer to solve global optimization problems. Engineering with Computers, 37(1), 509-532. + * **ExGWO**: Seyyedabbasi, A., & Kiani, F. (2021). I-GWO and Ex-GWO: improved algorithms of the Grey Wolf Optimizer to solve global optimization problems. Engineering with Computers, 37(1), 509-532. + * **DS_GWO**: Jiang, Jianhua, Ziying Zhao, Yutong Liu, Weihua Li, and Huan Wang. "DSGWO: An improved grey wolf optimizer with diversity enhanced strategy based on group-stage competition and balance mechanisms." Knowledge-Based Systems 250 (2022): 109100. + * **IOBL_GWO**: Bansal, J. C., & Singh, S. (2021). A better exploration strategy in Grey Wolf Optimizer. Journal of Ambient Intelligence and Humanized Computing, 12(1), 1099-1118. + * **OGWO**: Yu, X., Xu, W., & Li, C. (2021). Opposition-based learning grey wolf optimizer for global optimization. Knowledge-Based Systems, 226, 107139. + * **ER_GWO**: Long, W., Cai, S., Jiao, J. et al. An efficient and robust grey wolf optimizer algorithm for large-scale numerical optimization. Soft Comput 24, 997–1026 (2020). + * **CG_GWO**: Li, K., Li, S., Huang, Z. et al. Grey Wolf Optimization algorithm based on Cauchy-Gaussian mutation and improved search strategy. Sci Rep 12, 18961 (2022). + +* **GOA - Grasshopper Optimisation Algorithm** + * **OriginalGOA**: Saremi, S., Mirjalili, S., & Lewis, A. (2017). Grasshopper optimisation algorithm: theory and application. Advances in Engineering Software, 105, 30-47. + +* **GCO - Germinal Center Optimization** + * **OriginalGCO**: Villaseñor, C., Arana-Daniel, N., Alanis, A. Y., López-Franco, C., & Hernandez-Vargas, E. A. (2018). Germinal center optimization algorithm. International Journal of Computational Intelligence Systems, 12(1), 13-27. + * **BaseGCO**: The developed version + +* **GSKA - Gaining Sharing Knowledge-based Algorithm** + * **OriginalGSKA**: Mohamed, A. W., Hadi, A. A., & Mohamed, A. K. (2019). Gaining-sharing knowledge based algorithm for solving optimization problems: a novel nature-inspired algorithm. International Journal of Machine Learning and Cybernetics, 1-29. + * **BaseGSKA**: Mohamed, A.W., Hadi, A.A., Mohamed, A.K. and Awad, N.H., 2020, July. Evaluating the performance of adaptive GainingSharing knowledge based algorithm on CEC 2020 benchmark problems. In 2020 IEEE Congress on Evolutionary Computation (CEC) (pp. 1-8). IEEE. + +* **GBO - Gradient-Based Optimizer** + * **OriginalGBO**: Ahmadianfar, I., Bozorg-Haddad, O., & Chu, X. (2020). Gradient-based optimizer: A new metaheuristic optimization algorithm. Information Sciences, 540, 131-159. + +### H + +* **HC - Hill Climbing** . + * **OriginalHC**: Talbi, E. G., & Muntean, T. (1993, January). Hill-climbing, simulated annealing and genetic algorithms: a comparative study and application to the mapping problem. In [1993] Proceedings of the Twenty-sixth Hawaii International Conference on System Sciences (Vol. 2, pp. 565-573). IEEE. + * **SwarmHC**: The developed version based on swarm-based idea (Original is single-solution based method) + +* **HS - Harmony Search** . + * **OriginalHS**: Geem, Z. W., Kim, J. H., & Loganathan, G. V. (2001). A new heuristic optimization algorithm:harmony search. simulation, 76(2), 60-68. + * **BaseHS**: The developed version + +* **HHO - Harris Hawks Optimization** . + * **OriginalHHO**: Heidari, A. A., Mirjalili, S., Faris, H., Aljarah, I., Mafarja, M., & Chen, H. (2019). Harris hawks optimization: Algorithm and applications. Future Generation Computer Systems, 97, 849-872. + +* **HGSO - Henry Gas Solubility Optimization** . + * **OriginalHGSO**: Hashim, F. A., Houssein, E. H., Mabrouk, M. S., Al-Atabany, W., & Mirjalili, S. (2019). Henry gas solubility optimization: A novel physics-based algorithm. Future Generation Computer Systems, 101, 646-667. + +* **HGS - Hunger Games Search** . + * **OriginalHGS**: Yang, Y., Chen, H., Heidari, A. A., & Gandomi, A. H. (2021). Hunger games search:Visions, conception, implementation, deep analysis, perspectives, and towards performance shifts. Expert Systems with Applications, 177, 114864. + +* **HHOA - Horse Herd Optimization Algorithm (not done)** . + * **BaseHHOA**: MiarNaeimi, F., Azizyan, G., & Rashki, M. (2021). Horse herd optimization algorithm: A nature-inspired algorithm for high-dimensional optimization problems. Knowledge-Based Systems, 213, 106711. + +* **HBA - Honey Badger Algorithm**: + * **OriginalHBA**: Hashim, F. A., Houssein, E. H., Hussain, K., Mabrouk, M. S., & Al-Atabany, W. (2022). Honey Badger Algorithm: New metaheuristic algorithm for solving optimization problems. Mathematics and Computers in Simulation, 192, 84-110. + + +### I + +* **IWO - Invasive Weed Optimization** . + * **OriginalIWO**: Mehrabian, A. R., & Lucas, C. (2006). A novel numerical optimization algorithm inspired from weed colonization. Ecological informatics, 1(4), 355-366. + +* **ICA - Imperialist Competitive Algorithm** + * **OriginalICA**: Atashpaz-Gargari, E., & Lucas, C. (2007, September). Imperialist competitive algorithm: an algorithm for optimization inspired by imperialistic competition. In 2007 IEEE congress on evolutionary computation (pp. 4661-4667). Ieee. + +* **IMODE - Improved Multi-operator Differential Evolution Algorithm**: + * **OriginalIMODE**: Sallam, K. M., Elsayed, S. M., Chakrabortty, R. K., & Ryan, M. J. (2020, July). Improved multi-operator differential evolution algorithm for solving unconstrained problems. In 2020 IEEE congress on evolutionary computation (CEC) (pp. 1-8). IEEE. + +* **INFO - weIghted meaN oF vectOrs**: + * **OriginalINFO**: Ahmadianfar, I., Heidari, A. A., Gandomi, A. H., Chu, X., & Chen, H. (2021). RUN beyond the metaphor: An efficient optimization algorithm based on Runge Kutta method. Expert Systems with Applications, 181, 115079. + +### J + +* **JA - Jaya Algorithm** + * **OriginalJA**: Rao, R. (2016). Jaya: A simple and new optimization algorithm for solving constrained and unconstrained optimization problems. International Journal of Industrial Engineering Computations, 7(1), 19-34. + * **BaseJA**: The developed version + * **LevyJA**: Iacca, G., dos Santos Junior, V. C., & de Melo, V. V. (2021). An improved Jaya optimization algorithm with Levy flight. Expert Systems with Applications, 165, 113902. + +### K + +### L + +* **LSHADEcnEpSin - Ensemble sinusoidal differential covariance matrix adaptation with Euclidean neighborhood** + * **OriginalLSHADEcnEpSin**: Awad, N. H., Ali, M. Z., & Suganthan, P. N. (2017, June). Ensemble sinusoidal differential covariance matrix adaptation with Euclidean neighborhood for solving CEC2017 benchmark problems. In 2017 IEEE congress on evolutionary computation (CEC) (pp. 372-379). IEEE. + +* **LCO - Life Choice-based Optimization** + * **OriginalLCO**: Khatri, A., Gaba, A., Rana, K. P. S., & Kumar, V. (2019). A novel life choice-based optimizer. Soft Computing, 1-21. + * **BaseLCO**: The developed version + * **ImprovedLCO**: The improved version using Gaussian distribution and Mutation Mechanism + + +### M + +* **MA - Memetic Algorithm** + * **OriginalMA**: Moscato, P. (1989). On evolution, search, optimization, genetic algorithms and martial arts: Towards memetic algorithms. Caltech concurrent computation program, C3P Report, 826, 1989. + +* **MFO - Moth Flame Optimization** + * **OriginalMFO**: Mirjalili, S. (2015). Moth-flame optimization algorithm: A novel nature-inspired heuristic paradigm. Knowledge-based systems, 89, 228-249. + * **BaseMFO**: The developed version + +* **MVO - Multi-Verse Optimizer** + * **OriginalMVO**: Mirjalili, S., Mirjalili, S. M., & Hatamlou, A. (2016). Multi-verse optimizer: a nature-inspired algorithm for global optimization. Neural Computing and Applications, 27(2), 495-513. + * **BaseMVO**: The developed version + +* **MSA - Moth Search Algorithm** + * **OriginalMSA**: Wang, G. G. (2018). Moth search algorithm: a bio-inspired metaheuristic algorithm for global optimization problems. Memetic Computing, 10(2), 151-164. + +* **MRFO - Manta Ray Foraging Optimization** + * **OriginalMRFO**: Zhao, W., Zhang, Z., & Wang, L. (2020). Manta ray foraging optimization: An effective bio-inspired optimizer for engineering applications. Engineering Applications of Artificial Intelligence, 87, 103300. + +* **MPA - Marine Predators Algorithm**: + * **OriginalMPA**: Faramarzi, A., Heidarinejad, M., Mirjalili, S., & Gandomi, A. H. (2020). Marine Predators Algorithm: A nature-inspired metaheuristic. Expert systems with applications, 152, 113377. + +### N + +* **NRO - Nuclear Reaction Optimization** + * **OriginalNRO**: Wei, Z., Huang, C., Wang, X., Han, T., & Li, Y. (2019). Nuclear Reaction Optimization: A novel and powerful physics-based algorithm for global optimization. IEEE Access. + +* **NMRA - Nake Mole-Rat Algorithm** + * **OriginalNMRA**: Salgotra, R., & Singh, U. (2019). The naked mole-rat algorithm. Neural Computing and Applications, 31(12), 8837-8857. + * **ImprovedNMRA**: Singh, P., Mittal, N., Singh, U. and Salgotra, R., 2021. Naked mole-rat algorithm with improved exploration and exploitation capabilities to determine 2D and 3D coordinates of sensor nodes in WSNs. Arabian Journal for Science and Engineering, 46(2), pp.1155-1178. + + +### O + +### P + +* **PSO - Particle Swarm Optimization** + * **OriginalPSO**: Eberhart, R., & Kennedy, J. (1995, October). A new optimizer using particle swarm theory. In MHS'95. Proceedings of the Sixth International Symposium on Micro Machine and Human Science (pp. 39-43). Ieee. + * **PPSO**: Ghasemi, M., Akbari, E., Rahimnejad, A., Razavi, S. E., Ghavidel, S., & Li, L. (2019). Phasor particle swarm optimization: a simple and efficient variant of PSO. Soft Computing, 23(19), 9701-9718. + * **HPSO_TVAC**: Ghasemi, M., Aghaei, J., & Hadipour, M. (2017). New cls-organising hierarchical PSO with jumping time-varying acceleration coefficients. Electronics Letters, 53(20), 1360-1362. + * **C_PSO**: Liu, B., Wang, L., Jin, Y. H., Tang, F., & Huang, D. X. (2005). Improved particle swarm optimization combined with chaos. Chaos, Solitons & Fractals, 25(5), 1261-1271. + * **CL_PSO**: Liang, J. J., Qin, A. K., Suganthan, P. N., & Baskar, S. (2006). Comprehensive learning particle swarm optimizer for global optimization of multimodal functions. IEEE transactions on evolutionary computation, 10(3), 281-295. + +* **PFA - Pathfinder Algorithm** + * **OriginalPFA**: Yapici, H., & Cetinkaya, N. (2019). A new meta-heuristic optimizer: Pathfinder algorithm. Applied Soft Computing, 78, 545-568. + +* **PSS - Pareto-like Sequential Sampling** + * **OriginalPSS**: Shaqfa, M., & Beyer, K. (2021). Pareto-like sequential sampling heuristic for global optimisation. Soft Computing, 25(14), 9077-9096. + + +### Q + +* **QSA - Queuing Search Algorithm** + * **OriginalQSA**: Zhang, J., Xiao, M., Gao, L., & Pan, Q. (2018). Queuing search algorithm: A novel metaheuristic algorithm for solving engineering optimization problems. Applied Mathematical Modelling, 63, 464-490. + * **BaseQSA**: The developed version + * **OppoQSA**: Zheng, X. and Nguyen, H., 2022. A novel artificial intelligent model for predicting water treatment efficiency of various biochar systems based on artificial neural network and queuing search algorithm. Chemosphere, 287, p.132251. + * **LevyQSA**: Abderazek, H., Hamza, F., Yildiz, A.R., Gao, L. and Sait, S.M., 2021. A comparative analysis of the queuing search algorithm, the sine-cosine algorithm, the ant lion algorithm to determine the optimal weight design problem of a spur gear drive system. Materials Testing, 63(5), pp.442-447. + * **ImprovedQSA**: Nguyen, B.M., Hoang, B., Nguyen, T. and Nguyen, G., 2021. nQSV-Net: a novel queuing search variant for global space search and workload modeling. Journal of Ambient Intelligence and Humanized Computing, 12(1), pp.27-46. + +### R + +* **RUN - RUNge Kutta optimizer**: + * **OriginalRUN**: Ahmadianfar, I., Heidari, A. A., Gandomi, A. H., Chu, X., & Chen, H. (2021). RUN beyond the metaphor: An efficient optimization algorithm based on Runge Kutta method. Expert Systems with Applications, 181, 115079. + +### S + +* **SA - Simulated Annealling** + **OriginalSA**: Kirkpatrick, S., Gelatt Jr, C. D., & Vecchi, M. P. (1983). Optimization by simulated annealing. science, 220(4598), 671-680. + **GaussianSA**: Van Laarhoven, P. J., Aarts, E. H., van Laarhoven, P. J., & Aarts, E. H. (1987). Simulated annealing (pp. 7-15). Springer Netherlands. + **SwarmSA**: My developed version + +* **SSpiderO - Social Spider Optimization** + * **OriginalSSpiderO**: Cuevas, E., Cienfuegos, M., ZaldíVar, D., & Pérez-Cisneros, M. (2013). A swarm optimization algorithm inspired in the behavior of the social-spider. Expert Systems with Applications, 40(16), 6374-6384. + +* **SMO - Spider Monkey Optimization** + * **DevSMO**: Bansal, J. C., Sharma, H., Jadon, S. S., & Clerc, M. (2014). Spider monkey optimization algorithm for numerical optimization. Memetic computing, 6(1), 31-47. + +* **SOS - Symbiotic Organisms Search**: + * **OriginalSOS**: Cheng, M. Y., & Prayogo, D. (2014). Symbiotic organisms search: a new metaheuristic optimization algorithm. Computers & Structures, 139, 98-112. + +* **SSpiderA - Social Spider Algorithm** + * **OriginalSSpiderA**: James, J. Q., & Li, V. O. (2015). A social spider algorithm for global optimization. Applied Soft Computing, 30, 614-627. + +* **SCA - Sine Cosine Algorithm** + * **OriginalSCA**: Mirjalili, S. (2016). SCA: a sine cosine algorithm for solving optimization problems. Knowledge-Based Systems, 96, 120-133. + * **BaseSCA**: Attia, A.F., El Sehiemy, R.A. and Hasanien, H.M., 2018. Optimal power flow solution in power systems using a novel Sine-Cosine algorithm. International Journal of Electrical Power & Energy Systems, 99, pp.331-343. + +* **SRSR - Swarm Robotics Search And Rescue** + * **OriginalSRSR**: Bakhshipour, M., Ghadi, M. J., & Namdari, F. (2017). Swarm robotics search & rescue: A novel artificial intelligence-inspired optimization approach. Applied Soft Computing, 57, 708-726. + +* **SBO - Satin Bowerbird Optimizer** + * **OriginalSBO**: Moosavi, S. H. S., & Bardsiri, V. K. (2017). Satin bowerbird optimizer: a new optimization algorithm to optimize ANFIS for software development effort estimation. Engineering Applications of Artificial Intelligence, 60, 1-15. + * **BaseSBO**: The developed version + +* **SHO - Spotted Hyena Optimizer** + * **OriginalSHO**: Dhiman, G., & Kumar, V. (2017). Spotted hyena optimizer: a novel bio-inspired based metaheuristic technique for engineering applications. Advances in Engineering Software, 114, 48-70. + +* **SSO - Salp Swarm Optimization** + * **OriginalSSO**: Mirjalili, S., Gandomi, A. H., Mirjalili, S. Z., Saremi, S., Faris, H., & Mirjalili, S. M. (2017). Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software, 114, 163-191. + +* **SFO - Sailfish Optimizer** + * **OriginalSFO**: Shadravan, S., Naji, H. R., & Bardsiri, V. K. (2019). The Sailfish Optimizer: A novel nature-inspired metaheuristic algorithm for solving constrained engineering optimization problems. Engineering Applications of Artificial Intelligence, 80, 20-34. + * **ImprovedSFO**: Li, L.L., Shen, Q., Tseng, M.L. and Luo, S., 2021. Power system hybrid dynamic economic emission dispatch with wind energy based on improved sailfish algorithm. Journal of Cleaner Production, 316, p.128318. + +* **SARO - Search And Rescue Optimization** + * **OriginalSARO**: Shabani, A., Asgarian, B., Gharebaghi, S. A., Salido, M. A., & Giret, A. (2019). A New Optimization Algorithm Based on Search and Rescue Operations. Mathematical Problems in Engineering, 2019. + * **BaseSARO**: The developed version using Levy-flight + +* **SSDO - Social Ski-Driver Optimization** + * **OriginalSSDO**: Tharwat, A., & Gabel, T. (2019). Parameters optimization of support vector machines for imbalanced data using social ski driver algorithm. Neural Computing and Applications, 1-14. + +* **SLO - Sea Lion Optimization** + * **OriginalSLO**: Masadeh, R., Mahafzah, B. A., & Sharieh, A. (2019). Sea Lion Optimization Algorithm. Sea, 10(5). + * **ImprovedSLO**: The developed version + * **ModifiedSLO**: Masadeh, R., Alsharman, N., Sharieh, A., Mahafzah, B.A. and Abdulrahman, A., 2021. Task scheduling on cloud computing based on sea lion optimization algorithm. International Journal of Web Information Systems. + +* **Seagull Optimization Algorithm** + * **OriginalSOA**: Dhiman, G., & Kumar, V. (2019). Seagull optimization algorithm: Theory and its applications for large-scale industrial engineering problems. Knowledge-based systems, 165, 169-196. + * **DevSOA**: The developed version + +* **Squirrel Search Algorithm** + * **OriginalSquirrelSA**: Jain, M., Singh, V., & Rani, A. (2019). A novel nature-inspired algorithm for optimization: Squirrel search algorithm. Swarm and evolutionary computation, 44, 148-175. + +* **SMA - Slime Mould Algorithm** + * **OriginalSMA**: Li, S., Chen, H., Wang, M., Heidari, A. A., & Mirjalili, S. (2020). Slime mould algorithm: A new method for stochastic optimization. Future Generation Computer Systems. + * **BaseSMA**: The developed version + +* **SSA - Sparrow Search Algorithm** + * **OriginalSSA**: Jiankai Xue & Bo Shen (2020) A novel swarm intelligence optimization approach: sparrow search algorithm, Systems Science & Control Engineering, 8:1, 22-34, DOI: 10.1080/21642583.2019.1708830 + * **BaseSSA**: The developed version + +* **SPBO - Student Psychology Based Optimization** + * **OriginalSPBO**: Das, B., Mukherjee, V., & Das, D. (2020). Student psychology based optimization algorithm: A new population based optimization algorithm for solving optimization problems. Advances in Engineering software, 146, 102804. + * **DevSPBO**: The developed version + +* **SCSO - Sand Cat Swarm Optimization** + * **OriginalSCSO**: Seyyedabbasi, A., & Kiani, F. (2022). Sand Cat swarm optimization: a nature-inspired algorithm to solve global optimization problems. Engineering with Computers, 1-25. + +### T + +* **TLO - Teaching Learning Optimization** + * **OriginalTLO**: Rao, R. V., Savsani, V. J., & Vakharia, D. P. (2011). Teaching–learning-based optimization: a novel method for constrained mechanical design optimization problems. Computer-Aided Design, 43(3), 303-315. + * **BaseTLO**: Rao, R., & Patel, V. (2012). An elitist teaching-learning-based optimization algorithm for solving complex constrained optimization problems. International Journal of Industrial Engineering Computations, 3(4), 535-560. + * **ImprovedTLO**: Rao, R. V., & Patel, V. (2013). An improved teaching-learning-based optimization algorithm for solving unconstrained optimization problems. Scientia Iranica, 20(3), 710-720. + +* **TWO - Tug of War Optimization** + * **OriginalTWO**: Kaveh, A., & Zolghadr, A. (2016). A novel meta-heuristic algorithm: tug of war optimization. Iran University of Science & Technology, 6(4), 469-492. + * **OppoTWO**: Kaveh, A., Almasi, P. and Khodagholi, A., 2022. Optimum Design of Castellated Beams Using Four Recently Developed Meta-heuristic Algorithms. Iranian Journal of Science and Technology, Transactions of Civil Engineering, pp.1-13. + * **LevyTWO**: The developed version using Levy-flight + * **ImprovedTWO**: Nguyen, T., Hoang, B., Nguyen, G., & Nguyen, B. M. (2020). A new workload prediction model using extreme learning machine and enhanced tug of war optimization. Procedia Computer Science, 170, 362-369. + +* **TSA - Tunicate Swarm Algorithm** + * **OriginalTSA**: Kaur, S., Awasthi, L. K., Sangal, A. L., & Dhiman, G. (2020). Tunicate Swarm Algorithm: A new bio-inspired based metaheuristic paradigm for global optimization. Engineering Applications of Artificial Intelligence, 90, 103541. + +* **TSO - Tuna Swarm Optimization** + * **OriginalTSO**: Xie, L., Han, T., Zhou, H., Zhang, Z. R., Han, B., & Tang, A. (2021). Tuna swarm optimization: a novel swarm-based metaheuristic algorithm for global optimization. Computational intelligence and Neuroscience, 2021. + + +### U + +### V + +* **VCS - Virus Colony Search** + * **OriginalVCS**: Li, M. D., Zhao, H., Weng, X. W., & Han, T. (2016). A novel nature-inspired algorithm for optimization: Virus colony search. Advances in Engineering Software, 92, 65-88. + * **BaseVCS**: The developed version + +### W + +* **WCA - Water Cycle Algorithm** + * **OriginalWCA**: Eskandar, H., Sadollah, A., Bahreininejad, A., & Hamdi, M. (2012). Water cycle algorithm–A novel metaheuristic optimization method for solving constrained engineering optimization problems. Computers & Structures, 110, 151-166. + +* **WOA - Whale Optimization Algorithm** + * **OriginalWOA**: Mirjalili, S., & Lewis, A. (2016). The whale optimization algorithm. Advances in engineering software, 95, 51-67. + * **HI_WOA**: Tang, C., Sun, W., Wu, W., & Xue, M. (2019, July). A hybrid improved whale optimization algorithm. In 2019 IEEE 15th International Conference on Control and Automation (ICCA) (pp. 362-367). IEEE. + +* **WHO - Wildebeest Herd Optimization** + * **OriginalWHO**: Amali, D., & Dinakaran, M. (2019). Wildebeest herd optimization: A new global optimization algorithm inspired by wildebeest herding behaviour. Journal of Intelligent & Fuzzy Systems, (Preprint), 1-14. + +* **WDO - Wind Driven Optimization** + * **OriginalWDO**: Bayraktar, Z., Komurcu, M., Bossard, J.A. and Werner, D.H., 2013. The wind driven optimization technique and its application in electromagnetics. IEEE transactions on antennas and propagation, 61(5), pp.2745-2757. diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index d0c3cbf1..00000000 --- a/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line, and also -# from the environment for the first two. -SPHINXOPTS ?= -SPHINXBUILD ?= sphinx-build -SOURCEDIR = source -BUILDDIR = build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 061f32f9..00000000 --- a/docs/make.bat +++ /dev/null @@ -1,35 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=source -set BUILDDIR=build - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.https://www.sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% - -:end -popd diff --git a/docs/requirements.txt b/docs/requirements.txt deleted file mode 100644 index 603a9eb9..00000000 --- a/docs/requirements.txt +++ /dev/null @@ -1,10 +0,0 @@ -# Defining the exact version will make sure things don't break -sphinx==5.0.2 -sphinx_rtd_theme==1.0.0 -readthedocs-sphinx-search==0.3.2 -numpy>=1.17.1,<=1.26.0 -scipy>=1.7.1 -matplotlib==3.1.3 -pandas>=1.2.0 -opfunu>=1.0.0 -tqdm>=4.66.0 diff --git a/docs/source/_static/images/bio_inspired.png b/docs/source/_static/images/bio_inspired.png deleted file mode 100644 index 661b7371..00000000 Binary files a/docs/source/_static/images/bio_inspired.png and /dev/null differ diff --git a/docs/source/_static/images/general_format.png b/docs/source/_static/images/general_format.png deleted file mode 100644 index 7d406f4b..00000000 Binary files a/docs/source/_static/images/general_format.png and /dev/null differ diff --git a/docs/source/_static/images/history_metaheuristics.png b/docs/source/_static/images/history_metaheuristics.png deleted file mode 100644 index 3053eaef..00000000 Binary files a/docs/source/_static/images/history_metaheuristics.png and /dev/null differ diff --git a/docs/source/_static/images/illusion.png b/docs/source/_static/images/illusion.png deleted file mode 100644 index cd8ee1ae..00000000 Binary files a/docs/source/_static/images/illusion.png and /dev/null differ diff --git a/docs/source/_static/images/mealpy_flow.png b/docs/source/_static/images/mealpy_flow.png deleted file mode 100644 index b1d9c8ed..00000000 Binary files a/docs/source/_static/images/mealpy_flow.png and /dev/null differ diff --git a/docs/source/_static/images/neural_network.png b/docs/source/_static/images/neural_network.png deleted file mode 100644 index 6a758fdf..00000000 Binary files a/docs/source/_static/images/neural_network.png and /dev/null differ diff --git a/docs/source/_static/images/results/1d_trajectory.png b/docs/source/_static/images/results/1d_trajectory.png deleted file mode 100644 index 77cec992..00000000 Binary files a/docs/source/_static/images/results/1d_trajectory.png and /dev/null differ diff --git a/docs/source/_static/images/results/Current-best-convergence-chart.png b/docs/source/_static/images/results/Current-best-convergence-chart.png deleted file mode 100644 index 1b36393a..00000000 Binary files a/docs/source/_static/images/results/Current-best-convergence-chart.png and /dev/null differ diff --git a/docs/source/_static/images/results/Global-best-convergence-chart.png b/docs/source/_static/images/results/Global-best-convergence-chart.png deleted file mode 100644 index c40f4381..00000000 Binary files a/docs/source/_static/images/results/Global-best-convergence-chart.png and /dev/null differ diff --git a/docs/source/_static/images/results/Runtime-per-epoch-chart.png b/docs/source/_static/images/results/Runtime-per-epoch-chart.png deleted file mode 100644 index 221aa8e4..00000000 Binary files a/docs/source/_static/images/results/Runtime-per-epoch-chart.png and /dev/null differ diff --git a/docs/source/_static/images/results/diversity_chart.png b/docs/source/_static/images/results/diversity_chart.png deleted file mode 100644 index 16d1446a..00000000 Binary files a/docs/source/_static/images/results/diversity_chart.png and /dev/null differ diff --git a/docs/source/_static/images/results/explore_exploit_chart.png b/docs/source/_static/images/results/explore_exploit_chart.png deleted file mode 100644 index 9f378053..00000000 Binary files a/docs/source/_static/images/results/explore_exploit_chart.png and /dev/null differ diff --git a/docs/source/_static/images/results/global-objective-chart.png b/docs/source/_static/images/results/global-objective-chart.png deleted file mode 100644 index 33c5c818..00000000 Binary files a/docs/source/_static/images/results/global-objective-chart.png and /dev/null differ diff --git a/docs/source/_static/images/results/local-objective-chart.png b/docs/source/_static/images/results/local-objective-chart.png deleted file mode 100644 index 472ce52b..00000000 Binary files a/docs/source/_static/images/results/local-objective-chart.png and /dev/null differ diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 7cf70839..00000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,68 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# This file only contains a selection of the most common options. For a full -# list see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Path setup -------------------------------------------------------------- - -# 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. -# -import sphinx_rtd_theme -import os -import sys - -sys.path.insert(0, os.path.abspath('.')) -sys.path.insert(0, os.path.abspath('../../')) -sys.path.insert(1, os.path.abspath('../../mealpy')) - - -# -- Project information ----------------------------------------------------- - -project = 'MEALPY' -copyright = '2021, Thieu' -author = 'Thieu' - -# The full version, including alpha/beta/rc tags -release = '3.0.3' - - -# -- General configuration --------------------------------------------------- - -# 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.napoleon", - "sphinx.ext.intersphinx", - "sphinx.ext.viewcode", -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - - -# -- 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 = 'alabaster' -html_theme = 'sphinx_rtd_theme' - -html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] - -# 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'] - -highlight_language = 'python' diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index 17fa71dd..00000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,110 +0,0 @@ -Welcome to MEALPY's documentation! -================================== - -.. image:: https://img.shields.io/badge/release-3.0.3-yellow.svg - :target: https://github.com/thieu1995/mealpy/releases - -.. image:: https://img.shields.io/pypi/wheel/gensim.svg - :target: https://pypi.python.org/pypi/mealpy - -.. image:: https://badge.fury.io/py/mealpy.svg - :target: https://badge.fury.io/py/mealpy - -.. image:: https://img.shields.io/pypi/pyversions/mealpy.svg - :target: https://www.python.org/ - -.. image:: https://img.shields.io/pypi/status/mealpy.svg - :target: https://img.shields.io/pypi/status/mealpy.svg - -.. image:: https://github.com/thieu1995/mealpy/actions/workflows/publish-package.yaml/badge.svg - :target: https://github.com/thieu1995/mealpy/actions/workflows/publish-package.yaml - -.. image:: https://static.pepy.tech/badge/mealpy - :target: https://pepy.tech/project/mealpy - -.. image:: https://img.shields.io/github/release-date/thieu1995/mealpy.svg - :target: https://img.shields.io/github/release-date/thieu1995/mealpy.svg - -.. image:: https://readthedocs.org/projects/mealpy/badge/?version=latest - :target: https://mealpy.readthedocs.io/en/latest/?badge=latest - -.. image:: https://img.shields.io/badge/Chat-on%20Telegram-blue - :target: https://t.me/+fRVCJGuGJg1mNDg1 - -.. image:: http://isitmaintained.com/badge/resolution/thieu1995/mealpy.svg - :target: http://isitmaintained.com/project/thieu1995/mealpy - -.. image:: http://isitmaintained.com/badge/open/thieu1995/mealpy.svg - :target: http://isitmaintained.com/project/thieu1995/mealpy - -.. image:: https://img.shields.io/github/contributors/thieu1995/mealpy.svg - :target: https://img.shields.io/github/contributors/thieu1995/mealpy.svg - -.. image:: https://img.shields.io/badge/PR-Welcome-%23FF8300.svg? - :target: https://git-scm.com/book/en/v2/GitHub-Contributing-to-a-Project - -.. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.3711948.svg - :target: https://doi.org/10.1016/j.sysarc.2023.102871 - -.. image:: https://img.shields.io/badge/License-MIT-yellow.svg - :target: https://opensource.org/licenses/MIT - -:: - - "Knowledge is power, sharing it is the premise of progress in life. - It seems like a burden to someone, but it is the only way to achieve immortality. - `Nguyen Van Thieu`_ - - -.. _Nguyen Van Thieu: https://www.thieu1995.github.io/ - -MEALPY is a Python library that contains the largest number of the cutting-edge population-based *meta-heuristic algorithms* — a field that provides a fast and -efficient way to find the (approximation) global optimal point of mathematical optimization problems. - -Population-based meta-heuristic algorithms (PMAs) are the most popular algorithms in the field of optimization. There are several types of PMAs, including: - -- Evolutionary inspired computing -- Swarm inspired computing -- Physics inspired computing -- Human inspired computing -- Biology inspired computing -- Mathematical inspired computing -- And others such as: Music inspired, System inspired computing,... - - - -Features --------- - -- Our library provides all state-of-the-art population meta-heuristic algorithms for optimization problems. -- We have implemented all algorithms using Numpy to increase the speed of the algorithms. -- Additionally, we have designed a visualization module to help users understand and explore the results discovered by the model after learning. - - -.. toctree:: - :maxdepth: 4 - :caption: Quick Start: - - pages/quick_start.rst - - -.. toctree:: - :maxdepth: 4 - :caption: Models API: - - pages/models.rst - -.. toctree:: - :maxdepth: 4 - :caption: Support: - - pages/support.rst - - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/source/pages/general/advance_guide.rst b/docs/source/pages/general/advance_guide.rst deleted file mode 100644 index 2c01d967..00000000 --- a/docs/source/pages/general/advance_guide.rst +++ /dev/null @@ -1,27 +0,0 @@ -============= -Advance Guide -============= - -.. include:: advances/termination.rst -.. include:: advances/reproducibility.rst -.. include:: advances/multi_objective_optimization.rst -.. include:: advances/constraint_optimization.rst -.. include:: advances/discrete_optimization.rst -.. include:: advances/log_training_process.rst -.. include:: advances/custom_problem.rst -.. include:: advances/model_parameter.rst -.. include:: advances/model_problem_name.rst -.. include:: advances/agent_history.rst -.. include:: advances/saving_loading.rst -.. include:: advances/starting_positions.rst -.. include:: advances/import_all_models.rst - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/general/advances/agent_history.rst b/docs/source/pages/general/advances/agent_history.rst deleted file mode 100644 index dcf8a7ac..00000000 --- a/docs/source/pages/general/advances/agent_history.rst +++ /dev/null @@ -1,81 +0,0 @@ -Agent's History (Trajectory) -============================ - -**WARNING: Trajectory will cause the memory issues:** - -The history of the population is not saved by default, but you can enable this feature by setting the "save_population" keyword to True in the Problem -definition. Keep in mind that enabling this option may cause memory issues if your problem is too large, as it saves the history of the population in each -generation. However, if your problem is small enough, you can turn it on and visualize the trajectory chart of search agents. - -.. code-block:: python - - problem_dict1 = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "log_to": "console", - "save_population": True, # Default = False - } - - -You can access to the history of agent/population in model.history object with variables: - + list_global_best: List of global best SOLUTION found so far in all previous generations - + list_current_best: List of current best SOLUTION in each previous generations - + list_global_worst: List of global worst SOLUTION found so far in all previous generations - + list_current_worst: List of current worst SOLUTION in each previous generations - + list_epoch_time: List of runtime for each generation - + list_global_best_fit: List of global best FITNESS found so far in all previous generations - + list_current_best_fit: List of current best FITNESS in each previous generations - + list_diversity: List of DIVERSITY of swarm in all generations - + list_exploitation: List of EXPLOITATION percentages for all generations - + list_exploration: List of EXPLORATION percentages for all generations - + list_population: List of POPULATION in each generations - -**Note**: The last variable, 'list_population', is the one that can cause the "memory" error described above. -It is recommended to set the 'save_population' parameter to False (which is also the default) in the input problem dictionary if you do not plan to use it. - - - -.. code-block:: python - - import numpy as np - from mealpy import PSO - - def objective_function(solution): - return np.sum(solution**2) - - problem_dict = { - "obj_func": objective_function, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "verbose": True, - "save_population": False # Then you can't draw the trajectory chart - } - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_dict) - - print(model.history.list_global_best) - print(model.history.list_current_best) - print(model.history.list_global_worst) - print(model.history.list_current_worst) - print(model.history.list_epoch_time) - print(model.history.list_global_best_fit) - print(model.history.list_current_best_fit) - print(model.history.list_diversity) - print(model.history.list_exploitation) - print(model.history.list_exploration) - print(model.history.list_population) - - ## Remember if you set "save_population" to False, then there is no variable: list_population - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/constraint_optimization.rst b/docs/source/pages/general/advances/constraint_optimization.rst deleted file mode 100644 index 720ea67b..00000000 --- a/docs/source/pages/general/advances/constraint_optimization.rst +++ /dev/null @@ -1,126 +0,0 @@ -Constraint Optimization -======================= - -For this problem, we recommend that the user defines a punishment function. The more the objective is violated, the greater the punishment function will be. -As a result, the fitness will increase, and the solution will have a lower chance of being selected in the updating process. - - -* Declare problem dictionary: - -.. code-block:: python - - import numpy as np - from mealpy import PSO, FloatVar - - ## This is how you design Constrained Benchmark Function (G01) - #### Link: https://onlinelibrary.wiley.com/doi/pdf/10.1002/9781119136507.app2 - def objective_function(solution): - def g1(x): - return 2 * x[0] + 2 * x[1] + x[9] + x[10] - 10 - def g2(x): - return 2 * x[0] + 2 * x[2] + x[9] + x[10] - 10 - def g3(x): - return 2 * x[1] + 2 * x[2] + x[10] + x[11] - 10 - def g4(x): - return -8 * x[0] + x[9] - def g5(x): - return -8 * x[1] + x[10] - def g6(x): - return -8 * x[2] + x[11] - def g7(x): - return -2 * x[3] - x[4] + x[9] - def g8(x): - return -2 * x[5] - x[6] + x[10] - def g9(x): - return -2 * x[7] - x[8] + x[11] - - def violate(value): - return 0 if value <= 0 else value - - fx = 5 * np.sum(solution[:4]) - 5 * np.sum(solution[:4] ** 2) - np.sum(solution[4:13]) - - ## Increase the punishment for g1 and g4 to boost the algorithm (You can choice any constraint instead of g1 and g4) - fx += violate(g1(solution)) ** 2 + violate(g2(solution)) + violate(g3(solution)) + \ - 2 * violate(g4(solution)) + violate(g5(solution)) + violate(g6(solution)) + \ - violate(g7(solution)) + violate(g8(solution)) + violate(g9(solution)) - return fx - - ## Design a problem dictionary for constrained objective function above - problem_constrained = { - "obj_func": objective_function, - "bounds": FloatVar(lb=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ub=[1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1]), - "minmax": "min", - } - - ## Define the model and solve the problem - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_multi) - - - -* Or declare a custom Problem class: - -.. code-block:: python - - import numpy as np - from mealpy import PSO, FloatVar - from mealpy.utils.problem import Problem - - - ## Define a custom child class of Problem class. - class COP(Problem): - def __init__(self, lb, ub, minmax, **kwargs): - super().__init__(lb, ub, minmax, **kwargs) - - def g1(x): - return 2 * x[0] + 2 * x[1] + x[9] + x[10] - 10 - def g2(x): - return 2 * x[0] + 2 * x[2] + x[9] + x[10] - 10 - def g3(x): - return 2 * x[1] + 2 * x[2] + x[10] + x[11] - 10 - def g4(x): - return -8 * x[0] + x[9] - def g5(x): - return -8 * x[1] + x[10] - def g6(x): - return -8 * x[2] + x[11] - def g7(x): - return -2 * x[3] - x[4] + x[9] - def g8(x): - return -2 * x[5] - x[6] + x[10] - def g9(x): - return -2 * x[7] - x[8] + x[11] - - def violate(value): - return 0 if value <= 0 else value - - def obj_func(self, solution): - ## This is how you design Constrained Benchmark Function (G01) - #### Link: https://onlinelibrary.wiley.com/doi/pdf/10.1002/9781119136507.app2 - - fx = 5 * np.sum(solution[:4]) - 5 * np.sum(solution[:4] ** 2) - np.sum(solution[4:13]) - - ## Increase the punishment for g1 and g4 to boost the algorithm (You can choice any constraint instead of g1 and g4) - fx += self.violate(self.g1(solution)) ** 2 + self.violate(self.g2(solution)) + self.violate(self.g3(solution)) + \ - 2 * self.violate(self.g4(solution)) + self.violate(self.g5(solution)) + self.violate(self.g6(solution)) + \ - self.violate(self.g7(solution)) + self.violate(self.g8(solution)) + self.violate(self.g9(solution)) - - return fx - - ## Create an instance of MOP class - bounds = FloatVar(lb=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ub=[1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1]), - problem_cop = COP(bounds=bounds, minmax="min") - - ## Define the model and solve the problem - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_cop) - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/custom_problem.rst b/docs/source/pages/general/advances/custom_problem.rst deleted file mode 100644 index 28e62306..00000000 --- a/docs/source/pages/general/advances/custom_problem.rst +++ /dev/null @@ -1,44 +0,0 @@ -Custom Problem -============== - - -For complex problems, we recommend that the user define a custom child class of the `Problem` class instead of defining the problem dictionary. -For instance, when training a neural network, the dataset needs to be passed to the fitness function. Defining a child class allows for passing any -additional data that may be needed. - - -.. code-block:: python - - from mealpy import PSO, FloatVar, Problem - - class NeuralNetwork(Problem): - def __init__(self, bounds=None, minmax, dataset=None, additional=None, **kwargs): - self.dataset = dataset - self.additional = additional - super().__init__(bounds, minmax, **kwargs) - - def obj_func(self, solution): - network = NET(self.dataset, self.additional) - obj = network.loss - return obj - - ## Create an instance of MOP class - problem_cop = COP(bounds=FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), name="Network", - dataset=dataset, additional=additional, minmax="min") - - ## Define the model and solve the problem - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_cop) - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - - - diff --git a/docs/source/pages/general/advances/discrete_optimization.rst b/docs/source/pages/general/advances/discrete_optimization.rst deleted file mode 100644 index 3823bd16..00000000 --- a/docs/source/pages/general/advances/discrete_optimization.rst +++ /dev/null @@ -1,54 +0,0 @@ -Discrete Optimization -===================== - -For this type of problem, we recommend creating a custom child class of the Problem class and overriding the necessary functions. -At a minimum, three functions should be overridden: - - * obj_func: the fitness function - * generate_position: a function that generate solution - * amend_position: a function that bring back the solution to the boundary - - -Let's say we want to solve Travelling Salesman Problem (TSP), - - -.. code-block:: python - - import numpy as np - from mealpy import PermutationVar ## For Travelling Salesman Problem, the solution should be a permutation - - - class DOP(Problem): - def __init__(self, bounds, minmax, CITY_POSITIONS=None, **kwargs): - self.CITY_POSITIONS = CITY_POSITIONS - super().__init__(bounds, minmax, **kwargs) - - def obj_func(self, solution): - ## Objective for this problem is the sum of distance between all cities that salesman has passed - ## This can be change depend on your requirements - x = self.decode_solution(solution)["per"] - city_coord = self.CITY_POSITIONS[x] - line_x = city_coord[:, 0] - line_y = city_coord[:, 1] - total_distance = np.sum(np.sqrt(np.square(np.diff(line_x)) + np.square(np.diff(line_y)))) - return total_distance - - - ## Create an instance of DOP class - problem_cop = DOP(bounds=PermutationVar(valid_set=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], name="per"), - minmax="min", log_to="file", log_file="dop-results.txt") - - ## Define the model and solve the problem - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_cop) - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/import_all_models.rst b/docs/source/pages/general/advances/import_all_models.rst deleted file mode 100644 index caa94ba1..00000000 --- a/docs/source/pages/general/advances/import_all_models.rst +++ /dev/null @@ -1,912 +0,0 @@ -Import All Models -================= - -.. code-block:: python - - from mealpy import BBO, BBOA, BMO, EOA, IWO, SBO, SMA, SOA, SOS, TPO, TSA, VCS, WHO, BCO, EAO - from mealpy import CRO, DE, EP, ES, FPA, GA, MA, SHADE - from mealpy import (BRO, BSO, CA, CHIO, FBIO, GSKA, HBO, HCO, ICA, LCO, QSA, SARO, SPBO, SSDO, - TLO, TOA, WarSO, AFT, CDDO) - from mealpy import AOA, CEM, CGO, CircleSA, GBO, HC, INFO, PSS, RUN, SCA, SHIO, TS - from mealpy import ArchOA, ASO, CDO, EFO, EO, EVO, FLA, HGSO, MVO, NRO, RIME, SA, TWO, WDO, ESO, SOO - from mealpy import (ABC, ACOR, AGTO, ALO, AO, ARO, AVOA, BA, BeesA, BES, BFO, BSA, COA, CoatiOA, CSA, CSO, - DMOA, DO, EHO, ESOA, FA, FFA, FFO, FOA, FOX, GJO, GOA, GTO, GWO, HBA, HGS, HHO, JA, - MFO, MGO, MPA, MRFO, MSA, NGO, NMRA, OOA, PFA, POA, PSO, SCSO, SeaHO, ServalOA, SFO, - SHO, SLO, SRSR, SSA, SSO, SSpiderA, SSpiderO, STO, TDO, TSO, WaOA, WOA, ZOA, - EPC, SMO, SquirrelSA, FDO) - from mealpy import AEO, GCO, WCA - from mealpy import HS - from mealpy import LSHADEcnEpSin, IMODE - - from mealpy import (IntegerVar, FloatVar, StringVar, BinaryVar, BoolVar, CategoricalVar, - SequenceVar, PermutationVar, TransferBinaryVar, TransferBoolVar) - - from mealpy import Tuner, Multitask, Problem, Optimizer, Termination, ParameterGrid - from mealpy import get_all_optimizers, get_optimizer_by_class, get_optimizer_by_name - import numpy as np - - def objective_function(solution): - return np.sum(solution ** 2) - - problem = { - "obj_func": objective_function, - "bounds": FloatVar(lb=[-3] * 20, ub=[5] * 20), - "name": "Squared Problem", - "log_to": "file", - "log_file": "results.log" - } - - paras_bbo = { - "epoch": 20, - "pop_size": 50, - "p_m": 0.01, - "elites": 2, - } - paras_eoa = { - "epoch": 20, - "pop_size": 50, - "p_c": 0.9, - "p_m": 0.01, - "n_best": 2, - "alpha": 0.98, - "beta": 0.9, - "gamma": 0.9, - } - paras_iwo = { - "epoch": 20, - "pop_size": 50, - "seed_min": 3, - "seed_max": 9, - "exponent": 3, - "sigma_start": 0.6, - "sigma_end": 0.01, - } - paras_sbo = { - "epoch": 20, - "pop_size": 50, - "alpha": 0.9, - "p_m": 0.05, - "psw": 0.02, - } - paras_sma = { - "epoch": 20, - "pop_size": 50, - "p_t": 0.03, - } - paras_vcs = { - "epoch": 20, - "pop_size": 50, - "lamda": 0.5, - "sigma": 0.3, - } - paras_who = { - "epoch": 20, - "pop_size": 50, - "n_explore_step": 3, - "n_exploit_step": 3, - "eta": 0.15, - "p_hi": 0.9, - "local_alpha": 0.9, - "local_beta": 0.3, - "global_alpha": 0.2, - "global_beta": 0.8, - "delta_w": 2.0, - "delta_c": 2.0, - } - paras_cro = { - "epoch": 20, - "pop_size": 50, - "po": 0.4, - "Fb": 0.9, - "Fa": 0.1, - "Fd": 0.1, - "Pd": 0.5, - "GCR": 0.1, - "gamma_min": 0.02, - "gamma_max": 0.2, - "n_trials": 5, - } - paras_ocro = dict(paras_cro) - paras_ocro["restart_count"] = 5 - - paras_de = { - "epoch": 20, - "pop_size": 50, - "wf": 0.7, - "cr": 0.9, - "strategy": 0, - } - paras_jade = { - "epoch": 20, - "pop_size": 50, - "miu_f": 0.5, - "miu_cr": 0.5, - "pt": 0.1, - "ap": 0.1, - } - paras_sade = { - "epoch": 20, - "pop_size": 50, - } - paras_shade = paras_lshade = { - "epoch": 20, - "pop_size": 50, - "miu_f": 0.5, - "miu_cr": 0.5, - } - paras_sap_de = { - "epoch": 20, - "pop_size": 50, - "branch": "ABS" - } - paras_ep = paras_levy_ep = { - "epoch": 20, - "pop_size": 50, - "bout_size": 0.05 - } - paras_es = paras_levy_es = { - "epoch": 20, - "pop_size": 50, - "lamda": 0.75 - } - paras_fpa = { - "epoch": 20, - "pop_size": 50, - "p_s": 0.8, - "levy_multiplier": 0.2 - } - paras_ga = { - "epoch": 20, - "pop_size": 50, - "pc": 0.9, - "pm": 0.05, - } - paras_single_ga = { - "epoch": 20, - "pop_size": 50, - "pc": 0.9, - "pm": 0.8, - "selection": "roulette", - "crossover": "uniform", - "mutation": "swap", - } - paras_multi_ga = { - "epoch": 20, - "pop_size": 50, - "pc": 0.9, - "pm": 0.05, - "selection": "roulette", - "crossover": "uniform", - "mutation": "swap", - } - paras_ma = { - "epoch": 20, - "pop_size": 50, - "pc": 0.85, - "pm": 0.15, - "p_local": 0.5, - "max_local_gens": 10, - "bits_per_param": 4, - } - - paras_bro = { - "epoch": 20, - "pop_size": 50, - "threshold": 3, - } - paras_improved_bso = { - "epoch": 20, - "pop_size": 50, - "m_clusters": 5, - "p1": 0.2, - "p2": 0.8, - "p3": 0.4, - "p4": 0.5, - } - paras_bso = dict(paras_improved_bso) - paras_bso["slope"] = 20 - paras_ca = { - "epoch": 20, - "pop_size": 50, - "accepted_rate": 0.15, - } - paras_chio = { - "epoch": 20, - "pop_size": 50, - "brr": 0.15, - "max_age": 3 - } - paras_fbio = { - "epoch": 20, - "pop_size": 50, - } - paras_base_gska = { - "epoch": 20, - "pop_size": 50, - "pb": 0.1, - "kr": 0.9, - } - paras_gska = { - "epoch": 20, - "pop_size": 50, - "pb": 0.1, - "kf": 0.5, - "kr": 0.9, - "kg": 5, - } - paras_ica = { - "epoch": 20, - "pop_size": 50, - "empire_count": 5, - "assimilation_coeff": 1.5, - "revolution_prob": 0.05, - "revolution_rate": 0.1, - "revolution_step_size": 0.1, - "zeta": 0.1, - } - paras_lco = { - "epoch": 20, - "pop_size": 50, - "r1": 2.35, - } - paras_improved_lco = { - "epoch": 20, - "pop_size": 50, - } - paras_qsa = { - "epoch": 20, - "pop_size": 50, - } - paras_saro = { - "epoch": 20, - "pop_size": 50, - "se": 0.5, - "mu": 15 - } - paras_ssdo = { - "epoch": 20, - "pop_size": 50, - } - paras_tlo = { - "epoch": 20, - "pop_size": 50, - } - paras_improved_tlo = { - "epoch": 20, - "pop_size": 50, - "n_teachers": 5, - } - - paras_aoa = { - "epoch": 20, - "pop_size": 50, - "alpha": 5, - "miu": 0.5, - "moa_min": 0.2, - "moa_max": 0.9, - } - paras_cem = { - "epoch": 20, - "pop_size": 50, - "n_best": 20, - "alpha": 0.7, - } - paras_cgo = { - "epoch": 20, - "pop_size": 50, - } - paras_gbo = { - "epoch": 20, - "pop_size": 50, - "pr": 0.5, - "beta_min": 0.2, - "beta_max": 1.2, - } - paras_hc = { - "epoch": 20, - "pop_size": 50, - "neighbour_size": 50 - } - paras_swarm_hc = { - "epoch": 20, - "pop_size": 50, - "neighbour_size": 10 - } - paras_pss = { - "epoch": 20, - "pop_size": 50, - "acceptance_rate": 0.8, - "sampling_method": "LHS", - } - paras_sca = { - "epoch": 20, - "pop_size": 50, - } - - paras_hs = { - "epoch": 20, - "pop_size": 50, - "c_r": 0.95, - "pa_r": 0.05 - } - - paras_aeo = { - "epoch": 20, - "pop_size": 50, - } - paras_gco = { - "epoch": 20, - "pop_size": 50, - "cr": 0.7, - "wf": 1.25, - } - paras_wca = { - "epoch": 20, - "pop_size": 50, - "nsr": 4, - "wc": 2.0, - "dmax": 1e-6 - } - - paras_archoa = { - "epoch": 20, - "pop_size": 50, - "c1": 2, - "c2": 5, - "c3": 2, - "c4": 0.5, - "acc_max": 0.9, - "acc_min": 0.1, - } - paras_aso = { - "epoch": 20, - "pop_size": 50, - "alpha": 50, - "beta": 0.2, - } - paras_efo = { - "epoch": 20, - "pop_size": 50, - "r_rate": 0.3, - "ps_rate": 0.85, - "p_field": 0.1, - "n_field": 0.45, - } - paras_eo = { - "epoch": 20, - "pop_size": 50, - } - paras_hgso = { - "epoch": 20, - "pop_size": 50, - "n_clusters": 3, - } - paras_mvo = { - "epoch": 20, - "pop_size": 50, - "wep_min": 0.2, - "wep_max": 1.0, - } - paras_nro = { - "epoch": 20, - "pop_size": 50, - } - paras_sa = { - "epoch": 20, - "pop_size": 50, - "max_sub_iter": 5, - "t0": 1000, - "t1": 1, - "move_count": 5, - "mutation_rate": 0.1, - "mutation_step_size": 0.1, - "mutation_step_size_damp": 0.99, - } - paras_two = { - "epoch": 20, - "pop_size": 50, - } - paras_wdo = { - "epoch": 20, - "pop_size": 50, - "RT": 3, - "g_c": 0.2, - "alp": 0.4, - "c_e": 0.4, - "max_v": 0.3, - } - - paras_abc = { - "epoch": 20, - "pop_size": 50, - "n_elites": 16, - "n_others": 4, - "patch_size": 5.0, - "patch_reduction": 0.985, - "n_sites": 3, - "n_elite_sites": 1, - } - paras_acor = { - "epoch": 20, - "pop_size": 50, - "sample_count": 25, - "intent_factor": 0.5, - "zeta": 1.0, - } - paras_alo = { - "epoch": 20, - "pop_size": 50, - } - paras_ao = { - "epoch": 20, - "pop_size": 50, - } - paras_ba = { - "epoch": 20, - "pop_size": 50, - "loudness": 0.8, - "pulse_rate": 0.95, - "pf_min": 0., - "pf_max": 10., - } - paras_adaptive_ba = { - "epoch": 20, - "pop_size": 50, - "loudness_min": 1.0, - "loudness_max": 2.0, - "pr_min": 0.15, - "pr_max": 0.85, - "pf_min": 0., - "pf_max": 10., - } - paras_dev_ba = { - "epoch": 20, - "pop_size": 50, - "pulse_rate": 0.95, - "pf_min": 0., - "pf_max": 10., - } - paras_beesa = { - "epoch": 20, - "pop_size": 50, - "selected_site_ratio": 0.5, - "elite_site_ratio": 0.4, - "selected_site_bee_ratio": 0.1, - "elite_site_bee_ratio": 2.0, - "dance_radius": 0.1, - "dance_reduction": 0.99, - } - paras_prob_beesa = { - "epoch": 20, - "pop_size": 50, - "recruited_bee_ratio": 0.1, - "dance_radius": 0.1, - "dance_reduction": 0.99, - } - paras_bes = { - "epoch": 20, - "pop_size": 50, - "a_factor": 10, - "R_factor": 1.5, - "alpha": 2.0, - "c1": 2.0, - "c2": 2.0, - } - paras_bfo = { - "epoch": 20, - "pop_size": 50, - "Ci": 0.01, - "Ped": 0.25, - "Nc": 5, - "Ns": 4, - "d_attract": 0.1, - "w_attract": 0.2, - "h_repels": 0.1, - "w_repels": 10, - } - paras_abfo = { - "epoch": 20, - "pop_size": 50, - "C_s": 0.1, - "C_e": 0.001, - "Ped": 0.01, - "Ns": 4, - "N_adapt": 4, - "N_split": 40, - } - paras_bsa = { - "epoch": 20, - "pop_size": 50, - "ff": 10, - "pff": 0.8, - "c1": 1.5, - "c2": 1.5, - "a1": 1.0, - "a2": 1.0, - "fl": 0.5, - } - paras_coa = { - "epoch": 20, - "pop_size": 50, - "n_coyotes": 5, - } - paras_csa = { - "epoch": 20, - "pop_size": 50, - "p_a": 0.3, - } - paras_cso = { - "epoch": 20, - "pop_size": 50, - "mixture_ratio": 0.15, - "smp": 5, - "spc": False, - "cdc": 0.8, - "srd": 0.15, - "c1": 0.4, - "w_min": 0.4, - "w_max": 0.9, - "selected_strategy": 1, - } - paras_do = { - "epoch": 20, - "pop_size": 50, - } - paras_eho = { - "epoch": 20, - "pop_size": 50, - "alpha": 0.5, - "beta": 0.5, - "n_clans": 5, - } - paras_fa = { - "epoch": 20, - "pop_size": 50, - "max_sparks": 20, - "p_a": 0.04, - "p_b": 0.8, - "max_ea": 40, - "m_sparks": 5, - } - paras_ffa = { - "epoch": 20, - "pop_size": 50, - "gamma": 0.001, - "beta_base": 2, - "alpha": 0.2, - "alpha_damp": 0.99, - "delta": 0.05, - "exponent": 2, - } - paras_foa = { - "epoch": 20, - "pop_size": 50, - } - paras_goa = { - "epoch": 20, - "pop_size": 50, - "c_min": 0.00004, - "c_max": 1.0, - } - paras_gwo = { - "epoch": 20, - "pop_size": 50, - } - paras_hgs = { - "epoch": 20, - "pop_size": 50, - "PUP": 0.08, - "LH": 10000, - } - paras_hho = { - "epoch": 20, - "pop_size": 50, - } - paras_ja = { - "epoch": 20, - "pop_size": 50, - } - paras_mfo = { - "epoch": 20, - "pop_size": 50, - } - paras_mrfo = { - "epoch": 20, - "pop_size": 50, - "somersault_range": 2.0, - } - paras_msa = { - "epoch": 20, - "pop_size": 50, - "n_best": 5, - "partition": 0.5, - "max_step_size": 1.0, - } - paras_nmra = { - "epoch": 20, - "pop_size": 50, - "pb": 0.75, - } - paras_improved_nmra = { - "epoch": 20, - "pop_size": 50, - "pb": 0.75, - "pm": 0.01, - } - paras_pfa = { - "epoch": 20, - "pop_size": 50, - } - paras_pso = { - "epoch": 20, - "pop_size": 50, - "c1": 2.05, - "c2": 2.05, - "w_min": 0.4, - "w_max": 0.9, - } - paras_ppso = { - "epoch": 20, - "pop_size": 50, - } - paras_hpso_tvac = { - "epoch": 20, - "pop_size": 50, - "ci": 0.5, - "cf": 0.0, - } - paras_cpso = { - "epoch": 20, - "pop_size": 50, - "c1": 2.05, - "c2": 2.05, - "w_min": 0.4, - "w_max": 0.9, - } - paras_clpso = { - "epoch": 20, - "pop_size": 50, - "c_local": 1.2, - "w_min": 0.4, - "w_max": 0.9, - "max_flag": 7, - } - paras_sfo = { - "epoch": 20, - "pop_size": 50, - "pp": 0.1, - "AP": 4.0, - "epsilon": 0.0001, - } - paras_improved_sfo = { - "epoch": 20, - "pop_size": 50, - "pp": 0.1, - } - paras_sho = { - "epoch": 20, - "pop_size": 50, - "h_factor": 5.0, - "N_tried": 10, - } - paras_slo = paras_modified_slo = { - "epoch": 20, - "pop_size": 50, - } - paras_improved_slo = { - "epoch": 20, - "pop_size": 50, - "c1": 1.2, - "c2": 1.2 - } - paras_srsr = { - "epoch": 20, - "pop_size": 50, - } - paras_ssa = { - "epoch": 20, - "pop_size": 50, - "ST": 0.8, - "PD": 0.2, - "SD": 0.1, - } - paras_sso = { - "epoch": 20, - "pop_size": 50, - } - paras_sspidera = { - "epoch": 20, - "pop_size": 50, - "r_a": 1.0, - "p_c": 0.7, - "p_m": 0.1 - } - paras_sspidero = { - "epoch": 20, - "pop_size": 50, - "fp_min": 0.65, - "fp_max": 0.9 - } - paras_woa = { - "epoch": 20, - "pop_size": 50, - } - paras_hi_woa = { - "epoch": 20, - "pop_size": 50, - "feedback_max": 10 - } - - if __name__ == "__main__": - model = BBO.DevBBO(**paras_bbo) - model = BBO.OriginalBBO(**paras_bbo) - model = EOA.OriginalEOA(**paras_eoa) - model = IWO.OriginalIWO(**paras_eoa) - model = SBO.DevSBO(**paras_sbo) - model = SBO.OriginalSBO(**paras_sbo) - model = SMA.DevSMA(**paras_sma) - model = SMA.OriginalSMA(**paras_sma) - model = VCS.DevVCS(**paras_vcs) - model = VCS.OriginalVCS(**paras_vcs) - model = WHO.OriginalWHO(**paras_vcs) - - model = CRO.OriginalCRO(**paras_cro) - model = CRO.OCRO(**paras_ocro) - # model = DE.BaseDE(**paras_de) - model = DE.JADE(**paras_jade) - model = DE.SADE(**paras_sade) - model = SHADE.OriginalSHADE(**paras_shade) - model = SHADE.L_SHADE(**paras_lshade) - model = DE.SAP_DE(**paras_sap_de) - model = EP.OriginalEP(**paras_ep) - model = EP.LevyEP(**paras_levy_ep) - model = ES.OriginalES(**paras_ep) - model = ES.LevyES(**paras_levy_ep) - model = FPA.OriginalFPA(**paras_fpa) - model = GA.BaseGA(**paras_ga) - model = GA.SingleGA(**paras_single_ga) - model = GA.MultiGA(**paras_multi_ga) - model = MA.OriginalMA(**paras_ma) - - model = BRO.DevBRO(**paras_bro) - model = BRO.OriginalBRO(**paras_bro) - model = BSO.OriginalBSO(**paras_bso) - model = BSO.ImprovedBSO(**paras_improved_bso) - model = CA.OriginalCA(**paras_ca) - model = CHIO.DevCHIO(**paras_chio) - model = CHIO.OriginalCHIO(**paras_chio) - model = FBIO.DevFBIO(**paras_fbio) - model = FBIO.OriginalFBIO(**paras_fbio) - model = GSKA.DevGSKA(**paras_base_gska) - model = GSKA.OriginalGSKA(**paras_gska) - model = ICA.OriginalICA(**paras_ica) - model = LCO.DevLCO(**paras_lco) - model = LCO.OriginalLCO(**paras_lco) - model = LCO.ImprovedLCO(**paras_improved_lco) - model = QSA.DevQSA(**paras_qsa) - model = QSA.OriginalQSA(**paras_qsa) - model = QSA.OppoQSA(**paras_qsa) - model = QSA.LevyQSA(**paras_qsa) - model = QSA.ImprovedQSA(**paras_qsa) - model = SARO.DevSARO(**paras_saro) - model = SARO.OriginalSARO(**paras_saro) - model = SSDO.OriginalSSDO(**paras_ssdo) - model = TLO.DevTLO(**paras_tlo) - model = TLO.OriginalTLO(**paras_tlo) - model = TLO.ImprovedTLO(**paras_improved_tlo) - - model = AOA.OriginalAOA(**paras_aoa) - model = CEM.OriginalCEM(**paras_cem) - model = CGO.OriginalCGO(**paras_cgo) - model = GBO.OriginalGBO(**paras_gbo) - model = HC.OriginalHC(**paras_hc) - model = HC.SwarmHC(**paras_swarm_hc) - model = PSS.OriginalPSS(**paras_pss) - model = SCA.OriginalSCA(**paras_sca) - model = SCA.DevSCA(**paras_sca) - - model = HS.DevHS(**paras_hs) - model = HS.OriginalHS(**paras_hs) - - model = AEO.OriginalAEO(**paras_aeo) - model = AEO.EnhancedAEO(**paras_aeo) - model = AEO.ModifiedAEO(**paras_aeo) - model = AEO.ImprovedAEO(**paras_aeo) - model = AEO.AugmentedAEO(**paras_aeo) - model = GCO.DevGCO(**paras_aeo) - model = GCO.OriginalGCO(**paras_aeo) - model = WCA.OriginalWCA(**paras_wca) - - model = ArchOA.OriginalArchOA(**paras_archoa) - model = ASO.OriginalASO(**paras_aso) - model = EFO.OriginalEFO(**paras_efo) - model = EFO.DevEFO(**paras_efo) - model = EO.OriginalEO(**paras_eo) - model = EO.AdaptiveEO(**paras_eo) - model = EO.ModifiedEO(**paras_eo) - model = HGSO.OriginalHGSO(**paras_hgso) - model = MVO.OriginalMVO(**paras_mvo) - model = NRO.OriginalNRO(**paras_nro) - model = SA.OriginalSA(**paras_sa) - model = SA.SwarmSA(**paras_sa) - model = SA.GaussianSA(**paras_sa) - model = TWO.OriginalTWO(**paras_two) - model = TWO.OppoTWO(**paras_two) - model = TWO.LevyTWO(**paras_two) - model = TWO.EnhancedTWO(**paras_two) - model = WDO.OriginalWDO(**paras_wdo) - - model = ABC.OriginalABC(**paras_abc) - model = ACOR.OriginalACOR(**paras_acor) - model = ALO.OriginalALO(**paras_alo) - model = AO.OriginalAO(**paras_ao) - model = ALO.DevALO(**paras_alo) - model = BA.OriginalBA(**paras_ba) - model = BA.AdaptiveBA(**paras_adaptive_ba) - model = BA.DevBA(**paras_dev_ba) - model = BeesA.OriginalBeesA(**paras_beesa) - model = BeesA.ProbBeesA(**paras_prob_beesa) - model = BES.OriginalBES(**paras_bes) - model = BFO.OriginalBFO(**paras_bfo) - model = BFO.ABFO(**paras_abfo) - model = BSA.OriginalBSA(**paras_bsa) - model = COA.OriginalCOA(**paras_coa) - model = CSA.OriginalCSA(**paras_csa) - model = CSO.OriginalCSO(**paras_cso) - model = DO.OriginalDO(**paras_do) - model = EHO.OriginalEHO(**paras_eho) - model = FA.OriginalFA(**paras_fa) - model = FFA.OriginalFFA(**paras_ffa) - model = FOA.OriginalFOA(**paras_foa) - model = FOA.DevFOA(**paras_foa) - model = FOA.WhaleFOA(**paras_foa) - model = GOA.OriginalGOA(**paras_goa) - model = GWO.OriginalGWO(**paras_gwo) - model = GWO.RW_GWO(**paras_gwo) - model = HGS.OriginalHGS(**paras_hgs) - model = HHO.OriginalHHO(**paras_hho) - model = JA.OriginalJA(**paras_ja) - model = JA.DevJA(**paras_ja) - model = JA.LevyJA(**paras_ja) - model = MFO.OriginalMFO(**paras_mfo) - # model = MFO.BaseMFO(**paras_mfo) - model = MRFO.OriginalMRFO(**paras_mrfo) - model = MSA.OriginalMSA(**paras_msa) - model = NMRA.ImprovedNMRA(**paras_improved_nmra) - model = NMRA.OriginalNMRA(**paras_nmra) - model = PFA.OriginalPFA(**paras_pfa) - model = PSO.OriginalPSO(**paras_pso) - model = PSO.P_PSO(**paras_ppso) - model = PSO.HPSO_TVAC(**paras_hpso_tvac) - model = PSO.C_PSO(**paras_cpso) - model = PSO.CL_PSO(**paras_clpso) - model = SFO.OriginalSFO(**paras_sfo) - model = SFO.ImprovedSFO(**paras_improved_sfo) - model = SHO.OriginalSHO(**paras_sho) - model = SLO.OriginalSLO(**paras_slo) - model = SLO.ModifiedSLO(**paras_modified_slo) - model = SLO.ImprovedSLO(**paras_improved_slo) - model = SRSR.OriginalSRSR(**paras_srsr) - model = SSA.OriginalSSA(**paras_ssa) - model = SSA.DevSSA(**paras_ssa) - model = SSO.OriginalSSO(**paras_sso) - model = SSpiderA.OriginalSSpiderA(**paras_sspidera) - model = SSpiderO.OriginalSSpiderO(**paras_sspidero) - model = WOA.OriginalWOA(**paras_woa) - model = WOA.HI_WOA(**paras_hi_woa) - - g_best = model.solve(problem) - print(model.get_parameters()) - print(model.get_name()) - print(model.problem.get_name()) - print(model.get_attributes()["g_best"]) - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/general/advances/log_training_process.rst b/docs/source/pages/general/advances/log_training_process.rst deleted file mode 100644 index 619330e3..00000000 --- a/docs/source/pages/general/advances/log_training_process.rst +++ /dev/null @@ -1,60 +0,0 @@ -Log Training Process -==================== - -We currently offer three logging options: printing the training process on the console, logging the training process to a file, and not displaying or saving -the log process. - -* By default, if the "log_to" keyword is not declared in the problem dictionary, it will be logged to the console. - -.. code-block:: python - - problem_dict1 = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - # Default = "console" - } - - problem_dict1 = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "log_to": "console", - } - - -* If you want to log to the file, you need an additional keyword "log_file", - -.. code-block:: python - - problem_dict2 = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "log_to": "file", - "log_file": "result.log", # Default value = "mealpy.log" - } - - -* Set it to None if you don't want to log - -.. code-block:: python - - problem_dict3 = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "log_to": None, - } - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/model_parameter.rst b/docs/source/pages/general/advances/model_parameter.rst deleted file mode 100644 index 2a6f6eb7..00000000 --- a/docs/source/pages/general/advances/model_parameter.rst +++ /dev/null @@ -1,94 +0,0 @@ -Model's Parameters -================== - -**1. Hint Validation for setting up the hyper-parameters:** - -If you are unsure how to set up a parameter for the optimizer, you can try setting it to any value. The optimizer will then provide a "hint validation" that -can help you determine how to set valid parameters. - - -.. code-block:: python - - model = PSO.OriginalPSO(epoch="hello", pop_size="world") - model.solve(problem) - - # $ 2022/03/22 08:59:16 AM, ERROR, mealpy.utils.validator.Validator [line: 31]: 'epoch' is an integer and value should be in range: [1, 100000]. - - model = PSO.OriginalPSO(epoch=10, pop_size="world") - model.solve(problem) - - # $ 2022/03/22 09:01:51 AM, ERROR, mealpy.utils.validator.Validator [line: 31]: 'pop_size' is an integer and value should be in range: [10, 10000]. - - - -**2. Set up model's parameters as a dictionary:** - -.. code-block:: python - - from mealpy import DE, FloatVar - - problem = { - "obj_func": F5, - "bounds": FloatVar(lb=[-10,]*10, ub=[30,]*10), - "minmax": "min", - } - - paras_de = { - "epoch": 20, - "pop_size": 50, - "wf": 0.7, - "cr": 0.9, - "strategy": 0, - } - - model = DE.OriginalDE(**paras_de) - model.solve(problem) - - -This will definitely be helpful when using ParameterGrid/GridSearchCV from the scikit-learn library to tune the parameter of the models. For example; - - -.. code-block:: python - - from sklearn.model_selection import ParameterGrid - from mealpy import DE, FloatVar - - problem = { - "obj_func": F5, - "bounds": FloatVar(lb=[-10,]*10, ub=[30,]*10), - "minmax": "min", - } - - paras_de_grid = { - "epoch": [100, 200, 300, 500, 1000], - "pop_size": [50, 100], - "wf": [0.5, 0.6, 0.7, 0.8, 0.9], - "cr": [0.6, 0.7, 0.8, 0.9], - "strategy": [0, 1, 2, 3, 4], - } - - for paras_de in list(ParameterGrid(paras_de_grid)): - model = DE.OriginalDE(**paras_de) - model.solve(problem) - - -**3. Get the parameters of the model** - -Using the method below will return the model's parameters as a Python dictionary. If you want to convert it to a string, we recommend using the built-in -Python method: str(). - -.. code-block:: python - - model.get_parameters() # Return dictionary - - str(model.get_parameter()) # Return a string - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/general/advances/model_problem_name.rst b/docs/source/pages/general/advances/model_problem_name.rst deleted file mode 100644 index fc2575c5..00000000 --- a/docs/source/pages/general/advances/model_problem_name.rst +++ /dev/null @@ -1,47 +0,0 @@ -Set Up Model's/Problem's Name -============================= - -You do not necessarily need to set names for the optimizer and the problem, but doing so can help in saving results with the names of the model and the -problem, especially in multitask problems. - - -**1. Name the problem:** - -.. code-block:: python - - from mealpy.swarm_based import PSO - - problem = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "name": "Benchmark Function 5th" - } - - -**2. Name the optimizer model:** - -.. code-block:: python - - model = PSO.OriginalPSO(epoch=10, pop_size=50, name="Normal PSO") - model.solve(problem=problem) - - -**3. Get the name of problem and model** - - -.. code-block:: python - - print(model.name) # Normal PSO - print(model.problem.name) # Benchmark Function 5th - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/general/advances/multi_objective_optimization.rst b/docs/source/pages/general/advances/multi_objective_optimization.rst deleted file mode 100644 index 79ee3370..00000000 --- a/docs/source/pages/general/advances/multi_objective_optimization.rst +++ /dev/null @@ -1,84 +0,0 @@ -Multi-objective Optimization -============================ - -We currently offer a "weighting method" to solve multi-objective optimization problems. All you need to do is define your objective function, which returns a -list of objective values, and set the objective weights corresponding to each value. - - * obj_func: Your objective function. - * bounds: A list or an instance of problem type. - * minmax: Indicates whether the problem you are trying to solve is a minimum or maximum. The value can be "min" or "max". - * obj_weights: Optional list of weights for all of your objectives. The default is [1, 1, ..., 1]. - - -* Declare problem dictionary with "obj_weights": - -.. code-block:: python - - import numpy as np - from mealpy import PSO, FloatVar, Problem - - ## This is how you design multi-objective function - #### Link: https://en.wikipedia.org/wiki/Test_functions_for_optimization - def objective_multi(solution): - def booth(x, y): - return (x + 2*y - 7)**2 + (2*x + y - 5)**2 - def bukin(x, y): - return 100 * np.sqrt(np.abs(y - 0.01 * x**2)) + 0.01 * np.abs(x + 10) - def matyas(x, y): - return 0.26 * (x**2 + y**2) - 0.48 * x * y - return [booth(solution[0], solution[1]), bukin(solution[0], solution[1]), matyas(solution[0], solution[1])] - - ## Design a problem dictionary for multiple objective functions above - problem_multi = { - "obj_func": objective_multi, - "bounds": FloatVar(lb=[-10, -10], ub=[10, 10]), - "minmax": "min", - "obj_weights": [0.4, 0.1, 0.5] # Define it or default value will be [1, 1, 1] - } - - ## Define the model and solve the problem - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_multi) - - - -* Declare a custom Problem class: - -.. code-block:: python - - import numpy as np - from mealpy import PSO, FloatVar, Problem - - ## Define a custom child class of Problem class. - class MOP(Problem): - def __init__(self, bounds=None, minmax="min", **kwargs): - super().__init__(bounds, minmax, **kwargs) - - def booth(x, y): - return (x + 2*y - 7)**2 + (2*x + y - 5)**2 - def bukin(x, y): - return 100 * np.sqrt(np.abs(y - 0.01 * x**2)) + 0.01 * np.abs(x + 10) - def matyas(x, y): - return 0.26 * (x**2 + y**2) - 0.48 * x * y - - def obj_func(self, solution): - return [self.booth(solution[0], solution[1]), self.bukin(solution[0], solution[1]), self.matyas(solution[0], solution[1])] - - ## Create an instance of MOP class - problem_multi = MOP(bounds=FloatVar(lb=[-10, ] * 2, ub=[10, ] * 2), minmax="min", obj_weights=[0.4, 0.1, 0.5]) - - ## Define the model and solve the problem - model = PSO.OriginalPSO(epoch=1000, pop_size=50) - model.solve(problem=problem_multi) - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/reproducibility.rst b/docs/source/pages/general/advances/reproducibility.rst deleted file mode 100644 index 5336ec26..00000000 --- a/docs/source/pages/general/advances/reproducibility.rst +++ /dev/null @@ -1,57 +0,0 @@ -Reproducibility (Set Seed) -========================== - -By default, the `seed` parameter is set to `None`. When `seed=None`, the algorithm will use a different random seed each time it runs, leading to potentially different results across multiple executions. - -However, if you set a specific integer value for `seed`, the algorithm will produce the exact same results every time it is run with that particular seed. -This is crucial for debugging, verifying performance, and ensuring that your experiments are reproducible. - -For scenarios where you need to run the algorithm multiple times (e.g., n-trials for statistical analysis) while still maintaining reproducibility -for each individual trial, it is best practice to set a *different* seed for each trial. This allows you to recreate each specific trial's outcome if needed, -while still exploring the stochastic nature of the algorithm across different runs. - -.. code-block:: python - - from mealpy import SMA - - # Assuming 'problem' is already defined, e.g.: - # problem = { - # "obj_func": lambda solution: sum(x**2 for x in solution), - # "bounds": FloatVar(lb=(-10., )*30, ub=(10., )*30), - # "minmax": "min", - # } - - # Example 1: Running with default seed (None) - results may vary each time - model_default = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best_default = model_default.solve(problem=problem) - print(f"Run 1 (default seed) - Best fitness: {g_best_default.target.fitness}") - - g_best_default_2 = model_default.solve(problem=problem) # Rerunning the same model instance might reset some internal states, but generally results will differ due to new random seed - print(f"Run 2 (default seed) - Best fitness: {g_best_default_2.target.fitness}") - - # Example 2: Running with a specific seed - results will be identical for seed=10 - model_seeded_1 = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best_seeded_1 = model_seeded_1.solve(problem=problem, seed=10) - print(f"Run with seed=10 - Best fitness: {g_best_seeded_1.target.fitness}") - - model_seeded_2 = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) # Create a new model instance for clarity - g_best_seeded_2 = model_seeded_2.solve(problem=problem, seed=10) - print(f"Run with seed=10 (again) - Best fitness: {g_best_seeded_2.target.fitness}") # This will yield the same fitness as above - - # Example 3: Running multiple trials with different seeds for reproducibility of each trial - print("\nRunning 3 trials with different seeds:") - for i in range(3): - current_seed = 100 + i # Use a unique seed for each trial - model_trial = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best_trial = model_trial.solve(problem=problem, seed=current_seed) - print(f" Trial {i+1} (seed={current_seed}) - Best fitness: {g_best_trial.target.fitness}") - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/general/advances/saving_loading.rst b/docs/source/pages/general/advances/saving_loading.rst deleted file mode 100644 index eeecbe03..00000000 --- a/docs/source/pages/general/advances/saving_loading.rst +++ /dev/null @@ -1,59 +0,0 @@ -Saving and Loading Model -======================== - -Based on the tutorials above, we know that we can save the population after each epoch in the model by setting "save_population" to True in the problem dictionary. - -.. code-block:: python - - problem_dict1 = { - "obj_func": F5, - "bounds": FloatVar(lb=[-3, -5, 1, -10, ], ub=[5, 10, 100, 30, ]), - "minmax": "min", - "log_to": "console", - "save_population": True, # Default = False - } - - -However, as a warning, if your problem is too big, setting "save_population" to True can cause memory issues when running the model. It is also important to -note that "save_population" here means storing the population of each epoch in the model's history object, and not saving the model to a file. To save and -load the optimizer from a file, you will need to use the "io" module from "mealpy.utils". - - -.. code-block:: python - :emphasize-lines: 3,21,24 - - import numpy as np - from mealpy import GA, FloatVar, Problem - from mealpy.utils import io - - def objective_function(solution): - return np.sum(solution**2) - - problem = { - "obj_func": objective_function, - "bounds": FloatVar(lb=[-100, ] * 50, ub=[100, ] * 50), - "minmax": "min", - } - - ## Run the algorithm - model = BaseGA(epoch=100, pop_size=50) - g_best = model.solve(problem) - print(f"Best solution: {g_best.solution}, Best fitness: {g_best.target.fitness}") - - ## Save model to file - io.save_model(model, "results/model.pkl") - - ## Load the model from file - optimizer = io.load_model("results/model.pkl") - print(f"Best solution: {optimizer.g_best.solution}, Best fitness: {optimizer.g_best.target.fitness}") - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/starting_positions.rst b/docs/source/pages/general/advances/starting_positions.rst deleted file mode 100644 index b661de32..00000000 --- a/docs/source/pages/general/advances/starting_positions.rst +++ /dev/null @@ -1,57 +0,0 @@ -Starting Solutions -================== - -Not recommended to use this utility. But in case you need this: - -.. code-block:: python - - from mealpy import TLO, FloatVar - import numpy as np - - - def frequency_modulated(pos): - # range: [-6.4, 6.35], f(X*) = 0, phi = 2pi / 100 - phi = 2 * np.pi / 100 - result = 0 - for t in range(0, 101): - y_t = pos[0] * np.sin(pos[3] * t * phi + pos[1]*np.sin(pos[4] * t * phi + pos[2] * np.sin(pos[5] * t * phi))) - y_t0 = 1.0 * np.sin(5.0 * t * phi - 1.5 * np.sin(4.8 * t * phi + 2.0 * np.sin(4.9 * t * phi))) - result += (y_t - y_t0)**2 - return result - - fm_problem = { - "obj_func": frequency_modulated, - "bounds": FloatVar(lb=[-6.4, ] * 6, ub=[6.35, ] * 6), - "minmax": "min", - "log_to": "console", - } - - ## This is an example I use to create starting positions - ## Write your own function, remember the starting positions has to be: list of N vectors or 2D matrix of position vectors - def create_starting_solutions(n_dims=None, pop_size=None, num=1): - return np.ones((pop_size, n_dims)) * num + np.random.uniform(-1, 1) - - ## Define the model - model = TLO.OriginalTLO(epoch=100, pop_size=50) - - ## Input your starting positions here - list_pos = create_starting_solutions(6, 50, 2) - best_agent = model.solve(fm_problem, starting_solutions=list_pos) ## Remember the keyword: starting_solutions - print(f"Best solution: {model.g_best.solution}, Best fitness: {best_agent.target.fitness}") - - ## Training with other starting positions - list_pos2 = create_starting_solutions(6, 50, -1) - best_agent = model.solve(fm_problem, starting_solutions=list_pos2) - print(f"Best solution: {model.g_best.solution}, Best fitness: {best_agent.target.fitness}") - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/advances/termination.rst b/docs/source/pages/general/advances/termination.rst deleted file mode 100644 index a0d049e3..00000000 --- a/docs/source/pages/general/advances/termination.rst +++ /dev/null @@ -1,119 +0,0 @@ -Stopping Condition (Termination) -================================ - -In meta-heuristic algorithms, the optimization process involves iteratively generating and evolving a population of candidate solutions (individuals) to the -problem. Each generation consists of evaluating the fitness of each individual, selecting the best individuals for reproduction, and applying some specific -operators to generate a new population. By setting a maximum number of generations as a stopping condition, the algorithm will terminate after a certain -number of iterations, even if a satisfactory solution has not been found. This can be useful to prevent the algorithm from running indefinitely, especially -if there is no clear convergence criteria or if the fitness landscape is complex and difficult to navigate. - -However, it is important to note that the choice of the maximum number of generations should be based on the specific problem being solved, as well as the -computational resources available. A too small number of generations may not allow the algorithm to converge to a satisfactory solution, while a too large -number may result in unnecessary computational expense. - - -By default, when creating an optimizer, the default stopping condition (termination) is based on epochs (generations, iterations). - -However, there are different stopping conditions that you can try by creating a Termination dictionary. You can also use multiple stopping criteria together -to improve your model. There are 4 termination types in the class Termination: - -+ MG: Maximum Generations / Epochs / Iterations -+ FE: Maximum Number of Function Evaluations -+ TB: Time Bound - If you want your algorithm to run for a fixed amount of time (e.g., K seconds), especially when comparing different algorithms. -+ ES: Early Stopping - Similar to the idea in training neural networks (stop the program if the global best solution has not improved by epsilon after K epochs). - -+ Parameters for Termination class, set it to None if you don't want to use it - + max_epoch (int): Indicates the maximum number of generations for the MG type. - + max_fe (int): Indicates the maximum number of function evaluations for the FE type. - + max_time (float): Indicates the maximum amount of time for the TB type. - + max_early_stop (int): Indicates the maximum number of epochs for the ES type. - + epsilon (float): (Optional) This is used for the ES termination type (default value: 1e-10). - + termination (dict): (Optional) A dictionary of termination criteria. - - -**1. MG (Maximum Generations / Epochs): This is default in all algorithms** - -.. code-block:: python - - term_dict = { # When creating this object, it will override the default epoch you define in your model - "max_epoch": 1000 # 1000 epochs - } - -**2. FE (Number of Function Evaluation)** - -.. code-block:: python - - term_dict = { - "max_fe": 100000 # 100000 number of function evaluation - } - -**3. TB (Time Bound): If you want your algorithm to run for a fixed amount of time (e.g., K seconds), especially when comparing different algorithms.** - -.. code-block:: python - - term_dict = { - "max_time": 60 # 60 seconds to run this algorithm only - } - -**4. ES (Early Stopping): Similar to the idea in training neural networks (stop the program if the global best solution has not improved by epsilon after K epochs).** - -.. code-block:: python - - term_dict = { - "max_early_stop": 30 # after 30 epochs, if the global best doesn't improve then we stop the program - } - -**Setting multiple stopping criteria together. The first one that occurs will be used.** - -.. code-block:: python - - # Use max epochs and max function evaluations together - term_dict = { - "max_epoch": 1000, - "max_fe": 60000 - } - - # Use max function evaluations and time bound together - term_dict = { - "max_fe": 60000, - "max_time": 40 - } - - # Use max function evaluations and early stopping together - term_dict = { - "max_fe": 55000, - "max_early_stop": 15 - } - - # Use max epochs, max FE and early stopping together - term_dict = { - "max_epoch": 1200, - "max_fe": 55000, - "max_early_stop": 25 - } - - # Use all available stopping conditions together - term_dict = { - "max_epoch": 1100, - "max_fe": 80000, - "max_time": 10.5, - "max_early_stop": 25 - } - - -**After import and create a termination object, and an optimizer object, you can pass termination object to solve() function** - -.. code-block:: python - - model3 = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - model3.solve(problem_dict1, termination=term_dict) - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/build_new_optimizer.rst b/docs/source/pages/general/build_new_optimizer.rst deleted file mode 100644 index e9baba1d..00000000 --- a/docs/source/pages/general/build_new_optimizer.rst +++ /dev/null @@ -1,119 +0,0 @@ -=================== -Build New Optimizer -=================== - -The figure below shows the flow of the Optimizer class and which methods can be overridden and which methods should not be overridden to take advantage of -the Optimizer class. - - -.. image:: /_static/images/mealpy_flow.png - - -Based on this flow, we have created an example in "examples/build_new_optimizer.py" to show you how to do this in code. - - -**How to create a new optimizer?** - -.. code-block:: python - - import numpy as np - from mealpy import Optimizer, FloatVar - - - class MyAlgorithm(Optimizer): - """ - This is an example how to build new optimizer - """ - - def __init__(self, epoch=10000, pop_size=100, m_clusters=2, p1=0.75, **kwargs): - super().__init__(**kwargs) - self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) - self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) - self.m_clusters = self.validator.check_int("m_clusters", m_clusters, [2, 5]) - self.p1 = self.validator.check_float("p1", p1, (0, 1.0)) - - self.sort_flag = True - # Determine to sort the problem or not in each epoch - ## if True, the problem always sorted with fitness value increase - ## if False, the problem is not sorted - - def initialize_variables(self): - """ - This is method is called before initialization() method. - """ - ## Support variables - self.n_agents = int(self.pop_size / self.m_clusters) - self.space = self.problem.ub - self.problem.lb - - def initialization(self): - """ - Override this method if needed. But the first 2 lines of code is required. - """ - ### Required code - if self.pop is None: - self.pop = self.generate_population(self.pop_size) - - ### Your additional code can be implemented here - self.mean_pos = np.mean([agent[self.ID_POS] for agent in self.pop]) - - def evolve(self, epoch): - """ - You can do everything in this function (i.e., Loop through the population multiple times) - - Args: - epoch (int): The current iteration - """ - epsilon = 1.0 - epoch / self.epoch # The epsilon in each epoch is changing based on this equation - - ## 1. Replace the almost worst agent by random agent - if self.generator.uniform() < self.p1: - idx = self.generator.integers(self.n_agents, self.pop_size) - self.pop[idx] = self.generate_agent() - - ## 2. Replace all bad solutions by current_best + noise - for idx in range(self.n_agents, self.pop_size): - pos_new = self.pop[0].solution + epsilon * self.space * self.generator.normal(0, 1) - pos_new = self.correct_solution(pos_new) - agent = self.generate_agent(pos_new) - if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): - self.pop[idx] = agent - - ## 3. Move all good solutions toward current best solution - for idx in range(0, self.n_agents): - if idx == 0: - pos_new = self.pop[idx].solution + epsilon * self.space * self.generator.uniform(0, 1) - else: - pos_new = self.pop[idx].solution + epsilon * self.space * (self.pop[0].solution - self.pop[idx].solution) - pos_new = self.correct_solution(pos_new) - agent = self.generate_agent(pos_new) - if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): - self.pop[idx] = agent - - ## Do additional works here if needed. - - - ## Time to test our new optimizer - def objective_function(solution): - return np.sum(solution**2) - - problem_dict1 = { - "obj_func": objective_function, - "bounds": FloatVar(lb=[-100, ]*100, ub=[100, ]*100), - "minmax": "min", - } - - epoch = 50 - pop_size = 50 - model = MyAlgorithm(epoch, pop_size) - g_best = model.solve(problem_dict1) - print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/general/classification_table.rst b/docs/source/pages/general/classification_table.rst deleted file mode 100644 index 1545c378..00000000 --- a/docs/source/pages/general/classification_table.rst +++ /dev/null @@ -1,39 +0,0 @@ - -Warning: This classification is old. Now we update all new optimizers at `this table`_. - -* Meta-heuristic Algorithm's Categories: (Based on `this article`_) - + Evolutionary-based: inspired by Darwin's law of natural selection, evolutionary computing - + Swarm-based: inspired by movement, interaction, and organization of birds, social insects, and other animals - + Physics-based: inspired by physical laws such as Newton's law of universal gravitation, black holes, and multiverse - + Human-based: inspired by human interaction, such as queuing search, teaching-learning, and cultural algorithms - + Biology-based: inspired by biological creatures or microorganisms, such as genetic algorithms and artificial immune systems - + System-based: inspired by ecosystem, immune system, and network system. - + Math-based: inspired by mathematical forms or laws, such as sin-cosin functions, golden ratio. - + Music-based: inspired by music instruments, such as harmony search - -.. _this article: https://doi.org/10.1016/j.procs.2020.09.075 -.. _this table: https://github.com/thieu1995/mealpy?tab=readme-ov-file#-optimizer-classification-table - -* Difficulty - Difficulty Level (Personal Opinion): Objective observation from author. Depend on the number of parameters, number of equations, the original ideas, time spend for coding, source lines of code (SLOC). - + Easy: Few parameters, few equations, and very short SLOC (Source lines of code) - + Medium: More equations than the Easy level, longer SLOC than the Easy level - + Hard: Lots of equations, longer SLOC than the Medium level, and the paper is difficult to read. - + Hard* - Very hard:Lots of equations, SLOC is too long, and the paper is very difficult to read. - -**For newbies, it is recommended to start by reading papers on algorithms that are categorized as "easy" or "medium" difficulty level.** - -📖 Please check the table from `README.md on GitHub`_. - -.. _README.md on GitHub: https://github.com/thieu1995/mealpy?tab=readme-ov-file#-optimizer-classification-table - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - diff --git a/docs/source/pages/general/introduction.rst b/docs/source/pages/general/introduction.rst deleted file mode 100644 index e211c203..00000000 --- a/docs/source/pages/general/introduction.rst +++ /dev/null @@ -1,112 +0,0 @@ -============ -Introduction -============ - -**MEALPY** (MEta-heuristic ALgorithms in PYthon) is the most comprehensive Python library for cutting-edge, nature-inspired meta-heuristic algorithms. -It is released under the **MIT** license. - -- **Current version:** 3.0.3 -- **Total algorithms:** 233 - - 206 official (originals, hybrids, and variants) - - 27 custom-developed by our developers - -.. _All releases: https://pypi.org/project/mealpy/#history - -**Important:** -Different versions of MEALPY introduce different ways to define and pass hyperparameters. Please check your version carefully: - -- `< 1.0.5` -- `1.1.0 - 1.2.2` -- `2.0.0 - 2.1.2` -- `2.2.0` -- `2.3.0` -- `2.4.0 - 2.4.2`: Supports discrete problems -- `2.5.1 - 2.5.4`: Define once, solve multiple problems -- `>= 3.0.0`: Fully object-oriented design - - -Goals of this framework: - -- To share knowledge of the meta-heuristic field with everyone at no cost. -- To help researchers in all fields access optimization algorithms as quickly as possible. -- To implement both classical and state-of-the-art meta-heuristics, covering the entire history of meta-heuristics. - - -What MEALPY offers: - -- Analyze the parameters of algorithms. -- Perform qualitative and quantitative analyses of algorithms. -- Analyze the rate of convergence of algorithms. -- Test and analyze the scalability and robustness of algorithms. - -Want to request a new algorithm? -Open an `Issue ticket `_ or build your own using MEALPY’s modular components. - -* And please give us credits if you use this library, check some of my `previous paper`_. :: - - @article{van2023mealpy, - title={MEALPY: An open-source library for latest meta-heuristic algorithms in Python}, - author={Van Thieu, Nguyen and Mirjalili, Seyedali}, - journal={Journal of Systems Architecture}, - year={2023}, - publisher={Elsevier}, - doi={10.1016/j.sysarc.2023.102871} - } - -.. _previous paper: https://gist.github.com/thieu1995/2dcebc754bf0038d0c12b26ec9d591aa - - ------------- -Optimization ------------- - -Optimization is the process of finding the best solution from a set of feasible solutions. In real-world problems, -objective functions can be nonlinear, noisy, non-differentiable, or highly constrained—making traditional -gradient-based methods ineffective. - -Meta-heuristic algorithms offer a powerful alternative. They do not require gradient information and can handle -a wide range of optimization types: continuous, discrete, constrained, and multi-objective. - -A general optimization problem can be formulated as: - -.. image:: /_static/images/general_format.png - -Where `x` is the vector of decision variables (real, integer, or categorical), `f(x)` are the objective functions, -and `g(x), h(x)` are constraints. - -Classical methods like Newton-Raphson work well for smooth problems, but fail on complex landscapes. -Meta-heuristics provide a flexible, robust way to solve challenging problems when exact solutions are impractical or impossible. - -------------------------- -Meta-heuristic Algorithms -------------------------- - -Meta-heuristics are high-level search strategies that balance **exploration** (global search) and **exploitation** -(local refinement). They are inspired by natural processes like evolution, swarm behavior, physics, and chemistry. - -Key features: -- Use randomness to escape local optima -- Perform well on complex, multimodal problems -- Require minimal assumptions about the problem - -.. image:: /_static/images/bio_inspired.png - - -Meta-heuristics can be: -- **Population-based**: e.g., Genetic Algorithm, PSO -- **Trajectory-based**: e.g., Simulated Annealing - -.. image:: /_static/images/history_metaheuristics.png - -Despite their stochastic nature, well-designed meta-heuristics often produce high-quality solutions consistently. -MEALPY offers 200+ implementations of such algorithms, from classical to cutting-edge. - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/general/multitask.rst b/docs/source/pages/general/multitask.rst deleted file mode 100644 index 314efcaa..00000000 --- a/docs/source/pages/general/multitask.rst +++ /dev/null @@ -1,120 +0,0 @@ -================= -Multitask Solving -================= - -We build a dedicated class, Multitask, that can help you run several different scenarios. For example: - -1. Run 1 algorithm with 1 problem, and multiple trials -2. Run 1 algorithm with multiple problems, and multiple trials -3. Run multiple algorithms with 1 problem, and multiple trials -4. Run multiple algorithms with multiple problems, and multiple trials - -Please head to examples folder to learn more about this `Multitask-Examples`_ - -.. _Multitask-Examples: https://github.com/thieu1995/mealpy/tree/master/examples - - -**Below is a simple example with Multitask class** - -.. code-block:: python - - import numpy as np - ## Import libraries - from opfunu.cec_based.cec2017 import F52017, F102017, F292017 - from mealpy import FloatVar - from mealpy import BBO, DE - from mealpy import Multitask - - ## Define your own problems - f1 = F52017(30, f_bias=0) - f2 = F102017(30, f_bias=0) - f3 = F292017(30, f_bias=0) - - p1 = { - "bounds": FloatVar(lb=f1.lb, ub=f1.ub), - "obj_func": f1.evaluate, - "minmax": "min", - "name": "F5", - "log_to": "console", - } - - p2 = { - "bounds": FloatVar(lb=f2.lb, ub=f2.ub), - "obj_func": f2.evaluate, - "minmax": "min", - "name": "F10", - "log_to": "console", - } - - p3 = { - "bounds": FloatVar(lb=f3.lb, ub=f3.ub), - "obj_func": f3.evaluate, - "minmax": "min", - "name": "F29", - "log_to": "console", - } - - ## Define models - model1 = BBO.DevBBO(epoch=10000, pop_size=50) - model2 = BBO.OriginalBBO(epoch=10000, pop_size=50) - model3 = DE.OriginalDE(epoch=10000, pop_size=50) - model4 = DE.SAP_DE(epoch=10000, pop_size=50) - - ## Define termination if needed - term = { - "max_fe": 3000 - } - - ## Define and run Multitask - if __name__ == "__main__": - multitask = Multitask(algorithms=(model1, model2, model3, model4), problems=(p1, p2, p3), terminations=(term, ), modes=("thread", ), n_workers=4) - # default modes = "single", default termination = epoch (as defined in problem dictionary) - - multitask.execute(n_trials=5, n_jobs=None, save_path="history", save_as="csv", save_convergence=True, verbose=False) - # multitask.execute(n_trials=5, save_path="history", save_as="csv", save_convergence=True, verbose=False) - - -When define Multitask object, you can pass terminations and modes for each optimizer that solve each problem. -Assumption that we have 3 optimizers and 2 problems. Then terminations/modes can be as follows: - -.. code-block:: python - - # Each optimizer for each problem with different termination - terminations = [ (term_11, term_12), (term_21, term_22), (term_31, term_32) ] - - # The same termination for all problems with each optimizer - terminations = [ term_1, term_2, term_3 ] - ## Then it will be convert into - terminations = [ (term_1, term_1), (term_2, term_2), (term_3, term_3) ] - - # The same termination for all optimizers with each problem - terminations = [ term_1, term_2 ] - ## Then it will be convert into - terminations = [ (term_1, term_2), (term_1, term_2), (term_1, term_2) ] - - # The same termination for all optimizers and all problems - terminations = [term] - ## Then it will be convert into - terminations = [ (term, term), (term, term), (term, term) ] - -Remember the modes variables here is the mode using in each optimizer, the value can be "thread", "process", "swarm" or "single". - -After we have multitask object, we can call the function execute() to run it. There are two important parameters for this functions which are: n_trials and -n_jobs. - -* n_trials: the number of time you want to run the set of (optimizers, problems) above. -* n_jobs: defined the number of processes will be used to speed up the computation for `n_trials`. - * n_jobs <= 1 or None: we run `n_trials` in sequential order. - * n_jobs >= 2: we use `n_jobs` processes to run `n_trials` task in parallel. - -For example, we set n_trials = 10, and n_jobs = 4. Then at first, we create 4 processes to handle 4 trials simultaneously. - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/general/references.rst b/docs/source/pages/general/references.rst deleted file mode 100644 index 3d1a366d..00000000 --- a/docs/source/pages/general/references.rst +++ /dev/null @@ -1,17 +0,0 @@ ----------- -References ----------- - -Please see the completed references list in file `README.md in Github`_. - -.. _README.md in Github: https://github.com/thieu1995/mealpy?tab=readme-ov-file#references - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/general/simple_guide.rst b/docs/source/pages/general/simple_guide.rst deleted file mode 100644 index 4a280a1e..00000000 --- a/docs/source/pages/general/simple_guide.rst +++ /dev/null @@ -1,190 +0,0 @@ -============ -Simple Guide -============ - -In this phase, the main task is to find out the global optimal - in this project, we call it named *model* for simple. We designed the classical as well as -the state-of-the-art population-based meta-heuristics models: `Evolutionary-based`_, `Swarm-based`_, `Physics-based`_, `Human-based`_, `Biology-based`_, -`Mathematical-based`_, `Musical-based`_, and `System-based`_ - -.. _Evolutionary-based: ../models/mealpy.evolutionary_based.html -.. _Swarm-based: ../models/mealpy.swarm_based.html -.. _Physics-based: ../models/mealpy.physics_based.html -.. _Human-based: ../models/mealpy.human_based.html -.. _Biology-based: ../models/mealpy.bio_based.html -.. _Mathematical-based: ../models/mealpy.math_based.html -.. _Musical-based: ../models/mealpy.music_based.html -.. _System-based: ../models/mealpy.system_based.html - -All of this methods are used in the same way. So, in this guide, we'll demo with a specific method such as **Genetic Algorithm** in *Evolutionary-based*. - - ------------- -Installation ------------- - -**User Installation** - -Install the `current PyPI release`_. :: - - $ pip install mealpy==3.0.3 - -.. _current PyPI release: https://pypi.python.org/pypi/mealpy - -Or install the development version from GitHub:: - - $ pip install git+https://github.com/thieu1995/mealpy - - -Check the version of MEALPY:: - - $ import mealpy - $ mealpy.__version__ - - $ print(mealpy.get_all_optimizers()) - $ model = mealpy.get_optimizer_by_name("OriginalWOA")(epoch=100, pop_size=50) - ----------------------- -Getting started in 30s ----------------------- - -**Tutorial** - * Import libraries - * Define your fitness function - * Define a problem dictionary - * Training and get the results - -.. code-block:: python - - from mealpy import FloatVar, GA - import numpy as np - - def objective_func(solution): - return np.sum(solution**2) - - problem_dict = { - "obj_func": objective_func, - "bounds": FloatVar(lb=[-100, ] * 30, ub=[100, ] * 30,), - "minmax": "min", - } - - optimizer = GA.BaseGA(epoch=100, pop_size=50, pc=0.85, pm=0.1) - optimizer.solve(problem_dict) - - print(optimizer.g_best.solution) - print(optimizer.g_best.target.fitness) - -You can see the fitness after each iteration which is found by GA: - ----------------------------- -Fitness Function Preparation ----------------------------- - -Make sure that your designed `obj_func` function takes a solution (a numpy vector) and returns the objective value (a single real value or a list of real -values). We have already included the `opfunu` library, which is a framework of benchmark functions for optimization problems. You can use it very easily by: - - -.. code-block:: python - - from opfunu.type_based.uni_modal import Functions # or - from opfunu.cec.cec2014 import Fucntion # or - from opfunu.dimension_based.benchmarknd import Functions - - # Then you need to create an object of Function to get the functions - type_based = Functions() - F1 = type_based._sum_squres__ - F2 = type_based.__dixon_price__ - .... - - -If you prefer not to use the opfunu library and want to design your own fitness functions, that's okay too. All you need to do is write your own function -that takes a numpy vector (the solution) as input and returns a single objective value or a list of multiple objective values. - - -.. code-block:: python - - import numpy as np - - ## This is normal fitness function - def objective_normal(solution=None): - return np.sqrt(solution**2) # Single value - -------------------- -Problem Preparation -------------------- - -You will need to define a problem dictionary with must has keywords ("obj_func", "bounds", "minmax"). - - * obj_func: Your objective function - * bounds: The problem type, an instance of these classes: FloatVar, BoolVar, StringVar, IntegerVar, PermutationVar, BinaryVar, MixedSetVar - * minmax: The problem you are trying to solve is minimum or maximum, value can be "min" or "max" - - -.. code-block:: python - - ## Design a problem dictionary for normal function - problem_normal = { - "obj_func": objective_normal, - "bounds": FloatVar(lb=[-100, ] * 30, ub=[100, ]*30) - "minmax": "min", - } - --------- -Training --------- - -To start learning, call the **solve()** function. There are four different training modes available: - -1. **process**: Uses multiple cores to update fitness for the entire population (parallel processing; no effect on updating process). -2. **thread**: Uses multiple threads to update fitness for the entire population (parallel processing; no effect on updating process). -3. **swarm**: Updates fitness after the entire population moves (sequential processing; no effect on updating process). -4. **single**: Updates fitness after each agent moves (sequential processing; affects updating process). - - - -.. code-block:: python - - ## Need to import the algorithm that will be used - from mealpy import SMA, GA, PSO - - sma_model = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best = sma_model.solve(problem_normal) # default is: single - - sma_model = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best = sma_model.solve(problem_normal, mode="single") - - sma_model = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best = sma_model.solve(problem_normal, mode="swarm") - - ga_model = GA.BaseGA(epoch=1000, pop_size=100, pc=0.9, pm=0.05) - g_best = ga_model.solve(problem_multi, mode="thread") - - pso_model = PSO.OriginalPSO(epoch=500, pop_size=80, c1=2.0, c2=1.8, w_min=0.3, w_max=0.8) - g_best = pso_model.solve(problem_constrained, mode="process") - - - -You can set the number of workers when using "Parallel" training. - -.. code-block:: python - - from mealpy.bio_based import SMA - - sma_model = SMA.OriginalSMA(epoch=100, pop_size=50, pr=0.03) - g_best = sma_model.solve(problem_normal, mode="thread", n_workers=8) - # Using 8 threads to solve this problem - - -The returned result is the best agent found. It holds attribute like: - -- `solution`: the global best position it found on solving process -- `target` object: an instance of Target class, that holds `fitness` and `objectives` - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/general/tuner.rst b/docs/source/pages/general/tuner.rst deleted file mode 100644 index 148a4a47..00000000 --- a/docs/source/pages/general/tuner.rst +++ /dev/null @@ -1,83 +0,0 @@ -============================= -Tuner / Hyperparameter Tuning -============================= - -We build a dedicated class, Tuner, that can help you tune your algorithm's parameters. - -Please head to examples folder to learn more about this `Tuner-Examples`_ - -.. _Tuner-Examples: https://github.com/thieu1995/mealpy/tree/master/examples - - -**Below is a simple example with Tuner class** - -.. code-block:: python - - from opfunu.cec_based.cec2017 import F52017 - from mealpy import FloatVar, BBO, Tuner # We will use this Tuner utility - - - f1 = F52017(30, f_bias=0) - - p1 = { - "bounds": FloatVar(lb=f1.lb, ub=f1.ub), - "obj_func": f1.evaluate, - "minmax": "min", - "name": "F5", - "log_to": "console", - } - - paras_bbo_grid = { - "epoch": [10], - "pop_size": [10], - "n_elites": [2, 3, 4, 5], - "p_m": [0.01, 0.02, 0.05] - } - - term = { - "max_epoch": 200, - "max_time": 20, - "max_fe": 10000 - } - - if __name__ == "__main__": - ### Define model and parameter grid of the model (just like ParameterGrid / GridSearchCV) - model = BBO.OriginalBBO() - tuner = Tuner(model, paras_bbo_grid) - - ## Try to run this optimizer on this problem 5 times (n_trials = 5). - ## Get the best model by mean value of all trials - ## Distribute to 4 CPU to run (n_jobs=4) - tuner.execute(problem=p1, termination=term, n_trials=5, n_jobs=4, verbose=True) - - print(tuner.best_row) - print(tuner.best_score) - print(tuner.best_params) - print(type(tuner.best_params)) - - print(tuner.best_algorithm) - ## Better to save the tuning results to CSV for later usage - tuner.export_results() - tuner.export_figures() - - ## Now we can even re-train the algorithm with the best parameter by calling resolve() function - ## Resolve() function will call the solve() function in algorithm with default problem parameter is removed. - ## other parameters of solve() function is keeped and can be used. - g_best = tuner.resolve(mode="thread", n_workers=4, termination=term) - - ## Print out the best score of the best parameter - print(g_best.solution, g_best.target.fitness) - - print(tuner.algorithm.problem.get_name()) - - ## Print out the algorithm with the best parameter - print(tuner.best_algorithm.get_name()) - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/general/video_tutorials.rst b/docs/source/pages/general/video_tutorials.rst deleted file mode 100644 index 33e34e74..00000000 --- a/docs/source/pages/general/video_tutorials.rst +++ /dev/null @@ -1,158 +0,0 @@ -=============== -Video Tutorials -=============== - --------------------- -Mealpy Tutorial Full --------------------- - -* Part 1: |link_p1|, Part 2: |link_p2| - -.. |link_p1| raw:: html - - Youtube P1 - -.. |link_p2| raw:: html - - Youtube P1 - -* Please read the description in the video for timestamp notes - -* Or watch the |Full Video| with timestamp notes below: - -.. image:: https://img.youtube.com/vi/HWc-yNcyPLw/0.jpg - :target: https://www.youtube.com/watch?v=HWc-yNcyPLw - -.. |Full video| raw:: html - - Full Video - - -:: - - 0:00 - Intro - 0:19 - Download and install Miniconda on Windows 11 - 1:22 - Create a new environment using Miniconda - 2:32 - Install Mealpy - 5:08 - Pycharm and set environment on it - 9:22 - Introducing the structure of Mealpy library - 10:16 - The Optimizer class - 10:50 - The Problem class - 11:44 - The Termination class - 15:10 - The History class (How to draw figures) - 16:37 - How to import the mealpy library (Optimizer class) - 18:32 - Define a problem dictionary (problem instance of Problem class) - 19:32 - Define objective-function - 21:18 - Problem definition (Find minimum of Fx function) - 23:10 - How to call an optimizer to solve optimization problem - 25:38 - The Problem class - 26:23 - Sequential, Thread and Process training mode setting - 28:23 - Explaining the current best and global best (training output) - 29:18 - How to get final fitness and final position (solution) - 30:38 - The structure of the "solution" attribute in Optimizer class - 33:48 - Other ways to pass Lowerbound and Upperbound in problem dictionary - 36:05 - How to import and define the Termination object - 43:08 - Time-bound termination object - 45:16 - Early Stopping termination object - 47:18 - How to use Sequential/MultiThreading/MultiProcessing training mode - 51:58 - Fix error with MultiProcessing training mode - 55:54 - How to deal with Multi-objective Optimization Problem - 1:05:09 - How to deal with Constrained Optimization Problem - 1:11:46 - How to draw some important figures using History object - 1:23:15 - How to use Mealpy to optimize hyper-parameters of a model - 1:26:15 - Using Mealpy to optimization hyper-parameters of a traditional SVM classification - 1:30:18 - Brute force method for tunning hyper-parameters - 1:36:18 - GridSearchCV method for tunning hyper-parameters - 1:39:28 - Metaheuristic Algorithm method for tunning hyper-parameters - - ------------------------ -Mealpy + Neural Network ------------------------ - - -Gradient Descent Replacement -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -- Metaheuristic Algorithm in general can replace the Gradient Descent optimization to train the neural network. |youtube_1| - -.. image:: https://img.youtube.com/vi/auq7Na1Meus/0.jpg - :target: https://www.youtube.com/watch?v=auq7Na1Meus - -.. |youtube_1| raw:: html - - Youtube Link - - -- For Time-Series Problem: - - * Traditional Multilayer Perceptron (MLP): |link_code_1| - * Hybrid MLP Model (Mealpy + MLP): |link_code_2| - -.. |link_code_1| raw:: html - - Link Code - -.. |link_code_2| raw:: html - - Link Code - - -- For Classification Problem: - - * Traditional Multilayer Perceptron (MLP): |link_code_3| - * Hybrid MLP Model (Mealpy + MLP): |link_code_4| - -.. |link_code_3| raw:: html - - Link Code - -.. |link_code_4| raw:: html - - Link Code - - - -Optimize ANN Hyper-parameter -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -- Metaheuristic Algorithm also can optimize Hyper-parameter of Neural Network. |youtube_3| - -.. image:: https://img.youtube.com/vi/Fl3h9t087Pk/0.jpg - :target: https://www.youtube.com/watch?v=Fl3h9t087Pk - -.. |youtube_3| raw:: html - - Youtube Link - -- |link_code_5| for Classification problem. - -.. |link_code_5| raw:: html - - Link Code - - - - -------------------------- -Other Mealpy Applications -------------------------- - -* Solving Knapsack Problem (Discrete problems): |link_code_6| - -* Optimize SVM (SVC) model: |link_code_7| - -* Optimize Linear Regression Model: |link_code_8| - - -.. |link_code_6| raw:: html - - Link Code - -.. |link_code_7| raw:: html - - Link Code - -.. |link_code_8| raw:: html - - Link Code \ No newline at end of file diff --git a/docs/source/pages/general/visualization.rst b/docs/source/pages/general/visualization.rst deleted file mode 100644 index dd6f8ee6..00000000 --- a/docs/source/pages/general/visualization.rst +++ /dev/null @@ -1,73 +0,0 @@ -============= -Visualization -============= - -Drawing all available figures. There are 8 different figures for each algorithm. - -**1. Based on fitness value (global best and local best fitness chart)**: - -.. image:: /_static/images/results/Global-best-convergence-chart.png - :width: 49 % -.. image:: /_static/images/results/Current-best-convergence-chart.png - :width: 49 % - - -**2. Based on objective values (global best and local best objective chart)**: - -.. image:: /_static/images/results/global-objective-chart.png - :width: 49 % -.. image:: /_static/images/results/local-objective-chart.png - :width: 49 % - - -**3. Based on runtime value (runtime for each epoch)** - -**4. Based on exploration verse exploration value** - -.. image:: /_static/images/results/Runtime-per-epoch-chart.png - :width: 49 % -.. image:: /_static/images/results/explore_exploit_chart.png - :width: 49 % - -**5. Based on diversity of population** - -**6. Based on trajectory value (1D, 2D only)** - -.. image:: /_static/images/results/diversity_chart.png - :width: 49 % -.. image:: /_static/images/results/1d_trajectory.png - :width: 49 % - - -**How to call the functions?** - -.. code-block:: python - - model = SMA.Original(epoch=100, pop_size=50, pr=0.03) - model.solve(problem) - - ## You can access them all via object "history" like this: - model.history.save_global_objectives_chart(filename="hello/goc") - model.history.save_local_objectives_chart(filename="hello/loc") - - model.history.save_global_best_fitness_chart(filename="hello/gbfc") - model.history.save_local_best_fitness_chart(filename="hello/lbfc") - - model.history.save_runtime_chart(filename="hello/rtc") - - model.history.save_exploration_exploitation_chart(filename="hello/eec") - - model.history.save_diversity_chart(filename="hello/dc") - - model.history.save_trajectory_chart(list_agent_idx=[3, 5, 6, 7,], selected_dimensions=[3, 4], filename="hello/tc") - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/models.rst b/docs/source/pages/models.rst deleted file mode 100644 index d3ccd57e..00000000 --- a/docs/source/pages/models.rst +++ /dev/null @@ -1,17 +0,0 @@ - - -.. toctree:: - :maxdepth: 4 - - models/mealpy.rst - general/visualization.rst - general/build_new_optimizer.rst - general/tuner.rst - general/multitask.rst - -.. toctree:: - :maxdepth: 4 - - -.. toctree:: - :maxdepth: 4 diff --git a/docs/source/pages/models/mealpy.bio_based.rst b/docs/source/pages/models/mealpy.bio_based.rst deleted file mode 100644 index 7908a13c..00000000 --- a/docs/source/pages/models/mealpy.bio_based.rst +++ /dev/null @@ -1,106 +0,0 @@ -mealpy.bio\_based package -========================= - -mealpy.bio\_based.BBO module ----------------------------- - -.. automodule:: mealpy.bio_based.BBO - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.BBOA module ------------------------------ - -.. automodule:: mealpy.bio_based.BBOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.BMO module ----------------------------- - -.. automodule:: mealpy.bio_based.BMO - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.EOA module ----------------------------- - -.. automodule:: mealpy.bio_based.EOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.IWO module ----------------------------- - -.. automodule:: mealpy.bio_based.IWO - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.SBO module ----------------------------- - -.. automodule:: mealpy.bio_based.SBO - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.SMA module ----------------------------- - -.. automodule:: mealpy.bio_based.SMA - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.SOA module ----------------------------- - -.. automodule:: mealpy.bio_based.SOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.SOS module ----------------------------- - -.. automodule:: mealpy.bio_based.SOS - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.TPO module ----------------------------- - -.. automodule:: mealpy.bio_based.TPO - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.TSA module ----------------------------- - -.. automodule:: mealpy.bio_based.TSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.VCS module ----------------------------- - -.. automodule:: mealpy.bio_based.VCS - :members: - :undoc-members: - :show-inheritance: - -mealpy.bio\_based.WHO module ----------------------------- - -.. automodule:: mealpy.bio_based.WHO - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.evolutionary_based.rst b/docs/source/pages/models/mealpy.evolutionary_based.rst deleted file mode 100644 index 2ec0a952..00000000 --- a/docs/source/pages/models/mealpy.evolutionary_based.rst +++ /dev/null @@ -1,67 +0,0 @@ -mealpy.evolutionary\_based package -================================== - - -mealpy.evolutionary\_based.CRO module -------------------------------------- - -.. automodule:: mealpy.evolutionary_based.CRO - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.DE module ------------------------------------- - -.. automodule:: mealpy.evolutionary_based.DE - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.EP module ------------------------------------- - -.. automodule:: mealpy.evolutionary_based.EP - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.ES module ------------------------------------- - -.. automodule:: mealpy.evolutionary_based.ES - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.FPA module -------------------------------------- - -.. automodule:: mealpy.evolutionary_based.FPA - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.GA module ------------------------------------- - -.. automodule:: mealpy.evolutionary_based.GA - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.MA module ------------------------------------- - -.. automodule:: mealpy.evolutionary_based.MA - :members: - :undoc-members: - :show-inheritance: - -mealpy.evolutionary\_based.SHADE module ---------------------------------------- - -.. automodule:: mealpy.evolutionary_based.SHADE - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.human_based.rst b/docs/source/pages/models/mealpy.human_based.rst deleted file mode 100644 index 7514ed23..00000000 --- a/docs/source/pages/models/mealpy.human_based.rst +++ /dev/null @@ -1,147 +0,0 @@ -mealpy.human\_based package -=========================== - - -mealpy.human\_based.BRO module ------------------------------- - -.. automodule:: mealpy.human_based.BRO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.BSO module ------------------------------- - -.. automodule:: mealpy.human_based.BSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.CA module ------------------------------ - -.. automodule:: mealpy.human_based.CA - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.CHIO module -------------------------------- - -.. automodule:: mealpy.human_based.CHIO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.FBIO module -------------------------------- - -.. automodule:: mealpy.human_based.FBIO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.GSKA module -------------------------------- - -.. automodule:: mealpy.human_based.GSKA - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.HBO module ------------------------------- - -.. automodule:: mealpy.human_based.HBO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.HCO module ------------------------------- - -.. automodule:: mealpy.human_based.HCO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.ICA module ------------------------------- - -.. automodule:: mealpy.human_based.ICA - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.LCO module ------------------------------- - -.. automodule:: mealpy.human_based.LCO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.PO module ------------------------------ - -.. .. automodule:: mealpy.human_based.PO -.. :members: -.. :undoc-members: -.. :show-inheritance: - -mealpy.human\_based.QSA module ------------------------------- - -.. automodule:: mealpy.human_based.QSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.SARO module -------------------------------- - -.. automodule:: mealpy.human_based.SARO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.SPBO module -------------------------------- - -.. automodule:: mealpy.human_based.SPBO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.SSDO module -------------------------------- - -.. automodule:: mealpy.human_based.SSDO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.TLO module ------------------------------- - -.. automodule:: mealpy.human_based.TLO - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.TOA module ------------------------------- - -.. automodule:: mealpy.human_based.TOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.human\_based.WarSO module --------------------------------- - -.. automodule:: mealpy.human_based.WarSO - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.math_based.rst b/docs/source/pages/models/mealpy.math_based.rst deleted file mode 100644 index c86d4c2e..00000000 --- a/docs/source/pages/models/mealpy.math_based.rst +++ /dev/null @@ -1,99 +0,0 @@ -mealpy.math\_based package -========================== - - -mealpy.math\_based.AOA module ------------------------------ - -.. automodule:: mealpy.math_based.AOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.CEM module ------------------------------ - -.. automodule:: mealpy.math_based.CEM - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.CGO module ------------------------------ - -.. automodule:: mealpy.math_based.CGO - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.CircleSA module ----------------------------------- - -.. automodule:: mealpy.math_based.CircleSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.GBO module ------------------------------ - -.. automodule:: mealpy.math_based.GBO - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.HC module ----------------------------- - -.. automodule:: mealpy.math_based.HC - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.INFO module ------------------------------- - -.. automodule:: mealpy.math_based.INFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.PSS module ------------------------------ - -.. automodule:: mealpy.math_based.PSS - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.RUN module ------------------------------ - -.. automodule:: mealpy.math_based.RUN - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.SCA module ------------------------------ - -.. automodule:: mealpy.math_based.SCA - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.SHIO module ------------------------------- - -.. automodule:: mealpy.math_based.SHIO - :members: - :undoc-members: - :show-inheritance: - -mealpy.math\_based.TS module ------------------------------- - -.. automodule:: mealpy.math_based.TS - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.music_based.rst b/docs/source/pages/models/mealpy.music_based.rst deleted file mode 100644 index 2114a031..00000000 --- a/docs/source/pages/models/mealpy.music_based.rst +++ /dev/null @@ -1,10 +0,0 @@ -mealpy.music\_based package -=========================== - -mealpy.music\_based.HS module ------------------------------ - -.. automodule:: mealpy.music_based.HS - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.physics_based.rst b/docs/source/pages/models/mealpy.physics_based.rst deleted file mode 100644 index f4aae718..00000000 --- a/docs/source/pages/models/mealpy.physics_based.rst +++ /dev/null @@ -1,115 +0,0 @@ -mealpy.physics\_based package -============================= - - -mealpy.physics\_based.ASO module --------------------------------- - -.. automodule:: mealpy.physics_based.ASO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.ArchOA module ------------------------------------ - -.. automodule:: mealpy.physics_based.ArchOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.CDO module --------------------------------- - -.. automodule:: mealpy.physics_based.CDO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.EFO module --------------------------------- - -.. automodule:: mealpy.physics_based.EFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.EO module -------------------------------- - -.. automodule:: mealpy.physics_based.EO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.EVO module --------------------------------- - -.. automodule:: mealpy.physics_based.EVO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.FLA module --------------------------------- - -.. automodule:: mealpy.physics_based.FLA - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.HGSO module ---------------------------------- - -.. automodule:: mealpy.physics_based.HGSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.MVO module --------------------------------- - -.. automodule:: mealpy.physics_based.MVO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.NRO module --------------------------------- - -.. automodule:: mealpy.physics_based.NRO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.RIME module ---------------------------------- - -.. automodule:: mealpy.physics_based.RIME - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.SA module -------------------------------- - -.. automodule:: mealpy.physics_based.SA - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.TWO module --------------------------------- - -.. automodule:: mealpy.physics_based.TWO - :members: - :undoc-members: - :show-inheritance: - -mealpy.physics\_based.WDO module --------------------------------- - -.. automodule:: mealpy.physics_based.WDO - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.rst b/docs/source/pages/models/mealpy.rst deleted file mode 100644 index 08b328a8..00000000 --- a/docs/source/pages/models/mealpy.rst +++ /dev/null @@ -1,56 +0,0 @@ -============== -All Optimizers -============== - - -Subpackages ------------ - -.. toctree:: - :maxdepth: 4 - - mealpy.bio_based - mealpy.evolutionary_based - mealpy.human_based - mealpy.math_based - mealpy.music_based - mealpy.physics_based - mealpy.swarm_based - mealpy.system_based - mealpy.utils - - -mealpy.optimizer ----------------- - -.. automodule:: mealpy.optimizer - :members: - :undoc-members: - :show-inheritance: - -mealpy.tuner ------------- - -.. automodule:: mealpy.tuner - :members: - :undoc-members: - :show-inheritance: - -mealpy.multitask ----------------- - -.. automodule:: mealpy.multitask - :members: - :undoc-members: - :show-inheritance: - - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/models/mealpy.swarm_based.rst b/docs/source/pages/models/mealpy.swarm_based.rst deleted file mode 100644 index 5115d925..00000000 --- a/docs/source/pages/models/mealpy.swarm_based.rst +++ /dev/null @@ -1,490 +0,0 @@ -mealpy.swarm\_based package -=========================== - -mealpy.swarm\_based.ABC module ------------------------------- - -.. automodule:: mealpy.swarm_based.ABC - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.ACOR module -------------------------------- - -.. automodule:: mealpy.swarm_based.ACOR - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.AGTO module -------------------------------- - -.. automodule:: mealpy.swarm_based.AGTO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.ALO module ------------------------------- - -.. automodule:: mealpy.swarm_based.ALO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.AO module ------------------------------ - -.. automodule:: mealpy.swarm_based.AO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.ARO module ------------------------------- - -.. automodule:: mealpy.swarm_based.ARO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.AVOA module -------------------------------- - -.. automodule:: mealpy.swarm_based.AVOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.BA module ------------------------------ - -.. automodule:: mealpy.swarm_based.BA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.BES module ------------------------------- - -.. automodule:: mealpy.swarm_based.BES - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.BFO module ------------------------------- - -.. automodule:: mealpy.swarm_based.BFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.BSA module ------------------------------- - -.. automodule:: mealpy.swarm_based.BSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.BeesA module --------------------------------- - -.. automodule:: mealpy.swarm_based.BeesA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.COA module ------------------------------- - -.. automodule:: mealpy.swarm_based.COA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.CSA module ------------------------------- - -.. automodule:: mealpy.swarm_based.CSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.CSO module ------------------------------- - -.. automodule:: mealpy.swarm_based.CSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.CoatiOA module ----------------------------------- - -.. automodule:: mealpy.swarm_based.CoatiOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.DMOA module -------------------------------- - -.. automodule:: mealpy.swarm_based.DMOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.DO module ------------------------------ - -.. automodule:: mealpy.swarm_based.DO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.EHO module ------------------------------- - -.. automodule:: mealpy.swarm_based.EHO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.ESOA module -------------------------------- - -.. automodule:: mealpy.swarm_based.ESOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.FA module ------------------------------ - -.. automodule:: mealpy.swarm_based.FA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.FFA module ------------------------------- - -.. automodule:: mealpy.swarm_based.FFA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.FFO module ------------------------------- - -.. automodule:: mealpy.swarm_based.FFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.FOA module ------------------------------- - -.. automodule:: mealpy.swarm_based.FOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.FOX module ------------------------------- - -.. automodule:: mealpy.swarm_based.FOX - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.GJO module ------------------------------- - -.. automodule:: mealpy.swarm_based.GJO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.GOA module ------------------------------- - -.. automodule:: mealpy.swarm_based.GOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.GTO module ------------------------------- - -.. automodule:: mealpy.swarm_based.GTO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.GWO module ------------------------------- - -.. automodule:: mealpy.swarm_based.GWO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.HBA module ------------------------------- - -.. automodule:: mealpy.swarm_based.HBA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.HGS module ------------------------------- - -.. automodule:: mealpy.swarm_based.HGS - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.HHO module ------------------------------- - -.. automodule:: mealpy.swarm_based.HHO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.JA module ------------------------------ - -.. automodule:: mealpy.swarm_based.JA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.MFO module ------------------------------- - -.. automodule:: mealpy.swarm_based.MFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.MGO module ------------------------------- - -.. automodule:: mealpy.swarm_based.MGO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.MPA module ------------------------------- - -.. automodule:: mealpy.swarm_based.MPA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.MRFO module -------------------------------- - -.. automodule:: mealpy.swarm_based.MRFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.MSA module ------------------------------- - -.. automodule:: mealpy.swarm_based.MSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.NGO module ------------------------------- - -.. automodule:: mealpy.swarm_based.NGO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.NMRA module -------------------------------- - -.. automodule:: mealpy.swarm_based.NMRA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.OOA module ------------------------------- - -.. automodule:: mealpy.swarm_based.OOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.PFA module ------------------------------- - -.. automodule:: mealpy.swarm_based.PFA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.POA module ------------------------------- - -.. automodule:: mealpy.swarm_based.POA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.PSO module ------------------------------- - -.. automodule:: mealpy.swarm_based.PSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SCSO module -------------------------------- - -.. automodule:: mealpy.swarm_based.SCSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SFO module ------------------------------- - -.. automodule:: mealpy.swarm_based.SFO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SHO module ------------------------------- - -.. automodule:: mealpy.swarm_based.SHO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SLO module ------------------------------- - -.. automodule:: mealpy.swarm_based.SLO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SRSR module -------------------------------- - -.. automodule:: mealpy.swarm_based.SRSR - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SSA module ------------------------------- - -.. automodule:: mealpy.swarm_based.SSA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SSO module ------------------------------- - -.. automodule:: mealpy.swarm_based.SSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SSpiderA module ------------------------------------ - -.. automodule:: mealpy.swarm_based.SSpiderA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SSpiderO module ------------------------------------ - -.. automodule:: mealpy.swarm_based.SSpiderO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.STO module ------------------------------- - -.. automodule:: mealpy.swarm_based.STO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.SeaHO module --------------------------------- - -.. automodule:: mealpy.swarm_based.SeaHO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.ServalOA module ------------------------------------ - -.. automodule:: mealpy.swarm_based.ServalOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.TDO module ------------------------------- - -.. automodule:: mealpy.swarm_based.TDO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.TSO module ------------------------------- - -.. automodule:: mealpy.swarm_based.TSO - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.WOA module ------------------------------- - -.. automodule:: mealpy.swarm_based.WOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.WaOA module -------------------------------- - -.. automodule:: mealpy.swarm_based.WaOA - :members: - :undoc-members: - :show-inheritance: - -mealpy.swarm\_based.ZOA module ------------------------------- - -.. automodule:: mealpy.swarm_based.ZOA - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.system_based.rst b/docs/source/pages/models/mealpy.system_based.rst deleted file mode 100644 index 4096f4c1..00000000 --- a/docs/source/pages/models/mealpy.system_based.rst +++ /dev/null @@ -1,27 +0,0 @@ -mealpy.system\_based package -============================ - - -mealpy.system\_based.AEO module -------------------------------- - -.. automodule:: mealpy.system_based.AEO - :members: - :undoc-members: - :show-inheritance: - -mealpy.system\_based.GCO module -------------------------------- - -.. automodule:: mealpy.system_based.GCO - :members: - :undoc-members: - :show-inheritance: - -mealpy.system\_based.WCA module -------------------------------- - -.. automodule:: mealpy.system_based.WCA - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.utils.rst b/docs/source/pages/models/mealpy.utils.rst deleted file mode 100644 index 5ec5f170..00000000 --- a/docs/source/pages/models/mealpy.utils.rst +++ /dev/null @@ -1,81 +0,0 @@ -mealpy.utils package -==================== - - -.. toctree:: - :maxdepth: 4 - - mealpy.utils.visualize - - -mealpy.utils.agent module -------------------------- - -.. automodule:: mealpy.utils.agent - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.history module ---------------------------- - -.. automodule:: mealpy.utils.history - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.io module ----------------------- - -.. automodule:: mealpy.utils.io - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.logger module --------------------------- - -.. automodule:: mealpy.utils.logger - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.problem module ---------------------------- - -.. automodule:: mealpy.utils.problem - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.space module -------------------------- - -.. automodule:: mealpy.utils.space - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.target module --------------------------- - -.. automodule:: mealpy.utils.target - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.termination module -------------------------------- - -.. automodule:: mealpy.utils.termination - :members: - :undoc-members: - :show-inheritance: - -mealpy.utils.validator module ------------------------------ - -.. automodule:: mealpy.utils.validator - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/models/mealpy.utils.visualize.rst b/docs/source/pages/models/mealpy.utils.visualize.rst deleted file mode 100644 index 8b7b7c3f..00000000 --- a/docs/source/pages/models/mealpy.utils.visualize.rst +++ /dev/null @@ -1,10 +0,0 @@ -mealpy.utils.visualize package -============================== - -mealpy.utils.visualize.linechart module ---------------------------------------- - -.. automodule:: mealpy.utils.visualize.linechart - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/pages/quick_start.rst b/docs/source/pages/quick_start.rst deleted file mode 100644 index 920292ca..00000000 --- a/docs/source/pages/quick_start.rst +++ /dev/null @@ -1,14 +0,0 @@ - -.. toctree:: - :maxdepth: 4 - - general/introduction.rst - general/simple_guide.rst - general/advance_guide.rst - general/video_tutorials.rst - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 \ No newline at end of file diff --git a/docs/source/pages/support.rst b/docs/source/pages/support.rst deleted file mode 100644 index df4bbebd..00000000 --- a/docs/source/pages/support.rst +++ /dev/null @@ -1,85 +0,0 @@ -================ -Citation Request -================ - -Please include these citations if you plan to use this library:: - - @article{van2023mealpy, - title={MEALPY: An open-source library for latest meta-heuristic algorithms in Python}, - author={Van Thieu, Nguyen and Mirjalili, Seyedali}, - journal={Journal of Systems Architecture}, - year={2023}, - publisher={Elsevier}, - doi={10.1016/j.sysarc.2023.102871} - } - - @article{van2023groundwater, - title={Groundwater level modeling using Augmented Artificial Ecosystem Optimization}, - author={Van Thieu, Nguyen and Barma, Surajit Deb and Van Lam, To and Kisi, Ozgur and Mahesha, Amai}, - journal={Journal of Hydrology}, - volume={617}, - pages={129034}, - year={2023}, - publisher={Elsevier}, - doi={10.1016/j.jhydrol.2022.129034} - } -``` - - -If you have an open-ended or a research question, you can contact me via nguyenthieu2102@gmail.com - - -============== -Official Links -============== - - -* Official source code repo: https://github.com/thieu1995/mealpy -* Official document: https://mealpy.readthedocs.io/ -* Download releases: https://pypi.org/project/mealpy/ -* Issue tracker: https://github.com/thieu1995/mealpy/issues -* Notable changes log: https://github.com/thieu1995/mealpy/blob/master/ChangeLog.md -* Examples with different meapy version: https://github.com/thieu1995/mealpy/blob/master/examples/EXAMPLES.md -* Official chat/support group: https://t.me/+fRVCJGuGJg1mNDg1 - -* This project also related to our another projects which are "meta-heuristics" and "machine learning", check it here: - * https://github.com/thieu1995/opfunu - * https://github.com/thieu1995/metaheuristics - * https://github.com/thieu1995/enoppy - * https://github.com/thieu1995/MetaCluster - * https://github.com/thieu1995/pfevaluator - * https://github.com/mafese - * https://github.com/permetrics - * https://github.com/aiir-team - - -==================== -Classification Table -==================== - -.. include:: general/classification_table.rst - - -================= -Model References -================= - -.. include:: general/references.rst - - -======= -License -======= - -The project is licensed under MIT license. - - -.. toctree:: - :maxdepth: 4 - -.. toctree:: - :maxdepth: 4 - - -.. toctree:: - :maxdepth: 4 diff --git a/examples/EXAMPLES.md b/examples/EXAMPLES.md index 147c2726..c92b3797 100644 --- a/examples/EXAMPLES.md +++ b/examples/EXAMPLES.md @@ -43,7 +43,6 @@ 1:39:28 - Metaheuristic Algorithm method for tunning hyper-parameters ``` - ### Example * Please don't misunderstand between parameters (hyper-parameters) and variables. @@ -99,12 +98,11 @@ best_position, best_fitness = model1.solve() print(f"Best solution: {best_position}, Best fitness: {best_fitness}") ``` - ## Version Mealpy == 2.3.0 * Almost same as version 2.2.0 but - * The default amend_position function is moved from Optimizer to Problem class - * amend_position can be used to rebound the position of agent, therefore can be used to solve discrete problem + * The default amend_position function is moved from Optimizer to Problem class + * amend_position can be used to rebound the position of agent, therefore can be used to solve discrete problem ```python from mealpy.bio_based import SMA @@ -134,15 +132,14 @@ print(f"Best solution: {best_position}, Best fitness: {best_fitness}") ## Version Mealpy == 2.2.0 * Almost same as version 2.1.2 but - * You can pass the Problem dictionary or Problem object to the model. - * You can pass the Termination dictionary or Termination object to the model. - * The objective function is renamed as fitness function (obj_func -> fit_func) - * The general format of a solution is: **\[position, target\]** - * position: numpy vector (1-D array) - * target: **\[fitness, list_objectives\]** - * list_objectives: **\[objective 1, objective 2, ...\]** - * After the training process, everything can be accessed via the objective "history" (model.history) - + * You can pass the Problem dictionary or Problem object to the model. + * You can pass the Termination dictionary or Termination object to the model. + * The objective function is renamed as fitness function (obj_func -> fit_func) + * The general format of a solution is: **\[position, target\]** + * position: numpy vector (1-D array) + * target: **\[fitness, list_objectives\]** + * list_objectives: **\[objective 1, objective 2, ...\]** + * After the training process, everything can be accessed via the objective "history" (model.history) ```python from mealpy.bio_based import SMA @@ -164,12 +161,10 @@ model1 = SMA.BaseSMA(problem_dict1, epoch=100, pop_size=50, pr=0.03) best_position, best_fitness = model1.solve() print(f"Best solution: {best_position}, Best fitness: {best_fitness}") ``` - - ## Version 2.0.0 <= Mealpy <= 2.1.2 -* The batch-size idea is removed due to the new feature which is parallel training. +* The batch-size idea is removed due to the new feature which is parallel training. ```python @@ -368,9 +363,6 @@ model10.solve() ``` - - - ## Version 1.1.0 <= Mealpy <= 1.2.2 * The batch-size idea is not existed in Meta-heuristics field. I just take an inspiration from training batch-size of @@ -469,7 +461,7 @@ print(md1.solution[1]) print(md1.loss_train) ``` -## Mealpy <= 1.0.5 +## Mealpy <= 1.0.5 ```python # Simple example: this is for previous version ( version <= 1.0.5) diff --git a/examples/applications/discrete-problems/cloud_task_scheduling.py b/examples/applications/discrete-problems/cloud_task_scheduling.py index 1b8db516..d120eb5a 100644 --- a/examples/applications/discrete-problems/cloud_task_scheduling.py +++ b/examples/applications/discrete-problems/cloud_task_scheduling.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import PermutationVar, ACOR, Problem @@ -19,15 +20,16 @@ def obj_func(self, x): t = np.zeros((self.data["n_jobs"], self.data["n_machines"])) for job in range(self.data["n_jobs"]): for machine in range(self.data["n_machines"]): - if machine==0 and job ==0: - t[job,machine] = self.data["p"][int(order[job]),machine] - elif machine==0: - t[job,machine]=t[job-1, machine]+self.data["p"][int(order[job]),machine] - elif job==0: - t[job,machine]=t[job, machine-1]+self.data["p"][int(order[job]),machine] + if machine == 0 and job == 0: + t[job, machine] = self.data["p"][int(order[job]), machine] + elif machine == 0: + t[job, machine] = t[job - 1, machine] + self.data["p"][int(order[job]), machine] + elif job == 0: + t[job, machine] = t[job, machine - 1] + self.data["p"][int(order[job]), machine] else: - t[job,machine]=max(t[job-1, machine],t[job, machine-1])+self.data["p"][int(order[job]),machine] - makespan=t[-1,-1] + t[job, machine] = max(t[job - 1, machine], t[job, machine - 1]) + self.data["p"][ + int(order[job]), machine] + makespan = t[-1, -1] return makespan @@ -45,7 +47,7 @@ def obj_func(self, x): problem = MyProblem(bounds=PermutationVar(valid_set=(0, 1, 2, 3, 4), name="delta"), name="Wow", minmax="min", data=data, log_to="console") -model = ACOR.OriginalACOR(epoch=50, pop_size=20, sample_count = 25, intent_factor = 0.5, zeta = 1.0) +model = ACOR.OriginalACOR(epoch=50, pop_size=20, sample_count=25, intent_factor=0.5, zeta=1.0) g_best = model.solve(problem) print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") diff --git a/examples/applications/discrete-problems/employee_rostering.py b/examples/applications/discrete-problems/employee_rostering.py index 9ad92e42..bc7d3e6c 100644 --- a/examples/applications/discrete-problems/employee_rostering.py +++ b/examples/applications/discrete-problems/employee_rostering.py @@ -18,8 +18,8 @@ import numpy as np -from mealpy import IntegerVar, WOA, Problem +from mealpy import IntegerVar, WOA, Problem shift_requirements = np.array([[2, 1, 3], [4, 2, 1], [3, 3, 2]]) shift_costs = np.array([10, 8, 12]) @@ -34,6 +34,7 @@ "num_shifts": num_shifts } + class EmployeeRosteringProblem(Problem): def __init__(self, bounds=None, minmax="min", data=None, **kwargs): super().__init__(bounds, minmax, **kwargs) @@ -54,13 +55,13 @@ def obj_func(self, x): return total_cost + coverage_penalty -bounds = IntegerVar(lb=[0, ]*num_employees, ub=[num_shifts-1, ]*num_employees, name="shift_var") +bounds = IntegerVar(lb=[0, ] * num_employees, ub=[num_shifts - 1, ] * num_employees, name="shift_var") problem = EmployeeRosteringProblem(bounds=bounds, minmax="min", data=data) model = WOA.OriginalWOA(epoch=50, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution +print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution diff --git a/examples/applications/discrete-problems/job_shop_scheduling.py b/examples/applications/discrete-problems/job_shop_scheduling.py index fcdec9c9..df1d86d7 100644 --- a/examples/applications/discrete-problems/job_shop_scheduling.py +++ b/examples/applications/discrete-problems/job_shop_scheduling.py @@ -10,8 +10,8 @@ # specific requirements and constraints of your Job Shop Scheduling problem. import numpy as np -from mealpy import PermutationVar, WOA, Problem +from mealpy import PermutationVar, WOA, Problem job_times = [[2, 1, 3], [4, 2, 1], [3, 3, 2]] machine_times = [[3, 2, 1], [1, 4, 2], [2, 3, 2]] @@ -26,6 +26,7 @@ "n_machines": n_machines } + class JobShopProblem(Problem): def __init__(self, bounds=None, minmax="min", data=None, **kwargs): super().__init__(bounds, minmax, **kwargs) @@ -45,17 +46,19 @@ def obj_func(self, x): elif machine_idx == 0: makespan[job_idx][machine_idx] = makespan[job_idx - 1][machine_idx] + job_times[job_idx][machine_idx] else: - makespan[job_idx][machine_idx] = max(makespan[job_idx][machine_idx - 1], makespan[job_idx - 1][machine_idx]) + job_times[job_idx][machine_idx] + makespan[job_idx][machine_idx] = max(makespan[job_idx][machine_idx - 1], + makespan[job_idx - 1][machine_idx]) + job_times[job_idx][ + machine_idx] return np.max(makespan) -bounds = PermutationVar(valid_set=list(range(0, n_jobs*n_machines)), name="per_var") +bounds = PermutationVar(valid_set=list(range(0, n_jobs * n_machines)), name="per_var") problem = JobShopProblem(bounds=bounds, minmax="min", data=data) model = WOA.OriginalWOA(epoch=100, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution +print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution diff --git a/examples/applications/discrete-problems/knapsack_problem.ipynb b/examples/applications/discrete-problems/knapsack_problem.ipynb index 0b42cd60..e01a5bb2 100644 --- a/examples/applications/discrete-problems/knapsack_problem.ipynb +++ b/examples/applications/discrete-problems/knapsack_problem.ipynb @@ -31,7 +31,14 @@ "source": [ "# Solver\n", "\n", - "We gonna use WOA to solve this problem\n" + "We\n", + "gonna\n", + "use\n", + "WOA\n", + "to\n", + "solve\n", + "this\n", + "problem\n" ], "metadata": { "collapsed": false, @@ -175,16 +182,17 @@ } ], "source": [ - "from mealpy import BinaryVar, Problem, WOA\n", "import numpy as np\n", "\n", + "from mealpy import BinaryVar, Problem, WOA\n", + "\n", "\n", "class KP(Problem):\n", " def __init__(self, bounds=None, minmax=\"min\", name=\"KP\", data=None, **kwargs):\n", " self.name = name\n", " self.data = data\n", " super().__init__(bounds, minmax, **kwargs)\n", - " \n", + "\n", " def constrains(self, capacity):\n", " return capacity - self.data[\"capacity\"]\n", "\n", @@ -194,22 +202,22 @@ " current_capacity = np.sum(x * self.data[\"weights\"])\n", " violation = max(0, self.constrains(current_capacity))\n", " value = np.sum(x * self.data[\"values\"])\n", - " return value - violation**2\n", + " return value - violation ** 2\n", + "\n", "\n", "data = {\n", " \"values\": np.array([\n", " 360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,\n", " 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28,\n", " 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276,\n", - " 312 ]),\n", + " 312]),\n", " \"weights\": np.array([\n", - " 7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,\n", - " 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,\n", - " 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13 ]),\n", + " 7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,\n", + " 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,\n", + " 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13]),\n", " \"capacity\": 850\n", "}\n", "\n", - " \n", "## Now, we define an algorithm\n", "problem = KP(bounds=BinaryVar(n_vars=50, name=\"bin\"), minmax=\"max\", name=\"KP\", data=data)\n", "model = WOA.OriginalWOA(epoch=100, pop_size=30)\n", @@ -251,4 +259,4 @@ }, "nbformat": 4, "nbformat_minor": 1 -} \ No newline at end of file +} diff --git a/examples/applications/discrete-problems/location_optimization.py b/examples/applications/discrete-problems/location_optimization.py index 8d6e7da7..9da9a758 100644 --- a/examples/applications/discrete-problems/location_optimization.py +++ b/examples/applications/discrete-problems/location_optimization.py @@ -45,6 +45,7 @@ # mathematical modeling, and optimization techniques to determine the optimal locations for facilities. import numpy as np + from mealpy import BinaryVar, WOA, Problem # Define the coordinates of potential store locations @@ -88,9 +89,9 @@ def obj_func(self, x): x = x_decoded["placement_var"] total_coverage = np.sum(x) total_dist = np.sum(x[:, np.newaxis] * distance_matrix) - if total_dist == 0: # Penalize solutions with fewer stores + if total_dist == 0: # Penalize solutions with fewer stores return self.eps - if total_coverage < self.data["num_stores"]: # Penalize solutions with fewer stores + if total_coverage < self.data["num_stores"]: # Penalize solutions with fewer stores return self.eps return total_dist @@ -101,7 +102,7 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=50, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution +print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution diff --git a/examples/applications/discrete-problems/maintenance_scheduling.py b/examples/applications/discrete-problems/maintenance_scheduling.py index 471cd18c..c747ae16 100644 --- a/examples/applications/discrete-problems/maintenance_scheduling.py +++ b/examples/applications/discrete-problems/maintenance_scheduling.py @@ -19,8 +19,8 @@ import numpy as np -from mealpy import BinaryVar, WOA, Problem +from mealpy import BinaryVar, WOA, Problem num_tasks = 10 num_assets = 5 @@ -30,7 +30,7 @@ "num_tasks": num_tasks, "num_assets": num_assets, "task_durations": task_durations, - "unassigned_penalty": -100 # Define a penalty value for no task is assigned to asset + "unassigned_penalty": -100 # Define a penalty value for no task is assigned to asset } @@ -54,7 +54,8 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=50, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution).reshape((num_tasks, num_assets))}") # Decoded (Real) solution +print( + f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution).reshape((num_tasks, num_assets))}") # Decoded (Real) solution diff --git a/examples/applications/discrete-problems/product_planning.ipynb b/examples/applications/discrete-problems/product_planning.ipynb index 3c1888fa..a8fa153e 100644 --- a/examples/applications/discrete-problems/product_planning.ipynb +++ b/examples/applications/discrete-problems/product_planning.ipynb @@ -1189,28 +1189,28 @@ ], "source": [ "from mealpy import IntegerVar, Problem, SMA\n", - "import numpy as np\n", "\n", "\n", "class PPP(Problem):\n", " def __init__(self, bounds=None, minmax=\"min\", name=\"PPP\", **kwargs):\n", " self.name = name\n", " super().__init__(bounds, minmax, **kwargs)\n", - " \n", + "\n", " def constrains(self, x):\n", - " g1 = 2*x[0] + 3*x[1] - 100\n", - " g2 = 3*x[0] + 2*x[1] - 80\n", + " g1 = 2 * x[0] + 3 * x[1] - 100\n", + " g2 = 3 * x[0] + 2 * x[1] - 80\n", " return [g1, g2]\n", "\n", " def obj_func(self, solution):\n", - " solution = self.decode_solution(solution) \n", + " solution = self.decode_solution(solution)\n", " x = solution[\"var\"]\n", " g1, g2 = self.constrains(x)\n", - " profit = 5*x[0] + 4*x[1]\n", + " profit = 5 * x[0] + 4 * x[1]\n", " violation = max(g1, 0) + max(g2, 0)\n", - " return profit - violation**2\n", + " return profit - violation ** 2\n", + "\n", "\n", - "## Now, we define an algorithm, and pass an instance of our *Squared* class as the problem argument. \n", + "## Now, we define an algorithm, and pass an instance of our *Squared* class as the problem argument.\n", "problem = PPP(bounds=IntegerVar(lb=(0, 0), ub=(80, 80), name=\"var\"), minmax=\"max\", name=\"PPP\")\n", "model = SMA.OriginalSMA(epoch=1000, pop_size=30)\n", "g_best = model.solve(problem)\n", @@ -1247,4 +1247,4 @@ }, "nbformat": 4, "nbformat_minor": 1 -} \ No newline at end of file +} diff --git a/examples/applications/discrete-problems/production_optimization.py b/examples/applications/discrete-problems/production_optimization.py index d55a97d2..ffa1db05 100644 --- a/examples/applications/discrete-problems/production_optimization.py +++ b/examples/applications/discrete-problems/production_optimization.py @@ -38,7 +38,7 @@ # and meeting customer demands, while considering various constraints and factors specific to the production environment. -#============================================== EXAMPLE ======================================================== +# ============================================== EXAMPLE ======================================================== # Let's consider a simplified example of production optimization in the context of a manufacturing company that produces electronic devices, # such as smartphones. The objective is to maximize production output while minimizing production costs. @@ -70,6 +70,7 @@ import numpy as np + from mealpy import BinaryVar, WOA, Problem # Define the problem parameters @@ -117,7 +118,7 @@ def obj_func(self, x): x = x_decoded["placement_var"].reshape((self.data["num_tasks"], self.data["num_resources"])) # If any row has all 0 value, it indicates that this task is not allocated to any resource - if np.any(np.all(x==0, axis=1)) or np.any(np.all(x==0, axis=0)): + if np.any(np.all(x == 0, axis=1)) or np.any(np.all(x == 0, axis=0)): return self.data["penalty"] # Check violated constraints @@ -135,14 +136,16 @@ def obj_func(self, x): violated_constraints += 1 # Quality constraint - defect_rate = np.dot(self.data["production_costs"].reshape(1, -1), x) / np.dot(self.data["production_outputs"], x) + defect_rate = np.dot(self.data["production_costs"].reshape(1, -1), x) / np.dot(self.data["production_outputs"], + x) if np.any(defect_rate > max_defect_rate): violated_constraints += 1 # Calculate the fitness value based on the objectives and constraints - profit = np.sum(np.dot(self.data["production_outputs"].reshape(1, -1), x)) - np.sum(np.dot(self.data["production_costs"].reshape(1, -1), x)) + profit = np.sum(np.dot(self.data["production_outputs"].reshape(1, -1), x)) - np.sum( + np.dot(self.data["production_costs"].reshape(1, -1), x)) if violated_constraints > 0: - return profit + self.data["penalty"] * violated_constraints # Penalize solutions with violated constraints + return profit + self.data["penalty"] * violated_constraints # Penalize solutions with violated constraints return profit @@ -152,7 +155,8 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=50, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_tasks, num_resources))}") +print( + f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_tasks, num_resources))}") diff --git a/examples/applications/discrete-problems/shortest_path_problem.py b/examples/applications/discrete-problems/shortest_path_problem.py index 9c8a8f4a..bc441c69 100644 --- a/examples/applications/discrete-problems/shortest_path_problem.py +++ b/examples/applications/discrete-problems/shortest_path_problem.py @@ -13,6 +13,7 @@ # Further modifications and optimizations may be required depending on your specific use case. import numpy as np + from mealpy import PermutationVar, WOA, Problem # Define the graph representation @@ -30,7 +31,7 @@ class ShortestPathProblem(Problem): def __init__(self, bounds=None, minmax="min", data=None, **kwargs): super().__init__(bounds, minmax, **kwargs) self.data = data - self.eps = 1e10 # Penalty function for vertex with 0 connection + self.eps = 1e10 # Penalty function for vertex with 0 connection # Calculate the fitness of an individual def obj_func(self, x): @@ -55,7 +56,7 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=100, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution +print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution diff --git a/examples/applications/discrete-problems/supply_chain_optimization.py b/examples/applications/discrete-problems/supply_chain_optimization.py index 077029b7..9495174e 100644 --- a/examples/applications/discrete-problems/supply_chain_optimization.py +++ b/examples/applications/discrete-problems/supply_chain_optimization.py @@ -92,6 +92,7 @@ import numpy as np + from mealpy import BinaryVar, WOA, Problem # Define the problem parameters @@ -105,8 +106,8 @@ "num_products": num_products, "num_distribution_centers": num_distribution_centers, "transportation_cost": transportation_cost, - "max_capacity": 4, # Maximum capacity of each distribution center - "penalty": 1e10 # Define a penalty value for maximum capacity of each distribution center + "max_capacity": 4, # Maximum capacity of each distribution center + "penalty": 1e10 # Define a penalty value for maximum capacity of each distribution center } @@ -119,7 +120,8 @@ def obj_func(self, x): x_decoded = self.decode_solution(x) x = x_decoded["placement_var"].reshape((self.data["num_products"], self.data["num_distribution_centers"])) - if np.any(np.all(x==0, axis=1)): # If any row has all 0 value, it indicates that this product is not allocated to any distribution center. + if np.any(np.all(x == 0, + axis=1)): # If any row has all 0 value, it indicates that this product is not allocated to any distribution center. return 0 total_cost = np.sum(self.data["transportation_cost"] * x) @@ -137,7 +139,8 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=50, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_products, num_distribution_centers))}") +print( + f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_products, num_distribution_centers))}") diff --git a/examples/applications/discrete-problems/traveling_salesman_problem.py b/examples/applications/discrete-problems/traveling_salesman_problem.py index 2b863dab..000a28a1 100644 --- a/examples/applications/discrete-problems/traveling_salesman_problem.py +++ b/examples/applications/discrete-problems/traveling_salesman_problem.py @@ -14,6 +14,7 @@ import numpy as np + from mealpy import PermutationVar, WOA, Problem # Define the positions of the cities @@ -27,6 +28,7 @@ "num_cities": num_cities, } + class TspProblem(Problem): def __init__(self, bounds=None, minmax="min", data=None, **kwargs): super().__init__(bounds, minmax, **kwargs) @@ -61,7 +63,7 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=100, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution +print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)}") # Decoded (Real) solution diff --git a/examples/applications/discrete-problems/workflow_optimization.py b/examples/applications/discrete-problems/workflow_optimization.py index dd6940ab..8fe47822 100644 --- a/examples/applications/discrete-problems/workflow_optimization.py +++ b/examples/applications/discrete-problems/workflow_optimization.py @@ -79,6 +79,7 @@ import numpy as np + from mealpy import BinaryVar, WOA, Problem # Define the problem parameters @@ -93,9 +94,9 @@ "num_patients": num_patients, "num_resources": num_resources, "waiting_matrix": waiting_matrix, - "max_resource_capacity": 10, # Maximum capacity of each room - "max_waiting_time": 60, # Maximum waiting time - "penalty_value": 1e2, # Define a penalty value + "max_resource_capacity": 10, # Maximum capacity of each room + "max_waiting_time": 60, # Maximum waiting time + "penalty_value": 1e2, # Define a penalty value "penalty_patient": 1e10 } @@ -111,19 +112,21 @@ def obj_func(self, x): # If any row has all 0 value, it indicates that this patient is not allocated to any room. # If a patient a assigned to more than 3 room, not allow - if np.any(np.all(x==0, axis=1)) or np.any(np.sum(x>3, axis=1)): + if np.any(np.all(x == 0, axis=1)) or np.any(np.sum(x > 3, axis=1)): return self.data["penalty_patient"] # Calculate fitness based on optimization objectives room_used = np.sum(x, axis=0) wait_time = np.sum(x * self.data["waiting_matrix"], axis=1) - violated_constraints = np.sum(room_used > self.data["max_resource_capacity"]) + np.sum(wait_time > self.data["max_waiting_time"]) + violated_constraints = np.sum(room_used > self.data["max_resource_capacity"]) + np.sum( + wait_time > self.data["max_waiting_time"]) # Calculate the fitness value based on the objectives resource_utilization_fitness = 1 - np.mean(room_used) / self.data["max_resource_capacity"] waiting_time_fitness = 1 - np.mean(wait_time) / self.data["max_waiting_time"] - fitness = resource_utilization_fitness + waiting_time_fitness + self.data['penalty_value'] * violated_constraints + fitness = resource_utilization_fitness + waiting_time_fitness + self.data[ + 'penalty_value'] * violated_constraints return fitness @@ -133,7 +136,8 @@ def obj_func(self, x): model = WOA.OriginalWOA(epoch=50, pop_size=20) model.solve(problem) -print(f"Best agent: {model.g_best}") # Encoded solution -print(f"Best solution: {model.g_best.solution}") # Encoded solution +print(f"Best agent: {model.g_best}") # Encoded solution +print(f"Best solution: {model.g_best.solution}") # Encoded solution print(f"Best fitness: {model.g_best.target.fitness}") -print(f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_patients, num_resources))}") +print( + f"Best real scheduling: {model.problem.decode_solution(model.g_best.solution)['placement_var'].reshape((num_patients, num_resources))}") diff --git a/examples/applications/gear_box/gear_box_optimization.py b/examples/applications/gear_box/gear_box_optimization.py index 402bc9f5..25695ad0 100644 --- a/examples/applications/gear_box/gear_box_optimization.py +++ b/examples/applications/gear_box/gear_box_optimization.py @@ -1,8 +1,7 @@ - -from tkinter import W -from mealpy import FloatVar, WOA, GOA, GWO import numpy as np +from mealpy import FloatVar, WOA + """ refenrence article: https://www.tandfonline.com/doi/abs/10.1080/0305215X.2018.1509963 @@ -65,7 +64,8 @@ def violate(value): return 0 if value <= 0 else value fx = (np.pi / 4) * (rho / 1000) * ( - b * pow(m, 2) * pow(Z1, 2) * (pow(i, 2) + 1) - (pow(D_i, 2) - pow(d_0, 2)) * (l - b_w) - (n * pow(d_p, 2) * b_w) - (d_1 - d_2) * b) + b * pow(m, 2) * pow(Z1, 2) * (pow(i, 2) + 1) - (pow(D_i, 2) - pow(d_0, 2)) * (l - b_w) - ( + n * pow(d_p, 2) * b_w) - (d_1 - d_2) * b) fx += violate(g1(x)) + violate(g2(x)) + violate(g3(x)) return fx diff --git a/examples/applications/keras/mha-hybrid-mlp-classification.py b/examples/applications/keras/mha-hybrid-mlp-classification.py index c09d0616..f375c469 100644 --- a/examples/applications/keras/mha-hybrid-mlp-classification.py +++ b/examples/applications/keras/mha-hybrid-mlp-classification.py @@ -7,9 +7,10 @@ # https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/ import numpy as np -from keras.models import Sequential from keras.layers import Dense +from keras.models import Sequential from sklearn.metrics import accuracy_score + from mealpy import GWO, FloatVar @@ -39,7 +40,7 @@ def create_network(self): def create_problem(self): self.problem = { "obj_func": self.fitness_function, - "bounds": FloatVar(lb=(-1.,)*self.n_dims, ub=(1.,)*self.n_dims), + "bounds": FloatVar(lb=(-1.,) * self.n_dims, ub=(1.,) * self.n_dims), "minmax": "max", "log_to": "console", } diff --git a/examples/applications/keras/mha-hybrid-mlp-time-series.py b/examples/applications/keras/mha-hybrid-mlp-time-series.py index 7372bff5..69817a72 100644 --- a/examples/applications/keras/mha-hybrid-mlp-time-series.py +++ b/examples/applications/keras/mha-hybrid-mlp-time-series.py @@ -16,11 +16,12 @@ # univariate mlp example import numpy as np -from keras.models import Sequential from keras.layers import Dense -from mealpy import FloatVar, FPA +from keras.models import Sequential from permetrics.regression import RegressionMetric +from mealpy import FloatVar, FPA + # split a univariate sequence into samples def split_sequence(sequence, n_steps): @@ -61,7 +62,7 @@ def create_problem(self): self.n_dims = (self.n_inputs * self.n_hidden_nodes) + self.n_hidden_nodes + (self.n_hidden_nodes * 1) + 1 self.problem = { "obj_func": self.fitness_function, - "bounds": FloatVar(lb=(-1.,)*self.n_dims, ub=(1.0,)*self.n_dims), + "bounds": FloatVar(lb=(-1.,) * self.n_dims, ub=(1.0,) * self.n_dims), "minmax": "min", "obj_weights": [0.3, 0.2, 0.5], # [mae, mse, rmse] } diff --git a/examples/applications/keras/mha-hyper-parameter-mlp-time-series.py b/examples/applications/keras/mha-hyper-parameter-mlp-time-series.py index 9e2a9e6c..68b0e856 100644 --- a/examples/applications/keras/mha-hyper-parameter-mlp-time-series.py +++ b/examples/applications/keras/mha-hyper-parameter-mlp-time-series.py @@ -68,9 +68,9 @@ # univariate mlp example from sklearn.preprocessing import LabelEncoder + from examples.applications.keras.timeseries_util import generate_data, decode_solution, generate_loss_value from mealpy.evolutionary_based import FPA -from mealpy.swarm_based import GWO def fitness_function(solution, data): @@ -85,7 +85,8 @@ def fitness_function(solution, data): OPT_ENCODER.fit(['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']) # domain range ==> 7 values WOI_ENCODER = LabelEncoder() - WOI_ENCODER.fit(['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']) + WOI_ENCODER.fit( + ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']) ACT_ENCODER = LabelEncoder() ACT_ENCODER.fit(['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']) diff --git a/examples/applications/keras/mode_mlp_hyper_parameter_tunning.py b/examples/applications/keras/mode_mlp_hyper_parameter_tunning.py index 190f7d4a..8e069291 100644 --- a/examples/applications/keras/mode_mlp_hyper_parameter_tunning.py +++ b/examples/applications/keras/mode_mlp_hyper_parameter_tunning.py @@ -4,13 +4,16 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% +import time from pathlib import Path + +import numpy as np from pandas import DataFrame +from sklearn.preprocessing import LabelEncoder + from mealpy.swarm_based import WOA from timeseries_util import decode_solution, generate_loss_value, generate_data -from sklearn.preprocessing import LabelEncoder -import time -import numpy as np + np.random.seed(12345) @@ -27,7 +30,8 @@ def fitness_function(solution, data): OPT_ENCODER.fit(['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']) # domain range ==> 7 values WOI_ENCODER = LabelEncoder() - WOI_ENCODER.fit(['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']) + WOI_ENCODER.fit( + ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']) ACT_ENCODER = LabelEncoder() ACT_ENCODER.fit(['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']) @@ -84,7 +88,8 @@ def fitness_function(solution, data): df = DataFrame(error_full, columns=error_columns) - df.to_csv(f"{PATH_ERROR}{len(LB)}D_{model_name}_{mode_name}_mlp_paras_tuning_error.csv", header=True, index=False) + df.to_csv(f"{PATH_ERROR}{len(LB)}D_{model_name}_{mode_name}_mlp_paras_tuning_error.csv", header=True, + index=False) best_fit_full[mode_name] = best_fit_list best_fit_columns.append(mode_name) diff --git a/examples/applications/keras/timeseries_util.py b/examples/applications/keras/timeseries_util.py index 3b16b865..da6ca6e0 100644 --- a/examples/applications/keras/timeseries_util.py +++ b/examples/applications/keras/timeseries_util.py @@ -6,12 +6,12 @@ # univariate mlp example import numpy as np -from sklearn.preprocessing import MinMaxScaler -from keras.models import Sequential -from keras.layers import Dense -from keras import optimizers import statsmodels.datasets.co2 as co2 +from keras import optimizers +from keras.layers import Dense +from keras.models import Sequential from permetrics.regression import RegressionMetric +from sklearn.preprocessing import MinMaxScaler # split a univariate sequence into samples @@ -106,7 +106,8 @@ def generate_loss_value(structure, data): model.compile(optimizer=optimizer, loss='mse') # fit model - model.fit(data["X_train"], data["y_train"], epochs=structure["epoch"], batch_size=structure["batch_size"], verbose=2) + model.fit(data["X_train"], data["y_train"], epochs=structure["epoch"], batch_size=structure["batch_size"], + verbose=2) # We take the loss value of validation set as a fitness value for selecting # the best model demonstrate prediction diff --git a/examples/applications/keras/traditional-mlp-classification.py b/examples/applications/keras/traditional-mlp-classification.py index 560b676e..4405be00 100644 --- a/examples/applications/keras/traditional-mlp-classification.py +++ b/examples/applications/keras/traditional-mlp-classification.py @@ -6,11 +6,11 @@ # https://machinelearningmastery.com/display-deep-learning-model-training-history-in-keras/ -# Visualize training history -from keras.models import Sequential -from keras.layers import Dense import matplotlib.pyplot as plt import numpy +from keras.layers import Dense +# Visualize training history +from keras.models import Sequential # load pima indians dataset dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",") diff --git a/examples/applications/keras/traditional-mlp-time-series.py b/examples/applications/keras/traditional-mlp-time-series.py index 1d2dd604..19ea648e 100644 --- a/examples/applications/keras/traditional-mlp-time-series.py +++ b/examples/applications/keras/traditional-mlp-time-series.py @@ -8,8 +8,9 @@ # univariate mlp example import numpy as np -from keras.models import Sequential from keras.layers import Dense +from keras.models import Sequential + # split a univariate sequence into samples def split_sequence(sequence, n_steps): @@ -54,4 +55,3 @@ def split_sequence(sequence, n_steps): x_input = x_input.reshape((1, n_steps)) yhat = model.predict(x_input, verbose=0) print(yhat) - diff --git a/examples/applications/pathplanning/pathplanning.py b/examples/applications/pathplanning/pathplanning.py index a657542f..56d8ba1d 100644 --- a/examples/applications/pathplanning/pathplanning.py +++ b/examples/applications/pathplanning/pathplanning.py @@ -1,10 +1,8 @@ +import matplotlib.pyplot as plt +import numpy as np +from scipy.interpolate import interp1d -from mealpy.swarm_based.WOA import OriginalWOA -from mealpy.swarm_based.PSO import OriginalPSO from mealpy.swarm_based.GWO import OriginalGWO -from scipy.interpolate import interp1d -import numpy as np -import matplotlib.pyplot as plt class PathPlanning(): diff --git a/examples/applications/pytorch/linear_regression.py b/examples/applications/pytorch/linear_regression.py index d0279da2..37244238 100644 --- a/examples/applications/pytorch/linear_regression.py +++ b/examples/applications/pytorch/linear_regression.py @@ -8,6 +8,7 @@ import numpy as np import torch from torch.autograd import Variable + from mealpy import StringVar, FloatVar, IntegerVar, BBO, Problem diff --git a/examples/applications/run_constraint_functions.py b/examples/applications/run_constraint_functions.py index dbdc26df..0be7226d 100644 --- a/examples/applications/run_constraint_functions.py +++ b/examples/applications/run_constraint_functions.py @@ -4,42 +4,52 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SMA import numpy as np +from mealpy import FloatVar, SMA + ## Link: https://onlinelibrary.wiley.com/doi/pdf/10.1002/9781119136507.app2 def objective_function(solution): def g1(x): - return 2*x[0] + 2*x[1] + x[9] + x[10] - 10 + return 2 * x[0] + 2 * x[1] + x[9] + x[10] - 10 + def g2(x): return 2 * x[0] + 2 * x[2] + x[9] + x[10] - 10 + def g3(x): return 2 * x[1] + 2 * x[2] + x[10] + x[11] - 10 + def g4(x): - return -8*x[0] + x[9] + return -8 * x[0] + x[9] + def g5(x): - return -8*x[1] + x[10] + return -8 * x[1] + x[10] + def g6(x): - return -8*x[2] + x[11] + return -8 * x[2] + x[11] + def g7(x): - return -2*x[3] - x[4] + x[9] + return -2 * x[3] - x[4] + x[9] + def g8(x): - return -2*x[5] - x[6] + x[10] + return -2 * x[5] - x[6] + x[10] + def g9(x): - return -2*x[7] - x[8] + x[11] + return -2 * x[7] - x[8] + x[11] def violate(value): return 0 if value <= 0 else value - fx = 5 * np.sum(solution[:4]) - 5*np.sum(solution[:4]**2) - np.sum(solution[4:13]) + fx = 5 * np.sum(solution[:4]) - 5 * np.sum(solution[:4] ** 2) - np.sum(solution[4:13]) ## Increase the punishment for g1 and g4 to boost the algorithm (You can choice any constraint instead of g1 and g4) - fx += violate(g1(solution))**2 + violate(g2(solution)) + violate(g3(solution)) + \ - 2*violate(g4(solution)) + violate(g5(solution)) + violate(g6(solution))+ \ - violate(g7(solution)) + violate(g8(solution)) + violate(g9(solution)) + fx += violate(g1(solution)) ** 2 + violate(g2(solution)) + violate(g3(solution)) + \ + 2 * violate(g4(solution)) + violate(g5(solution)) + violate(g6(solution)) + \ + violate(g7(solution)) + violate(g8(solution)) + violate(g9(solution)) return fx + problem = { "obj_func": objective_function, "bounds": FloatVar(lb=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ub=[1, 1, 1, 1, 1, 1, 1, 1, 1, 100, 100, 100, 1]), diff --git a/examples/applications/run_distributed_optimization.py b/examples/applications/run_distributed_optimization.py index b55ee5de..a77c69d2 100644 --- a/examples/applications/run_distributed_optimization.py +++ b/examples/applications/run_distributed_optimization.py @@ -14,26 +14,27 @@ distributed execution where applicable, allowing you to leverage multiple threads or CPU cores to speed up computation. """ +import numpy as np from mealpy import FloatVar, SMA -import numpy as np def objective_function(solution): - return np.sum(solution**2) + return np.sum(solution ** 2) + problem = { "obj_func": objective_function, - "bounds": FloatVar(lb=(-100., )*100, ub=(100., )*100), + "bounds": FloatVar(lb=(-100.,) * 100, ub=(100.,) * 100), "minmax": "min", "log_to": "console", } ## Run distributed SMA algorithm using 10 threads optimizer = SMA.OriginalSMA(epoch=10000, pop_size=100, pr=0.03) -optimizer.solve(problem, mode="thread", n_workers=10) # Distributed to 10 threads +optimizer.solve(problem, mode="thread", n_workers=10) # Distributed to 10 threads print(f"Best solution: {optimizer.g_best.solution}, Best fitness: {optimizer.g_best.target.fitness}") ## Run distributed SMA algorithm using 8 CPUs (cores) -optimizer.solve(problem, mode="process", n_workers=8) # Distributed to 8 cores +optimizer.solve(problem, mode="process", n_workers=8) # Distributed to 8 cores print(f"Best solution: {optimizer.g_best.solution}, Best fitness: {optimizer.g_best.target.fitness}") diff --git a/examples/applications/run_large_scale_optimization.py b/examples/applications/run_large_scale_optimization.py index baf3eb8d..e25dca7a 100644 --- a/examples/applications/run_large_scale_optimization.py +++ b/examples/applications/run_large_scale_optimization.py @@ -11,16 +11,18 @@ Here's an example demonstrating how to set up and run an optimization for a large-scale problem. """ +import numpy as np from mealpy import FloatVar, SHADE -import numpy as np + def objective_function(solution): - return np.sum(solution**2) + return np.sum(solution ** 2) + problem = { "obj_func": objective_function, - "bounds": FloatVar(lb=(-1000., )*10000, ub=(1000.,)*10000), # 10000 dimensions + "bounds": FloatVar(lb=(-1000.,) * 10000, ub=(1000.,) * 10000), # 10000 dimensions "minmax": "min", "log_to": "console", } diff --git a/examples/applications/run_multi_objective_functions.py b/examples/applications/run_multi_objective_functions.py index a09fe71d..85b00401 100644 --- a/examples/applications/run_multi_objective_functions.py +++ b/examples/applications/run_multi_objective_functions.py @@ -5,20 +5,20 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, SMA ## Link: https://en.wikipedia.org/wiki/Test_functions_for_optimization def objective_function(solution): - def booth(x, y): - return (x + 2*y - 7)**2 + (2*x + y - 5)**2 + return (x + 2 * y - 7) ** 2 + (2 * x + y - 5) ** 2 def bukin(x, y): - return 100 * np.sqrt(np.abs(y - 0.01 * x**2)) + 0.01 * np.abs(x + 10) + return 100 * np.sqrt(np.abs(y - 0.01 * x ** 2)) + 0.01 * np.abs(x + 10) def matyas(x, y): - return 0.26 * (x**2 + y**2) - 0.48 * x * y + return 0.26 * (x ** 2 + y ** 2) - 0.48 * x * y return [booth(solution[0], solution[1]), bukin(solution[0], solution[1]), matyas(solution[0], solution[1])] @@ -28,7 +28,7 @@ def matyas(x, y): "bounds": FloatVar(lb=(-10, -10), ub=(10, 10)), "minmax": "min", "log_to": "console", - "obj_weights": [0.4, 0.1, 0.5] # Define it or default value will be [1, 1, 1] + "obj_weights": [0.4, 0.1, 0.5] # Define it or default value will be [1, 1, 1] } ## Run the algorithm diff --git a/examples/applications/sklearn/svm_classification.py b/examples/applications/sklearn/svm_classification.py index cc0d674e..43442c11 100644 --- a/examples/applications/sklearn/svm_classification.py +++ b/examples/applications/sklearn/svm_classification.py @@ -146,14 +146,14 @@ # print(f"Best parameters: {model.problem.decode_solution(model.g_best.solution)}") -##################################### Mealpy 3.0.2 -from sklearn.svm import SVC +from sklearn import datasets, metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler -from sklearn import datasets, metrics -from mealpy import FloatVar, StringVar, SHADE, Problem -from mealpy import BBO +##################################### Mealpy 3.0.2 +from sklearn.svm import SVC +from mealpy import BBO +from mealpy import FloatVar, StringVar, SHADE, Problem # Load the data set; In this example, the breast cancer dataset is loaded. bc = datasets.load_breast_cancer() diff --git a/examples/applications/sklearn/svm_hyperparameter_optimization.py b/examples/applications/sklearn/svm_hyperparameter_optimization.py index 92412eb5..bbd42f79 100644 --- a/examples/applications/sklearn/svm_hyperparameter_optimization.py +++ b/examples/applications/sklearn/svm_hyperparameter_optimization.py @@ -11,15 +11,13 @@ This demonstrates how to integrate MEALPY with a machine learning workflow. """ - -from sklearn.svm import SVC +from sklearn import datasets, metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler -from sklearn import datasets, metrics +from sklearn.svm import SVC from mealpy import FloatVar, StringVar, IntegerVar, BoolVar, CategoricalVar, SMA, Problem - # Load the data set; In this example, the breast cancer dataset is loaded. X, y = datasets.load_breast_cancer(return_X_y=True) @@ -57,6 +55,7 @@ def obj_func(self, x): # Measure the performance return metrics.accuracy_score(self.data["y_test"], y_predict) + my_bounds = [ FloatVar(lb=0.01, ub=1000., name="C_paras"), StringVar(valid_sets=('linear', 'poly', 'rbf', 'sigmoid'), name="kernel_paras"), diff --git a/examples/build_new_optimizer.py b/examples/build_new_optimizer.py index 87e11a25..68832535 100644 --- a/examples/build_new_optimizer.py +++ b/examples/build_new_optimizer.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -66,7 +67,7 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - epxilon = 1 - 1 * (epoch + 1) / self.epoch # The epxilon in each epoch is changing based on this equation + epxilon = 1 - 1 * (epoch + 1) / self.epoch # The epxilon in each epoch is changing based on this equation ## 1. Replace the almost worst agent by random agent if np.random.uniform() < self.p1: @@ -87,7 +88,8 @@ def evolve(self, epoch): if idx == 0: pos_new = self.pop[idx][self.ID_POS] + epxilon * self.space * np.random.uniform(0, 1) else: - pos_new = self.pop[idx][self.ID_POS] + epxilon * self.space * (self.pop[0][self.ID_POS] - self.pop[idx][self.ID_POS]) + pos_new = self.pop[idx][self.ID_POS] + epxilon * self.space * ( + self.pop[0][self.ID_POS] - self.pop[idx][self.ID_POS]) pos_new = self.amend_position(pos_new, self.problem.lb, self.problem.ub) fit_new = self.get_target_wrapper(pos_new) if self.compare_agent([pos_new, fit_new], self.pop[idx]): @@ -98,12 +100,13 @@ def evolve(self, epoch): ## Time to test our new optimizer def fitness(solution): - return np.sum(solution**2) + return np.sum(solution ** 2) + problem_dict1 = { "fit_func": fitness, - "lb": [-100, ]*100, - "ub": [100, ]*100, + "lb": [-100, ] * 100, + "ub": [100, ] * 100, "minmax": "min", } diff --git a/examples/optimizers/run_bwo_example.py b/examples/optimizers/run_bwo_example.py index bbd89371..1129540e 100644 --- a/examples/optimizers/run_bwo_example.py +++ b/examples/optimizers/run_bwo_example.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, BWO diff --git a/examples/run_all_parameters.py b/examples/run_all_parameters.py index 9957a48c..4a7239bf 100644 --- a/examples/run_all_parameters.py +++ b/examples/run_all_parameters.py @@ -5,17 +5,19 @@ # --------------------------------------------------% from opfunu.cec_based.cec2017 import F292017 + from mealpy import FloatVar -from mealpy.bio_based import BBO, EOA, IWO, SBO, SMA, TPO, VCS, WHO +from mealpy.bio_based import BBO, EOA, IWO, SBO, SMA, VCS, WHO from mealpy.evolutionary_based import CRO, DE, EP, ES, FPA, GA, MA, SHADE from mealpy.human_based import BRO, BSO, CA, CHIO, FBIO, GSKA, ICA, LCO, QSA, SARO, SSDO, TLO from mealpy.math_based import AOA, CEM, CGO, GBO, HC, PSS, SCA from mealpy.music_based import HS from mealpy.physics_based import ArchOA, ASO, EFO, EO, HGSO, MVO, NRO, SA, TWO, WDO +from mealpy.swarm_based import ABC, ACOR, ALO, AO, BA, BeesA, BES, BFO, BSA, COA, CSA, CSO, DO, EHO, FA, FFA, FOA, GOA, \ + GWO, HGS +from mealpy.swarm_based import HHO, JA, MFO, MRFO, MSA, NMRA, PFA, PSO, SFO, SHO, SLO, SRSR, SSA, SSO, SSpiderA, \ + SSpiderO, WOA from mealpy.system_based import AEO, GCO, WCA -from mealpy.swarm_based import ABC, ACOR, ALO, AO, BA, BeesA, BES, BFO, BSA, COA, CSA, CSO, DO, EHO, FA, FFA, FOA, GOA, GWO, HGS -from mealpy.swarm_based import HHO, JA, MFO, MRFO, MSA, NMRA, PFA, PSO, SFO, SHO, SLO, SRSR, SSA, SSO, SSpiderA, SSpiderO, WOA - f18 = F292017(ndim=30, f_bias=0) P1 = { @@ -726,7 +728,6 @@ "feedback_max": 10 } - model = BBO.DevBBO(**paras_bbo) model = BBO.OriginalBBO(**paras_bbo) model = EOA.OriginalEOA(**paras_eoa) @@ -887,4 +888,4 @@ print(model.get_parameters()) print(model.get_name()) print(model.problem.get_name()) -print(g_best) \ No newline at end of file +print(g_best) diff --git a/examples/run_multi_functions.py b/examples/run_multi_functions.py index 8496bd04..936cea74 100644 --- a/examples/run_multi_functions.py +++ b/examples/run_multi_functions.py @@ -5,10 +5,11 @@ # --------------------------------------------------% from pathlib import Path + from opfunu.cec_basic import cec2014_nobias from pandas import DataFrame -from mealpy.evolutionary_based.DE import OriginalDE +from mealpy.evolutionary_based.DE import OriginalDE PATH_RESULTS = "history/results/" Path(PATH_RESULTS).mkdir(parents=True, exist_ok=True) @@ -22,8 +23,8 @@ wf = 0.8 cr = 0.9 -func_names = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19"] - +func_names = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", + "F17", "F18", "F19"] ## Run model best_fit_full = {} diff --git a/examples/run_multi_functions_multi_trials.py b/examples/run_multi_functions_multi_trials.py index 07ec5069..36f2ee75 100644 --- a/examples/run_multi_functions_multi_trials.py +++ b/examples/run_multi_functions_multi_trials.py @@ -5,10 +5,11 @@ # --------------------------------------------------% from pathlib import Path + from opfunu.cec_basic import cec2014_nobias from pandas import DataFrame -from mealpy.evolutionary_based.DE import OriginalDE +from mealpy.evolutionary_based.DE import OriginalDE model_name = "DE" N_TRIALS = 3 @@ -19,7 +20,8 @@ pop_size = 50 wf = 0.8 cr = 0.9 -func_names = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19"] +func_names = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", + "F17", "F18", "F19"] PATH_ERROR = "history1/error/" + model_name + "/" PATH_BEST_FIT = "history1/best_fit/" @@ -32,7 +34,7 @@ for func_name in func_names: error_full = {} best_fit_list = [] - for id_trial in range(1, N_TRIALS+1): + for id_trial in range(1, N_TRIALS + 1): problem = { "fit_func": getattr(cec2014_nobias, func_name), "lb": LB, diff --git a/examples/run_multi_functions_multi_trials_parallel.py b/examples/run_multi_functions_multi_trials_parallel.py index 99222adc..7a1317c6 100644 --- a/examples/run_multi_functions_multi_trials_parallel.py +++ b/examples/run_multi_functions_multi_trials_parallel.py @@ -6,10 +6,11 @@ import concurrent.futures as parallel from pathlib import Path + from opfunu.cec_basic import cec2014_nobias from pandas import DataFrame -from mealpy.evolutionary_based.DE import OriginalDE +from mealpy.evolutionary_based.DE import OriginalDE model_name = "DE" N_TRIALS = 5 @@ -27,6 +28,7 @@ Path(PATH_ERROR).mkdir(parents=True, exist_ok=True) Path(PATH_BEST_FIT).mkdir(parents=True, exist_ok=True) + def find_minimum(function_name): """ We can run multiple functions at the same time. diff --git a/examples/run_multi_functions_parallel.py b/examples/run_multi_functions_parallel.py index 74868125..8e5b5d7c 100644 --- a/examples/run_multi_functions_parallel.py +++ b/examples/run_multi_functions_parallel.py @@ -7,17 +7,19 @@ import concurrent.futures as parallel from functools import partial from pathlib import Path + from opfunu.cec_basic import cec2014_nobias from pandas import DataFrame -from mealpy.evolutionary_based.DE import OriginalDE +from mealpy.evolutionary_based.DE import OriginalDE PATH_RESULTS = "history/results/" Path(PATH_RESULTS).mkdir(parents=True, exist_ok=True) model_name = "DE" n_dims = 30 -func_names = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19"] +func_names = ["F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", + "F17", "F18", "F19"] def find_minimum(function_name, n_dims): diff --git a/examples/run_multitask.ipynb b/examples/run_multitask.ipynb index bc3e0005..0c220b2a 100644 --- a/examples/run_multitask.ipynb +++ b/examples/run_multitask.ipynb @@ -6,10 +6,25 @@ "outputs": [], "source": [ "# Scenarios\n", - "1. Run 1 algorithm with 1 problem, and multiple trials \n", - "2. Run 1 algorithm with multiple problems, and multiple trials\n", - "3. Run multiple algorithms with 1 problem, and multiple trials\n", - "4. Run multiple algorithms with multiple problems, and multiple trials" + "1.\n", + "Run\n", + "1\n", + "algorithm\n", + "with 1 problem, and multiple trials\n", + "2.\n", + "Run\n", + "1\n", + "algorithm\n", + "with multiple problems, and multiple trials\n", + "3.\n", + "Run\n", + "multiple\n", + "algorithms\n", + "with 1 problem, and multiple trials\n", + "4.\n", + "Run\n", + "multiple\n", + "algorithms with multiple problems, and multiple trials" ], "metadata": { "collapsed": false, @@ -30,9 +45,10 @@ "source": [ "## Import libraries\n", "from opfunu.cec_based.cec2017 import F52017, F102017, F292017\n", - "from mealpy import FloatVar\n", + "\n", "from mealpy import BBO, DE\n", - "from mealpy import Multitask # this is the utility class we will use" + "from mealpy import FloatVar\n", + "from mealpy import Multitask # this is the utility class we will use" ] }, { @@ -123,7 +139,7 @@ ], "source": [ "if __name__ == \"__main__\":\n", - " multitask = Multitask(algorithms=(model1, ), problems=(p1, )) # Need the \",\" because it is a tuple >= 1.\n", + " multitask = Multitask(algorithms=(model1,), problems=(p1,)) # Need the \",\" because it is a tuple >= 1.\n", " multitask.execute(n_trials=3, save_path=\"history1\", save_as=\"csv\", verbose=True)" ] }, @@ -165,7 +181,8 @@ ], "source": [ "if __name__ == \"__main__\":\n", - " multitask = Multitask(algorithms=(model1, ), problems=(p1, p2, p3), n_workers=4) # Need the \",\" because it is a tuple >= 1.\n", + " multitask = Multitask(algorithms=(model1,), problems=(p1, p2, p3),\n", + " n_workers=4) # Need the \",\" because it is a tuple >= 1.\n", " multitask.execute(n_trials=3, save_path=\"history2\", save_as=\"csv\", verbose=True)" ] }, @@ -207,7 +224,8 @@ ], "source": [ "if __name__ == \"__main__\":\n", - " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p3, ), n_workers=3) # Need the \",\" because it is a tuple >= 1.\n", + " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p3,),\n", + " n_workers=3) # Need the \",\" because it is a tuple >= 1.\n", " multitask.execute(n_trials=3, save_path=\"history3\", save_as=\"csv\", verbose=True)" ] }, @@ -267,7 +285,7 @@ ], "source": [ "if __name__ == \"__main__\":\n", - " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p1, p2, p3), n_workers=4) \n", + " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p1, p2, p3), n_workers=4)\n", " multitask.execute(n_trials=3, save_path=\"history4\", save_as=\"csv\", verbose=True)" ] }, @@ -327,7 +345,7 @@ ], "source": [ "if __name__ == \"__main__\":\n", - " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p1, p2, p3), mode=(\"thread\", ), n_workers=4) \n", + " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p1, p2, p3), mode=(\"thread\",), n_workers=4)\n", " multitask.execute(n_trials=3, n_jobs=4, save_path=\"history5\", save_as=\"csv\", verbose=True)" ] }, @@ -387,7 +405,7 @@ ], "source": [ "if __name__ == \"__main__\":\n", - " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p1, p2, p3), modes=(\"thread\",), n_workers=5) \n", + " multitask = Multitask(algorithms=(model1, model2, model3), problems=(p1, p2, p3), modes=(\"thread\",), n_workers=5)\n", " multitask.execute(n_trials=3, save_path=\"history6\", save_as=\"csv\", save_convergence=True, verbose=True)" ] }, @@ -424,4 +442,4 @@ }, "nbformat": 4, "nbformat_minor": 1 -} \ No newline at end of file +} diff --git a/examples/run_multitask.py b/examples/run_multitask.py index d5d5eeaa..fe350be3 100644 --- a/examples/run_multitask.py +++ b/examples/run_multitask.py @@ -17,8 +17,9 @@ ## Import libraries from opfunu.cec_based.cec2017 import F52017, F102017, F292017 -from mealpy import FloatVar + from mealpy import BBO, DE +from mealpy import FloatVar from mealpy import Multitask ## Define your own problems @@ -63,7 +64,9 @@ ## Define and run Multitask if __name__ == "__main__": - multitask = Multitask(algorithms=(model1, model2, model3, model4), problems=(p1, p2, p3), terminations=(term, ), modes=("thread", ), n_workers=4) + multitask = Multitask(algorithms=(model1, model2, model3, model4), problems=(p1, p2, p3), terminations=(term,), + modes=("thread",), n_workers=4) # default modes = "single", default termination = epoch (as defined in problem dictionary) - multitask.execute(n_trials=5, n_jobs=None, save_path="history7", save_as="csv", save_convergence=True, verbose=False) + multitask.execute(n_trials=5, n_jobs=None, save_path="history7", save_as="csv", save_convergence=True, + verbose=False) # multitask.execute(n_trials=5, save_path="history", save_as="csv", save_convergence=True, verbose=False) diff --git a/examples/run_simple_function.py b/examples/run_simple_function.py index d9789bfa..8efe5311 100644 --- a/examples/run_simple_function.py +++ b/examples/run_simple_function.py @@ -5,6 +5,7 @@ # --------------------------------------------------% from opfunu.cec_based.cec2017 import F52017 + from mealpy import FloatVar, BBO ## Define your own problems @@ -20,7 +21,7 @@ } optimizer = BBO.OriginalBBO(epoch=100, pop_size=30) -optimizer.solve(p1, seed=10) # Set seed for each solved problem +optimizer.solve(p1, seed=10) # Set seed for each solved problem optimizer.history.save_diversity_chart() optimizer.history.save_runtime_chart() @@ -30,4 +31,3 @@ optimizer.history.save_local_best_fitness_chart() optimizer.history.save_global_objectives_chart() optimizer.history.save_local_objectives_chart() - diff --git a/examples/run_tuner.ipynb b/examples/run_tuner.ipynb index fc95a86f..85f0d0fd 100644 --- a/examples/run_tuner.ipynb +++ b/examples/run_tuner.ipynb @@ -25,6 +25,7 @@ "outputs": [], "source": [ "import numpy as np\n", + "\n", "from mealpy import FloatVar, BBO, Tuner" ] }, @@ -50,10 +51,11 @@ "outputs": [], "source": [ "def objective_function(solution):\n", - " return np.sum(solution**2) + np.sum(solution**3)\n", + " return np.sum(solution ** 2) + np.sum(solution ** 3)\n", + "\n", "\n", "problem = {\n", - " \"bounds\": FloatVar(lb=(-10,)*20, ub=(10, )*20), # 20 dimensions\n", + " \"bounds\": FloatVar(lb=(-10,) * 20, ub=(10,) * 20), # 20 dimensions\n", " \"obj_func\": objective_function,\n", " \"minmax\": \"min\",\n", " \"name\": \"Mixed Square and Cube Problem\",\n", @@ -173,7 +175,19 @@ "source": [ "## Can't run the parallel mode in Jupiter, but in Pycharm, Spider, or Command Line run just fine.\n", "\n", - "* We can use sequential mode, which will take more times to run. (Default mode is also sequential)" + "*We\n", + "can\n", + "use\n", + "sequential\n", + "mode, which\n", + "will\n", + "take\n", + "more\n", + "times\n", + "to\n", + "run.(Default\n", + "mode is also\n", + "sequential)" ], "metadata": { "collapsed": false, @@ -235,8 +249,7 @@ "## Print out the algorithm with the best parameter\n", "print(f\"Best Optimizer: {tuner.best_algorithm}\")\n", "\n", - "\n", - "## Now we can even re-train the algorithm with the best parameter by calling resolve() function \n", + "## Now we can even re-train the algorithm with the best parameter by calling resolve() function\n", "## Resolve() function will call the solve() function in algorithm with default problem parameter is removed. \n", "## other parameters of solve() function is keeped and can be used.\n", "\n", @@ -278,4 +291,4 @@ }, "nbformat": 4, "nbformat_minor": 1 -} \ No newline at end of file +} diff --git a/examples/run_tuner.py b/examples/run_tuner.py index d6d52d6a..797004fd 100644 --- a/examples/run_tuner.py +++ b/examples/run_tuner.py @@ -5,6 +5,7 @@ # --------------------------------------------------% from opfunu.cec_based.cec2017 import F52017 + from mealpy import FloatVar, BBO, Tuner ## You can define your own problem, here I took the F5 benchmark function in CEC-2017 as an example. diff --git a/examples/utils/history_best_worst.py b/examples/utils/history_best_worst.py index e0bc9962..ff9500b9 100644 --- a/examples/utils/history_best_worst.py +++ b/examples/utils/history_best_worst.py @@ -5,12 +5,12 @@ # --------------------------------------------------% import numpy as np -from mealpy import FloatVar, BBO +from mealpy import FloatVar, BBO problem = { - "obj_func": lambda sol: np.sum(sol**2), - "bounds": FloatVar(lb=(-100.,)*20, ub=(100.,)*20, name="delta"), + "obj_func": lambda sol: np.sum(sol ** 2), + "bounds": FloatVar(lb=(-100.,) * 20, ub=(100.,) * 20, name="delta"), "minmax": "min", } diff --git a/examples/utils/io_save_load_model.py b/examples/utils/io_save_load_model.py index d44e86a0..b9e40c8d 100644 --- a/examples/utils/io_save_load_model.py +++ b/examples/utils/io_save_load_model.py @@ -5,17 +5,18 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, BBO from mealpy.utils import io def objective_function(solution): - return np.sum(solution**2) + return np.sum(solution ** 2) problem = { "obj_func": objective_function, - "bounds": FloatVar(lb=(-100.,)*20, ub=(100.,)*20, name="delta"), + "bounds": FloatVar(lb=(-100.,) * 20, ub=(100.,) * 20, name="delta"), "minmax": "min", } diff --git a/examples/utils/run_BinaryVar.py b/examples/utils/run_BinaryVar.py index 8b2c22b5..aac4edc1 100644 --- a/examples/utils/run_BinaryVar.py +++ b/examples/utils/run_BinaryVar.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import BinaryVar, Problem +from mealpy import BinaryVar, Problem ## 1. Show error # bounds = [ @@ -23,7 +23,7 @@ BinaryVar(n_vars=11, name="delta"), ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -31,10 +31,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_BoolVar.py b/examples/utils/run_BoolVar.py index fa589132..d0dd031f 100644 --- a/examples/utils/run_BoolVar.py +++ b/examples/utils/run_BoolVar.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import BoolVar, Problem +from mealpy import BoolVar, Problem # ## 1. Show error # bounds = [ @@ -23,7 +23,7 @@ BoolVar(n_vars=11, name="delta"), ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -31,10 +31,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_CategoricalVar.py b/examples/utils/run_CategoricalVar.py index 97bce0f6..3ebb2e72 100644 --- a/examples/utils/run_CategoricalVar.py +++ b/examples/utils/run_CategoricalVar.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import CategoricalVar, Problem +from mealpy import CategoricalVar, Problem ## 1. One variable bounds = [ @@ -16,22 +16,21 @@ ## 2. Multiple variables bounds = [ CategoricalVar(valid_sets=((0.5, "backward", "forward"), - ("0.2", "None", "root"), - ("auto", None, "modified"), - ("random", 1, "roulette", 0.5, "round-robin")), name="delta") + ("0.2", "None", "root"), + ("auto", None, "modified"), + ("random", 1, "roulette", 0.5, "round-robin")), name="delta") ] ## 3. Multiple variables bounds = [ CategoricalVar(valid_sets=(("auto", 2, 3, "backward", "forward", True), - (1, 0, 10, "leaf", "branch", "root", False), - (0.01, "auto", 0.1, "adaptive", 0.05, "modified"), - ("random", 0, 2, 4, "tournament", "roulette", "round-robin")), name="delta"), + (1, 0, 10, "leaf", "branch", "root", False), + (0.01, "auto", 0.1, "adaptive", 0.05, "modified"), + ("random", 0, 2, 4, "tournament", "roulette", "round-robin")), name="delta"), CategoricalVar(valid_sets=(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000), name="epoch") ] - -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -39,10 +38,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_FloatVar.py b/examples/utils/run_FloatVar.py index 4ab37c8f..7b2b7aef 100644 --- a/examples/utils/run_FloatVar.py +++ b/examples/utils/run_FloatVar.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, Problem # ## 1. One variable @@ -14,10 +15,10 @@ ## 2. Multiple variables bounds = [ - FloatVar(lb=(-10., )*7, ub=(10., )*7, name="delta") + FloatVar(lb=(-10.,) * 7, ub=(10.,) * 7, name="delta") ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -25,10 +26,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_IntegerVar.py b/examples/utils/run_IntegerVar.py index 15b1a855..aae75bea 100644 --- a/examples/utils/run_IntegerVar.py +++ b/examples/utils/run_IntegerVar.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import IntegerVar, Problem +from mealpy import IntegerVar, Problem # ## 1. One variable # bounds = [ @@ -15,10 +15,10 @@ ## 2. Multiple variables bounds = [ - IntegerVar(lb=(-1, )*20, ub=(1, )*20, name="delta") + IntegerVar(lb=(-1,) * 20, ub=(1,) * 20, name="delta") ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") print(problem.lb, problem.ub) @@ -27,10 +27,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_Mix_Type.py b/examples/utils/run_Mix_Type.py index 8dedf141..c648a3e2 100644 --- a/examples/utils/run_Mix_Type.py +++ b/examples/utils/run_Mix_Type.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import IntegerVar, FloatVar, StringVar, PermutationVar, BinaryVar, BoolVar, Problem +from mealpy import IntegerVar, FloatVar, StringVar, PermutationVar, BinaryVar, BoolVar, Problem # 1. IntegerVar and StringVar bounds = [ @@ -54,7 +54,7 @@ BoolVar(n_vars=2, name="gama") ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -62,10 +62,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_PermutationVar.py b/examples/utils/run_PermutationVar.py index 7dd13235..948d8172 100644 --- a/examples/utils/run_PermutationVar.py +++ b/examples/utils/run_PermutationVar.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import PermutationVar, Problem +from mealpy import PermutationVar, Problem # bounds = [ # PermutationVar(valid_set=(-10, 10), name="delta"), @@ -20,7 +20,7 @@ PermutationVar(valid_set=(-10, -4, 10, 6, -2), name="delta"), ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -28,10 +28,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_SequenceVar.py b/examples/utils/run_SequenceVar.py index 221e8117..88c112b8 100644 --- a/examples/utils/run_SequenceVar.py +++ b/examples/utils/run_SequenceVar.py @@ -5,16 +5,16 @@ # --------------------------------------------------% import numpy as np -from mealpy import SequenceVar, Problem +from mealpy import SequenceVar, Problem ## 1. One variable bounds = [ - SequenceVar(valid_sets=((1, ), {2, 3}, [3, 5, 1]), return_type=list), + SequenceVar(valid_sets=((1,), {2, 3}, [3, 5, 1]), return_type=list), ] bounds = [ - SequenceVar(valid_sets=[(1, ), (2, 3), (3, 5, 1)], return_type=list), + SequenceVar(valid_sets=[(1,), (2, 3), (3, 5, 1)], return_type=list), ] bounds = [ @@ -25,7 +25,7 @@ SequenceVar(valid_sets=[{0, }, {8, 34}, {36, 50, 1}], return_type=set), ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -33,10 +33,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_StringVar.py b/examples/utils/run_StringVar.py index 2c954bbd..3e6332db 100644 --- a/examples/utils/run_StringVar.py +++ b/examples/utils/run_StringVar.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np -from mealpy import StringVar, Problem +from mealpy import StringVar, Problem ## 1. One variable bounds = [ @@ -29,7 +29,7 @@ ("random", "damn", "roulette", "huhu")), name="delta") ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -37,10 +37,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") diff --git a/examples/utils/run_Target.py b/examples/utils/run_Target.py index 42c3e0d8..ed0044af 100644 --- a/examples/utils/run_Target.py +++ b/examples/utils/run_Target.py @@ -12,6 +12,7 @@ def objective_function(solution): # This function returns a list of two objectives for the given solution return [solution[0] ** 2, solution[1] ** 2] + # Define the solution and weights solution = [2, 3] weights = [0.5, 0.5] diff --git a/examples/utils/run_TransferBinaryVar.py b/examples/utils/run_TransferBinaryVar.py index f0082bae..37017197 100644 --- a/examples/utils/run_TransferBinaryVar.py +++ b/examples/utils/run_TransferBinaryVar.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import TransferBinaryVar, Problem print(f"Supported transfer functions: {TransferBinaryVar.SUPPORTED_TF_FUNCS}") @@ -24,8 +25,7 @@ TransferBinaryVar(n_vars=11, name="delta", tf_func="sstf_02"), ] - -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -33,10 +33,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") @@ -46,6 +46,6 @@ bounds = [ TransferBinaryVar(n_vars=2, name="delta", tf_func="sstf_02", all_zeros=False), ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(problem.generate_solution(encoded=False)) ## It will never generate a solution with all variables = 0. diff --git a/examples/utils/run_TransferBoolVar.py b/examples/utils/run_TransferBoolVar.py index e11de0c2..93a75afb 100644 --- a/examples/utils/run_TransferBoolVar.py +++ b/examples/utils/run_TransferBoolVar.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import TransferBoolVar, Problem print(f"Supported transfer functions: {TransferBoolVar.SUPPORTED_TF_FUNCS}") @@ -24,8 +25,7 @@ TransferBoolVar(n_vars=11, name="delta", tf_func="sstf_02"), ] - -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(f"Problem: {problem}") print(f"Bounds: {problem.bounds}") @@ -33,10 +33,10 @@ x = problem.generate_solution() print(x) -x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem -x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem -x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem -x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem +x = problem.generate_solution(encoded=False) # Real world (actual solution - decoded solution) for the problem +x1 = problem.encode_solution(x) # Optimizer solution (encoded solution) for the problem +x2 = problem.correct_solution(x1) # Correct the solution (encoded and bounded solution) for the problem +x3 = problem.decode_solution(x1) # Real world (actual solution - decoded solution) for the problem print(f"Real value solution: {x}") print(f"Encoded solution: {x1}") print(f"Bounded solution: {x2}") @@ -46,6 +46,6 @@ bounds = [ TransferBoolVar(n_vars=2, name="delta", tf_func="sstf_02"), ] -problem = Problem(bounds, obj_func=lambda sol: np.sum(sol**2)) +problem = Problem(bounds, obj_func=lambda sol: np.sum(sol ** 2)) print(problem.generate_solution(encoded=False)) ## It will never generate a solution with all variables = 0. diff --git a/examples/utils/run_g_best.py b/examples/utils/run_g_best.py index 4bad67f0..01b16938 100644 --- a/examples/utils/run_g_best.py +++ b/examples/utils/run_g_best.py @@ -5,6 +5,7 @@ # --------------------------------------------------% from opfunu.cec_based.cec2017 import F52017 + from mealpy import FloatVar, BBO @@ -16,6 +17,7 @@ def get_first_best_population(opt): return idx, pop_child return None, None + ## Define your own problems f1 = F52017(30, f_bias=0) @@ -29,7 +31,7 @@ def get_first_best_population(opt): } optimizer = BBO.OriginalBBO(epoch=100, pop_size=30) -optimizer.solve(p1, seed=10) # Set seed for each solved problem +optimizer.solve(p1, seed=10) # Set seed for each solved problem idx, my_first_found_best_pop = get_first_best_population(optimizer) print(f"The global best solution found at generation: {idx}") diff --git a/examples/utils/run_problem.ipynb b/examples/utils/run_problem.ipynb index e0033747..e7ebd863 100644 --- a/examples/utils/run_problem.ipynb +++ b/examples/utils/run_problem.ipynb @@ -43,6 +43,7 @@ "source": [ "import numpy as np\n", "from opfunu.cec_based.cec2017 import F292017\n", + "\n", "from mealpy.bio_based import BBO\n", "from mealpy.utils.problem import Problem\n", "\n", @@ -50,11 +51,12 @@ "#### Solve problem with dictionary definition (custom fitness function)\n", "\n", "def fitness(solution):\n", - " return np.sum(solution**2)\n", + " return np.sum(solution ** 2)\n", + "\n", "\n", "p0 = {\n", - " \"lb\": [-100, ]*10,\n", - " \"ub\": [100,]*10,\n", + " \"lb\": [-100, ] * 10,\n", + " \"ub\": [100, ] * 10,\n", " \"minmax\": \"min\",\n", " \"fit_func\": fitness,\n", " \"name\": \"Custom Squared Func\"\n", @@ -117,9 +119,11 @@ "\n", "f18 = F292017(30, f_bias=0)\n", "\n", + "\n", "def fitness(solution):\n", " return f18.evaluate(solution)\n", "\n", + "\n", "p1 = {\n", " \"lb\": f18.lb.tolist(),\n", " \"ub\": f18.ub.tolist(),\n", @@ -185,7 +189,7 @@ " self.name = name\n", "\n", " def fit_func(self, solution):\n", - " return [np.sum(solution ** 2), np.sum(solution[:5]**3)]\n", + " return [np.sum(solution ** 2), np.sum(solution[:5] ** 3)]\n", "\n", "\n", "p2 = Squared(lb=[-10, ] * 20, ub=[10, ] * 20, minmax=\"min\", obj_weights=[0.5, 0.5])\n", @@ -371,7 +375,6 @@ "\n", "model = BBO.BaseBBO(epoch=10, pop_size=50)\n", "\n", - "\n", "for term in [term1, term2]:\n", " best_position, best_fitness = model.solve(p6, termination=term)\n", " print(model.get_parameters())\n", @@ -413,4 +416,4 @@ }, "nbformat": 4, "nbformat_minor": 1 -} \ No newline at end of file +} diff --git a/examples/utils/run_termination.py b/examples/utils/run_termination.py index 10d9b569..4755518e 100644 --- a/examples/utils/run_termination.py +++ b/examples/utils/run_termination.py @@ -5,9 +5,10 @@ # --------------------------------------------------% import numpy as np -from mealpy import FloatVar, BBO, Termination from opfunu.cec_based.cec2017 import F292017 +from mealpy import FloatVar, BBO, Termination + ## 1) Single termination f18 = F292017(ndim=30) @@ -24,17 +25,14 @@ g_best = model.solve(problem_dict1, termination={"max_epoch": 100}) print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") - ## 2. Number of Function Evaluation g_best = model.solve(problem_dict1, termination={"max_fe": 10000}) print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") - ## 3. Time bound g_best = model.solve(problem_dict1, termination={"max_time": 5.5}) print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") - ## 4. Early Stopping g_best = model.solve(problem_dict1, termination={"max_early_stop": 5}) print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") @@ -43,14 +41,14 @@ ## 2) Combine all of them # Define an example objective function (e.g., sphere function) def fitness(solution): - return np.sum(solution**2) + return np.sum(solution ** 2) term_dict = { "max_epoch": 100, "max_fe": 2000, # 2000 number of function evaluation - "max_time": 1.5, # 1.5 seconds to run the program - "max_early_stop": 15 # 15 epochs if the best fitness is not getting better we stop the program + "max_time": 1.5, # 1.5 seconds to run the program + "max_early_stop": 15 # 15 epochs if the best fitness is not getting better we stop the program } # Define the problem dimension and search space (e.g., for a 30-D problem with [-10, 10] bounds for each variable) diff --git a/examples/utils/run_time.py b/examples/utils/run_time.py index 4f317d8b..f5c165ae 100644 --- a/examples/utils/run_time.py +++ b/examples/utils/run_time.py @@ -5,18 +5,20 @@ # --------------------------------------------------% import time + import numpy as np + from mealpy import FloatVar, BBO, GA, PSO def fitness(solution): """Example objective function (e.g., sphere function)""" - return np.sum(solution**2) + return np.sum(solution ** 2) problem_dict1 = { "obj_func": fitness, - "bounds": FloatVar(lb=(-100.,)*30, ub=(100.,)*30), + "bounds": FloatVar(lb=(-100.,) * 30, ub=(100.,) * 30), "minmax": "min", } diff --git a/examples/utils/visualize/all_charts.py b/examples/utils/visualize/all_charts.py index a749b8f5..60ff93bb 100644 --- a/examples/utils/visualize/all_charts.py +++ b/examples/utils/visualize/all_charts.py @@ -4,9 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% +import numpy as np + from mealpy.bio_based import SMA from mealpy.utils.visualize import * -import numpy as np + ## Multi-objective but single fitness function. By using weighting method to convert from multiple to single. @@ -16,7 +18,7 @@ def fitness_function(solution): t2 = ((2 * solution[1]) / 5) ** 2 t3 = 0 for i in range(3, len(solution)): - t3 += (1 + solution[i]**2)**0.5 + t3 += (1 + solution[i] ** 2) ** 0.5 return [t1, t2, t3] @@ -33,26 +35,32 @@ def fitness_function(solution): best_position, best_fitness = model.solve(problem) print(f"Best solution: {best_position}, Best fitness: {best_fitness}") -export_convergence_chart(model.history.list_global_best_fit, title='Global Best Fitness') # Draw global best fitness found so far in previous generations -export_convergence_chart(model.history.list_current_best_fit, title='Local Best Fitness') # Draw current best fitness in each previous generation -export_convergence_chart(model.history.list_epoch_time, title='Runtime chart', y_label="Second") # Draw runtime for each generation +export_convergence_chart(model.history.list_global_best_fit, + title='Global Best Fitness') # Draw global best fitness found so far in previous generations +export_convergence_chart(model.history.list_current_best_fit, + title='Local Best Fitness') # Draw current best fitness in each previous generation +export_convergence_chart(model.history.list_epoch_time, title='Runtime chart', + y_label="Second") # Draw runtime for each generation ## On the exploration and exploitation in popular swarm-based metaheuristic algorithms # This exploration/exploitation chart should draws for single algorithm and single fitness function -export_explore_exploit_chart([model.history.list_exploration, model.history.list_exploitation]) # Draw exploration and exploitation chart +export_explore_exploit_chart( + [model.history.list_exploration, model.history.list_exploitation]) # Draw exploration and exploitation chart # This diversity chart should draws for multiple algorithms for a single fitness function at the same time to compare the diversity spreading -export_diversity_chart([model.history.list_diversity], list_legends=['GA']) # Draw diversity measurement chart +export_diversity_chart([model.history.list_diversity], list_legends=['GA']) # Draw diversity measurement chart ## Because convergence chart is formulated from objective values and weights, thus we also want to draw objective charts to understand the convergence # Need a little bit more pre-processing -global_obj_list = np.array([agent[1][1] for agent in model.history.list_global_best]) # 2D array / matrix 2D -global_obj_list = [global_obj_list[:,idx] for idx in range(0, len(global_obj_list[0]))] # Make each obj_list as a element in array for drawing +global_obj_list = np.array([agent[1][1] for agent in model.history.list_global_best]) # 2D array / matrix 2D +global_obj_list = [global_obj_list[:, idx] for idx in + range(0, len(global_obj_list[0]))] # Make each obj_list as a element in array for drawing export_objectives_chart(global_obj_list, title='Global Objectives Chart') current_obj_list = np.array([agent[1][1] for agent in model.history.list_current_best]) # 2D array / matrix 2D -current_obj_list = [current_obj_list[:, idx] for idx in range(0, len(current_obj_list[0]))] # Make each obj_list as a element in array for drawing +current_obj_list = [current_obj_list[:, idx] for idx in + range(0, len(current_obj_list[0]))] # Make each obj_list as a element in array for drawing export_objectives_chart(current_obj_list, title='Local Objectives Chart') ## Drawing trajectory of some agents in the first and second dimensions @@ -60,17 +68,16 @@ def fitness_function(solution): pos_list = [] list_legends = [] dimension = 2 -y_label = f"x{dimension+1}" -for i in range(0, 5, 2): # Get the third dimension of position of the first 3 solutions +y_label = f"x{dimension + 1}" +for i in range(0, 5, 2): # Get the third dimension of position of the first 3 solutions x = [pop[0][0][dimension] for pop in model.history.list_population] pos_list.append(x) - list_legends.append(f"Agent {i+1}.") + list_legends.append(f"Agent {i + 1}.") # pop[0]: Get the first solution # pop[0][0]: Get the position of the first solution # pop[0][0][0]: Get the first dimension of the position of the first solution export_trajectory_chart(pos_list, list_legends=list_legends, y_label=y_label) - ### Or better to use the API ## You can access all of available figures via object "history" like this: model.history.save_global_objectives_chart(filename="results/goc") @@ -81,4 +88,3 @@ def fitness_function(solution): model.history.save_exploration_exploitation_chart(filename="results/eec") model.history.save_diversity_chart(filename="results/dc") model.history.save_trajectory_chart(list_agent_idx=[3, 5], selected_dimensions=[2], filename="results/tc") - diff --git a/examples/utils/visualize/convergence_chart.py b/examples/utils/visualize/convergence_chart.py index 897e0da8..72d03781 100644 --- a/examples/utils/visualize/convergence_chart.py +++ b/examples/utils/visualize/convergence_chart.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, BBO from mealpy.utils.visualize import * @@ -13,9 +14,9 @@ # Multi-objective but single fitness/target value. By using weighting method to convert from multiple objectives to single target def fitness_function(solution): - f1 = (np.sum(solution**2) - np.mean(solution)) / len(solution) + f1 = (np.sum(solution ** 2) - np.mean(solution)) / len(solution) f2 = np.sum(np.sqrt(np.abs(solution))) - f3 = np.sum(np.mean(solution**2) - solution) + f3 = np.sum(np.mean(solution ** 2) - solution) return [f1, f2, f3] @@ -31,9 +32,9 @@ def fitness_function(solution): g_best = model.solve(problem) print(f"Best solution: {g_best.solution}, Best fitness: {g_best.fitness}") - ## Draw convergence chart for globest solution found so far in each previous generation -export_convergence_chart(model.history.list_global_best_fit, title='Global Best Fitness', filename="Global-best-convergence-chart") +export_convergence_chart(model.history.list_global_best_fit, title='Global Best Fitness', + filename="Global-best-convergence-chart") # Parameter for this function # data: optimizer.history_list_g_best_fit -> List of global best fitness found so far in each previous generation @@ -47,7 +48,9 @@ def fitness_function(solution): # verbose: show the figure on Python IDE, default = True ## Draw convergence chart for current best solution in each generation -export_convergence_chart(model.history.list_current_best_fit, title='Local Best Fitness', filename='Current-best-convergence-chart') +export_convergence_chart(model.history.list_current_best_fit, title='Local Best Fitness', + filename='Current-best-convergence-chart') ## Draw runtime for each generation -export_convergence_chart(model.history.list_epoch_time, title='Runtime chart', y_label="Second", filename='Runtime-per-epoch-chart') +export_convergence_chart(model.history.list_epoch_time, title='Runtime chart', y_label="Second", + filename='Runtime-per-epoch-chart') diff --git a/examples/utils/visualize/exploration_exploitation_chart.py b/examples/utils/visualize/exploration_exploitation_chart.py index 67de4923..ad8ebfbc 100644 --- a/examples/utils/visualize/exploration_exploitation_chart.py +++ b/examples/utils/visualize/exploration_exploitation_chart.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, BBO from mealpy.utils.visualize import * @@ -34,7 +35,8 @@ def fitness_function(solution): ## On the exploration and exploitation in popular swarm-based metaheuristic algorithms (the idea come from this paper) # This exploration/exploitation chart should draws for single algorithm and single fitness function -export_explore_exploit_chart([model.history.list_exploration, model.history.list_exploitation]) # Draw exploration and exploitation chart +export_explore_exploit_chart( + [model.history.list_exploration, model.history.list_exploitation]) # Draw exploration and exploitation chart # Parameter for this function # data: is the list of array @@ -54,7 +56,6 @@ def fitness_function(solution): # This diversity chart should draw for multiple algorithms for a single fitness function at the same time to compare the diversity spreading export_diversity_chart([model.history.list_diversity], list_legends=['BBO']) # Draw diversity measurement chart - # Parameter for this function # data: is the list of array # + optimizer1.history_list_div -> List of diversity spreading for this optimizer1 diff --git a/examples/utils/visualize/objectives_chart.py b/examples/utils/visualize/objectives_chart.py index 49814f38..fb2b6d32 100644 --- a/examples/utils/visualize/objectives_chart.py +++ b/examples/utils/visualize/objectives_chart.py @@ -5,9 +5,11 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, BBO from mealpy.utils.visualize import * + ## Define your own fitness function # Multi-objective but single fitness/target value. By using weighting method to convert from multiple objectives to single target @@ -30,15 +32,16 @@ def fitness_function(solution): g_best = model.solve(problem) print(f"Best solution: {g_best.solution}, Best fitness: {g_best.fitness}") - ## Because convergence chart is formulated from objective values and weights, thus we also want to draw objective charts to understand the convergence # Need a little bit more pre-processing global_obj_list = np.array([agent[-1][-1] for agent in model.history.list_global_best]) # 2D array / matrix 2D -global_obj_list = [global_obj_list[:, idx] for idx in range(0, len(global_obj_list[0]))] # Make each obj_list as a element in array for drawing +global_obj_list = [global_obj_list[:, idx] for idx in + range(0, len(global_obj_list[0]))] # Make each obj_list as a element in array for drawing export_objectives_chart(global_obj_list, title='Global Objectives Chart', filename="global-objective-chart") current_obj_list = np.array([agent[-1][-1] for agent in model.history.list_current_best]) # 2D array / matrix 2D -current_obj_list = [current_obj_list[:, idx] for idx in range(0, len(current_obj_list[0]))] # Make each obj_list as a element in array for drawing +current_obj_list = [current_obj_list[:, idx] for idx in + range(0, len(current_obj_list[0]))] # Make each obj_list as a element in array for drawing export_objectives_chart(current_obj_list, title='Local Objectives Chart', filename="local-objective-chart") # Parameter for this function diff --git a/examples/utils/visualize/trajectory_chart.py b/examples/utils/visualize/trajectory_chart.py index fd374764..38787f60 100644 --- a/examples/utils/visualize/trajectory_chart.py +++ b/examples/utils/visualize/trajectory_chart.py @@ -5,9 +5,11 @@ # --------------------------------------------------% import numpy as np + from mealpy import FloatVar, BBO from mealpy.utils.visualize import * + ## Define your own fitness function # Multi-objective but single fitness/target value. By using weighting method to convert from multiple objectives to single target diff --git a/mealpy/__init__.py b/mealpy/__init__.py index e9248276..770d87ef 100644 --- a/mealpy/__init__.py +++ b/mealpy/__init__.py @@ -27,32 +27,33 @@ # >>> g_best = model.solve(problem) # >>> print(f"Best solution: {g_best.solution}, Best fitness: {g_best.target.fitness}") -__version__ = "3.0.3" +__version__ = "3.0.4.1" -import sys import inspect +import sys + from .bio_based import (BBO, BBOA, BMO, EOA, IWO, SBO, SMA, SOA, SOS, TPO, TSA, VCS, WHO, BCO, EAO, SFOA) from .evolutionary_based import (BWO, CRO, DE, EP, ES, FPA, GA, MA, SHADE) +from .game_based import THRO from .human_based import (BRO, BSO, CA, CHIO, FBIO, GSKA, HBO, HCO, ICA, LCO, QSA, SARO, SPBO, SSDO, TLO, TOA, WarSO, AFT, CDDO, DOA) from .math_based import (AOA, CEM, CGO, CircleSA, GBO, HC, INFO, PSS, RUN, SCA, SHIO, TS) +from .multitask import Multitask +from .music_based import HS +from .optimizer import Optimizer from .physics_based import (ArchOA, ASO, CDO, EFO, EO, EVO, FLA, HGSO, MVO, NRO, RIME, SA, TWO, WDO, ESO, SOO, MSO) +from .sota_based import LSHADEcnEpSin, IMODE from .swarm_based import (ABC, ACOR, AGTO, ALO, AO, ARO, AVOA, BA, BeesA, BES, BFO, BSA, COA, CoatiOA, CSA, CSO, DMOA, DO, EHO, ESOA, FA, FFA, FFO, FOA, FOX, GJO, GOA, GTO, GWO, HBA, HGS, HHO, JA, MFO, MGO, MPA, MRFO, MSA, MShOA, NGO, NMRA, OOA, PFA, POA, PSO, SCSO, SeaHO, ServalOA, SFO, SHO, SLO, SRSR, SSA, SSO, SSpiderA, SSpiderO, STO, TDO, TSO, WaOA, WOA, ZOA, EPC, SMO, SquirrelSA, FDO) from .system_based import AEO, GCO, WCA -from .music_based import HS -from .game_based import THRO -from .sota_based import LSHADEcnEpSin, IMODE -from .utils.problem import Problem -from .utils.termination import Termination from .tuner import Tuner, ParameterGrid -from .multitask import Multitask -from .optimizer import Optimizer +from .utils.problem import Problem from .utils.space import (IntegerVar, FloatVar, StringVar, BinaryVar, BoolVar, CategoricalVar, SequenceVar, PermutationVar, TransferBinaryVar, TransferBoolVar) +from .utils.termination import Termination __EXCLUDE_MODULES = ["__builtins__", "current_module", "inspect", "sys"] diff --git a/mealpy/bio_based/BBO.py b/mealpy/bio_based/BBO.py index f7aa1b64..d3fcc17e 100644 --- a/mealpy/bio_based/BBO.py +++ b/mealpy/bio_based/BBO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,7 +44,8 @@ class OriginalBBO(Optimizer): [1] Simon, D., 2008. Biogeography-based optimization. IEEE transactions on evolutionary computation, 12(6), pp.702-713. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, p_m: float = 0.01, n_elites: int = 2, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, p_m: float = 0.01, n_elites: int = 2, + **kwargs: object) -> None: """ Initialize the algorithm components. @@ -130,7 +132,8 @@ class DevBBO(OriginalBBO): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, p_m: float = 0.01, n_elites: int = 2, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, p_m: float = 0.01, n_elites: int = 2, + **kwargs: object) -> None: """ Initialize the algorithm components. diff --git a/mealpy/bio_based/BBOA.py b/mealpy/bio_based/BBOA.py index b0463257..d068a84d 100644 --- a/mealpy/bio_based/BBOA.py +++ b/mealpy/bio_based/BBOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -65,14 +66,17 @@ def evolve(self, epoch): ## Pedal marking behaviour pop_new = [] for idx in range(0, self.pop_size): - if pp <= 1/3: # Gait while walking - pos_new = self.pop[idx].solution + (-pp * self.generator.random(self.problem.n_dims) * self.pop[idx].solution) - elif 1/3 < pp <= 2/3: # Careful Stepping + if pp <= 1 / 3: # Gait while walking + pos_new = self.pop[idx].solution + ( + -pp * self.generator.random(self.problem.n_dims) * self.pop[idx].solution) + elif 1 / 3 < pp <= 2 / 3: # Careful Stepping qq = pp * self.generator.random(self.problem.n_dims) - pos_new = self.pop[idx].solution + (qq * (self.g_best.solution - self.generator.integers(1, 3) * self.g_worst.solution)) + pos_new = self.pop[idx].solution + ( + qq * (self.g_best.solution - self.generator.integers(1, 3) * self.g_worst.solution)) else: ww = 2 * pp * np.pi * self.generator.random(self.problem.n_dims) - pos_new = self.pop[idx].solution + (ww*self.g_best.solution - np.abs(self.pop[idx].solution)) - (ww*self.g_worst.solution - np.abs(self.pop[idx].solution)) + pos_new = self.pop[idx].solution + (ww * self.g_best.solution - np.abs(self.pop[idx].solution)) - ( + ww * self.g_worst.solution - np.abs(self.pop[idx].solution)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -88,9 +92,11 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): kk = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) if self.compare_target(self.pop[idx].target, self.pop[kk].target, self.problem.minmax): - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[idx].solution - self.pop[kk].solution) else: - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[kk].solution - self.pop[idx].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[kk].solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/bio_based/BCO.py b/mealpy/bio_based/BCO.py index 11f6b629..70cdd276 100644 --- a/mealpy/bio_based/BCO.py +++ b/mealpy/bio_based/BCO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -68,7 +69,9 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, c_min: float = 0.01, self.max_swim_steps = self.validator.check_int("max_swim_steps", max_swim_steps, (2, 10)) self.energy_threshold = self.validator.check_float("energy_threshold", energy_threshold, (0, 1.0)) self.migration_prob = self.validator.check_float("migration_prob", migration_prob, (0, 1.0)) - self.set_parameters(["epoch", "pop_size", "c_min", "c_max", "n_chemotaxis", "max_swim_steps", "energy_threshold", "migration_prob"]) + self.set_parameters( + ["epoch", "pop_size", "c_min", "c_max", "n_chemotaxis", "max_swim_steps", "energy_threshold", + "migration_prob"]) self.sort_flag = False def initialize_variables(self): diff --git a/mealpy/bio_based/BMO.py b/mealpy/bio_based/BMO.py index 8c583959..63869c6d 100644 --- a/mealpy/bio_based/BMO.py +++ b/mealpy/bio_based/BMO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -47,7 +48,7 @@ def __init__(self, epoch=10000, pop_size=100, pl=5, **kwargs): super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.pl = self.validator.check_int("pl", pl, [1, self.pop_size-1]) + self.pl = self.validator.check_int("pl", pl, [1, self.pop_size - 1]) self.set_parameters(["epoch", "pop_size", "pl"]) self.sort_flag = True diff --git a/mealpy/bio_based/EAO.py b/mealpy/bio_based/EAO.py index ea6225a0..5c96d7b8 100644 --- a/mealpy/bio_based/EAO.py +++ b/mealpy/bio_based/EAO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -68,7 +69,7 @@ def evolve(self, epoch: int) -> None: epoch: The current iteration """ # Adaptation Factor - tăng dần theo thời gian - AF = np.sqrt(epoch/ self.epoch) + AF = np.sqrt(epoch / self.epoch) # Handle each enzyme for idx in range(self.pop_size): @@ -84,14 +85,16 @@ def evolve(self, epoch: int) -> None: ## Candidate A: vector-valued random factors scA1 = self.ec + (1 - self.ec) * self.generator.random(size=self.problem.n_dims) exA = AF * (self.ec + (1 - self.ec) * self.generator.random(size=self.problem.n_dims)) - posA = self.pop[idx].solution + scA1 * (self.pop[j1].solution - self.pop[j2].solution) + exA * (self.g_best.solution - self.pop[idx].solution) + posA = self.pop[idx].solution + scA1 * (self.pop[j1].solution - self.pop[j2].solution) + exA * ( + self.g_best.solution - self.pop[idx].solution) posA = self.correct_solution(posA) agentA = self.generate_agent(posA) ## Candidate B: scalar random factors scB1 = self.ec + (1 - self.ec) * self.generator.random() exB = AF * (self.ec + (1 - self.ec) * self.generator.random()) - posB = self.pop[idx].solution + scB1 * (self.pop[j1].solution - self.pop[j2].solution) + exB * (self.g_best.solution - self.pop[idx].solution) + posB = self.pop[idx].solution + scB1 * (self.pop[j1].solution - self.pop[j2].solution) + exB * ( + self.g_best.solution - self.pop[idx].solution) posB = self.correct_solution(posB) agentB = self.generate_agent(posB) diff --git a/mealpy/bio_based/EOA.py b/mealpy/bio_based/EOA.py index 6bdf7d97..889df0ee 100644 --- a/mealpy/bio_based/EOA.py +++ b/mealpy/bio_based/EOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -137,7 +138,8 @@ def evolve(self, epoch): self.pop[idx] = self.get_better_agent(agent, self.pop[idx], self.problem.minmax) if self.mode in self.AVAILABLE_MODES: pop_new = self.update_target_for_population(pop_new) - self.pop[self.n_best:] = self.greedy_selection_population(pop_new, self.pop[self.n_best:], self.problem.minmax) + self.pop[self.n_best:] = self.greedy_selection_population(pop_new, self.pop[self.n_best:], + self.problem.minmax) ## Elitism Strategy: Replace the worst with the previous generation's elites. self.pop, _, _ = self.get_special_agents(self.pop, minmax=self.problem.minmax) diff --git a/mealpy/bio_based/IWO.py b/mealpy/bio_based/IWO.py index 8cfc29dd..9173dde2 100644 --- a/mealpy/bio_based/IWO.py +++ b/mealpy/bio_based/IWO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -67,7 +68,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, seed_min: int = 2, s self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) self.seed_min = self.validator.check_int("seed_min", seed_min, [1, 3]) - self.seed_max = self.validator.check_int("seed_max", seed_max, [4, int(self.pop_size/2)]) + self.seed_max = self.validator.check_int("seed_max", seed_max, [4, int(self.pop_size / 2)]) self.exponent = self.validator.check_int("exponent", exponent, [2, 4]) self.sigma_start = self.validator.check_float("sigma_start", sigma_start, [0.5, 5.0]) self.sigma_end = self.validator.check_float("sigma_end", sigma_end, (0, 0.5)) @@ -82,7 +83,7 @@ def evolve(self, epoch=None): epoch (int): The current iteration """ # Update Standard Deviation - sigma = (1. - epoch/self.epoch) ** self.exponent * (self.sigma_start - self.sigma_end) + self.sigma_end + sigma = (1. - epoch / self.epoch) ** self.exponent * (self.sigma_start - self.sigma_end) + self.sigma_end pop, list_best, list_worst = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) best, worst = list_best[0], list_worst[0] pop_new = [] diff --git a/mealpy/bio_based/SBO.py b/mealpy/bio_based/SBO.py index 36cad067..90e97da0 100644 --- a/mealpy/bio_based/SBO.py +++ b/mealpy/bio_based/SBO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -44,7 +45,8 @@ class DevSBO(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.94, p_m: float = 0.05, psw: float = 0.02, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.94, p_m: float = 0.05, + psw: float = 0.02, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -80,7 +82,8 @@ def evolve(self, epoch): rdx = self.get_index_roulette_wheel_selection(fit_list) ### Calculating Step Size lamda = self.alpha * self.generator.uniform() - pos_new = self.pop[idx].solution + lamda * ((self.pop[rdx].solution + self.g_best.solution) / 2 - self.pop[idx].solution) + pos_new = self.pop[idx].solution + lamda * ( + (self.pop[rdx].solution + self.g_best.solution) / 2 - self.pop[idx].solution) ### Mutation temp = self.pop[idx].solution + self.generator.normal(0, 1, self.problem.n_dims) * self.sigma pos_new = np.where(self.generator.random(self.problem.n_dims) < self.p_m, temp, pos_new) @@ -134,7 +137,8 @@ class OriginalSBO(DevSBO): to optimize ANFIS for software development effort estimation. Engineering Applications of Artificial Intelligence, 60, pp.1-15. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.94, p_m: float = 0.05, psw: float = 0.02, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.94, p_m: float = 0.05, + psw: float = 0.02, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -189,7 +193,8 @@ def evolve(self, epoch): ### Calculating Step Size lamda = self.alpha / (1 + prob_list[rdx]) pos_new[jdx] = self.pop[idx].solution[jdx] + lamda * \ - ((self.pop[rdx].solution[jdx] + self.g_best.solution[jdx]) / 2 - self.pop[idx].solution[jdx]) + ((self.pop[rdx].solution[jdx] + self.g_best.solution[jdx]) / 2 - self.pop[idx].solution[ + jdx]) ### Mutation if self.generator.uniform() < self.p_m: pos_new[jdx] = self.pop[idx].solution[jdx] + self.generator.normal(0, 1) * self.sigma[jdx] diff --git a/mealpy/bio_based/SFOA.py b/mealpy/bio_based/SFOA.py index cd6f4579..165d5824 100644 --- a/mealpy/bio_based/SFOA.py +++ b/mealpy/bio_based/SFOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -87,8 +88,9 @@ def evolve(self, epoch): pos = np.where(self.generator.random(size=self.problem.n_dims) < self.gp, pos1, pos2) pos_new[jp1] = pos[jp1] # Boundary check for individual dimension - pos_new[jp1] = np.where((pos_new[jp1] < self.problem.lb[jp1]) | (pos_new[jp1] > self.problem.ub[jp1]), - self.pop[idx].solution[jp1], pos_new[jp1]) + pos_new[jp1] = np.where( + (pos_new[jp1] < self.problem.lb[jp1]) | (pos_new[jp1] > self.problem.ub[jp1]), + self.pop[idx].solution[jp1], pos_new[jp1]) else: # for nD is not larger than 5 jp2 = self.generator.integers(0, self.problem.n_dims) @@ -121,8 +123,9 @@ def evolve(self, epoch): r1, r2 = self.generator.random(size=2) kp = self.generator.choice(5, size=2, replace=False) pos_new = self.pop[idx].solution + r1 * dm[kp[0]] + r2 * dm[kp[1]] # exploitation - if idx == self.pop_size - 1: # last individual - pos_new = np.exp(-epoch * self.pop_size / self.epoch) * self.pop[idx].solution # regeneration of starfish + if idx == self.pop_size - 1: # last individual + pos_new = np.exp(-epoch * self.pop_size / self.epoch) * self.pop[ + idx].solution # regeneration of starfish pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/bio_based/SMA.py b/mealpy/bio_based/SMA.py index cd95a98c..a7ee5f1e 100644 --- a/mealpy/bio_based/SMA.py +++ b/mealpy/bio_based/SMA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -87,7 +88,8 @@ def evolve(self, epoch): vc = self.generator.uniform(-b, b, self.problem.n_dims) # two positions randomly selected from population, apply for the whole problem size instead of 1 variable id_a, id_b = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) - pos_1 = self.g_best.solution + vb * (self.weights[idx] * self.pop[id_a].solution - self.pop[id_b].solution) + pos_1 = self.g_best.solution + vb * ( + self.weights[idx] * self.pop[id_a].solution - self.pop[id_b].solution) pos_2 = vc * self.pop[idx].solution condition = self.generator.random(self.problem.n_dims) < p pos_new = np.where(condition, pos_1, pos_2) @@ -162,10 +164,10 @@ def evolve(self, epoch): # Eq.(2.5) if idx <= int(self.pop_size / 2): self.weights[idx] = 1 + self.generator.uniform(0, 1, self.problem.n_dims) * \ - np.log10((self.g_best.target.fitness - self.pop[idx].target.fitness) / ss + 1) + np.log10((self.g_best.target.fitness - self.pop[idx].target.fitness) / ss + 1) else: self.weights[idx] = 1 - self.generator.uniform(0, 1, self.problem.n_dims) * \ - np.log10((self.g_best.target.fitness - self.pop[idx].target.fitness) / ss + 1) + np.log10((self.g_best.target.fitness - self.pop[idx].target.fitness) / ss + 1) aa = np.arctanh(-(epoch / self.epoch) + 1) # Eq.(2.4) bb = 1 - epoch / self.epoch @@ -183,7 +185,9 @@ def evolve(self, epoch): # two positions randomly selected from population id_a, id_b = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) if self.generator.uniform() < p: # Eq.(2.1) - pos_new[jdx] = self.g_best.solution[jdx] + vb[jdx] * (self.weights[idx, jdx] * self.pop[id_a].solution[jdx] - self.pop[id_b].solution[jdx]) + pos_new[jdx] = self.g_best.solution[jdx] + vb[jdx] * ( + self.weights[idx, jdx] * self.pop[id_a].solution[jdx] - self.pop[id_b].solution[ + jdx]) else: pos_new[jdx] = vc[jdx] * pos_new[jdx] pos_new = self.correct_solution(pos_new) diff --git a/mealpy/bio_based/SOA.py b/mealpy/bio_based/SOA.py index 93c77091..799068e7 100644 --- a/mealpy/bio_based/SOA.py +++ b/mealpy/bio_based/SOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -58,20 +59,20 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - A = self.fc - epoch*self.fc / self.epoch # Eq. 6 + A = self.fc - epoch * self.fc / self.epoch # Eq. 6 uu = vv = 1 pop_new = [] for idx in range(0, self.pop_size): - B = 2 * A**2 * self.generator.random() # Eq. 8 - M = B * (self.g_best.solution - self.pop[idx].solution) # Eq. 7 - C = A * self.pop[idx].solution # Eq. 5 - D = np.abs(C + M) # Eq. 9 - k = self.generator.uniform(0, 2*np.pi) - r = uu * np.exp(k*vv) + B = 2 * A ** 2 * self.generator.random() # Eq. 8 + M = B * (self.g_best.solution - self.pop[idx].solution) # Eq. 7 + C = A * self.pop[idx].solution # Eq. 5 + D = np.abs(C + M) # Eq. 9 + k = self.generator.uniform(0, 2 * np.pi) + r = uu * np.exp(k * vv) xx = r * np.cos(k) yy = r * np.sin(k) zz = r * k - pos_new = xx * yy * zz * D + self.generator.normal(0, 1) * self.g_best.solution # Eq. 14 + pos_new = xx * yy * zz * D + self.generator.normal(0, 1) * self.g_best.solution # Eq. 14 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -133,20 +134,20 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - A = self.fc - epoch*self.fc / self.epoch # Eq. 6 + A = self.fc - epoch * self.fc / self.epoch # Eq. 6 uu = vv = 1 pop_new = [] for idx in range(0, self.pop_size): - B = 2 * A**2 * self.generator.random() # Eq. 8 - M = B * (self.g_best.solution - self.pop[idx].solution) # Eq. 7 - C = A * self.pop[idx].solution # Eq. 5 - D = np.abs(C + M) # Eq. 9 - k = self.generator.uniform(0, 2*np.pi) - r = uu * np.exp(k*vv) + B = 2 * A ** 2 * self.generator.random() # Eq. 8 + M = B * (self.g_best.solution - self.pop[idx].solution) # Eq. 7 + C = A * self.pop[idx].solution # Eq. 5 + D = np.abs(C + M) # Eq. 9 + k = self.generator.uniform(0, 2 * np.pi) + r = uu * np.exp(k * vv) xx = r * np.cos(k) yy = r * np.sin(k) zz = r * k - pos_new = xx * yy * zz * D + self.g_best.solution # Eq. 14 + pos_new = xx * yy * zz * D + self.g_best.solution # Eq. 14 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/bio_based/SOS.py b/mealpy/bio_based/SOS.py index 4428cbd6..f28061ce 100644 --- a/mealpy/bio_based/SOS.py +++ b/mealpy/bio_based/SOS.py @@ -71,7 +71,8 @@ def evolve(self, epoch): self.pop[jdx].update(solution=xj_new, target=xj_target) ## Commensalism phase jdx = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) - xi_new = self.pop[idx].solution + self.generator.uniform(-1, 1) * (self.g_best.solution - self.pop[jdx].solution) + xi_new = self.pop[idx].solution + self.generator.uniform(-1, 1) * ( + self.g_best.solution - self.pop[jdx].solution) xi_new = self.correct_solution(xi_new) xi_target = self.get_target(xi_new) if self.compare_target(xi_target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/bio_based/TPO.py b/mealpy/bio_based/TPO.py index d1c54d27..7f7dce68 100644 --- a/mealpy/bio_based/TPO.py +++ b/mealpy/bio_based/TPO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -52,7 +53,8 @@ class DevTPO(Optimizer): traveling salesman problem. Journal of Intelligent Systems, 28(5), 849-871. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.3, beta: float = 50.0, theta: float = 0.9, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.3, beta: float = 50.0, + theta: float = 0.9, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -63,7 +65,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.3, """ super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) - self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) # Number of branches + self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) # Number of branches self.alpha = self.validator.check_float("alpha", alpha, [-10.0, 10.]) self.beta = self.validator.check_float("beta", beta, [-100., 100]) self.theta = self.validator.check_float("theta", theta, (0, 1.0)) @@ -80,7 +82,7 @@ def initialize_variables(self): def initialization(self): self.pop_total = [] - self.pop = [] # The best leaf in each branches + self.pop = [] # The best leaf in each branches for idx in range(self.pop_size): leafs = self.generate_population(self.n_leafs) best = self.get_best_agent(leafs, self.problem.minmax) @@ -98,7 +100,8 @@ def evolve(self, epoch): pos_list = np.array([agent.solution for agent in self.pop_total[idx]]) carbon_gain = self._theta * self.g_best.solution - pos_list roots_old = np.copy(self.roots) - self.roots += self.alpha * carbon_gain * self.generator.uniform(-0.5, 0.5, (self.n_leafs, self.problem.n_dims)) + self.roots += self.alpha * carbon_gain * self.generator.uniform(-0.5, 0.5, + (self.n_leafs, self.problem.n_dims)) nutrient_value = self._theta * (self.roots - roots_old) pos_list_new = self.g_best.solution + self.beta * nutrient_value pop_new = [] @@ -108,10 +111,12 @@ def evolve(self, epoch): pop_new.append(agent) if self.mode not in self.AVAILABLE_MODES: agent.target = self.get_target(pos_new) - self.pop_total[idx][jdx] = self.get_better_agent(agent, self.pop_total[idx][jdx], self.problem.minmax) + self.pop_total[idx][jdx] = self.get_better_agent(agent, self.pop_total[idx][jdx], + self.problem.minmax) if self.mode in self.AVAILABLE_MODES: pop_new = self.update_target_for_population(pop_new) - self.pop_total[idx] = self.greedy_selection_population(pop_new, self.pop_total[idx], self.problem.minmax) + self.pop_total[idx] = self.greedy_selection_population(pop_new, self.pop_total[idx], + self.problem.minmax) self._theta = self._theta * self.theta for idx in range(0, self.pop_size): best = self.get_best_agent(self.pop_total[idx], self.problem.minmax) diff --git a/mealpy/bio_based/TSA.py b/mealpy/bio_based/TSA.py index 71696f7f..e40fa768 100644 --- a/mealpy/bio_based/TSA.py +++ b/mealpy/bio_based/TSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -73,7 +74,7 @@ def evolve(self, epoch): t2 = self.g_best.solution - A * np.abs(self.g_best.solution - c2 * self.pop[idx].solution) pos_new = np.where(c3 >= 0.5, t1, t2) if idx != 0: - pos_new = (pos_new + self.pop[idx-1].solution) / 2 + pos_new = (pos_new + self.pop[idx - 1].solution) / 2 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/bio_based/VCS.py b/mealpy/bio_based/VCS.py index 8e4633a4..cf100de9 100644 --- a/mealpy/bio_based/VCS.py +++ b/mealpy/bio_based/VCS.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -42,7 +43,8 @@ class DevVCS(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, lamda: float = 0.5, sigma: float = 1.5, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, lamda: float = 0.5, sigma: float = 1.5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -90,7 +92,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): sigma = (np.log1p(epoch + 1) / self.epoch) * (self.pop[idx].solution - self.g_best.solution) gauss = self.generator.normal(self.generator.normal(self.g_best.solution, np.abs(sigma))) - pos_new = gauss + self.generator.uniform() * self.g_best.solution - self.generator.uniform() * self.pop[idx].solution + pos_new = gauss + self.generator.uniform() * self.g_best.solution - self.generator.uniform() * self.pop[ + idx].solution pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop.append(agent) @@ -173,7 +176,8 @@ class OriginalVCS(DevVCS): for optimization: Virus colony search. Advances in Engineering Software, 92, pp.65-88. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, lamda: float = 0.5, sigma: float = 1.5, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, lamda: float = 0.5, sigma: float = 1.5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -199,8 +203,10 @@ def evolve(self, epoch): pop = [] for idx in range(0, self.pop_size): sigma = (np.log1p(epoch) / self.epoch) * (self.pop[idx].solution - self.g_best.solution) - gauss = np.array([self.generator.normal(self.g_best.solution[j], np.abs(sigma[j])) for j in range(0, self.problem.n_dims)]) - pos_new = gauss + self.generator.uniform() * self.g_best.solution - self.generator.uniform() * self.pop[idx].solution + gauss = np.array([self.generator.normal(self.g_best.solution[j], np.abs(sigma[j])) for j in + range(0, self.problem.n_dims)]) + pos_new = gauss + self.generator.uniform() * self.g_best.solution - self.generator.uniform() * self.pop[ + idx].solution pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop.append(agent) @@ -234,7 +240,8 @@ def evolve(self, epoch): for j in range(0, self.problem.n_dims): if self.generator.uniform() > pr: id1, id2 = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) - pos_new[j] = self.pop[id1].solution[j] - (self.pop[id2].solution[j] - self.pop[idx].solution[j]) * self.generator.uniform() + pos_new[j] = self.pop[id1].solution[j] - ( + self.pop[id2].solution[j] - self.pop[idx].solution[j]) * self.generator.uniform() pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop.append(agent) diff --git a/mealpy/bio_based/WHO.py b/mealpy/bio_based/WHO.py index c8807b2e..68a38053 100644 --- a/mealpy/bio_based/WHO.py +++ b/mealpy/bio_based/WHO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -54,7 +55,8 @@ class OriginalWHO(Optimizer): """ def __init__(self, epoch=10000, pop_size=100, n_explore_step=3, n_exploit_step=3, eta=0.15, p_hi=0.9, - local_alpha=0.9, local_beta=0.3, global_alpha=0.2, global_beta=0.8, delta_w=2.0, delta_c=2.0, **kwargs): + local_alpha=0.9, local_beta=0.3, global_alpha=0.2, global_beta=0.8, delta_w=2.0, delta_c=2.0, + **kwargs): """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -84,7 +86,8 @@ def __init__(self, epoch=10000, pop_size=100, n_explore_step=3, n_exploit_step=3 self.delta_w = self.validator.check_float("delta_w", delta_w, (0.5, 5.0)) self.delta_c = self.validator.check_float("delta_c", delta_c, (0.5, 5.0)) self.set_parameters(["epoch", "pop_size", "n_explore_step", "n_exploit_step", - "eta", "p_hi", "local_alpha", "local_beta", "global_alpha", "global_beta", "delta_w", "delta_c"]) + "eta", "p_hi", "local_alpha", "local_beta", "global_alpha", "global_beta", "delta_w", + "delta_c"]) self.sort_flag = False def evolve(self, epoch): @@ -100,7 +103,8 @@ def evolve(self, epoch): ### 1. Local movement (Milling behaviour) local_list = [] for j in range(0, self.n_explore_step): - temp = self.pop[idx].solution + self.eta * self.generator.uniform() * self.generator.uniform(self.problem.lb, self.problem.ub) + temp = self.pop[idx].solution + self.eta * self.generator.uniform() * self.generator.uniform( + self.problem.lb, self.problem.ub) pos_new = self.correct_solution(temp) agent = self.generate_empty_agent(pos_new) local_list.append(agent) @@ -108,7 +112,8 @@ def evolve(self, epoch): local_list[-1].target = self.get_target(pos_new) local_list = self.update_target_for_population(local_list) best_local = self.get_best_agent(local_list, self.problem.minmax) - temp = self.local_alpha * best_local.solution + self.local_beta * (self.pop[idx].solution - best_local.solution) + temp = self.local_alpha * best_local.solution + self.local_beta * ( + self.pop[idx].solution - best_local.solution) pos_new = self.correct_solution(temp) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -121,7 +126,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): ### 2. Herd instinct idr = self.generator.choice(range(0, self.pop_size)) - if self.compare_target(self.pop[idr].target, self.pop[idx].target, self.problem.minmax) and self.generator.random() < self.p_hi: + if self.compare_target(self.pop[idr].target, self.pop[idx].target, + self.problem.minmax) and self.generator.random() < self.p_hi: temp = self.global_alpha * self.pop[idx].solution + self.global_beta * self.pop[idr].solution pos_new = self.correct_solution(temp) tar_new = self.get_target(pos_new) diff --git a/mealpy/evolutionary_based/BWO.py b/mealpy/evolutionary_based/BWO.py index b7642769..dada741f 100644 --- a/mealpy/evolutionary_based/BWO.py +++ b/mealpy/evolutionary_based/BWO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer diff --git a/mealpy/evolutionary_based/CRO.py b/mealpy/evolutionary_based/CRO.py index 79b16b30..28957161 100644 --- a/mealpy/evolutionary_based/CRO.py +++ b/mealpy/evolutionary_based/CRO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -51,8 +52,10 @@ class OriginalCRO(Optimizer): The coral reefs optimization algorithm: a novel metaheuristic for efficiently solving optimization problems. The Scientific World Journal, 2014. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, po: float = 0.4, Fb: float = 0.9, Fa: float = 0.1, Fd: float = 0.1, - Pd: float = 0.5, GCR: float = 0.1, gamma_min: float = 0.02, gamma_max: float = 0.2, n_trials: int = 3, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, po: float = 0.4, Fb: float = 0.9, Fa: float = 0.1, + Fd: float = 0.1, + Pd: float = 0.5, GCR: float = 0.1, gamma_min: float = 0.02, gamma_max: float = 0.2, n_trials: int = 3, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -79,7 +82,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, po: float = 0.4, Fb: self.gamma_min = self.validator.check_float("gamma_min", gamma_min, (0, 0.15)) self.gamma_max = self.validator.check_float("gamma_max", gamma_max, (0.15, 1.0)) self.n_trials = self.validator.check_int("n_trials", n_trials, [2, int(self.pop_size / 2)]) - self.set_parameters(["epoch", "pop_size", "po", "Fb", "Fa", "Fd", "Pd", "GCR", "gamma_min", "gamma_max", "n_trials"]) + self.set_parameters( + ["epoch", "pop_size", "po", "Fb", "Fa", "Fd", "Pd", "GCR", "gamma_min", "gamma_max", "n_trials"]) self.sort_flag = False def initialization(self): @@ -97,8 +101,9 @@ def initialization(self): self.occupied_list[self.occupied_idx_list] = 1 def gaussian_mutation__(self, position): - random_pos = position + self.G1 * (self.problem.ub - self.problem.lb) * self.generator.normal(0, 1, self.problem.n_dims) - condition =self.generator.random(self.problem.n_dims) < self.GCR + random_pos = position + self.G1 * (self.problem.ub - self.problem.lb) * self.generator.normal(0, 1, + self.problem.n_dims) + condition = self.generator.random(self.problem.n_dims) < self.GCR pos_new = np.where(condition, random_pos, position) return self.correct_solution(pos_new) @@ -127,12 +132,14 @@ def larvae_setting__(self, larvae): def sort_occupied_reef__(self): def reef_fitness(idx): return self.pop[idx].target.fitness + return sorted(self.occupied_idx_list, key=reef_fitness) def broadcast_spawning_brooding__(self): # Step 1a larvae = [] - selected_corals = self.generator.choice(self.occupied_idx_list, int(len(self.occupied_idx_list) * self.Fb), replace=False) + selected_corals = self.generator.choice(self.occupied_idx_list, int(len(self.occupied_idx_list) * self.Fb), + replace=False) for idx in self.occupied_idx_list: if idx not in selected_corals: pos_new = self.gaussian_mutation__(self.pop[idx].solution) @@ -143,7 +150,8 @@ def broadcast_spawning_brooding__(self): # Step 1b while len(selected_corals) >= 2: id1, id2 = self.generator.choice(range(len(selected_corals)), 2, replace=False) - pos_new = self.multi_point_cross__(self.pop[selected_corals[id1]].solution, self.pop[selected_corals[id2]].solution) + pos_new = self.multi_point_cross__(self.pop[selected_corals[id1]].solution, + self.pop[selected_corals[id2]].solution) agent = self.generate_empty_agent(pos_new) larvae.append(agent) if self.mode not in self.AVAILABLE_MODES: @@ -225,8 +233,10 @@ class OCRO(OriginalCRO): Intelligence Systems, 12(2), p.1144. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, po: float = 0.4, Fb: float = 0.9, Fa: float = 0.1, Fd: float = 0.1, Pd: float = 0.5, - GCR: float = 0.1, gamma_min: float = 0.02, gamma_max: float = 0.2, n_trials: int = 3, restart_count: int = 20, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, po: float = 0.4, Fb: float = 0.9, Fa: float = 0.1, + Fd: float = 0.1, Pd: float = 0.5, + GCR: float = 0.1, gamma_min: float = 0.02, gamma_max: float = 0.2, n_trials: int = 3, + restart_count: int = 20, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -244,7 +254,9 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, po: float = 0.4, Fb: """ super().__init__(epoch, pop_size, po, Fb, Fa, Fd, Pd, GCR, gamma_min, gamma_max, n_trials, **kwargs) self.restart_count = self.validator.check_int("restart_count", restart_count, [2, int(epoch / 2)]) - self.set_parameters(["epoch", "pop_size", "po", "Fb", "Fa", "Fd", "Pd", "GCR", "gamma_min", "gamma_max", "n_trials", "restart_count"]) + self.set_parameters( + ["epoch", "pop_size", "po", "Fb", "Fa", "Fd", "Pd", "GCR", "gamma_min", "gamma_max", "n_trials", + "restart_count"]) self.sort_flag = False def initialize_variables(self): diff --git a/mealpy/evolutionary_based/DE.py b/mealpy/evolutionary_based/DE.py index e32a4a77..8fd6471a 100644 --- a/mealpy/evolutionary_based/DE.py +++ b/mealpy/evolutionary_based/DE.py @@ -5,8 +5,9 @@ # --------------------------------------------------% import numpy as np -from mealpy.optimizer import Optimizer from scipy.stats import cauchy + +from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -53,7 +54,8 @@ class OriginalDE(Optimizer): LSHADE algorithms for global numerical optimization. Swarm and Evolutionary Computation, 50, p.100455. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, wf: float = 0.1, cr: float = 0.9, strategy: int = 0, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, wf: float = 0.1, cr: float = 0.9, strategy: int = 0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -88,7 +90,8 @@ def evolve(self, epoch): # Choose 3 random element and different to i for idx in range(0, self.pop_size): idx_list = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 3, replace=False) - pos_new = self.pop[idx_list[0]].solution + self.wf * (self.pop[idx_list[1]].solution - self.pop[idx_list[2]].solution) + pos_new = self.pop[idx_list[0]].solution + self.wf * ( + self.pop[idx_list[1]].solution - self.pop[idx_list[2]].solution) pos_new = self.mutation__(self.pop[idx].solution, pos_new) agent = self.generate_empty_agent(pos_new) pop.append(agent) @@ -98,7 +101,8 @@ def evolve(self, epoch): elif self.strategy == 1: for idx in range(0, self.pop_size): idx_list = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) - pos_new = self.g_best.solution + self.wf * (self.pop[idx_list[0]].solution - self.pop[idx_list[1]].solution) + pos_new = self.g_best.solution + self.wf * ( + self.pop[idx_list[0]].solution - self.pop[idx_list[1]].solution) pos_new = self.mutation__(self.pop[idx].solution, pos_new) agent = self.generate_empty_agent(pos_new) pop.append(agent) @@ -108,7 +112,8 @@ def evolve(self, epoch): elif self.strategy == 2: for idx in range(0, self.pop_size): idx_list = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 4, replace=False) - pos_new = self.g_best.solution + self.wf * (self.pop[idx_list[0]].solution - self.pop[idx_list[1]].solution) + \ + pos_new = self.g_best.solution + self.wf * ( + self.pop[idx_list[0]].solution - self.pop[idx_list[1]].solution) + \ self.wf * (self.pop[idx_list[2]].solution - self.pop[idx_list[3]].solution) pos_new = self.mutation__(self.pop[idx].solution, pos_new) agent = self.generate_empty_agent(pos_new) @@ -119,7 +124,8 @@ def evolve(self, epoch): elif self.strategy == 3: for idx in range(0, self.pop_size): idx_list = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 5, replace=False) - pos_new = self.pop[idx_list[0]].solution + self.wf * (self.pop[idx_list[1]].solution - self.pop[idx_list[2]].solution) + \ + pos_new = self.pop[idx_list[0]].solution + self.wf * ( + self.pop[idx_list[1]].solution - self.pop[idx_list[2]].solution) + \ self.wf * (self.pop[idx_list[3]].solution - self.pop[idx_list[4]].solution) pos_new = self.mutation__(self.pop[idx].solution, pos_new) agent = self.generate_empty_agent(pos_new) @@ -408,7 +414,8 @@ def evolve(self, epoch): self.crm = np.mean(self.dyn_list_cr) self.dyn_list_cr = list() if epoch / self.loop_probability == 0: - self.p1 = self.ns1 * (self.ns2 + self.nf2) / (self.ns2 * (self.ns1 + self.nf1) + self.ns1 * (self.ns2 + self.nf2)) + self.p1 = self.ns1 * (self.ns2 + self.nf2) / ( + self.ns2 * (self.ns1 + self.nf1) + self.ns1 * (self.ns2 + self.nf2)) self.ns1 = self.ns2 = self.nf1 = self.nf2 = 0 @@ -495,13 +502,17 @@ def evolve(self, epoch): self.F = self.generator.normal(0, 1) ## Crossover if self.generator.uniform(0, 1) < self.pop[idx].crossover or idx == j: - pos_new = self.pop[idxs[0]].solution + self.F * (self.pop[idxs[1]].solution - self.pop[idxs[2]].solution) - cr_new = self.pop[idxs[0]].crossover + self.F * (self.pop[idxs[1]].crossover - self.pop[idxs[2]].crossover) + pos_new = self.pop[idxs[0]].solution + self.F * ( + self.pop[idxs[1]].solution - self.pop[idxs[2]].solution) + cr_new = self.pop[idxs[0]].crossover + self.F * ( + self.pop[idxs[1]].crossover - self.pop[idxs[2]].crossover) mr_new = self.pop[idxs[0]].mutation + self.F * (self.pop[idxs[1]].mutation - self.pop[idxs[2]].mutation) if self.branch == "ABS": - ps_new = self.pop[idxs[0]].pop_size + int(self.F * (self.pop[idxs[1]].pop_size - self.pop[idxs[2]].pop_size)) + ps_new = self.pop[idxs[0]].pop_size + int( + self.F * (self.pop[idxs[1]].pop_size - self.pop[idxs[2]].pop_size)) else: # elif self.branch == "REL": - ps_new = self.pop[idxs[0]].pop_size + self.F * (self.pop[idxs[1]].pop_size - self.pop[idxs[2]].pop_size) + ps_new = self.pop[idxs[0]].pop_size + self.F * ( + self.pop[idxs[1]].pop_size - self.pop[idxs[2]].pop_size) pos_new = self.correct_solution(pos_new) cr_new = self.edit_to_range__(cr_new, 0, 1, self.generator.random) mr_new = self.edit_to_range__(mr_new, 0, 1, self.generator.random) diff --git a/mealpy/evolutionary_based/EP.py b/mealpy/evolutionary_based/EP.py index 8f0cb803..ab6eab27 100644 --- a/mealpy/evolutionary_based/EP.py +++ b/mealpy/evolutionary_based/EP.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -79,10 +80,12 @@ def evolve(self, epoch): """ child = [] for idx in range(0, self.pop_size): - pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, self.problem.n_dims) + pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, + self.problem.n_dims) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) - s_old = self.pop[idx].strategy + self.generator.normal(0, 1.0, self.problem.n_dims) * np.abs(self.pop[idx].strategy) ** 0.5 + s_old = self.pop[idx].strategy + self.generator.normal(0, 1.0, self.problem.n_dims) * np.abs( + self.pop[idx].strategy) ** 0.5 agent.update(solution=pos_new, strategy=s_old, win=0) child.append(agent) if self.mode not in self.AVAILABLE_MODES: @@ -152,9 +155,11 @@ def evolve(self, epoch): """ child = [] for idx in range(0, self.pop_size): - pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, self.problem.n_dims) + pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, + self.problem.n_dims) pos_new = self.correct_solution(pos_new) - s_old = self.pop[idx].strategy + self.generator.normal(0, 1.0, self.problem.n_dims) * np.abs(self.pop[idx].strategy) ** 0.5 + s_old = self.pop[idx].strategy + self.generator.normal(0, 1.0, self.problem.n_dims) * np.abs( + self.pop[idx].strategy) ** 0.5 agent = self.generate_empty_agent(pos_new) agent.update(solution=pos_new, strategy=s_old, win=0) child.append(agent) @@ -180,7 +185,8 @@ def evolve(self, epoch): pop_comeback = [] idx_list = self.generator.choice(range(0, len(pop_left)), int(0.5 * len(pop_left)), replace=False) for idx in idx_list: - pos_new = pop_left[idx].solution + self.get_levy_flight_step(multiplier=0.01, size=self.problem.n_dims, case=0) + pos_new = pop_left[idx].solution + self.get_levy_flight_step(multiplier=0.01, size=self.problem.n_dims, + case=0) pos_new = self.correct_solution(pos_new) strategy = self.distance = 0.05 * (self.problem.ub - self.problem.lb) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/evolutionary_based/ES.py b/mealpy/evolutionary_based/ES.py index e8d1d27a..15348c2c 100644 --- a/mealpy/evolutionary_based/ES.py +++ b/mealpy/evolutionary_based/ES.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -57,7 +58,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, lamda: float = 0.75, self.set_parameters(["epoch", "pop_size", "lamda"]) self.n_child = int(self.lamda * self.pop_size) self.sort_flag = True - + def initialize_variables(self): self.distance = 0.05 * (self.problem.ub - self.problem.lb) @@ -76,11 +77,14 @@ def evolve(self, epoch): """ child = [] for idx in range(0, self.n_child): - pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, self.problem.n_dims) + pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, + self.problem.n_dims) pos_new = self.correct_solution(pos_new) tau = np.sqrt(2.0 * self.problem.n_dims) ** (-1.0) tau_p = np.sqrt(2.0 * np.sqrt(self.problem.n_dims)) ** (-1.0) - strategy = np.exp(tau_p * self.generator.normal(0, 1.0, self.problem.n_dims) + tau * self.generator.normal(0, 1.0, self.problem.n_dims)) + strategy = np.exp( + tau_p * self.generator.normal(0, 1.0, self.problem.n_dims) + tau * self.generator.normal(0, 1.0, + self.problem.n_dims)) agent = self.generate_empty_agent(pos_new) agent.update(solution=pos_new, strategy=strategy) child.append(agent) @@ -143,11 +147,14 @@ def evolve(self, epoch): """ child = [] for idx in range(0, self.n_child): - pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, self.problem.n_dims) + pos_new = self.pop[idx].solution + self.pop[idx].strategy * self.generator.normal(0, 1.0, + self.problem.n_dims) pos_new = self.correct_solution(pos_new) tau = np.sqrt(2.0 * self.problem.n_dims) ** (-1.0) tau_p = np.sqrt(2.0 * np.sqrt(self.problem.n_dims)) ** (-1.0) - strategy = np.exp(tau_p * self.generator.normal(0, 1.0, self.problem.n_dims) + tau * self.generator.normal(0, 1.0, self.problem.n_dims)) + strategy = np.exp( + tau_p * self.generator.normal(0, 1.0, self.problem.n_dims) + tau * self.generator.normal(0, 1.0, + self.problem.n_dims)) agent = self.generate_empty_agent(pos_new) agent.update(solution=pos_new, strategy=strategy) child.append(agent) @@ -156,18 +163,22 @@ def evolve(self, epoch): child = self.update_target_for_population(child) child_levy = [] for idx in range(0, self.n_child): - pos_new = self.pop[idx].solution + self.get_levy_flight_step(multiplier=0.001, size=self.problem.n_dims, case=-1) + pos_new = self.pop[idx].solution + self.get_levy_flight_step(multiplier=0.001, size=self.problem.n_dims, + case=-1) pos_new = self.correct_solution(pos_new) tau = np.sqrt(2.0 * self.problem.n_dims) ** (-1.0) tau_p = np.sqrt(2.0 * np.sqrt(self.problem.n_dims)) ** (-1.0) - stdevs = np.array([np.exp(tau_p * self.generator.normal(0, 1.0) + tau * self.generator.normal(0, 1.0)) for _ in range(self.problem.n_dims)]) + stdevs = np.array( + [np.exp(tau_p * self.generator.normal(0, 1.0) + tau * self.generator.normal(0, 1.0)) for _ in + range(self.problem.n_dims)]) agent = self.generate_empty_agent(pos_new) agent.update(solution=pos_new, strategy=stdevs) child_levy.append(agent) if self.mode not in self.AVAILABLE_MODES: child_levy[-1].target = self.get_target(pos_new) child_levy = self.update_target_for_population(child_levy) - self.pop = self.get_sorted_and_trimmed_population(child + child_levy + self.pop, self.pop_size, self.problem.minmax) + self.pop = self.get_sorted_and_trimmed_population(child + child_levy + self.pop, self.pop_size, + self.problem.minmax) class CMA_ES(Optimizer): @@ -200,6 +211,7 @@ class CMA_ES(Optimizer): ~~~~~~~~~~ [1] Hansen, N., & Ostermeier, A. (2001). Completely derandomized self-adaptation in evolution strategies. Evolutionary computation, 9(2), 159-195. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -223,19 +235,22 @@ def before_main_loop(self): self.ps = np.zeros(self.problem.n_dims) self.C = np.eye(self.problem.n_dims) self.pc = np.zeros(self.problem.n_dims) - self.w = np.log(self.pop_size + 0.5) - np.log(np.arange(1, self.pop_size+1)) + self.w = np.log(self.pop_size + 0.5) - np.log(np.arange(1, self.pop_size + 1)) self.w = self.w / np.sum(self.w) - self.mu_eff = 1. / np.sum(self.w**2) # Number of effective solutions + self.mu_eff = 1. / np.sum(self.w ** 2) # Number of effective solutions # Step Size Control Parameters (c_sigma and d_sigma); sigma0 = 0.1 * (self.problem.ub - self.problem.lb) self.cs = (self.mu_eff + 2) / (self.problem.n_dims + self.mu_eff + 5) - self.ds = 1 + self.cs + 2*np.max(np.sqrt((self.mu_eff - 1.)/(self.problem.n_dims + 1)) - 1, 0) - self.ENN = np.sqrt(self.problem.n_dims) * (1 - 1.0/(4*self.problem.n_dims) + 1.0/(21*self.problem.n_dims**2)) + self.ds = 1 + self.cs + 2 * np.max(np.sqrt((self.mu_eff - 1.) / (self.problem.n_dims + 1)) - 1, 0) + self.ENN = np.sqrt(self.problem.n_dims) * ( + 1 - 1.0 / (4 * self.problem.n_dims) + 1.0 / (21 * self.problem.n_dims ** 2)) ## Covariance Update Parameters - self.cc = (4+self.mu_eff/self.problem.n_dims) / (4 + self.problem.n_dims + 2 *self.mu_eff/self.problem.n_dims) - self.c1 = 2. / ((self.problem.n_dims + 1.3)**2 + self.mu_eff) + self.cc = (4 + self.mu_eff / self.problem.n_dims) / ( + 4 + self.problem.n_dims + 2 * self.mu_eff / self.problem.n_dims) + self.c1 = 2. / ((self.problem.n_dims + 1.3) ** 2 + self.mu_eff) alpha_mu = 2 - self.cmu = min(1-self.c1, alpha_mu*(self.mu_eff-2+1/self.mu_eff)/((self.problem.n_dims+2)**2+alpha_mu*self.mu_eff/2)) + self.cmu = min(1 - self.c1, alpha_mu * (self.mu_eff - 2 + 1 / self.mu_eff) / ( + (self.problem.n_dims + 2) ** 2 + alpha_mu * self.mu_eff / 2)) self.hth = (1.4 + 2 / (self.problem.n_dims + 1)) * self.ENN self.sigma = sigma0 self.x_mean = np.mean([agent.solution for agent in self.pop[:self.mu]], axis=0) @@ -270,15 +285,15 @@ def evolve(self, epoch): self.x_mean = self.x_mean + self.sigma * self.x_step # Update Step Size t11 = np.dot(self.x_step, np.linalg.inv(np.linalg.cholesky(self.C).T)) - self.ps = (1 - self.cs)*self.ps + np.sqrt(self.cs * (2 - self.cs) * self.mu_eff) * t11 - self.sigma = self.sigma * np.exp(self.cs / self.ds * (np.linalg.norm(self.ps)/self.ENN - 1))**0.3 + self.ps = (1 - self.cs) * self.ps + np.sqrt(self.cs * (2 - self.cs) * self.mu_eff) * t11 + self.sigma = self.sigma * np.exp(self.cs / self.ds * (np.linalg.norm(self.ps) / self.ENN - 1)) ** 0.3 # Update Covariance Matrix - if np.linalg.norm(self.ps) / np.sqrt(1 - (1 - self.cs)**(2 * epoch)) < self.hth: + if np.linalg.norm(self.ps) / np.sqrt(1 - (1 - self.cs) ** (2 * epoch)) < self.hth: hs = 1 else: hs = 0 delta = (1 - hs) * self.cc * (2 - self.cc) - self.pc = (1 - self.cc)*self.pc + hs*np.sqrt(self.cc * (2 - self.cc)*self.mu_eff) * self.x_step + self.pc = (1 - self.cc) * self.pc + hs * np.sqrt(self.cc * (2 - self.cc) * self.mu_eff) * self.x_step self.C = (1 - self.c1 - self.cmu) * self.C + self.c1 * (np.outer(self.pc, self.pc)) + delta * self.C for idx in range(0, self.mu): self.C = self.C + self.cmu * self.w[idx] * np.outer(self.pop[idx].step, self.pop[idx].step) @@ -321,6 +336,7 @@ class Simple_CMA_ES(Optimizer): ~~~~~~~~~~ [1] Hansen, N., & Ostermeier, A. (2001). Completely derandomized self-adaptation in evolution strategies. Evolutionary computation, 9(2), 159-195. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: diff --git a/mealpy/evolutionary_based/FPA.py b/mealpy/evolutionary_based/FPA.py index df08bf31..54c05292 100644 --- a/mealpy/evolutionary_based/FPA.py +++ b/mealpy/evolutionary_based/FPA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -44,7 +45,8 @@ class OriginalFPA(Optimizer): conference on unconventional computing and natural computation (pp. 240-249). Springer, Berlin, Heidelberg. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, p_s: float = 0.8, levy_multiplier: float = 0.1, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, p_s: float = 0.8, levy_multiplier: float = 0.1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -76,10 +78,12 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): if self.generator.uniform() < self.p_s: levy = self.get_levy_flight_step(multiplier=self.levy_multiplier, size=self.problem.n_dims, case=-1) - pos_new = self.pop[idx].solution + 1.0 / np.sqrt(epoch) * levy * (self.pop[idx].solution - self.g_best.solution) + pos_new = self.pop[idx].solution + 1.0 / np.sqrt(epoch) * levy * ( + self.pop[idx].solution - self.g_best.solution) else: id1, id2 = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) - pos_new = self.pop[idx].solution + self.generator.uniform() * (self.pop[id1].solution - self.pop[id2].solution) + pos_new = self.pop[idx].solution + self.generator.uniform() * ( + self.pop[id1].solution - self.pop[id2].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop.append(agent) diff --git a/mealpy/evolutionary_based/GA.py b/mealpy/evolutionary_based/GA.py index e9420b52..53e9a01e 100644 --- a/mealpy/evolutionary_based/GA.py +++ b/mealpy/evolutionary_based/GA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -62,7 +63,8 @@ class BaseGA(Optimizer): [1] Whitley, D., 1994. A genetic algorithm tutorial. Statistics and computing, 4(2), pp.65-85. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm: float = 0.025, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm: float = 0.025, + **kwargs: object) -> None: """ Args: epoch: maximum number of iterations, default = 10000 @@ -89,19 +91,23 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm self.mutation_multipoints = True if "selection" in kwargs: - self.selection = self.validator.check_str("selection", kwargs["selection"], ["tournament", "random", "roulette"]) + self.selection = self.validator.check_str("selection", kwargs["selection"], + ["tournament", "random", "roulette"]) if "k_way" in kwargs: self.k_way = self.validator.check_float("k_way", kwargs["k_way"], (0, 1.0)) if "crossover" in kwargs: - self.crossover = self.validator.check_str("crossover", kwargs["crossover"], ["one_point", "multi_points", "uniform", "arithmetic"]) + self.crossover = self.validator.check_str("crossover", kwargs["crossover"], + ["one_point", "multi_points", "uniform", "arithmetic"]) if "mutation_multipoints" in kwargs: - self.mutation_multipoints = self.validator.check_bool("mutation_multipoints", kwargs["mutation_multipoints"]) + self.mutation_multipoints = self.validator.check_bool("mutation_multipoints", + kwargs["mutation_multipoints"]) if self.mutation_multipoints: if "mutation" in kwargs: self.mutation = self.validator.check_str("mutation", kwargs["mutation"], ["flip", "swap"]) else: if "mutation" in kwargs: - self.mutation = self.validator.check_str("mutation", kwargs["mutation"], ["flip", "swap", "scramble", "inversion"]) + self.mutation = self.validator.check_str("mutation", kwargs["mutation"], + ["flip", "swap", "scramble", "inversion"]) def selection_process__(self, list_fitness): """ @@ -124,7 +130,7 @@ def selection_process__(self, list_fitness): id_c2 = self.get_index_roulette_wheel_selection(list_fitness) elif self.selection == "random": id_c1, id_c2 = self.generator.choice(range(self.pop_size), 2, replace=False) - else: ## tournament + else: ## tournament id_c1, id_c2 = self.get_index_kway_tournament_selection(self.pop, k_way=self.k_way, output=2) return self.pop[id_c1].solution, self.pop[id_c2].solution @@ -150,7 +156,7 @@ def selection_process_00__(self, pop_selected): id_c2 = self.get_index_roulette_wheel_selection(list_fitness) elif self.selection == "random": id_c1, id_c2 = self.generator.choice(range(len(pop_selected)), 2, replace=False) - else: ## tournament + else: ## tournament id_c1, id_c2 = self.get_index_kway_tournament_selection(pop_selected, k_way=self.k_way, output=2) return pop_selected[id_c1].solution, pop_selected[id_c2].solution @@ -173,7 +179,7 @@ def selection_process_01__(self, pop_dad, pop_mom): elif self.selection == "random": id_c1 = self.generator.choice(range(len(pop_dad))) id_c2 = self.generator.choice(range(len(pop_mom))) - else: ## tournament + else: ## tournament id_c1 = self.get_index_kway_tournament_selection(pop_dad, k_way=self.k_way, output=1)[0] id_c2 = self.get_index_kway_tournament_selection(pop_mom, k_way=self.k_way, output=1)[0] return pop_dad[id_c1].solution, pop_mom[id_c2].solution @@ -196,15 +202,15 @@ def crossover_process__(self, dad, mom): if self.crossover == "arithmetic": w1, w2 = self.crossover_arithmetic(dad, mom) elif self.crossover == "one_point": - cut = self.generator.integers(1, self.problem.n_dims-1) + cut = self.generator.integers(1, self.problem.n_dims - 1) w1 = np.concatenate([dad[:cut], mom[cut:]]) w2 = np.concatenate([mom[:cut], dad[cut:]]) elif self.crossover == "multi_points": - idxs = self.generator.choice(range(1, self.problem.n_dims-1), 2, replace=False) + idxs = self.generator.choice(range(1, self.problem.n_dims - 1), 2, replace=False) cut1, cut2 = np.min(idxs), np.max(idxs) w1 = np.concatenate([dad[:cut1], mom[cut1:cut2], dad[cut2:]]) w2 = np.concatenate([mom[:cut1], dad[cut1:cut2], mom[cut2:]]) - else: # uniform + else: # uniform flip = self.generator.integers(0, 2, self.problem.n_dims) w1 = dad * flip + mom * (1 - flip) w2 = mom * flip + dad * (1 - flip) @@ -238,7 +244,7 @@ def mutation_process__(self, child): idx_swap = self.generator.choice(list(set(range(0, self.problem.n_dims)) - {idx})) child[idx], child[idx_swap] = child[idx_swap], child[idx] return child - else: # "flip" + else: # "flip" mutation_child = self.problem.generate_solution() flag_child = self.generator.uniform(0, 1, self.problem.n_dims) < self.pm return np.where(flag_child, mutation_child, child) @@ -259,7 +265,7 @@ def mutation_process__(self, child): self.generator.shuffle(temp) child[cut1:cut2] = temp return child - else: # "flip" + else: # "flip" idx = self.generator.integers(0, self.problem.n_dims) child[idx] = self.generator.uniform(self.problem.lb[idx], self.problem.ub[idx]) return child @@ -291,7 +297,7 @@ def evolve(self, epoch): """ list_fitness = np.array([agent.target.fitness for agent in self.pop]) pop_new = [] - for i in range(0, int(self.pop_size/2)): + for i in range(0, int(self.pop_size / 2)): ### Selection child1, child2 = self.selection_process__(list_fitness) @@ -374,7 +380,8 @@ class SingleGA(BaseGA): [1] Whitley, D., 1994. A genetic algorithm tutorial. Statistics and computing, 4(2), pp.65-85. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm: float = 0.8, selection: str = "roulette", + def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm: float = 0.8, + selection: str = "roulette", crossover: str = "uniform", mutation: str = "swap", k_way: float = 0.2, **kwargs: object) -> None: """ Args: @@ -389,7 +396,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm """ super().__init__(epoch, pop_size, pc, pm, **kwargs) self.selection = self.validator.check_str("selection", selection, ["tournament", "random", "roulette"]) - self.crossover = self.validator.check_str("crossover", crossover, ["one_point", "multi_points", "uniform", "arithmetic"]) + self.crossover = self.validator.check_str("crossover", crossover, + ["one_point", "multi_points", "uniform", "arithmetic"]) self.mutation = self.validator.check_str("mutation", mutation, ["flip", "swap", "scramble", "inversion"]) self.k_way = self.validator.check_float("k_way", k_way, (0, 1.0)) self.set_parameters(["epoch", "pop_size", "pc", "pm", "selection", "crossover", "mutation", "k_way"]) @@ -426,7 +434,7 @@ def mutation_process__(self, child): self.generator.shuffle(temp) child[cut1:cut2] = temp return child - else: # "flip" + else: # "flip" idx = self.generator.integers(0, self.problem.n_dims) child[idx] = self.generator.uniform(self.problem.lb[idx], self.problem.ub[idx]) return child @@ -493,12 +501,14 @@ def __init__(self, epoch=10000, pop_size=100, pc=0.95, pm=0.8, selection="roulet crossover="uniform", mutation="swap", k_way=0.2, elite_best=0.1, elite_worst=0.3, strategy=0, **kwargs): super().__init__(epoch, pop_size, pc, pm, selection, crossover, mutation, k_way, **kwargs) - self.elite_best = self.validator.check_is_int_and_float("elite_best", elite_best, [1, int(self.pop_size / 2)-1], (0, 0.5)) + self.elite_best = self.validator.check_is_int_and_float("elite_best", elite_best, + [1, int(self.pop_size / 2) - 1], (0, 0.5)) self.n_elite_best = int(self.elite_best * self.pop_size) if self.elite_best < 1 else self.elite_best if self.n_elite_best < 1: self.n_elite_best = 1 - self.elite_worst = self.validator.check_is_int_and_float("elite_worst", elite_worst, [1, int(self.pop_size / 2)-1], (0, 0.5)) + self.elite_worst = self.validator.check_is_int_and_float("elite_worst", elite_worst, + [1, int(self.pop_size / 2) - 1], (0, 0.5)) self.n_elite_worst = int(self.elite_worst * self.pop_size) if self.elite_worst < 1 else self.elite_worst if self.n_elite_worst < 1: self.n_elite_worst = 1 @@ -535,8 +545,8 @@ def evolve(self, epoch): pop_new[-1].target = self.get_target(pos_new) self.pop = self.update_target_for_population(pop_new) else: - pop_dad = self.pop[self.n_elite_best:self.n_elite_best+self.n_elite_worst] - pop_mom = self.pop[self.n_elite_best+self.n_elite_worst:] + pop_dad = self.pop[self.n_elite_best:self.n_elite_best + self.n_elite_worst] + pop_mom = self.pop[self.n_elite_best + self.n_elite_worst:] for idx in range(self.n_elite_best, self.pop_size): ### Selection child1, child2 = self.selection_process_01__(pop_dad, pop_mom) @@ -609,7 +619,8 @@ class MultiGA(BaseGA): """ def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm: float = 0.025, - selection: str = "roulette", crossover: str = "arithmetic", mutation: str = "flip", k_way: float = 0.2, **kwargs: object) -> None: + selection: str = "roulette", crossover: str = "arithmetic", mutation: str = "flip", k_way: float = 0.2, + **kwargs: object) -> None: """ Args: epoch: maximum number of iterations, default = 10000 @@ -623,7 +634,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm """ super().__init__(epoch, pop_size, pc, pm, **kwargs) self.selection = self.validator.check_str("selection", selection, ["tournament", "random", "roulette"]) - self.crossover = self.validator.check_str("crossover", crossover, ["one_point", "multi_points", "uniform", "arithmetic"]) + self.crossover = self.validator.check_str("crossover", crossover, + ["one_point", "multi_points", "uniform", "arithmetic"]) self.mutation = self.validator.check_str("mutation", mutation, ["flip", "swap"]) self.k_way = self.validator.check_float("k_way", k_way, (0, 1.0)) self.set_parameters(["epoch", "pop_size", "pc", "pm", "selection", "crossover", "mutation", "k_way"]) @@ -646,7 +658,7 @@ def mutation_process__(self, child): idx_swap = self.generator.choice(list(set(range(0, self.problem.n_dims)) - {idx})) child[idx], child[idx_swap] = child[idx_swap], child[idx] return child - else: # "flip" + else: # "flip" mutation_child = self.problem.generate_solution() flag_child = self.generator.uniform(0, 1, self.problem.n_dims) < self.pm return np.where(flag_child, mutation_child, child) @@ -700,12 +712,14 @@ def __init__(self, epoch=10000, pop_size=100, pc=0.95, pm=0.8, selection="roulet crossover="uniform", mutation="swap", k_way=0.2, elite_best=0.1, elite_worst=0.3, strategy=0, **kwargs): super().__init__(epoch, pop_size, pc, pm, selection, crossover, mutation, k_way, **kwargs) - self.elite_best = self.validator.check_is_int_and_float("elite_best", elite_best, [1, int(self.pop_size / 2) - 1], (0, 0.5)) + self.elite_best = self.validator.check_is_int_and_float("elite_best", elite_best, + [1, int(self.pop_size / 2) - 1], (0, 0.5)) self.n_elite_best = int(self.elite_best * self.pop_size) if self.elite_best < 1 else self.elite_best if self.n_elite_best < 1: self.n_elite_best = 1 - self.elite_worst = self.validator.check_is_int_and_float("elite_worst", elite_worst, [1, int(self.pop_size / 2) - 1], (0, 0.5)) + self.elite_worst = self.validator.check_is_int_and_float("elite_worst", elite_worst, + [1, int(self.pop_size / 2) - 1], (0, 0.5)) self.n_elite_worst = int(self.elite_worst * self.pop_size) if self.elite_worst < 1 else self.elite_worst if self.n_elite_worst < 1: self.n_elite_worst = 1 @@ -742,8 +756,8 @@ def evolve(self, epoch): pop_new[-1].target = self.get_target(pos_new) self.pop = self.update_target_for_population(pop_new) else: - pop_dad = self.pop[self.n_elite_best:self.n_elite_best+self.n_elite_worst] - pop_mom = self.pop[self.n_elite_best+self.n_elite_worst:] + pop_dad = self.pop[self.n_elite_best:self.n_elite_best + self.n_elite_worst] + pop_mom = self.pop[self.n_elite_best + self.n_elite_worst:] for idx in range(self.n_elite_best, self.pop_size): ### Selection child1, child2 = self.selection_process_01__(pop_dad, pop_mom) @@ -837,12 +851,14 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.95, pm self.pc = self.validator.check_float("pc", pc, (0, 1.0)) self.pm = self.validator.check_float("pm", pm, (0, 1.0)) self.selection = self.validator.check_str("selection", selection, ["tournament", "random", "roulette"]) - self.crossover = self.validator.check_str("crossover", crossover, ["one_point", "multi_points", "uniform", "arithmetic"]) + self.crossover = self.validator.check_str("crossover", crossover, + ["one_point", "multi_points", "uniform", "arithmetic"]) self.mutation_multipoints = self.validator.check_bool("mutation_multipoints", mutation_multipoints) if self.mutation_multipoints: self.mutation = self.validator.check_str("mutation", mutation, ["flip", "swap"]) else: self.mutation = self.validator.check_str("mutation", mutation, ["flip", "swap", "scramble", "inversion"]) self.k_way = self.validator.check_float("k_way", k_way, (0, 1.0)) - self.set_parameters(["epoch", "pop_size", "pc", "pm", "selection", "crossover", "mutation", "k_way", "mutation_multipoints"]) + self.set_parameters( + ["epoch", "pop_size", "pc", "pm", "selection", "crossover", "mutation", "k_way", "mutation_multipoints"]) self.sort_flag = False diff --git a/mealpy/evolutionary_based/MA.py b/mealpy/evolutionary_based/MA.py index 4cb38b76..5d83a6b5 100644 --- a/mealpy/evolutionary_based/MA.py +++ b/mealpy/evolutionary_based/MA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -67,7 +68,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pc: float = 0.85, pm self.pc = self.validator.check_float("pc", pc, (0, 1.0)) self.pm = self.validator.check_float("pm", pm, (0, 1.0)) self.p_local = self.validator.check_float("p_local", p_local, (0, 1.0)) - self.max_local_gens = self.validator.check_int("max_local_gens", max_local_gens, [2, int(pop_size/2)]) + self.max_local_gens = self.validator.check_int("max_local_gens", max_local_gens, [2, int(pop_size / 2)]) self.bits_per_param = self.validator.check_int("bits_per_param", bits_per_param, [2, 32]) self.set_parameters(["epoch", "pop_size", "pc", "pm", "p_local", "max_local_gens", "bits_per_param"]) self.sort_flag = True @@ -94,7 +95,9 @@ def decode__(self, bitstring: str = None) -> np.ndarray: vector = np.ones(self.problem.n_dims) for idx in range(0, self.problem.n_dims): param = bitstring[idx * self.bits_per_param: (idx + 1) * self.bits_per_param] # Select 16 bit every time - vector[idx] = self.problem.lb[idx] + ((self.problem.ub[idx] - self.problem.lb[idx]) / ((2.0 ** self.bits_per_param) - 1)) * int(param, 2) + vector[idx] = self.problem.lb[idx] + ( + (self.problem.ub[idx] - self.problem.lb[idx]) / ((2.0 ** self.bits_per_param) - 1)) * int(param, + 2) return vector def crossover__(self, dad=None, mom=None): diff --git a/mealpy/evolutionary_based/SHADE.py b/mealpy/evolutionary_based/SHADE.py index 9c170021..202b4607 100644 --- a/mealpy/evolutionary_based/SHADE.py +++ b/mealpy/evolutionary_based/SHADE.py @@ -5,9 +5,10 @@ # --------------------------------------------------% import numpy as np -from mealpy.optimizer import Optimizer from scipy.stats import cauchy +from mealpy.optimizer import Optimizer + class OriginalSHADE(Optimizer): """ @@ -45,7 +46,8 @@ class OriginalSHADE(Optimizer): differential evolution. In 2013 IEEE congress on evolutionary computation (pp. 71-78). IEEE. """ - def __init__(self, epoch: int = 750, pop_size: int = 100, miu_f: float = 0.5, miu_cr: float = 0.5, **kwargs: object) -> None: + def __init__(self, epoch: int = 750, pop_size: int = 100, miu_f: float = 0.5, miu_cr: float = 0.5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -201,7 +203,8 @@ class L_SHADE(Optimizer): linear population size reduction. In 2014 IEEE congress on evolutionary computation (CEC) (pp. 1658-1665). IEEE. """ - def __init__(self, epoch: int = 750, pop_size: int = 100, miu_f: float = 0.5, miu_cr: float = 0.5, **kwargs: object) -> None: + def __init__(self, epoch: int = 750, pop_size: int = 100, miu_f: float = 0.5, miu_cr: float = 0.5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 diff --git a/mealpy/game_based/THRO.py b/mealpy/game_based/THRO.py index a8a893b5..d9a0484f 100644 --- a/mealpy/game_based/THRO.py +++ b/mealpy/game_based/THRO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,6 +46,7 @@ class OriginalTHRO(Optimizer): Tianji’s horse racing optimization (THRO): a new metaheuristic inspired by ancient wisdom and its engineering optimization applications. Artificial Intelligence Review, 58(9), p.282. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -71,13 +73,13 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - + ### """Main racing phase with five scenarios""" # Randomly shuffle and redistribute populations self.pop = self.rng.sample(self.pop, len(self.pop)) self.pop_tianji = self.pop[:self.n_pop].copy() self.pop_king = self.pop[self.n_pop:].copy() - + # Sort populations by fitness self.pop_tianji = self.get_sorted_population(self.pop_tianji, self.problem.minmax) self.pop_king = self.get_sorted_population(self.pop_king, self.problem.minmax) @@ -96,7 +98,7 @@ def evolve(self, epoch): rand_dim = self.generator.permutation(self.problem.n_dims) rand_num = int(np.ceil(np.sin(np.pi / 2 * self.generator.random()) * self.problem.n_dims)) k_b[idx, rand_dim[:rand_num]] = 1 - + # Weight parameter p = 1 - epoch / self.epoch @@ -140,17 +142,19 @@ def evolve(self, epoch): if case == 1: # Update Tianji's slowest horse pos_new = ((p * self.pop_tianji[tianji_slowest_id].solution + (1 - p) * self.pop_tianji[0].solution) + - tianji_r * (self.pop_tianji[0].solution - self.pop_tianji[tianji_slowest_id].solution + - p * (tianji_mean - king_mean))) * tianji_alpha + t_beta + tianji_r * (self.pop_tianji[0].solution - self.pop_tianji[tianji_slowest_id].solution + + p * (tianji_mean - king_mean))) * tianji_alpha + t_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_tianji[tianji_slowest_id].target, self.problem.minmax): self.pop_tianji[tianji_slowest_id] = agent # Update King's slowest horse - pos_new = ((p * self.pop_king[king_slowest_id].solution + (1 - p) * self.pop_tianji[tianji_slowest_id].solution) + - king_r * (self.pop_tianji[tianji_slowest_id].solution - self.pop_king[king_slowest_id].solution + - p * (tianji_mean - king_mean))) * king_alpha + k_beta + pos_new = ((p * self.pop_king[king_slowest_id].solution + (1 - p) * self.pop_tianji[ + tianji_slowest_id].solution) + + king_r * (self.pop_tianji[tianji_slowest_id].solution - self.pop_king[ + king_slowest_id].solution + + p * (tianji_mean - king_mean))) * king_alpha + k_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_king[king_slowest_id].target, self.problem.minmax): @@ -164,8 +168,8 @@ def evolve(self, epoch): tr1 = self.generator.choice(list(set(range(self.n_pop)) - {tianji_slowest_id})) # Update Tianji's slowest horse pos_new = ((p * self.pop_tianji[tianji_slowest_id].solution + (1 - p) * self.pop_tianji[tr1].solution) + - tianji_r * (self.pop_tianji[tr1].solution - self.pop_tianji[tianji_slowest_id].solution + - p * (tianji_mean - king_mean))) * tianji_alpha + t_beta + tianji_r * (self.pop_tianji[tr1].solution - self.pop_tianji[tianji_slowest_id].solution + + p * (tianji_mean - king_mean))) * tianji_alpha + t_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_tianji[tianji_slowest_id].target, self.problem.minmax): @@ -173,8 +177,8 @@ def evolve(self, epoch): # Update King's fastest horse pos_new = ((p * self.pop_king[king_fastest_id].solution + (1 - p) * self.pop_king[0].solution) + - king_r * (self.pop_king[0].solution - self.pop_king[king_fastest_id].solution + - p * (tianji_mean - king_mean))) * king_alpha + k_beta + king_r * (self.pop_king[0].solution - self.pop_king[king_fastest_id].solution + + p * (tianji_mean - king_mean))) * king_alpha + k_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_king[king_fastest_id].target, self.problem.minmax): @@ -204,18 +208,22 @@ def evolve(self, epoch): # Scenario 3: Tianji's fastest < King's fastest if case_fast == 1: # Update Tianji's fastest horse - pos_new = ((p * self.pop_tianji[tianji_fastest_id].solution + (1 - p) * self.pop_tianji[0].solution) + - tianji_r * (self.pop_tianji[0].solution - self.pop_tianji[tianji_fastest_id].solution + - p * (tianji_mean - king_mean))) * tianji_alpha + t_beta + pos_new = ((p * self.pop_tianji[tianji_fastest_id].solution + (1 - p) * self.pop_tianji[ + 0].solution) + + tianji_r * (self.pop_tianji[0].solution - self.pop_tianji[tianji_fastest_id].solution + + p * (tianji_mean - king_mean))) * tianji_alpha + t_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) - if self.compare_target(agent.target, self.pop_tianji[tianji_fastest_id].target, self.problem.minmax): + if self.compare_target(agent.target, self.pop_tianji[tianji_fastest_id].target, + self.problem.minmax): self.pop_tianji[tianji_fastest_id] = agent # Update King's fastest horse - pos_new = ((p * self.pop_king[king_fastest_id].solution + (1 - p) * self.pop_tianji[tianji_fastest_id].solution) + - king_r * (self.pop_tianji[tianji_fastest_id].solution - self.pop_king[king_fastest_id].solution + - p * (tianji_mean - king_mean))) * king_alpha + k_beta + pos_new = ((p * self.pop_king[king_fastest_id].solution + (1 - p) * self.pop_tianji[ + tianji_fastest_id].solution) + + king_r * (self.pop_tianji[tianji_fastest_id].solution - self.pop_king[ + king_fastest_id].solution + + p * (tianji_mean - king_mean))) * king_alpha + k_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_king[king_fastest_id].target, self.problem.minmax): @@ -229,18 +237,20 @@ def evolve(self, epoch): tr2 = self.generator.choice(list(set(range(self.n_pop)) - {tianji_fastest_id})) # Update Tianji's slowest horse - pos_new = ((p * self.pop_tianji[tianji_slowest_id].solution + (1 - p) * self.pop_tianji[tr2].solution) + - tianji_r * (self.pop_tianji[tr2].solution - self.pop_tianji[tianji_slowest_id].solution + - p * (tianji_mean - king_mean))) * tianji_alpha + t_beta + pos_new = ((p * self.pop_tianji[tianji_slowest_id].solution + (1 - p) * self.pop_tianji[ + tr2].solution) + + tianji_r * (self.pop_tianji[tr2].solution - self.pop_tianji[tianji_slowest_id].solution + + p * (tianji_mean - king_mean))) * tianji_alpha + t_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) - if self.compare_target(agent.target, self.pop_tianji[tianji_slowest_id].target, self.problem.minmax): + if self.compare_target(agent.target, self.pop_tianji[tianji_slowest_id].target, + self.problem.minmax): self.pop_tianji[tianji_slowest_id] = agent # Update King's fastest horse pos_new = ((p * self.pop_king[king_fastest_id].solution + (1 - p) * self.pop_king[0].solution) + - king_r * (self.pop_king[0].solution - self.pop_king[king_fastest_id].solution + - p * (tianji_mean - king_mean))) * king_alpha + k_beta + king_r * (self.pop_king[0].solution - self.pop_king[king_fastest_id].solution + + p * (tianji_mean - king_mean))) * king_alpha + k_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_king[king_fastest_id].target, self.problem.minmax): @@ -254,18 +264,20 @@ def evolve(self, epoch): tr3 = self.generator.choice(list(set(range(self.n_pop)) - {tianji_slowest_id})) # Update Tianji's slowest horse - pos_new = ((p * self.pop_tianji[tianji_slowest_id].solution + (1 - p) * self.pop_tianji[tr3].solution) + - tianji_r * (self.pop_tianji[tr3].solution - self.pop_tianji[tianji_slowest_id].solution + - p * (tianji_mean - king_mean))) * tianji_alpha + t_beta + pos_new = ((p * self.pop_tianji[tianji_slowest_id].solution + (1 - p) * self.pop_tianji[ + tr3].solution) + + tianji_r * (self.pop_tianji[tr3].solution - self.pop_tianji[tianji_slowest_id].solution + + p * (tianji_mean - king_mean))) * tianji_alpha + t_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) - if self.compare_target(agent.target, self.pop_tianji[tianji_slowest_id].target, self.problem.minmax): + if self.compare_target(agent.target, self.pop_tianji[tianji_slowest_id].target, + self.problem.minmax): self.pop_tianji[tianji_slowest_id] = agent # Update King's fastest horse pos_new = ((p * self.pop_king[king_fastest_id].solution + (1 - p) * self.pop_king[0].solution) + - king_r * (self.pop_king[0].solution - self.pop_king[king_fastest_id].solution + - p * (tianji_mean - king_mean))) * king_alpha + k_beta + king_r * (self.pop_king[0].solution - self.pop_king[king_fastest_id].solution + + p * (tianji_mean - king_mean))) * king_alpha + k_beta pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_king[king_fastest_id].target, self.problem.minmax): @@ -285,11 +297,12 @@ def evolve(self, epoch): # Training for Tianji's population pos_new = self.pop_tianji[idx].solution for jdx in range(self.problem.n_dims): - if self.generator.random() > 0.5: # Levy flight based training + if self.generator.random() > 0.5: # Levy flight based training tr4, tr5 = self.generator.choice(list(set(range(self.n_pop)) - {idx}), size=2, replace=False) lt = self.get_levy_flight_step(beta=1.5, multiplier=0.2, size=None, case=-1) - pos_new[jdx] = pos_new[jdx] + lt * (self.pop_tianji[tr4].solution[jdx] - self.pop_tianji[tr5].solution[jdx]) - else: # Best-guided training + pos_new[jdx] = pos_new[jdx] + lt * ( + self.pop_tianji[tr4].solution[jdx] - self.pop_tianji[tr5].solution[jdx]) + else: # Best-guided training mt = 0.5 * (1 + 0.001 * (1 - epoch / self.epoch) ** 2 * np.sin(np.pi * self.generator.random())) pos_new[jdx] = best_tianji.solution[jdx] + mt * (best_tianji.solution[jdx] - pos_new[jdx]) pos_new = self.correct_solution(pos_new) @@ -300,11 +313,12 @@ def evolve(self, epoch): # Training for King's population pos_new = self.pop_tianji[idx].solution for jdx in range(self.problem.n_dims): - if self.generator.random() > 0.5: # Levy flight based training + if self.generator.random() > 0.5: # Levy flight based training kr1, kr2 = self.generator.choice(list(set(range(self.n_pop)) - {idx}), size=2, replace=False) lk = self.get_levy_flight_step(beta=1.5, multiplier=0.2, size=None, case=-1) - pos_new[jdx] = pos_new[jdx] + lk * (self.pop_king[kr1].solution[jdx] - self.pop_king[kr2].solution[jdx]) - else: # Best-guided training + pos_new[jdx] = pos_new[jdx] + lk * ( + self.pop_king[kr1].solution[jdx] - self.pop_king[kr2].solution[jdx]) + else: # Best-guided training mk = 0.5 * (1 + 0.001 * (1 - epoch / self.epoch) ** 2 * np.sin(np.pi * self.generator.random())) pos_new[jdx] = best_king.solution[jdx] + mk * (best_king.solution[jdx] - pos_new[jdx]) pos_new = self.correct_solution(pos_new) diff --git a/mealpy/human_based/AFT.py b/mealpy/human_based/AFT.py index 1ffb337a..ed9e7831 100644 --- a/mealpy/human_based/AFT.py +++ b/mealpy/human_based/AFT.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -39,6 +40,7 @@ class OriginalAFT(Optimizer): [1] Braik, M., Ryalat, M. H., & Al-Zoubi, H. (2022). A novel meta-heuristic algorithm for solving numerical optimization problems: Ali Baba and the forty thieves. Neural Computing and Applications, 34(1), 409-455. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -53,7 +55,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> def before_main_loop(self): # Initialize best positions (Marjaneh's astute plans) - self.pop_best = self.pop.copy() # It is like local best positions like in PSO + self.pop_best = self.pop.copy() # It is like local best positions like in PSO # self.pop is population of alibaba ==> It will always update with new version no matter what def evolve(self, epoch): @@ -65,7 +67,7 @@ def evolve(self, epoch): """ # Calculate AFT parameters # Perception potential - decreases over iterations - Pp = 0.1 * np.log(2.75 * (epoch/ self.epoch) ** 0.1) + Pp = 0.1 * np.log(2.75 * (epoch / self.epoch) ** 0.1) # Tracking distance - decreases over iterations Td = 2 * np.exp(-2 * (epoch / self.epoch) ** 2) @@ -81,16 +83,19 @@ def evolve(self, epoch): # Case 1: Follow global best with tracking distance direction = np.sign(self.generator.random() - 0.5) movement = (Td * (self.pop_best[idx].solution - self.pop[idx].solution) * self.generator.random() + - Td * (self.pop[idx].solution - self.pop_best[random_followers[idx]].solution) * self.generator.random()) + Td * (self.pop[idx].solution - self.pop_best[ + random_followers[idx]].solution) * self.generator.random()) pos_new = self.g_best.solution + movement * direction else: # Case 3: Random exploration within tracking distance - pos_new = self.problem.lb + Td * (self.problem.ub - self.problem.lb) * self.generator.random(self.problem.n_dims) + pos_new = self.problem.lb + Td * (self.problem.ub - self.problem.lb) * self.generator.random( + self.problem.n_dims) else: # Thieves don't know where to search - opposite direction (Marjaneh's tricks) direction = np.sign(self.generator.random() - 0.5) movement = (Td * (self.pop_best[idx].solution - self.pop[idx].solution) * self.generator.random() + - Td * (self.pop[idx].solution - self.pop_best[random_followers[idx]].solution) * self.generator.random()) + Td * (self.pop[idx].solution - self.pop_best[ + random_followers[idx]].solution) * self.generator.random()) pos_new = self.g_best.solution - movement * direction # Clip to bounds pos_new = self.correct_solution(pos_new) diff --git a/mealpy/human_based/BRO.py b/mealpy/human_based/BRO.py index 4105ce06..4a6fdf66 100644 --- a/mealpy/human_based/BRO.py +++ b/mealpy/human_based/BRO.py @@ -6,6 +6,7 @@ import numpy as np from scipy.spatial.distance import cdist + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -105,7 +106,9 @@ def evolve(self, epoch): ## Update Loser if self.pop[jdx].damage < self.threshold: ## If loser not dead yet, move it based on general pos_new = self.generator.uniform() * (np.maximum(self.pop[jdx].solution, self.g_best.solution) - - np.minimum(self.pop[jdx].solution, self.g_best.solution)) + np.maximum(self.pop[jdx].solution, self.g_best.solution) + np.minimum(self.pop[jdx].solution, + self.g_best.solution)) + np.maximum( + self.pop[jdx].solution, self.g_best.solution) dam_new = self.pop[jdx].damage + 1 self.pop[jdx].target = self.get_target(self.pop[jdx].solution) else: ## Loser dead and respawn again @@ -119,7 +122,8 @@ def evolve(self, epoch): ## Update Loser by following position of Winner self.pop[idx] = self.pop[jdx].copy() ## Update Winner by following position of General to protect the King and General - pos_new = self.pop[jdx].solution + self.generator.uniform() * (self.g_best.solution - self.pop[jdx].solution) + pos_new = self.pop[jdx].solution + self.generator.uniform() * ( + self.g_best.solution - self.pop[jdx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) agent.damage = 0 @@ -193,8 +197,10 @@ def evolve(self, epoch): if self.compare_target(self.pop[idx].target, self.pop[jdx].target, self.problem.minmax): dam, vic = jdx, idx ## The mistake also here in the paper. if self.pop[dam].damage < self.threshold: - pos_new = self.generator.uniform(0, 1, self.problem.n_dims) * (np.maximum(self.pop[dam].solution, self.g_best.solution) - - np.minimum(self.pop[dam].solution, self.g_best.solution)) + np.maximum(self.pop[dam].solution, self.g_best.solution) + pos_new = self.generator.uniform(0, 1, self.problem.n_dims) * ( + np.maximum(self.pop[dam].solution, self.g_best.solution) - + np.minimum(self.pop[dam].solution, self.g_best.solution)) + np.maximum( + self.pop[dam].solution, self.g_best.solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) agent.damage = self.pop[dam].damage + 1 diff --git a/mealpy/human_based/BSO.py b/mealpy/human_based/BSO.py index baea3ec9..83e6a848 100644 --- a/mealpy/human_based/BSO.py +++ b/mealpy/human_based/BSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -62,7 +63,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, m_clusters: int = 5, super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) - self.m_clusters = self.validator.check_int("m_clusters", m_clusters, [2, int(self.pop_size/5)]) + self.m_clusters = self.validator.check_int("m_clusters", m_clusters, [2, int(self.pop_size / 5)]) self.p1 = self.validator.check_float("p1", p1, (0, 1.0)) self.p2 = self.validator.check_float("p2", p2, (0, 1.0)) self.p3 = self.validator.check_float("p3", p3, (0, 1.0)) @@ -103,14 +104,16 @@ def evolve(self, epoch): if self.generator.uniform() < self.p2: # p_6b if self.generator.uniform() < self.p3: - pos_new = self.centers[cluster_id].solution + epsilon * self.generator.normal(0, 1, self.problem.n_dims) + pos_new = self.centers[cluster_id].solution + epsilon * self.generator.normal(0, 1, + self.problem.n_dims) else: # 2. Using levy flight here levy_step = self.get_levy_flight_step(beta=1.0, multiplier=0.001, size=self.problem.n_dims, case=-1) pos_new = self.pop_group[cluster_id][location_id].solution + levy_step else: id1, id2 = self.generator.choice(range(0, self.m_clusters), 2, replace=False) if self.generator.uniform() < self.p4: - pos_new = 0.5 * (self.centers[id1].solution + self.centers[id2].solution) + epsilon * self.generator.normal(0, 1, self.problem.n_dims) + pos_new = 0.5 * (self.centers[id1].solution + self.centers[ + id2].solution) + epsilon * self.generator.normal(0, 1, self.problem.n_dims) else: rand_id1 = self.generator.integers(0, self.m_solution) rand_id2 = self.generator.integers(0, self.m_solution) @@ -121,11 +124,14 @@ def evolve(self, epoch): pop_group[cluster_id][location_id] = agent if self.mode not in self.AVAILABLE_MODES: agent.target = self.get_target(pos_new) - pop_group[cluster_id][location_id] = self.get_better_agent(agent, self.pop_group[cluster_id][location_id], self.problem.minmax) + pop_group[cluster_id][location_id] = self.get_better_agent(agent, + self.pop_group[cluster_id][location_id], + self.problem.minmax) if self.mode in self.AVAILABLE_MODES: for idx in range(0, self.m_clusters): pop_group[idx] = self.update_target_for_population(pop_group[idx]) - pop_group[idx] = self.greedy_selection_population(self.pop_group[idx], pop_group[idx], self.problem.minmax) + pop_group[idx] = self.greedy_selection_population(self.pop_group[idx], pop_group[idx], + self.problem.minmax) # Needed to update the centers and population self.centers = self.find_cluster__(pop_group) @@ -216,14 +222,17 @@ def evolve(self, epoch): if self.generator.uniform() < self.p3: # p_6i cluster_id = self.generator.integers(0, self.m_clusters) if self.generator.uniform() < self.p3: - pos_new = self.centers[cluster_id].solution + epsilon * self.generator.normal(0, 1, self.problem.n_dims) + pos_new = self.centers[cluster_id].solution + epsilon * self.generator.normal(0, 1, + self.problem.n_dims) else: rand_idx = self.generator.integers(0, self.m_solution) - pos_new = self.pop_group[cluster_id][rand_idx].solution + self.generator.normal(0, 1, self.problem.n_dims) + pos_new = self.pop_group[cluster_id][rand_idx].solution + self.generator.normal(0, 1, + self.problem.n_dims) else: id1, id2 = self.generator.choice(range(0, self.m_clusters), 2, replace=False) if self.generator.uniform() < self.p4: - pos_new = 0.5 * (self.centers[id1].solution + self.centers[id2].solution) + epsilon * self.generator.normal(0, 1, self.problem.n_dims) + pos_new = 0.5 * (self.centers[id1].solution + self.centers[ + id2].solution) + epsilon * self.generator.normal(0, 1, self.problem.n_dims) else: rand_id1 = self.generator.integers(0, self.m_solution) rand_id2 = self.generator.integers(0, self.m_solution) @@ -234,11 +243,14 @@ def evolve(self, epoch): pop_group[cluster_id][location_id] = agent if self.mode not in self.AVAILABLE_MODES: agent.target = self.get_target(pos_new) - pop_group[cluster_id][location_id] = self.get_better_agent(agent, self.pop_group[cluster_id][location_id], self.problem.minmax) + pop_group[cluster_id][location_id] = self.get_better_agent(agent, + self.pop_group[cluster_id][location_id], + self.problem.minmax) if self.mode in self.AVAILABLE_MODES: for idx in range(0, self.m_clusters): pop_group[idx] = self.update_target_for_population(pop_group[idx]) - pop_group[idx] = self.greedy_selection_population(self.pop_group[idx], pop_group[idx], self.problem.minmax) + pop_group[idx] = self.greedy_selection_population(self.pop_group[idx], pop_group[idx], + self.problem.minmax) # Needed to update the centers and population self.centers = self.find_cluster__(pop_group) self.pop = [] diff --git a/mealpy/human_based/CA.py b/mealpy/human_based/CA.py index ac0c2bf4..d6f57dd9 100644 --- a/mealpy/human_based/CA.py +++ b/mealpy/human_based/CA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -85,7 +86,8 @@ def evolve(self, epoch): epoch (int): The current iteration """ # create next generation - pop_child = [self.create_faithful__(self.dyn_belief_space["lb"], self.dyn_belief_space["ub"]) for _ in range(0, self.pop_size)] + pop_child = [self.create_faithful__(self.dyn_belief_space["lb"], self.dyn_belief_space["ub"]) for _ in + range(0, self.pop_size)] # select next generation pop_new = [] pop_full = self.pop + pop_child diff --git a/mealpy/human_based/CDDO.py b/mealpy/human_based/CDDO.py index 95dceb70..2c3ef3ed 100644 --- a/mealpy/human_based/CDDO.py +++ b/mealpy/human_based/CDDO.py @@ -48,6 +48,7 @@ class OriginalCDDO(Optimizer): [1] Abdulhameed, S., Rashid, T.A. Child Drawing Development Optimization Algorithm Based on Child’s Cognitive Development. Arab J Sci Eng 47, 1337–1351 (2022). https://doi.org/10.1007/s13369-021-05928-6 """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, pattern_size=10, creativity_rate=0.1, **kwargs: object) -> None: """ @@ -77,7 +78,8 @@ def before_main_loop(self): if self.pop[idx].solution[p1] == 0: self.list_gr.append(self.pop[idx].solution[p2]) else: - self.list_gr.append(self.pop[idx].solution[p1] + self.pop[idx].solution[p2] / self.pop[idx].solution[p1]) + self.list_gr.append( + self.pop[idx].solution[p1] + self.pop[idx].solution[p2] / self.pop[idx].solution[p1]) def evolve(self, epoch): """ @@ -102,7 +104,8 @@ def evolve(self, epoch): self.SR = self.generator.integers(6, 11) / 10 elif 1.5 < self.list_gr[idx] < 2: # Consider the learnt patterns - pos_new = pattern[self.generator.integers(0, self.pattern_size)].solution - self.creativity_rate * self.pop_local[idx].solution + pos_new = pattern[self.generator.integers(0, self.pattern_size)].solution - self.creativity_rate * \ + self.pop_local[idx].solution self.LR = self.generator.integers(0, 6) / 10 self.SR = self.generator.integers(0, 6) / 10 pos_new = self.correct_solution(pos_new) diff --git a/mealpy/human_based/CHIO.py b/mealpy/human_based/CHIO.py index a0bab443..cf20d330 100644 --- a/mealpy/human_based/CHIO.py +++ b/mealpy/human_based/CHIO.py @@ -5,8 +5,8 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer -from mealpy.utils.target import Target class OriginalCHIO(Optimizer): @@ -45,7 +45,8 @@ class OriginalCHIO(Optimizer): Neural Comput & Applic 33, 5011–5042 (2021). https://doi.org/10.1007/s00521-020-05296-6 """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, brr: float = 0.15, max_age: int = 10, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, brr: float = 0.15, max_age: int = 10, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -57,7 +58,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, brr: float = 0.15, m self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) self.brr = self.validator.check_float("brr", brr, (0, 1.0)) - self.max_age = self.validator.check_int("max_age", max_age, [1, 1+int(epoch/5)]) + self.max_age = self.validator.check_int("max_age", max_age, [1, 1 + int(epoch / 5)]) self.set_parameters(["epoch", "pop_size", "brr", "max_age"]) def initialize_variables(self): @@ -85,17 +86,20 @@ def evolve(self, epoch): # print("Epoch: {}, i: {}, immunity_list: {}".format(epoch, i, self.immunity_type_list)) break idx_selected = self.generator.choice(idx_candidates[0]) - pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * (self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) + pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * ( + self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) is_corona_list[i] = True elif (1.0 / 3) * self.brr <= rand < (2.0 / 3) * self.brr: idx_candidates = np.where(self.immunity_type_list == 0) # Susceptible list idx_selected = self.generator.choice(idx_candidates[0]) - pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * (self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) + pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * ( + self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) elif (2.0 / 3) * self.brr <= rand < self.brr: idx_candidates = np.where(self.immunity_type_list == 2) # Immunity list fit_list = np.array([self.pop[item].target.fitness for item in idx_candidates[0]]) idx_selected = idx_candidates[0][np.argmin(fit_list)] # Found the index of best fitness - pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * (self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) + pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * ( + self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) if self.finished: break pos_new = self.correct_solution(pos_new) @@ -116,10 +120,12 @@ def evolve(self, epoch): ## Calculate immunity mean of population fit_list = np.array([agent.target.fitness for agent in self.pop]) delta_fx = np.mean(fit_list) - if self.compare_fitness(pop_new[idx].target.fitness, delta_fx, self.problem.minmax) and self.immunity_type_list[idx] == 0 and is_corona_list[idx]: + if self.compare_fitness(pop_new[idx].target.fitness, delta_fx, self.problem.minmax) and \ + self.immunity_type_list[idx] == 0 and is_corona_list[idx]: self.immunity_type_list[idx] = 1 self.age_list[idx] = 1 - if self.compare_fitness(delta_fx, pop_new[idx].target.fitness, self.problem.minmax) and (self.immunity_type_list[idx] == 1): + if self.compare_fitness(delta_fx, pop_new[idx].target.fitness, self.problem.minmax) and ( + self.immunity_type_list[idx] == 1): self.immunity_type_list[idx] = 2 self.age_list[idx] = 0 # Step 5: Fatality condition @@ -157,7 +163,8 @@ class DevCHIO(OriginalCHIO): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, brr: float = 0.15, max_age: int = 10, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, brr: float = 0.15, max_age: int = 10, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -183,25 +190,30 @@ def evolve(self, epoch): if rand < (1.0 / 3) * self.brr: idx_candidates = np.where(self.immunity_type_list == 1) # Infected list if idx_candidates[0].size == 0: - rand_choice = self.generator.choice(range(0, self.pop_size), int(0.33 * self.pop_size), replace=False) + rand_choice = self.generator.choice(range(0, self.pop_size), int(0.33 * self.pop_size), + replace=False) self.immunity_type_list[rand_choice] = 1 idx_candidates = np.where(self.immunity_type_list == 1) idx_selected = self.generator.choice(idx_candidates[0]) - pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * (self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) + pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * ( + self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) is_corona_list[i] = True elif (1.0 / 3) * self.brr <= rand < (2.0 / 3) * self.brr: idx_candidates = np.where(self.immunity_type_list == 0) # Susceptible list if idx_candidates[0].size == 0: - rand_choice = self.generator.choice(range(0, self.pop_size), int(0.33 * self.pop_size), replace=False) + rand_choice = self.generator.choice(range(0, self.pop_size), int(0.33 * self.pop_size), + replace=False) self.immunity_type_list[rand_choice] = 0 idx_candidates = np.where(self.immunity_type_list == 0) idx_selected = self.generator.choice(idx_candidates[0]) - pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * (self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) + pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * ( + self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) elif (2.0 / 3) * self.brr <= rand < self.brr: idx_candidates = np.where(self.immunity_type_list == 2) # Immunity list fit_list = np.array([self.pop[item].target.fitness for item in idx_candidates[0]]) idx_selected = idx_candidates[0][np.argmin(fit_list)] # Found the index of best fitness - pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * (self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) + pos_new[j] = self.pop[i].solution[j] + self.generator.uniform() * ( + self.pop[i].solution[j] - self.pop[idx_selected].solution[j]) if self.finished: break pos_new = self.correct_solution(pos_new) @@ -220,10 +232,12 @@ def evolve(self, epoch): ## Calculate immunity mean of population fit_list = np.array([agent.target.fitness for agent in self.pop]) delta_fx = np.mean(fit_list) - if self.compare_fitness(pop_new[idx].target.fitness, delta_fx, self.problem.minmax) and (self.immunity_type_list[idx] == 0) and is_corona_list[idx]: + if self.compare_fitness(pop_new[idx].target.fitness, delta_fx, self.problem.minmax) and ( + self.immunity_type_list[idx] == 0) and is_corona_list[idx]: self.immunity_type_list[idx] = 1 self.age_list[idx] = 1 - if self.compare_fitness(delta_fx, pop_new[idx].target.fitness, self.problem.minmax) and (self.immunity_type_list[idx] == 1): + if self.compare_fitness(delta_fx, pop_new[idx].target.fitness, self.problem.minmax) and ( + self.immunity_type_list[idx] == 1): self.immunity_type_list[idx] = 2 self.age_list[idx] = 0 # Step 5: Fatality condition diff --git a/mealpy/human_based/DOA.py b/mealpy/human_based/DOA.py index afe628df..165d9cc7 100644 --- a/mealpy/human_based/DOA.py +++ b/mealpy/human_based/DOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -95,15 +96,18 @@ def evolve(self, epoch): # Forgetting and supplementation strategy cos_term = (np.cos((epoch + self.epoch / 10) * np.pi / self.epoch) + 1) / 2 for jdx in in_indices: - pos_new[jdx] = pbest.solution[jdx] + (self.generator.random() * (self.problem.ub[jdx] - self.problem.lb[jdx]) + self.problem.lb[jdx]) * cos_term + pos_new[jdx] = pbest.solution[jdx] + ( + self.generator.random() * (self.problem.ub[jdx] - self.problem.lb[jdx]) + + self.problem.lb[jdx]) * cos_term # Boundary handling if pos_new[jdx] > self.problem.ub[jdx] or pos_new[jdx] < self.problem.lb[jdx]: - if self.problem.n_dims > 15: # For high-dimensional problems + if self.problem.n_dims > 15: # For high-dimensional problems rdx = self.generator.choice(list(set(range(self.pop_size)) - {idx})) pos_new[jdx] = self.pop[rdx].solution[jdx] - else: # For low-dimensional problems - pos_new[jdx] = self.generator.random() * (self.problem.ub[jdx] - self.problem.lb[jdx]) + self.problem.lb[jdx] - else: # Alternative update strategy + else: # For low-dimensional problems + pos_new[jdx] = self.generator.random() * ( + self.problem.ub[jdx] - self.problem.lb[jdx]) + self.problem.lb[jdx] + else: # Alternative update strategy for jdx in in_indices: rdx = self.generator.choice(list(set(range(self.pop_size)) - {idx})) pos_new[jdx] = self.pop[rdx].solution[jdx] @@ -115,7 +119,7 @@ def evolve(self, epoch): pop_new[idx].target = self.get_target(pop_new[idx].solution) pop_new = self.update_target_for_population(pop_new) self.pop = pop_new - else: # Exploitation phase (last 10% of iterations) + else: # Exploitation phase (last 10% of iterations) # Update population pop_new = [] for idx in range(self.pop_size): @@ -125,14 +129,17 @@ def evolve(self, epoch): pos_new = self.g_best.solution.copy() for jdx in in_indices: cos_term = (np.cos(epoch * np.pi / self.epoch) + 1) / 2 - pos_new[jdx] = pos_new[jdx] + (self.generator.random() * (self.problem.ub[idx] - self.problem.lb[idx]) + self.problem.lb[idx]) * cos_term + pos_new[jdx] = pos_new[jdx] + ( + self.generator.random() * (self.problem.ub[idx] - self.problem.lb[idx]) + + self.problem.lb[idx]) * cos_term # Boundary handling if pos_new[jdx] > self.problem.ub[jdx] or pos_new[jdx] < self.problem.lb[jdx]: if self.problem.n_dims > 15: rdx = self.generator.choice(list(set(range(self.pop_size)) - {idx})) pos_new[jdx] = self.pop[rdx].solution[jdx] else: - pos_new[jdx] = self.generator.random() * (self.problem.ub[jdx] - self.problem.lb[jdx]) + self.problem.lb[jdx] + pos_new[jdx] = self.generator.random() * (self.problem.ub[jdx] - self.problem.lb[jdx]) + \ + self.problem.lb[jdx] pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/human_based/FBIO.py b/mealpy/human_based/FBIO.py index 56359cb5..11acbd46 100644 --- a/mealpy/human_based/FBIO.py +++ b/mealpy/human_based/FBIO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -68,7 +69,8 @@ def evolve(self, epoch): # Eq.(2) in FBI Inspired Meta - Optimization pos_a = self.pop[idx].solution.copy() pos_a[n_change] = self.pop[idx].solution[n_change] + self.generator.normal() * \ - (self.pop[idx].solution[n_change] - (self.pop[nb1].solution[n_change] + self.pop[nb2].solution[n_change]) / 2) + (self.pop[idx].solution[n_change] - ( + self.pop[nb1].solution[n_change] + self.pop[nb2].solution[n_change]) / 2) pos_a = self.correct_solution(pos_a) agent = self.generate_empty_agent(pos_a) pop_new.append(agent) @@ -87,7 +89,8 @@ def evolve(self, epoch): if self.generator.random() > prob[idx]: r1, r2, r3 = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 3, replace=False) ## Remove third loop here, the condition also not good, need to remove also. No need Rnd variable - temp = self.g_best.solution + self.pop[r1].solution + self.generator.uniform() * (self.pop[r2].solution - self.pop[r3].solution) + temp = self.g_best.solution + self.pop[r1].solution + self.generator.uniform() * ( + self.pop[r2].solution - self.pop[r3].solution) condition = self.generator.random(self.problem.n_dims) < 0.5 pos_new = np.where(condition, temp, self.pop[idx].solution) else: @@ -125,11 +128,13 @@ def evolve(self, epoch): if self.compare_target(self.pop[idx].target, self.pop[rr].target, self.problem.minmax): ## Eq.(7) in FBI Inspired Meta-Optimization pos_b = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ - (self.pop[rr].solution - self.pop[idx].solution) + self.generator.uniform() * (self.g_best.solution - self.pop[rr].solution) + (self.pop[rr].solution - self.pop[idx].solution) + self.generator.uniform() * ( + self.g_best.solution - self.pop[rr].solution) else: ## Eq.(8) in FBI Inspired Meta-Optimization pos_b = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ - (self.pop[idx].solution - self.pop[rr].solution) + self.generator.uniform() * (self.g_best.solution - self.pop[idx].solution) + (self.pop[idx].solution - self.pop[rr].solution) + self.generator.uniform() * ( + self.g_best.solution - self.pop[idx].solution) pos_b = self.correct_solution(pos_b) agent = self.generate_empty_agent(pos_b) pop_child.append(agent) @@ -202,7 +207,8 @@ def evolve(self, epoch): # Eq.(2) in FBI Inspired Meta - Optimization pos_a = self.pop[idx].solution.copy() pos_a[n_change] = self.pop[idx].solution[n_change] + (self.generator.uniform() - 0.5) * 2 * \ - (self.pop[idx].solution[n_change] - (self.pop[nb1].solution[n_change] + self.pop[nb2].solution[n_change]) / 2) + (self.pop[idx].solution[n_change] - ( + self.pop[nb1].solution[n_change] + self.pop[nb2].solution[n_change]) / 2) ## Not good move here, change only 1 variable but check bound of all variable in solution pos_a = self.correct_solution(pos_a) agent = self.generate_empty_agent(pos_a) @@ -266,10 +272,12 @@ def evolve(self, epoch): if self.compare_target(self.pop[idx].target, self.pop[rr].target, self.problem.minmax): ## Eq.(7) in FBI Inspired Meta-Optimization pos_b = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ - (self.pop[rr].solution - self.pop[idx].solution) + self.generator.uniform() * (self.g_best.solution - self.pop[rr].solution) + (self.pop[rr].solution - self.pop[idx].solution) + self.generator.uniform() * ( + self.g_best.solution - self.pop[rr].solution) else: ## Eq.(8) in FBI Inspired Meta-Optimization - pos_b = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * (self.pop[idx].solution - self.pop[rr].solution) + \ + pos_b = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * ( + self.pop[idx].solution - self.pop[rr].solution) + \ self.generator.uniform() * (self.g_best.solution - self.pop[idx].solution) pos_b = self.correct_solution(pos_b) agent = self.generate_empty_agent(pos_b) diff --git a/mealpy/human_based/GSKA.py b/mealpy/human_based/GSKA.py index aeaac025..e84ebb29 100644 --- a/mealpy/human_based/GSKA.py +++ b/mealpy/human_based/GSKA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,7 +44,8 @@ class DevGSKA(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, pb: float = 0.1, kr: float = 0.7, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, pb: float = 0.1, kr: float = 0.7, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -83,7 +85,8 @@ def evolve(self, epoch): rand_idx = self.generator.choice(list(set(range(0, self.pop_size)) - {previ, idx, nexti})) if self.compare_target(self.pop[rand_idx].target, self.pop[idx].target, self.problem.minmax): pos_new = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ - (self.pop[previ].solution - self.pop[nexti].solution + self.pop[rand_idx].solution - self.pop[idx].solution) + (self.pop[previ].solution - self.pop[nexti].solution + self.pop[rand_idx].solution - + self.pop[idx].solution) else: pos_new = self.g_best.solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ (self.pop[rand_idx].solution - self.pop[idx].solution) @@ -98,7 +101,8 @@ def evolve(self, epoch): rand_mid = self.generator.choice(list(set(range(id1, id2)) - {idx})) if self.compare_target(self.pop[rand_mid].target, self.pop[idx].target, self.problem.minmax): pos_new = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ - (self.pop[rand_best].solution - self.pop[rand_worst].solution + self.pop[rand_mid].solution - self.pop[idx].solution) + (self.pop[rand_best].solution - self.pop[rand_worst].solution + self.pop[ + rand_mid].solution - self.pop[idx].solution) else: pos_new = self.g_best.solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ (self.pop[rand_mid].solution - self.pop[idx].solution) @@ -153,7 +157,8 @@ class OriginalGSKA(Optimizer): optimization problems: a novel nature-inspired algorithm. International Journal of Machine Learning and Cybernetics, 11(7), pp.1501-1529. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, pb: float = 0.1, kf: float = 0.5, kr: float = 0.9, kg: int = 5, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, pb: float = 0.1, kf: float = 0.5, kr: float = 0.9, + kg: int = 5, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 diff --git a/mealpy/human_based/HBO.py b/mealpy/human_based/HBO.py index 95805136..c3cf25e7 100644 --- a/mealpy/human_based/HBO.py +++ b/mealpy/human_based/HBO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -82,7 +83,7 @@ def heapifying__(self, pop, degree=3): # Heapifying t = c while t > 0: - parent_id = int(np.floor((t + 1)/degree) - 1) + parent_id = int(np.floor((t + 1) / degree) - 1) if self.compare_target(pop[parent_id].target, pop[t].target, self.problem.minmax): break else: @@ -101,36 +102,40 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - gama = (np.mod(epoch, self.it_per_cycle) +1) / self.qtr_cycle + gama = (np.mod(epoch, self.it_per_cycle) + 1) / self.qtr_cycle gama = np.abs(2 - gama) p1 = 1. - epoch / self.epoch p2 = p1 + (1 - p1) / 2 - for c in range(self.pop_size-1, 0, -1): - if c == 0: # Dealing with root + for c in range(self.pop_size - 1, 0, -1): + if c == 0: # Dealing with root continue else: - parent_id = int(np.floor((c+1)/self.degree) - 1) - cur_agent = self.pop[self.heap[c][1]].copy() #Sol to be updated - par_agent = self.pop[self.heap[parent_id][1]] #Sol to be updated with reference to + parent_id = int(np.floor((c + 1) / self.degree) - 1) + cur_agent = self.pop[self.heap[c][1]].copy() # Sol to be updated + par_agent = self.pop[self.heap[parent_id][1]] # Sol to be updated with reference to # Sol to be updated with reference to - if self.friend_limits[c, 0] < self.friend_limits[c, 1]+1: + if self.friend_limits[c, 0] < self.friend_limits[c, 1] + 1: friend_idx = self.friend_limits[c, 0] else: - friend_idx = self.generator.choice(list(set(range(self.friend_limits[c, 0], self.friend_limits[c, 1])) - {c})) + friend_idx = self.generator.choice( + list(set(range(self.friend_limits[c, 0], self.friend_limits[c, 1])) - {c})) fri_agent = self.pop[self.heap[friend_idx][1]] - #Position Updating + # Position Updating rr = self.generator.random(self.problem.n_dims) rn = (2 * self.generator.random(self.problem.n_dims) - 1) for jdx in range(self.problem.n_dims): if rr[jdx] < p1: continue elif rr[jdx] < p2: - cur_agent.solution[jdx] = par_agent.solution[jdx] + rn[jdx] * gama * np.abs(par_agent.solution[jdx] - cur_agent.solution[jdx]) + cur_agent.solution[jdx] = par_agent.solution[jdx] + rn[jdx] * gama * np.abs( + par_agent.solution[jdx] - cur_agent.solution[jdx]) else: if self.compare_target(self.heap[friend_idx][0], self.heap[c][0], self.problem.minmax): - cur_agent.solution[jdx] = fri_agent.solution[jdx] + rn[jdx] * gama * np.abs(fri_agent.solution[jdx] - cur_agent.solution[jdx]) + cur_agent.solution[jdx] = fri_agent.solution[jdx] + rn[jdx] * gama * np.abs( + fri_agent.solution[jdx] - cur_agent.solution[jdx]) else: - cur_agent.solution[jdx] += rn[jdx] * gama * np.abs(fri_agent.solution[jdx] - cur_agent.solution[jdx]) + cur_agent.solution[jdx] += rn[jdx] * gama * np.abs( + fri_agent.solution[jdx] - cur_agent.solution[jdx]) pos_new = self.correct_solution(cur_agent.solution) cur_agent = self.generate_agent(pos_new) if self.compare_target(cur_agent.target, self.heap[c][0], self.problem.minmax): diff --git a/mealpy/human_based/HCO.py b/mealpy/human_based/HCO.py index cf444822..20c165b0 100644 --- a/mealpy/human_based/HCO.py +++ b/mealpy/human_based/HCO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -118,7 +119,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): a1 = self.pop_p[idx].solution - self.pop[idx].solution a2 = self.g_best.solution - self.pop[idx].solution - self.vec[idx] = self.wfv * (VV[idx] + self.vec[idx]) + self.c1 * a1*np.sin(2*np.pi*epoch/self.epoch) + self.c2*a2*np.sin(2*np.pi*epoch/self.epoch) + self.vec[idx] = self.wfv * (VV[idx] + self.vec[idx]) + self.c1 * a1 * np.sin( + 2 * np.pi * epoch / self.epoch) + self.c2 * a2 * np.sin(2 * np.pi * epoch / self.epoch) pos_new = self.pop[idx].solution + self.vec[idx] pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/human_based/ICA.py b/mealpy/human_based/ICA.py index 78f134c1..37f6578e 100644 --- a/mealpy/human_based/ICA.py +++ b/mealpy/human_based/ICA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -49,8 +50,10 @@ class OriginalICA(Optimizer): optimization inspired by imperialistic competition. In 2007 IEEE congress on evolutionary computation (pp. 4661-4667). Ieee. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, empire_count: int = 5, assimilation_coeff: float = 1.5, revolution_prob: float = 0.05, - revolution_rate: float = 0.1, revolution_step_size: float = 0.1, zeta: float = 0.1, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, empire_count: int = 5, assimilation_coeff: float = 1.5, + revolution_prob: float = 0.05, + revolution_rate: float = 0.1, revolution_step_size: float = 0.1, zeta: float = 0.1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -104,7 +107,8 @@ def initialization(self): for i in range(0, self.empire_count - 1): self.empires[i] = [] n_colonies = int(round(prob_empires_list[i] * colony_count)) - idx_list = self.generator.choice(list(set(range(0, colony_count)) - set(idx_already_selected)), n_colonies, replace=False).tolist() + idx_list = self.generator.choice(list(set(range(0, colony_count)) - set(idx_already_selected)), n_colonies, + replace=False).tolist() idx_already_selected += idx_list for idx in idx_list: self.empires[i].append(self.pop_colonies[idx]) @@ -124,7 +128,8 @@ def evolve(self, epoch): for idx, colonies in self.empires.items(): for idx_colony, colony in enumerate(colonies): pos_new = colony.solution + self.assimilation_coeff * \ - self.generator.uniform(0, 1, self.problem.n_dims) * (self.pop_empires[idx].solution - colony.solution) + self.generator.uniform(0, 1, self.problem.n_dims) * ( + self.pop_empires[idx].solution - colony.solution) pos_new = self.correct_solution(pos_new) self.empires[idx][idx_colony].solution = pos_new if self.mode not in self.AVAILABLE_MODES: diff --git a/mealpy/human_based/LCO.py b/mealpy/human_based/LCO.py index 13974483..7090f5ab 100644 --- a/mealpy/human_based/LCO.py +++ b/mealpy/human_based/LCO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -73,10 +74,11 @@ def evolve(self, epoch): elif prob < 0.7: # Update using Eq. 2-6 f1 = 1 - epoch / self.epoch f2 = 1 - f1 - prev_pos = self.g_best.solution if idx == 0 else self.pop[idx-1].solution + prev_pos = self.g_best.solution if idx == 0 else self.pop[idx - 1].solution best_diff = f1 * self.r1 * (self.g_best.solution - self.pop[idx].solution) better_diff = f2 * self.r1 * (prev_pos - self.pop[idx].solution) - temp = self.pop[idx].solution + self.generator.random() * better_diff + self.generator.random() * best_diff + temp = self.pop[ + idx].solution + self.generator.random() * better_diff + self.generator.random() * best_diff else: temp = self.problem.ub - (self.pop[idx].solution - self.problem.lb) * self.generator.random() pos_new = self.correct_solution(temp) @@ -150,7 +152,8 @@ def evolve(self, epoch): else: better_diff = f * self.r1 * (self.g_best.solution - self.pop[idx].solution) best_diff = (1 - f) * self.r1 * (self.pop[0].solution - self.pop[idx].solution) - temp = self.pop[idx].solution + self.generator.random() * better_diff + self.generator.random() * best_diff + temp = self.pop[ + idx].solution + self.generator.random() * better_diff + self.generator.random() * best_diff else: temp = self.problem.generate_solution() pos_new = self.correct_solution(temp) diff --git a/mealpy/human_based/QSA.py b/mealpy/human_based/QSA.py index 7ec65666..9dab8abd 100644 --- a/mealpy/human_based/QSA.py +++ b/mealpy/human_based/QSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -87,7 +88,8 @@ def update_business_1__(self, pop=None, current_epoch=None): beta = np.power(current_epoch, np.power(current_epoch / self.epoch, 0.5)) alpha = self.generator.uniform(-1, 1) E = self.generator.exponential(0.5, self.problem.n_dims) - F1 = beta * alpha * (E * np.abs(A - pop[idx].solution)) + self.generator.exponential(0.5) * (A - pop[idx].solution) + F1 = beta * alpha * (E * np.abs(A - pop[idx].solution)) + self.generator.exponential(0.5) * ( + A - pop[idx].solution) F2 = beta * alpha * (E * np.abs(A - pop[idx].solution)) if case == 1: pos_new = A + F1 @@ -149,7 +151,8 @@ def update_business_3__(self, pop, g_best): for idx in range(self.pop_size): X_new = pop[idx].solution.copy() id1 = self.generator.choice(self.pop_size) - temp = g_best.solution + self.generator.exponential(0.5, self.problem.n_dims) * (pop[id1].solution - pop[idx].solution) + temp = g_best.solution + self.generator.exponential(0.5, self.problem.n_dims) * ( + pop[id1].solution - pop[idx].solution) X_new = np.where(self.generator.random(self.problem.n_dims) > pr[idx], temp, X_new) pos_new = self.correct_solution(X_new) agent = self.generate_empty_agent(pos_new) @@ -207,7 +210,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> super().__init__(epoch, pop_size, **kwargs) self.sort_flag = True - def opposition_based__(self, pop = None, g_best = None): + def opposition_based__(self, pop=None, g_best=None): pop = self.get_sorted_population(pop, self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): @@ -426,7 +429,7 @@ def update_business_3__(self, pop, g_best): X1 = pop[i1].solution X2 = pop[i2].solution pos_new[jdx] = X1[jdx] + e * (X2[jdx] - pop[idx].solution[jdx]) - pos_new= self.correct_solution(pos_new) + pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) if self.mode not in self.AVAILABLE_MODES: diff --git a/mealpy/human_based/SARO.py b/mealpy/human_based/SARO.py index b9570090..83e49c0c 100644 --- a/mealpy/human_based/SARO.py +++ b/mealpy/human_based/SARO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -36,7 +37,8 @@ class DevSARO(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, se: float = 0.5, mu: int = 15, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, se: float = 0.5, mu: int = 15, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -48,7 +50,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, se: float = 0.5, mu: self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) self.se = self.validator.check_float("se", se, (0, 1.0)) - self.mu = self.validator.check_int("mu", mu, [2, 2+int(self.pop_size/2)]) + self.mu = self.validator.check_int("mu", mu, [2, 2 + int(self.pop_size / 2)]) self.set_parameters(["epoch", "pop_size", "se", "mu"]) self.sort_flag = True @@ -83,7 +85,8 @@ def evolve(self, epoch): #### Remove third loop here, also using random flight back when out of bound pos_new_1 = self.pop[k].solution + self.generator.uniform() * sd pos_new_2 = pop_x[idx].solution + self.generator.uniform() * sd - condition = np.logical_and(self.generator.uniform(0, 1, self.problem.n_dims) < self.se, self.pop[k].target.fitness < pop_x[idx].target.fitness) + condition = np.logical_and(self.generator.uniform(0, 1, self.problem.n_dims) < self.se, + self.pop[k].target.fitness < pop_x[idx].target.fitness) pos_new = np.where(condition, pos_new_1, pos_new_2) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -160,7 +163,8 @@ class OriginalSARO(DevSARO): algorithm based on search and rescue operations. Mathematical Problems in Engineering, 2019. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, se: float = 0.5, mu: int = 15, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, se: float = 0.5, mu: int = 15, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 diff --git a/mealpy/human_based/SPBO.py b/mealpy/human_based/SPBO.py index c2df3064..48fe31cb 100644 --- a/mealpy/human_based/SPBO.py +++ b/mealpy/human_based/SPBO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -44,6 +45,7 @@ class OriginalSPBO(Optimizer): [1] Das, B., Mukherjee, V., & Das, D. (2020). Student psychology based optimization algorithm: A new population based optimization algorithm for solving optimization problems. Advances in Engineering software, 146, 102804. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) @@ -60,25 +62,29 @@ def evolve(self, epoch): """ for jdx in range(0, self.problem.n_dims): idx_best = self.get_index_best(self.pop, self.problem.minmax) - mid = self.generator.integers(1, self.pop_size-1) + mid = self.generator.integers(1, self.pop_size - 1) x_mean = np.mean([agent.solution for agent in self.pop], axis=0) pop_new = [] for idx in range(0, self.pop_size): if idx == idx_best: k = self.generator.choice([1, 2]) j = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) - new_pos = self.g_best.solution + (-1)**k * self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[j].solution) + new_pos = self.g_best.solution + (-1) ** k * self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[j].solution) elif idx < mid: ## Good Student if self.generator.random() > self.generator.random(): - new_pos = self.g_best.solution + self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + new_pos = self.g_best.solution + self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) else: - new_pos = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + \ - self.generator.random() * (self.pop[idx].solution - x_mean) + new_pos = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) + \ + self.generator.random() * (self.pop[idx].solution - x_mean) else: ## Average Student if self.generator.random() > self.generator.random(): - new_pos = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (x_mean - self.pop[idx].solution) + new_pos = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + x_mean - self.pop[idx].solution) else: new_pos = self.problem.generate_solution() new_pos = self.correct_solution(new_pos) @@ -138,15 +144,19 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): if idx == 0: j = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) - new_pos = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) * (self.g_best.solution - self.pop[j].solution) - elif idx < good: ## Good Student + new_pos = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) * ( + self.g_best.solution - self.pop[j].solution) + elif idx < good: ## Good Student if self.generator.random() > self.generator.random(): - new_pos = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + new_pos = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) else: ra = self.generator.random(self.problem.n_dims) - new_pos = self.pop[idx].solution + ra * (self.g_best.solution - self.pop[idx].solution) + (1 - ra) * (self.pop[idx].solution - x_mean) + new_pos = self.pop[idx].solution + ra * (self.g_best.solution - self.pop[idx].solution) + ( + 1 - ra) * (self.pop[idx].solution - x_mean) elif idx < average: ## Average Student - new_pos = self.pop[idx].solution + self.generator.normal(0, 1, self.problem.n_dims) * (x_mean - self.pop[idx].solution) + new_pos = self.pop[idx].solution + self.generator.normal(0, 1, self.problem.n_dims) * ( + x_mean - self.pop[idx].solution) else: new_pos = self.problem.generate_solution() new_pos = self.correct_solution(new_pos) diff --git a/mealpy/human_based/SSDO.py b/mealpy/human_based/SSDO.py index c4424e79..e5a9a336 100644 --- a/mealpy/human_based/SSDO.py +++ b/mealpy/human_based/SSDO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -78,13 +79,16 @@ def evolve(self, epoch): r2 = self.generator.uniform() for i in range(0, self.pop_size): if r2 <= 0.5: ## Use Sine function to move - vel_new = c * np.sin(r1) * (self.pop[i].local_solution - self.pop[i].solution) + (2-c)*np.sin(r1) * (pos_mean - self.pop[i].solution) + vel_new = c * np.sin(r1) * (self.pop[i].local_solution - self.pop[i].solution) + (2 - c) * np.sin( + r1) * (pos_mean - self.pop[i].solution) else: ## Use Cosine function to move - vel_new = c * np.cos(r1) * (self.pop[i].local_solution - self.pop[i].solution) + (2-c)*np.cos(r1) * (pos_mean - self.pop[i].solution) + vel_new = c * np.cos(r1) * (self.pop[i].local_solution - self.pop[i].solution) + (2 - c) * np.cos( + r1) * (pos_mean - self.pop[i].solution) pop_new[i].velocity = vel_new ## Reproduction for idx in range(0, self.pop_size): - pos_new = self.generator.normal(0, 1, self.problem.n_dims) * pop_new[idx].solution + self.generator.random() * pop_new[idx].velocity + pos_new = self.generator.normal(0, 1, self.problem.n_dims) * pop_new[ + idx].solution + self.generator.random() * pop_new[idx].velocity pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) agent.local_solution = self.pop[idx].solution.copy() diff --git a/mealpy/human_based/TLO.py b/mealpy/human_based/TLO.py index 06dc05b5..a800ad75 100644 --- a/mealpy/human_based/TLO.py +++ b/mealpy/human_based/TLO.py @@ -4,8 +4,10 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from functools import reduce + +import numpy as np + from mealpy.optimizer import Optimizer @@ -69,7 +71,8 @@ def evolve(self, epoch): ## Teaching Phrase TF = self.generator.integers(1, 3) # 1 or 2 (never 3) list_pos = np.array([agent.solution for agent in self.pop]) - DIFF_MEAN = self.generator.random(self.problem.n_dims) * (self.g_best.solution - TF * np.mean(list_pos, axis=0)) + DIFF_MEAN = self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - TF * np.mean(list_pos, axis=0)) pos_new = self.pop[idx].solution + DIFF_MEAN pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -86,9 +89,11 @@ def evolve(self, epoch): pos_new = self.pop[idx].solution.copy().astype(float) id_partner = self.generator.choice(np.setxor1d(np.array(range(self.pop_size)), np.array([idx]))) if self.compare_target(self.pop[idx].target, self.pop[id_partner].target, self.problem.minmax): - pos_new += self.generator.random(self.problem.n_dims) * (self.pop[idx].solution - self.pop[id_partner].solution) + pos_new += self.generator.random(self.problem.n_dims) * ( + self.pop[idx].solution - self.pop[id_partner].solution) else: - pos_new += self.generator.random(self.problem.n_dims) * (self.pop[id_partner].solution - self.pop[idx].solution) + pos_new += self.generator.random(self.problem.n_dims) * ( + self.pop[id_partner].solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_child.append(agent) @@ -219,7 +224,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_teachers: int = 5, n_teachers (int): number of teachers in class """ super().__init__(epoch, pop_size, **kwargs) - self.n_teachers = self.validator.check_int("n_teachers", n_teachers, [2, int(np.sqrt(self.pop_size)-1)]) + self.n_teachers = self.validator.check_int("n_teachers", n_teachers, [2, int(np.sqrt(self.pop_size) - 1)]) self.set_parameters(["epoch", "pop_size", "n_teachers"]) self.n_students = self.pop_size - self.n_teachers self.n_students_in_team = int(self.n_students / self.n_teachers) @@ -261,9 +266,11 @@ def evolve(self, epoch): diff_mean = self.generator.random() * (teacher.solution - TF * mean_team) # Step 8 id2 = self.generator.choice(list(set(range(0, self.n_teachers)) - {id_teach})) if self.compare_target(teacher.target, team[id2].target, self.problem.minmax): - pos_new = (student.solution + diff_mean) + self.generator.random() * (team[id2].solution - student.solution) + pos_new = (student.solution + diff_mean) + self.generator.random() * ( + team[id2].solution - student.solution) else: - pos_new = (student.solution + diff_mean) + self.generator.random() * (student.solution - team[id2].solution) + pos_new = (student.solution + diff_mean) + self.generator.random() * ( + student.solution - team[id2].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/human_based/TOA.py b/mealpy/human_based/TOA.py index 289bc076..57b25eba 100644 --- a/mealpy/human_based/TOA.py +++ b/mealpy/human_based/TOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -52,6 +53,7 @@ class OriginalTOA(Optimizer): [1] Dehghani, M., & Trojovský, P. (2021). Teamwork optimization algorithm: A new optimization approach for function minimization/maximization. Sensors, 21(13), 4567. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -82,7 +84,8 @@ def evolve(self, epoch): """ for idx in range(0, self.pop_size): # Stage 1: Supervisor guidance - pos_new = self.pop[idx].solution + self.generator.random() * (self.g_best.solution - self.generator.integers(1, 3) * self.pop[idx].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.g_best.solution - self.generator.integers(1, 3) * self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): @@ -96,7 +99,8 @@ def evolve(self, epoch): sf_pos = self.correct_solution(np.mean(sf_pos, axis=0)) sf = self.generate_agent(sf_pos) pos_new = self.pop[idx].solution + self.generator.random() * (sf.solution - self.generator.integers(1, 3) * - self.pop[idx].solution) * np.sign(self.pop[idx].target.fitness - sf.target.fitness) + self.pop[idx].solution) * np.sign( + self.pop[idx].target.fitness - sf.target.fitness) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/human_based/WarSO.py b/mealpy/human_based/WarSO.py index a28ffb64..74fa76d5 100644 --- a/mealpy/human_based/WarSO.py +++ b/mealpy/human_based/WarSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -76,14 +77,14 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): r1 = self.generator.random() if r1 < self.rr: - pos_new = 2*r1*(self.g_best.solution - self.pop[com[idx]].solution) + \ - self.wl[idx]*self.generator.random()*(pop_sorted[idx].solution - self.pop[idx].solution) + pos_new = 2 * r1 * (self.g_best.solution - self.pop[com[idx]].solution) + \ + self.wl[idx] * self.generator.random() * (pop_sorted[idx].solution - self.pop[idx].solution) else: - pos_new = 2*r1*(pop_sorted[idx].solution - self.g_best.solution) + \ + pos_new = 2 * r1 * (pop_sorted[idx].solution - self.g_best.solution) + \ self.generator.random() * (self.wl[idx] * self.g_best.solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent self.wg[idx] += 1 - self.wl[idx] = 1 * self.wl[idx] * (1 - self.wg[idx] / self.epoch)**2 + self.wl[idx] = 1 * self.wl[idx] * (1 - self.wg[idx] / self.epoch) ** 2 diff --git a/mealpy/math_based/AOA.py b/mealpy/math_based/AOA.py index a23cd7ca..aaebc81c 100644 --- a/mealpy/math_based/AOA.py +++ b/mealpy/math_based/AOA.py @@ -74,7 +74,7 @@ def evolve(self, epoch): epoch (int): The current iteration """ moa = self.moa_min + epoch * ((self.moa_max - self.moa_min) / self.epoch) # Eq. 2 - mop = 1 - ((epoch+1) ** (1.0 / self.alpha)) / (self.epoch ** (1.0 / self.alpha)) # Eq. 4 + mop = 1 - ((epoch + 1) ** (1.0 / self.alpha)) / (self.epoch ** (1.0 / self.alpha)) # Eq. 4 pop_new = [] for idx in range(0, self.pop_size): pos_new = self.pop[idx].solution.copy() @@ -85,12 +85,15 @@ def evolve(self, epoch): pos_new[j] = self.g_best.solution[j] / (mop + self.EPSILON) * \ ((self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) else: - pos_new[j] = self.g_best.solution[j] * mop * ((self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) + pos_new[j] = self.g_best.solution[j] * mop * ( + (self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) else: # Exploitation phase if r3 < 0.5: - pos_new[j] = self.g_best.solution[j] - mop * ((self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) + pos_new[j] = self.g_best.solution[j] - mop * ( + (self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) else: - pos_new[j] = self.g_best.solution[j] + mop * ((self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) + pos_new[j] = self.g_best.solution[j] + mop * ( + (self.problem.ub[j] - self.problem.lb[j]) * self.miu + self.problem.lb[j]) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/math_based/CEM.py b/mealpy/math_based/CEM.py index 6136a473..fa12155c 100644 --- a/mealpy/math_based/CEM.py +++ b/mealpy/math_based/CEM.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,8 @@ class OriginalCEM(Optimizer): cross-entropy method. Annals of operations research, 134(1), pp.19-67. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 20, alpha: float = 0.7, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 20, alpha: float = 0.7, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -56,7 +58,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 20, al super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) - self.n_best = self.validator.check_int("n_best", n_best, [2, int(self.pop_size/2)]) + self.n_best = self.validator.check_int("n_best", n_best, [2, int(self.pop_size / 2)]) self.alpha = self.validator.check_float("alpha", alpha, (0, 1.0)) self.set_parameters(["epoch", "pop_size", "n_best", "alpha"]) self.sort_flag = True @@ -89,7 +91,7 @@ def evolve(self, epoch): pop_new.append(agent) if self.mode not in self.AVAILABLE_MODES: agent.target = self.get_target(pos_new) - self.pop[idx] =self.get_better_agent(agent, self.pop[idx], self.problem.minmax) + self.pop[idx] = self.get_better_agent(agent, self.pop[idx], self.problem.minmax) if self.mode in self.AVAILABLE_MODES: pop_new = self.update_target_for_population(pop_new) self.pop = self.greedy_selection_population(self.pop, pop_new, self.problem.minmax) diff --git a/mealpy/math_based/CGO.py b/mealpy/math_based/CGO.py index e240f629..35416ec2 100644 --- a/mealpy/math_based/CGO.py +++ b/mealpy/math_based/CGO.py @@ -4,7 +4,6 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from mealpy.optimizer import Optimizer diff --git a/mealpy/math_based/CircleSA.py b/mealpy/math_based/CircleSA.py index 17704a37..7e7f7450 100644 --- a/mealpy/math_based/CircleSA.py +++ b/mealpy/math_based/CircleSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -56,14 +57,15 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - a = np.pi - np.pi * (epoch/self.epoch)**2 # Eq. 8 + a = np.pi - np.pi * (epoch / self.epoch) ** 2 # Eq. 8 p = 1 - 0.9 * (epoch / self.epoch) ** 0.5 threshold = self.c_factor * self.epoch pop_new = [] for idx in range(0, self.pop_size): w = a * self.generator.random() - a if epoch > threshold: - x_new = self.g_best.solution + (self.g_best.solution - self.pop[idx].solution) * np.tan(w * self.generator.random()) + x_new = self.g_best.solution + (self.g_best.solution - self.pop[idx].solution) * np.tan( + w * self.generator.random()) else: x_new = self.g_best.solution - (self.g_best.solution - self.pop[idx].solution) * np.tan(w * p) pos_new = self.correct_solution(x_new) diff --git a/mealpy/math_based/GBO.py b/mealpy/math_based/GBO.py index 8950aac6..a82ff6ef 100644 --- a/mealpy/math_based/GBO.py +++ b/mealpy/math_based/GBO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -42,7 +43,8 @@ class OriginalGBO(Optimizer): A new metaheuristic optimization algorithm. Information Sciences, 540, pp.131-159. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, pr: float = 0.5, beta_min: float = 0.2, beta_max: float = 1.2, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, pr: float = 0.5, beta_min: float = 0.2, + beta_max: float = 1.2, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -91,7 +93,8 @@ def evolve(self, epoch): self.pop[idx].solution / (self.g_worst.solution - self.g_best.solution + epsilon) y_p = self.generator.random() * ((z + self.pop[idx].solution) / 2 + self.generator.random() * delta_x) y_q = self.generator.random() * ((z + self.pop[idx].solution) / 2 - self.generator.random() * delta_x) - x2 = self.g_best.solution - self.generator.normal() * p1 * 2 * delta_x * self.pop[idx].solution / (y_p - y_q + epsilon) + \ + x2 = self.g_best.solution - self.generator.normal() * p1 * 2 * delta_x * self.pop[idx].solution / ( + y_p - y_q + epsilon) + \ self.generator.random() * p2 * (self.pop[r1].solution - self.pop[r2].solution) x3 = self.pop[idx].solution - p1 * (x2 - x1) diff --git a/mealpy/math_based/HC.py b/mealpy/math_based/HC.py index 0a447042..1692c7da 100644 --- a/mealpy/math_based/HC.py +++ b/mealpy/math_based/HC.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -124,7 +125,7 @@ def __init__(self, epoch=10000, pop_size=100, neighbour_size=10, **kwargs): super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.neighbour_size = self.validator.check_int("neighbour_size", neighbour_size, [2, int(self.pop_size/2)]) + self.neighbour_size = self.validator.check_int("neighbour_size", neighbour_size, [2, int(self.pop_size / 2)]) self.set_parameters(["epoch", "pop_size", "neighbour_size"]) self.sort_flag = False diff --git a/mealpy/math_based/INFO.py b/mealpy/math_based/INFO.py index 3e1bc8d5..6bb6fe3b 100644 --- a/mealpy/math_based/INFO.py +++ b/mealpy/math_based/INFO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -61,7 +62,7 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - alpha = 2 * np.exp(-4 * (epoch / self.epoch)) # Eqs.(5.1) - Eq.(9.1) + alpha = 2 * np.exp(-4 * (epoch / self.epoch)) # Eqs.(5.1) - Eq.(9.1) idx_better = self.generator.integers(2, 6) better = self.pop[idx_better] g_worst = self.pop[-1] @@ -69,8 +70,8 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): ## Updating rule stage - delta = 2 * self.generator.random() * alpha - alpha # Eq. (5) - sigma = 2 * self.generator.random() * alpha - alpha # Eq. (9) + delta = 2 * self.generator.random() * alpha - alpha # Eq. (5) + sigma = 2 * self.generator.random() * alpha - alpha # Eq. (9) ## Select three random solution a, b, c = self.generator.choice(range(0, self.pop_size), 3, replace=False) e1 = 1e-25 @@ -81,30 +82,30 @@ def evolve(self, epoch): omg1 = np.max([fit_a, fit_b, fit_c]) MM1 = np.array([fit_a - fit_b, fit_a - fit_c, fit_b - fit_c]) - w1 = np.cos(MM1[0] + np.pi) * np.exp(-np.abs(MM1[0] / omg1)) # Eq. (4.2) - w2 = np.cos(MM1[1] + np.pi) * np.exp(-np.abs(MM1[1] / omg1)) # Eq. (4.3) - w3 = np.cos(MM1[2] + np.pi) * np.exp(-np.abs(MM1[2] / omg1)) # Eq. (4.4) + w1 = np.cos(MM1[0] + np.pi) * np.exp(-np.abs(MM1[0] / omg1)) # Eq. (4.2) + w2 = np.cos(MM1[1] + np.pi) * np.exp(-np.abs(MM1[1] / omg1)) # Eq. (4.3) + w3 = np.cos(MM1[2] + np.pi) * np.exp(-np.abs(MM1[2] / omg1)) # Eq. (4.4) Wt1 = np.sum([w1, w2, w3]) - WM1 = delta * (w1 * (self.pop[a].solution - self.pop[b].solution) + # Eq.(4.1) - w2 * (self.pop[a].solution - self.pop[c].solution) + - w3 * (self.pop[b].solution - self.pop[c].solution)) / (Wt1 + 1) + epsilon + WM1 = delta * (w1 * (self.pop[a].solution - self.pop[b].solution) + # Eq.(4.1) + w2 * (self.pop[a].solution - self.pop[c].solution) + + w3 * (self.pop[b].solution - self.pop[c].solution)) / (Wt1 + 1) + epsilon fit_1 = self.g_best.target.fitness fit_2 = better.target.fitness fit_3 = g_worst.target.fitness omg2 = np.max([fit_1, fit_2, fit_3]) MM2 = np.array([fit_1 - fit_2, fit_1 - fit_3, fit_2 - fit_3]) - w4 = np.cos(MM2[0] + np.pi) * np.exp(-np.abs(MM2[0] / omg2)) # Eq. (4.7) - w5 = np.cos(MM2[1] + np.pi) * np.exp(-np.abs(MM2[1] / omg2)) # Eq. (4.8) - w6 = np.cos(MM2[2] + np.pi) * np.exp(-np.abs(MM2[2] / omg2)) # Eq. (4.9) + w4 = np.cos(MM2[0] + np.pi) * np.exp(-np.abs(MM2[0] / omg2)) # Eq. (4.7) + w5 = np.cos(MM2[1] + np.pi) * np.exp(-np.abs(MM2[1] / omg2)) # Eq. (4.8) + w6 = np.cos(MM2[2] + np.pi) * np.exp(-np.abs(MM2[2] / omg2)) # Eq. (4.9) Wt2 = np.sum([w4, w5, w6]) - WM2 = delta * (w4 * (self.g_best.solution - better.solution) + # Eq. (4.6) + WM2 = delta * (w4 * (self.g_best.solution - better.solution) + # Eq. (4.6) w5 * (self.g_best.solution - g_worst.solution) + - w6 * (better.solution - g_worst.solution)) / (Wt2 + 1) + epsilon + w6 * (better.solution - g_worst.solution)) / (Wt2 + 1) + epsilon ## Determine MeanRule r = self.generator.uniform(0.1, 0.5) - mean_rule = r * WM1 + (1 - r) * WM2 # Eq. (4) - if self.generator.random() < 0.5: # Eq. (8) + mean_rule = r * WM1 + (1 - r) * WM2 # Eq. (4) + if self.generator.random() < 0.5: # Eq. (8) z1 = self.pop[idx].solution + sigma * (self.generator.random() * mean_rule) + self.generator.random() * \ (self.g_best.solution - self.pop[a].solution) / (fit_1 - fit_a + 1) z2 = self.g_best.solution + sigma * (self.generator.random() * mean_rule) + self.generator.random() * \ @@ -116,25 +117,28 @@ def evolve(self, epoch): (self.pop[a].solution - self.pop[b].solution) / (fit_a - fit_b + 1) ## Vector combining stage mu = 0.05 * self.generator.random(self.problem.n_dims) - u1 = z1 + mu * np.abs(z1 - z2) # Eq. (10.1) - u2 = z2 + mu * np.abs(z1 - z2) # Eq. (10.2) + u1 = z1 + mu * np.abs(z1 - z2) # Eq. (10.1) + u2 = z2 + mu * np.abs(z1 - z2) # Eq. (10.2) cond1 = self.generator.random(self.problem.n_dims) < 0.05 cond2 = self.generator.random(self.problem.n_dims) < 0.05 x1 = np.where(cond1, u1, u2) - pos_new = np.where(cond2, x1, self.pop[idx].solution) # Eq. (10.3) + pos_new = np.where(cond2, x1, self.pop[idx].solution) # Eq. (10.3) ## Local search stage if self.generator.random() < 0.5: - L = int(self.generator.random() < 0.5) # 0 or 1 - v1 = (1 - L) * 2 * self.generator.random() + L # Eqs. (11.5) - v2 = self.generator.random() * L + (1 - L) # Eq. (11.6) - x_avg = (self.pop[a].solution + self.pop[b].solution + self.pop[c].solution) / 3 # Eq. (11.4) + L = int(self.generator.random() < 0.5) # 0 or 1 + v1 = (1 - L) * 2 * self.generator.random() + L # Eqs. (11.5) + v2 = self.generator.random() * L + (1 - L) # Eq. (11.6) + x_avg = (self.pop[a].solution + self.pop[b].solution + self.pop[c].solution) / 3 # Eq. (11.4) phi = self.generator.random() - x_rand = phi * x_avg + (1 - phi) * (phi * better.solution + (1 - phi) * self.g_best.solution) # Eq. (11.3) + x_rand = phi * x_avg + (1 - phi) * ( + phi * better.solution + (1 - phi) * self.g_best.solution) # Eq. (11.3) n_rand = L * self.generator.random(self.problem.n_dims) + (1 - L) * self.generator.random() - if self.generator.random() < 0.5: # Eq. (11.1) - pos_new = self.g_best.solution + n_rand * (mean_rule + self.generator.random() * (self.g_best.solution - self.pop[a].solution)) - else: # Eq. (11.2) - pos_new = x_rand + n_rand * (mean_rule + self.generator.random() * (v1 * self.g_best.solution - v2 * x_rand)) + if self.generator.random() < 0.5: # Eq. (11.1) + pos_new = self.g_best.solution + n_rand * ( + mean_rule + self.generator.random() * (self.g_best.solution - self.pop[a].solution)) + else: # Eq. (11.2) + pos_new = x_rand + n_rand * ( + mean_rule + self.generator.random() * (v1 * self.g_best.solution - v2 * x_rand)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/math_based/PSS.py b/mealpy/math_based/PSS.py index 4cb82900..440d47a3 100644 --- a/mealpy/math_based/PSS.py +++ b/mealpy/math_based/PSS.py @@ -6,6 +6,7 @@ import numpy as np from scipy.stats import qmc + from mealpy.optimizer import Optimizer @@ -45,7 +46,8 @@ class OriginalPSS(Optimizer): [1] Shaqfa, M. and Beyer, K., 2021. Pareto-like sequential sampling heuristic for global optimisation. Soft Computing, 25(14), pp.9077-9096. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, acceptance_rate: float = 0.9, sampling_method: str = "LHS", **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, acceptance_rate: float = 0.9, + sampling_method: str = "LHS", **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -69,7 +71,7 @@ def initialize_variables(self): def create_population(self, pop_size=None): if self.sampling_method == "MC": pop = self.generator.random(self.pop_size, self.problem.n_dims) - else: # Default: "LHS" + else: # Default: "LHS" sampler = qmc.LatinHypercube(d=self.problem.n_dims) pop = sampler.random(n=pop_size) return pop @@ -102,7 +104,8 @@ def evolve(self, epoch): deviation = self.generator.uniform(min(0, self.g_best.solution[k]), max(0, self.g_best.solution[k])) if self.new_solution: # The deviation is positive dynamic real number - deviation = abs(0.5 * (1. - self.acceptance_rate) * (self.problem.ub[k] - self.problem.lb[k])) * (1 - (epoch / self.epoch)) + deviation = abs(0.5 * (1. - self.acceptance_rate) * (self.problem.ub[k] - self.problem.lb[k])) * ( + 1 - (epoch / self.epoch)) reduced_lb = self.g_best.solution[k] - deviation reduced_lb = np.amax([reduced_lb, self.problem.lb[k]]) reduced_ub = reduced_lb + deviation * 2. diff --git a/mealpy/math_based/RUN.py b/mealpy/math_based/RUN.py index c9a3efbe..a97d4835 100644 --- a/mealpy/math_based/RUN.py +++ b/mealpy/math_based/RUN.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -61,13 +62,13 @@ def runge_kutta__(self, xb, xw, delta_x): r1 = self.generator.random(dim) r2 = self.generator.random(dim) K1 = 0.5 * (self.generator.random() * xw - C * xb) - K2 = 0.5 * (self.generator.random() * (xw + r2*K1*delta_x/2) - (C*xb + r1*K1*delta_x/2)) - K3 = 0.5 * (self.generator.random() * (xw + r2*K2*delta_x/2) - (C*xb + r1*K2*delta_x/2)) - K4 = 0.5 * (self.generator.random() * (xw + r2*K3*delta_x) - (C*xb + r1*K3*delta_x)) - return (K1 + 2*K2 + 2*K3 + K4)/6 + K2 = 0.5 * (self.generator.random() * (xw + r2 * K1 * delta_x / 2) - (C * xb + r1 * K1 * delta_x / 2)) + K3 = 0.5 * (self.generator.random() * (xw + r2 * K2 * delta_x / 2) - (C * xb + r1 * K2 * delta_x / 2)) + K4 = 0.5 * (self.generator.random() * (xw + r2 * K3 * delta_x) - (C * xb + r1 * K3 * delta_x)) + return (K1 + 2 * K2 + 2 * K3 + K4) / 6 def uniform_random__(self, a, b, size): - a2, b2 = a/2, b/2 + a2, b2 = a / 2, b / 2 mu = a2 + b2 sig = b2 - a2 return mu + sig * (2 * self.generator.uniform(0, 1, size) - 1) @@ -86,15 +87,17 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - f = 20 * np.exp(-(12. * epoch / self.epoch)) # Eq.17.6 - SF = 2.*(0.5 - self.generator.random(self.pop_size)) * f # Eq.17.5 + f = 20 * np.exp(-(12. * epoch / self.epoch)) # Eq.17.6 + SF = 2. * (0.5 - self.generator.random(self.pop_size)) * f # Eq.17.5 x_list = np.array([agent.solution for agent in self.pop]) - x_average = np.mean(x_list, axis=0) # Determine the Average of Solutions + x_average = np.mean(x_list, axis=0) # Determine the Average of Solutions for idx in range(0, self.pop_size): ## Determine Delta X (Eqs. 11.1 to 11.3) - gama = self.generator.random() * (self.pop[idx].solution - self.generator.uniform(0, 1, self.problem.n_dims) * - (self.problem.ub - self.problem.lb)) * np.exp(-4 * epoch / self.epoch) - stp = self.generator.uniform(0, 1, self.problem.n_dims) * ((self.g_best.solution - self.generator.random() * x_average) + gama) + gama = self.generator.random() * ( + self.pop[idx].solution - self.generator.uniform(0, 1, self.problem.n_dims) * + (self.problem.ub - self.problem.lb)) * np.exp(-4 * epoch / self.epoch) + stp = self.generator.uniform(0, 1, self.problem.n_dims) * ( + (self.g_best.solution - self.generator.random() * x_average) + gama) delta_x = 2 * self.generator.uniform(0, 1, self.problem.n_dims) * np.abs(stp) ## Determine Three Random Indices of Solutions a, b, c = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 3, replace=False) @@ -108,9 +111,9 @@ def evolve(self, epoch): SM = self.runge_kutta__(xb, xw, delta_x) local_best = self.get_best_agent(self.pop, self.problem.minmax) L = self.generator.choice(range(0, 2), self.problem.n_dims) - xc = L * self.pop[idx].solution + (1 - L) * self.pop[a].solution # Eq. 17.3 - xm = L * self.g_best.solution + (1 - L) * local_best.solution # Eq. 17.4 - r = self.generator.choice([1, -1], self.problem.n_dims) # An integer number + xc = L * self.pop[idx].solution + (1 - L) * self.pop[a].solution # Eq. 17.3 + xm = L * self.g_best.solution + (1 - L) * local_best.solution # Eq. 17.4 + r = self.generator.choice([1, -1], self.problem.n_dims) # An integer number g = 2 * self.generator.random() mu = 0.5 + 1 * self.generator.uniform(0, 1, self.problem.n_dims) ## Determine New Solution Based on Runge Kutta Method (Eq.18) @@ -124,15 +127,18 @@ def evolve(self, epoch): self.pop[idx].update(solution=pos_new, target=tar_new) ## Enhanced solution quality (ESQ) (Eq. 19) if self.generator.random() < 0.5: - w = self.uniform_random__(0, 2, self.problem.n_dims) * np.exp(-5*self.generator.random() * epoch / self.epoch) # Eq.19-1 + w = self.uniform_random__(0, 2, self.problem.n_dims) * np.exp( + -5 * self.generator.random() * epoch / self.epoch) # Eq.19-1 r = np.floor(self.uniform_random__(-1, 2, 1)) u = 2 * self.generator.random(self.problem.n_dims) a, b, c = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 3, replace=False) - x_ave = (self.pop[a].solution + self.pop[b].solution + self.pop[c].solution) / 3 # Eq.19-2 + x_ave = (self.pop[a].solution + self.pop[b].solution + self.pop[c].solution) / 3 # Eq.19-2 beta = self.generator.random(self.problem.n_dims) - x_new1 = beta * self.g_best.solution + (1 - beta) * x_ave # Eq.19-3 - x_new2_temp1 = x_new1 + r*w * np.abs(self.generator.normal(0, 1, self.problem.n_dims) + (x_new1 - x_ave)) - x_new2_temp2 = x_new1 - x_ave + r*w*np.abs(self.generator.normal(0, 1, self.problem.n_dims) + u * x_new1 - x_ave) + x_new1 = beta * self.g_best.solution + (1 - beta) * x_ave # Eq.19-3 + x_new2_temp1 = x_new1 + r * w * np.abs( + self.generator.normal(0, 1, self.problem.n_dims) + (x_new1 - x_ave)) + x_new2_temp2 = x_new1 - x_ave + r * w * np.abs( + self.generator.normal(0, 1, self.problem.n_dims) + u * x_new1 - x_ave) x_new2 = np.where(w < 1, x_new2_temp1, x_new2_temp2) pos_new2 = self.correct_solution(x_new2) tar_new2 = self.get_target(pos_new2) @@ -141,8 +147,9 @@ def evolve(self, epoch): else: if w[self.generator.integers(0, self.problem.n_dims)] > self.generator.random(): SM = self.runge_kutta__(self.pop[idx].solution, pos_new2, delta_x) - x_new3 = pos_new2 - self.generator.random()*pos_new2 + \ - SF[idx] * (SM + (2 * self.generator.random(self.problem.n_dims)*self.g_best.solution - pos_new2)) # Eq. 20 + x_new3 = pos_new2 - self.generator.random() * pos_new2 + \ + SF[idx] * (SM + (2 * self.generator.random( + self.problem.n_dims) * self.g_best.solution - pos_new2)) # Eq. 20 pos_new3 = self.correct_solution(x_new3) tar_new3 = self.get_target(pos_new3) if self.compare_target(tar_new3, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/math_based/SCA.py b/mealpy/math_based/SCA.py index 8b6d2420..5caa5aac 100644 --- a/mealpy/math_based/SCA.py +++ b/mealpy/math_based/SCA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -65,8 +66,10 @@ def evolve(self, epoch): r2 = 2 * np.pi * self.generator.uniform(0, 1, self.problem.n_dims) r3 = 2 * self.generator.uniform(0, 1, self.problem.n_dims) # Eq. 3.3, 3.1 and 3.2 - pos_new1 = self.pop[idx].solution + r1 * np.sin(r2) * np.abs(r3 * self.g_best.solution - self.pop[idx].solution) - pos_new2 = self.pop[idx].solution + r1 * np.cos(r2) * np.abs(r3 * self.g_best.solution - self.pop[idx].solution) + pos_new1 = self.pop[idx].solution + r1 * np.sin(r2) * np.abs( + r3 * self.g_best.solution - self.pop[idx].solution) + pos_new2 = self.pop[idx].solution + r1 * np.cos(r2) * np.abs( + r3 * self.g_best.solution - self.pop[idx].solution) pos_new = np.where(self.generator.random(self.problem.n_dims) < 0.5, pos_new1, pos_new2) # Check the bound pos_new = self.correct_solution(pos_new) @@ -145,9 +148,11 @@ def evolve(self, epoch): r4 = self.generator.uniform() # Eq. 3.3, 3.1 and 3.2 if r4 < 0.5: - pos_new[jdx] = pos_new[jdx] + r1 * np.sin(r2) * np.abs(r3 * self.g_best.solution[jdx] - pos_new[jdx]) + pos_new[jdx] = pos_new[jdx] + r1 * np.sin(r2) * np.abs( + r3 * self.g_best.solution[jdx] - pos_new[jdx]) else: - pos_new[jdx] = pos_new[jdx] + r1 * np.cos(r2) * np.abs(r3 * self.g_best.solution[jdx] - pos_new[jdx]) + pos_new[jdx] = pos_new[jdx] + r1 * np.cos(r2) * np.abs( + r3 * self.g_best.solution[jdx] - pos_new[jdx]) # Check the bound pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -234,7 +239,8 @@ class QleSCA(DevSCA): algorithm (QLESCA). Expert Systems with Applications, 193, 116417. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.1, gama: float = 0.9, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.1, gama: float = 0.9, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -299,9 +305,11 @@ def evolve(self, epoch): r2 = 2 * np.pi * self.generator.uniform() r4 = self.generator.uniform() if r4 < 0.5: - pos_new = self.pop[idx].solution + r1 * np.sin(r2) * (r3 * self.g_best.solution - self.pop[idx].solution) + pos_new = self.pop[idx].solution + r1 * np.sin(r2) * ( + r3 * self.g_best.solution - self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + r1 * np.cos(r2) * (r3 * self.g_best.solution - self.pop[idx].solution) + pos_new = self.pop[idx].solution + r1 * np.cos(r2) * ( + r3 * self.g_best.solution - self.pop[idx].solution) # Check the bound pos_new = self.correct_solution(pos_new) agent.solution = pos_new diff --git a/mealpy/math_based/SHIO.py b/mealpy/math_based/SHIO.py index e9ab3189..cacaaae5 100644 --- a/mealpy/math_based/SHIO.py +++ b/mealpy/math_based/SHIO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -69,9 +70,12 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): a = a - 0.04 - x1 = b1.solution + (a*2*self.generator.random(self.problem.n_dims) - a)*np.abs(self.generator.random(self.problem.n_dims) * b1.solution - self.pop[idx].solution) - x2 = b2.solution + (a*2*self.generator.random(self.problem.n_dims) - a)*np.abs(self.generator.random(self.problem.n_dims) * b2.solution - self.pop[idx].solution) - x3 = b3.solution + (a*2*self.generator.random(self.problem.n_dims) - a)*np.abs(self.generator.random(self.problem.n_dims) * b3.solution - self.pop[idx].solution) + x1 = b1.solution + (a * 2 * self.generator.random(self.problem.n_dims) - a) * np.abs( + self.generator.random(self.problem.n_dims) * b1.solution - self.pop[idx].solution) + x2 = b2.solution + (a * 2 * self.generator.random(self.problem.n_dims) - a) * np.abs( + self.generator.random(self.problem.n_dims) * b2.solution - self.pop[idx].solution) + x3 = b3.solution + (a * 2 * self.generator.random(self.problem.n_dims) - a) * np.abs( + self.generator.random(self.problem.n_dims) * b3.solution - self.pop[idx].solution) pos_new = (x1 + x2 + x3) / 3 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/math_based/TS.py b/mealpy/math_based/TS.py index 18e1e591..e6abfd57 100644 --- a/mealpy/math_based/TS.py +++ b/mealpy/math_based/TS.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -79,7 +80,8 @@ def evolve(self, epoch): epoch (int): The current iteration """ # Generate candidate solutions by perturbing the current solution - candidates = self.generator.normal(loc=self.x, scale=self.perturbation_scale, size=(self.neighbour_size, self.problem.n_dims)) + candidates = self.generator.normal(loc=self.x, scale=self.perturbation_scale, + size=(self.neighbour_size, self.problem.n_dims)) # Evaluate candidate solutions and select best move list_candidates = [] for candidate in candidates: diff --git a/mealpy/multitask.py b/mealpy/multitask.py index c9c5f6e9..9b4e0d8d 100644 --- a/mealpy/multitask.py +++ b/mealpy/multitask.py @@ -4,15 +4,17 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% +import concurrent.futures as parallel +import os +from copy import deepcopy +from functools import partial +from pathlib import Path from typing import Union, List, Tuple + import pandas as pd -from pathlib import Path + from mealpy.optimizer import Optimizer from mealpy.utils.validator import Validator -from functools import partial -import concurrent.futures as parallel -from copy import deepcopy -import os class Multitask: @@ -80,8 +82,10 @@ class Multitask: >>> multitask.execute(n_trials=5, n_jobs=None, save_path="history", save_as="csv", save_convergence=True, verbose=False) >>> # multitask.execute(n_trials=5, save_path="history", save_as="csv", save_convergence=True, verbose=False) """ + def __init__(self, algorithms: Union[List, Tuple] = None, problems: Union[List, Tuple] = None, - terminations: Union[List, Tuple] = None, modes: Union[List, Tuple] = None, n_workers: int = None, **kwargs: object) -> None: + terminations: Union[List, Tuple] = None, modes: Union[List, Tuple] = None, n_workers: int = None, + **kwargs: object) -> None: self.__set_keyword_arguments(kwargs) self.validator = Validator(log_to="console", log_file=None) self.algorithms = self.validator.check_list_tuple("algorithms", algorithms, "Optimizer") @@ -97,15 +101,18 @@ def check_input(self, name=None, values=None, kind=None): return None elif type(values) in (list, tuple): if len(values) == 1: - values_final = [[deepcopy(values[0]) for _ in range(0, self.m_problems)] for _ in range(0, self.n_algorithms)] + values_final = [[deepcopy(values[0]) for _ in range(0, self.m_problems)] for _ in + range(0, self.n_algorithms)] elif len(values) == self.n_algorithms: - values_final = [deepcopy(values[idx] for _ in range(0, self.m_problems)) for idx in range(0, self.n_algorithms)] + values_final = [deepcopy(values[idx] for _ in range(0, self.m_problems)) for idx in + range(0, self.n_algorithms)] elif len(values) == self.m_problems: values_final = [deepcopy(values) for _ in range(0, self.n_algorithms)] elif len(values) == (self.n_algorithms * self.m_problems): values_final = values else: - raise ValueError(f"{name} should be list of {kind} instances with size (1) or (n) or (m) or (n*m), n: #algorithms, m: #problems.") + raise ValueError( + f"{name} should be list of {kind} instances with size (1) or (n) or (m) or (n*m), n: #algorithms, m: #problems.") return values_final else: raise ValueError(f"{name} should be list of {kind} instances.") @@ -162,7 +169,7 @@ def execute(self, n_trials: int = 2, n_jobs: int = None, save_path: str = "histo for id_optimizer, optimizer in enumerate(self.algorithms): if not isinstance(optimizer, Optimizer): - print(f"Model: {id_optimizer+1} is not an instance of Optimizer class.") + print(f"Model: {id_optimizer + 1} is not an instance of Optimizer class.") continue ## Check parent directories @@ -183,23 +190,27 @@ def execute(self, n_trials: int = 2, n_jobs: int = None, save_path: str = "histo convergence_trials = {} best_fit_trials = [] - trial_list = list(range(1, n_trials+1)) + trial_list = list(range(1, n_trials + 1)) if n_processors is not None: with parallel.ProcessPoolExecutor(n_processors) as executor: - list_results = executor.map(partial(self.__run__, optimizer=optimizer, problem=problem, termination=term, mode=mode), trial_list) + list_results = executor.map( + partial(self.__run__, optimizer=optimizer, problem=problem, termination=term, mode=mode), + trial_list) for result in list_results: convergence_trials[f"trial_{result['id_trial']}"] = result['convergence'] best_fit_trials.append(result['best_fitness']) if verbose: - print(f"Solving problem: {result['problem_name']} using algorithm: {optimizer.get_name()}, on the: {result['id_trial']} trial") + print( + f"Solving problem: {result['problem_name']} using algorithm: {optimizer.get_name()}, on the: {result['id_trial']} trial") else: for idx in trial_list: result = self.__run__(idx, optimizer, problem, termination=term, mode=mode) convergence_trials[f"trial_{result['id_trial']}"] = result['convergence'] best_fit_trials.append(result['best_fitness']) if verbose: - print(f"Solving problem: {result['problem_name']} using algorithm: {optimizer.get_name()}, on the: {result['id_trial']} trial") + print( + f"Solving problem: {result['problem_name']} using algorithm: {optimizer.get_name()}, on the: {result['id_trial']} trial") best_fit_optimizer_results[result['problem_name']] = best_fit_trials if save_convergence: diff --git a/mealpy/music_based/HS.py b/mealpy/music_based/HS.py index 5da9055f..472c364c 100644 --- a/mealpy/music_based/HS.py +++ b/mealpy/music_based/HS.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,7 +44,8 @@ class DevHS(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c_r: float = 0.95, pa_r: float = 0.05, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, c_r: float = 0.95, pa_r: float = 0.05, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -129,7 +131,8 @@ class OriginalHS(DevHS): optimization algorithm: harmony search. simulation, 76(2), pp.60-68. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c_r: float = 0.95, pa_r: float = 0.05, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, c_r: float = 0.95, pa_r: float = 0.05, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -157,8 +160,9 @@ def evolve(self, epoch): # Pitch Adjustment if self.generator.uniform() <= self.pa_r: mean = (self.problem.lb + self.problem.ub) / 2 - std_dev = abs(self.problem.ub - self.problem.lb) / 6 # This assumes a range of +/- 3 standard deviations - delta = self.dyn_fw * self.generator.normal(mean, std_dev) # Gaussian(Normal) + std_dev = abs( + self.problem.ub - self.problem.lb) / 6 # This assumes a range of +/- 3 standard deviations + delta = self.dyn_fw * self.generator.normal(mean, std_dev) # Gaussian(Normal) pos_new[jdx] = pos_new[jdx] + delta[jdx] pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/optimizer.py b/mealpy/optimizer.py index cf03d1de..d86d07fa 100644 --- a/mealpy/optimizer.py +++ b/mealpy/optimizer.py @@ -4,22 +4,24 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from typing import List, Union, Tuple, Dict +import concurrent.futures as parallel +import os import random +import time +from functools import partial +from math import gamma +from typing import List, Union, Tuple, Dict + import numpy as np from tqdm import tqdm + from mealpy.utils.agent import Agent -from mealpy.utils.problem import Problem -from math import gamma from mealpy.utils.history import History +from mealpy.utils.logger import Logger +from mealpy.utils.problem import Problem from mealpy.utils.target import Target from mealpy.utils.termination import Termination -from mealpy.utils.logger import Logger from mealpy.utils.validator import Validator -import concurrent.futures as parallel -from functools import partial -import os -import time class Optimizer: @@ -57,7 +59,7 @@ def __init__(self, **kwargs): self.nfe_counter = 1 # The first one is tested in Problem class self.parameters, self.params_name_ordered = {}, None self.is_parallelizable = True - self.generator, self.rng = None, None # random module for numpy and random (python) + self.generator, self.rng = None, None # random module for numpy and random (python) def __set_keyword_arguments(self, kwargs): for key, value in kwargs.items(): @@ -126,16 +128,19 @@ def before_initialization(self, starting_solutions: Union[List, Tuple, np.ndarra if starting_solutions is None: pass elif type(starting_solutions) in self.SUPPORTED_ARRAYS and len(starting_solutions) == self.pop_size: - if type(starting_solutions[0]) in self.SUPPORTED_ARRAYS and len(starting_solutions[0]) == self.problem.n_dims: + if type(starting_solutions[0]) in self.SUPPORTED_ARRAYS and len( + starting_solutions[0]) == self.problem.n_dims: if self.mode in self.AVAILABLE_MODES: self.pop = [self.generate_empty_agent(solution) for solution in starting_solutions] self.pop = self.update_target_for_population(self.pop) else: self.pop = [self.generate_agent(solution) for solution in starting_solutions] else: - raise ValueError("Invalid starting_solutions. It should be a list of positions or 2D matrix of positions only.") + raise ValueError( + "Invalid starting_solutions. It should be a list of positions or 2D matrix of positions only.") else: - raise ValueError("Invalid starting_solutions. It should be a list/2D matrix of positions with same length as pop_size.") + raise ValueError( + "Invalid starting_solutions. It should be a list/2D matrix of positions with same length as pop_size.") def initialization(self) -> None: if self.pop is None: @@ -166,7 +171,8 @@ def check_problem(self, problem, seed) -> None: raise ValueError("problem needs to be a dict or an instance of Problem class.") self.generator = np.random.default_rng(seed) self.rng = random.Random(seed) # local RNG for random module - self.logger = Logger(self.problem.log_to, log_file=self.problem.log_file).create_logger(name=f"{self.__module__}.{self.__class__.__name__}") + self.logger = Logger(self.problem.log_to, log_file=self.problem.log_file).create_logger( + name=f"{self.__module__}.{self.__class__.__name__}") self.logger.info(self) self.history = History(log_to=self.problem.log_to, log_file=self.problem.log_file) self.pop, self.g_best, self.g_worst = None, None, None @@ -175,7 +181,8 @@ def check_mode_and_workers(self, mode, n_workers): self.mode = self.validator.check_str("mode", mode, self.SUPPORTED_MODES) if self.mode in self.PARALLEL_MODES: if not self.is_parallelizable: - self.logger.warning(f"{self.get_name()} doesn't support parallelization. The default mode 'single' is activated.") + self.logger.warning( + f"{self.get_name()} doesn't support parallelization. The default mode 'single' is activated.") self.mode = "single" elif n_workers is not None: if self.mode == "process": @@ -184,7 +191,8 @@ def check_mode_and_workers(self, mode, n_workers): self.n_workers = self.validator.check_int("n_workers", n_workers, [2, min(32, os.cpu_count() + 4)]) self.logger.info(f"The parallel mode '{self.mode}' is selected with {self.n_workers} workers.") else: - self.logger.warning(f"The parallel mode: {self.mode} is selected. But n_workers is not set. The default n_workers = 4 is used.") + self.logger.warning( + f"The parallel mode: {self.mode} is selected. But n_workers is not set. The default n_workers = 4 is used.") self.n_workers = 4 def check_termination(self, mode="start", termination=None, epoch=None): @@ -194,7 +202,8 @@ def check_termination(self, mode="start", termination=None, epoch=None): if isinstance(termination, Termination): self.termination = termination elif type(termination) == dict: - self.termination = Termination(log_to=self.problem.log_to, log_file=self.problem.log_file, **termination) + self.termination = Termination(log_to=self.problem.log_to, log_file=self.problem.log_file, + **termination) else: raise ValueError("Termination needs to be a dict or an instance of Termination class.") self.nfe_counter = 0 @@ -292,8 +301,9 @@ def track_optimize_step(self, pop: List[Agent] = None, epoch: int = None, runtim div = np.mean(np.abs(np.median(pos_matrix, axis=0) - pos_matrix), axis=0) self.history.list_diversity.append(np.mean(div, axis=0)) ## Print epoch - self.logger.info(f">>>Problem: {self.problem.name}, Epoch: {epoch}, Current best: {self.history.list_current_best[-1].target.fitness}, " - f"Global best: {self.history.list_global_best[-1].target.fitness}, Runtime: {runtime:.5f} seconds") + self.logger.info( + f">>>Problem: {self.problem.name}, Epoch: {epoch}, Current best: {self.history.list_current_best[-1].target.fitness}, " + f"Global best: {self.history.list_global_best[-1].target.fitness}, Runtime: {runtime:.5f} seconds") def track_optimize_process(self) -> None: """ @@ -509,7 +519,8 @@ def get_worst_agent(pop: List[Agent], minmax: str = "min") -> Agent: @staticmethod def get_special_agents(pop: List[Agent] = None, n_best: int = 3, n_worst: int = 3, - minmax: str = "min") -> Tuple[List[Agent], Union[List[Agent], None], Union[List[Agent], None]]: + minmax: str = "min") -> Tuple[ + List[Agent], Union[List[Agent], None], Union[List[Agent], None]]: """ Get special agents include sorted population, n1 best agents, n2 worst agents @@ -535,7 +546,8 @@ def get_special_agents(pop: List[Agent] = None, n_best: int = 3, n_worst: int = return pop, [agent.copy() for agent in pop[:n_best]], [agent.copy() for agent in pop[::-1][:n_worst]] @staticmethod - def get_special_fitness(pop: List[Agent] = None, minmax: str = "min") -> Tuple[Union[float, np.ndarray], float, float]: + def get_special_fitness(pop: List[Agent] = None, minmax: str = "min") -> Tuple[ + Union[float, np.ndarray], float, float]: """ Get special target include the total fitness, the best fitness, and the worst fitness @@ -573,7 +585,8 @@ def get_better_agent(agent_x: Agent, agent_y: Agent, minmax: str = "min", revers ### Survivor Selection @staticmethod - def greedy_selection_population(pop_old: List[Agent] = None, pop_new: List[Agent] = None, minmax: str = "min") -> List[Agent]: + def greedy_selection_population(pop_old: List[Agent] = None, pop_new: List[Agent] = None, minmax: str = "min") -> \ + List[Agent]: """ Args: pop_old: The current population @@ -587,12 +600,15 @@ def greedy_selection_population(pop_old: List[Agent] = None, pop_new: List[Agent if len_old != len_new: raise ValueError("Greedy selection of two population with different length.") if minmax == "min": - return [pop_new[idx] if pop_new[idx].target.fitness < pop_old[idx].target.fitness else pop_old[idx] for idx in range(len_old)] + return [pop_new[idx] if pop_new[idx].target.fitness < pop_old[idx].target.fitness else pop_old[idx] for idx + in range(len_old)] else: - return [pop_new[idx] if pop_new[idx].target.fitness > pop_old[idx].target.fitness else pop_old[idx] for idx in range(len_old)] + return [pop_new[idx] if pop_new[idx].target.fitness > pop_old[idx].target.fitness else pop_old[idx] for idx + in range(len_old)] @staticmethod - def get_sorted_and_trimmed_population(pop: List[Agent] = None, pop_size: int = None, minmax: str = "min") -> List[Agent]: + def get_sorted_and_trimmed_population(pop: List[Agent] = None, pop_size: int = None, minmax: str = "min") -> List[ + Agent]: """ Args: pop: The population @@ -626,7 +642,8 @@ def update_global_best_agent(self, pop: List[Agent], save: bool = True) -> Union self.history.list_global_best.append(better) ## Save current worst self.history.list_current_worst.append(c_worst) - worse = self.get_better_agent(c_worst, self.history.list_global_worst[-1], self.problem.minmax, reverse=True) + worse = self.get_better_agent(c_worst, self.history.list_global_worst[-1], self.problem.minmax, + reverse=True) self.history.list_global_worst.append(worse) return sorted_pop, better else: @@ -636,9 +653,11 @@ def update_global_best_agent(self, pop: List[Agent], save: bool = True) -> Union global_better = self.get_better_agent(c_best, self.history.list_global_best[-1], self.problem.minmax) self.history.list_global_best[-1] = global_better ## Handle current worst - local_worst = self.get_better_agent(c_worst, self.history.list_current_worst[-1], self.problem.minmax, reverse=True) + local_worst = self.get_better_agent(c_worst, self.history.list_current_worst[-1], self.problem.minmax, + reverse=True) self.history.list_current_worst[-1] = local_worst - global_worst = self.get_better_agent(c_worst, self.history.list_global_worst[-1], self.problem.minmax, reverse=True) + global_worst = self.get_better_agent(c_worst, self.history.list_global_worst[-1], self.problem.minmax, + reverse=True) self.history.list_global_worst[-1] = global_worst return sorted_pop, global_better @@ -665,7 +684,8 @@ def get_index_roulette_wheel_selection(self, list_fitness: np.array): prob = final_fitness / np.sum(final_fitness) return int(self.generator.choice(range(0, len(list_fitness)), p=prob)) - def get_index_kway_tournament_selection(self, pop: List = None, k_way: float = 0.2, output: int = 2, reverse: bool = False) -> List: + def get_index_kway_tournament_selection(self, pop: List = None, k_way: float = 0.2, output: int = 2, + reverse: bool = False) -> List: """ Args: pop: The population @@ -688,8 +708,9 @@ def get_index_kway_tournament_selection(self, pop: List = None, k_way: float = 0 return [parent[0] for parent in list_parents[-output:]] return [parent[0] for parent in list_parents[:output]] - def get_levy_flight_step(self, beta: float = 1.0, multiplier: float = 0.001, - size: Union[List, Tuple, np.ndarray] = None, case: int = 0) -> Union[float, List, np.ndarray]: + def get_levy_flight_step(self, beta: float = 1.0, multiplier: float = 0.001, + size: Union[List, Tuple, np.ndarray] = None, case: int = 0) -> Union[ + float, List, np.ndarray]: """ Get the Levy-flight step size @@ -712,7 +733,8 @@ def get_levy_flight_step(self, beta: float = 1.0, multiplier: float = 0.001, """ # u and v are two random variables which follow self.generator.normal distribution # sigma_u : standard deviation of u - sigma_u = np.power(gamma(1. + beta) * np.sin(np.pi * beta / 2) / (gamma((1 + beta) / 2.) * beta * np.power(2., (beta - 1) / 2)), 1. / beta) + sigma_u = np.power(gamma(1. + beta) * np.sin(np.pi * beta / 2) / ( + gamma((1 + beta) / 2.) * beta * np.power(2., (beta - 1) / 2)), 1. / beta) # sigma_v : standard deviation of v sigma_v = 1 size = 1 if size is None else size @@ -736,7 +758,8 @@ def generate_opposition_solution(self, agent: Agent = None, g_best: Agent = None Returns: The opposite solution """ - pos_new = self.problem.lb + self.problem.ub - g_best.solution + self.generator.uniform() * (g_best.solution - agent.solution) + pos_new = self.problem.lb + self.problem.ub - g_best.solution + self.generator.uniform() * ( + g_best.solution - agent.solution) return self.correct_solution(pos_new) def generate_group_population(self, pop: List[Agent], n_groups: int, m_agents: int) -> List: @@ -793,7 +816,8 @@ def improved_ms(self, pop=None, g_best=None): ## m: mutation, s: search agent.solution = self.correct_solution(pos_new) pop_new.append(agent) pop_new = self.update_target_for_population(pop_new) - pop_s1 = self.greedy_selection_population(pop_s1, pop_new, self.problem.minmax) ## Greedy method --> improved exploitation + pop_s1 = self.greedy_selection_population(pop_s1, pop_new, + self.problem.minmax) ## Greedy method --> improved exploitation ## Search Mechanism pos_s1_list = [agent.solution for agent in pop_s1] diff --git a/mealpy/physics_based/ASO.py b/mealpy/physics_based/ASO.py index a54d7faa..a789dd55 100644 --- a/mealpy/physics_based/ASO.py +++ b/mealpy/physics_based/ASO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -46,7 +47,8 @@ class OriginalASO(Optimizer): hydrogeologic parameter estimation problem. Knowledge-Based Systems, 163, pp.283-304. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: int = 10, beta: float = 0.2, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: int = 10, beta: float = 0.2, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -115,7 +117,8 @@ def acceleration__(self, population, g_best, iteration): # calculate LJ-potential radius = np.linalg.norm(pop[idx].solution - atom.solution) potential = self.find_LJ_potential__(iteration, dist_average, radius) - temp += potential * self.generator.uniform(0, 1, self.problem.n_dims) * ((atom.solution - pop[idx].solution) / (radius + eps)) + temp += potential * self.generator.uniform(0, 1, self.problem.n_dims) * ( + (atom.solution - pop[idx].solution) / (radius + eps)) temp = self.alpha * temp + self.beta * (g_best.solution - pop[idx].solution) # calculate acceleration acc = G * temp / pop[idx].mass diff --git a/mealpy/physics_based/ArchOA.py b/mealpy/physics_based/ArchOA.py index 9b19fe23..3a53faf6 100644 --- a/mealpy/physics_based/ArchOA.py +++ b/mealpy/physics_based/ArchOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -77,9 +78,10 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 2, c2: f def generate_empty_agent(self, solution: np.ndarray = None) -> Agent: if solution is None: solution = self.problem.generate_solution(encoded=True) - den = self.generator.uniform(self.problem.lb, self.problem.ub) # Density - vol = self.generator.uniform(self.problem.lb, self.problem.ub) # Volume - acc = self.problem.lb + self.generator.uniform(self.problem.lb, self.problem.ub) * (self.problem.ub - self.problem.lb) # Acceleration + den = self.generator.uniform(self.problem.lb, self.problem.ub) # Density + vol = self.generator.uniform(self.problem.lb, self.problem.ub) # Volume + acc = self.problem.lb + self.generator.uniform(self.problem.lb, self.problem.ub) * ( + self.problem.ub - self.problem.lb) # Acceleration return Agent(solution=solution, den=den, vol=vol, acc=acc) def evolve(self, epoch): @@ -113,7 +115,8 @@ def evolve(self, epoch): max_acc = np.max(list_acc) ## Normalize acceleration using Eq. 12 for idx in range(0, self.pop_size): - self.pop[idx].acc = self.acc_max * (list_acc[idx] - min_acc) / (max_acc - min_acc + self.EPSILON) + self.acc_min + self.pop[idx].acc = self.acc_max * (list_acc[idx] - min_acc) / ( + max_acc - min_acc + self.EPSILON) + self.acc_min pop_new = [] for idx in range(0, self.pop_size): agent = self.pop[idx].copy() diff --git a/mealpy/physics_based/CDO.py b/mealpy/physics_based/CDO.py index b5c26bea..1795b77e 100644 --- a/mealpy/physics_based/CDO.py +++ b/mealpy/physics_based/CDO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -61,17 +62,17 @@ def evolve(self, epoch): epoch (int): The current iteration """ _, (b1, b2, b3), _ = self.get_special_agents(self.pop, n_best=3, n_worst=1, minmax=self.problem.minmax) - a = 3. - 3.*epoch/self.epoch - a1 = np.log10((16000-1) * self.generator.random() + 16000) - a2 = np.log10((270000-1) * self.generator.random() + 270000) - a3 = np.log10((300000-1) * self.generator.random() + 300000) + a = 3. - 3. * epoch / self.epoch + a1 = np.log10((16000 - 1) * self.generator.random() + 16000) + a2 = np.log10((270000 - 1) * self.generator.random() + 270000) + a3 = np.log10((300000 - 1) * self.generator.random() + 300000) pop_new = [] for idx in range(0, self.pop_size): r1 = self.generator.random(self.problem.n_dims) r2 = self.generator.random(self.problem.n_dims) - pa = np.pi * r1*r1 / (0.25 * a1) - a * self.generator.random(self.problem.n_dims) + pa = np.pi * r1 * r1 / (0.25 * a1) - a * self.generator.random(self.problem.n_dims) c1 = r2 * r2 * np.pi - alpha = np.abs(c1*b1.solution - self.pop[idx].solution) + alpha = np.abs(c1 * b1.solution - self.pop[idx].solution) pos_a = 0.25 * (b1.solution - pa * alpha) r3 = self.generator.random(self.problem.n_dims) diff --git a/mealpy/physics_based/EFO.py b/mealpy/physics_based/EFO.py index 46f346e6..545109d3 100644 --- a/mealpy/physics_based/EFO.py +++ b/mealpy/physics_based/EFO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -71,9 +72,11 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): r_idx1 = self.generator.integers(0, int(self.pop_size * self.p_field)) # top r_idx2 = self.generator.integers(int(self.pop_size * (1 - self.n_field)), self.pop_size) # bottom - r_idx3 = self.generator.integers(int((self.pop_size * self.p_field) + 1), int(self.pop_size * (1 - self.n_field))) # middle + r_idx3 = self.generator.integers(int((self.pop_size * self.p_field) + 1), + int(self.pop_size * (1 - self.n_field))) # middle if self.generator.random() < self.ps_rate: - pos_new = self.pop[r_idx1].solution + self.phi * self.generator.random() * (self.g_best.solution - self.pop[r_idx3].solution) \ + pos_new = self.pop[r_idx1].solution + self.phi * self.generator.random() * ( + self.g_best.solution - self.pop[r_idx3].solution) \ + self.generator.random() * (self.g_best.solution - self.pop[r_idx2].solution) else: pos_new = self.problem.generate_solution() @@ -81,7 +84,8 @@ def evolve(self, epoch): # (only for some generated particles) to bring diversity to the population if self.generator.random() < self.r_rate: RI = self.generator.integers(0, self.problem.n_dims) - pos_new[self.generator.integers(0, self.problem.n_dims)] = self.generator.uniform(self.problem.lb[RI], self.problem.ub[RI]) + pos_new[self.generator.integers(0, self.problem.n_dims)] = self.generator.uniform(self.problem.lb[RI], + self.problem.ub[RI]) # checking whether the generated number is inside boundary or not pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -159,9 +163,12 @@ def initialization(self): # iteration we allocate them in the beginning before algorithm start self.r_index1 = self.generator.integers(0, int(self.pop_size * self.p_field), (self.problem.n_dims, self.epoch)) # random particles from positive field - self.r_index2 = self.generator.integers(int(self.pop_size * (1 - self.n_field)), self.pop_size, (self.problem.n_dims, self.epoch)) + self.r_index2 = self.generator.integers(int(self.pop_size * (1 - self.n_field)), self.pop_size, + (self.problem.n_dims, self.epoch)) # random particles from negative field - self.r_index3 = self.generator.integers(int((self.pop_size * self.p_field) + 1), int(self.pop_size * (1 - self.n_field)), (self.problem.n_dims, self.epoch)) + self.r_index3 = self.generator.integers(int((self.pop_size * self.p_field) + 1), + int(self.pop_size * (1 - self.n_field)), + (self.problem.n_dims, self.epoch)) # random particles from neutral field self.ps = self.generator.uniform(0, 1, (self.problem.n_dims, self.epoch)) # Probability of selecting electromagnets of generated particle from the positive field @@ -181,19 +188,22 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - iter01 = epoch-1 + iter01 = epoch - 1 r = self.r_force[iter01] x_new = np.zeros(self.problem.n_dims) # temporary array to store generated particle for idx in range(0, self.problem.n_dims): if self.ps[idx, iter01] > self.ps_rate: x_new[idx] = self.pop[self.r_index3[idx, iter01]].solution[idx] + \ - self.phi * r * (self.pop[self.r_index1[idx, iter01]].solution[idx] - self.pop[self.r_index3[idx, iter01]].solution[idx]) + \ - r * (self.pop[self.r_index3[idx, iter01]].solution[idx] - self.pop[self.r_index2[idx, iter01]].solution[idx]) + self.phi * r * (self.pop[self.r_index1[idx, iter01]].solution[idx] - + self.pop[self.r_index3[idx, iter01]].solution[idx]) + \ + r * (self.pop[self.r_index3[idx, iter01]].solution[idx] - + self.pop[self.r_index2[idx, iter01]].solution[idx]) else: x_new[idx] = self.pop[self.r_index1[idx, iter01]].solution[idx] # replacement of one electromagnet of generated particle with a random number (only for some generated particles) to bring diversity to the population if self.rp[iter01] < self.r_rate: - x_new[self.RI] = self.problem.lb[self.RI] + (self.problem.ub[self.RI] - self.problem.lb[self.RI]) * self.randomization[iter01] + x_new[self.RI] = self.problem.lb[self.RI] + (self.problem.ub[self.RI] - self.problem.lb[self.RI]) * \ + self.randomization[iter01] RI = self.RI + 1 if RI >= self.problem.n_dims: self.RI = 0 diff --git a/mealpy/physics_based/EO.py b/mealpy/physics_based/EO.py index b1cd05b3..b324246a 100644 --- a/mealpy/physics_based/EO.py +++ b/mealpy/physics_based/EO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -82,7 +83,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): lamda = self.generator.uniform(0, 1, self.problem.n_dims) # lambda in Eq. 11 r = self.generator.uniform(0, 1, self.problem.n_dims) # r in Eq. 11 - c_eq = c_pool[self.generator.integers(0, len(c_pool))].solution # random selection 1 of candidate from the pool + c_eq = c_pool[ + self.generator.integers(0, len(c_pool))].solution # random selection 1 of candidate from the pool f = self.a1 * np.sign(r - 0.5) * (np.exp(-lamda * t) - 1.0) # Eq. 11 r1 = self.generator.uniform() r2 = self.generator.uniform() # r1, r2 in Eq. 15 @@ -159,7 +161,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): lamda = self.generator.uniform(0, 1, self.problem.n_dims) # lambda in Eq. 11 r = self.generator.uniform(0, 1, self.problem.n_dims) # r in Eq. 11 - c_eq = c_pool[self.generator.integers(0, len(c_pool))].solution # random selection 1 of candidate from the pool + c_eq = c_pool[ + self.generator.integers(0, len(c_pool))].solution # random selection 1 of candidate from the pool f = self.a1 * np.sign(r - 0.5) * (np.exp(-lamda * t) - 1.0) # Eq. 11 r1 = self.generator.uniform() r2 = self.generator.uniform() # r1, r2 in Eq. 15 @@ -275,7 +278,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): lamda = self.generator.uniform(0, 1, self.problem.n_dims) r = self.generator.uniform(0, 1, self.problem.n_dims) - c_eq = c_pool[self.generator.integers(0, len(c_pool))].solution # random selection 1 of candidate from the pool + c_eq = c_pool[ + self.generator.integers(0, len(c_pool))].solution # random selection 1 of candidate from the pool f = self.a1 * np.sign(r - 0.5) * (np.exp(-lamda * t) - 1.0) # Eq. 14 r1 = self.generator.uniform() r2 = self.generator.uniform() diff --git a/mealpy/physics_based/ESO.py b/mealpy/physics_based/ESO.py index dcd8c813..3e88b9ff 100644 --- a/mealpy/physics_based/ESO.py +++ b/mealpy/physics_based/ESO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -60,7 +61,7 @@ def evolve(self, epoch): # Calculate field resistance based on population spread pos_pop = np.array([agent.solution for agent in self.pop]) mean_pos = np.mean(pos_pop, axis=0) - std_pos = np.sqrt(np.mean(np.sum((pos_pop - mean_pos)**2, axis=1))) + std_pos = np.sqrt(np.mean(np.sum((pos_pop - mean_pos) ** 2, axis=1))) # std_pos = np.std(pos_pop, axis=0) peak_to_peak = np.max(np.max(pos_pop, axis=0) - np.min(pos_pop, axis=0)) # Field resistance @@ -146,7 +147,8 @@ def evolve(self, epoch): # Average position of ionized areas avg_ionized = np.mean([agent.solution for agent in ionized_pop], axis=0) # Random perturbation - pos_new = avg_ionized + storm_power * np.exp(fc) * self.generator.uniform(-fc, fc, self.problem.n_dims) + pos_new = avg_ionized + storm_power * np.exp(fc) * self.generator.uniform(-fc, fc, + self.problem.n_dims) else: # Random search pos_new = self.generator.uniform(self.problem.lb, self.problem.ub, self.problem.n_dims) diff --git a/mealpy/physics_based/EVO.py b/mealpy/physics_based/EVO.py index 25a37a2e..48d8943b 100644 --- a/mealpy/physics_based/EVO.py +++ b/mealpy/physics_based/EVO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,6 +46,7 @@ class OriginalEVO(Optimizer): [1] Azizi, M., Aickelin, U., A. Khorshidi, H., & Baghalzadeh Shishehgarkhaneh, M. (2023). Energy valley optimizer: a novel metaheuristic algorithm for global and engineering optimization. Scientific Reports, 13(1), 226. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -68,14 +70,15 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): pos_list = np.array([agent.solution for agent in self.pop]) fit_list = np.array([agent.target.fitness for agent in self.pop]) - dis = np.sqrt(np.sum((self.pop[idx].solution - pos_list)**2, axis=1)) + dis = np.sqrt(np.sum((self.pop[idx].solution - pos_list) ** 2, axis=1)) idx_dis_sort = np.argsort(dis) CnPtIdx = self.generator.choice(list(set(range(2, self.pop_size)) - {idx})) x_team = pos_list[idx_dis_sort[1:CnPtIdx], :] x_avg_team = np.mean(x_team, axis=0) x_avg_pop = np.mean(pos_list, axis=0) eb = np.mean(fit_list) - sl = (fit_list[idx] - self.g_best.target.fitness) / (self.g_worst.target.fitness - self.g_best.target.fitness + self.EPSILON) + sl = (fit_list[idx] - self.g_best.target.fitness) / ( + self.g_worst.target.fitness - self.g_best.target.fitness + self.EPSILON) pos_new1 = self.pop[idx].solution.copy() pos_new2 = self.pop[idx].solution.copy() @@ -101,7 +104,9 @@ def evolve(self, epoch): pop_new.append(agent1) pop_new.append(agent2) else: - pos_new = pos_new1 + self.generator.random() * sl * self.generator.uniform(self.problem.lb, self.problem.ub, self.problem.n_dims) + pos_new = pos_new1 + self.generator.random() * sl * self.generator.uniform(self.problem.lb, + self.problem.ub, + self.problem.n_dims) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/physics_based/FLA.py b/mealpy/physics_based/FLA.py index f4d26c53..925161fb 100644 --- a/mealpy/physics_based/FLA.py +++ b/mealpy/physics_based/FLA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -50,6 +51,7 @@ class OriginalFLA(Optimizer): [1] Hashim, F. A., Mostafa, R. R., Hussien, A. G., Mirjalili, S., & Sallam, K. M. (2023). Fick’s Law Algorithm: A physical law-based algorithm for numerical optimization. Knowledge-Based Systems, 260, 110146. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, C1: float = 0.5, C2: float = 2.0, C3: float = 0.1, C4: float = 0.2, C5: float = 2.0, DD: float = 0.01, **kwargs: object) -> None: """ @@ -78,7 +80,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, C1: float = 0.5, C2: def before_main_loop(self): self.xss = self.get_sorted_population(self.pop, self.problem.minmax) self.g_best = self.xss[0].copy() - self.n1 = int(np.round(self.pop_size/2)) + self.n1 = int(np.round(self.pop_size / 2)) self.n2 = self.pop_size - self.n1 self.pop1 = self.pop[:self.n1].copy() self.pop2 = self.pop[self.n1:].copy() @@ -102,30 +104,34 @@ def evolve(self, epoch): xm1 = np.mean(pos1_list, axis=0) xm2 = np.mean(pos2_list, axis=0) xm = np.mean(pos_list, axis=0) - tf = np.sinh(epoch/ self.epoch)**self.C1 + tf = np.sinh(epoch / self.epoch) ** self.C1 pop_new = [] if tf < 0.9: - dof = np.exp(-(self.C2 * tf - self.generator.random()))**self.C2 + dof = np.exp(-(self.C2 * tf - self.generator.random())) ** self.C2 tdo = self.C5 * tf - self.generator.random() if tdo < self.generator.random(): - m1n, m2n = self.C3*self.n1, self.C4*self.n1 - nt12 = int(np.round((m2n - m1n)*self.generator.random() + m1n)) + m1n, m2n = self.C3 * self.n1, self.C4 * self.n1 + nt12 = int(np.round((m2n - m1n) * self.generator.random() + m1n)) for idx in range(0, nt12): dfg = self.generator.integers(1, 3) - jj = -self.DD * (xm2 - xm1) / (np.linalg.norm(self.best2.solution - self.pop1[idx].solution) + self.EPSILON) - pos_new = self.best2.solution + dfg*dof*self.generator.random(self.problem.n_dims)*(jj*self.best2.solution - self.pop1[idx].solution) + jj = -self.DD * (xm2 - xm1) / ( + np.linalg.norm(self.best2.solution - self.pop1[idx].solution) + self.EPSILON) + pos_new = self.best2.solution + dfg * dof * self.generator.random(self.problem.n_dims) * ( + jj * self.best2.solution - self.pop1[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) for idx in range(nt12, self.n1): - tt = self.pop1[idx].solution + dof * (self.generator.random(self.problem.n_dims) * (self.problem.ub - self.problem.lb) + self.problem.lb) + tt = self.pop1[idx].solution + dof * (self.generator.random(self.problem.n_dims) * ( + self.problem.ub - self.problem.lb) + self.problem.lb) pp = self.generator.random(self.problem.n_dims) pos_new = np.where(pp < 0.8, self.best1.solution, np.where(pp >= 0.9, self.pop1[idx].solution, tt)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) for idx in range(0, self.n2): - pos_new = self.best2.solution + dof * (self.generator.random(self.problem.n_dims) * (self.problem.ub - self.problem.lb) + self.problem.lb) + pos_new = self.best2.solution + dof * (self.generator.random(self.problem.n_dims) * ( + self.problem.ub - self.problem.lb) + self.problem.lb) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -134,24 +140,28 @@ def evolve(self, epoch): nt12 = int(np.round((m2n - m1n) * self.generator.random() + m1n)) for idx in range(0, nt12): dfg = self.generator.integers(1, 3) - jj = -self.DD*(xm1-xm2) / (np.linalg.norm(self.best1.solution - self.pop2[idx].solution) + self.EPSILON) - pos_new = self.best1.solution + dfg * dof * self.generator.random(self.problem.n_dims) * (jj * self.best1.solution - self.pop2[idx].solution) + jj = -self.DD * (xm1 - xm2) / ( + np.linalg.norm(self.best1.solution - self.pop2[idx].solution) + self.EPSILON) + pos_new = self.best1.solution + dfg * dof * self.generator.random(self.problem.n_dims) * ( + jj * self.best1.solution - self.pop2[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) for idx in range(nt12, self.n2): - tt = self.pop2[idx].solution + dof * (self.generator.random(self.problem.n_dims) * (self.problem.ub - self.problem.lb) + self.problem.lb) + tt = self.pop2[idx].solution + dof * (self.generator.random(self.problem.n_dims) * ( + self.problem.ub - self.problem.lb) + self.problem.lb) pp = self.generator.random(self.problem.n_dims) pos_new = np.where(pp < 0.8, self.best2.solution, np.where(pp >= 0.9, self.pop2[idx].solution, tt)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) for idx in range(0, self.n1): - pos_new = self.best1.solution + dof * (self.generator.random(self.problem.n_dims) * (self.problem.ub - self.problem.lb) + self.problem.lb) + pos_new = self.best1.solution + dof * (self.generator.random(self.problem.n_dims) * ( + self.problem.ub - self.problem.lb) + self.problem.lb) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) - else: # Equilibrium operator (EO) + else: # Equilibrium operator (EO) if tf <= 1: for idx in range(0, self.n1): dfg = self.generator.integers(1, 3) @@ -159,11 +169,12 @@ def evolve(self, epoch): if tttt == 0: jj = 0 else: - jj = -self.DD*(self.best1.solution - xm1) / tttt + jj = -self.DD * (self.best1.solution - xm1) / tttt drf = np.exp(-jj / tf) ms = np.exp(-self.best1.target.fitness / (self.pop1[idx].target.fitness + self.EPSILON)) qeo = dfg * drf * self.generator.random(self.problem.n_dims) - pos_new = self.best1.solution + qeo*self.pop1[idx].solution + qeo *(ms * self.best1.solution - self.pop1[idx].solution) + pos_new = self.best1.solution + qeo * self.pop1[idx].solution + qeo * ( + ms * self.best1.solution - self.pop1[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -177,11 +188,12 @@ def evolve(self, epoch): drf = np.exp(-jj / tf) ms = np.exp(-self.best2.target.fitness / (self.pop2[idx].target.fitness + self.EPSILON)) qeo = dfg * drf * self.generator.random(self.problem.n_dims) - pos_new = self.best2.solution + qeo * self.pop2[idx].solution + qeo * (ms * self.best2.solution - self.pop2[idx].solution) + pos_new = self.best2.solution + qeo * self.pop2[idx].solution + qeo * ( + ms * self.best2.solution - self.pop2[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) - else: # Steady state operator (SSO) + else: # Steady state operator (SSO) for idx in range(0, self.n1): dfg = self.generator.integers(1, 3) tttt = np.linalg.norm(self.g_best.solution - self.pop1[idx].solution) @@ -192,7 +204,8 @@ def evolve(self, epoch): drf = np.exp(-jj / tf) ms = np.exp(-self.fsss / (self.pop1[idx].target.fitness + self.EPSILON)) qg = dfg * drf * self.generator.random(self.problem.n_dims) - pos_new = self.g_best.solution + qg * self.pop1[idx].solution + qg * (ms * self.best1.solution - self.pop1[idx].solution) + pos_new = self.g_best.solution + qg * self.pop1[idx].solution + qg * ( + ms * self.best1.solution - self.pop1[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -206,7 +219,8 @@ def evolve(self, epoch): drf = np.exp(-jj / tf) ms = np.exp(-self.fsss / (self.pop2[idx].target.fitness + self.EPSILON)) qg = dfg * drf * self.generator.random(self.problem.n_dims) - pos_new = self.g_best.solution + qg * self.pop2[idx].solution + qg * (ms * self.g_best.solution - self.pop2[idx].solution) + pos_new = self.g_best.solution + qg * self.pop2[idx].solution + qg * ( + ms * self.g_best.solution - self.pop2[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/physics_based/HGSO.py b/mealpy/physics_based/HGSO.py index e57bea30..3ba0d797 100644 --- a/mealpy/physics_based/HGSO.py +++ b/mealpy/physics_based/HGSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -53,7 +54,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_clusters: int = 2, super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) - self.n_clusters = self.validator.check_int("n_clusters", n_clusters, [2, int(self.pop_size/5)]) + self.n_clusters = self.validator.check_int("n_clusters", n_clusters, [2, int(self.pop_size / 5)]) self.set_parameters(["epoch", "pop_size", "n_clusters"]) self.n_elements = int(self.pop_size / self.n_clusters) self.sort_flag = False @@ -107,9 +108,12 @@ def evolve(self, epoch): ##### Based on Eq. 8, 9, 10 self.H_j = self.H_j * np.exp(-self.C_j * (1.0 / np.exp(-epoch / self.epoch) - 1.0 / self.T0)) S_ij = self.K * self.H_j * self.P_ij - gama = self.beta * np.exp(- ((self.p_best[idx].target.fitness + self.epsilon) / (self.pop_group[idx][jdx].target.fitness + self.epsilon))) - pos_new = self.pop_group[idx][jdx].solution + F * self.generator.uniform() * gama * (self.p_best[idx].solution - self.pop_group[idx][jdx].solution) + \ - F * self.generator.uniform() * self.alpha * (S_ij * self.g_best.solution - self.pop_group[idx][jdx].solution) + gama = self.beta * np.exp(- ((self.p_best[idx].target.fitness + self.epsilon) / ( + self.pop_group[idx][jdx].target.fitness + self.epsilon))) + pos_new = self.pop_group[idx][jdx].solution + F * self.generator.uniform() * gama * ( + self.p_best[idx].solution - self.pop_group[idx][jdx].solution) + \ + F * self.generator.uniform() * self.alpha * ( + S_ij * self.g_best.solution - self.pop_group[idx][jdx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/physics_based/MSO.py b/mealpy/physics_based/MSO.py index 157707bb..8c9c2358 100644 --- a/mealpy/physics_based/MSO.py +++ b/mealpy/physics_based/MSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -142,12 +143,15 @@ def evolve(self, epoch): hh = self.g_best.solution - self.pop[idx].solution zf = np.sign(hh) hh = np.abs(hh * self.generator.random(self.problem.n_dims)) - gama = self.generator.random(self.problem.n_dims) * 90 * ((self.epoch - self.nfe_counter * 0.99) / self.epoch) + gama = self.generator.random(self.problem.n_dims) * 90 * ( + (self.epoch - self.nfe_counter * 0.99) / self.epoch) amax = self.atand(1.0 / (2 * self.tand(gama))) amin = self.atand((self.sind(gama) * self.cosd(gama)) / (1 + (self.sind(gama)) ** 2)) fai = (amax - amin) * self.generator.random() + amin omg = self.asind(self.generator.random() * self.sind(fai + gama)) - x = (hh / self.tand(gama)) - (((hh / self.sind(gama)) - (hh * self.sind(fai)) / (self.cosd(fai + gama))) * self.cosd(omg)) / self.cosd(omg - gama) + x = (hh / self.tand(gama)) - ( + ((hh / self.sind(gama)) - (hh * self.sind(fai)) / (self.cosd(fai + gama))) * self.cosd( + omg)) / self.cosd(omg - gama) pos_new = self.pop[idx].solution + x * zf pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) diff --git a/mealpy/physics_based/MVO.py b/mealpy/physics_based/MVO.py index ab1a5a62..fb49a549 100644 --- a/mealpy/physics_based/MVO.py +++ b/mealpy/physics_based/MVO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -40,7 +41,8 @@ class DevMVO(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, wep_min: float = 0.2, wep_max: float = 1.0, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, wep_min: float = 0.2, wep_max: float = 1.0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -74,8 +76,10 @@ def evolve(self, epoch): white_hole_id = self.get_index_roulette_wheel_selection(list_fitness) black_hole_pos_1 = self.pop[idx].solution + tdr * self.generator.normal(0, 1) * \ (self.pop[white_hole_id].solution - self.pop[idx].solution) - black_hole_pos_2 = self.g_best.solution + tdr * self.generator.normal(0, 1) * (self.g_best.solution - self.pop[idx].solution) - black_hole_pos = np.where(self.generator.random(self.problem.n_dims) < 0.5, black_hole_pos_1, black_hole_pos_2) + black_hole_pos_2 = self.g_best.solution + tdr * self.generator.normal(0, 1) * ( + self.g_best.solution - self.pop[idx].solution) + black_hole_pos = np.where(self.generator.random(self.problem.n_dims) < 0.5, black_hole_pos_1, + black_hole_pos_2) else: black_hole_pos = self.problem.generate_solution() pos_new = self.correct_solution(black_hole_pos) @@ -126,7 +130,8 @@ class OriginalMVO(DevMVO): algorithm for global optimization. Neural Computing and Applications, 27(2), pp.495-513. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, wep_min: float = 0.2, wep_max: float = 1.0, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, wep_min: float = 0.2, wep_max: float = 1.0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -178,7 +183,8 @@ def evolve(self, epoch): list_fitness_normalized = self.generator.uniform(0, 0.1, self.pop_size) else: ### Normalize inflation rates (NI in Eq. (3.1) in the paper) - list_fitness_normalized = np.reshape(self.normalize__(np.array([list_fitness_raw])), self.pop_size) # Matrix + list_fitness_normalized = np.reshape(self.normalize__(np.array([list_fitness_raw])), + self.pop_size) # Matrix pop_new = [] for idx in range(0, self.pop_size): black_hole_pos = self.pop[idx].solution.copy() @@ -195,9 +201,11 @@ def evolve(self, epoch): if r2 < wep: r3 = self.generator.uniform() if r3 < 0.5: - black_hole_pos[jdx] = self.g_best.solution[jdx] + tdr * self.generator.uniform(self.problem.lb[jdx], self.problem.ub[jdx]) + black_hole_pos[jdx] = self.g_best.solution[jdx] + tdr * self.generator.uniform( + self.problem.lb[jdx], self.problem.ub[jdx]) else: - black_hole_pos[jdx] = self.g_best.solution[jdx] - tdr * self.generator.uniform(self.problem.lb[jdx], self.problem.ub[jdx]) + black_hole_pos[jdx] = self.g_best.solution[jdx] - tdr * self.generator.uniform( + self.problem.lb[jdx], self.problem.ub[jdx]) pos_new = self.correct_solution(black_hole_pos) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/physics_based/NRO.py b/mealpy/physics_based/NRO.py index c5caa636..627d9c4b 100644 --- a/mealpy/physics_based/NRO.py +++ b/mealpy/physics_based/NRO.py @@ -4,8 +4,10 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np import math + +import numpy as np + from mealpy.optimizer import Optimizer @@ -69,8 +71,10 @@ def evolve(self, epoch): epoch (int): The current iteration """ xichma_v = 1 - xichma_u = ((math.gamma(1 + 1.5) * math.sin(math.pi * 1.5 / 2)) / (math.gamma((1 + 1.5) / 2) * 1.5 * 2 ** ((1.5 - 1) / 2))) ** (1.0 / 1.5) - levy_b = (self.generator.normal(0, xichma_u)) / (np.sqrt(np.abs(self.generator.normal(0, xichma_v))) ** (1.0 / 1.5)) + xichma_u = ((math.gamma(1 + 1.5) * math.sin(math.pi * 1.5 / 2)) / ( + math.gamma((1 + 1.5) / 2) * 1.5 * 2 ** ((1.5 - 1) / 2))) ** (1.0 / 1.5) + levy_b = (self.generator.normal(0, xichma_u)) / ( + np.sqrt(np.abs(self.generator.normal(0, xichma_v))) ** (1.0 / 1.5)) # NFi phase Pb = self.generator.uniform() Pfi = self.generator.uniform() @@ -87,20 +91,28 @@ def evolve(self, epoch): if self.generator.uniform() <= Pfi: ### Update based on Eq. 3 if self.generator.uniform() <= Pb: - xichma1 = (np.log(epoch) * 1.0 / epoch) * np.abs(np.subtract(self.pop[idx].solution, self.g_best.solution)) - gauss = np.array([self.generator.normal(self.g_best.solution[j], xichma1[j]) for j in range(self.problem.n_dims)]) - Xi = gauss + self.generator.uniform() * self.g_best.solution - round(self.generator.random() + 1) * Nei + xichma1 = (np.log(epoch) * 1.0 / epoch) * np.abs( + np.subtract(self.pop[idx].solution, self.g_best.solution)) + gauss = np.array([self.generator.normal(self.g_best.solution[j], xichma1[j]) for j in + range(self.problem.n_dims)]) + Xi = gauss + self.generator.uniform() * self.g_best.solution - round( + self.generator.random() + 1) * Nei ### Update based on Eq. 6 else: i2 = self.generator.choice(temp1, replace=False) - xichma2 = (np.log(epoch) * 1.0 / epoch) * np.abs(np.subtract(self.pop[i2].solution, self.g_best.solution)) - gauss = np.array([self.generator.normal(self.pop[idx].solution[j], xichma2[j]) for j in range(self.problem.n_dims)]) - Xi = gauss + self.generator.uniform() * self.g_best.solution - round(self.generator.random() + 2) * Nei + xichma2 = (np.log(epoch) * 1.0 / epoch) * np.abs( + np.subtract(self.pop[i2].solution, self.g_best.solution)) + gauss = np.array([self.generator.normal(self.pop[idx].solution[j], xichma2[j]) for j in + range(self.problem.n_dims)]) + Xi = gauss + self.generator.uniform() * self.g_best.solution - round( + self.generator.random() + 2) * Nei ## Update based on Eq. 9 else: i3 = self.generator.choice(temp1, replace=False) - xichma2 = (np.log(epoch) * 1.0 / epoch) * np.abs(np.subtract(self.pop[i3].solution, self.g_best.solution)) - Xi = np.array([self.generator.normal(self.pop[idx].solution[j], xichma2[j]) for j in range(self.problem.n_dims)]) + xichma2 = (np.log(epoch) * 1.0 / epoch) * np.abs( + np.subtract(self.pop[i3].solution, self.g_best.solution)) + Xi = np.array( + [self.generator.normal(self.pop[idx].solution[j], xichma2[j]) for j in range(self.problem.n_dims)]) ## Check the boundary and evaluate the fitness function pos_new = self.correct_solution(Xi) agent = self.generate_empty_agent(pos_new) @@ -124,23 +136,28 @@ def evolve(self, epoch): for j in range(self.problem.n_dims): #### Levy flight strategy is described as Eq. 18 if self.pop[i2].solution[j] == self.pop[idx].solution[j]: - X_ion[j] = self.pop[idx].solution[j] + alpha * levy_b * (self.pop[idx].solution[j] - self.g_best.solution[j]) + X_ion[j] = self.pop[idx].solution[j] + alpha * levy_b * ( + self.pop[idx].solution[j] - self.g_best.solution[j]) #### If not, based on Eq. 11, 12 else: if self.generator.uniform() <= 0.5: - X_ion[j] = self.pop[i1].solution[j] + self.generator.uniform() * (self.pop[i2].solution[j] - self.pop[idx].solution[j]) + X_ion[j] = self.pop[i1].solution[j] + self.generator.uniform() * ( + self.pop[i2].solution[j] - self.pop[idx].solution[j]) else: - X_ion[j] = self.pop[i1].solution[j] - self.generator.uniform() * (self.pop[i2].solution[j] - self.pop[idx].solution[j]) + X_ion[j] = self.pop[i1].solution[j] - self.generator.uniform() * ( + self.pop[i2].solution[j] - self.pop[idx].solution[j]) else: #### Levy flight strategy is described as Eq. 21 _, _, worst = self.get_special_agents(self.pop, n_worst=1, minmax=self.problem.minmax) X_worst = worst[0] for j in range(self.problem.n_dims): ##### Based on Eq. 21 if X_worst.solution[j] == self.g_best.solution[j]: - X_ion[j] = self.pop[idx].solution[j] + alpha * levy_b * (self.problem.ub[j] - self.problem.lb[j]) + X_ion[j] = self.pop[idx].solution[j] + alpha * levy_b * ( + self.problem.ub[j] - self.problem.lb[j]) ##### Based on Eq. 13 else: - X_ion[j] = self.pop[idx].solution[j] + round(self.generator.uniform()) * self.generator.uniform() * \ + X_ion[j] = self.pop[idx].solution[j] + round( + self.generator.uniform()) * self.generator.uniform() * \ (X_worst.solution[j] - self.g_best.solution[j]) ## Check the boundary and evaluate the fitness function for X_ion pos_new = self.correct_solution(X_ion) @@ -174,9 +191,11 @@ def evolve(self, epoch): else: if self.generator.uniform() > 0.5: X_fu = self.pop[idx].solution - 0.5 * (np.sin(2 * np.pi * freq * epoch + np.pi) * - (self.epoch - epoch) / self.epoch + 1) * (self.pop[i1].solution - self.pop[i2].solution) + (self.epoch - epoch) / self.epoch + 1) * ( + self.pop[i1].solution - self.pop[i2].solution) else: - X_fu = self.pop[idx].solution - 0.5 * (np.sin(2 * np.pi * freq * epoch + np.pi) * epoch / self.epoch + 1) * \ + X_fu = self.pop[idx].solution - 0.5 * ( + np.sin(2 * np.pi * freq * epoch + np.pi) * epoch / self.epoch + 1) * \ (self.pop[i1].solution - self.pop[i2].solution) pos_new = self.correct_solution(X_fu) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/physics_based/RIME.py b/mealpy/physics_based/RIME.py index 27d2814d..b0a84a10 100644 --- a/mealpy/physics_based/RIME.py +++ b/mealpy/physics_based/RIME.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -44,6 +45,7 @@ class OriginalRIME(Optimizer): ~~~~~~~~~~ [1] Su, H., Zhao, D., Heidari, A. A., Liu, L., Zhang, X., Mafarja, M., & Chen, H. (2023). RIME: A physics-based optimization. Neurocomputing. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, sr: float = 5., **kwargs: object) -> None: """ Args: @@ -65,8 +67,9 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - rime_factor = (self.generator.random() - 0.5)*2*np.cos(np.pi*epoch/(self.epoch/10)) * (1 - np.round(epoch*self.sr/self.epoch) / self.sr) - ee = np.sqrt((epoch+1)/self.epoch) + rime_factor = (self.generator.random() - 0.5) * 2 * np.cos(np.pi * epoch / (self.epoch / 10)) * ( + 1 - np.round(epoch * self.sr / self.epoch) / self.sr) + ee = np.sqrt((epoch + 1) / self.epoch) fits = np.array([agent.target.fitness for agent in self.pop]).reshape((1, -1)) fits_norm = fits / np.linalg.norm(fits, axis=1, keepdims=True) LB = self.problem.lb @@ -77,7 +80,8 @@ def evolve(self, epoch): for jdx in range(0, self.problem.n_dims): # Soft-rime search strategy if self.generator.random() < ee: - pos_new[jdx] = self.g_best.solution[jdx] + rime_factor*(LB[jdx] + self.generator.random() * (UB[jdx] - LB[jdx])) + pos_new[jdx] = self.g_best.solution[jdx] + rime_factor * ( + LB[jdx] + self.generator.random() * (UB[jdx] - LB[jdx])) # Hard-rime puncture mechanism if self.generator.random() < fits_norm[0, idx]: pos_new[jdx] = self.g_best.solution[jdx] diff --git a/mealpy/physics_based/SA.py b/mealpy/physics_based/SA.py index 2e313104..f6b27921 100644 --- a/mealpy/physics_based/SA.py +++ b/mealpy/physics_based/SA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,7 +44,8 @@ class OriginalSA(Optimizer): [1] Kirkpatrick, S., Gelatt Jr, C. D., & Vecchi, M. P. (1983). Optimization by simulated annealing. science, 220(4598), 671-680. """ - def __init__(self, epoch: int = 10000, pop_size: int = 2, temp_init: float = 100, step_size: float = 0.1, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 2, temp_init: float = 100, step_size: float = 0.1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -79,7 +81,7 @@ def evolve(self, epoch): # Calculate the energy difference delta_energy = np.abs(self.agent_current.target.fitness - agent.target.fitness) # calculate probability acceptance criterion - p_accept = np.exp(-delta_energy/ (self.temp_init / epoch)) + p_accept = np.exp(-delta_energy / (self.temp_init / epoch)) if self.generator.random() < p_accept: self.agent_current = agent self.pop = [self.g_best.copy(), self.agent_current.copy()] @@ -157,7 +159,7 @@ def evolve(self, epoch): else: # Calculate the energy difference delta_energy = np.abs(self.agent_current.target.fitness - agent.target.fitness) - p_accept = np.exp(-delta_energy/self.temp_current) + p_accept = np.exp(-delta_energy / self.temp_current) if self.generator.random() < p_accept: self.agent_current = agent # Reduce the temperature @@ -204,8 +206,10 @@ class SwarmSA(Optimizer): annealing: Theory and applications (pp. 7-15). Springer, Dordrecht. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, max_sub_iter: int = 5, t0: int = 1000, t1: int = 1, move_count: int = 5, - mutation_rate: float = 0.1, mutation_step_size: float = 0.1, mutation_step_size_damp: float = 0.99, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, max_sub_iter: int = 5, t0: int = 1000, t1: int = 1, + move_count: int = 5, + mutation_rate: float = 0.1, mutation_step_size: float = 0.1, mutation_step_size_damp: float = 0.99, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -224,10 +228,11 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, max_sub_iter: int = self.max_sub_iter = self.validator.check_int("max_sub_iter", max_sub_iter, [1, 100000]) self.t0 = self.validator.check_int("t0", t0, [500, 2000]) self.t1 = self.validator.check_int("t1", t1, [1, 100]) - self.move_count = self.validator.check_int("move_count", move_count, [2, int(self.pop_size/2)]) + self.move_count = self.validator.check_int("move_count", move_count, [2, int(self.pop_size / 2)]) self.mutation_rate = self.validator.check_float("mutation_rate", mutation_rate, (0, 1.0)) self.mutation_step_size = self.validator.check_float("mutation_step_size", mutation_step_size, (0, 1.0)) - self.mutation_step_size_damp = self.validator.check_float("mutation_step_size_damp", mutation_step_size_damp, (0, 1.0)) + self.mutation_step_size_damp = self.validator.check_float("mutation_step_size_damp", mutation_step_size_damp, + (0, 1.0)) self.set_parameters(["epoch", "pop_size", "max_sub_iter", "t0", "t1", "move_count", "mutation_rate", "mutation_step_size", "mutation_step_size_damp"]) self.sort_flag = True diff --git a/mealpy/physics_based/SOO.py b/mealpy/physics_based/SOO.py index 880f0130..31b54699 100644 --- a/mealpy/physics_based/SOO.py +++ b/mealpy/physics_based/SOO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -81,7 +82,7 @@ def evolve(self, epoch): caf = 2 * np.pi / (self.initial_period + 0.001 * epoch) # Update scaling factor - scaler = 2 * (1.0 - epoch / self.epoch) + scaler = 2 * (1.0 - epoch / self.epoch) # Update positions of star oscillators pop_new = [] @@ -91,9 +92,11 @@ def evolve(self, epoch): r3 = self.generator.random(size=self.problem.n_dims) # Calculate oscillation positions - osc1 = scaler * (caf * r1 - 1) * (self.pop[idx].solution - np.abs(r1 * np.sin(r2) * np.abs(r3 * self.g_best.solution))) + osc1 = scaler * (caf * r1 - 1) * ( + self.pop[idx].solution - np.abs(r1 * np.sin(r2) * np.abs(r3 * self.g_best.solution))) osc1_pos = self.g_best.solution - r1 * r3 * osc1 - osc2 = scaler * (caf * r1 - 1) * (self.pop[idx].solution - np.abs(r1 * np.cos(r2) * np.abs(r3 * self.g_best.solution))) + osc2 = scaler * (caf * r1 - 1) * ( + self.pop[idx].solution - np.abs(r1 * np.cos(r2) * np.abs(r3 * self.g_best.solution))) osc2_pos = self.g_best.solution - r2 * r3 * osc2 pos_new = r3 * (osc1_pos + osc2_pos) / 2 pos_new = self.correct_solution(pos_new) diff --git a/mealpy/physics_based/TWO.py b/mealpy/physics_based/TWO.py index 54eea0fc..44f6e60b 100644 --- a/mealpy/physics_based/TWO.py +++ b/mealpy/physics_based/TWO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -80,7 +81,7 @@ def update_weight__(self, teams): if maxx == minn: list_fits = self.generator.uniform(0.0, 1.0, self.pop_size) list_weights = np.exp(-(list_fits - maxx) / (maxx - minn)) - list_weights = list_weights/np.sum(list_weights) + 0.1 + list_weights = list_weights / np.sum(list_weights) + 0.1 for idx in range(self.pop_size): teams[idx].weight = list_weights[idx] return teams @@ -110,7 +111,8 @@ def evolve(self, epoch): for jdx in range(self.problem.n_dims): if pos_new[jdx] < self.problem.lb[jdx] or pos_new[jdx] > self.problem.ub[jdx]: if self.generator.random() <= 0.5: - pos_new[jdx] = self.g_best.solution[jdx] + self.generator.standard_normal() / epoch * (self.g_best.solution[jdx] - pos_new[jdx]) + pos_new[jdx] = self.g_best.solution[jdx] + self.generator.standard_normal() / epoch * ( + self.g_best.solution[jdx] - pos_new[jdx]) if pos_new[jdx] < self.problem.lb[jdx] or pos_new[jdx] > self.problem.ub[jdx]: pos_new[jdx] = self.pop[idx].solution[jdx] else: @@ -164,8 +166,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> def initialization(self): if self.pop is None: self.pop = self.generate_population(self.pop_size) - list_idx = self.generator.choice(range(0, self.pop_size), int(self.pop_size/2), replace=False) - pop_temp = [self.pop[list_idx[idx]] for idx in range(0, int(self.pop_size/2))] + list_idx = self.generator.choice(range(0, self.pop_size), int(self.pop_size / 2), replace=False) + pop_temp = [self.pop[list_idx[idx]] for idx in range(0, int(self.pop_size / 2))] pop_oppo = [] for idx in range(len(pop_temp)): pos_opposite = self.problem.ub + self.problem.lb - pop_temp[idx].solution @@ -201,7 +203,8 @@ def evolve(self, epoch): self.pop[idx].solution = pos_new ## Amend solution and update fitness value for idx in range(self.pop_size): - pos_new = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) / (epoch) * (self.g_best.solution - pop_new[idx].solution) + pos_new = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) / (epoch) * ( + self.g_best.solution - pop_new[idx].solution) conditions = np.logical_or(pop_new[idx].solution < self.problem.lb, pop_new[idx].solution > self.problem.ub) conditions = np.logical_and(conditions, self.generator.random(self.problem.n_dims) < 0.5) pos_new = np.where(conditions, pos_new, self.pop[idx].solution) @@ -278,14 +281,15 @@ def evolve(self, epoch): acceleration = resultant_force * g / (self.pop[idx].weight * self.muy_k) delta_x = 1 / 2 * acceleration + np.power(self.alpha, epoch) * self.beta * \ (self.problem.ub - self.problem.lb) * self.generator.normal(0, 1, self.problem.n_dims) - pos_new +=delta_x + pos_new += delta_x pop_new[idx].solution = pos_new for idx in range(self.pop_size): pos_new = self.pop[idx].solution.copy().astype(float) for jdx in range(self.problem.n_dims): if pos_new[jdx] < self.problem.lb[jdx] or pos_new[jdx] > self.problem.ub[jdx]: if self.generator.random() <= 0.5: - pos_new[jdx] = self.g_best.solution[jdx] + self.generator.standard_normal() / epoch * (self.g_best.solution[jdx] - pos_new[jdx]) + pos_new[jdx] = self.g_best.solution[jdx] + self.generator.standard_normal() / epoch * ( + self.g_best.solution[jdx] - pos_new[jdx]) if pos_new[jdx] < self.problem.lb[jdx] or pos_new[jdx] > self.problem.ub[jdx]: pos_new[jdx] = self.pop[idx].solution[jdx] else: @@ -392,7 +396,8 @@ def evolve(self, epoch): for jdx in range(self.problem.n_dims): if pos_new[jdx] < self.problem.lb[jdx] or pos_new[jdx] > self.problem.ub[jdx]: if self.generator.random() <= 0.5: - pos_new[jdx] = self.g_best.solution[jdx] + self.generator.standard_normal() / epoch * (self.g_best.solution[jdx] - pos_new[jdx]) + pos_new[jdx] = self.g_best.solution[jdx] + self.generator.standard_normal() / epoch * ( + self.g_best.solution[jdx] - pos_new[jdx]) if pos_new[jdx] < self.problem.lb[jdx] or pos_new[jdx] > self.problem.ub[jdx]: pos_new[jdx] = self.pop[idx].solution[jdx] else: diff --git a/mealpy/physics_based/WDO.py b/mealpy/physics_based/WDO.py index 6f020c62..341ea520 100644 --- a/mealpy/physics_based/WDO.py +++ b/mealpy/physics_based/WDO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -76,7 +77,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, RT: int = 3, g_c: fl self.sort_flag = False def initialize_variables(self): - self.dyn_list_velocity = self.max_v * self.generator.uniform(self.problem.lb, self.problem.ub, (self.pop_size, self.problem.n_dims)) + self.dyn_list_velocity = self.max_v * self.generator.uniform(self.problem.lb, self.problem.ub, + (self.pop_size, self.problem.n_dims)) def evolve(self, epoch): """ @@ -90,7 +92,8 @@ def evolve(self, epoch): rand_dim = self.generator.integers(0, self.problem.n_dims) temp = self.dyn_list_velocity[idx][rand_dim] * np.ones(self.problem.n_dims) vel = (1 - self.alp) * self.dyn_list_velocity[idx] - self.g_c * self.pop[idx].solution + \ - (1 - 1.0 / (idx + 1)) * self.RT * (self.g_best.solution - self.pop[idx].solution) + self.c_e * temp / (idx + 1) + (1 - 1.0 / (idx + 1)) * self.RT * ( + self.g_best.solution - self.pop[idx].solution) + self.c_e * temp / (idx + 1) vel = np.clip(vel, -self.max_v, self.max_v) # Update air parcel positions, check the bound and calculate pressure (fitness) self.dyn_list_velocity[idx] = vel diff --git a/mealpy/sota_based/IMODE.py b/mealpy/sota_based/IMODE.py index 0299bd3b..7d8eff2b 100644 --- a/mealpy/sota_based/IMODE.py +++ b/mealpy/sota_based/IMODE.py @@ -5,7 +5,9 @@ # --------------------------------------------------% from typing import Tuple, List + import numpy as np + from mealpy.optimizer import Optimizer @@ -93,7 +95,8 @@ def _generate_parameters(self) -> Tuple[np.ndarray, np.ndarray]: # Regenerate negative F values negative_mask = f <= 0 while np.any(negative_mask): - f[negative_mask] = mu_f[negative_mask] + 0.1 * np.tan(np.pi * (self.generator.random(np.sum(negative_mask)) - 0.5)) + f[negative_mask] = mu_f[negative_mask] + 0.1 * np.tan( + np.pi * (self.generator.random(np.sum(negative_mask)) - 0.5)) negative_mask = f <= 0 f = np.clip(f, 0, 1) return f, cr @@ -115,7 +118,8 @@ def _generate_random_indices(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, total_size = len(combined_pop) # Generate unique random indices and Ensure indices are different - r1, r2, r3 = np.zeros(self.pop_size, dtype=int), np.zeros(self.pop_size, dtype=int), np.zeros(self.pop_size, dtype=int) + r1, r2, r3 = np.zeros(self.pop_size, dtype=int), np.zeros(self.pop_size, dtype=int), np.zeros(self.pop_size, + dtype=int) for idx in range(0, self.pop_size): x1, x3 = self.generator.choice(list(set(range(self.pop_size)) - {idx}), size=2, replace=False) x2 = self.generator.choice(list(set(range(total_size)) - {idx, x1, x3})) @@ -142,7 +146,7 @@ def _mutation(self, f: np.ndarray) -> np.ndarray: matrix_pbest = matrix_pos[pbest_indices] matrix_mutant[op1_mask] = (matrix_pos[op1_mask] + f[op1_mask, np.newaxis] * (matrix_pbest[op1_mask] - matrix_pos[op1_mask] + - matrix_pos[r1[op1_mask]] - matrix_combined[r2[op1_mask]])) + matrix_pos[r1[op1_mask]] - matrix_combined[r2[op1_mask]])) # Operator 2: DE/current-to-pbest/1/bin if np.any(op2_mask): p_best_size = max(int(0.25 * self.pop_size), 1) @@ -150,14 +154,14 @@ def _mutation(self, f: np.ndarray) -> np.ndarray: matrix_pbest = matrix_pos[pbest_indices] matrix_mutant[op2_mask] = (matrix_pos[op2_mask] + f[op2_mask, np.newaxis] * (matrix_pbest[op2_mask] - matrix_pos[op2_mask] + - matrix_pos[r1[op2_mask]] - matrix_pos[r3[op2_mask]])) + matrix_pos[r1[op2_mask]] - matrix_pos[r3[op2_mask]])) # Operator 3: DE/rand-to-pbest/1 if np.any(op3_mask): p_best_size = max(int(0.5 * self.pop_size), 2) pbest_indices = self.generator.integers(0, p_best_size, self.pop_size) matrix_pbest = matrix_pos[pbest_indices] matrix_mutant[op3_mask] = (f[op3_mask, np.newaxis] * matrix_pos[r1[op3_mask]] + - f[op3_mask, np.newaxis] * (matrix_pbest[op3_mask] - matrix_pos[r3[op3_mask]])) + f[op3_mask, np.newaxis] * (matrix_pbest[op3_mask] - matrix_pos[r3[op3_mask]])) return matrix_mutant def _handle_boundaries(self, vectors: np.ndarray) -> np.ndarray: @@ -165,16 +169,16 @@ def _handle_boundaries(self, vectors: np.ndarray) -> np.ndarray: strategy = self.generator.integers(1, 4) result = [] - if strategy == 1: # Strategy 1: Midpoint repair + if strategy == 1: # Strategy 1: Midpoint repair for idx in range(0, len(vectors)): res = np.select([vectors[idx] < self.problem.lb, vectors[idx] > self.problem.ub], [(vectors[idx] + self.problem.ub) / 2, (vectors[idx] + self.problem.lb) / 2], default=vectors[idx]) result.append(res) - elif strategy == 2: # Strategy 2: Reflection + elif strategy == 2: # Strategy 2: Reflection for idx in range(0, len(vectors)): res = vectors[idx] - flag1 = res < self.problem.lb + flag1 = res < self.problem.lb res[flag1] = np.clip( 2 * self.problem.lb[flag1] - res[flag1], self.problem.lb[flag1], self.problem.ub[flag1] ) @@ -183,7 +187,7 @@ def _handle_boundaries(self, vectors: np.ndarray) -> np.ndarray: 2 * self.problem.ub[flag2] - res[flag2], self.problem.lb[flag2], self.problem.ub[flag2] ) result.append(res) - else: # Strategy 3: Random reinitialization + else: # Strategy 3: Random reinitialization for idx in range(0, len(vectors)): res = vectors[idx] mask_lower = res < self.problem.lb @@ -217,7 +221,7 @@ def _crossover(self, mutant: np.ndarray, cr: np.ndarray) -> np.ndarray: jdx += 1 return trial - def _update_archive(self, improved_pop = None): + def _update_archive(self, improved_pop=None): """Update solution archive""" if len(improved_pop) == 0: return @@ -300,7 +304,8 @@ def evolve(self, epoch): if np.max(successful_cr) == 0: self.memory_cr[self.memory_pos] = -1 else: - self.memory_cr[self.memory_pos] = np.sum(weights * successful_cr ** 2) / np.sum(weights * successful_cr) + self.memory_cr[self.memory_pos] = np.sum(weights * successful_cr ** 2) / np.sum( + weights * successful_cr) # Update memory position self.memory_pos = (self.memory_pos + 1) % self.memory_size else: diff --git a/mealpy/sota_based/LSHADEcnEpSin.py b/mealpy/sota_based/LSHADEcnEpSin.py index 3e480bf8..f286cd43 100644 --- a/mealpy/sota_based/LSHADEcnEpSin.py +++ b/mealpy/sota_based/LSHADEcnEpSin.py @@ -4,8 +4,9 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from scipy.stats import cauchy, norm import numpy as np +from scipy.stats import cauchy, norm + from mealpy.optimizer import Optimizer @@ -74,7 +75,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, miu_f: float = 0.5, def initialize_variables(self): self.NP_init = self.pop_size if self.pop_size else 18 * self.problem.n_dims self.NP_min = self.pop_size_min # Minimum population size - self.NP = self.NP_init # population size will be updated in each iteration + self.NP = self.NP_init # population size will be updated in each iteration # Memory settings self.H = self.memory_size # Memory size @@ -153,7 +154,7 @@ def current_to_pbest_mutation(self, idx, F, p=0.1): # Mutation pos_new = self.pop[idx].solution + F * (pop_sorted[pbest_idx].solution - self.pop[idx].solution) + \ - F * (self.pop[r1].solution - pop_combined[r2].solution) + F * (self.pop[r1].solution - pop_combined[r2].solution) # Ensure the new position is within bounds pos_new = self.correct_solution(pos_new) return pos_new @@ -203,7 +204,8 @@ def covariance_matrix_crossover(self, target, mutant): CR = np.clip(CR, 0, 1) # Binomial crossover in eigen space - trial_prime = np.where(self.generator.uniform(0, 1, self.problem.n_dims) <= CR, mutant_prime, target_prime) + trial_prime = np.where(self.generator.uniform(0, 1, self.problem.n_dims) <= CR, mutant_prime, + target_prime) j_rand = self.generator.integers(0, self.problem.n_dims) trial_prime[j_rand] = mutant_prime[j_rand] # Ensure at least one gene from mutant # Transform back to original coordinate system @@ -298,7 +300,7 @@ def evolve(self, epoch): agent = self.generate_agent(pos_new) # Selection - if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): # Success + if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): # Success delta = abs(self.pop[idx].target.fitness - agent.target.fitness) S_F.append(F) S_CR.append(CR) @@ -313,7 +315,7 @@ def evolve(self, epoch): self.archive = self.archive + [self.pop[idx].copy()] # Replace with trial self.pop[idx] = agent - else: # Failure + else: # Failure if epoch <= self.epoch // 2: if config_used == 1: nf1_current += 1 diff --git a/mealpy/swarm_based/ABC.py b/mealpy/swarm_based/ABC.py index 8ce10c5b..f5f11911 100644 --- a/mealpy/swarm_based/ABC.py +++ b/mealpy/swarm_based/ABC.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -42,6 +43,7 @@ class OriginalABC(Optimizer): [1] B. Basturk, D. Karaboga, An artificial bee colony (ABC) algorithm for numeric function optimization, in: IEEE Swarm Intelligence Symposium 2006, May 12–14, Indianapolis, IN, USA, 2006. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, n_limits: int = 25, **kwargs: object) -> None: """ Args: diff --git a/mealpy/swarm_based/ACOR.py b/mealpy/swarm_based/ACOR.py index 244f31f8..7c7b4142 100644 --- a/mealpy/swarm_based/ACOR.py +++ b/mealpy/swarm_based/ACOR.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -94,7 +95,7 @@ def evolve(self, epoch): for jdx in range(0, self.problem.n_dims): rdx = self.get_index_roulette_wheel_selection(matrix_p) child[jdx] = self.pop[rdx].solution[jdx] + self.generator.normal() * matrix_sigma[rdx, jdx] # (1) - pos_new = self.correct_solution(child) # (2) + pos_new = self.correct_solution(child) # (2) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) if self.mode not in self.AVAILABLE_MODES: diff --git a/mealpy/swarm_based/AGTO.py b/mealpy/swarm_based/AGTO.py index 9c284110..36aa0b64 100644 --- a/mealpy/swarm_based/AGTO.py +++ b/mealpy/swarm_based/AGTO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,9 @@ class OriginalAGTO(Optimizer): [1] Abdollahzadeh, B., Soleimanian Gharehchopogh, F., & Mirjalili, S. (2021). Artificial gorilla troops optimizer: a new nature‐inspired metaheuristic algorithm for global optimization problems. International Journal of Intelligent Systems, 36(10), 5887-5958. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, p1: float = 0.03, p2: float = 0.8, beta: float = 3.0, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, p1: float = 0.03, p2: float = 0.8, beta: float = 3.0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -54,8 +57,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, p1: float = 0.03, p2 super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.p1 = self.validator.check_float("p1", p1, (0, 1)) # p in the paper - self.p2 = self.validator.check_float("p2", p2, (0, 1)) # w in the paper + self.p1 = self.validator.check_float("p1", p1, (0, 1)) # p in the paper + self.p2 = self.validator.check_float("p2", p2, (0, 1)) # w in the paper self.beta = self.validator.check_float("beta", beta, [-10.0, 10.0]) self.set_parameters(["epoch", "pop_size", "p1", "p2", "beta"]) self.sort_flag = False @@ -67,7 +70,7 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - a = (np.cos(2*self.generator.random())+1) * (1 - epoch/self.epoch) + a = (np.cos(2 * self.generator.random()) + 1) * (1 - epoch / self.epoch) c = a * (2 * self.generator.random() - 1) ## Exploration pop_new = [] @@ -78,11 +81,12 @@ def evolve(self, epoch): if self.generator.random() >= 0.5: z = self.generator.uniform(-a, a, self.problem.n_dims) rand_idx = self.generator.integers(0, self.pop_size) - pos_new = (self.generator.random() - a) * self.pop[rand_idx].solution + c * z * self.pop[idx].solution + pos_new = (self.generator.random() - a) * self.pop[rand_idx].solution + c * z * self.pop[ + idx].solution else: id1, id2 = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) - pos_new = self.pop[idx].solution - c*(c*self.pop[idx].solution - self.pop[id1].solution) + \ - self.generator.random() * (self.pop[idx].solution - self.pop[id2].solution) + pos_new = self.pop[idx].solution - c * (c * self.pop[idx].solution - self.pop[id1].solution) + \ + self.generator.random() * (self.pop[idx].solution - self.pop[id2].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -101,14 +105,15 @@ def evolve(self, epoch): if a >= self.p2: g = 2 ** c delta = (np.abs(np.mean(pos_list, axis=0)) ** g) ** (1.0 / g) - pos_new = c*delta*(self.pop[idx].solution - self.g_best.solution) + self.pop[idx].solution + pos_new = c * delta * (self.pop[idx].solution - self.g_best.solution) + self.pop[idx].solution else: if self.generator.random() >= 0.5: h = self.generator.normal(0, 1, self.problem.n_dims) else: h = self.generator.normal(0, 1) r1 = self.generator.random() - pos_new = self.g_best.solution - (2*r1-1)*(self.g_best.solution - self.pop[idx].solution) * (self.beta * h) + pos_new = self.g_best.solution - (2 * r1 - 1) * (self.g_best.solution - self.pop[idx].solution) * ( + self.beta * h) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -151,6 +156,7 @@ class MGTO(Optimizer): [1] Mostafa, R. R., Gaheen, M. A., Abd ElAziz, M., Al-Betar, M. A., & Ewees, A. A. (2023). An improved gorilla troops optimizer for global optimization problems and feature selection. Knowledge-Based Systems, 110462. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, pp: float = 0.03, **kwargs: object) -> None: """ Args: @@ -161,7 +167,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pp: float = 0.03, ** super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.pp = self.validator.check_float("p1", pp, (0, 1)) # p in the paper + self.pp = self.validator.check_float("p1", pp, (0, 1)) # p in the paper self.set_parameters(["epoch", "pop_size", "pp"]) self.sort_flag = False @@ -205,11 +211,12 @@ def evolve(self, epoch): else: if self.generator.random() >= 0.5: rand_idx = self.generator.integers(0, self.pop_size) - pos_new = (self.generator.random() - C) * self.pop[rand_idx].solution + L * self.generator.uniform(-C, C) * self.pop[idx].solution + pos_new = (self.generator.random() - C) * self.pop[rand_idx].solution + L * self.generator.uniform( + -C, C) * self.pop[idx].solution else: id1, id2 = self.generator.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) - pos_new = self.pop[idx].solution - L*(L*self.pop[idx].solution - self.pop[id1].solution) + \ - self.generator.random() * (self.pop[idx].solution - self.pop[id2].solution) + pos_new = self.pop[idx].solution - L * (L * self.pop[idx].solution - self.pop[id1].solution) + \ + self.generator.random() * (self.pop[idx].solution - self.pop[id2].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -230,11 +237,12 @@ def evolve(self, epoch): M = (np.abs(np.mean(pos_list, axis=0)) ** g) ** (1.0 / g) # print(M) p = self.generator.uniform(0, 1, self.problem.n_dims) - pos_new = L * M * (self.pop[idx].solution - self.g_best.solution) * (0.01 * np.tan(np.pi*( p - 0.5))) + pos_new = L * M * (self.pop[idx].solution - self.g_best.solution) * (0.01 * np.tan(np.pi * (p - 0.5))) else: Q = 2 * self.generator.random() - 1 v = self.generator.uniform(0, 1) - pos_new = self.g_best.solution - Q * (self.g_best.solution - self.pop[idx].solution) * np.tan(v * np.pi/2) + pos_new = self.g_best.solution - Q * (self.g_best.solution - self.pop[idx].solution) * np.tan( + v * np.pi / 2) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/swarm_based/ALO.py b/mealpy/swarm_based/ALO.py index b96ddc1b..1a9cda93 100644 --- a/mealpy/swarm_based/ALO.py +++ b/mealpy/swarm_based/ALO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -109,7 +110,7 @@ def evolve(self, epoch): RA = self.random_walk_antlion__(self.pop[rolette_index].solution, epoch) # RE is the random walk around the elite (the best antlion so far) RE = self.random_walk_antlion__(self.g_best.solution, epoch) - temp = (RA[:, epoch-1] + RE[:, epoch-1]) / 2 # Equation(2.13) in the paper + temp = (RA[:, epoch - 1] + RE[:, epoch - 1]) / 2 # Equation(2.13) in the paper # Bound checking (bring back the antlions of ants inside search space if they go beyonds the boundaries pos_new = self.correct_solution(temp) agent = self.generate_empty_agent(pos_new) @@ -179,7 +180,8 @@ def random_walk_antlion__(self, solution, current_epoch): ub = ub + solution if self.generator.random() < 0.5 else -ub + solution # This function creates n random walks and normalize according to lb and ub vectors, ## Using matrix and vector for better performance - X = np.array([np.cumsum(2 * (self.generator.random(self.pop_size) > 0.5) - 1) for _ in range(0, self.problem.n_dims)]) + X = np.array( + [np.cumsum(2 * (self.generator.random(self.pop_size) > 0.5) - 1) for _ in range(0, self.problem.n_dims)]) a = np.min(X, axis=1) b = np.max(X, axis=1) temp1 = np.reshape((ub - lb) / (b - a), (self.problem.n_dims, 1)) diff --git a/mealpy/swarm_based/AO.py b/mealpy/swarm_based/AO.py index f6097487..a82c540d 100644 --- a/mealpy/swarm_based/AO.py +++ b/mealpy/swarm_based/AO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -78,14 +79,17 @@ def evolve(self, epoch): levy_step = self.get_levy_flight_step(beta=1.5, multiplier=1.0, case=-1) if epoch <= (2 / 3) * self.epoch: # Eq. 3, 4 if self.generator.random() < 0.5: - pos_new = self.g_best.solution * (1 - epoch / self.epoch) + self.generator.random() * (x_mean - self.g_best.solution) + pos_new = self.g_best.solution * (1 - epoch / self.epoch) + self.generator.random() * ( + x_mean - self.g_best.solution) else: idx = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) - pos_new = self.g_best.solution * levy_step + self.pop[idx].solution + self.generator.random() * (y - x) # Eq. 5 + pos_new = self.g_best.solution * levy_step + self.pop[idx].solution + self.generator.random() * ( + y - x) # Eq. 5 else: if self.generator.random() < 0.5: pos_new = alpha * (self.g_best.solution - x_mean) - self.generator.random() * \ - (self.generator.random() * (self.problem.ub - self.problem.lb) + self.problem.lb) * delta # Eq. 13 + (self.generator.random() * ( + self.problem.ub - self.problem.lb) + self.problem.lb) * delta # Eq. 13 else: pos_new = QF * self.g_best.solution - (g2 * self.pop[idx].solution * self.generator.random()) - \ g2 * levy_step + self.generator.random() * g1 # Eq. 14 @@ -184,11 +188,13 @@ def evolve(self, epoch): self.generator.random() * (x_mean - self.g_best.solution)) # Eq. (3) and Eq. (4) else: idx = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) - pos_new = self.g_best.solution * levy_step + self.pop[idx].solution + self.generator.random() * (y - x) # Eq. 5 + pos_new = self.g_best.solution * levy_step + self.pop[idx].solution + self.generator.random() * ( + y - x) # Eq. 5 else: if self.generator.random() < 0.5: pos_new = (alpha * (self.g_best.solution - x_mean) - self.generator.random() * - (self.generator.random() * (self.problem.ub - self.problem.lb) + self.problem.lb) * delta) # Eq. 13 + (self.generator.random() * ( + self.problem.ub - self.problem.lb) + self.problem.lb) * delta) # Eq. 13 else: pos_new = (QF * self.g_best.solution - (g2 * self.pop[idx].solution * self.generator.random()) - g2 * levy_step + self.generator.random() * g1) # Eq. 14 diff --git a/mealpy/swarm_based/ARO.py b/mealpy/swarm_based/ARO.py index 293b2b17..4b857f56 100644 --- a/mealpy/swarm_based/ARO.py +++ b/mealpy/swarm_based/ARO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -60,26 +61,29 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - theta = 2 * (1 - epoch/self.epoch) + theta = 2 * (1 - epoch / self.epoch) pop_new = [] for idx in range(0, self.pop_size): - L = (np.exp(1) - np.exp((epoch / self.epoch)**2)) * (np.sin(2*np.pi*self.generator.random())) + L = (np.exp(1) - np.exp((epoch / self.epoch) ** 2)) * (np.sin(2 * np.pi * self.generator.random())) temp = np.zeros(self.problem.n_dims) - rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), int(np.ceil(self.generator.random()*self.problem.n_dims)), replace=False) + rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), + int(np.ceil(self.generator.random() * self.problem.n_dims)), replace=False) temp[rd_index] = 1 - R = L * temp # Eq 2 - A = 2 * np.log(1.0 / self.generator.random()) * theta # Eq. 15 - if A > 1: # detour foraging strategy + R = L * temp # Eq 2 + A = 2 * np.log(1.0 / self.generator.random()) * theta # Eq. 15 + if A > 1: # detour foraging strategy rand_idx = self.generator.integers(0, self.pop_size) pos_new = self.pop[rand_idx].solution + R * (self.pop[idx].solution - self.pop[rand_idx].solution) + \ - np.round(0.5 * (0.05 + self.generator.random())) * self.generator.normal(0, 1) # Eq. 1 - else: # Random hiding stage + np.round(0.5 * (0.05 + self.generator.random())) * self.generator.normal(0, 1) # Eq. 1 + else: # Random hiding stage gr = np.zeros(self.problem.n_dims) - rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), int(np.ceil(self.generator.random() * self.problem.n_dims)), replace=False) - gr[rd_index] = 1 # Eq. 12 - H = self.generator.normal(0, 1) * (epoch / self.epoch) # Eq. 8 - b = self.pop[idx].solution + H * gr * self.pop[idx].solution # Eq. 13 - pos_new = self.pop[idx].solution + R * (self.generator.random() * b - self.pop[idx].solution) # Eq. 11 + rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), + int(np.ceil(self.generator.random() * self.problem.n_dims)), + replace=False) + gr[rd_index] = 1 # Eq. 12 + H = self.generator.normal(0, 1) * (epoch / self.epoch) # Eq. 8 + b = self.pop[idx].solution + H * gr * self.pop[idx].solution # Eq. 13 + pos_new = self.pop[idx].solution + R * (self.generator.random() * b - self.pop[idx].solution) # Eq. 11 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -142,27 +146,30 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - theta = 2 * (1 - (epoch+1)/self.epoch) + theta = 2 * (1 - (epoch + 1) / self.epoch) pop_new = [] for idx in range(0, self.pop_size): - L = (np.exp(1) - np.exp((epoch / self.epoch)**2)) * (np.sin(2*np.pi*self.generator.random())) + L = (np.exp(1) - np.exp((epoch / self.epoch) ** 2)) * (np.sin(2 * np.pi * self.generator.random())) temp = np.zeros(self.problem.n_dims) - rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), int(np.ceil(self.generator.random()*self.problem.n_dims)), replace=False) + rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), + int(np.ceil(self.generator.random() * self.problem.n_dims)), replace=False) temp[rd_index] = 1 - R = L * temp # Eq 2 - A = 2 * np.log(1.0 / self.generator.random()) * theta # Eq. 15 - if A > 1: # # detour foraging strategy + R = L * temp # Eq 2 + A = 2 * np.log(1.0 / self.generator.random()) * theta # Eq. 15 + if A > 1: # # detour foraging strategy rand_idx = self.generator.integers(0, self.pop_size) pos_new = self.pop[rand_idx].solution + R * (self.pop[idx].solution - self.pop[rand_idx].solution) + \ - np.round(0.5 * (0.05 + self.generator.random())) * self.generator.normal(0, 1) # Eq. 1 - else: # Random hiding stage + np.round(0.5 * (0.05 + self.generator.random())) * self.generator.normal(0, 1) # Eq. 1 + else: # Random hiding stage gr = np.zeros(self.problem.n_dims) - rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), int(np.ceil(self.generator.random() * self.problem.n_dims)), replace=False) - gr[rd_index] = 1 # Eq. 12 - H = self.generator.normal(0, 1) * (epoch / self.epoch) # Eq. 8 - b = self.pop[idx].solution + H * gr * self.pop[idx].solution # Eq. 13 + rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), + int(np.ceil(self.generator.random() * self.problem.n_dims)), + replace=False) + gr[rd_index] = 1 # Eq. 12 + H = self.generator.normal(0, 1) * (epoch / self.epoch) # Eq. 8 + b = self.pop[idx].solution + H * gr * self.pop[idx].solution # Eq. 13 levy = self.get_levy_flight_step(beta=1.5, multiplier=0.1) - pos_new = self.pop[idx].solution + R * (levy * b - self.pop[idx].solution) # Eq. 11 + pos_new = self.pop[idx].solution + R * (levy * b - self.pop[idx].solution) # Eq. 11 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -180,7 +187,7 @@ def evolve(self, epoch): idx_far = np.sign(dd - TS) < 0 n_df = np.sum(idx_far) n_dc = np.sum(np.sign(dd - TS) > 0) - src = 1 - 6*np.sum(dd**2) / np.dot(dd, (dd**2 - 1)) + src = 1 - 6 * np.sum(dd ** 2) / np.dot(dd, (dd ** 2 - 1)) if len(dd[idx_far]) == 0: df_lb, df_ub = np.min(dd), np.max(dd) else: @@ -245,26 +252,29 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - theta = 2 * (1 - (epoch+1)/self.epoch) + theta = 2 * (1 - (epoch + 1) / self.epoch) pop_new = [] for idx in range(0, self.pop_size): - L = (np.exp(1) - np.exp((epoch / self.epoch)**2)) * (np.sin(2*np.pi*self.generator.random())) + L = (np.exp(1) - np.exp((epoch / self.epoch) ** 2)) * (np.sin(2 * np.pi * self.generator.random())) temp = np.zeros(self.problem.n_dims) - rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), int(np.ceil(self.generator.random()*self.problem.n_dims)), replace=False) + rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), + int(np.ceil(self.generator.random() * self.problem.n_dims)), replace=False) temp[rd_index] = 1 - R = L * temp # Eq 2 - A = 2 * np.log(1.0 / self.generator.random()) * theta # Eq. 15 - if A > 1: # # detour foraging strategy + R = L * temp # Eq 2 + A = 2 * np.log(1.0 / self.generator.random()) * theta # Eq. 15 + if A > 1: # # detour foraging strategy rand_idx = self.generator.integers(0, self.pop_size) pos_new = self.pop[rand_idx].solution + R * (self.pop[idx].solution - self.pop[rand_idx].solution) + \ - np.round(0.5 * (0.05 + self.generator.random())) * self.generator.normal(0, 1) # Eq. 1 - else: # Random hiding stage + np.round(0.5 * (0.05 + self.generator.random())) * self.generator.normal(0, 1) # Eq. 1 + else: # Random hiding stage gr = np.zeros(self.problem.n_dims) - rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), int(np.ceil(self.generator.random() * self.problem.n_dims)), replace=False) - gr[rd_index] = 1 # Eq. 12 - H = self.generator.normal(0, 1) * (epoch / self.epoch) # Eq. 8 - b = self.pop[idx].solution + H * gr * self.pop[idx].solution # Eq. 13 - pos_new = self.pop[idx].solution + R * (self.generator.random() * b - self.pop[idx].solution) # Eq. 11 + rd_index = self.generator.choice(np.arange(0, self.problem.n_dims), + int(np.ceil(self.generator.random() * self.problem.n_dims)), + replace=False) + gr[rd_index] = 1 # Eq. 12 + H = self.generator.normal(0, 1) * (epoch / self.epoch) # Eq. 8 + b = self.pop[idx].solution + H * gr * self.pop[idx].solution # Eq. 13 + pos_new = self.pop[idx].solution + R * (self.generator.random() * b - self.pop[idx].solution) # Eq. 11 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/swarm_based/AVOA.py b/mealpy/swarm_based/AVOA.py index b4d8757b..bbf1ec02 100644 --- a/mealpy/swarm_based/AVOA.py +++ b/mealpy/swarm_based/AVOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -73,37 +74,44 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - a = self.generator.uniform(-2, 2) * ((np.sin((np.pi / 2) * (epoch / self.epoch)) ** self.gama) + np.cos((np.pi / 2) * (epoch / self.epoch)) - 1) - ppp = (2 * self.generator.random() + 1) * (1 - epoch/self.epoch) + a + a = self.generator.uniform(-2, 2) * ((np.sin((np.pi / 2) * (epoch / self.epoch)) ** self.gama) + np.cos( + (np.pi / 2) * (epoch / self.epoch)) - 1) + ppp = (2 * self.generator.random() + 1) * (1 - epoch / self.epoch) + a _, best_list, _ = self.get_special_agents(self.pop, n_best=2, minmax=self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): - F = ppp * (2 * self.generator.random() -1) - rand_idx = self.generator.choice([0, 1], p=[self.alpha, 1-self.alpha]) + F = ppp * (2 * self.generator.random() - 1) + rand_idx = self.generator.choice([0, 1], p=[self.alpha, 1 - self.alpha]) rand_pos = best_list[rand_idx].solution - if np.abs(F) >= 1: # Exploration + if np.abs(F) >= 1: # Exploration if self.generator.random() < self.p1: pos_new = rand_pos - (np.abs((2 * self.generator.random()) * rand_pos - self.pop[idx].solution)) * F else: - pos_new = rand_pos - F + self.generator.random()*((self.problem.ub - self.problem.lb)*self.generator.random() + self.problem.lb) - else: # Exploitation - if np.abs(F) < 0.5: # Phase 1 + pos_new = rand_pos - F + self.generator.random() * ( + (self.problem.ub - self.problem.lb) * self.generator.random() + self.problem.lb) + else: # Exploitation + if np.abs(F) < 0.5: # Phase 1 best_x1 = best_list[0].solution best_x2 = best_list[1].solution if self.generator.random() < self.p2: - A = best_x1 - ((best_x1 * self.pop[idx].solution) / (best_x1 - self.pop[idx].solution**2 + self.EPSILON))*F - B = best_x2 - ((best_x2 * self.pop[idx].solution) / (best_x2 - self.pop[idx].solution**2 + self.EPSILON))*F + A = best_x1 - ((best_x1 * self.pop[idx].solution) / ( + best_x1 - self.pop[idx].solution ** 2 + self.EPSILON)) * F + B = best_x2 - ((best_x2 * self.pop[idx].solution) / ( + best_x2 - self.pop[idx].solution ** 2 + self.EPSILON)) * F pos_new = (A + B) / 2 else: pos_new = rand_pos - np.abs(rand_pos - self.pop[idx].solution) * F * \ self.get_levy_flight_step(beta=1.5, multiplier=1., size=self.problem.n_dims, case=-1) - else: # Phase 2 + else: # Phase 2 if self.generator.random() < self.p3: - pos_new = (np.abs((2 * self.generator.random()) * rand_pos - self.pop[idx].solution)) * (F + self.generator.random()) - \ + pos_new = (np.abs((2 * self.generator.random()) * rand_pos - self.pop[idx].solution)) * ( + F + self.generator.random()) - \ (rand_pos - self.pop[idx].solution) else: - s1 = rand_pos * (self.generator.random() * self.pop[idx].solution / (2 * np.pi)) * np.cos(self.pop[idx].solution) - s2 = rand_pos * (self.generator.random() * self.pop[idx].solution / (2 * np.pi)) * np.sin(self.pop[idx].solution) + s1 = rand_pos * (self.generator.random() * self.pop[idx].solution / (2 * np.pi)) * np.cos( + self.pop[idx].solution) + s2 = rand_pos * (self.generator.random() * self.pop[idx].solution / (2 * np.pi)) * np.sin( + self.pop[idx].solution) pos_new = rand_pos - (s1 + s2) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/swarm_based/BA.py b/mealpy/swarm_based/BA.py index 86790937..12beee9b 100644 --- a/mealpy/swarm_based/BA.py +++ b/mealpy/swarm_based/BA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -100,7 +101,8 @@ def evolve(self, epoch): for idx in range(self.pop_size): ## Replace the old position by the new one when its has better fitness. ## and then update loudness and emission rate - if self.compare_target(pop_new[idx].target, self.pop[idx].target, self.problem.minmax) and self.generator.random() < self.loudness: + if self.compare_target(pop_new[idx].target, self.pop[idx].target, + self.problem.minmax) and self.generator.random() < self.loudness: self.pop[idx].update(solution=pop_new[idx].solution, target=pop_new[idx].target) @@ -146,7 +148,8 @@ class AdaptiveBA(Optimizer): """ def __init__(self, epoch: int = 10000, pop_size: object = 100, loudness_min: float = 1.0, loudness_max: float = 2.0, - pr_min: float = 0.15, pr_max: float = 0.85, pf_min: float = -10., pf_max: float = 10., **kwargs: object) -> None: + pr_min: float = 0.15, pr_max: float = 0.85, pf_min: float = -10., pf_max: float = 10., + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -168,7 +171,8 @@ def __init__(self, epoch: int = 10000, pop_size: object = 100, loudness_min: flo self.pf_min = self.validator.check_float("pf_min", pf_min, [-10., 10.]) self.pf_max = self.validator.check_float("pf_max", pf_max, [0., 10.]) self.alpha = self.gamma = 0.9 - self.set_parameters(["epoch", "pop_size", "loudness_min", "loudness_max", "pr_min", "pr_max", "pf_min", "pf_max"]) + self.set_parameters( + ["epoch", "pop_size", "loudness_min", "loudness_max", "pr_min", "pr_max", "pf_min", "pf_max"]) self.sort_flag = False def generate_empty_agent(self, solution: np.ndarray = None) -> Agent: @@ -205,10 +209,12 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): ## Replace the old position by the new one when its has better fitness. ## and then update loudness and emission rate - if self.compare_target(pop_new[idx].target, self.pop[idx].target, self.problem.minmax) and self.generator.random() < pop_new[idx].loudness: + if self.compare_target(pop_new[idx].target, self.pop[idx].target, + self.problem.minmax) and self.generator.random() < pop_new[idx].loudness: loudness = self.alpha * pop_new[idx].loudness pulse_rate = pop_new[idx].pulse_rate * (1 - np.exp(-self.gamma * epoch)) - self.pop[idx].update(solution=pop_new[idx].solution, target=pop_new[idx].target, loudness=loudness, pulse_rate=pulse_rate) + self.pop[idx].update(solution=pop_new[idx].solution, target=pop_new[idx].target, loudness=loudness, + pulse_rate=pulse_rate) class DevBA(Optimizer): @@ -271,7 +277,8 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): pf = self.pf_min + (self.pf_max - self.pf_min) * self.generator.uniform() # Eq. 2 - self.dyn_list_velocity[idx] = self.generator.uniform() * self.dyn_list_velocity[idx] + (self.g_best.solution - self.pop[idx].solution) * pf # Eq. 3 + self.dyn_list_velocity[idx] = self.generator.uniform() * self.dyn_list_velocity[idx] + ( + self.g_best.solution - self.pop[idx].solution) * pf # Eq. 3 x = self.pop[idx].solution + self.dyn_list_velocity[idx] # Eq. 4 pos_new = self.correct_solution(x) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/swarm_based/BES.py b/mealpy/swarm_based/BES.py index 9a4c6494..d1548f86 100644 --- a/mealpy/swarm_based/BES.py +++ b/mealpy/swarm_based/BES.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -136,7 +137,8 @@ def evolve(self, epoch): pos_mean = np.mean(pos_list, axis=0) pop_new = [] for idx in range(0, self.pop_size): - pos_new = self.generator.uniform() * self.g_best.solution + x1_list[idx] * (self.pop[idx].solution - self.c1 * pos_mean) \ + pos_new = self.generator.uniform() * self.g_best.solution + x1_list[idx] * ( + self.pop[idx].solution - self.c1 * pos_mean) \ + y1_list[idx] * (self.pop[idx].solution - self.c2 * self.g_best.solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/swarm_based/BFO.py b/mealpy/swarm_based/BFO.py index 3e39d190..49efb2bd 100644 --- a/mealpy/swarm_based/BFO.py +++ b/mealpy/swarm_based/BFO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -56,8 +57,10 @@ class OriginalBFO(Optimizer): IEEE control systems magazine, 22(3), pp.52-67. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, Ci: float = 0.01, Ped: float = 0.25, Nc: int = 5, Ns: int = 4, - d_attract: float = 0.1, w_attract: float = 0.2, h_repels: float = 0.1, w_repels: float = 10, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, Ci: float = 0.01, Ped: float = 0.25, Nc: int = 5, + Ns: int = 4, + d_attract: float = 0.1, w_attract: float = 0.2, h_repels: float = 0.1, w_repels: float = 10, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -84,7 +87,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, Ci: float = 0.01, Pe self.w_attract = self.validator.check_float("w_attract", w_attract, (0, 1.0)) self.h_repels = self.validator.check_float("h_repels", h_repels, (0, 1.0)) self.w_repels = self.validator.check_float("w_repels", w_repels, (2.0, 20.0)) - self.set_parameters(["epoch", "pop_size", "Ci", "Ped", "Nc", "Ns", "d_attract", "w_attract", "h_repels", "w_repels"]) + self.set_parameters( + ["epoch", "pop_size", "Ci", "Ped", "Nc", "Ns", "d_attract", "w_attract", "h_repels", "w_repels"]) self.half_pop_size = int(self.pop_size / 2) self.is_parallelizable = False self.sort_flag = False @@ -249,9 +253,11 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): step_size = self.update_step_size__(self.pop, idx) for m in range(0, self.swim_length): # Ns - delta_i = (self.g_best.solution - self.pop[idx].solution) + (self.pop[idx].local_solution - self.pop[idx].solution) + delta_i = (self.g_best.solution - self.pop[idx].solution) + ( + self.pop[idx].local_solution - self.pop[idx].solution) delta = np.sqrt(np.abs(np.dot(delta_i, delta_i.T))) - unit_vector = self.generator.uniform(self.problem.lb, self.problem.ub) if delta == 0 else (delta_i / delta) + unit_vector = self.generator.uniform(self.problem.lb, self.problem.ub) if delta == 0 else ( + delta_i / delta) pos_new = self.pop[idx].solution + step_size * unit_vector pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) @@ -263,7 +269,8 @@ def evolve(self, epoch): self.pop[idx].update(local_solution=pos_new.copy(), local_target=agent.target.copy()) else: self.pop[idx].nutrients -= 1 - if self.pop[idx].nutrients > max(self.N_split, self.N_split + (len(self.pop) - self.pop_size) / self.N_adapt): + if self.pop[idx].nutrients > max(self.N_split, + self.N_split + (len(self.pop) - self.pop_size) / self.N_adapt): tt = self.generator.normal(0, 1, self.problem.n_dims) pos_new = tt * self.pop[idx].solution + (1 - tt) * (self.g_best.solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) diff --git a/mealpy/swarm_based/BSA.py b/mealpy/swarm_based/BSA.py index 268a88dd..3f822ab1 100644 --- a/mealpy/swarm_based/BSA.py +++ b/mealpy/swarm_based/BSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -50,7 +51,8 @@ class OriginalBSA(Optimizer): """ def __init__(self, epoch: int = 10000, pop_size: int = 100, ff: int = 10, pff: float = 0.8, - c1: float = 1.5, c2: float = 1.5, a1: float = 1.0, a2: float = 1.0, fc: float = 0.5, **kwargs: object) -> None: + c1: float = 1.5, c2: float = 1.5, a1: float = 1.0, a2: float = 1.0, fc: float = 0.5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -66,7 +68,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, ff: int = 10, pff: f super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.ff = self.validator.check_int("ff", ff, [2, int(self.pop_size/2)]) + self.ff = self.validator.check_int("ff", ff, [2, int(self.pop_size / 2)]) self.pff = self.validator.check_float("pff", pff, (0, 1.0)) self.c1 = self.validator.check_float("c1", c1, (0, 5.0)) self.c2 = self.validator.check_float("c2", c2, (0, 5.0)) @@ -110,11 +112,13 @@ def evolve(self, epoch): self.generator.uniform() * (self.pop[idx].local_solution - self.pop[idx].solution) + \ self.c2 * self.generator.uniform() * (self.g_best.solution - self.pop[idx].solution) else: # Birds keep vigilance. Eq. 2 - A1 = self.a1 * np.exp(-self.pop_size * self.pop[idx].local_target.fitness / (self.EPSILON + fit_sum)) + A1 = self.a1 * np.exp( + -self.pop_size * self.pop[idx].local_target.fitness / (self.EPSILON + fit_sum)) k = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) t1 = (fit_list[idx] - fit_list[k]) / (abs(fit_list[idx] - fit_list[k]) + self.EPSILON) A2 = self.a2 * np.exp(t1 * self.pop_size * fit_list[k] / (fit_sum + self.EPSILON)) - x_new = self.pop[idx].solution + A1 * self.generator.uniform(0, 1) * (pos_mean - self.pop[idx].solution) + \ + x_new = self.pop[idx].solution + A1 * self.generator.uniform(0, 1) * ( + pos_mean - self.pop[idx].solution) + \ A2 * self.generator.uniform(-1, 1) * (self.g_best.solution - self.pop[idx].solution) agent.solution = self.correct_solution(x_new) pop_new.append(agent) @@ -142,11 +146,13 @@ def evolve(self, epoch): if choose < 3: # Producing (Equation 5) for idx in range(int(self.pop_size / 2 + 1), self.pop_size): agent = self.pop[idx].copy() - x_new = self.pop[idx].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * self.pop[idx].solution + x_new = self.pop[idx].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * \ + self.pop[idx].solution agent.solution = self.correct_solution(x_new) pop_new[idx] = agent if choose == 1: - x_new = self.pop[min_idx].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * self.pop[min_idx].solution + x_new = self.pop[min_idx].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * \ + self.pop[min_idx].solution agent = self.pop[min_idx].copy() agent.solution = self.correct_solution(x_new) pop_new[min_idx] = agent @@ -161,12 +167,14 @@ def evolve(self, epoch): else: # Scrounging (Equation 6) for i in range(0, int(0.5 * self.pop_size)): agent = self.pop[i].copy() - x_new = self.pop[i].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * self.pop[i].solution + x_new = self.pop[i].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * self.pop[ + i].solution agent.solution = self.correct_solution(x_new) pop_new[i] = agent if choose == 4: agent = self.pop[min_idx].copy() - x_new = self.pop[min_idx].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * self.pop[min_idx].solution + x_new = self.pop[min_idx].solution + self.generator.uniform(self.problem.lb, self.problem.ub) * \ + self.pop[min_idx].solution agent.solution = self.correct_solution(x_new) for i in range(int(self.pop_size / 2 + 1), self.pop_size): if choose == 3 or min_idx != i: diff --git a/mealpy/swarm_based/BeesA.py b/mealpy/swarm_based/BeesA.py index 23129b59..9069bc6e 100644 --- a/mealpy/swarm_based/BeesA.py +++ b/mealpy/swarm_based/BeesA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -49,8 +50,10 @@ class CleverBookBeesA(Optimizer): [1] D. T. Pham, Ghanbarzadeh A., Koc E., Otri S., Rahim S., and M.Zaidi. The bees algorithm - a novel tool for complex optimisation problems. In Proceedings of IPROMS 2006 Conference, pages 454–461, 2006. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, n_elites: int = 16, n_others: int = 4, - patch_size: float = 5.0, patch_reduction: float = 0.985, n_sites: int = 3, n_elite_sites: int = 1, **kwargs: object) -> None: + patch_size: float = 5.0, patch_reduction: float = 0.985, n_sites: int = 3, n_elite_sites: int = 1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -71,7 +74,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_elites: int = 16, self.patch_reduction = self.validator.check_float("patch_reduction", patch_reduction, (0, 1.0)) self.n_sites = self.validator.check_int("n_sites", n_sites, [2, 5]) self.n_elite_sites = self.validator.check_int("n_elite_sites", n_elite_sites, [1, 3]) - self.set_parameters(["epoch", "pop_size", "n_elites", "n_others", "patch_size", "patch_reduction", "n_sites", "n_elite_sites"]) + self.set_parameters( + ["epoch", "pop_size", "n_elites", "n_others", "patch_size", "patch_reduction", "n_sites", "n_elite_sites"]) self.sort_flag = True def search_neighborhood__(self, parent=None, neigh_size=None): @@ -82,7 +86,8 @@ def search_neighborhood__(self, parent=None, neigh_size=None): for idx in range(0, neigh_size): t1 = self.generator.integers(0, len(parent.solution) - 1) new_bee = parent.solution.copy() - new_bee[t1] = (parent.solution[t1] + self.generator.uniform() * self.patch_size) if self.generator.uniform() < 0.5 \ + new_bee[t1] = (parent.solution[ + t1] + self.generator.uniform() * self.patch_size) if self.generator.uniform() < 0.5 \ else (parent.solution[t1] - self.generator.uniform() * self.patch_size) pos_new = self.correct_solution(new_bee) agent = self.generate_empty_agent(pos_new) @@ -178,11 +183,12 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, selected_site_ratio: # (Scout Bee Count or Population Size, Selected Sites Count) self.selected_site_ratio = self.validator.check_float("selected_site_ratio", selected_site_ratio, (0, 1.0)) self.elite_site_ratio = self.validator.check_float("elite_site_ratio", elite_site_ratio, (0, 1.0)) - self.selected_site_bee_ratio = self.validator.check_float("selected_site_bee_ratio", selected_site_bee_ratio, (0, 1.0)) + self.selected_site_bee_ratio = self.validator.check_float("selected_site_bee_ratio", selected_site_bee_ratio, + (0, 1.0)) self.elite_site_bee_ratio = self.validator.check_float("elite_site_bee_ratio", elite_site_bee_ratio, (0, 3.0)) self.dance_radius = self.validator.check_float("dance_radius", dance_radius, (0, 1.0)) self.dance_reduction = self.validator.check_float("dance_reduction", dance_reduction, (0, 1.0)) - self.set_parameters(["epoch", "pop_size", "selected_site_ratio", "elite_site_ratio", "selected_site_bee_ratio", + self.set_parameters(["epoch", "pop_size", "selected_site_ratio", "elite_site_ratio", "selected_site_bee_ratio", "elite_site_bee_ratio", "dance_radius", "dance_reduction"]) # Initial Value of Dance Radius self.dyn_radius = self.dance_radius diff --git a/mealpy/swarm_based/COA.py b/mealpy/swarm_based/COA.py index 68618195..1b353420 100644 --- a/mealpy/swarm_based/COA.py +++ b/mealpy/swarm_based/COA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -93,7 +94,8 @@ def evolve(self, epoch): for i in range(self.n_coyotes): rc1, rc2 = self.generator.choice(list(set(range(0, self.n_coyotes)) - {i}), 2, replace=False) # Try to update the social condition according to the alpha and the pack tendency(Eq. 12) - pos_new = self.pop_group[p][i].solution + self.generator.random() * (self.pop_group[p][0].solution - self.pop_group[p][rc1].solution) + \ + pos_new = self.pop_group[p][i].solution + self.generator.random() * ( + self.pop_group[p][0].solution - self.pop_group[p][rc1].solution) + \ self.generator.random() * (tendency - self.pop_group[p][rc2].solution) # Keep the coyotes in the search space (optimization problem constraint) pos_new = self.correct_solution(pos_new) @@ -111,7 +113,8 @@ def evolve(self, epoch): id_dad, id_mom = self.generator.choice(list(range(0, self.n_coyotes)), 2, replace=False) prob1 = (1. - self.ps) / 2. # Generate the pup considering intrinsic and extrinsic influence - pup = np.where(self.generator.random(self.problem.n_dims) < prob1, self.pop_group[p][id_dad].solution, self.pop_group[p][id_mom].solution) + pup = np.where(self.generator.random(self.problem.n_dims) < prob1, self.pop_group[p][id_dad].solution, + self.pop_group[p][id_mom].solution) # Eventual noise pos_new = self.generator.normal(0, 1) * pup pos_new = self.correct_solution(pos_new) @@ -134,7 +137,8 @@ def evolve(self, epoch): if self.generator.random() < self.p_leave: id_pack1, id_pack2 = self.generator.choice(list(range(0, self.n_packs)), 2, replace=False) id1, id2 = self.generator.choice(list(range(0, self.n_coyotes)), 2, replace=False) - self.pop_group[id_pack1][id1], self.pop_group[id_pack2][id2] = self.pop_group[id_pack2][id2], self.pop_group[id_pack1][id1] + self.pop_group[id_pack1][id1], self.pop_group[id_pack2][id2] = self.pop_group[id_pack2][id2], \ + self.pop_group[id_pack1][id1] # Update coyotes ages for id_pack in range(0, self.n_packs): diff --git a/mealpy/swarm_based/CSA.py b/mealpy/swarm_based/CSA.py index fd9e6b5c..0ffb191b 100644 --- a/mealpy/swarm_based/CSA.py +++ b/mealpy/swarm_based/CSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer diff --git a/mealpy/swarm_based/CSO.py b/mealpy/swarm_based/CSO.py index 39387198..5032975d 100644 --- a/mealpy/swarm_based/CSO.py +++ b/mealpy/swarm_based/CSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -82,7 +83,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, mixture_ratio: float self.w_min = self.validator.check_float("w_min", w_min, [0.1, 0.5]) self.w_max = self.validator.check_float("w_max", w_max, [0.5, 2.0]) self.selected_strategy = self.validator.check_int("selected_strategy", selected_strategy, [0, 4]) - self.set_parameters(["epoch", "pop_size", "mixture_ratio", "smp", "spc", "cdc", "srd", "c1", "w_min", "w_max", "selected_strategy"]) + self.set_parameters(["epoch", "pop_size", "mixture_ratio", "smp", "spc", "cdc", "srd", "c1", "w_min", "w_max", + "selected_strategy"]) self.sort_flag = False def generate_empty_agent(self, solution: np.ndarray = None) -> Agent: @@ -104,7 +106,8 @@ def seeking_mode__(self, cat): candidate_cats.append(cat.copy()) clone_cats = [cat.copy() for _ in range(self.smp - 1)] for clone in clone_cats: - idx = self.generator.choice(range(0, self.problem.n_dims), int(self.cdc * self.problem.n_dims), replace=False) + idx = self.generator.choice(range(0, self.problem.n_dims), int(self.cdc * self.problem.n_dims), + replace=False) pos_new1 = clone.solution * (1 + self.srd) pos_new2 = clone.solution * (1 - self.srd) pos_new = np.where(self.generator.random(self.problem.n_dims) < 0.5, pos_new1, pos_new2) diff --git a/mealpy/swarm_based/CoatiOA.py b/mealpy/swarm_based/CoatiOA.py index 0e4b015e..9c0d2bcc 100644 --- a/mealpy/swarm_based/CoatiOA.py +++ b/mealpy/swarm_based/CoatiOA.py @@ -44,6 +44,7 @@ class OriginalCoatiOA(Optimizer): [1] Dehghani, M., Montazeri, Z., Trojovská, E., & Trojovský, P. (2023). Coati Optimization Algorithm: A new bio-inspired metaheuristic algorithm for solving optimization problems. Knowledge-Based Systems, 259, 110011. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -65,9 +66,10 @@ def evolve(self, epoch): epoch (int): The current iteration """ # Phase1: Hunting and attacking strategy on iguana (Exploration Phase) - size2 = int(self.pop_size/2) + size2 = int(self.pop_size / 2) for idx in range(0, size2): - pos_new = self.pop[idx].solution + self.generator.random() * (self.g_best.solution - self.generator.integers(1, 3) * self.pop[idx].solution) # Eq. 4 + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.g_best.solution - self.generator.integers(1, 3) * self.pop[idx].solution) # Eq. 4 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): @@ -76,9 +78,11 @@ def evolve(self, epoch): for idx in range(size2, self.pop_size): iguana = self.generate_agent() if self.compare_target(iguana.target, self.pop[idx].target, self.problem.minmax): - pos_new = self.pop[idx].solution + self.generator.random() * (iguana.solution - self.generator.integers(1, 3) * self.pop[idx].solution) # Eq. 6 + pos_new = self.pop[idx].solution + self.generator.random() * ( + iguana.solution - self.generator.integers(1, 3) * self.pop[idx].solution) # Eq. 6 else: - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[idx].solution - iguana.solution) # Eq. 6 + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[idx].solution - iguana.solution) # Eq. 6 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): @@ -87,7 +91,8 @@ def evolve(self, epoch): # Phase2: The process of escaping from predators (Exploitation Phase) for idx in range(0, self.pop_size): LO, HI = self.problem.lb / epoch, self.problem.ub / epoch - pos_new = self.pop[idx].solution + (1 - 2 * self.generator.random()) * (LO + self.generator.random() * (HI - LO)) # Eq. 8 + pos_new = self.pop[idx].solution + (1 - 2 * self.generator.random()) * ( + LO + self.generator.random() * (HI - LO)) # Eq. 8 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/DMOA.py b/mealpy/swarm_based/DMOA.py index a26309c2..0a01ef0e 100644 --- a/mealpy/swarm_based/DMOA.py +++ b/mealpy/swarm_based/DMOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -46,7 +47,8 @@ class OriginalDMOA(Optimizer): Computer methods in applied mechanics and engineering, 391, 114570. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, n_baby_sitter: int = 3, peep: float = 2, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, n_baby_sitter: int = 3, peep: float = 2, + **kwargs: object) -> None: super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) @@ -70,7 +72,7 @@ def evolve(self, epoch): epoch (int): The current iteration """ ## Abandonment Counter - CF = (1. - epoch/self.epoch)**(2.*epoch/self.epoch) + CF = (1. - epoch / self.epoch) ** (2. * epoch / self.epoch) fit_list = np.array([agent.target.fitness for agent in self.pop]) mean_cost = np.mean(fit_list) fi = np.exp(-fit_list / mean_cost) @@ -95,7 +97,8 @@ def evolve(self, epoch): new_pos = self.correct_solution(new_pos) agent = self.generate_agent(new_pos) ## Sleeping mould - SM[idx] = (agent.target.fitness - self.pop[idx].target.fitness)/np.max([agent.target.fitness, self.pop[idx].target.fitness]) + SM[idx] = (agent.target.fitness - self.pop[idx].target.fitness) / np.max( + [agent.target.fitness, self.pop[idx].target.fitness]) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent else: @@ -198,7 +201,8 @@ def evolve(self, epoch): new_pos = self.correct_solution(new_pos) agent = self.generate_agent(new_pos) ## Sleeping mould - SM[idx] = (agent.target.fitness - self.pop[idx].target.fitness) / (np.max([agent.target.fitness, self.pop[idx].target.fitness]) + self.EPSILON) + SM[idx] = (agent.target.fitness - self.pop[idx].target.fitness) / ( + np.max([agent.target.fitness, self.pop[idx].target.fitness]) + self.EPSILON) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent else: diff --git a/mealpy/swarm_based/DO.py b/mealpy/swarm_based/DO.py index 69aed414..1c487b69 100644 --- a/mealpy/swarm_based/DO.py +++ b/mealpy/swarm_based/DO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -67,7 +68,8 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - _, (self.g_best, ), (self.g_worst, ) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) + _, (self.g_best,), (self.g_worst,) = self.get_special_agents(self.pop, n_best=1, n_worst=1, + minmax=self.problem.minmax) r = (self.problem.ub - self.problem.lb) / 4 + ((self.problem.ub - self.problem.lb) * (2 * epoch / self.epoch)) w = 0.9 - epoch * ((0.9 - 0.4) / self.epoch) @@ -126,7 +128,8 @@ def evolve(self, epoch): if np.any(dist_to_food > r): if neighbours_num > 1: temp = w * self.pop_delta[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * A + \ - self.generator.uniform(0, 1, self.problem.n_dims) * C + self.generator.uniform(0, 1, self.problem.n_dims) * S + self.generator.uniform(0, 1, self.problem.n_dims) * C + self.generator.uniform(0, 1, + self.problem.n_dims) * S temp = np.clip(temp, -1 * self.delta_max, self.delta_max) pos_delta_new = temp.copy() pos_new += temp diff --git a/mealpy/swarm_based/EHO.py b/mealpy/swarm_based/EHO.py index c9e20afa..190914af 100644 --- a/mealpy/swarm_based/EHO.py +++ b/mealpy/swarm_based/EHO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,8 @@ class OriginalEHO(Optimizer): In 2015 3rd international symposium on computational and business intelligence (ISCBI) (pp. 1-5). IEEE. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.5, beta: float = 0.5, n_clans: int = 5, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.5, beta: float = 0.5, n_clans: int = 5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -59,7 +61,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, alpha: float = 0.5, self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) self.alpha = self.validator.check_float("alpha", alpha, (0, 3.0)) self.beta = self.validator.check_float("beta", beta, (0, 1.0)) - self.n_clans = self.validator.check_int("n_clans", n_clans, [2, int(self.pop_size/5)]) + self.n_clans = self.validator.check_int("n_clans", n_clans, [2, int(self.pop_size / 5)]) self.set_parameters(["epoch", "pop_size", "alpha", "beta", "n_clans"]) self.n_individuals = int(self.pop_size / self.n_clans) self.sort_flag = False diff --git a/mealpy/swarm_based/EPC.py b/mealpy/swarm_based/EPC.py index 467e4bce..05a84ed9 100644 --- a/mealpy/swarm_based/EPC.py +++ b/mealpy/swarm_based/EPC.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -78,7 +79,8 @@ def initialize_variables(self): self.body_temperature = 308.15 # K (35°C) self.mu = 0.01 # Attenuation coefficient (can be tuned) # Calculate heat radiation using Stefan-Boltzmann law (Equation 6) - self.heat_radiation = (self.surface_area * self.emissivity * self.stefan_boltzmann * (self.body_temperature ** 4)) + self.heat_radiation = ( + self.surface_area * self.emissivity * self.stefan_boltzmann * (self.body_temperature ** 4)) def calculate_attractiveness(self, heat_radiation: float, distance: float) -> float: """ diff --git a/mealpy/swarm_based/ESOA.py b/mealpy/swarm_based/ESOA.py index 8f4e797c..6e941315 100644 --- a/mealpy/swarm_based/ESOA.py +++ b/mealpy/swarm_based/ESOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -89,13 +90,13 @@ def evolve(self, epoch): # Individual Direction p_d = self.pop[idx].local_solution - self.pop[idx].solution p_d = p_d * (self.pop[idx].local_target.fitness - self.pop[idx].target.fitness) - p_d = p_d / (np.sum(p_d) **2 + self.EPSILON) + p_d = p_d / (np.sum(p_d) ** 2 + self.EPSILON) d_p = p_d + self.pop[idx].g # Group Direction c_d = self.g_best.solution - self.pop[idx].solution c_d = c_d * (self.g_best.target.fitness - self.pop[idx].target.fitness) - c_d = c_d / (np.sum(c_d)**2 + self.EPSILON) + c_d = c_d / (np.sum(c_d) ** 2 + self.EPSILON) d_g = c_d + self.g_best.g # Gradient Estimation @@ -105,7 +106,7 @@ def evolve(self, epoch): g = g / (np.sum(g) + self.EPSILON) self.pop[idx].m = self.beta1 * self.pop[idx].m + (1 - self.beta1) * g - self.pop[idx].v = self.beta2 * self.pop[idx].v + (1 - self.beta2) * g**2 + self.pop[idx].v = self.beta2 * self.pop[idx].v + (1 - self.beta2) * g ** 2 self.pop[idx].weights -= self.pop[idx].m / (np.sqrt(self.pop[idx].v) + self.EPSILON) # Advice Forward @@ -114,7 +115,7 @@ def evolve(self, epoch): y_0 = self.get_target(x_0) # Random Search - r3 = self.generator.uniform(-np.pi/2, np.pi/2, self.problem.n_dims) + r3 = self.generator.uniform(-np.pi / 2, np.pi / 2, self.problem.n_dims) x_n = self.pop[idx].solution + np.tan(r3) * hop / epoch * 0.5 x_n = self.correct_solution(x_n) y_n = self.get_target(x_n) @@ -147,7 +148,8 @@ def evolve(self, epoch): if self.compare_target(y_best, self.pop[idx].local_target, self.problem.minmax): self.pop[idx].local_solution = x_best self.pop[idx].local_target = y_best - self.pop[idx].g = (np.sum(self.pop[idx].weights * self.pop[idx].solution) - self.pop[idx].target.fitness) * self.pop[idx].solution + self.pop[idx].g = (np.sum(self.pop[idx].weights * self.pop[idx].solution) - self.pop[ + idx].target.fitness) * self.pop[idx].solution else: if self.generator.random() < 0.3: self.pop[idx].solution = x_best diff --git a/mealpy/swarm_based/FA.py b/mealpy/swarm_based/FA.py index 521a3a36..8d72c1ce 100644 --- a/mealpy/swarm_based/FA.py +++ b/mealpy/swarm_based/FA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -95,7 +96,8 @@ def evolve(self, epoch): pop_new = [] for j in range(0, si_): pos_new = self.pop[idx].solution.copy() - list_idx = self.generator.choice(range(0, self.problem.n_dims), round(self.generator.uniform() * self.problem.n_dims), replace=False) + list_idx = self.generator.choice(range(0, self.problem.n_dims), + round(self.generator.uniform() * self.problem.n_dims), replace=False) displacement = Ai * self.generator.uniform(-1, 1) pos_new[list_idx] = pos_new[list_idx] + displacement pos_new = np.where(np.logical_or(pos_new < self.problem.lb, pos_new > self.problem.ub), @@ -110,7 +112,8 @@ def evolve(self, epoch): for _ in range(0, self.m_sparks): idx = self.generator.integers(0, self.pop_size) pos_new = self.pop[idx].solution.copy() - list_idx = self.generator.choice(range(0, self.problem.n_dims), round(self.generator.uniform() * self.problem.n_dims), replace=False) + list_idx = self.generator.choice(range(0, self.problem.n_dims), + round(self.generator.uniform() * self.problem.n_dims), replace=False) pos_new[list_idx] = pos_new[list_idx] + self.generator.normal(0, 1, len(list_idx)) # Gaussian condition = np.logical_or(pos_new < self.problem.lb, pos_new > self.problem.ub) pos_true = self.problem.lb + np.abs(pos_new) % (self.problem.ub - self.problem.lb) diff --git a/mealpy/swarm_based/FDO.py b/mealpy/swarm_based/FDO.py index eb256e2e..5c7478da 100644 --- a/mealpy/swarm_based/FDO.py +++ b/mealpy/swarm_based/FDO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,6 +44,7 @@ class OriginalFDO(Optimizer): [1] Abdullah, J. M., & Ahmed, T. (2019). Fitness dependent optimizer: inspired by the bee swarming reproductive process. IEEe Access, 7, 43473-43486. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, weight_factor=0.1, **kwargs: object) -> None: """ Args: diff --git a/mealpy/swarm_based/FFA.py b/mealpy/swarm_based/FFA.py index 3f7c912e..6b534403 100644 --- a/mealpy/swarm_based/FFA.py +++ b/mealpy/swarm_based/FFA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -48,7 +49,8 @@ class OriginalFFA(Optimizer): """ def __init__(self, epoch: int = 10000, pop_size: int = 100, gamma: float = 0.001, beta_base: float = 2, - alpha: float = 0.2, alpha_damp: float = 0.99, delta: float = 0.05, exponent: int = 2, **kwargs: object) -> None: + alpha: float = 0.2, alpha_damp: float = 0.99, delta: float = 0.05, exponent: int = 2, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -96,7 +98,8 @@ def evolve(self, epoch): beta = self.beta_base * np.exp(-self.gamma * rij ** self.exponent) # Mutation Vector mutation_vector = self.delta * self.generator.uniform(0, 1, self.problem.n_dims) - temp = np.matmul((self.pop[j].solution - agent.solution), self.generator.uniform(0, 1, (self.problem.n_dims, self.problem.n_dims))) + temp = np.matmul((self.pop[j].solution - agent.solution), + self.generator.uniform(0, 1, (self.problem.n_dims, self.problem.n_dims))) pos_new = agent.solution + self.dyn_alpha * mutation_vector + beta * temp pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) diff --git a/mealpy/swarm_based/FFO.py b/mealpy/swarm_based/FFO.py index e84c07a0..a74722b7 100644 --- a/mealpy/swarm_based/FFO.py +++ b/mealpy/swarm_based/FFO.py @@ -4,7 +4,6 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from mealpy.optimizer import Optimizer @@ -45,6 +44,7 @@ class OriginalFFO(Optimizer): [1] Trojovská, E., Dehghani, M., & Trojovský, P. (2022). Fennec Fox Optimization: A New Nature-Inspired Optimization Algorithm. IEEE Access, 10, 84417-84443. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -77,9 +77,11 @@ def evolve(self, epoch): # PHASE 2: ESCAPE STRATEGY FROM THE PREDATORS’ ATTACK (EXPLORATION) kk = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[idx].solution - self.pop[kk].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/FOA.py b/mealpy/swarm_based/FOA.py index 84825fc9..0f7f6d33 100644 --- a/mealpy/swarm_based/FOA.py +++ b/mealpy/swarm_based/FOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -40,6 +41,7 @@ class OriginalFOA(Optimizer): [1] Pan, W.T., 2012. A new fruit fly optimization algorithm: taking the financial distress model as an example. Knowledge-Based Systems, 26, pp.69-74. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -71,7 +73,8 @@ def evolve(self, epoch): """ pop_new = [] for idx in range(0, self.pop_size): - pos_new = self.pop[idx].solution + self.generator.random() * self.generator.normal(self.problem.lb, self.problem.ub) + pos_new = self.pop[idx].solution + self.generator.random() * self.generator.normal(self.problem.lb, + self.problem.ub) pos_new = self.norm_consecutive_adjacent__(pos_new) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/swarm_based/FOX.py b/mealpy/swarm_based/FOX.py index 97f578c8..9bb35c28 100644 --- a/mealpy/swarm_based/FOX.py +++ b/mealpy/swarm_based/FOX.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -47,7 +48,9 @@ class OriginalFOX(Optimizer): ~~~~~~~~~~ [1] Mohammed, H., & Rashid, T. (2023). FOX: a FOX-inspired optimization algorithm. Applied Intelligence, 53(1), 1030-1050. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 0.18, c2: float = 0.82, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 0.18, c2: float = 0.82, + **kwargs: object) -> None: super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) @@ -130,6 +133,7 @@ class DevFOX(Optimizer): ~~~~~~~~~~ [1] Mohammed, H., & Rashid, T. (2023). FOX: a FOX-inspired optimization algorithm. Applied Intelligence, 53(1), 1030-1050. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 0.18, c2: float = 0.82, pp=0.5, **kwargs: object) -> None: super().__init__(**kwargs) diff --git a/mealpy/swarm_based/GJO.py b/mealpy/swarm_based/GJO.py index f28483d6..b5e51ee9 100644 --- a/mealpy/swarm_based/GJO.py +++ b/mealpy/swarm_based/GJO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -40,6 +41,7 @@ class OriginalGJO(Optimizer): [1] Chopra, N., & Ansari, M. M. (2022). Golden jackal optimization: A novel nature-inspired optimizer for engineering applications. Expert Systems with Applications, 198, 116924. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -59,7 +61,7 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - E1 = 1.5*(1.-(epoch/self.epoch)) + E1 = 1.5 * (1. - (epoch / self.epoch)) RL = self.get_levy_flight_step(beta=1.5, multiplier=0.05, size=(self.pop_size, self.problem.n_dims), case=-1) _, (male, female), _ = self.get_special_agents(self.pop, n_best=2, n_worst=1, minmax=self.problem.minmax) pop_new = [] @@ -68,14 +70,14 @@ def evolve(self, epoch): female_pos = female.solution.copy() for jdx in range(0, self.problem.n_dims): r1 = self.generator.random() - E0 = 2*r1 - 1 + E0 = 2 * r1 - 1 E = E1 * E0 - if np.abs(E) < 1: # EXPLOITATION - t1 = np.abs( (RL[idx, jdx] * male.solution[jdx] - self.pop[idx].solution[jdx]) ) - male_pos[jdx] = male.solution[jdx] - E*t1 - t2 = np.abs( (RL[idx, jdx] * female.solution[jdx] - self.pop[idx].solution[jdx]) ) - female_pos[jdx] = female.solution[jdx] - E*t2 - else: # EXPLORATION + if np.abs(E) < 1: # EXPLOITATION + t1 = np.abs((RL[idx, jdx] * male.solution[jdx] - self.pop[idx].solution[jdx])) + male_pos[jdx] = male.solution[jdx] - E * t1 + t2 = np.abs((RL[idx, jdx] * female.solution[jdx] - self.pop[idx].solution[jdx])) + female_pos[jdx] = female.solution[jdx] - E * t2 + else: # EXPLORATION t1 = np.abs((male.solution[jdx] - RL[idx, jdx] * self.pop[idx].solution[jdx])) male_pos[jdx] = male.solution[jdx] - E * t1 t2 = np.abs((female.solution[jdx] - RL[idx, jdx] * self.pop[idx].solution[jdx])) diff --git a/mealpy/swarm_based/GOA.py b/mealpy/swarm_based/GOA.py index 3a6e9d22..cdabda49 100644 --- a/mealpy/swarm_based/GOA.py +++ b/mealpy/swarm_based/GOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,8 @@ class OriginalGOA(Optimizer): theory and application. Advances in Engineering Software, 105, pp.30-47. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c_min: float = 0.00004, c_max: float = 2.0, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, c_min: float = 0.00004, c_max: float = 2.0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -81,13 +83,15 @@ def evolve(self, epoch): S_i_total = np.zeros(self.problem.n_dims) for j in range(0, self.pop_size): dist = np.sqrt(np.sum((self.pop[idx].solution - self.pop[j].solution) ** 2)) - r_ij_vector = (self.pop[idx].solution - self.pop[j].solution) / (dist + self.EPSILON) # xj - xi / dij in Eq.(2.7) + r_ij_vector = (self.pop[idx].solution - self.pop[j].solution) / ( + dist + self.EPSILON) # xj - xi / dij in Eq.(2.7) xj_xi = 2 + np.remainder(dist, 2) # |xjd - xid| in Eq. (2.7) ## The first part inside the big bracket in Eq. (2.7) 16 955 230 764 212 047 193 643 ran = (c / 2) * (self.problem.ub - self.problem.lb) s_ij = ran * self.s_function__(xj_xi) * r_ij_vector S_i_total += s_ij - x_new = c * self.generator.normal(0, 1, self.problem.n_dims) * S_i_total + self.g_best.solution # Eq. (2.7) in the paper + x_new = c * self.generator.normal(0, 1, + self.problem.n_dims) * S_i_total + self.g_best.solution # Eq. (2.7) in the paper pos_new = self.correct_solution(x_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/swarm_based/GTO.py b/mealpy/swarm_based/GTO.py index 07c4cbef..1f1f6a8f 100644 --- a/mealpy/swarm_based/GTO.py +++ b/mealpy/swarm_based/GTO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,9 @@ class OriginalGTO(Optimizer): [1] Sadeeq, H. T., & Abdulazeez, A. M. (2022). Giant Trevally Optimizer (GTO): A Novel Metaheuristic Algorithm for Global Optimization and Challenging Engineering Problems. IEEE Access, 10, 121615-121640. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, A: float = 0.4, H: float = 2.0, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, A: float = 0.4, H: float = 2.0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -72,7 +75,8 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): # Eq.(4) - pos_new = self.g_best.solution * self.generator.random() + ((self.problem.ub - self.problem.lb) * self.generator.random() + self.problem.lb) * \ + pos_new = self.g_best.solution * self.generator.random() + ( + (self.problem.ub - self.problem.lb) * self.generator.random() + self.problem.lb) * \ self.get_levy_flight_step(beta=1.5, multiplier=0.01, size=self.problem.n_dims, case=-1) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -91,7 +95,7 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): r3 = self.generator.random() - pos_new = self.g_best.solution * self.A * r3 + pos_m - self.pop[idx].solution * r3 # Eq. 7 + pos_new = self.g_best.solution * self.A * r3 + pos_m - self.pop[idx].solution * r3 # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -104,14 +108,14 @@ def evolve(self, epoch): _, self.g_best = self.update_global_best_agent(self.pop, save=False) # Step 3: Attacking - H = self.generator.random() * self.H * (1 - epoch / self.epoch) # Eq.(15) + H = self.generator.random() * self.H * (1 - epoch / self.epoch) # Eq.(15) pop_new = [] for idx in range(0, self.pop_size): # the distance between the prey and the attacker, and can be calculated using (12): dist = np.sum(np.abs(self.g_best.solution - self.pop[idx].solution)) theta2 = (360 - 0) * self.generator.random() + 0 - theta1 = (1.33 / 1.00029) * np.sin(np.radians(theta2)) # calculate theta_1 using (10) - VD = np.sin(np.radians(theta1)) * dist # Eq. 11 + theta1 = (1.33 / 1.00029) * np.sin(np.radians(theta2)) # calculate theta_1 using (10) + VD = np.sin(np.radians(theta1)) * dist # Eq. 11 # Eq. (13) pos_new = self.pop[idx].solution * np.sin(np.radians(theta2)) * self.pop[idx].target.fitness + VD + H pos_new = self.correct_solution(pos_new) @@ -163,6 +167,7 @@ class Matlab102GTO(Optimizer): [1] Sadeeq, H. T., & Abdulazeez, A. M. (2022). Giant Trevally Optimizer (GTO): A Novel Metaheuristic Algorithm for Global Optimization and Challenging Engineering Problems. IEEE Access, 10, 121615-121640. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -186,8 +191,9 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): # foraging movement patterns of giant trevallies are simulated using Eq.(4) - pos_new = self.g_best.solution * self.generator.random() + ((self.problem.ub - self.problem.lb) * self.generator.random() + self.problem.lb) * \ - self.get_levy_flight_step(beta=1.5, multiplier=0.01, size=self.problem.n_dims, case=-1) + pos_new = self.g_best.solution * self.generator.random() + ( + (self.problem.ub - self.problem.lb) * self.generator.random() + self.problem.lb) * \ + self.get_levy_flight_step(beta=1.5, multiplier=0.01, size=self.problem.n_dims, case=-1) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -207,7 +213,7 @@ def evolve(self, epoch): # In the choosing area step, giant trevallies identify and select the best area in terms of # the amount of food (seabirds) within the selected search space where they can hunt for prey. r3 = self.generator.random() - pos_new = self.g_best.solution * A * r3 + pos_m - self.pop[idx].solution * r3 # Eq. 7 + pos_new = self.g_best.solution * A * r3 + pos_m - self.pop[idx].solution * r3 # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -221,16 +227,16 @@ def evolve(self, epoch): self.pop, self.g_best = self.update_global_best_agent(self.pop, save=False) # Step 3: Attacking - H = self.generator.random() * 2. * (1. - epoch / self.epoch) # Eq.(15) + H = self.generator.random() * 2. * (1. - epoch / self.epoch) # Eq.(15) pop_new = [] for idx in range(0, self.pop_size): # the distance between the prey and the attacker, and can be calculated using (12): dist = np.sum(np.abs(self.g_best.solution - self.pop[idx].solution)) theta2 = (360 - 0) * self.generator.random() + 0 - theta1 = 1.3296 * np.sin(np.radians(theta2)) # calculate theta_1 using (10) + theta1 = 1.3296 * np.sin(np.radians(theta2)) # calculate theta_1 using (10) # visual distortion indicates the apparent height of the bird, which is always seen # to be higher than its actual height due to the refraction of the light. - VD = np.sin(np.radians(theta1)) * dist # Eq. 11 + VD = np.sin(np.radians(theta1)) * dist # Eq. 11 # the behavior of giant trevally when chasing and jumping out of the water is mathematically simulated using (13) pos_new = self.pop[idx].solution * np.sin(np.radians(theta2)) * self.pop[idx].target.fitness + VD + H pos_new = self.correct_solution(pos_new) @@ -282,6 +288,7 @@ class Matlab101GTO(Optimizer): [1] Sadeeq, H. T., & Abdulazeez, A. M. (2022). Giant Trevally Optimizer (GTO): A Novel Metaheuristic Algorithm for Global Optimization and Challenging Engineering Problems. IEEE Access, 10, 121615-121640. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -308,8 +315,10 @@ def evolve(self, epoch): if idx == jdx: continue # foraging movement patterns of giant trevallies are simulated using Eq.(4) - pos_new = self.g_best.solution * self.generator.random() + ((self.problem.ub - self.problem.lb) * self.generator.random() + - self.problem.lb) * self.get_levy_flight_step(beta=1.5, multiplier=0.01, size=self.problem.n_dims, case=-1) + pos_new = self.g_best.solution * self.generator.random() + ( + (self.problem.ub - self.problem.lb) * self.generator.random() + + self.problem.lb) * self.get_levy_flight_step(beta=1.5, multiplier=0.01, + size=self.problem.n_dims, case=-1) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -328,7 +337,7 @@ def evolve(self, epoch): # In the choosing area step, giant trevallies identify and select the best area in terms of # the amount of food (seabirds) within the selected search space where they can hunt for prey. r3 = self.generator.random() - pos_new = self.g_best.solution * A * r3 + pos_m - self.pop[idx].solution * r3 # Eq. 7 + pos_new = self.g_best.solution * A * r3 + pos_m - self.pop[idx].solution * r3 # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -341,7 +350,7 @@ def evolve(self, epoch): _, self.g_best = self.update_global_best_agent(self.pop, save=False) # Step 3: Attacking - H = self.generator.random() * 2. * (1.0 - epoch / self.epoch) # Eq.(15) + H = self.generator.random() * 2. * (1.0 - epoch / self.epoch) # Eq.(15) for idx in range(0, self.pop_size): pop_new = [] for jdx in range(0, self.pop_size): @@ -350,10 +359,10 @@ def evolve(self, epoch): # the distance between the prey and the attacker, and can be calculated using (12): dist = np.sum(np.abs(self.g_best.solution - self.pop[idx].solution)) theta2 = (360 - 0) * self.generator.random() + 0 - theta1 = 1.3296 * np.sin(np.radians(theta2)) # calculate theta_1 using (10) + theta1 = 1.3296 * np.sin(np.radians(theta2)) # calculate theta_1 using (10) # visual distortion indicates the apparent height of the bird, which is always seen # to be higher than its actual height due to the refraction of the light. - VD = np.sin(np.radians(theta1)) * dist # Eq. 11 + VD = np.sin(np.radians(theta1)) * dist # Eq. 11 # the behavior of giant trevally when chasing and jumping out of the water is mathematically simulated using (13) pos_new = self.pop[idx].solution * np.sin(np.radians(theta2)) * self.pop[idx].target.fitness + VD + H pos_new = self.correct_solution(pos_new) diff --git a/mealpy/swarm_based/GWO.py b/mealpy/swarm_based/GWO.py index 21756e4f..5805b003 100644 --- a/mealpy/swarm_based/GWO.py +++ b/mealpy/swarm_based/GWO.py @@ -5,9 +5,10 @@ # --------------------------------------------------% import numpy as np + +from mealpy.optimizer import Optimizer from mealpy.utils.chaotic import ChaoticMap as CM from mealpy.utils.fuzzy import FuzzySystem as FS -from mealpy.optimizer import Optimizer class OriginalGWO(Optimizer): @@ -244,7 +245,8 @@ def evolve(self, epoch): da = self.generator.random() * np.abs(C1 * list_best[0].solution - self.pop[idx].solution) else: P, L = self.generator.random(), self.generator.uniform(-1, 1) - da = P * np.exp(self.bb * L) * np.cos(2*np.pi*L) * np.abs(C1 * list_best[0].solution - self.pop[idx].solution) + da = P * np.exp(self.bb * L) * np.cos(2 * np.pi * L) * np.abs( + C1 * list_best[0].solution - self.pop[idx].solution) X1 = list_best[0].solution - A1 * da X2 = list_best[1].solution - A2 * np.abs(C2 * list_best[1].solution - self.pop[idx].solution) X3 = list_best[2].solution - A3 * np.abs(C3 * list_best[2].solution - self.pop[idx].solution) @@ -297,7 +299,8 @@ class IGWO(OriginalGWO): Engineering with Computers. 34. 10.1007/s00366-017-0567-1. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, a_min: float = 0.02, a_max: float = 2.2, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, a_min: float = 0.02, a_max: float = 2.2, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -404,7 +407,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) self.chaotic_name = self.validator.check_str("chaotic_name", chaotic_name, ChaoticGWO.CHAOTIC_MAPS.keys()) - self.initial_chaotic_value = self.validator.check_float("initial_chaotic_value", initial_chaotic_value, [0.0, 1.0]) + self.initial_chaotic_value = self.validator.check_float("initial_chaotic_value", initial_chaotic_value, + [0.0, 1.0]) self.set_parameters(["epoch", "pop_size", "chaotic_name", "initial_chaotic_value"]) self.sort_flag = False @@ -598,7 +602,7 @@ def evolve(self, epoch): epoch (int): The current iteration """ # linearly decreased from 2 to 0 - a = 2 * (1. - (epoch / self.epoch)**self.explore_factor) + a = 2 * (1. - (epoch / self.epoch) ** self.explore_factor) pop_sorted, list_best, _ = self.get_special_agents(self.pop, n_best=3, minmax=self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): @@ -886,15 +890,16 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): # Try explorative equation first r1, r2, r3, r4, r5 = self.generator.random(5) - if r5 >= 0.5: # Exploration around random wolf + if r5 >= 0.5: # Exploration around random wolf # Select random wolf from population jdx = self.generator.choice(list(set(range(self.pop_size)) - {idx})) x_rand = self.pop[jdx].solution pos_new = x_rand - r1 * np.abs(x_rand - 2 * r2 * self.pop[idx].solution) - else: # Exploration around alpha wolf + else: # Exploration around alpha wolf # Calculate average position of all wolves x_avg = np.mean([agent.solution for agent in self.pop], axis=0) - pos_new = (list_best[0].solution - x_avg) - r3 * (self.problem.lb + r4 * (self.problem.ub - self.problem.lb)) + pos_new = (list_best[0].solution - x_avg) - r3 * ( + self.problem.lb + r4 * (self.problem.ub - self.problem.lb)) # Apply boundary constraints pos_new = self.correct_solution(pos_new) tar_new = self.get_target(pos_new) @@ -934,7 +939,7 @@ def evolve(self, epoch): # Replace worst 3 wolves with opposite solutions if they are better for idx in range(0, 3): - if self.compare_target(obl_pop[idx].target, self.pop[indices[-3+idx]].target, self.problem.minmax): + if self.compare_target(obl_pop[idx].target, self.pop[indices[-3 + idx]].target, self.problem.minmax): self.pop[idx] = obl_pop[idx] @@ -999,7 +1004,8 @@ def initialization(self) -> None: agent_opposite.target = self.get_target(pos_opposite) pop_opposite.append(agent_opposite) # Combine original and opposite populations - self.pop = self.get_sorted_and_trimmed_population(self.pop + pop_opposite, self.pop_size, minmax=self.problem.minmax) + self.pop = self.get_sorted_and_trimmed_population(self.pop + pop_opposite, self.pop_size, + minmax=self.problem.minmax) def evolve(self, epoch): """ @@ -1009,7 +1015,7 @@ def evolve(self, epoch): epoch (int): The current iteration """ # linearly decreased from 2 to 0 - a = 2. * (1 - (epoch / self.epoch)**self.miu_factor) + a = 2. * (1 - (epoch / self.epoch) ** self.miu_factor) _, list_best, _ = self.get_special_agents(self.pop, n_best=3, minmax=self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): @@ -1043,7 +1049,8 @@ def evolve(self, epoch): agent_opposite.target = self.get_target(pos_opposite) pop_opposite.append(agent_opposite) # Combine original and opposite populations - self.pop = self.get_sorted_and_trimmed_population(self.pop + pop_opposite, self.pop_size, minmax=self.problem.minmax) + self.pop = self.get_sorted_and_trimmed_population(self.pop + pop_opposite, self.pop_size, + minmax=self.problem.minmax) class ER_GWO(Optimizer): @@ -1096,7 +1103,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) self.a_initial = self.validator.check_float("a_initial", a_initial, [0.0, 10.0]) self.a_final = self.validator.check_float("a_final", a_final, [0.0, self.a_initial]) - self.miu_factor = self.validator.check_float("miu_factor", miu_factor, [1.0001, 1.01]) # Required in paper + self.miu_factor = self.validator.check_float("miu_factor", miu_factor, [1.0001, 1.01]) # Required in paper self.set_parameters(["epoch", "pop_size", "a_initial", "a_final", "miu_factor"]) self.sort_flag = False @@ -1204,8 +1211,8 @@ def cauchy_gaussian_mutation(self, best, leader, epoch): else: sigma = 1.0 # Generate Cauchy and Gaussian random variables - c_rand = self.generator.standard_cauchy(size=self.problem.n_dims) * sigma**2 + 0 - g_rand = self.generator.normal(loc=0, scale=sigma**2, size=self.problem.n_dims) + c_rand = self.generator.standard_cauchy(size=self.problem.n_dims) * sigma ** 2 + 0 + g_rand = self.generator.normal(loc=0, scale=sigma ** 2, size=self.problem.n_dims) # Apply mutation (equation 8) mutated_pos = leader.solution * (1 + eps1 * c_rand + eps2 * g_rand) @@ -1253,7 +1260,8 @@ def evolve(self, epoch): else: # Exploration around alpha wolf # Calculate average position of all wolves x_avg = np.mean([agent.solution for agent in self.pop], axis=0) - pos_new = (list_best[0].solution - x_avg) - r3 * (self.problem.lb + r4 * (self.problem.ub - self.problem.lb)) + pos_new = (list_best[0].solution - x_avg) - r3 * ( + self.problem.lb + r4 * (self.problem.ub - self.problem.lb)) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) diff --git a/mealpy/swarm_based/HBA.py b/mealpy/swarm_based/HBA.py index c8e280f4..4dc425ee 100644 --- a/mealpy/swarm_based/HBA.py +++ b/mealpy/swarm_based/HBA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -54,8 +55,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> self.sort_flag = False def initialize_variables(self): - self.beta = 6 # the ability of HB to get the food Eq.(4) - self.C = 2 # constant in Eq. (3) + self.beta = 6 # the ability of HB to get the food Eq.(4) + self.C = 2 # constant in Eq. (3) def get_intensity__(self, best, pop): size = len(pop) @@ -78,8 +79,8 @@ def evolve(self, epoch): epoch (int): The current iteration """ tt = self.epoch - alpha= self.C * np.exp(-tt/self.epoch) # density factor in Eq. (3) - I = self.get_intensity__(self.g_best, self.pop) # intensity in Eq. (2) + alpha = self.C * np.exp(-tt / self.epoch) # density factor in Eq. (3) + I = self.get_intensity__(self.g_best, self.pop) # intensity in Eq. (2) pop_new = [] for idx in range(0, self.pop_size): r = self.generator.random() @@ -90,7 +91,8 @@ def evolve(self, epoch): r5 = self.generator.random(self.problem.n_dims) r6 = self.generator.random(self.problem.n_dims) r7 = self.generator.random(self.problem.n_dims) - temp1 = self.g_best.solution + F * self.beta * I[idx] * self.g_best.solution + F*r3*alpha*di*np.abs(np.cos(2*np.pi*r4) * (1 - np.cos(2*np.pi*r5))) + temp1 = self.g_best.solution + F * self.beta * I[idx] * self.g_best.solution + F * r3 * alpha * di * np.abs( + np.cos(2 * np.pi * r4) * (1 - np.cos(2 * np.pi * r5))) temp2 = self.g_best.solution + F * r7 * alpha * di pos_new = np.where(r6 < 0.5, temp1, temp2) pos_new = self.correct_solution(pos_new) diff --git a/mealpy/swarm_based/HGS.py b/mealpy/swarm_based/HGS.py index 352611d1..ca1a14e2 100644 --- a/mealpy/swarm_based/HGS.py +++ b/mealpy/swarm_based/HGS.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -45,7 +46,8 @@ class OriginalHGS(Optimizer): deep analysis, perspectives, and towards performance shifts. Expert Systems with Applications, 177, p.114864. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, PUP: float = 0.08, LH: float = 10000, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, PUP: float = 0.08, LH: float = 10000, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -98,11 +100,11 @@ def evolve(self, epoch): """ ## Eq. (2.2) ### Find the current best and current worst - _, (g_best, ), (g_worst, ) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) + _, (g_best,), (g_worst,) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) pop = self.update_hunger_value__(self.pop, g_best, g_worst) ## Eq. (2.4) - shrink = 2 * (1 - epoch / self.epoch) + shrink = 2 * (1 - epoch / self.epoch) total_hunger = np.sum([pop[idx].hunger for idx in range(0, self.pop_size)]) pop_new = [] diff --git a/mealpy/swarm_based/HHO.py b/mealpy/swarm_based/HHO.py index 2ba2ef90..7090a2c4 100644 --- a/mealpy/swarm_based/HHO.py +++ b/mealpy/swarm_based/HHO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -72,7 +73,8 @@ def evolve(self, epoch): # Harris' hawks perch randomly based on 2 strategy: if self.generator.random() >= 0.5: # perch based on other family members X_rand = self.pop[self.generator.integers(0, self.pop_size)].solution.copy() - pos_new = X_rand - self.generator.uniform() * np.abs(X_rand - 2 * self.generator.uniform() * self.pop[idx].solution) + pos_new = X_rand - self.generator.uniform() * np.abs( + X_rand - 2 * self.generator.uniform() * self.pop[idx].solution) else: # perch on a random tall tree (random site inside group's home range) X_m = np.mean([x.solution for x in self.pop]) pos_new = (self.g_best.solution - X_m) - self.generator.uniform() * \ diff --git a/mealpy/swarm_based/JA.py b/mealpy/swarm_based/JA.py index 6cdef462..492739c1 100644 --- a/mealpy/swarm_based/JA.py +++ b/mealpy/swarm_based/JA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -56,10 +57,11 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - _, (g_best, ), (g_worst, ) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) + _, (g_best,), (g_worst,) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (g_best.solution - np.abs(self.pop[idx].solution)) + \ + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + g_best.solution - np.abs(self.pop[idx].solution)) + \ self.generator.normal() * (g_worst.solution - np.abs(self.pop[idx].solution)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -119,12 +121,13 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - _, (g_best, ), (g_worst, ) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) + _, (g_best,), (g_worst,) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): pos_new = self.pop[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ (g_best.solution - np.abs(self.pop[idx].solution)) - \ - self.generator.uniform(0, 1, self.problem.n_dims) * (g_worst.solution - np.abs(self.pop[idx].solution)) + self.generator.uniform(0, 1, self.problem.n_dims) * ( + g_worst.solution - np.abs(self.pop[idx].solution)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -168,6 +171,7 @@ class LevyJA(DevJA): [1] Iacca, G., dos Santos Junior, V.C. and de Melo, V.V., 2021. An improved Jaya optimization algorithm with Lévy flight. Expert Systems with Applications, 165, p.113902. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -184,7 +188,7 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - _, (g_best, ), (g_worst, ) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) + _, (g_best,), (g_worst,) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) pop_new = [] for idx in range(0, self.pop_size): L1 = self.get_levy_flight_step(multiplier=1.0, beta=1.8, case=-1) diff --git a/mealpy/swarm_based/MFO.py b/mealpy/swarm_based/MFO.py index 6ee3946b..b807ab66 100644 --- a/mealpy/swarm_based/MFO.py +++ b/mealpy/swarm_based/MFO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer diff --git a/mealpy/swarm_based/MGO.py b/mealpy/swarm_based/MGO.py index afbcf4ce..ef02f941 100644 --- a/mealpy/swarm_based/MGO.py +++ b/mealpy/swarm_based/MGO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -40,6 +41,7 @@ class OriginalMGO(Optimizer): [1] Abdollahzadeh, B., Gharehchopogh, F. S., Khodadadi, N., & Mirjalili, S. (2022). Mountain gazelle optimizer: a new nature-inspired metaheuristic algorithm for global optimization problems. Advances in Engineering Software, 174, 103282. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -72,20 +74,27 @@ def evolve(self, epoch): """ pop_new = [] for idx in range(0, self.pop_size): - idxs_rand = self.generator.permutation(self.pop_size)[:int(np.ceil(self.pop_size/3))] - pos_list = np.array([ self.pop[mm].solution for mm in idxs_rand ]) + idxs_rand = self.generator.permutation(self.pop_size)[:int(np.ceil(self.pop_size / 3))] + pos_list = np.array([self.pop[mm].solution for mm in idxs_rand]) idx_rand = self.generator.integers(int(np.ceil(self.pop_size / 3)), self.pop_size) - M = self.pop[idx_rand].solution * np.floor(self.generator.normal()) + np.mean(pos_list, axis=0) * np.ceil(self.generator.normal()) + M = self.pop[idx_rand].solution * np.floor(self.generator.normal()) + np.mean(pos_list, axis=0) * np.ceil( + self.generator.normal()) # Calculate the vector of coefficients cofi = self.coefficient_vector__(self.problem.n_dims, epoch, self.epoch) A = self.generator.standard_normal(self.problem.n_dims) * np.exp(2 - epoch * (2. / self.epoch)) - D = (np.abs(self.pop[idx].solution) + np.abs(self.g_best.solution))*(2 * self.generator.random() - 1) + D = (np.abs(self.pop[idx].solution) + np.abs(self.g_best.solution)) * (2 * self.generator.random() - 1) # Update the location - x2 = self.g_best.solution - np.abs((self.generator.integers(1, 3)*M - self.generator.integers(1, 3)*self.pop[idx].solution) * A) * cofi[self.generator.integers(0, 4), :] - x3 = M + cofi[self.generator.integers(0, 4), :] + (self.generator.integers(1, 3)*self.g_best.solution - self.generator.integers(1, 3)*self.pop[self.generator.integers(self.pop_size)].solution)*cofi[self.generator.integers(0, 4), :] - x4 = self.pop[idx].solution - D + (self.generator.integers(1, 3)*self.g_best.solution - self.generator.integers(1, 3)*M) * cofi[self.generator.integers(0, 4), :] + x2 = self.g_best.solution - np.abs( + (self.generator.integers(1, 3) * M - self.generator.integers(1, 3) * self.pop[idx].solution) * A) * \ + cofi[self.generator.integers(0, 4), :] + x3 = M + cofi[self.generator.integers(0, 4), :] + ( + self.generator.integers(1, 3) * self.g_best.solution - self.generator.integers(1, 3) * self.pop[ + self.generator.integers(self.pop_size)].solution) * cofi[self.generator.integers(0, 4), :] + x4 = self.pop[idx].solution - D + ( + self.generator.integers(1, 3) * self.g_best.solution - self.generator.integers(1, 3) * M) * \ + cofi[self.generator.integers(0, 4), :] x1 = self.problem.generate_solution() x1 = self.correct_solution(x1) diff --git a/mealpy/swarm_based/MPA.py b/mealpy/swarm_based/MPA.py index 8473ffda..06b241a6 100644 --- a/mealpy/swarm_based/MPA.py +++ b/mealpy/swarm_based/MPA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -69,7 +70,7 @@ def evolve(self, epoch): Args: epoch (int): The current iteration """ - CF = (1 - epoch/self.epoch)**(2 * epoch/self.epoch) + CF = (1 - epoch / self.epoch) ** (2 * epoch / self.epoch) RL = self.get_levy_flight_step(beta=1.5, multiplier=0.05, size=(self.pop_size, self.problem.n_dims), case=-1) RB = self.generator.standard_normal((self.pop_size, self.problem.n_dims)) per1 = self.generator.permutation(self.pop_size) @@ -77,23 +78,24 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): R = self.generator.random(self.problem.n_dims) - if epoch < self.epoch / 3: # Phase 1 (Eq.12) + if epoch < self.epoch / 3: # Phase 1 (Eq.12) step_size = RB[idx] * (self.g_best.solution - RB[idx] * self.pop[idx].solution) pos_new = self.pop[idx].solution + self.P * R * step_size - elif self.epoch / 3 < epoch < 2*self.epoch / 3: # Phase 2 (Eqs. 13 & 14) + elif self.epoch / 3 < epoch < 2 * self.epoch / 3: # Phase 2 (Eqs. 13 & 14) if idx > self.pop_size / 2: step_size = RB[idx] * (RB[idx] * self.g_best.solution - self.pop[idx].solution) pos_new = self.g_best.solution + self.P * CF * step_size else: step_size = RL[idx] * (self.g_best.solution - RL[idx] * self.pop[idx].solution) pos_new = self.pop[idx].solution + self.P * R * step_size - else: # Phase 3 (Eq. 15) + else: # Phase 3 (Eq. 15) step_size = RL[idx] * (RL[idx] * self.g_best.solution - self.pop[idx].solution) pos_new = self.g_best.solution + self.P * CF * step_size pos_new = self.correct_solution(pos_new) if self.generator.random() < self.FADS: u = np.where(self.generator.random(self.problem.n_dims) < self.FADS, 1, 0) - pos_new = pos_new + CF * (self.problem.lb + self.generator.random(self.problem.n_dims) * (self.problem.ub - self.problem.lb)) * u + pos_new = pos_new + CF * (self.problem.lb + self.generator.random(self.problem.n_dims) * ( + self.problem.ub - self.problem.lb)) * u else: r = self.generator.random() step_size = (self.FADS * (1 - r) + r) * (self.pop[per1[idx]].solution - self.pop[per2[idx]].solution) diff --git a/mealpy/swarm_based/MRFO.py b/mealpy/swarm_based/MRFO.py index 44b5a476..963890a4 100644 --- a/mealpy/swarm_based/MRFO.py +++ b/mealpy/swarm_based/MRFO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,7 +44,8 @@ class OriginalMRFO(Optimizer): optimizer for engineering applications. Engineering Applications of Artificial Intelligence, 87, p.103300. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, somersault_range: float = 2.0, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, somersault_range: float = 2.0, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -77,14 +79,17 @@ def evolve(self, epoch): x_t1 = x_rand + self.generator.uniform() * (x_rand - self.pop[idx].solution) + \ beta * (x_rand - self.pop[idx].solution) else: - x_t1 = x_rand + self.generator.uniform() * (self.pop[idx - 1].solution - self.pop[idx].solution) + \ + x_t1 = x_rand + self.generator.uniform() * ( + self.pop[idx - 1].solution - self.pop[idx].solution) + \ beta * (x_rand - self.pop[idx].solution) else: if idx == 0: - x_t1 = self.g_best.solution + self.generator.uniform() * (self.g_best.solution - self.pop[idx].solution) + \ + x_t1 = self.g_best.solution + self.generator.uniform() * ( + self.g_best.solution - self.pop[idx].solution) + \ beta * (self.g_best.solution - self.pop[idx].solution) else: - x_t1 = self.g_best.solution + self.generator.uniform() * (self.pop[idx - 1].solution - self.pop[idx].solution) + \ + x_t1 = self.g_best.solution + self.generator.uniform() * ( + self.pop[idx - 1].solution - self.pop[idx].solution) + \ beta * (self.g_best.solution - self.pop[idx].solution) # Chain foraging (Eq. 1,2) else: @@ -158,7 +163,8 @@ class WMQIMRFO(Optimizer): complex CCG-Ball curves, Knowledge-Based Systems (2022), doi: https://doi.org/10.1016/j.knosys.2021.108071. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, somersault_range: float = 2.0, pm: float = 0.5, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, somersault_range: float = 2.0, pm: float = 0.5, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -184,7 +190,7 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): x_t = self.pop[idx].solution - x_t1 = self.pop[idx-1].solution + x_t1 = self.pop[idx - 1].solution ## Morlet wavelet mutation strategy ## Goal is to jump out of local optimum --> Performed in exploration stage @@ -201,9 +207,9 @@ def evolve(self, epoch): r1 = self.generator.uniform() beta = 2 * np.exp(r1 * (self.epoch - epoch) / self.epoch) * np.sin(2 * np.pi * r1) - if coef < self.generator.random(): # Cyclone foraging + if coef < self.generator.random(): # Cyclone foraging x_rand = self.problem.generate_solution() - if self.generator.random() < self.pm: # Morlet wavelet mutation + if self.generator.random() < self.pm: # Morlet wavelet mutation if idx == 0: pos_new = x_rand + self.generator.random() * (x_rand - x_t) + beta * (x_rand - x_t) else: @@ -211,18 +217,24 @@ def evolve(self, epoch): else: conditions = self.generator.uniform(0, 1, self.problem.n_dims) > 0.5 if idx == 0: - t1 = x_rand + self.generator.random(self.problem.n_dims) * (x_rand - x_t) + beta * (x_rand - x_t) + xichma * (self.problem.ub - x_t) - t2 = x_rand + self.generator.random(self.problem.n_dims) * (x_rand - x_t) + beta * (x_rand - x_t) + xichma * (x_t - self.problem.lb) + t1 = x_rand + self.generator.random(self.problem.n_dims) * (x_rand - x_t) + beta * ( + x_rand - x_t) + xichma * (self.problem.ub - x_t) + t2 = x_rand + self.generator.random(self.problem.n_dims) * (x_rand - x_t) + beta * ( + x_rand - x_t) + xichma * (x_t - self.problem.lb) else: - t1 = x_rand + self.generator.random(self.problem.n_dims) * (x_t1 - x_t) + beta * (x_rand - x_t) + xichma * (self.problem.ub - x_t) - t2 = x_rand + self.generator.random(self.problem.n_dims) * (x_t1 - x_t) + beta * (x_rand - x_t) + xichma * (x_t - self.problem.lb) + t1 = x_rand + self.generator.random(self.problem.n_dims) * (x_t1 - x_t) + beta * ( + x_rand - x_t) + xichma * (self.problem.ub - x_t) + t2 = x_rand + self.generator.random(self.problem.n_dims) * (x_t1 - x_t) + beta * ( + x_rand - x_t) + xichma * (x_t - self.problem.lb) pos_new = np.where(conditions, t1, t2) else: if idx == 0: - pos_new = self.g_best.solution + self.generator.random() * (self.g_best.solution - x_t) + beta * (self.g_best.solution - x_t) + pos_new = self.g_best.solution + self.generator.random() * ( + self.g_best.solution - x_t) + beta * (self.g_best.solution - x_t) else: - pos_new = self.g_best.solution + self.generator.random() * (x_t1 - x_t) + beta * (self.g_best.solution - x_t) - else: # Chain foraging (Eq. 1,2) + pos_new = self.g_best.solution + self.generator.random() * (x_t1 - x_t) + beta * ( + self.g_best.solution - x_t) + else: # Chain foraging (Eq. 1,2) r = self.generator.random() alpha = 2 * r * np.sqrt(np.abs(np.log(r))) if idx == 0: @@ -244,7 +256,7 @@ def evolve(self, epoch): pop_child = [] for idx in range(0, self.pop_size): pos_new = self.pop[idx].solution + self.somersault_range * \ - (self.generator.random() * g_best.solution - self.generator.random() * self.pop[idx].solution) + (self.generator.random() * g_best.solution - self.generator.random() * self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_child.append(agent) @@ -260,14 +272,16 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): idx2, idx3 = idx + 1, idx + 2 - if idx == self.pop_size-2: + if idx == self.pop_size - 2: idx2, idx3 = idx + 1, 0 - if idx == self.pop_size-1: + if idx == self.pop_size - 1: idx2, idx3 = 0, 1 f1, f2, f3 = self.pop[idx].target.fitness, self.pop[idx2].target.fitness, self.pop[idx3].target.fitness x1, x2, x3 = self.pop[idx].solution, self.pop[idx2].solution, self.pop[idx3].solution - a = f1 / ((x1 - x2) * (x1 - x3) + self.EPSILON) + f2 / ((x2 - x1) * (x2 - x3) + self.EPSILON) + f3 / ((x3 - x1) * (x3 - x2) + self.EPSILON) - gx = ((x3 ** 2 - x2 ** 2) * f1 + (x1 ** 2 - x3 ** 2) * f2 + (x2 ** 2 - x1 ** 2) * f3) / (2 * ((x3 - x2) * f1 + (x1 - x3) * f2 + (x2 - x1) * f3) + self.EPSILON) + a = f1 / ((x1 - x2) * (x1 - x3) + self.EPSILON) + f2 / ((x2 - x1) * (x2 - x3) + self.EPSILON) + f3 / ( + (x3 - x1) * (x3 - x2) + self.EPSILON) + gx = ((x3 ** 2 - x2 ** 2) * f1 + (x1 ** 2 - x3 ** 2) * f2 + (x2 ** 2 - x1 ** 2) * f3) / ( + 2 * ((x3 - x2) * f1 + (x1 - x3) * f2 + (x2 - x1) * f3) + self.EPSILON) pos_new = np.where(a > 0, gx, x1) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/swarm_based/MSA.py b/mealpy/swarm_based/MSA.py index c3d607b8..d08344b7 100644 --- a/mealpy/swarm_based/MSA.py +++ b/mealpy/swarm_based/MSA.py @@ -4,8 +4,10 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from math import gamma + +import numpy as np + from mealpy.optimizer import Optimizer @@ -47,7 +49,8 @@ class OriginalMSA(Optimizer): global optimization problems. Memetic Computing, 10(2), pp.151-164. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 5, partition: float = 0.5, max_step_size: float = 1.0, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 5, partition: float = 0.5, + max_step_size: float = 1.0, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -59,7 +62,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 5, par super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) - self.n_best = self.validator.check_int("n_best", n_best, [2, int(self.pop_size/2)]) + self.n_best = self.validator.check_int("n_best", n_best, [2, int(self.pop_size / 2)]) self.partition = self.validator.check_float("partition", partition, (0, 1.0)) self.max_step_size = self.validator.check_float("max_step_size", max_step_size, (0, 5.0)) self.set_parameters(["epoch", "pop_size", "n_best", "partition", "max_step_size"]) @@ -73,7 +76,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_best: int = 5, par def _levy_walk(self, iteration): beta = 1.5 # Eq. 2.23 - sigma = (gamma(1 + beta) * np.sin(np.pi * (beta - 1) / 2) / (gamma(beta / 2) * (beta - 1) * 2 ** ((beta - 2) / 2))) ** (1 / (beta - 1)) + sigma = (gamma(1 + beta) * np.sin(np.pi * (beta - 1) / 2) / ( + gamma(beta / 2) * (beta - 1) * 2 ** ((beta - 2) / 2))) ** (1 / (beta - 1)) u = self.generator.uniform(self.problem.lb, self.problem.ub) * sigma v = self.generator.uniform(self.problem.lb, self.problem.ub) step = u / np.abs(v) ** (1.0 / (beta - 1)) # Eq. 2.21 diff --git a/mealpy/swarm_based/MShOA.py b/mealpy/swarm_based/MShOA.py index 44a34996..e76415fa 100644 --- a/mealpy/swarm_based/MShOA.py +++ b/mealpy/swarm_based/MShOA.py @@ -17,6 +17,7 @@ # not inter-iteration change. PTI update happens AFTER strategy application. import numpy as np + from mealpy.optimizer import Optimizer @@ -98,7 +99,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, polarization_rate: f self.k_value = self.validator.check_float("k_value", k_value, (0.0, 1.0)) self.set_parameters(["epoch", "pop_size", "polarization_rate", "strike_factor", "k_value"]) self.sort_flag = False - + # PTI (Polarization Type Indicator) vector: one value per agent ∈ {1, 2, 3} # Initialized randomly according to Algorithm 1 in the paper # PTI = 1: Foraging/Navigation (vertical linear polarized light) @@ -136,10 +137,10 @@ def evolve(self, epoch: int) -> None: # Step 1: Extract current positions X_i(t) before strategy application pop_pos = np.array([agent.solution for agent in self.pop]) # X_i(t) g_best_pos = self.g_best.solution # Shape: (n_dims,) - + # Initialize position update matrix (will become X'_i(t) after strategies) pos_new = pop_pos.copy() - + # Generate random indices for Strategy 1 (Foraging) - ensure r ≠ i random_indices = self.generator.integers(0, self.pop_size, self.pop_size) # Ensure r ≠ i: if random_indices[i] == i, replace with another random index (excluding i) @@ -149,19 +150,19 @@ def evolve(self, epoch: int) -> None: candidates = list(range(0, idx)) + list(range(idx + 1, self.pop_size)) if len(candidates) > 0: random_indices[idx] = self.generator.choice(candidates) - + # Create masks for each strategy based on current PTI values mask_strategy1 = (self.pti == 1) # Foraging/Navigation mask_strategy2 = (self.pti == 2) # Attack/Strike mask_strategy3 = (self.pti == 3) # Defense/Burrow - + # Expand masks to match dimensions: (pop_size,) -> (pop_size, n_dims) mask_s1_expanded = mask_strategy1[:, np.newaxis] mask_s2_expanded = mask_strategy2[:, np.newaxis] mask_s3_expanded = mask_strategy3[:, np.newaxis] - + # Step 2: Apply strategies based on PTI to generate X'_i(t) - + # Strategy 1: Foraging/Navigation (PTI = 1) - Equation 12 (Langevin/Brownian) # x_i(t+1) = x_best - (x_i(t) - x_best) + D_i(x_r(t) - x_i(t)) # where D_i: scalar diffusion coefficient per agent, sampled from U(-1, 1) as in Eq. 12 @@ -172,14 +173,14 @@ def evolve(self, epoch: int) -> None: D = self.generator.uniform(-1.0, 1.0, size=(self.pop_size, 1)) # scalar diffusion coefficient per agent foraging_pos = g_best_pos - v + D * R_t # D broadcasts to all dimensions pos_new = np.where(mask_s1_expanded, foraging_pos, pos_new) - + # Strategy 2: Attack/Strike (PTI = 2) - Equation 14 (circular motion) # x_i(t+1) = x_best * cos(θ) # where θ ~ U(π, 2π) theta = self.generator.uniform(np.pi, 2 * np.pi, size=self.pop_size)[:, np.newaxis] strike_pos = g_best_pos * np.cos(theta) # element-wise multiplication pos_new = np.where(mask_s2_expanded, strike_pos, pos_new) - + # Strategy 3: Defense/Burrow/Shelter (PTI = 3) - Equation 15 # Defense: x_i(t+1) = x_best + k * x_best # Shelter: x_i(t+1) = x_best - k * x_best @@ -196,7 +197,7 @@ def evolve(self, epoch: int) -> None: g_best_pos + k * g_best_pos, # defense g_best_pos - k * g_best_pos) # shelter pos_new = np.where(mask_s3_expanded, defense_pos, pos_new) - + # Step 3: Calculate LPA from intra-iteration change (X_i(t) vs X'_i(t)) # LPA_i = arccos((X_i(t) · X'_i(t)) / (||X_i(t)|| ||X'_i(t)||)) # Normalize vectors for dot product calculation @@ -205,12 +206,12 @@ def evolve(self, epoch: int) -> None: dot_product = np.sum(pop_pos_norm * pos_new_norm, axis=1) dot_product = np.clip(dot_product, -1.0, 1.0) # Ensure valid range for arccos lpa = np.arccos(dot_product) # Left Polarization Angle ∈ [0, π] - + # Step 4: Calculate RPA, LPT, RPT, LAD, RAD (Algorithm 1) - + # Calculate Right Polarization Angle (RPA): RPA_i = rand * π (Eq. 4) rpa = self.generator.random(self.pop_size) * np.pi # RPA ∈ [0, π] - + # Determine Left Polarization Type (LPT) and Right Polarization Type (RPT) based on Eq. 5 # Eq. 5 defines three types with π/8 intervals: # Type 1: 3π/8 ≤ açı ≤ 5π/8 @@ -220,25 +221,27 @@ def evolve(self, epoch: int) -> None: pi_38 = 3 * np.pi / 8 pi_58 = 5 * np.pi / 8 pi_78 = 7 * np.pi / 8 - + # LPT determination from LPA (Eq. 5) lpt = np.where( (lpa >= pi_38) & (lpa <= pi_58), 1, # Type 1: 3π/8 ≤ LPA ≤ 5π/8 np.where( - ((lpa >= 0) & (lpa <= pi_8)) | ((lpa >= pi_78) & (lpa <= np.pi)), 2, # Type 2: 0 ≤ LPA ≤ π/8 or 7π/8 ≤ LPA ≤ π + ((lpa >= 0) & (lpa <= pi_8)) | ((lpa >= pi_78) & (lpa <= np.pi)), 2, + # Type 2: 0 ≤ LPA ≤ π/8 or 7π/8 ≤ LPA ≤ π 3 # Type 3: π/8 < LPA < 3π/8 or 5π/8 < LPA < 7π/8 ) ) - + # RPT determination from RPA (Eq. 5) rpt = np.where( (rpa >= pi_38) & (rpa <= pi_58), 1, # Type 1: 3π/8 ≤ RPA ≤ 5π/8 np.where( - ((rpa >= 0) & (rpa <= pi_8)) | ((rpa >= pi_78) & (rpa <= np.pi)), 2, # Type 2: 0 ≤ RPA ≤ π/8 or 7π/8 ≤ RPA ≤ π + ((rpa >= 0) & (rpa <= pi_8)) | ((rpa >= pi_78) & (rpa <= np.pi)), 2, + # Type 2: 0 ≤ RPA ≤ π/8 or 7π/8 ≤ RPA ≤ π 3 # Type 3: π/8 < RPA < 3π/8 or 5π/8 < RPA < 7π/8 ) ) - + # Calculate Left Angular Difference (LAD) and Right Angular Difference (RAD) (Eq. 6) # Eq. 6 defines piecewise calculation: # 0 ≤ açı ≤ π/8 → LAD/RAD = açı @@ -246,7 +249,7 @@ def evolve(self, epoch: int) -> None: # 3π/8 ≤ açı ≤ 5π/8 → LAD/RAD = |π/2 − açı| # π/8 < açı < 3π/8 → LAD/RAD = |π/4 − açı| # 5π/8 < açı < 7π/8 → LAD/RAD = |3π/4 − açı| - + # LAD calculation from LPA (Eq. 6) lad = np.where( (lpa >= 0) & (lpa <= pi_8), lpa, # 0 ≤ LPA ≤ π/8 → LAD = LPA @@ -261,7 +264,7 @@ def evolve(self, epoch: int) -> None: ) ) ) - + # RAD calculation from RPA (Eq. 6) rad = np.where( (rpa >= 0) & (rpa <= pi_8), rpa, # 0 ≤ RPA ≤ π/8 → RAD = RPA @@ -276,7 +279,7 @@ def evolve(self, epoch: int) -> None: ) ) ) - + # Step 5: Update PTI according to Algorithm 1 (Eq. 7) # PTI_i = LPT_i if LAD_i < RAD_i else RPT_i # In case of equality, choose RPT (else branch) diff --git a/mealpy/swarm_based/NGO.py b/mealpy/swarm_based/NGO.py index 89d86fea..a161ccfe 100644 --- a/mealpy/swarm_based/NGO.py +++ b/mealpy/swarm_based/NGO.py @@ -4,7 +4,6 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from mealpy.optimizer import Optimizer @@ -46,6 +45,7 @@ class OriginalNGO(Optimizer): [1] Dehghani, M., Hubálovský, Š., & Trojovský, P. (2021). Northern goshawk optimization: a new swarm-based algorithm for solving optimization problems. IEEE Access, 9, 162059-162080. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -71,18 +71,21 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): # Phase 1: Exploration kk = self.generator.permutation(self.pop_size)[0] - if self.compare_target(self.pop[kk].target, self.pop[idx].target): # Eq. 4 - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) + if self.compare_target(self.pop[kk].target, self.pop[idx].target): # Eq. 4 + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[idx].solution - self.pop[kk].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent # PHASE 2 Exploitation - R = 0.02 * (1. - epoch / self.epoch) # Eq. 6 - pos_new = self.pop[idx].solution + (-R + 2 * R * self.generator.random(self.problem.n_dims)) * self.pop[idx].solution # Eq. 7 + R = 0.02 * (1. - epoch / self.epoch) # Eq. 6 + pos_new = self.pop[idx].solution + (-R + 2 * R * self.generator.random(self.problem.n_dims)) * self.pop[ + idx].solution # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/NMRA.py b/mealpy/swarm_based/NMRA.py index b3fb9e43..623b4497 100644 --- a/mealpy/swarm_based/NMRA.py +++ b/mealpy/swarm_based/NMRA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -41,6 +42,7 @@ class OriginalNMRA(Optimizer): ~~~~~~~~~~ [1] Salgotra, R. and Singh, U., 2019. The naked mole-rat algorithm. Neural Computing and Applications, 31(12), pp.8837-8857. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, pb: float = 0.75, **kwargs: object) -> None: """ Args: @@ -69,10 +71,12 @@ def evolve(self, epoch): if idx < self.size_b: # breeding operators if self.generator.uniform() < self.pb: alpha = self.generator.uniform() - pos_new = (1 - alpha) * self.pop[idx].solution + alpha * (self.g_best.solution - self.pop[idx].solution) + pos_new = (1 - alpha) * self.pop[idx].solution + alpha * ( + self.g_best.solution - self.pop[idx].solution) else: # working operators t1, t2 = self.generator.choice(range(self.size_b, self.pop_size), 2, replace=False) - pos_new = self.pop[idx].solution + self.generator.uniform() * (self.pop[t1].solution - self.pop[t2].solution) + pos_new = self.pop[idx].solution + self.generator.uniform() * ( + self.pop[t1].solution - self.pop[t2].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/swarm_based/OOA.py b/mealpy/swarm_based/OOA.py index e165a429..85a773b2 100644 --- a/mealpy/swarm_based/OOA.py +++ b/mealpy/swarm_based/OOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,6 +46,7 @@ class OriginalOOA(Optimizer): [1] Trojovský, P., & Dehghani, M. Osprey Optimization Algorithm: A new bio-inspired metaheuristic algorithm for solving engineering optimization problems. Frontiers in Mechanical Engineering, 8, 136. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -85,14 +87,16 @@ def evolve(self, epoch): kk = self.generator.permutation(idxs)[0] sf = self.pop[kk] r1 = self.generator.integers(1, 3) - pos_new = self.pop[idx].solution + self.generator.normal(0, 1) * (sf.solution - r1 * self.pop[idx].solution) # Eq. 5 + pos_new = self.pop[idx].solution + self.generator.normal(0, 1) * ( + sf.solution - r1 * self.pop[idx].solution) # Eq. 5 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent # PHASE 2: CARRYING THE FISH TO THE SUITABLE POSITION (EXPLOITATION) - pos_new = self.pop[idx].solution + self.problem.lb + self.generator.random() * (self.problem.ub - self.problem.lb) # Eq. 7 + pos_new = self.pop[idx].solution + self.problem.lb + self.generator.random() * ( + self.problem.ub - self.problem.lb) # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/PFA.py b/mealpy/swarm_based/PFA.py index 37da1fdf..817d9c99 100644 --- a/mealpy/swarm_based/PFA.py +++ b/mealpy/swarm_based/PFA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -39,6 +40,7 @@ class OriginalPFA(Optimizer): [1] Yapici, H. and Cetinkaya, N., 2019. A new meta-heuristic optimizer: Pathfinder algorithm. Applied soft computing, 78, pp.545-568. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -63,7 +65,8 @@ def evolve(self, epoch): t = 1. - epoch * 1.0 / self.epoch space = self.problem.ub - self.problem.lb ## Update the position of pathfinder and check the bound - pos_new = self.pop[0].solution + 2 * self.generator.uniform() * (self.g_best.solution - self.pop[0].solution) + A + pos_new = self.pop[0].solution + 2 * self.generator.uniform() * ( + self.g_best.solution - self.pop[0].solution) + A pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) pop_new = [agent, ] diff --git a/mealpy/swarm_based/POA.py b/mealpy/swarm_based/POA.py index 313662e1..a63ff990 100644 --- a/mealpy/swarm_based/POA.py +++ b/mealpy/swarm_based/POA.py @@ -4,7 +4,6 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from mealpy.optimizer import Optimizer @@ -46,6 +45,7 @@ class OriginalPOA(Optimizer): [1] Trojovský, P., & Dehghani, M. (2022). Pelican optimization algorithm: A novel nature-inspired algorithm for engineering applications. Sensors, 22(3), 855. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -70,17 +70,20 @@ def evolve(self, epoch): kk = self.generator.permutation(self.pop_size)[0] for idx in range(0, self.pop_size): # PHASE 1: Moving towards prey (exploration phase) - if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): # Eq. 4 - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) + if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): # Eq. 4 + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[idx].solution - self.pop[kk].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent # PHASE 2: Winging on the water surface (exploitation phase) # Eq. 6 - pos_new = self.pop[idx].solution + 0.2 * (1 - epoch/self.epoch) *(2*self.generator.random(self.problem.n_dims) - 1) * self.pop[idx].solution + pos_new = self.pop[idx].solution + 0.2 * (1 - epoch / self.epoch) * ( + 2 * self.generator.random(self.problem.n_dims) - 1) * self.pop[idx].solution pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/PSO.py b/mealpy/swarm_based/PSO.py index 207503bc..288b5577 100644 --- a/mealpy/swarm_based/PSO.py +++ b/mealpy/swarm_based/PSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -43,7 +44,8 @@ class OriginalPSO(Optimizer): ICNN'95-international conference on neural networks (Vol. 4, pp. 1942-1948). IEEE. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 2.05, c2: float = 2.05, w: float = 0.4, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 2.05, c2: float = 2.05, w: float = 0.4, + **kwargs: object) -> None: """ Args: epoch: maximum number of iterations, default = 10000 @@ -93,8 +95,10 @@ def evolve(self, epoch): """ # Update weight after each move count (weight down) for idx in range(0, self.pop_size): - cognitive = self.c1 * self.generator.random(self.problem.n_dims) * (self.pop[idx].local_solution - self.pop[idx].solution) - social = self.c2 * self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + cognitive = self.c1 * self.generator.random(self.problem.n_dims) * ( + self.pop[idx].local_solution - self.pop[idx].solution) + social = self.c2 * self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) self.pop[idx].velocity = self.w * self.pop[idx].velocity + cognitive + social pos_new = self.pop[idx].solution + self.pop[idx].velocity pos_new = self.correct_solution(pos_new) @@ -140,7 +144,8 @@ class AIW_PSO(Optimizer): Lecture Notes in Computer Science(), vol 4029. Springer, Berlin, Heidelberg. https://doi.org/10.1007/11785231_48 """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 2.05, c2: float = 2.05, alpha: float = 0.4, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 2.05, c2: float = 2.05, alpha: float = 0.4, + **kwargs: object) -> None: """ Args: epoch: maximum number of iterations, default = 10000 @@ -191,11 +196,13 @@ def evolve(self, epoch): current_best = self.get_best_agent(self.pop, self.problem.minmax) for idx in range(0, self.pop_size): denom = np.abs(self.pop[idx].local_solution - current_best.solution) - denom = np.where(denom==0, 1e-6, denom) - isa = np.abs(self.pop[idx].solution - self.pop[idx].local_solution) / denom # individual search ability + denom = np.where(denom == 0, 1e-6, denom) + isa = np.abs(self.pop[idx].solution - self.pop[idx].local_solution) / denom # individual search ability w = 1 - self.alpha * (1.0 / (1.0 + np.exp(-isa))) - cognitive = self.c1 * self.generator.random(self.problem.n_dims) * (self.pop[idx].local_solution - self.pop[idx].solution) - social = self.c2 * self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + cognitive = self.c1 * self.generator.random(self.problem.n_dims) * ( + self.pop[idx].local_solution - self.pop[idx].solution) + social = self.c2 * self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) velocity = w * self.pop[idx].velocity + cognitive + social self.pop[idx].velocity = np.clip(velocity, self.v_min, self.v_max) pos_new = self.pop[idx].solution + self.pop[idx].velocity @@ -296,8 +303,10 @@ def evolve(self, epoch): # Update weight after each move count (weight down) w = (self.epoch - epoch) / self.epoch * (self.w_max - self.w_min) + self.w_min for idx in range(0, self.pop_size): - cognitive = self.c1 * self.generator.random(self.problem.n_dims) * (self.pop[idx].local_solution - self.pop[idx].solution) - social = self.c2 * self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + cognitive = self.c1 * self.generator.random(self.problem.n_dims) * ( + self.pop[idx].local_solution - self.pop[idx].solution) + social = self.c2 * self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) velocity = w * self.pop[idx].velocity + cognitive + social self.pop[idx].velocity = np.clip(velocity, self.v_min, self.v_max) pos_new = self.pop[idx].solution + self.pop[idx].velocity @@ -380,7 +389,8 @@ def evolve(self, epoch): bb = 2 * (np.cos(self.dyn_delta_list[idx])) ee = np.abs(np.cos(self.dyn_delta_list[idx])) ** aa tt = np.abs(np.sin(self.dyn_delta_list[idx])) ** bb - v_new = ee * (self.pop[idx].local_solution - self.pop[idx].solution) + tt * (self.g_best.solution - self.pop[idx].solution) + v_new = ee * (self.pop[idx].local_solution - self.pop[idx].solution) + tt * ( + self.g_best.solution - self.pop[idx].solution) v_new = np.minimum(np.maximum(v_new, -self.v_max), self.v_max) self.pop[idx].velocity = v_new pos_new = self.pop[idx].solution + v_new @@ -460,10 +470,12 @@ def evolve(self, epoch): c1_it = np.abs(w) ** (c_it * w) c2_it = np.abs(1 - w) ** (c_it / (1 - w)) #################### HPSO - v_new = c1_it * self.generator.uniform(0, 1, self.problem.n_dims) * (self.pop[idx].local_solution - self.pop[idx].solution) + \ + v_new = c1_it * self.generator.uniform(0, 1, self.problem.n_dims) * ( + self.pop[idx].local_solution - self.pop[idx].solution) + \ c2_it * self.generator.uniform(0, 1, self.problem.n_dims) * \ (self.g_best.solution + self.pop[idx_k].local_solution - 2 * self.pop[idx].solution) - v_new = np.where(v_new == 0, np.sign(0.5 - self.generator.uniform()) * self.generator.uniform() * self.v_max, v_new) + v_new = np.where(v_new == 0, + np.sign(0.5 - self.generator.uniform()) * self.generator.uniform() * self.v_max, v_new) v_new = np.sign(v_new) * np.minimum(np.abs(v_new), self.v_max) ######################### v_new = np.minimum(np.maximum(v_new, -self.v_max), self.v_max) @@ -533,7 +545,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 2.05, c2 self.set_parameters(["epoch", "pop_size", "c1", "c2", "w_min", "w_max"]) self.sort_flag = False self.is_parallelizable = False - + def initialize_variables(self): self.v_max = 0.5 * (self.problem.ub - self.problem.lb) self.v_min = -self.v_max @@ -564,7 +576,8 @@ def evolve(self, epoch): fit_min = np.min(list_fits) for idx in range(self.pop_size): w = self.get_weights__(self.pop[idx].target.fitness, fit_avg, fit_min) - v_new = w * self.pop[idx].velocity + self.c1 * self.generator.random() * (self.pop[idx].local_solution - self.pop[idx].solution) + \ + v_new = w * self.pop[idx].velocity + self.c1 * self.generator.random() * ( + self.pop[idx].local_solution - self.pop[idx].solution) + \ self.c2 * self.generator.random() * (self.g_best.solution - self.pop[idx].solution) v_new = np.clip(v_new, self.v_min, self.v_max) x_new = self.pop[idx].solution + v_new @@ -653,7 +666,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, c_local: float = 1.2 self.set_parameters(["epoch", "pop_size", "c_local", "w_min", "w_max", "max_flag"]) self.sort_flag = False self.is_parallelizable = True - + def initialize_variables(self): self.v_max = 0.5 * (self.problem.ub - self.problem.lb) self.v_min = -self.v_max @@ -720,7 +733,8 @@ def evolve(self, epoch): pop_child = self.greedy_selection_population(self.pop, pop_new, self.problem.minmax) for idx in range(0, self.pop_size): if self.compare_target(pop_new[idx].target, self.pop[idx].local_target, self.problem.minmax): - pop_child[idx].update(local_solution=pop_new[idx].solution.copy(), local_target=pop_new[idx].target.copy()) + pop_child[idx].update(local_solution=pop_new[idx].solution.copy(), + local_target=pop_new[idx].target.copy()) self.flags[idx] = 0 else: self.flags[idx] += 1 diff --git a/mealpy/swarm_based/SCSO.py b/mealpy/swarm_based/SCSO.py index 959ca2cf..b9b793af 100644 --- a/mealpy/swarm_based/SCSO.py +++ b/mealpy/swarm_based/SCSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -40,6 +41,7 @@ class OriginalSCSO(Optimizer): [1] Seyyedabbasi, A., & Kiani, F. (2022). Sand Cat swarm optimization: a nature-inspired algorithm to solve global optimization problems. Engineering with Computers, 1-25. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -53,7 +55,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> self.sort_flag = False def initialize_variables(self): - self.ss = 2 # maximum Sensitivity range + self.ss = 2 # maximum Sensitivity range self.pp = np.arange(1, 361) def get_index_roulette_wheel_selection__(self, p): @@ -72,7 +74,7 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): r = self.generator.random() * guides_r - R = (2*guides_r)*self.generator.random() - guides_r # controls to transition phases + R = (2 * guides_r) * self.generator.random() - guides_r # controls to transition phases pos_new = self.pop[idx].solution.copy() for jdx in range(0, self.problem.n_dims): teta = self.get_index_roulette_wheel_selection__(self.pp) @@ -81,7 +83,8 @@ def evolve(self, epoch): pos_new[jdx] = self.g_best.solution[jdx] - r * rand_pos * np.cos(teta) else: cp = int(self.generator.random() * self.pop_size) - pos_new[jdx] = r * (self.pop[cp].solution[jdx] - self.generator.random() * self.pop[idx].solution[jdx]) + pos_new[jdx] = r * ( + self.pop[cp].solution[jdx] - self.generator.random() * self.pop[idx].solution[jdx]) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/swarm_based/SFO.py b/mealpy/swarm_based/SFO.py index d4c189b7..97bafbcd 100644 --- a/mealpy/swarm_based/SFO.py +++ b/mealpy/swarm_based/SFO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,8 @@ class OriginalSFO(Optimizer): algorithm for solving constrained engineering optimization problems. Engineering Applications of Artificial Intelligence, 80, pp.20-34. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, pp: float = 0.1, AP: float = 4.0, epsilon: float = 0.0001, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, pp: float = 0.1, AP: float = 4.0, + epsilon: float = 0.0001, **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -66,9 +68,9 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, pp: float = 0.1, AP: def initialization(self): if self.pop is None: - self.pop = self.generate_population(self.pop_size) # pop = sailfish + self.pop = self.generate_population(self.pop_size) # pop = sailfish self.s_pop = self.generate_population(self.s_size) - self.s_gbest = self.get_best_agent(self.s_pop, self.problem.minmax) # s_pop = sardines + self.s_gbest = self.get_best_agent(self.s_pop, self.problem.minmax) # s_pop = sardines def evolve(self, epoch): """ @@ -84,7 +86,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): lamda_i = 2 * self.generator.uniform() * PD - PD pos_new = self.s_gbest.solution - lamda_i * \ - (self.generator.uniform() * (self.pop[idx].solution + self.s_gbest.solution) / 2 - self.pop[idx].solution) + (self.generator.uniform() * (self.pop[idx].solution + self.s_gbest.solution) / 2 - self.pop[ + idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -106,7 +109,8 @@ def evolve(self, epoch): #### Random self.generator.choice number of dimensions in sardines updated, remove third loop by numpy vector computation pos_new = self.s_pop[idx].solution.copy() list2 = self.generator.choice(range(0, self.problem.n_dims), beta, replace=False) - pos_new[list2] = (self.generator.uniform(0, 1, self.problem.n_dims) * (self.s_gbest.solution - self.s_pop[idx].solution + AP))[list2] + pos_new[list2] = (self.generator.uniform(0, 1, self.problem.n_dims) * ( + self.s_gbest.solution - self.s_pop[idx].solution + AP))[list2] pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) if self.mode not in self.AVAILABLE_MODES: @@ -173,6 +177,7 @@ class ImprovedSFO(Optimizer): >>> print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, pp: float = 0.1, **kwargs: object) -> None: """ Args: @@ -208,7 +213,8 @@ def evolve(self, epoch): PD = 1 - len(self.pop) / (len(self.pop) + len(self.s_pop)) lamda_i = 2 * self.generator.uniform() * PD - PD pos_new = self.s_gbest.solution - \ - lamda_i * (self.generator.uniform() * (self.g_best.solution + self.s_gbest.solution) / 2 - self.pop[idx].solution) + lamda_i * (self.generator.uniform() * (self.g_best.solution + self.s_gbest.solution) / 2 - + self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -224,7 +230,8 @@ def evolve(self, epoch): if AP < 0.5: for idx in range(0, len(self.s_pop)): temp = (self.g_best.solution + AP) / 2 - pos_new = self.problem.lb + self.problem.ub - temp + self.generator.uniform() * (temp - self.s_pop[idx].solution) + pos_new = self.problem.lb + self.problem.ub - temp + self.generator.uniform() * ( + temp - self.s_pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) if self.mode not in self.AVAILABLE_MODES: diff --git a/mealpy/swarm_based/SHO.py b/mealpy/swarm_based/SHO.py index 10b12f18..e94b6489 100644 --- a/mealpy/swarm_based/SHO.py +++ b/mealpy/swarm_based/SHO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -43,7 +44,9 @@ class OriginalSHO(Optimizer): [1] Dhiman, G. and Kumar, V., 2017. Spotted hyena optimizer: a novel bio-inspired based metaheuristic technique for engineering applications. Advances in Engineering Software, 114, pp.48-70. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, h_factor: float = 5., n_trials: int = 10, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, h_factor: float = 5., n_trials: int = 10, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -81,7 +84,7 @@ def evolve(self, epoch): N = 1 for _ in range(0, self.n_trials): pos_temp = self.g_best.solution + self.generator.normal(0, 1, self.problem.n_dims) * \ - self.generator.uniform(self.problem.lb, self.problem.ub) + self.generator.uniform(self.problem.lb, self.problem.ub) pos_new = self.correct_solution(pos_temp) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.g_best.target, self.problem.minmax): diff --git a/mealpy/swarm_based/SLO.py b/mealpy/swarm_based/SLO.py index 536172e1..469b94c1 100644 --- a/mealpy/swarm_based/SLO.py +++ b/mealpy/swarm_based/SLO.py @@ -4,8 +4,10 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from math import gamma + +import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -42,6 +44,7 @@ class OriginalSLO(Optimizer): ~~~~~~~~~~ [1] Masadeh, R., Mahafzah, B.A. and Sharieh, A., 2019. Sea lion optimization algorithm. Sea, 10(5), p.388. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -75,12 +78,15 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): if SP_leader < 0.25: if c < 1: - pos_new = self.g_best.solution - c * np.abs(2 * self.generator.random() * self.g_best.solution - self.pop[idx].solution) + pos_new = self.g_best.solution - c * np.abs( + 2 * self.generator.random() * self.g_best.solution - self.pop[idx].solution) else: ri = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) # random index - pos_new = self.pop[ri].solution - c * np.abs(2 * self.generator.random() * self.pop[ri].solution - self.pop[idx].solution) + pos_new = self.pop[ri].solution - c * np.abs( + 2 * self.generator.random() * self.pop[ri].solution - self.pop[idx].solution) else: - pos_new = np.abs(self.g_best.solution - self.pop[idx].solution) * np.cos(2 * np.pi * self.generator.uniform(-1, 1)) + self.g_best.solution + pos_new = np.abs(self.g_best.solution - self.pop[idx].solution) * np.cos( + 2 * np.pi * self.generator.uniform(-1, 1)) + self.g_best.solution # In the paper doesn't check also doesn't update old solution at this point pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) @@ -121,6 +127,7 @@ class ModifiedSLO(Optimizer): >>> print(f"Solution: {g_best.solution}, Fitness: {g_best.target.fitness}") >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -184,7 +191,8 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): agent = self.pop[idx].copy() if SP_leader >= 0.6: - pos_new = np.cos(2 * np.pi * self.generator.normal(0, 1)) * np.abs(self.g_best.solution - self.pop[idx].solution) + self.g_best.solution + pos_new = np.cos(2 * np.pi * self.generator.normal(0, 1)) * np.abs( + self.g_best.solution - self.pop[idx].solution) + self.g_best.solution else: if self.generator.uniform() < pa: dist1 = self.generator.uniform() * np.abs(2 * self.g_best.solution - self.pop[idx].solution) @@ -239,7 +247,9 @@ class ImprovedSLO(ModifiedSLO): [1] Nguyen, Binh Minh, Trung Tran, Thieu Nguyen, and Giang Nguyen. "An improved sea lion optimization for workload elasticity prediction with neural networks." International Journal of Computational Intelligence Systems 15, no. 1 (2022): 90. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 1.2, c2: float = 1.2, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, c1: float = 1.2, c2: float = 1.2, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -281,16 +291,19 @@ def evolve(self, epoch): # Create a new solution by equation below # Then create an opposition solution of above solution # Compare both of them and keep the good one (Searching at both direction) - pos_new = self.g_best.solution + c * self.generator.normal(0, 1, self.problem.n_dims) * (self.g_best.solution - self.pop[idx].solution) + pos_new = self.g_best.solution + c * self.generator.normal(0, 1, self.problem.n_dims) * ( + self.g_best.solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) target_new = self.get_target(pos_new) - pos_new_oppo = self.problem.lb + self.problem.ub - self.g_best.solution + self.generator.random() * (self.g_best.solution - pos_new) + pos_new_oppo = self.problem.lb + self.problem.ub - self.g_best.solution + self.generator.random() * ( + self.g_best.solution - pos_new) pos_new_oppo = self.correct_solution(pos_new_oppo) target_new_oppo = self.get_target(pos_new_oppo) if self.compare_target(target_new_oppo, target_new, self.problem.minmax): pos_new = pos_new_oppo else: # Exploitation - pos_new = self.g_best.solution + np.cos(2 * np.pi * self.generator.uniform(-1, 1)) * np.abs(self.g_best.solution - self.pop[idx].solution) + pos_new = self.g_best.solution + np.cos(2 * np.pi * self.generator.uniform(-1, 1)) * np.abs( + self.g_best.solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent.solution = pos_new pop_new.append(agent) diff --git a/mealpy/swarm_based/SMO.py b/mealpy/swarm_based/SMO.py index 20ab0a46..102ffdf1 100644 --- a/mealpy/swarm_based/SMO.py +++ b/mealpy/swarm_based/SMO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -86,8 +87,8 @@ def initialize_variables(self): max_possible_groups = self.pop_size // 3 self.num_groups = min(self.max_groups, max_possible_groups) self.group_size = -(-self.pop_size // self.num_groups) - self.LLL = self.epoch // 10 # local_leader_limit - self.GLL = self.epoch // 20 # global_leader_limit + self.LLL = self.epoch // 10 # local_leader_limit + self.GLL = self.epoch // 20 # global_leader_limit # Counters self.local_limit_counts = [0] * self.num_groups @@ -99,19 +100,22 @@ def initialization(self) -> None: # Split groups self.groups = self.split_fill_by_group(self.pop, self.num_groups) # Get local leaders - self.local_leaders = [self.get_sorted_population(group, self.problem.minmax, return_index=False)[0] for group in self.groups] + self.local_leaders = [self.get_sorted_population(group, self.problem.minmax, return_index=False)[0] for group in + self.groups] def local_leader_phase(self): """Local Leader Phase - all monkeys update based on local leader""" for group_idx, group in enumerate(self.groups): n_items = len(group) for idx in range(n_items): - list_rand = self.generator.choice(list(set(range(n_items)) - {idx}), size=self.problem.n_dims, replace=True) + list_rand = self.generator.choice(list(set(range(n_items)) - {idx}), size=self.problem.n_dims, + replace=True) vector = np.array([group[jdx].solution[kdx] for kdx, jdx in enumerate(list_rand)]) pos_new = group[idx].solution + self.generator.uniform(0, 1, self.problem.n_dims) * \ (self.local_leaders[group_idx].solution - group[idx].solution) + \ self.generator.uniform(-1, 1, self.problem.n_dims) * (vector - group[idx].solution) - pos_new = np.where(self.generator.uniform(0, 1, self.problem.n_dims) >= self.perturbation_rate, pos_new, group[idx].solution) + pos_new = np.where(self.generator.uniform(0, 1, self.problem.n_dims) >= self.perturbation_rate, pos_new, + group[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, group[idx].target, self.problem.minmax): @@ -143,8 +147,9 @@ def global_leader_phase(self): jdx = self.generator.choice(list(set(range(self.group_size)) - {idx})) pos_new = agent.solution.copy() # Update using equation (4) - pos_new[k] = pos_new[k] + self.generator.uniform(0, 1) * (self.g_best.solution[k] - pos_new[k]) +\ - self.generator.uniform(-1, 1) * (group[jdx].solution[k] - pos_new[k]) + pos_new[k] = pos_new[k] + self.generator.uniform(0, 1) * ( + self.g_best.solution[k] - pos_new[k]) + \ + self.generator.uniform(-1, 1) * (group[jdx].solution[k] - pos_new[k]) # Apply bounds pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) @@ -154,10 +159,12 @@ def global_leader_phase(self): def local_leader_decision_phase(self): """Local Leader Decision Phase - handle stagnated local leaders""" - local_leaders_new = [self.get_sorted_population(group, self.problem.minmax, return_index=False)[0] for group in self.groups] + local_leaders_new = [self.get_sorted_population(group, self.problem.minmax, return_index=False)[0] for group in + self.groups] for group_idx, group in enumerate(self.groups): # Update local limit count - if self.compare_target(self.local_leaders[group_idx].target, local_leaders_new[group_idx].target, self.problem.minmax): + if self.compare_target(self.local_leaders[group_idx].target, local_leaders_new[group_idx].target, + self.problem.minmax): self.local_limit_counts[group_idx] += 1 else: self.local_limit_counts[group_idx] = 0 @@ -171,9 +178,12 @@ def local_leader_decision_phase(self): # Random initialization pos_new_01 = self.generator.uniform(self.problem.lb, self.problem.ub, self.problem.n_dims) # Update using equation (5) - pos_new_02 = agent.solution + self.generator.uniform(0, 1, self.problem.n_dims) * (self.g_best.solution - agent.solution) + \ - self.generator.uniform(0, 1, self.problem.n_dims) * (agent.solution - self.local_leaders[group_idx].solution) - pos_new = np.where(self.generator.uniform(0, 1, self.problem.n_dims) >= self.perturbation_rate, pos_new_01, pos_new_02) + pos_new_02 = agent.solution + self.generator.uniform(0, 1, self.problem.n_dims) * ( + self.g_best.solution - agent.solution) + \ + self.generator.uniform(0, 1, self.problem.n_dims) * ( + agent.solution - self.local_leaders[group_idx].solution) + pos_new = np.where(self.generator.uniform(0, 1, self.problem.n_dims) >= self.perturbation_rate, + pos_new_01, pos_new_02) # Apply bounds pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) @@ -194,7 +204,8 @@ def global_leader_decision_phase(self): self.pop = self.merge_groups(self.groups) # Update local leaders after fission/fusion self.local_limit_counts = [0] * self.num_groups - self.local_leaders = [self.get_sorted_population(group, self.problem.minmax, return_index=False)[0] for group in self.groups] + self.local_leaders = [self.get_sorted_population(group, self.problem.minmax, return_index=False)[0] for + group in self.groups] def update_leaders(self): self.pop = self.merge_groups(self.groups) @@ -215,7 +226,6 @@ def evolve(self, epoch): epoch (int): The current iteration """ - self.local_leader_phase() self.global_leader_phase() self.update_leaders() diff --git a/mealpy/swarm_based/SRSR.py b/mealpy/swarm_based/SRSR.py index 4b6d06ac..3313eb6a 100644 --- a/mealpy/swarm_based/SRSR.py +++ b/mealpy/swarm_based/SRSR.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -40,6 +41,7 @@ class OriginalSRSR(Optimizer): [1] Bakhshipour, M., Ghadi, M.J. and Namdari, F., 2017. Swarm robotics search & rescue: A novel artificial intelligence-inspired optimization approach. Applied Soft Computing, 57, pp.708-726. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -107,7 +109,8 @@ def evolve(self, epoch): self.SIF = 6 self.sigma_temp[idx] = self.SIF * self.generator.uniform() self.pop[idx].sigma = self.sigma_temp[idx] * np.abs(self.pop[0].solution - self.pop[idx].solution) + \ - self.generator.uniform() ** 2 * ((self.pop[0].solution - self.pop[idx].solution) < 0.05) + self.generator.uniform() ** 2 * ( + (self.pop[0].solution - self.pop[idx].solution) < 0.05) # ----- Generating New Positions Using New Obtained Mu And Sigma Values -------------- pos_new = self.generator.normal(self.pop[idx].mu, self.pop[idx].sigma, self.problem.n_dims) pos_new = self.correct_solution(pos_new) @@ -146,8 +149,9 @@ def evolve(self, epoch): gb = self.generator.uniform(-1, 1, self.problem.n_dims) gb[gb >= 0] = 1 gb[gb < 0] = -1 - pos_new = self.pop[idx].solution * self.generator.uniform() + gb * (self.pop[0].solution - self.pop[idx].solution) + \ - self.movement_factor * self.generator.uniform(self.problem.lb, self.problem.ub) + pos_new = self.pop[idx].solution * self.generator.uniform() + gb * ( + self.pop[0].solution - self.pop[idx].solution) + \ + self.movement_factor * self.generator.uniform(self.problem.lb, self.problem.ub) pos_new = self.correct_solution(pos_new) agent.solution = pos_new pop_new.append(agent) @@ -176,18 +180,23 @@ def evolve(self, epoch): master_robot = {"original": np.reshape(self.pop[0].solution, (self.problem.n_dims, 1)), "sign": np.reshape(np.sign(self.pop[0].solution), (self.problem.n_dims, 1)), "abs": np.reshape(abs(self.pop[0].solution), (self.problem.n_dims, 1)), - "int": np.reshape(np.floor(abs(self.pop[0].solution)), (self.problem.n_dims, 1)), # INTEGER PART - "frac": np.reshape(abs(self.pop[0].solution) - np.floor(abs(self.pop[0].solution)), (self.problem.n_dims, 1)) + "int": np.reshape(np.floor(abs(self.pop[0].solution)), (self.problem.n_dims, 1)), + # INTEGER PART + "frac": np.reshape(abs(self.pop[0].solution) - np.floor(abs(self.pop[0].solution)), + (self.problem.n_dims, 1)) } # FRACTIONAL PART # ------- Applying Nth-root And Nth-exponent Operators To Create Position Of New Worker Robots ------- - worker_robot1 = (master_robot["int"] + np.power(master_robot["frac"], 1 / (1 + self.generator.integers(1, 4)))) * master_robot["sign"] + worker_robot1 = (master_robot["int"] + np.power(master_robot["frac"], + 1 / (1 + self.generator.integers(1, 4)))) * master_robot[ + "sign"] id_changed1 = np.argwhere(np.round(self.generator.uniform(self.problem.lb, self.problem.ub))) id_changed1 = np.reshape(id_changed1, (len(id_changed1))) worker_robot1 = np.reshape(worker_robot1, (self.problem.n_dims, 1)) worker_robot1[id_changed1] = master_robot["original"][id_changed1] - worker_robot2 = (master_robot["int"] + np.power(master_robot["frac"], (1 + self.generator.integers(1, 4)))) * master_robot["sign"] + worker_robot2 = (master_robot["int"] + np.power(master_robot["frac"], + (1 + self.generator.integers(1, 4)))) * master_robot["sign"] id_changed2 = np.argwhere(np.round(self.generator.uniform(self.problem.lb, self.problem.ub))) id_changed2 = np.reshape(id_changed2, (len(id_changed2))) worker_robot2 = np.reshape(worker_robot2, (self.problem.n_dims, 1)) @@ -199,7 +208,8 @@ def evolve(self, epoch): sec2 = random_per_mutation[int(self.problem.n_dims / 2):] worker_robot3 = np.zeros((self.problem.n_dims, 1)) worker_robot3[sec1] = (master_robot["int"][sec1] + np.power(master_robot["frac"][sec1], - 1 / (1 + self.generator.integers(1, 4)))) * master_robot["sign"][sec1] + 1 / (1 + self.generator.integers(1, 4)))) * \ + master_robot["sign"][sec1] worker_robot3[sec2] = (master_robot["int"][sec2] + master_robot["frac"][sec2] ** (1 + self.generator.integers(1, 4))) * master_robot["sign"][sec2] id_changed3 = np.argwhere(np.round(self.generator.uniform(self.problem.lb, self.problem.ub))) @@ -218,7 +228,8 @@ def evolve(self, epoch): worker_robot5[id_changed5] = master_robot["original"][id_changed5] # --------- Progress Assessment: Replacing More Quality Solutions With Previous Ones --------------- - workers = np.concatenate((worker_robot1.T, worker_robot2.T, worker_robot3.T, worker_robot4.T, worker_robot5.T), axis=0) + workers = np.concatenate( + (worker_robot1.T, worker_robot2.T, worker_robot3.T, worker_robot4.T, worker_robot5.T), axis=0) pop_workers = [] for idx in range(0, 5): pos_new = self.correct_solution(workers[idx]) diff --git a/mealpy/swarm_based/SSA.py b/mealpy/swarm_based/SSA.py index ab644ecd..b117c7b2 100644 --- a/mealpy/swarm_based/SSA.py +++ b/mealpy/swarm_based/SSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -45,7 +46,9 @@ class DevSSA(Optimizer): [1] Xue, J. and Shen, B., 2020. A novel swarm intelligence optimization approach: sparrow search algorithm. Systems Science & Control Engineering, 8(1), pp.22-34. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, ST: float = 0.8, PD: float = 0.2, SD: float = 0.1, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, ST: float = 0.8, PD: float = 0.2, SD: float = 0.1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -91,9 +94,11 @@ def evolve(self, epoch): x_new = self.pop[idx].solution + self.generator.normal() * np.ones(self.problem.n_dims) else: # Using equation (4) update the sparrow’s location; - _, (g_best, ), (g_worst, ) = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) + _, (g_best,), (g_worst,) = self.get_special_agents(self.pop, n_best=1, n_worst=1, + minmax=self.problem.minmax) if idx > int(self.pop_size / 2): - x_new = self.generator.normal() * np.exp((g_worst.solution - self.pop[idx].solution) / (idx + 1) ** 2) + x_new = self.generator.normal() * np.exp( + (g_worst.solution - self.pop[idx].solution) / (idx + 1) ** 2) else: x_new = g_best.solution + np.abs(self.pop[idx].solution - g_best.solution) * self.generator.normal() pos_new = self.correct_solution(x_new) @@ -112,7 +117,8 @@ def evolve(self, epoch): for idx in range(0, len(pop2)): # Using equation (5) update the sparrow’s location; if self.compare_target(self.pop[idx].target, g_best.target, self.problem.minmax): - x_new = pop2[idx].solution + self.generator.uniform(-1, 1) * (np.abs(pop2[idx].solution - g_worst.solution) / + x_new = pop2[idx].solution + self.generator.uniform(-1, 1) * ( + np.abs(pop2[idx].solution - g_worst.solution) / (pop2[idx].target.fitness - g_worst.target.fitness + self.EPSILON)) else: x_new = g_best.solution + self.generator.normal() * np.abs(pop2[idx].solution - g_best.solution) @@ -165,7 +171,9 @@ class OriginalSSA(DevSSA): [1] Xue, J. and Shen, B., 2020. A novel swarm intelligence optimization approach: sparrow search algorithm. Systems Science & Control Engineering, 8(1), pp.22-34. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, ST: float = 0.8, PD: float = 0.2, SD: float = 0.1, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, ST: float = 0.8, PD: float = 0.2, SD: float = 0.1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -200,7 +208,8 @@ def evolve(self, epoch): _, x_p, worst = self.get_special_agents(self.pop, n_best=1, n_worst=1, minmax=self.problem.minmax) g_best, g_worst = x_p[0], worst[0] if idx > int(self.pop_size / 2): - x_new = self.generator.normal() * np.exp((g_worst.solution - self.pop[idx].solution) / (idx + 1) ** 2) + x_new = self.generator.normal() * np.exp( + (g_worst.solution - self.pop[idx].solution) / (idx + 1) ** 2) else: L = np.ones((1, self.problem.n_dims)) A = np.sign(self.generator.uniform(-1, 1, (1, self.problem.n_dims))) @@ -222,8 +231,9 @@ def evolve(self, epoch): for idx in range(0, len(pop2)): # Using equation (5) update the sparrow’s location; if self.compare_target(self.pop[idx].target, g_best.target, self.problem.minmax): - x_new = pop2[idx].solution + self.generator.uniform(-1, 1) * (np.abs(pop2[idx].solution - g_worst.solution) / - (pop2[idx].target.fitness - g_worst.target.fitness + self.EPSILON)) + x_new = pop2[idx].solution + self.generator.uniform(-1, 1) * ( + np.abs(pop2[idx].solution - g_worst.solution) / + (pop2[idx].target.fitness - g_worst.target.fitness + self.EPSILON)) else: x_new = g_best.solution + self.generator.normal() * np.abs(pop2[idx].solution - g_best.solution) pos_new = self.correct_solution(x_new) diff --git a/mealpy/swarm_based/SSO.py b/mealpy/swarm_based/SSO.py index af1b1a1c..e00ffc82 100644 --- a/mealpy/swarm_based/SSO.py +++ b/mealpy/swarm_based/SSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -39,6 +40,7 @@ class OriginalSSO(Optimizer): [1] Mirjalili, S., Gandomi, A.H., Mirjalili, S.Z., Saremi, S., Faris, H. and Mirjalili, S.M., 2017. Salp Swarm Algorithm: A bio-inspired optimizer for engineering design problems. Advances in Engineering Software, 114, pp.163-191. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -65,8 +67,10 @@ def evolve(self, epoch): if idx < self.pop_size / 2: c2_list = self.generator.random(self.problem.n_dims) c3_list = self.generator.random(self.problem.n_dims) - pos_new_1 = self.g_best.solution + c1 * ((self.problem.ub - self.problem.lb) * c2_list + self.problem.lb) - pos_new_2 = self.g_best.solution - c1 * ((self.problem.ub - self.problem.lb) * c2_list + self.problem.lb) + pos_new_1 = self.g_best.solution + c1 * ( + (self.problem.ub - self.problem.lb) * c2_list + self.problem.lb) + pos_new_2 = self.g_best.solution - c1 * ( + (self.problem.ub - self.problem.lb) * c2_list + self.problem.lb) pos_new = np.where(c3_list < 0.5, pos_new_1, pos_new_2) else: # Eq. (3.4) in the paper diff --git a/mealpy/swarm_based/SSpiderA.py b/mealpy/swarm_based/SSpiderA.py index 05fec0e5..6c116a1a 100644 --- a/mealpy/swarm_based/SSpiderA.py +++ b/mealpy/swarm_based/SSpiderA.py @@ -6,6 +6,7 @@ import numpy as np from scipy.spatial.distance import cdist + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -48,7 +49,9 @@ class OriginalSSpiderA(Optimizer): ~~~~~~~~~~ [1] James, J.Q. and Li, V.O., 2015. A social spider algorithm for global optimization. Applied soft computing, 30, pp.614-627. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, r_a: float = 1.0, p_c: float = 0.7, p_m: float = 0.1, **kwargs: object) -> None: + + def __init__(self, epoch: int = 10000, pop_size: int = 100, r_a: float = 1.0, p_c: float = 0.7, p_m: float = 0.1, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -109,7 +112,8 @@ def evolve(self, epoch): dist = cdist(all_pos, all_pos, 'euclidean') intensity_source = np.array([it.intensity for it in self.pop]) intensity_attenuation = np.exp(-dist / (base_distance * self.r_a)) ## vector (pop_size) - intensity_receive = np.dot(np.reshape(intensity_source, (1, self.pop_size)), intensity_attenuation) ## vector (1, pop_size) + intensity_receive = np.dot(np.reshape(intensity_source, (1, self.pop_size)), + intensity_attenuation) ## vector (1, pop_size) id_best_intensity = np.argmax(intensity_receive) pop_new = [] for idx in range(0, self.pop_size): @@ -118,9 +122,11 @@ def evolve(self, epoch): agent.target_solution = self.pop[id_best_intensity].target_solution if self.generator.uniform() > self.p_c: ## changing mask agent.mask = np.where(self.generator.uniform(0, 1, self.problem.n_dims) < self.p_m, 0, 1) - pos_new = np.where(self.pop[idx].mask == 0, self.pop[idx].target_solution, self.pop[self.generator.integers(0, self.pop_size)].solution) + pos_new = np.where(self.pop[idx].mask == 0, self.pop[idx].target_solution, + self.pop[self.generator.integers(0, self.pop_size)].solution) ## Perform random walk - pos_new = self.pop[idx].solution + self.generator.normal() * (self.pop[idx].solution - self.pop[idx].local_vector) + \ + pos_new = self.pop[idx].solution + self.generator.normal() * ( + self.pop[idx].solution - self.pop[idx].local_vector) + \ (pos_new - self.pop[idx].solution) * self.generator.normal() agent.solution = self.correct_solution(pos_new) if self.mode not in self.AVAILABLE_MODES: diff --git a/mealpy/swarm_based/SSpiderO.py b/mealpy/swarm_based/SSpiderO.py index 16f41269..5da14610 100644 --- a/mealpy/swarm_based/SSpiderO.py +++ b/mealpy/swarm_based/SSpiderO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent @@ -45,7 +46,8 @@ class OriginalSSpiderO(Optimizer): optimization algorithm: modifications, applications, and perspectives. Mathematical Problems in Engineering, 2018. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, fp_min: float = 0.65, fp_max: float = 0.9, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, fp_min: float = 0.65, fp_max: float = 0.9, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -104,7 +106,8 @@ def move_females__(self, epoch=None): x_s = np.zeros(self.problem.n_dims) vibs = 0 if id_min is not None: - vibs = 2 * (pop[id_min].weight * np.exp(-(self.generator.uniform() * dist_min ** 2))) # Vib for the shortest + vibs = 2 * (pop[id_min].weight * np.exp( + -(self.generator.uniform() * dist_min ** 2))) # Vib for the shortest x_s = pop[id_min].solution ## Find the position b @@ -114,8 +117,8 @@ def move_females__(self, epoch=None): ## Do attraction or repulsion beta = self.generator.uniform(0, 1, self.problem.n_dims) gamma = self.generator.uniform(0, 1, self.problem.n_dims) - rd_pos = 2 * self.p_m[epoch-1] * (self.generator.uniform(0, 1, self.problem.n_dims) - 0.5) - if self.generator.uniform() >= self.p_m[epoch-1]: # Do an attraction + rd_pos = 2 * self.p_m[epoch - 1] * (self.generator.uniform(0, 1, self.problem.n_dims) - 0.5) + if self.generator.uniform() >= self.p_m[epoch - 1]: # Do an attraction pos_new = self.pop_females[idx].solution + vibs * (x_s - self.pop_females[idx].solution) * beta + \ vibb * (self.g_best.solution - self.pop_females[idx].solution) * gamma + rd_pos else: # Do a repulsion @@ -140,7 +143,7 @@ def move_males__(self, epoch=None): mean = np.sum(all_wei * all_pos, axis=0) / total_wei for idx in range(0, self.n_m): delta = 2 * self.generator.uniform(0, 1, self.problem.n_dims) - 0.5 - rd_pos = 2 * self.p_m[epoch-1] * (self.generator.random(self.problem.n_dims) - 0.5) + rd_pos = 2 * self.p_m[epoch - 1] * (self.generator.random(self.problem.n_dims) - 0.5) if self.pop_males[idx].weight >= my_median: # Spider above the median # Start looking for a female with stronger vibration @@ -148,7 +151,8 @@ def move_males__(self, epoch=None): dist_min = 99999999 for jdx in range(0, self.n_f): if self.pop_females[jdx].weight > self.pop_males[idx].weight: - dt = np.linalg.norm(self.pop_females[jdx].solution - self.pop_males[idx].solution) / scale_distance + dt = np.linalg.norm( + self.pop_females[jdx].solution - self.pop_males[idx].solution) / scale_distance if dt < dist_min and dt != 0: dist_min = dt id_min = jdx diff --git a/mealpy/swarm_based/STO.py b/mealpy/swarm_based/STO.py index 08adc5c3..0ab0340e 100644 --- a/mealpy/swarm_based/STO.py +++ b/mealpy/swarm_based/STO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -46,6 +47,7 @@ class OriginalSTO(Optimizer): [1] Trojovský, P., Dehghani, M., & Hanuš, P. (2022). Siberian Tiger Optimization: A New Bio-Inspired Metaheuristic Algorithm for Solving Engineering Optimization Problems. IEEE Access, 10, 132396-132431. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -86,14 +88,16 @@ def evolve(self, epoch): kk = self.generator.permutation(idxs)[0] sf = self.pop[kk] r1 = self.generator.integers(1, 3) - pos_new = self.pop[idx].solution + self.generator.random() * (sf.solution - r1 * self.pop[idx].solution) # Eq. 5 + pos_new = self.pop[idx].solution + self.generator.random() * ( + sf.solution - r1 * self.pop[idx].solution) # Eq. 5 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent # PHASE 2: CARRYING THE FISH TO THE SUITABLE POSITION (EXPLOITATION) - pos_new = self.pop[idx].solution + self.generator.random() * (self.problem.ub - self.problem.lb) / epoch # Eq. 7 + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.problem.ub - self.problem.lb) / epoch # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/SeaHO.py b/mealpy/swarm_based/SeaHO.py index d1037f4a..00c843f1 100644 --- a/mealpy/swarm_based/SeaHO.py +++ b/mealpy/swarm_based/SeaHO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -66,29 +67,33 @@ def evolve(self, epoch): epoch (int): The current iteration """ # The motor behavior of sea horses - step_length = self.get_levy_flight_step(beta=1.5, multiplier=0.01, size=(self.pop_size, self.problem.n_dims), case=-1) + step_length = self.get_levy_flight_step(beta=1.5, multiplier=0.01, size=(self.pop_size, self.problem.n_dims), + case=-1) pop_new = [] for idx in range(0, self.pop_size): beta = self.generator.normal(0, 1, self.problem.n_dims) theta = 2 * np.pi * self.generator.random(self.problem.n_dims) row = self.uu * np.exp(theta * self.vv) xx, yy, zz = row * np.cos(theta), row * np.sin(theta), row * theta - if self.generator.normal(0, 1) > 0: # Eq. 4 - pos_new = self.pop[idx].solution + step_length[idx] * ((self.g_best.solution - self.pop[idx].solution) * xx * yy * zz + self.g_best.solution) - else: # Eq. 7 - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * self.ll * beta * (self.g_best.solution - beta * self.g_best.solution) + if self.generator.normal(0, 1) > 0: # Eq. 4 + pos_new = self.pop[idx].solution + step_length[idx] * ( + (self.g_best.solution - self.pop[idx].solution) * xx * yy * zz + self.g_best.solution) + else: # Eq. 7 + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * self.ll * beta * ( + self.g_best.solution - beta * self.g_best.solution) pos_new = self.correct_solution(pos_new) pop_new.append(pos_new) # The predation behavior of sea horses pop_child = [] - alpha = (1 - epoch/self.epoch) ** (2 * epoch / self.epoch) + alpha = (1 - epoch / self.epoch) ** (2 * epoch / self.epoch) for idx in range(0, self.pop_size): r1 = self.generator.random(self.problem.n_dims) if self.generator.random() >= 0.1: - pos_new = alpha * (self.g_best.solution - r1 * pop_new[idx]) + (1 - alpha) * self.g_best.solution # Eq. 10 + pos_new = alpha * (self.g_best.solution - r1 * pop_new[idx]) + ( + 1 - alpha) * self.g_best.solution # Eq. 10 else: - pos_new = (1 - alpha) * (pop_new[idx] - r1 * self.g_best.solution) + alpha * pop_new[idx] # Eq. 11 + pos_new = (1 - alpha) * (pop_new[idx] - r1 * self.g_best.solution) + alpha * pop_new[idx] # Eq. 11 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_child.append(agent) @@ -96,15 +101,15 @@ def evolve(self, epoch): pop_child[-1].target = self.get_target(pos_new) if self.mode in self.AVAILABLE_MODES: pop_child = self.update_target_for_population(pop_child) - pop_child = self.get_sorted_population(pop_child, self.problem.minmax) # Sorted population + pop_child = self.get_sorted_population(pop_child, self.problem.minmax) # Sorted population # The reproductive behavior of sea horses - dads = pop_child[:int(self.pop_size/2)] - moms = pop_child[int(self.pop_size/2):] + dads = pop_child[:int(self.pop_size / 2)] + moms = pop_child[int(self.pop_size / 2):] pop_offspring = [] - for kdx in range(0, int(self.pop_size/2)): + for kdx in range(0, int(self.pop_size / 2)): r3 = self.generator.random() - pos_new = r3 * dads[kdx].solution + (1 - r3) * moms[kdx].solution # Eq. 13 + pos_new = r3 * dads[kdx].solution + (1 - r3) * moms[kdx].solution # Eq. 13 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_offspring.append(agent) diff --git a/mealpy/swarm_based/ServalOA.py b/mealpy/swarm_based/ServalOA.py index 5e306cee..0a6d9882 100644 --- a/mealpy/swarm_based/ServalOA.py +++ b/mealpy/swarm_based/ServalOA.py @@ -44,6 +44,7 @@ class OriginalServalOA(Optimizer): [1] Dehghani, M., & Trojovský, P. (2022). Serval Optimization Algorithm: A New Bio-Inspired Approach for Solving Optimization Problems. Biomimetics, 7(4), 204. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -68,14 +69,16 @@ def evolve(self, epoch): for idx in range(self.pop_size): # Phase 1: Prey Selection and Attacking (Exploration) pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * \ - (self.pop[kk].solution - self.generator.integers(1, 3, self.problem.n_dims) * self.pop[idx].solution) + (self.pop[kk].solution - self.generator.integers(1, 3, self.problem.n_dims) * self.pop[ + idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent # Phase 2: Chase Process (Exploitation) - pos_new = self.pop[idx].solution + self.generator.integers(1, 3, self.problem.n_dims) * (self.problem.ub - self.problem.lb) / epoch # Eq. 6 + pos_new = self.pop[idx].solution + self.generator.integers(1, 3, self.problem.n_dims) * ( + self.problem.ub - self.problem.lb) / epoch # Eq. 6 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/SquirrelSA.py b/mealpy/swarm_based/SquirrelSA.py index 91f567c6..78771461 100644 --- a/mealpy/swarm_based/SquirrelSA.py +++ b/mealpy/swarm_based/SquirrelSA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -40,6 +41,7 @@ class OriginalSquirrelSA(Optimizer): [1] Jain, M., Singh, V., & Rani, A. (2019). A novel nature-inspired algorithm for optimization: Squirrel search algorithm. Swarm and evolutionary computation, 44, 148-175. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, n_food_sources=4, predator_prob=0.1, gliding_constant=1.9, scaling_factor=18, beta=1.5, **kwargs: object) -> None: """ @@ -60,7 +62,8 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, n_food_sources=4, pr self.gliding_constant = self.validator.check_float("gliding_constant", gliding_constant, [0.0, 10.0]) self.scaling_factor = self.validator.check_float("scaling_factor", scaling_factor, [1, 100]) self.beta = self.validator.check_float("beta", beta, [0.0, 10.0]) - self.set_parameters(["epoch", "pop_size", "n_food_sources", "predator_prob", "gliding_constant", "scaling_factor", "beta"]) + self.set_parameters( + ["epoch", "pop_size", "n_food_sources", "predator_prob", "gliding_constant", "scaling_factor", "beta"]) self.sort_flag = True def initialize_variables(self): @@ -101,11 +104,12 @@ def evolve(self, epoch): # Assign roles: 1 hickory, 3 acorn, rest normal trees pop_new = self.pop.copy() # Case 1: Acorn squirrels move toward hickory tree - for idx in range(1, self.n_acorn_trees+1): + for idx in range(1, self.n_acorn_trees + 1): d_g = self.calculate_gliding_distance() if self.generator.random() >= self.predator_prob: # No predator: move toward hickory - pos_new = self.pop[idx].solution + d_g * self.gliding_constant * (self.g_best.solution - self.pop[idx].solution) + pos_new = self.pop[idx].solution + d_g * self.gliding_constant * ( + self.g_best.solution - self.pop[idx].solution) else: # Predator present: random location pos_new = self.generator.uniform(self.problem.lb, self.problem.ub, self.problem.n_dims) @@ -118,7 +122,7 @@ def evolve(self, epoch): # Case 2: Normal squirrels move toward acorn trees indices_random = np.array(list(range(self.pop_size - self.n_food_sources))) self.generator.shuffle(indices_random) - indices_random = indices_random + self.n_food_sources # True indices of normal squirrels + indices_random = indices_random + self.n_food_sources # True indices of normal squirrels n_cut = self.generator.integers(1, self.pop_size - self.n_food_sources - 1) for idx in indices_random[n_cut:]: # Select random acorn tree @@ -126,7 +130,8 @@ def evolve(self, epoch): d_g = self.calculate_gliding_distance() if self.generator.random() >= self.predator_prob: # No predator: move toward acorn - pos_new = self.pop[idx].solution + d_g * self.gliding_constant * (self.pop[jdx].solution - self.pop[idx].solution) + pos_new = self.pop[idx].solution + d_g * self.gliding_constant * ( + self.pop[jdx].solution - self.pop[idx].solution) else: # Predator present: random location pos_new = self.generator.uniform(self.problem.lb, self.problem.ub, self.problem.n_dims) @@ -141,7 +146,8 @@ def evolve(self, epoch): d_g = self.calculate_gliding_distance() if self.generator.random() >= self.predator_prob: # No predator: move toward hickory - pos_new = self.pop[idx].solution + d_g * self.gliding_constant * (self.pop[0].solution - self.pop[idx].solution) + pos_new = self.pop[idx].solution + d_g * self.gliding_constant * ( + self.pop[0].solution - self.pop[idx].solution) else: # Predator present: random location pos_new = self.generator.uniform(self.problem.lb, self.problem.ub, self.problem.n_dims) @@ -152,7 +158,8 @@ def evolve(self, epoch): pop_new[idx] = agent # Seasonal monitoring condition - S_c = np.mean([ np.sqrt(np.sum((self.pop[idx].solution - self.pop[0].solution)**2)) for idx in range(1, self.n_food_sources) ]) + S_c = np.mean([np.sqrt(np.sum((self.pop[idx].solution - self.pop[0].solution) ** 2)) for idx in + range(1, self.n_food_sources)]) # Calculate minimum seasonal constant S_min = (10e-6 / 365) * (epoch / (self.epoch / 2.5)) @@ -161,7 +168,7 @@ def evolve(self, epoch): n_relocate = max(1, len(self.pop_size - self.n_food_sources) // 4) relocate_indices = self.generator.choice(indices_random, n_relocate, replace=False) for idx in relocate_indices: - levy = self.get_levy_flight_step(beta = self.beta, multiplier = 0.01, size = self.problem.n_dims, case = -1) + levy = self.get_levy_flight_step(beta=self.beta, multiplier=0.01, size=self.problem.n_dims, case=-1) pos_new = self.problem.lb + levy * (self.problem.ub - self.problem.lb) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) diff --git a/mealpy/swarm_based/TDO.py b/mealpy/swarm_based/TDO.py index 3ce8b31b..8fd85c23 100644 --- a/mealpy/swarm_based/TDO.py +++ b/mealpy/swarm_based/TDO.py @@ -4,7 +4,6 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np from mealpy.optimizer import Optimizer @@ -46,6 +45,7 @@ class OriginalTDO(Optimizer): [1] Dehghani, M., Hubálovský, Š., & Trojovský, P. (2022). Tasmanian devil optimization: a new bio-inspired optimization algorithm for solving optimization algorithm. IEEE Access, 10, 19599-19620. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -73,29 +73,34 @@ def evolve(self, epoch): # CARRION selection using (3) kk = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[kk].solution - self.generator.integers(1, 3)*self.pop[idx].solution) + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[idx].solution - self.pop[kk].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent else: - # STRATEGY 2: FEEDING BY EATING PREY (EXPLOITATION PHASE) - # stage1: prey selection and attack it + # STRATEGY 2: FEEDING BY EATING PREY (EXPLOITATION PHASE) + # stage1: prey selection and attack it kk = self.generator.choice(list(set(range(0, self.pop_size)) - {idx})) if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[idx].solution - self.pop[kk].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): self.pop[idx] = agent # stage2: prey chasing - rr = 0.01 * (1 - epoch/self.epoch) # Calculating the neighborhood radius using(9) - pos_new = self.pop[idx].solution + (-rr + 2 * rr * self.generator.random(self.problem.n_dims)) * self.pop[idx].solution + rr = 0.01 * (1 - epoch / self.epoch) # Calculating the neighborhood radius using(9) + pos_new = self.pop[idx].solution + (-rr + 2 * rr * self.generator.random(self.problem.n_dims)) * self.pop[ + idx].solution pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/TSO.py b/mealpy/swarm_based/TSO.py index a5e02fe8..9c02c88c 100644 --- a/mealpy/swarm_based/TSO.py +++ b/mealpy/swarm_based/TSO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -41,6 +42,7 @@ class OriginalTSO(Optimizer): [1] Xie, L., Han, T., Zhou, H., Zhang, Z. R., Han, B., & Tang, A. (2021). Tuna swarm optimization: a novel swarm-based metaheuristic algorithm for global optimization. Computational intelligence and Neuroscience, 2021. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -63,19 +65,23 @@ def get_new_local_pos__(self, C, a1, a2, t, epoch): else: if self.generator.random() < 0.5: r1 = self.generator.random() - beta = np.exp(r1 * np.exp(3*np.cos(np.pi*((self.epoch - epoch) / self.epoch)))) * np.cos(2*np.pi*r1) + beta = np.exp(r1 * np.exp(3 * np.cos(np.pi * ((self.epoch - epoch) / self.epoch)))) * np.cos( + 2 * np.pi * r1) if self.generator.random() < C: - local_pos = a1*(self.g_best.solution + beta * np.abs(self.g_best.solution - self.pop[0].solution)) + a2 * self.pop[0].solution # Eq (8.3) + local_pos = a1 * (self.g_best.solution + beta * np.abs( + self.g_best.solution - self.pop[0].solution)) + a2 * self.pop[0].solution # Eq (8.3) else: rand_pos = self.problem.generate_solution() - local_pos = a1 * (rand_pos + beta*np.abs(rand_pos - self.pop[0].solution)) + a2 * self.pop[0].solution # Eq (8.1) + local_pos = a1 * (rand_pos + beta * np.abs(rand_pos - self.pop[0].solution)) + a2 * self.pop[ + 0].solution # Eq (8.1) else: tf = self.generator.choice([-1, 1]) if self.generator.random() < 0.5: - local_pos = tf * t**2 * self.pop[0].solution # Eq 9.2 + local_pos = tf * t ** 2 * self.pop[0].solution # Eq 9.2 else: - local_pos = self.g_best.solution + self.generator.random(self.problem.n_dims) * (self.g_best.solution - self.pop[0].solution) + \ - tf * t**2 * (self.g_best.solution - self.pop[0].solution) + local_pos = self.g_best.solution + self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - self.pop[0].solution) + \ + tf * t ** 2 * (self.g_best.solution - self.pop[0].solution) return local_pos def evolve(self, epoch): @@ -99,20 +105,24 @@ def evolve(self, epoch): else: if self.generator.random() > 0.5: r1 = self.generator.random() - beta = np.exp(r1 * np.exp(3*np.cos(np.pi * (self.epoch - epoch)/self.epoch))) * np.cos(2*np.pi*r1) + beta = np.exp(r1 * np.exp(3 * np.cos(np.pi * (self.epoch - epoch) / self.epoch))) * np.cos( + 2 * np.pi * r1) if self.generator.random() < C: - pos_new = a1 * (self.g_best.solution + beta*np.abs(self.g_best.solution - self.pop[idx].solution)) + \ - a2 * self.pop[idx-1].solution # Eq. 8.4 + pos_new = a1 * (self.g_best.solution + beta * np.abs( + self.g_best.solution - self.pop[idx].solution)) + \ + a2 * self.pop[idx - 1].solution # Eq. 8.4 else: rand_pos = self.problem.generate_solution() - pos_new = a1 * (rand_pos + beta*np.abs(rand_pos - self.pop[idx].solution)) + a2 * self.pop[idx-1].solution # Eq 8.2 + pos_new = a1 * (rand_pos + beta * np.abs(rand_pos - self.pop[idx].solution)) + a2 * \ + self.pop[idx - 1].solution # Eq 8.2 else: tf = self.generator.choice([-1, 1]) if self.generator.random() < 0.5: pos_new = self.g_best.solution + self.generator.random(self.problem.n_dims) * \ - (self.g_best.solution - self.pop[idx].solution) + tf * tt**2 * (self.g_best.solution - self.pop[idx].solution) # Eq 9.1 + (self.g_best.solution - self.pop[idx].solution) + tf * tt ** 2 * ( + self.g_best.solution - self.pop[idx].solution) # Eq 9.1 else: - pos_new = tf * tt**2 * self.pop[idx].solution # Eq 9.2 + pos_new = tf * tt ** 2 * self.pop[idx].solution # Eq 9.2 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/swarm_based/WOA.py b/mealpy/swarm_based/WOA.py index e51df854..bbdeb4dd 100644 --- a/mealpy/swarm_based/WOA.py +++ b/mealpy/swarm_based/WOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -39,6 +40,7 @@ class OriginalWOA(Optimizer): ~~~~~~~~~~ [1] Mirjalili, S. and Lewis, A., 2016. The whale optimization algorithm. Advances in engineering software, 95, pp.51-67. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -78,7 +80,7 @@ def evolve(self, epoch): pos_new[jdx] = self.pop[id_r].solution[jdx] - A * D_X_rand else: D_Leader = abs(C * self.g_best.solution[jdx] - self.pop[idx].solution[jdx]) - pos_new[jdx] = self.g_best.solution[jdx]- A * D_Leader + pos_new[jdx] = self.g_best.solution[jdx] - A * D_Leader else: D1 = abs(self.g_best.solution[jdx] - self.pop[idx].solution[jdx]) pos_new[jdx] = D1 * np.exp(b * l) * np.cos(l * 2 * np.pi) + self.g_best.solution[jdx] @@ -122,6 +124,7 @@ class DevWOA(Optimizer): ~~~~~~~~~~ [1] Mirjalili, S. and Lewis, A., 2016. The whale optimization algorithm. Advances in engineering software, 95, pp.51-67. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -212,6 +215,7 @@ class HI_WOA(Optimizer): [1] Tang, C., Sun, W., Wu, W. and Xue, M., 2019, July. A hybrid improved whale optimization algorithm. In 2019 IEEE 15th International Conference on Control and Automation (ICCA) (pp. 362-367). IEEE. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, feedback_max: int = 10, **kwargs: object) -> None: """ Args: @@ -222,7 +226,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, feedback_max: int = super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.feedback_max = self.validator.check_int("feedback_max", feedback_max, [2, 2+int(self.epoch/2)]) + self.feedback_max = self.validator.check_int("feedback_max", feedback_max, [2, 2 + int(self.epoch / 2)]) # The maximum of times g_best doesn't change -> need to change half of population self.set_parameters(["epoch", "pop_size", "feedback_max"]) self.sort_flag = True diff --git a/mealpy/swarm_based/WaOA.py b/mealpy/swarm_based/WaOA.py index d808226d..7ffa6a90 100644 --- a/mealpy/swarm_based/WaOA.py +++ b/mealpy/swarm_based/WaOA.py @@ -43,6 +43,7 @@ class OriginalWaOA(Optimizer): ~~~~~~~~~~ [1] Trojovský, P., & Dehghani, M. (2022). Walrus Optimization Algorithm: A New Bio-Inspired Metaheuristic Algorithm. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -66,10 +67,12 @@ def evolve(self, epoch): for idx in range(0, self.pop_size): # Phase 1: Feeding strategy (exploration) kk = self.generator.permutation(self.pop_size)[0] - if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): # Eq. 4 - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) + if self.compare_target(self.pop[kk].target, self.pop[idx].target, self.problem.minmax): # Eq. 4 + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[kk].solution - self.generator.integers(1, 3) * self.pop[idx].solution) else: - pos_new = self.pop[idx].solution + self.generator.random() * (self.pop[idx].solution - self.pop[kk].solution) + pos_new = self.pop[idx].solution + self.generator.random() * ( + self.pop[idx].solution - self.pop[kk].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): @@ -77,7 +80,7 @@ def evolve(self, epoch): # PHASE 2 Exploitation LB, UB = self.problem.lb / epoch, self.problem.ub / epoch - pos_new = self.pop[idx].solution + LB + (UB - self.generator.random() * LB) # Eq. 7 + pos_new = self.pop[idx].solution + LB + (UB - self.generator.random() * LB) # Eq. 7 pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop[idx].target, self.problem.minmax): diff --git a/mealpy/swarm_based/ZOA.py b/mealpy/swarm_based/ZOA.py index 6a9b409b..88b0564e 100644 --- a/mealpy/swarm_based/ZOA.py +++ b/mealpy/swarm_based/ZOA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -46,6 +47,7 @@ class OriginalZOA(Optimizer): [1] Trojovská, E., Dehghani, M., & Trojovský, P. (2022). Zebra optimization algorithm: A new bio-inspired optimization algorithm for solving optimization algorithm. IEEE Access, 10, 49445-49473. """ + def __init__(self, epoch: int = 10000, pop_size: int = 100, **kwargs: object) -> None: """ Args: @@ -69,7 +71,8 @@ def evolve(self, epoch): pop_new = [] for idx in range(0, self.pop_size): r1 = np.round(1 + self.generator.random()) - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.g_best.solution - r1 * self.pop[idx].solution) # Eq. 3 + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.g_best.solution - r1 * self.pop[idx].solution) # Eq. 3 pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -87,11 +90,13 @@ def evolve(self, epoch): if self.generator.random() < 0.5: # S1: the lion attacks the zebra and thus the zebra chooses an escape strategy r2 = 0.1 - pos_new = self.pop[idx].solution + r2 * (2 + self.generator.random(self.problem.n_dims) - 1) * (1 - epoch/self.epoch)*self.pop[idx].solution + pos_new = self.pop[idx].solution + r2 * (2 + self.generator.random(self.problem.n_dims) - 1) * ( + 1 - epoch / self.epoch) * self.pop[idx].solution else: # S2: other predators attack the zebra and the zebra will choose the offensive strategy r2 = self.generator.integers(1, 3) - pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * (self.pop[kk].solution - r2 * self.pop[idx].solution) + pos_new = self.pop[idx].solution + self.generator.random(self.problem.n_dims) * ( + self.pop[kk].solution - r2 * self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) diff --git a/mealpy/system_based/AEO.py b/mealpy/system_based/AEO.py index 7935a9a1..f188de1d 100644 --- a/mealpy/system_based/AEO.py +++ b/mealpy/system_based/AEO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -86,7 +87,7 @@ def evolve(self, epoch): else: r2 = self.generator.uniform() x_t1 = self.pop[idx].solution + c * (r2 * (self.pop[idx].solution - self.pop[0].solution) - + (1 - r2) * (self.pop[idx].solution - self.pop[jdx].solution)) + + (1 - r2) * (self.pop[idx].solution - self.pop[jdx].solution)) pos_new = self.correct_solution(x_t1) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -212,7 +213,7 @@ def evolve(self, epoch): e = r3 * self.generator.integers(1, 3) - 1 h = 2 * r3 - 1 if self.generator.random() < 0.5: - beta = 1 - (1 - 0) * (epoch/ self.epoch) # Eq. 21 + beta = 1 - (1 - 0) * (epoch / self.epoch) # Eq. 21 x_r = self.pop[self.generator.integers(0, self.pop_size - 1)].solution if self.generator.random() < 0.5: x_new = beta * x_r + (1 - beta) * self.pop[idx].solution @@ -317,11 +318,13 @@ def evolve(self, epoch): else: # Eq. 17 r5 = self.generator.random() if r4 <= 0.5: - x_t1 = self.pop[idx].solution + np.sin(r5) * c * (r5 * (self.pop[idx].solution - self.pop[0].solution) + - (1 - r5) * (self.pop[idx].solution - self.pop[j].solution)) + x_t1 = self.pop[idx].solution + np.sin(r5) * c * ( + r5 * (self.pop[idx].solution - self.pop[0].solution) + + (1 - r5) * (self.pop[idx].solution - self.pop[j].solution)) else: - x_t1 = self.pop[idx].solution + np.cos(r5) * c * (r5 * (self.pop[idx].solution - self.pop[0].solution) + - (1 - r5) * (self.pop[idx].solution - self.pop[j].solution)) + x_t1 = self.pop[idx].solution + np.cos(r5) * c * ( + r5 * (self.pop[idx].solution - self.pop[0].solution) + + (1 - r5) * (self.pop[idx].solution - self.pop[j].solution)) pos_new = self.correct_solution(x_t1) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -441,7 +444,7 @@ def evolve(self, epoch): else: # Eq. 25 r5 = self.generator.random() pos_new = self.pop[idx].solution + H * c * (r5 * (self.pop[idx].solution - self.pop[0].solution) + - (1 - r5) * (self.pop[idx].solution - self.pop[j].solution)) + (1 - r5) * (self.pop[idx].solution - self.pop[j].solution)) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -560,10 +563,12 @@ def evolve(self, epoch): else: r2 = self.generator.uniform() pos_new = self.pop[idx].solution + wf * c * (r2 * (self.pop[idx].solution - self.pop[0].solution) + - (1 - r2) * (self.pop[idx].solution - self.pop[j].solution)) + (1 - r2) * (self.pop[idx].solution - self.pop[ + j].solution)) else: pos_new = self.pop[idx].solution + self.get_levy_flight_step(1., 0.001, case=-1) * \ - (1.0 / np.sqrt(epoch)) * np.sign(self.generator.random() - 0.5) * (self.pop[idx].solution - self.g_best.solution) + (1.0 / np.sqrt(epoch)) * np.sign(self.generator.random() - 0.5) * ( + self.pop[idx].solution - self.g_best.solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_new.append(agent) @@ -580,10 +585,13 @@ def evolve(self, epoch): pop_child = [] for idx in range(0, self.pop_size): if self.generator.random() < 0.5: - pos_new = best.solution + self.generator.normal(0, 1, self.problem.n_dims) * (best.solution - self.pop[idx].solution) + pos_new = best.solution + self.generator.normal(0, 1, self.problem.n_dims) * ( + best.solution - self.pop[idx].solution) else: beta = self.generator.uniform(0.01, 1.) - pos_new = best.solution + self.get_levy_flight_step(beta=beta, multiplier=0.01, size=self.problem.n_dims, case=0) * (best.solution - self.pop[idx].solution) + pos_new = best.solution + self.get_levy_flight_step(beta=beta, multiplier=0.01, + size=self.problem.n_dims, case=0) * ( + best.solution - self.pop[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) pop_child.append(agent) diff --git a/mealpy/system_based/GCO.py b/mealpy/system_based/GCO.py index 0c67e626..93518414 100644 --- a/mealpy/system_based/GCO.py +++ b/mealpy/system_based/GCO.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -39,7 +40,8 @@ class DevGCO(Optimizer): >>> print(f"Solution: {model.g_best.solution}, Fitness: {model.g_best.target.fitness}") """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, cr: float = 0.7, wf: float = 1.25, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, cr: float = 0.7, wf: float = 1.25, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -94,7 +96,8 @@ def evolve(self, epoch): fit_list = np.array([agent.target.fitness for agent in self.pop]) fit_max = np.max(fit_list) fit_min = np.min(fit_list) - self.dyn_list_cell_counter[idx] += 10 * (self.pop[idx].target.fitness - fit_max) / (fit_min - fit_max + self.EPSILON) + self.dyn_list_cell_counter[idx] += 10 * (self.pop[idx].target.fitness - fit_max) / ( + fit_min - fit_max + self.EPSILON) class OriginalGCO(DevGCO): @@ -134,7 +137,8 @@ class OriginalGCO(DevGCO): Germinal center optimization algorithm. International Journal of Computational Intelligence Systems, 12(1), p.13. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, cr: float = 0.7, wf: float = 1.25, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, cr: float = 0.7, wf: float = 1.25, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 diff --git a/mealpy/system_based/WCA.py b/mealpy/system_based/WCA.py index 30888bfd..6568727f 100644 --- a/mealpy/system_based/WCA.py +++ b/mealpy/system_based/WCA.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.optimizer import Optimizer @@ -52,7 +53,8 @@ class OriginalWCA(Optimizer): optimization method for solving constrained engineering optimization problems. Computers & Structures, 110, pp.151-166. """ - def __init__(self, epoch: int = 10000, pop_size: int = 100, nsr: int = 4, wc: float = 2.0, dmax: float = 1e-6, **kwargs: object) -> None: + def __init__(self, epoch: int = 10000, pop_size: int = 100, nsr: int = 4, wc: float = 2.0, dmax: float = 1e-6, + **kwargs: object) -> None: """ Args: epoch (int): maximum number of iterations, default = 10000 @@ -64,7 +66,7 @@ def __init__(self, epoch: int = 10000, pop_size: int = 100, nsr: int = 4, wc: fl super().__init__(**kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [5, 10000]) - self.nsr = self.validator.check_int("nsr", nsr, [2, int(self.pop_size/2)]) + self.nsr = self.validator.check_int("nsr", nsr, [2, int(self.pop_size / 2)]) self.wc = self.validator.check_float("wc", wc, (1.0, 3.0)) self.dmax = self.validator.check_float("dmax", dmax, (0, 1.0)) self.set_parameters(["epoch", "pop_size", "nsr", "wc", "dmax"]) @@ -79,7 +81,7 @@ def initialization(self): n_stream = self.pop_size - self.nsr g_best = self.pop[0].copy() # Global best solution (sea) self.pop_best = self.pop[:self.nsr] # Including sea and river (1st solution is sea) - self.pop_stream = self.pop[self.nsr:] # Forming Stream + self.pop_stream = self.pop[self.nsr:] # Forming Stream # Designate streams to rivers and sea cost_river_list = np.array([agent.target.fitness for agent in self.pop_best]) @@ -90,7 +92,8 @@ def initialization(self): idx_already_selected = [] for i in range(0, self.nsr - 1): streams[i] = [] - idx_list = self.generator.choice(list(set(range(0, n_stream)) - set(idx_already_selected)), num_child_in_river_list[i], replace=False).tolist() + idx_list = self.generator.choice(list(set(range(0, n_stream)) - set(idx_already_selected)), + num_child_in_river_list[i], replace=False).tolist() idx_already_selected += idx_list for idx in idx_list: streams[i].append(self.pop_stream[idx]) @@ -112,7 +115,8 @@ def evolve(self, epoch): # Update stream stream_new = [] for idx_stream, stream in enumerate(stream_list): - pos_new = stream.solution + self.generator.uniform() * self.wc * (self.pop_best[idx].solution - stream.solution) + pos_new = stream.solution + self.generator.uniform() * self.wc * ( + self.pop_best[idx].solution - stream.solution) pos_new = self.correct_solution(pos_new) agent = self.generate_empty_agent(pos_new) stream_new.append(agent) @@ -124,7 +128,8 @@ def evolve(self, epoch): if self.compare_target(stream_best.target, self.pop_best[idx].target, self.problem.minmax): self.pop_best[idx] = stream_best.copy() # Update river - pos_new = self.pop_best[idx].solution + self.generator.uniform() * self.wc * (self.g_best.solution - self.pop_best[idx].solution) + pos_new = self.pop_best[idx].solution + self.generator.uniform() * self.wc * ( + self.g_best.solution - self.pop_best[idx].solution) pos_new = self.correct_solution(pos_new) agent = self.generate_agent(pos_new) if self.compare_target(agent.target, self.pop_best[idx].target, self.problem.minmax): diff --git a/mealpy/tuner.py b/mealpy/tuner.py index 4a429698..f1048714 100644 --- a/mealpy/tuner.py +++ b/mealpy/tuner.py @@ -4,23 +4,25 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% +import concurrent.futures as parallel +import operator +import os +import platform +from collections import abc +from functools import partial, reduce +from itertools import product +from pathlib import Path from typing import Union, List, Tuple, Dict + +import matplotlib.pyplot as plt import numpy as np import pandas as pd -import matplotlib.pyplot as plt -from pathlib import Path -from mealpy.utils.termination import Termination + from mealpy.optimizer import Optimizer from mealpy.utils.agent import Agent from mealpy.utils.problem import Problem +from mealpy.utils.termination import Termination from mealpy.utils.validator import Validator -from collections import abc -from functools import partial, reduce -from itertools import product -import concurrent.futures as parallel -import operator -import os -import platform class ParameterGrid: @@ -58,7 +60,8 @@ class ParameterGrid: def __init__(self, param_grid): if not isinstance(param_grid, (abc.Mapping, abc.Iterable)): - raise TypeError(f"Parameter grid should be a dict or a list, got: {param_grid!r} of type {type(param_grid).__name__}") + raise TypeError( + f"Parameter grid should be a dict or a list, got: {param_grid!r} of type {type(param_grid).__name__}") if isinstance(param_grid, abc.Mapping): # wrap dictionary in a singleton list to support either dict or list of dicts @@ -70,14 +73,16 @@ def __init__(self, param_grid): raise TypeError(f"Parameter grid is not a dict ({grid!r})") for key, value in grid.items(): if isinstance(value, np.ndarray) and value.ndim > 1: - raise ValueError(f"Parameter array for {key!r} should be one-dimensional, got: {value!r} with shape {value.shape}") + raise ValueError( + f"Parameter array for {key!r} should be one-dimensional, got: {value!r} with shape {value.shape}") if isinstance(value, str) or not isinstance(value, (np.ndarray, abc.Sequence)): raise TypeError( f"Parameter grid for parameter {key!r} needs to be a list or a" f" numpy array, but got {value!r} (of type {type(value).__name__}) instead. Single values " "need to be wrapped in a list with one element.") if len(value) == 0: - raise ValueError(f"Parameter grid for parameter {key!r} need to be a non-empty sequence, got: {value!r}") + raise ValueError( + f"Parameter grid for parameter {key!r} need to be a non-empty sequence, got: {value!r}") self.param_grid = param_grid def __iter__(self): @@ -209,7 +214,8 @@ class Tuner: >>> print(tuner.best_algorithm.get_name()) """ - def __init__(self, algorithm: Union[str, Optimizer] = None, param_grid: Union[Dict, List] = None, **kwargs: object) -> None: + def __init__(self, algorithm: Union[str, Optimizer] = None, param_grid: Union[Dict, List] = None, + **kwargs: object) -> None: self.__set_keyword_arguments(kwargs) self.validator = Validator(log_to="console", log_file=None) self.algorithm = self.validator.check_is_instance("algorithm", algorithm, Optimizer) @@ -341,7 +347,7 @@ def __run__(self, id_trial, mode="single", n_workers=None, termination=None): return id_trial, g_best, self.algorithm.history.list_global_best_fit def __generate_dict_from_list(self, my_list): - keys = np.arange(1, len(my_list)+1) + keys = np.arange(1, len(my_list) + 1) return dict(zip(keys, my_list)) def __generate_dict_result(self, params, trial, loss_list): @@ -351,7 +357,8 @@ def __generate_dict_result(self, params, trial, loss_list): return result_dict def execute(self, problem: Union[Dict, Problem] = None, termination: Union[Dict, Termination] = None, - n_trials: int = 2, n_jobs: int = None, mode: str = "single", n_workers: int = 2, verbose: bool = True) -> None: + n_trials: int = 2, n_jobs: int = None, mode: str = "single", n_workers: int = 2, + verbose: bool = True) -> None: """Execute Tuner utility Args: @@ -390,26 +397,30 @@ def execute(self, problem: Union[Dict, Problem] = None, termination: Union[Dict, trial_list = list(range(0, self.n_trials)) if n_cpus is not None: with parallel.ProcessPoolExecutor(n_cpus) as executor: - list_results = executor.map(partial(self.__run__, n_workers=n_workers, mode=mode, termination=termination), trial_list) + list_results = executor.map( + partial(self.__run__, n_workers=n_workers, mode=mode, termination=termination), trial_list) for (idx, g_best, loss_epoch) in list_results: best_fit_results[-1][trial_columns[idx]] = g_best.target.fitness loss_results.append(self.__generate_dict_result(params, idx, loss_epoch)) if verbose: - print(f"Algorithm: {self.algorithm.get_name()}, with params: {params}, trial: {idx + 1}, best fitness: {g_best.target.fitness}") + print( + f"Algorithm: {self.algorithm.get_name()}, with params: {params}, trial: {idx + 1}, best fitness: {g_best.target.fitness}") else: for idx in trial_list: idx, g_best, loss_epoch = self.__run__(idx, mode=mode, n_workers=n_workers, termination=termination) best_fit_results[-1][trial_columns[idx]] = g_best.target.fitness loss_results.append(self.__generate_dict_result(params, idx, loss_epoch)) if verbose: - print(f"Algorithm: {self.algorithm.get_name()}, with params: {params}, trial: {idx+1}, best fitness: {g_best.target.fitness}") + print( + f"Algorithm: {self.algorithm.get_name()}, with params: {params}, trial: {idx + 1}, best fitness: {g_best.target.fitness}") self.df_fit = pd.DataFrame(best_fit_results) self.df_fit["trial_mean"] = self.df_fit[trial_columns].mean(axis=1) self.df_fit["trial_std"] = self.df_fit[trial_columns].std(axis=1) self.df_fit["rank_mean"] = self.df_fit["trial_mean"].rank(ascending=ascending) self.df_fit["rank_std"] = self.df_fit["trial_std"].rank(ascending=ascending) - self.df_fit["rank_mean_std"] = self.df_fit[["rank_mean", "rank_std"]].apply(tuple, axis=1).rank(method='dense', ascending=ascending) + self.df_fit["rank_mean_std"] = self.df_fit[["rank_mean", "rank_std"]].apply(tuple, axis=1).rank(method='dense', + ascending=ascending) self._best_row = self.df_fit[self.df_fit["rank_mean_std"] == self.df_fit["rank_mean_std"].min()] self._best_params = self._best_row["params"].values[0] self._best_score = self._best_row["trial_mean"].values[0] diff --git a/mealpy/utils/__init__.py b/mealpy/utils/__init__.py index 7ae9c295..19a05b8e 100644 --- a/mealpy/utils/__init__.py +++ b/mealpy/utils/__init__.py @@ -4,12 +4,12 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% +from . import chaotic +from . import fuzzy from . import history +from . import io +from . import logger from . import problem from . import termination -from . import visualize from . import validator -from . import io -from . import logger -from . import chaotic -from . import fuzzy +from . import visualize diff --git a/mealpy/utils/agent.py b/mealpy/utils/agent.py index 4c785ead..791f1061 100644 --- a/mealpy/utils/agent.py +++ b/mealpy/utils/agent.py @@ -5,7 +5,9 @@ # --------------------------------------------------% from typing import Any + import numpy as np + from mealpy.utils.target import Target @@ -96,7 +98,7 @@ def is_better_than(self, other: "Agent", minmax: str = "min") -> bool: """ return self._compare_fitness(other, minmax) == -1 - def __repr__(self): # represent + def __repr__(self): # represent return f"id: {self.id}, target: {self.target}, solution: {self.solution}" def __eq__(self, other): diff --git a/mealpy/utils/history.py b/mealpy/utils/history.py index d25b2b2b..23c14ceb 100644 --- a/mealpy/utils/history.py +++ b/mealpy/utils/history.py @@ -5,6 +5,7 @@ # --------------------------------------------------% import numpy as np + from mealpy.utils import visualize from mealpy.utils.agent import Agent from mealpy.utils.logger import Logger @@ -82,12 +83,12 @@ def __init__(self, **kwargs): self.list_diversity = [] # List of diversity of swarm in all generations self.list_exploitation = [] # List of exploitation percentages for all generations self.list_exploration = [] # List of exploration percentages for all generations - self.list_global_worst = [] # List of global worst solution found so far in all previous generations - self.list_current_worst = [] # List of current worst solution in each previous generations + self.list_global_worst = [] # List of global worst solution found so far in all previous generations + self.list_current_worst = [] # List of current worst solution in each previous generations self.epoch, self.log_to, self.log_file = None, None, None self.__set_keyword_arguments(kwargs) self.logger = Logger(self.log_to, log_file=self.log_file).create_logger(name=f"{__name__}.{__class__.__name__}", - format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') + format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') def __set_keyword_arguments(self, kwargs): for key, value in kwargs.items(): @@ -109,38 +110,49 @@ def get_global_repeated_times(self, epsilon: float) -> int: count = 0 return count - def save_global_best_fitness_chart(self, title='Global Best Fitness', legend=None, linestyle='-', color='b', x_label="#Iteration", - y_label="Function Value", filename="global-best-fitness-chart", exts=(".png", ".pdf"), verbose=True): + def save_global_best_fitness_chart(self, title='Global Best Fitness', legend=None, linestyle='-', color='b', + x_label="#Iteration", + y_label="Function Value", filename="global-best-fitness-chart", + exts=(".png", ".pdf"), verbose=True): # Draw global best fitness found so far in previous generations - visualize.export_convergence_chart(data=self.list_global_best_fit, title=title, legend=legend, linestyle=linestyle, - color=color, x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose) - - def save_local_best_fitness_chart(self, title='Local Best Fitness', legend=None, linestyle='-', color='b', x_label="#Iteration", - y_label="Function Value", filename="local-best-fitness-chart", exts=(".png", ".pdf"), verbose=True): + visualize.export_convergence_chart(data=self.list_global_best_fit, title=title, legend=legend, + linestyle=linestyle, + color=color, x_label=x_label, y_label=y_label, filename=filename, exts=exts, + verbose=verbose) + + def save_local_best_fitness_chart(self, title='Local Best Fitness', legend=None, linestyle='-', color='b', + x_label="#Iteration", + y_label="Function Value", filename="local-best-fitness-chart", + exts=(".png", ".pdf"), verbose=True): # Draw current best fitness in each previous generation - visualize.export_convergence_chart(self.list_current_best_fit, title=title, legend=legend, linestyle=linestyle, color=color, - x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose) + visualize.export_convergence_chart(self.list_current_best_fit, title=title, legend=legend, linestyle=linestyle, + color=color, + x_label=x_label, y_label=y_label, filename=filename, exts=exts, + verbose=verbose) def save_runtime_chart(self, title='Runtime chart', legend=None, linestyle='-', color='b', x_label="#Iteration", y_label='Second', filename="runtime-chart", exts=(".png", ".pdf"), verbose=True): # Draw runtime for each generation - visualize.export_convergence_chart(self.list_epoch_time, title=title, legend=legend, linestyle=linestyle, color=color, - x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose) + visualize.export_convergence_chart(self.list_epoch_time, title=title, legend=legend, linestyle=linestyle, + color=color, + x_label=x_label, y_label=y_label, filename=filename, exts=exts, + verbose=verbose) ## The paper: On the exploration and exploitation in popular swarm-based metaheuristic algorithms - def save_exploration_exploitation_chart(self, title="Exploration vs Exploitation Percentages", list_colors=('blue', 'orange'), + def save_exploration_exploitation_chart(self, title="Exploration vs Exploitation Percentages", + list_colors=('blue', 'orange'), filename="exploration-exploitation-chart", verbose=True): # This exploration/exploitation chart should draws for single algorithm and single fitness function # Draw exploration and exploitation chart visualize.export_explore_exploit_chart(data=[self.list_exploration, self.list_exploitation], title=title, - list_colors=list_colors, filename=filename, verbose=verbose) + list_colors=list_colors, filename=filename, verbose=verbose) def save_diversity_chart(self, title='Diversity Measurement Chart', algorithm_name='Algorithm', filename="diversity-chart", verbose=True): # This diversity chart should draws for multiple algorithms for a single fitness function at the same time # to compare the diversity spreading visualize.export_diversity_chart(data=[self.list_diversity], title=title, list_legends=[algorithm_name], - filename=filename, verbose=verbose) + filename=filename, verbose=verbose) ## Because convergence chart is formulated from objective values and weights, ## thus we also want to draw objective charts to understand the convergence @@ -152,19 +164,22 @@ def save_global_objectives_chart(self, title='Global Objectives Chart', x_label= global_obj_list = np.array([agent.target.objectives for agent in self.list_global_best]) # Make each obj_list as a element in array for drawing global_obj_list = [global_obj_list[:, idx] for idx in range(0, len(global_obj_list[0]))] - visualize.export_objectives_chart(global_obj_list, title=title, x_label=x_label, y_labels=y_labels, filename=filename, verbose=verbose) + visualize.export_objectives_chart(global_obj_list, title=title, x_label=x_label, y_labels=y_labels, + filename=filename, verbose=verbose) def save_local_objectives_chart(self, title='Local Objectives Chart', x_label="#Iteration", y_labels=None, filename="local-objectives-chart", verbose=True): current_obj_list = np.array([agent.target.objectives for agent in self.list_current_best]) # Make each obj_list as a element in array for drawing current_obj_list = [current_obj_list[:, idx] for idx in range(0, len(current_obj_list[0]))] - visualize.export_objectives_chart(current_obj_list, title=title, x_label=x_label, y_labels=y_labels, filename=filename, verbose=verbose) + visualize.export_objectives_chart(current_obj_list, title=title, x_label=x_label, y_labels=y_labels, + filename=filename, verbose=verbose) def save_trajectory_chart(self, title="Trajectory of some agents", list_agent_idx=(1, 2, 3, 4, 5), selected_dimensions=(1, 2), filename="trajectory-chart", verbose=True): if len(self.list_population) < 2: - raise ValueError(f"Can't draw the trajectory because 'save_population' is set to False or the number of epochs is too small.") + raise ValueError( + f"Can't draw the trajectory because 'save_population' is set to False or the number of epochs is too small.") ## Drawing trajectory of some agents in the first and second dimensions # Need a little more pre-processing list_agent_idx = set(list_agent_idx) @@ -178,9 +193,11 @@ def save_trajectory_chart(self, title="Trajectory of some agents", list_agent_id if len(list_agent_idx) < 1 or len(list_agent_idx) > 10: raise ValueError(f"Trajectory chart for more than 10 agents is not supported.") if list_agent_idx[-1] > len(self.list_population[0]) or list_agent_idx[0] < 1: - raise ValueError(f"Can't draw trajectory chart, the index of selected agents should be in range of [1, {len(self.list_population[0])}]") + raise ValueError( + f"Can't draw trajectory chart, the index of selected agents should be in range of [1, {len(self.list_population[0])}]") if selected_dimensions[-1] > len(self.list_population[0][0].solution) or selected_dimensions[0] < 1: - raise ValueError(f"Can't draw trajectory chart, the index of selected dimensions should be in range of [1, {len(self.list_population[0][0].solution)}]") + raise ValueError( + f"Can't draw trajectory chart, the index of selected dimensions should be in range of [1, {len(self.list_population[0][0].solution)}]") pos_list = [] list_legends = [] @@ -195,7 +212,7 @@ def save_trajectory_chart(self, title="Trajectory of some agents", list_agent_id pos_list.append(x) list_legends.append(f"Agent {id_agent}") visualize.export_trajectory_chart(pos_list, n_dimensions=n_dim, title=title, list_legends=list_legends, - y_label=y_label, filename=filename, verbose=verbose) + y_label=y_label, filename=filename, verbose=verbose) elif n_dim == 2: x_label = f"x{selected_dimensions[0]}" y_label = f"x{selected_dimensions[1]}" @@ -206,5 +223,6 @@ def save_trajectory_chart(self, title="Trajectory of some agents", list_agent_id pos_temp.append(x) pos_list.append(pos_temp) list_legends.append(f"Agent {id_agent}") - visualize.export_trajectory_chart(pos_list, n_dimensions=n_dim, title=title, list_legends=list_legends, x_label=x_label, - y_label=y_label, filename=filename, verbose=verbose) + visualize.export_trajectory_chart(pos_list, n_dimensions=n_dim, title=title, list_legends=list_legends, + x_label=x_label, + y_label=y_label, filename=filename, verbose=verbose) diff --git a/mealpy/utils/io.py b/mealpy/utils/io.py index 729d4b62..0552645e 100644 --- a/mealpy/utils/io.py +++ b/mealpy/utils/io.py @@ -7,7 +7,7 @@ import pickle -def save_model(model, path_save:str): +def save_model(model, path_save: str): if path_save is None: path_save = "model.pkl" else: @@ -16,7 +16,7 @@ def save_model(model, path_save:str): pickle.dump(model, open(path_save, 'wb')) -def load_model(path_load:str): +def load_model(path_load: str): if path_load is None: path_load = "model.pkl" else: diff --git a/mealpy/utils/logger.py b/mealpy/utils/logger.py index b0ff2d49..0e9bab02 100644 --- a/mealpy/utils/logger.py +++ b/mealpy/utils/logger.py @@ -13,7 +13,8 @@ def __init__(self, log_to="console", **kwargs): self.log_to = log_to self.log_file = None self.__set_keyword_arguments(kwargs) - self.default_formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s: %(message)s', datefmt="%Y/%m/%d %I:%M:%S %p") + self.default_formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s: %(message)s', + datefmt="%Y/%m/%d %I:%M:%S %p") self.default_logfile = "mealpy.log" def __set_keyword_arguments(self, kwargs): @@ -25,7 +26,8 @@ def create_logger(self, name=__name__, format_str=None): if self.log_to == "console": logger.setLevel(logging.INFO) if format_str is None: - formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s: %(message)s', datefmt="%Y/%m/%d %I:%M:%S %p") + formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s: %(message)s', + datefmt="%Y/%m/%d %I:%M:%S %p") else: formatter = logging.Formatter(format_str, datefmt="%Y/%m/%d %I:%M:%S %p") handler = logging.StreamHandler() @@ -33,7 +35,8 @@ def create_logger(self, name=__name__, format_str=None): elif self.log_to == "file": logger.setLevel(logging.DEBUG) if format_str is None: - formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s: %(message)s', datefmt="%Y/%m/%d %I:%M:%S %p") + formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s: %(message)s', + datefmt="%Y/%m/%d %I:%M:%S %p") else: formatter = logging.Formatter(format_str, datefmt="%Y/%m/%d %I:%M:%S %p") if self.log_file is None: @@ -43,7 +46,8 @@ def create_logger(self, name=__name__, format_str=None): else: logger.setLevel(logging.ERROR) if format_str is None: - formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s', datefmt="%Y/%m/%d %I:%M:%S %p") + formatter = logging.Formatter('%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s', + datefmt="%Y/%m/%d %I:%M:%S %p") else: formatter = logging.Formatter(format_str, datefmt="%Y/%m/%d %I:%M:%S %p") handler = logging.StreamHandler() diff --git a/mealpy/utils/problem.py b/mealpy/utils/problem.py index 081def8b..34d4df77 100644 --- a/mealpy/utils/problem.py +++ b/mealpy/utils/problem.py @@ -5,11 +5,13 @@ # --------------------------------------------------% import numbers -import numpy as np from typing import Union, List, Tuple, Dict + +import numpy as np + +from mealpy.utils.logger import Logger from mealpy.utils.space import (BaseVar, IntegerVar, FloatVar, StringVar, BinaryVar, BoolVar, PermutationVar, CategoricalVar, SequenceVar, TransferBinaryVar, TransferBoolVar) -from mealpy.utils.logger import Logger from mealpy.utils.target import Target @@ -28,7 +30,7 @@ def __init__(self, bounds: Union[List, Tuple, np.ndarray, BaseVar], minmax: str self.__set_keyword_arguments(kwargs) self.set_bounds(bounds) self.logger = Logger(self.log_to, log_file=self.log_file).create_logger(name=f"{__name__}.{__class__.__name__}", - format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') + format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') @property def bounds(self): @@ -53,7 +55,8 @@ def n_objs(self): ) self.obj_weights = np.ones(self._n_objs) elif len(np.array(self.obj_weights).ravel()) != self._n_objs: - raise ValueError(f"`obj_weights` length {len(self.obj_weights)} does not match number of objectives {self._n_objs}.") + raise ValueError( + f"`obj_weights` length {len(self.obj_weights)} does not match number of objectives {self._n_objs}.") return self._n_objs def __set_keyword_arguments(self, kwargs): @@ -70,10 +73,12 @@ def set_bounds(self, bounds): if isinstance(bound, BaseVar): bound.seed = self.seed else: - raise ValueError(f"Invalid bounds. All variables in bounds should be an instance of {self.SUPPORTED_VARS}") + raise ValueError( + f"Invalid bounds. All variables in bounds should be an instance of {self.SUPPORTED_VARS}") self._bounds.append(bound) else: - raise TypeError(f"Invalid bounds. It should be type of {self.SUPPORTED_ARRAYS} or an instance of {self.SUPPORTED_VARS}") + raise TypeError( + f"Invalid bounds. It should be type of {self.SUPPORTED_ARRAYS} or an instance of {self.SUPPORTED_VARS}") self.lb = np.concatenate([bound.lb for bound in self._bounds]) self.ub = np.concatenate([bound.ub for bound in self._bounds]) self.n_dims = len(self.lb) @@ -128,12 +133,13 @@ def decode_solution_with_bounds(x, bounds): def correct_solution_with_bounds(x: Union[List, Tuple, np.ndarray], bounds: List) -> np.ndarray: x_new, n_vars = [], 0 for idx, var in enumerate(bounds): - x_new += list(var.correct(x[n_vars:n_vars+var.n_vars])) + x_new += list(var.correct(x[n_vars:n_vars + var.n_vars])) n_vars += var.n_vars return np.array(x_new) @staticmethod - def generate_solution_with_bounds(bounds: Union[List, Tuple, np.ndarray], encoded: bool = True) -> Union[List, np.ndarray]: + def generate_solution_with_bounds(bounds: Union[List, Tuple, np.ndarray], encoded: bool = True) -> Union[ + List, np.ndarray]: x = [var.generate() for var in bounds] if encoded: return Problem.encode_solution_with_bounds(x, bounds) diff --git a/mealpy/utils/space.py b/mealpy/utils/space.py index aa45ccf9..96c83c5f 100644 --- a/mealpy/utils/space.py +++ b/mealpy/utils/space.py @@ -4,9 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np import numbers as nb from abc import ABC, abstractmethod + +import numpy as np + from mealpy.utils import transfer @@ -34,6 +36,7 @@ def fit(self, y): y : list, tuple Labels to encode. """ + def safe_key(val): # Chuyển None -> 0, số -> 1, chuỗi -> 2, object khác -> 3 if val is None: @@ -162,7 +165,7 @@ def __init__(self, lb=-10., ub=10., name="float"): def _set_bounds(self, lb, ub): if isinstance(lb, nb.Number) and isinstance(ub, nb.Number): - self.lb, self.ub = np.array((lb, ), dtype=float), np.array((ub,), dtype=float) + self.lb, self.ub = np.array((lb,), dtype=float), np.array((ub,), dtype=float) self.n_vars = 1 elif type(lb) in self.SUPPORTED_ARRAY and type(ub) in self.SUPPORTED_ARRAY: if len(lb) == len(ub): @@ -196,7 +199,7 @@ def __init__(self, lb=-10, ub=10, name="integer"): def _set_bounds(self, lb, ub): if isinstance(lb, nb.Number) and isinstance(ub, nb.Number): lb, ub = int(lb) - 0.5, int(ub) + 0.5 - self.eps - self.lb, self.ub = np.array((lb, ), dtype=float), np.array((ub, ), dtype=float) + self.lb, self.ub = np.array((lb,), dtype=float), np.array((ub,), dtype=float) self.n_vars = 1 elif type(lb) in self.SUPPORTED_ARRAY and type(ub) in self.SUPPORTED_ARRAY: if len(lb) == len(ub): @@ -219,7 +222,7 @@ def correct(self, x): return np.clip(x, self.lb, self.ub) def generate(self): - return self.generator.integers(self.lb+0.5, self.ub+0.5+self.eps) + return self.generator.integers(self.lb + 0.5, self.ub + 0.5 + self.eps) class StringVar(BaseVar): @@ -362,7 +365,6 @@ def generate(self): class TransferBinaryVar(BinaryVar): - SUPPORTED_TF_FUNCS = ["vstf_01", "vstf_02", "vstf_03", "vstf_04", "sstf_01", "sstf_02", "sstf_03", "sstf_04"] def __init__(self, n_vars=1, name="tf-binary", tf_func="vstf_01", lb=-8., ub=8., all_zeros=True): @@ -420,7 +422,6 @@ def generate(self): class TransferBoolVar(BoolVar): - SUPPORTED_TF_FUNCS = ["vstf_01", "vstf_02", "vstf_03", "vstf_04", "sstf_01", "sstf_02", "sstf_03", "sstf_04"] def __init__(self, n_vars=1, name="boolean", tf_func="vstf_01", lb=-8., ub=8.): diff --git a/mealpy/utils/target.py b/mealpy/utils/target.py index 669851b1..cf2d723e 100644 --- a/mealpy/utils/target.py +++ b/mealpy/utils/target.py @@ -4,8 +4,9 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from typing import Union, List, Tuple import numbers +from typing import Union, List, Tuple + import numpy as np diff --git a/mealpy/utils/termination.py b/mealpy/utils/termination.py index cf125afd..61718479 100644 --- a/mealpy/utils/termination.py +++ b/mealpy/utils/termination.py @@ -67,7 +67,7 @@ def __init__(self, max_epoch=None, max_fe=None, max_time=None, max_early_stop=No self.name, self.message, self.log_to, self.log_file = "Termination", "", None, None self.__set_condition(self.max_epoch, self.max_fe, self.max_time, self.max_early_stop) self.logger = Logger(self.log_to, log_file=self.log_file).create_logger(name=f"{__name__}.{__class__.__name__}", - format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') + format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') self.logger.propagate = False def __set_keyword_arguments(self, kwargs): @@ -80,7 +80,8 @@ def __set_keyword_arguments(self, kwargs): def __set_condition(self, max_epoch, max_fe, max_time, max_early_stop): if (max_epoch is None) and (max_fe is None) and (max_time is None) and (max_early_stop is None): - raise ValueError("Please set at least one stopping condition with parameter 'max_epoch' or 'max_fe' or 'max_time' or 'max_early_stop'") + raise ValueError( + "Please set at least one stopping condition with parameter 'max_epoch' or 'max_fe' or 'max_time' or 'max_early_stop'") else: if max_epoch is not None: self.max_epoch = self.validator.check_int("max_epoch", max_epoch, [1, 10000000]) diff --git a/mealpy/utils/validator.py b/mealpy/utils/validator.py index 30b563ad..0176432d 100644 --- a/mealpy/utils/validator.py +++ b/mealpy/utils/validator.py @@ -4,9 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -import numpy as np import operator from numbers import Number + +import numpy as np + from mealpy.utils.logger import Logger SEQUENCE = (list, tuple, np.ndarray) @@ -42,14 +44,14 @@ def __init__(self, **kwargs): self.log_to, self.log_file = None, None self.__set_keyword_arguments(kwargs) self.logger = Logger(self.log_to, log_file=self.log_file).create_logger(name=f"{__name__}.{__class__.__name__}", - format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') + format_str='%(asctime)s, %(levelname)s, %(name)s [line: %(lineno)d]: %(message)s') self.logger.propagate = False def __set_keyword_arguments(self, kwargs): for key, value in kwargs.items(): setattr(self, key, value) - def check_int(self, name:str, value: int, bound=None): + def check_int(self, name: str, value: int, bound=None): if isinstance(value, Number): if bound is None: return int(value) diff --git a/mealpy/utils/visualize/linechart.py b/mealpy/utils/visualize/linechart.py index 5b4536ee..da5fe39e 100644 --- a/mealpy/utils/visualize/linechart.py +++ b/mealpy/utils/visualize/linechart.py @@ -4,28 +4,28 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% +import platform +import re from pathlib import Path + import numpy as np -import re from matplotlib import pyplot as plt -import platform - LIST_LINESTYLES = [ - '-', # solid line style - '--', # dashed line style - '-.', # dash-dot line style - - ':', # point marker - '-', # solid line style - '--', # dashed line style - '-.', # dash-dot line style - ':', # point marker - - '-', # solid line style - '--', # dashed line style - '-.', # dash-dot line style - ':', # point marker + '-', # solid line style + '--', # dashed line style + '-.', # dash-dot line style + + ':', # point marker + '-', # solid line style + '--', # dashed line style + '-.', # dash-dot line style + ':', # point marker + + '-', # solid line style + '--', # dashed line style + '-.', # dash-dot line style + ':', # point marker ] LIST_MARKERS = [ @@ -42,8 +42,8 @@ ] LIST_COLORS = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', - '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', - '#bcbd22', '#17becf'] + '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', + '#bcbd22', '#17becf'] def __clean_filename__(filename): @@ -51,16 +51,16 @@ def __clean_filename__(filename): regular_expression = '[' + re.escape(''.join(chars_to_remove)) + ']' temp = filename.encode("ascii", "ignore") - fname = temp.decode() # Removed all non-ascii characters - fname = re.sub(regular_expression, '', fname) # Removed all special characters - fname.replace("_", "-") # Replaced _ by - + fname = temp.decode() # Removed all non-ascii characters + fname = re.sub(regular_expression, '', fname) # Removed all special characters + fname.replace("_", "-") # Replaced _ by - return fname def __check_filepath__(filename): - filename.replace("\\", "/") # For better handling the parent folder + filename.replace("\\", "/") # For better handling the parent folder if "/" in filename: - list_names = filename.split("/")[:-1] # Remove last element because it is filename + list_names = filename.split("/")[:-1] # Remove last element because it is filename filepath = "/".join(list_names) Path(filepath).mkdir(parents=True, exist_ok=True) return filename @@ -88,7 +88,8 @@ def _draw_line_(data=None, title=None, legend=None, linestyle='-', color='b', x_ def _draw_multi_line_(data=None, title=None, list_legends=None, list_styles=None, list_colors=None, - x_label="#Iteration", y_label="Function Value", filename=None, exts=(".png", ".pdf"), verbose=True): + x_label="#Iteration", y_label="Function Value", filename=None, exts=(".png", ".pdf"), + verbose=True): x = np.arange(0, len(data[0])) for idx, y in enumerate(data): plt.plot(x, y, label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx]) @@ -107,7 +108,8 @@ def _draw_multi_line_(data=None, title=None, list_legends=None, list_styles=None def _draw_multi_subplots_in_same_figure_(data=None, title=None, list_legends=None, list_styles=None, list_colors=None, - x_label="#Iteration", y_labels=None, filename=None, exts=(".png", ".pdf"), verbose=True): + x_label="#Iteration", y_labels=None, filename=None, exts=(".png", ".pdf"), + verbose=True): n_lines = len(data) len_lines = len(data[0]) x = np.arange(0, len_lines) @@ -131,7 +133,8 @@ def _draw_multi_subplots_in_same_figure_(data=None, title=None, list_legends=Non if list_legends is None: ax.plot(x, data[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx]) else: - ax.plot(x, data[idx], label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx]) + ax.plot(x, data[idx], label=list_legends[idx], markerfacecolor=list_colors[idx], + linestyle=list_styles[idx]) if y_labels is None: ax.set_ylabel(f"Objective {idx + 1}") else: @@ -148,16 +151,21 @@ def _draw_multi_subplots_in_same_figure_(data=None, title=None, list_legends=Non plt.close() -def export_convergence_chart(data=None, title="Convergence Chart", legend=None, linestyle='-', color='b', x_label="#Iteration", - y_label="Function Value", filename="convergence_chart", exts=(".png", ".pdf"), verbose=True): +def export_convergence_chart(data=None, title="Convergence Chart", legend=None, linestyle='-', color='b', + x_label="#Iteration", + y_label="Function Value", filename="convergence_chart", exts=(".png", ".pdf"), + verbose=True): _draw_line_(data, title=title, legend=legend, linestyle=linestyle, color=color, x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose) -def export_explore_exploit_chart(data=None, title="Exploration vs Exploitation Percentages", list_legends=("Exploration %", "Exploitation %"), - list_styles=('-', '-'), list_colors=('blue', 'orange'), x_label="#Iteration", y_label="Percentage", +def export_explore_exploit_chart(data=None, title="Exploration vs Exploitation Percentages", + list_legends=("Exploration %", "Exploitation %"), + list_styles=('-', '-'), list_colors=('blue', 'orange'), x_label="#Iteration", + y_label="Percentage", filename="explore_exploit_chart", exts=(".png", ".pdf"), verbose=True): - _draw_multi_line_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, list_colors=list_colors, + _draw_multi_line_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, + list_colors=list_colors, x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose) @@ -168,23 +176,28 @@ def export_diversity_chart(data=None, title='Diversity Measurement Chart', list_ list_styles = LIST_LINESTYLES[:len(data)] if list_colors is None: list_colors = LIST_COLORS[:len(data)] - _draw_multi_line_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, list_colors=list_colors, + _draw_multi_line_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, + list_colors=list_colors, x_label=x_label, y_label=y_label, filename=filename, exts=exts, verbose=verbose) def export_objectives_chart(data=None, title="Objectives chart", list_legends=None, list_styles=None, list_colors=None, - x_label="#Iteration", y_labels=None, filename="Objective-chart", exts=(".png", ".pdf"), verbose=True): + x_label="#Iteration", y_labels=None, filename="Objective-chart", exts=(".png", ".pdf"), + verbose=True): if list_styles is None: list_styles = LIST_LINESTYLES[:len(data)] if list_colors is None: list_colors = LIST_COLORS[:len(data)] - _draw_multi_subplots_in_same_figure_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, list_colors=list_colors, - x_label=x_label, y_labels=y_labels, filename=filename, exts=exts, verbose=verbose) + _draw_multi_subplots_in_same_figure_(data=data, title=title, list_legends=list_legends, list_styles=list_styles, + list_colors=list_colors, + x_label=x_label, y_labels=y_labels, filename=filename, exts=exts, + verbose=verbose) -def export_trajectory_chart(data=None, n_dimensions=1, title="Trajectory of some agents after generations", list_legends=None, - list_styles=None, list_colors=None, x_label="#Iteration", y_label="X1", - filename="1d_trajectory", exts=(".png", ".pdf"), verbose=True): +def export_trajectory_chart(data=None, n_dimensions=1, title="Trajectory of some agents after generations", + list_legends=None, + list_styles=None, list_colors=None, x_label="#Iteration", y_label="X1", + filename="1d_trajectory", exts=(".png", ".pdf"), verbose=True): if list_styles is None: list_styles = LIST_LINESTYLES[:len(data)] if list_colors is None: @@ -196,7 +209,8 @@ def export_trajectory_chart(data=None, n_dimensions=1, title="Trajectory of some plt.plot(x, y, label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx]) elif n_dimensions == 2: for idx, point in enumerate(data): - plt.plot(point[0], point[1], label=list_legends[idx], markerfacecolor=list_colors[idx], linestyle=list_styles[idx]) + plt.plot(point[0], point[1], label=list_legends[idx], markerfacecolor=list_colors[idx], + linestyle=list_styles[idx]) plt.title(title) plt.xlabel(x_label) @@ -209,4 +223,3 @@ def export_trajectory_chart(data=None, n_dimensions=1, title="Trajectory of some if platform.system() != "Linux" and verbose: plt.show() plt.close() - diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..06292264 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,131 @@ +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "mealpy-lts" +dynamic = ["version"] +description = "An Open-source Library for Latest Meta-heuristic Algorithms in Python" +readme = "README.md" +license = { text = "MIT" } + +authors = [ + { name = "Thieu", email = "nguyenthieu2102@gmail.com" } +] + +maintainers = [ + { name = "ltsim", email = "tsim@cucei.udg.mx" } +] + +keywords = [ + "optimization", "metaheuristics", "MHA", "mathematical optimization", + "nature-inspired algorithms", "evolutionary computation", "soft computing", + "population-based algorithms", "Stochastic optimization", "Global optimization", + "Convergence analysis", "Search space exploration", "Local search", + "Computational intelligence", "Black-box optimization", "Robust optimization", + "Hybrid algorithms", "Benchmark functions", "Metaheuristic design", + "Performance analysis", "Exploration versus exploitation", "Self-adaptation", + "Constrained optimization", "Intelligent optimization", "Adaptive search", + "Simulations", "Algorithm selection", +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Information Technology", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Natural Language :: English", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: Implementation :: CPython", + "Topic :: System :: Benchmark", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Mathematics", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Scientific/Engineering :: Information Analysis", + "Topic :: Scientific/Engineering :: Visualization", + "Topic :: Scientific/Engineering :: Bio-Informatics", + "Topic :: Software Development :: Build Tools", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Libraries :: Python Modules", + "Topic :: Utilities", +] +requires-python = ">=3.10" +dependencies = [ + "numpy>=2.1.3", + "scipy>=1.15.0", + "pandas>=2.2.2", + "matplotlib>=3.10.9", + "tqdm>=4.67.3", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0", + "pytest-cov>=5.0", + "mypy>=1.9.0", + "twine>=5.0", + "flake8>=7.0", + "pandas-stubs>=2.2.3", + "scipy-stubs>=1.15.0", +] + +[project.urls] +"Homepage" = "https://github.com/ltsim/mealpy-lts" +"Documentation" = "https://mealpy.readthedocs.io/" +"Source Code" = "https://github.com/ltsim/mealpy-lts" +"Bug Tracker" = "https://github.com/ltsim/mealpy-lts/issues" +"Change Log" = "https://github.com/ltsim/mealpy-lts/blob/master/CHANGELOG.md" + +[tool.setuptools.dynamic] +version = { attr = "mealpy.__version__" } + +[tool.setuptools.packages.find] +exclude = ["tests*", "examples*"] + +[tool.setuptools] +include-package-data = true + +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py", "*_test.py"] +python_classes = ["Test*"] +python_functions = ["test_*"] +addopts = "-v --tb=short --strict-markers" + +[tool.mypy] +files = ["mealpy"] +exclude = ["tests/", "docs/", "examples/"] +python_version = "3.10" +warn_unused_ignores = true +warn_redundant_casts = true +warn_unreachable = true +no_implicit_optional = true +strict_optional = true +disallow_untyped_defs = true +disallow_incomplete_defs = true +disallow_any_generics = false +disallow_any_unimported = false +disallow_subclassing_any = false +disallow_untyped_decorators = false +check_untyped_defs = true +warn_return_any = false +show_error_codes = true +show_column_numbers = true +pretty = true +error_summary = true + +[[tool.mypy.overrides]] +module = [ + "matplotlib.*", + "PIL.*", + "numpy", + "numpy.*", + "tqdm.*" +] +ignore_missing_imports = true \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 90bcd4ec..00000000 --- a/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -numpy>=1.17.1,<=1.26.0 -scipy>=1.7.1 -pandas>=1.2.0 -matplotlib>=3.1.3 -opfunu>=1.0.0 -tqdm>=4.66.0 diff --git a/setup.py b/setup.py deleted file mode 100644 index 280500c9..00000000 --- a/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python -# Created by "Thieu" at 13:24, 27/02/2022 ----------% -# Email: nguyenthieu2102@gmail.com % -# Github: https://github.com/thieu1995 % -# --------------------------------------------------% - -import setuptools -import os -import re - - -with open("requirements.txt", encoding='utf-8') as f: - REQUIREMENTS = f.read().splitlines() - - -def get_version(): - init_path = os.path.join(os.path.dirname(__file__), 'mealpy', '__init__.py') - with open(init_path, 'r', encoding='utf-8') as f: - init_content = f.read() - version_match = re.search(r"^__version__ = ['\"]([^'\"]+)['\"]", init_content, re.M) - if version_match: - return version_match.group(1) - raise RuntimeError("Unable to find version string.") - - -def readme(): - with open('README.md', encoding='utf-8') as f: - res = f.read() - return res - - -setuptools.setup( - name="mealpy", - version=get_version(), - author="Thieu", - author_email="nguyenthieu2102@gmail.com", - description="MEALPY: An Open-source Library for Latest Meta-heuristic Algorithms in Python", - long_description=readme(), - long_description_content_type="text/markdown", - keywords=["optimization", "metaheuristics", "MHA", "mathematical optimization", "nature-inspired algorithms", - "evolutionary computation", "soft computing", "population-based algorithms", - "Stochastic optimization", "Global optimization", "Convergence analysis", "Search space exploration", - "Local search", "Computational intelligence", "Black-box optimization", "Robust optimization", - "Hybrid algorithms", "Benchmark functions", "Metaheuristic design", "Performance analysis", - "Exploration versus exploitation", "Self-adaptation", "Constrained optimization", - "Intelligent optimization", "Adaptive search", "Simulations", "Algorithm selection"], - url="https://github.com/thieu1995/mealpy", - project_urls={ - 'Documentation': 'https://mealpy.readthedocs.io/', - 'Source Code': 'https://github.com/thieu1995/mealpy', - 'Bug Tracker': 'https://github.com/thieu1995/mealpy/issues', - 'Change Log': 'https://github.com/thieu1995/mealpy/blob/master/ChangeLog.md', - 'Forum': 'https://t.me/+fRVCJGuGJg1mNDg1', - }, - packages=setuptools.find_packages(exclude=['tests*', 'examples*']), - include_package_data=True, - license="MIT", - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Intended Audience :: Education", - "Intended Audience :: Information Technology", - "Intended Audience :: Science/Research", - "License :: OSI Approved :: MIT License", - "Natural Language :: English", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Topic :: System :: Benchmark", - "Topic :: Scientific/Engineering", - "Topic :: Scientific/Engineering :: Mathematics", - "Topic :: Scientific/Engineering :: Artificial Intelligence", - "Topic :: Scientific/Engineering :: Information Analysis", - "Topic :: Scientific/Engineering :: Visualization", - "Topic :: Scientific/Engineering :: Bio-Informatics", - "Topic :: Software Development :: Build Tools", - "Topic :: Software Development :: Libraries", - "Topic :: Software Development :: Libraries :: Python Modules", - "Topic :: Utilities", - ], - install_requires=REQUIREMENTS, - extras_require={ - "dev": ["pytest>=7.0", "twine>=4.0.1", "pytest-cov==4.0.0", "flake8>=4.0.1"], - }, - python_requires='>=3.8', -) diff --git a/tests/bio_based/test_BBO.py b/tests/bio_based/test_BBO.py index 465b76ec..172655e8 100644 --- a/tests/bio_based/test_BBO.py +++ b/tests/bio_based/test_BBO.py @@ -4,15 +4,17 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, BBO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, BBO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): def objective_function(solution): return np.sum(solution ** 2) + prob = { "obj_func": objective_function, "bounds": FloatVar(lb=[-10, -15, -4, -2, -8], ub=[10, 15, 12, 8, 20]), diff --git a/tests/bio_based/test_EOA.py b/tests/bio_based/test_EOA.py index ebd84a81..9f7313f8 100644 --- a/tests/bio_based/test_EOA.py +++ b/tests/bio_based/test_EOA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, EOA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, EOA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/bio_based/test_IWO.py b/tests/bio_based/test_IWO.py index 0a18ca7b..0971fb2f 100644 --- a/tests/bio_based/test_IWO.py +++ b/tests/bio_based/test_IWO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, IWO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, IWO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/bio_based/test_SBO.py b/tests/bio_based/test_SBO.py index 02af253c..d3b74130 100644 --- a/tests/bio_based/test_SBO.py +++ b/tests/bio_based/test_SBO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SBO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SBO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/bio_based/test_SMA.py b/tests/bio_based/test_SMA.py index 5ab25e80..b2f71d3f 100644 --- a/tests/bio_based/test_SMA.py +++ b/tests/bio_based/test_SMA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SMA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SMA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/bio_based/test_VCS.py b/tests/bio_based/test_VCS.py index d7c9cc05..bab71b11 100644 --- a/tests/bio_based/test_VCS.py +++ b/tests/bio_based/test_VCS.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, VCS, Optimizer import numpy as np import pytest +from mealpy import FloatVar, VCS, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/bio_based/test_WHO.py b/tests/bio_based/test_WHO.py index 76b69d5a..01de9961 100644 --- a/tests/bio_based/test_WHO.py +++ b/tests/bio_based/test_WHO.py @@ -25,7 +25,8 @@ def objective_function(solution): def test_BaseWHO_results(problem): model = WHO.OriginalWHO(epoch=10, pop_size=50, n_explore_step=3, n_exploit_step=3, eta=0.15, p_hi=0.9, - local_alpha=0.9, local_beta=0.3, global_alpha=0.2, global_beta=0.8, delta_w=2.0, delta_c=2.0) + local_alpha=0.9, local_beta=0.3, global_alpha=0.2, global_beta=0.8, delta_w=2.0, + delta_c=2.0) g_best = model.solve(problem) assert isinstance(model, Optimizer) assert isinstance(g_best.solution, np.ndarray) diff --git a/tests/evolutionary_based/test_CRO.py b/tests/evolutionary_based/test_CRO.py index fcf0c04b..ab75a02c 100644 --- a/tests/evolutionary_based/test_CRO.py +++ b/tests/evolutionary_based/test_CRO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, CRO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, CRO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/evolutionary_based/test_DE.py b/tests/evolutionary_based/test_DE.py index 3f641a5c..f46aa479 100644 --- a/tests/evolutionary_based/test_DE.py +++ b/tests/evolutionary_based/test_DE.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, DE, Optimizer import numpy as np import pytest +from mealpy import FloatVar, DE, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/evolutionary_based/test_EP.py b/tests/evolutionary_based/test_EP.py index c20a1c56..7b3eb7f1 100644 --- a/tests/evolutionary_based/test_EP.py +++ b/tests/evolutionary_based/test_EP.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, EP, Optimizer import numpy as np import pytest +from mealpy import FloatVar, EP, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/evolutionary_based/test_ES.py b/tests/evolutionary_based/test_ES.py index 1fda2619..46f0f2c3 100644 --- a/tests/evolutionary_based/test_ES.py +++ b/tests/evolutionary_based/test_ES.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, ES, Optimizer import numpy as np import pytest +from mealpy import FloatVar, ES, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/evolutionary_based/test_FPA.py b/tests/evolutionary_based/test_FPA.py index 36122464..311c4cb4 100644 --- a/tests/evolutionary_based/test_FPA.py +++ b/tests/evolutionary_based/test_FPA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, FPA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, FPA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/evolutionary_based/test_MA.py b/tests/evolutionary_based/test_MA.py index 67a6c091..1d7d86ee 100644 --- a/tests/evolutionary_based/test_MA.py +++ b/tests/evolutionary_based/test_MA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, MA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, MA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/evolutionary_based/test_SHADE.py b/tests/evolutionary_based/test_SHADE.py index 6eacffbb..9eb52795 100644 --- a/tests/evolutionary_based/test_SHADE.py +++ b/tests/evolutionary_based/test_SHADE.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SHADE, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SHADE, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_BRO.py b/tests/human_based/test_BRO.py index f15d924b..5f951e30 100644 --- a/tests/human_based/test_BRO.py +++ b/tests/human_based/test_BRO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, BRO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, BRO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_BSO.py b/tests/human_based/test_BSO.py index 0a780538..5700e772 100644 --- a/tests/human_based/test_BSO.py +++ b/tests/human_based/test_BSO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, BSO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, BSO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_CA.py b/tests/human_based/test_CA.py index 4c54153e..f7f8ef27 100644 --- a/tests/human_based/test_CA.py +++ b/tests/human_based/test_CA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, CA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, CA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_CHIO.py b/tests/human_based/test_CHIO.py index 94f6990e..e28d9885 100644 --- a/tests/human_based/test_CHIO.py +++ b/tests/human_based/test_CHIO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, CHIO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, CHIO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_FBIO.py b/tests/human_based/test_FBIO.py index 87e267ae..d30a9ee0 100644 --- a/tests/human_based/test_FBIO.py +++ b/tests/human_based/test_FBIO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, FBIO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, FBIO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_GSKA.py b/tests/human_based/test_GSKA.py index 279d889d..71bf2176 100644 --- a/tests/human_based/test_GSKA.py +++ b/tests/human_based/test_GSKA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, GSKA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, GSKA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_ICA.py b/tests/human_based/test_ICA.py index fce200b3..626cf2d8 100644 --- a/tests/human_based/test_ICA.py +++ b/tests/human_based/test_ICA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, ICA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, ICA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): @@ -25,7 +26,8 @@ def objective_function(solution): def test_ICA_results(problem): models = [ - ICA.OriginalICA(epoch=10, pop_size=50, empire_count=5, assimilation_coeff=1.5, revolution_prob=0.05, revolution_rate=0.1, revolution_step_size=0.1, zeta=0.1) + ICA.OriginalICA(epoch=10, pop_size=50, empire_count=5, assimilation_coeff=1.5, revolution_prob=0.05, + revolution_rate=0.1, revolution_step_size=0.1, zeta=0.1) ] for model in models: g_best = model.solve(problem) diff --git a/tests/human_based/test_LCO.py b/tests/human_based/test_LCO.py index ee9e8261..f2a0569e 100644 --- a/tests/human_based/test_LCO.py +++ b/tests/human_based/test_LCO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, LCO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, LCO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_QSA.py b/tests/human_based/test_QSA.py index 12b48eb0..95e41339 100644 --- a/tests/human_based/test_QSA.py +++ b/tests/human_based/test_QSA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, QSA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, QSA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_SARO.py b/tests/human_based/test_SARO.py index 92d8f14d..021eda05 100644 --- a/tests/human_based/test_SARO.py +++ b/tests/human_based/test_SARO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SARO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SARO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_SSDO.py b/tests/human_based/test_SSDO.py index 1416e029..a09e4930 100644 --- a/tests/human_based/test_SSDO.py +++ b/tests/human_based/test_SSDO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SSDO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SSDO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/human_based/test_TLO.py b/tests/human_based/test_TLO.py index f3e134e6..1126a5b2 100644 --- a/tests/human_based/test_TLO.py +++ b/tests/human_based/test_TLO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, TLO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, TLO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_AOA.py b/tests/math_based/test_AOA.py index b9bca478..794a15a8 100644 --- a/tests/math_based/test_AOA.py +++ b/tests/math_based/test_AOA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, AOA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, AOA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_CEM.py b/tests/math_based/test_CEM.py index 43d88aa4..832f4f46 100644 --- a/tests/math_based/test_CEM.py +++ b/tests/math_based/test_CEM.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, CEM, Optimizer import numpy as np import pytest +from mealpy import FloatVar, CEM, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_CGO.py b/tests/math_based/test_CGO.py index b78d5508..c4776407 100644 --- a/tests/math_based/test_CGO.py +++ b/tests/math_based/test_CGO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, CGO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, CGO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_GBO.py b/tests/math_based/test_GBO.py index ba218bec..575040c9 100644 --- a/tests/math_based/test_GBO.py +++ b/tests/math_based/test_GBO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, GBO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, GBO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_HC.py b/tests/math_based/test_HC.py index 6ab74336..a10967e7 100644 --- a/tests/math_based/test_HC.py +++ b/tests/math_based/test_HC.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, HC, Optimizer import numpy as np import pytest +from mealpy import FloatVar, HC, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_PSS.py b/tests/math_based/test_PSS.py index 860a81cc..521de2c4 100644 --- a/tests/math_based/test_PSS.py +++ b/tests/math_based/test_PSS.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, PSS, Optimizer import numpy as np import pytest +from mealpy import FloatVar, PSS, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_SCA.py b/tests/math_based/test_SCA.py index a200504a..5e4c111b 100644 --- a/tests/math_based/test_SCA.py +++ b/tests/math_based/test_SCA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SCA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SCA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/math_based/test_TS.py b/tests/math_based/test_TS.py index 58d56c55..ce47b793 100644 --- a/tests/math_based/test_TS.py +++ b/tests/math_based/test_TS.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, TS, Optimizer import numpy as np import pytest +from mealpy import FloatVar, TS, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/music_based/test_HS.py b/tests/music_based/test_HS.py index 69f2909a..fd86facf 100644 --- a/tests/music_based/test_HS.py +++ b/tests/music_based/test_HS.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, HS, Optimizer import numpy as np import pytest +from mealpy import FloatVar, HS, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_ASO.py b/tests/physics_based/test_ASO.py index d63f08d4..015c5ae8 100644 --- a/tests/physics_based/test_ASO.py +++ b/tests/physics_based/test_ASO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, ASO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, ASO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_ArchOA.py b/tests/physics_based/test_ArchOA.py index c5ff94a6..75a2e308 100644 --- a/tests/physics_based/test_ArchOA.py +++ b/tests/physics_based/test_ArchOA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, ArchOA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, ArchOA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_EFO.py b/tests/physics_based/test_EFO.py index e941dbf7..662a3a6b 100644 --- a/tests/physics_based/test_EFO.py +++ b/tests/physics_based/test_EFO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, EFO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, EFO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_EO.py b/tests/physics_based/test_EO.py index 796cd559..847a2e44 100644 --- a/tests/physics_based/test_EO.py +++ b/tests/physics_based/test_EO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, EO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, EO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_HGSO.py b/tests/physics_based/test_HGSO.py index 1832e499..5fe19485 100644 --- a/tests/physics_based/test_HGSO.py +++ b/tests/physics_based/test_HGSO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, HGSO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, HGSO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_MVO.py b/tests/physics_based/test_MVO.py index e2bc39e6..82e445c5 100644 --- a/tests/physics_based/test_MVO.py +++ b/tests/physics_based/test_MVO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, MVO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, MVO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_NRO.py b/tests/physics_based/test_NRO.py index 700f3176..c8db9fd9 100644 --- a/tests/physics_based/test_NRO.py +++ b/tests/physics_based/test_NRO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, NRO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, NRO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_SA.py b/tests/physics_based/test_SA.py index c51d00b2..3a200e76 100644 --- a/tests/physics_based/test_SA.py +++ b/tests/physics_based/test_SA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_TWO.py b/tests/physics_based/test_TWO.py index a05f04ca..307fdfb6 100644 --- a/tests/physics_based/test_TWO.py +++ b/tests/physics_based/test_TWO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, TWO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, TWO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/physics_based/test_WDO.py b/tests/physics_based/test_WDO.py index 462e2df3..01537137 100644 --- a/tests/physics_based/test_WDO.py +++ b/tests/physics_based/test_WDO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, WDO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, WDO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_AO.py b/tests/swarm_based/test_AO.py index 13b456e0..0801d3bf 100644 --- a/tests/swarm_based/test_AO.py +++ b/tests/swarm_based/test_AO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, AO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, AO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_BA.py b/tests/swarm_based/test_BA.py index 838aec24..7c4dbafc 100644 --- a/tests/swarm_based/test_BA.py +++ b/tests/swarm_based/test_BA.py @@ -27,7 +27,8 @@ def objective_function(solution): def test_BA_results(problem): models = [ BA.OriginalBA(epoch=10, pop_size=50, loudness=0.8, pulse_rate=0.95, pf_min=0.1, pf_max=10.0), - BA.AdaptiveBA(epoch=10, pop_size=50, loudness_min=1.0, loudness_max=2.0, pr_min=0.15, pr_max=0.85, pf_min=-2.5, pf_max=10.), + BA.AdaptiveBA(epoch=10, pop_size=50, loudness_min=1.0, loudness_max=2.0, pr_min=0.15, pr_max=0.85, pf_min=-2.5, + pf_max=10.), BA.DevBA(epoch=10, pop_size=50, pulse_rate=0.95, pf_min=0., pf_max=10.) ] for model in models: diff --git a/tests/swarm_based/test_BES.py b/tests/swarm_based/test_BES.py index e862ee5d..f435e010 100644 --- a/tests/swarm_based/test_BES.py +++ b/tests/swarm_based/test_BES.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, BES, Optimizer import numpy as np import pytest +from mealpy import FloatVar, BES, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_BFO.py b/tests/swarm_based/test_BFO.py index a1df8caf..9cdd8eea 100644 --- a/tests/swarm_based/test_BFO.py +++ b/tests/swarm_based/test_BFO.py @@ -26,7 +26,8 @@ def objective_function(solution): def test_BFO_results(problem): models = [ - BFO.OriginalBFO(epoch=10, pop_size=50, Ci=0.01, Ped=0.25, Nc=5, Ns=4, d_attract=0.1, w_attract=0.2, h_repels=0.1, w_repels=10), + BFO.OriginalBFO(epoch=10, pop_size=50, Ci=0.01, Ped=0.25, Nc=5, Ns=4, d_attract=0.1, w_attract=0.2, + h_repels=0.1, w_repels=10), BFO.ABFO(epoch=10, pop_size=50, C_s=0.1, C_e=0.001, Ped=0.01, Ns=4, N_adapt=2, N_split=40), ] for model in models: diff --git a/tests/swarm_based/test_BeesA.py b/tests/swarm_based/test_BeesA.py index 9996e62f..c04acdf8 100644 --- a/tests/swarm_based/test_BeesA.py +++ b/tests/swarm_based/test_BeesA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, BeesA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, BeesA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): @@ -26,7 +27,8 @@ def objective_function(solution): def test_BeesA_results(problem): models = [ BeesA.ProbBeesA(epoch=10, pop_size=10, recruited_bee_ratio=0.1, dance_radius=0.1, dance_reduction=0.99), - BeesA.OriginalBeesA(epoch=10, pop_size=10, selected_site_ratio=0.5, elite_site_ratio=0.4, selected_site_bee_ratio=0.1, + BeesA.OriginalBeesA(epoch=10, pop_size=10, selected_site_ratio=0.5, elite_site_ratio=0.4, + selected_site_bee_ratio=0.1, elite_site_bee_ratio=2.0, dance_radius=0.1, dance_reduction=0.99, ), ] for model in models: diff --git a/tests/swarm_based/test_COA.py b/tests/swarm_based/test_COA.py index 8328b662..fcdf5b60 100644 --- a/tests/swarm_based/test_COA.py +++ b/tests/swarm_based/test_COA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, COA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, COA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_CSA.py b/tests/swarm_based/test_CSA.py index 70f1b049..121b9946 100644 --- a/tests/swarm_based/test_CSA.py +++ b/tests/swarm_based/test_CSA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, CSA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, CSA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_CSO.py b/tests/swarm_based/test_CSO.py index 3c6d6f03..4a09bd62 100644 --- a/tests/swarm_based/test_CSO.py +++ b/tests/swarm_based/test_CSO.py @@ -26,7 +26,8 @@ def objective_function(solution): def test_CSO_results(problem): models = [ - CSO.OriginalCSO(epoch=10, pop_size=50, mixture_ratio=0.15, smp=5, spc=False, cdc=0.8, srd=0.15, c1=0.4, w_min=0.4, w_max=0.9) + CSO.OriginalCSO(epoch=10, pop_size=50, mixture_ratio=0.15, smp=5, spc=False, cdc=0.8, srd=0.15, c1=0.4, + w_min=0.4, w_max=0.9) ] for model in models: g_best = model.solve(problem) diff --git a/tests/swarm_based/test_DO.py b/tests/swarm_based/test_DO.py index 3136a974..490afc47 100644 --- a/tests/swarm_based/test_DO.py +++ b/tests/swarm_based/test_DO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, DO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, DO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_FFA.py b/tests/swarm_based/test_FFA.py index e2052064..ef89cc84 100644 --- a/tests/swarm_based/test_FFA.py +++ b/tests/swarm_based/test_FFA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, FFA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, FFA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): @@ -25,7 +26,8 @@ def objective_function(solution): def test_FFA_results(problem): models = [ - FFA.OriginalFFA(epoch=10, pop_size=50, gamma=0.001, beta_base=2, alpha=0.2, alpha_damp=0.99, delta=0.05, exponent=2) + FFA.OriginalFFA(epoch=10, pop_size=50, gamma=0.001, beta_base=2, alpha=0.2, alpha_damp=0.99, delta=0.05, + exponent=2) ] for model in models: g_best = model.solve(problem) diff --git a/tests/swarm_based/test_FOA.py b/tests/swarm_based/test_FOA.py index fb3b04ca..f46c1c02 100644 --- a/tests/swarm_based/test_FOA.py +++ b/tests/swarm_based/test_FOA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, FOA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, FOA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_GOA.py b/tests/swarm_based/test_GOA.py index 88b8ed46..96ef0445 100644 --- a/tests/swarm_based/test_GOA.py +++ b/tests/swarm_based/test_GOA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, GOA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, GOA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_GWO.py b/tests/swarm_based/test_GWO.py index 8b9bb545..dca42b9f 100644 --- a/tests/swarm_based/test_GWO.py +++ b/tests/swarm_based/test_GWO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, GWO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, GWO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_HGS.py b/tests/swarm_based/test_HGS.py index 0a099fe3..d022f4b4 100644 --- a/tests/swarm_based/test_HGS.py +++ b/tests/swarm_based/test_HGS.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, HGS, Optimizer import numpy as np import pytest +from mealpy import FloatVar, HGS, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_HHO.py b/tests/swarm_based/test_HHO.py index c9c3703e..ccdd2959 100644 --- a/tests/swarm_based/test_HHO.py +++ b/tests/swarm_based/test_HHO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, HHO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, HHO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_JA.py b/tests/swarm_based/test_JA.py index 1c8df6cc..b9650ec3 100644 --- a/tests/swarm_based/test_JA.py +++ b/tests/swarm_based/test_JA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, JA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, JA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_MFO.py b/tests/swarm_based/test_MFO.py index 5b6a2454..4d91d63d 100644 --- a/tests/swarm_based/test_MFO.py +++ b/tests/swarm_based/test_MFO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, MFO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, MFO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_MFRO.py b/tests/swarm_based/test_MFRO.py index 78e5b675..bf315a54 100644 --- a/tests/swarm_based/test_MFRO.py +++ b/tests/swarm_based/test_MFRO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, MRFO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, MRFO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_MSA.py b/tests/swarm_based/test_MSA.py index e6c35ebd..21c97be7 100644 --- a/tests/swarm_based/test_MSA.py +++ b/tests/swarm_based/test_MSA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, MSA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, MSA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_NMRA.py b/tests/swarm_based/test_NMRA.py index 7d6b0db9..1fc4fca2 100644 --- a/tests/swarm_based/test_NMRA.py +++ b/tests/swarm_based/test_NMRA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, NMRA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, NMRA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_PFA.py b/tests/swarm_based/test_PFA.py index 1c1cc4fe..8aee89fd 100644 --- a/tests/swarm_based/test_PFA.py +++ b/tests/swarm_based/test_PFA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, PFA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, PFA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_PSO.py b/tests/swarm_based/test_PSO.py index 6eae1d1b..3aa4f0c3 100644 --- a/tests/swarm_based/test_PSO.py +++ b/tests/swarm_based/test_PSO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, PSO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, PSO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SFO.py b/tests/swarm_based/test_SFO.py index 73ed5f39..5d3486be 100644 --- a/tests/swarm_based/test_SFO.py +++ b/tests/swarm_based/test_SFO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SFO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SFO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SHO.py b/tests/swarm_based/test_SHO.py index 19b36f2c..dc93236b 100644 --- a/tests/swarm_based/test_SHO.py +++ b/tests/swarm_based/test_SHO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SHO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SHO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SLO.py b/tests/swarm_based/test_SLO.py index 766ff39d..3ba009d5 100644 --- a/tests/swarm_based/test_SLO.py +++ b/tests/swarm_based/test_SLO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SLO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SLO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SRSR.py b/tests/swarm_based/test_SRSR.py index c1a2c4bd..3b407093 100644 --- a/tests/swarm_based/test_SRSR.py +++ b/tests/swarm_based/test_SRSR.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SRSR, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SRSR, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SSA.py b/tests/swarm_based/test_SSA.py index 2e797e75..a9ad31c5 100644 --- a/tests/swarm_based/test_SSA.py +++ b/tests/swarm_based/test_SSA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SSA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SSA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SSO.py b/tests/swarm_based/test_SSO.py index 7f5fc16c..8875bea1 100644 --- a/tests/swarm_based/test_SSO.py +++ b/tests/swarm_based/test_SSO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SSO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SSO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SSpiderA.py b/tests/swarm_based/test_SSpiderA.py index 9d8443a7..7946f13e 100644 --- a/tests/swarm_based/test_SSpiderA.py +++ b/tests/swarm_based/test_SSpiderA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SSpiderA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SSpiderA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_SSpiderO.py b/tests/swarm_based/test_SSpiderO.py index eabc525b..74e7c3fb 100644 --- a/tests/swarm_based/test_SSpiderO.py +++ b/tests/swarm_based/test_SSpiderO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, SSpiderO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, SSpiderO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/swarm_based/test_WOA.py b/tests/swarm_based/test_WOA.py index a2391962..4e76cf6e 100644 --- a/tests/swarm_based/test_WOA.py +++ b/tests/swarm_based/test_WOA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, WOA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, WOA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/system_based/test_AEO.py b/tests/system_based/test_AEO.py index 7b6e02ed..e5715021 100644 --- a/tests/system_based/test_AEO.py +++ b/tests/system_based/test_AEO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, AEO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, AEO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/system_based/test_GCO.py b/tests/system_based/test_GCO.py index 1186a18d..f71938c9 100644 --- a/tests/system_based/test_GCO.py +++ b/tests/system_based/test_GCO.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, GCO, Optimizer import numpy as np import pytest +from mealpy import FloatVar, GCO, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/system_based/test_WCA.py b/tests/system_based/test_WCA.py index bcc234d8..0f7c084c 100644 --- a/tests/system_based/test_WCA.py +++ b/tests/system_based/test_WCA.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, WCA, Optimizer import numpy as np import pytest +from mealpy import FloatVar, WCA, Optimizer + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def problem(): diff --git a/tests/test_optimizer.py b/tests/test_optimizer.py index 9eac9b79..e6831642 100644 --- a/tests/test_optimizer.py +++ b/tests/test_optimizer.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import Problem, Optimizer, FloatVar import numpy as np import pytest +from mealpy import Problem, Optimizer, FloatVar + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def model(): diff --git a/tests/test_tuner.py b/tests/test_tuner.py index 5e84baac..ece4b36e 100644 --- a/tests/test_tuner.py +++ b/tests/test_tuner.py @@ -4,10 +4,11 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import FloatVar, WOA, Tuner import numpy as np import pytest +from mealpy import FloatVar, WOA, Tuner + @pytest.fixture(scope="module") # scope: Call only 1 time at the beginning def model(): diff --git a/tests/utils/test_termination.py b/tests/utils/test_termination.py index 3b5b8f9b..28f8dd42 100644 --- a/tests/utils/test_termination.py +++ b/tests/utils/test_termination.py @@ -4,9 +4,10 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy import Termination import pytest +from mealpy import Termination + @pytest.mark.parametrize("max_epoch, system_code", [ diff --git a/tests/utils/test_validator.py b/tests/utils/test_validator.py index f7bcd6f3..29a49109 100644 --- a/tests/utils/test_validator.py +++ b/tests/utils/test_validator.py @@ -4,9 +4,10 @@ # Github: https://github.com/thieu1995 % # --------------------------------------------------% -from mealpy.utils import validator import pytest +from mealpy.utils import validator + @pytest.mark.parametrize("value, bound, output", [