diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index a8bebcf..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5fc3cab --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,69 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.9", "3.11"] + + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - name: Install ALDes and dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[test]" + - name: Verify installed commands and dependencies + run: | + python -m pip check + aldes-train --help + aldes-paper-subset --help + - name: Lint + run: | + python -m ruff check . + python -m ruff format --check . + - name: Test + env: + ALDES_DEVICE: cpu + ALDES_EVAL_WORKERS: "2" + run: python -m pytest -q + + package: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + cache: pip + - run: python -m pip install --upgrade pip build twine + - run: python -m build + - run: python -m twine check dist/* + - run: python -m venv /tmp/aldes-wheel + - run: /tmp/aldes-wheel/bin/python -m pip install dist/*.whl + - name: Validate the installed wheel outside the repository + working-directory: /tmp + run: | + /tmp/aldes-wheel/bin/python -m pip check + /tmp/aldes-wheel/bin/aldes-train --help + /tmp/aldes-wheel/bin/aldes-paper-subset --help + /tmp/aldes-wheel/bin/python - <<'PY' + import importlib.metadata + from run_paper_subset import DEFAULT_REFERENCE_DIR, _reference_result + + assert importlib.metadata.version("aldes") == "2.0.0" + assert DEFAULT_REFERENCE_DIR.is_dir() + assert _reference_result(DEFAULT_REFERENCE_DIR, 1).size == 30 + PY diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..74fe5f8 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,26 @@ +name: release assets + +on: + release: + types: [published] + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.release.tag_name }} + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + - run: python -m pip install --upgrade pip build twine + - run: python -m build + - run: python -m twine check dist/* + - name: Attach distributions to the GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "${{ github.event.release.tag_name }}" dist/* --clobber diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2ab8f0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +.DS_Store +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.venv/ +build/ +dist/ +*.egg-info/ +logs/ +experiments/ +ela/ +*.pt +*.pth +*.ckpt diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e179a42 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,43 @@ +# Changelog + +All notable changes to ALDes are documented here. + +## 2.0.0 - 2026-07-20 + +### Added + +- A pure-Python execution path backed by AutoOptLib 1.3.0, with no MATLAB or + MATLAB Engine runtime dependency. +- Automatic PyTorch accelerator selection for NVIDIA CUDA, AMD ROCm, Apple + MPS, and CPU, with environment-variable overrides. +- Deterministic CPU multiprocessing for generated-algorithm and objective + evaluation while neural-network work remains on the selected PyTorch device. +- Explicit independent single-problem and feature-conditioned continual-design + modes. Independent design is the default and does not extract problem + features; continual design uses landscape features and EWC. +- A constrained generator and matching executor grammar: fork can follow + choose, each branch contains one search operation except that crossover may + be followed by mutation, and branches merge into one shared update. +- Command-line entry points for training and the time-bounded paper subset, + portable packaged reference results, tests, and cross-version CI. + +### Changed + +- Aligned the PBO training protocol with the paper: 100 PPO epochs, 16 sampled + algorithms per epoch, five PPO updates, 5,000 training evaluations, and an + optional 30-run/50,000-evaluation final test. +- Replaced the historical Python-to-MATLAB bridge with the public Python + AutoOptLib ALDes backend and its 32-token vocabulary. +- Made one PBO problem and one seed the safe default command-line scope. +- Moved historical plotting results from the removed MATLAB tree into + `draw/datas/reference_results` without changing their contents. + +### Removed + +- Bundled MATLAB source, MATLAB-specific bridge scripts, stale bytecode, + obsolete TorchText data loaders, and generated experiment artifacts. + +## 1.0.0 + +- Original research release combining Python model training with MATLAB + algorithm execution. diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 0000000..5b0ab14 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,40 @@ +cff-version: 1.2.0 +message: "If you use ALDes, please cite the paper below." +title: "ALDes: Automated Metaheuristic Algorithm Design with Autoregressive Learning" +type: software +version: 2.0.0 +date-released: 2026-07-20 +repository-code: "https://github.com/auto4opt/ALDes" +license: Apache-2.0 +authors: + - family-names: Zhao + given-names: Qi + - family-names: Liu + given-names: Tengfei + - family-names: Yan + given-names: Bai + - family-names: Duan + given-names: Qiqi + - family-names: Yang + given-names: Jian + - family-names: Shi + given-names: Yuhui +preferred-citation: + type: article + title: "Automated Metaheuristic Algorithm Design with Autoregressive Learning" + year: 2024 + doi: "10.1109/TEVC.2024.3464677" + journal: "IEEE Transactions on Evolutionary Computation" + authors: + - family-names: Zhao + given-names: Qi + - family-names: Liu + given-names: Tengfei + - family-names: Yan + given-names: Bai + - family-names: Duan + given-names: Qiqi + - family-names: Yang + given-names: Jian + - family-names: Shi + given-names: Yuhui diff --git a/EWC.py b/EWC.py index 727521e..5e3759f 100644 --- a/EWC.py +++ b/EWC.py @@ -1,60 +1,40 @@ -from copy import deepcopy +"""Diagonal-Fisher elastic weight consolidation for continual ALDes.""" + +from __future__ import annotations import torch from torch import nn -from torch.nn import functional as F -from torch.autograd import Variable -import torch.utils.data - - -def variable(t: torch.Tensor, use_cuda=True, **kwargs): - if torch.cuda.is_available() and use_cuda: - t = t.cuda() - return Variable(t, **kwargs) -class EWC(object): +class EWC: def __init__(self, model: nn.Module): - - self.model = model - - self.params = {n: p for n, p in self.model.named_parameters() if p.requires_grad} - self._means = {} - self._precision_matrices = None #self._diag_fisher() - - for n, p in deepcopy(self.params).items(): - self._means[n] = variable(p.data) - - def _diag_fisher(self): - precision_matrices = {} - for n, p in deepcopy(self.params).items(): - p.data.zero_() - precision_matrices[n] = variable(p.data) - - #self.model.eval() - for n, p in self.model.named_parameters(): - if p.grad != None: - precision_matrices[n].data += p.grad.data ** 2 - precision_matrices = {n: p for n, p in precision_matrices.items()} - return precision_matrices - - def update_diag_fisher(self,model): - precision_matrices = {} - for n, p in deepcopy(self.params).items(): - p.data.zero_() - precision_matrices[n] = variable(p.data) - for n, p in model.named_parameters(): - if p.grad != None: - precision_matrices[n].data += p.grad.data ** 2 - precision_matrices = {n: p for n, p in precision_matrices.items()} - if self._precision_matrices is None: - self._precision_matrices = precision_matrices - else: - for key in precision_matrices: - self._precision_matrices[key] +=precision_matrices[key] - def penalty(self, model: nn.Module): - loss = 0 - for n, p in model.named_parameters(): - _loss = self._precision_matrices[n] * (p - self._means[n]) ** 2 - loss += _loss.sum() - return loss*100 \ No newline at end of file + self._means = { + name: parameter.detach().clone() + for name, parameter in model.named_parameters() + if parameter.requires_grad + } + self._precision_matrices = { + name: torch.zeros_like(parameter) + for name, parameter in model.named_parameters() + if parameter.requires_grad + } + + def update_diag_fisher(self, model: nn.Module) -> None: + """Accumulate squared policy gradients for one sampled batch.""" + + for name, parameter in model.named_parameters(): + if name in self._precision_matrices and parameter.grad is not None: + self._precision_matrices[name] += parameter.grad.detach().square() + + def penalty(self, model: nn.Module) -> torch.Tensor: + loss = torch.zeros((), device=next(model.parameters()).device) + for name, parameter in model.named_parameters(): + if name in self._precision_matrices: + loss = ( + loss + + ( + self._precision_matrices[name] + * (parameter - self._means[name]).square() + ).sum() + ) + return loss diff --git a/README.md b/README.md index fe17dcb..222af0f 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,191 @@ -Code for Automated Metaheuristic Algorithm Design with Autoregressive Learning +# ALDes -### 1. Env congfig: - - Follow aldes.yaml, and you need congfig Matlab R2020B connect to you aldes python env. -### 2. Training: +Pure-Python implementation of **Automated Metaheuristic Algorithm Design with +Autoregressive Learning** (ALDes). -#### Prepare - Run plfacco_feature.py to calculate PBO problem's Landscape feature. +ALDes treats algorithm design as constrained autoregressive sequence generation. +A Transformer policy generates a variable-length metaheuristic program, PPO +learns from the program's performance, and AutoOptLib executes the generated +algorithm without MATLAB or MATLAB Engine. -#### Training - In train.py, run rain_separately() for single problem task, and train_in_one() for continual problem task. +## Release scope +This release supports the paper's 23 pseudo-Boolean optimization (PBO) tasks: + +- independent design from scratch for one target problem; +- feature-conditioned continual design with EWC; +- the paper's training and test budgets; +- automatic neural-network acceleration on CUDA, ROCm, or Apple MPS; +- parallel CPU evaluation of generated algorithms. + +The paper's RIS beamforming and power-system restoration experiments are not +part of this release. The repository therefore makes no claim that those two +application results can be reproduced here. + +## Installation + +Python 3.9--3.11 is supported. Clone only this repository and install it from +the repository root: + +```bash +git clone --branch v2.0.0 --depth 1 https://github.com/auto4opt/ALDes.git +cd ALDes +python -m pip install -e . +``` + +The installation automatically downloads the compatible +`autooptlib[aldes]` dependency from the official AutoOptLib GitHub release. +Users do not need to clone AutoOptLib separately. The Python import name is +lowercase: + +```python +import autooptlib +``` + +A Conda environment can be created instead: + +```bash +conda env create -f aldes.yaml +conda activate aldes +``` + +For development and tests, install the test extra: + +```bash +python -m pip install -e ".[test]" +``` + +## Quick start + +The default command performs one independent design trial on PBO F1 with +seed 1: + +```bash +aldes-train +``` + +The equivalent source command is: + +```bash +python train.py +``` + +The inferred algorithm sequence is printed and written to the run log. A +single-problem run does not save a model checkpoint because the trained policy +is not reused after its final algorithm has been inferred. + +Choose another problem or multiple explicit trials with command-line options: + +```bash +aldes-train --problems 14 --seeds 1 +aldes-train --problems 1,14,15 --seeds 1,2 +aldes-train --problems 14 --seeds 1 --evaluate-test +``` + +`--evaluate-test` applies the paper's full 30-run test protocol after training. +Without it, only training and final algorithm inference are performed. + +## Continual design + +Continual mode extracts PBO landscape features, conditions one policy on those +features, and applies EWC between tasks: + +```bash +aldes-train --mode continual --problems 1,2,11 --seeds 1 +``` + +The default continual sequence is defined in `conf.py`. Checkpoint output is +optional and is only intended for a policy that must be reused across continual +stages: + +```bash +aldes-train --mode continual --checkpoint-dir logs/continual +``` + +No checkpoint binary is distributed with this repository. + +## Compute devices + +PyTorch devices are selected automatically in this order: + +1. NVIDIA CUDA or AMD ROCm; +2. Apple Metal Performance Shaders (MPS); +3. CPU. + +PyTorch must have been built for the user's accelerator. In ROCm builds, AMD +devices are exposed through PyTorch's `cuda` API. Override automatic selection +when needed: + +```bash +ALDES_DEVICE=cpu aldes-train +ALDES_DEVICE=cuda aldes-train +ALDES_DEVICE=mps aldes-train +``` + +Only neural-network training and inference use the selected accelerator. +Generated algorithms and objective functions run on CPUs. Candidate algorithms +are evaluated in parallel using up to the available logical CPU cores: + +```bash +ALDES_EVAL_WORKERS=8 aldes-train +ALDES_EVAL_WORKERS=1 aldes-train # disable multiprocessing +``` + +## Paper protocol + +The default configuration for each PBO design trial is: + +- training instances: dimensions 100, 225, and 400; +- 100 PPO epochs and 16 generated algorithms per epoch; +- 5 PPO updates per epoch; +- 5 runs per training instance and 5,000 function evaluations per run; +- population size 50; +- test instance: dimension 625; +- 30 test runs and 50,000 function evaluations per run. + +The single-problem mode does not extract or input problem features. Feature +conditioning is enabled only in continual mode. + +## Time-bounded paper subset + +The repository includes a runner that completes whole paper-protocol trials +until the next problem is predicted to exceed a wall-clock budget: + +```bash +aldes-paper-subset --problems 1,14,15 --time-budget-minutes 60 +``` + +The budget is checked only between problems. A started problem always retains +all 100 epochs and the complete 30-run test. Structured JSON results are written +under `experiments/`; this local output directory and all model checkpoints are +ignored by Git. + +Historical comparison data used by the plotting notebooks are stored under +`draw/datas/reference_results` and can be read with SciPy. + +## Tests + +Run the test suite and static checks with: + +```bash +python -m pytest -q +python -m ruff check . +``` + +GitHub Actions repeats installation, linting, and tests on Linux with Python +3.9 and 3.11. Tests cover device selection, serial/parallel evaluation parity, +single and continual feature modes, grammar-valid generation, PPO likelihood +replay, EWC accumulation, and a pure-Python PPO update. + +## Citation + +If you use ALDes, cite: + +> Q. Zhao, T. Liu, B. Yan, Q. Duan, J. Yang, and Y. Shi, "Automated +> Metaheuristic Algorithm Design with Autoregressive Learning," IEEE +> Transactions on Evolutionary Computation, 2024. +> https://doi.org/10.1109/TEVC.2024.3464677 + +## License + +ALDes is released under the Apache License 2.0. See `LICENSE`. diff --git a/__pycache__/EWC.cpython-38.pyc b/__pycache__/EWC.cpython-38.pyc deleted file mode 100644 index 39d135f..0000000 Binary files a/__pycache__/EWC.cpython-38.pyc and /dev/null differ diff --git a/__pycache__/conf.cpython-38.pyc b/__pycache__/conf.cpython-38.pyc deleted file mode 100644 index be358f7..0000000 Binary files a/__pycache__/conf.cpython-38.pyc and /dev/null differ diff --git a/__pycache__/data.cpython-38.pyc b/__pycache__/data.cpython-38.pyc deleted file mode 100644 index 5f2e47a..0000000 Binary files a/__pycache__/data.cpython-38.pyc and /dev/null differ diff --git a/__pycache__/matlab_setting.cpython-38.pyc b/__pycache__/matlab_setting.cpython-38.pyc deleted file mode 100644 index edb2300..0000000 Binary files a/__pycache__/matlab_setting.cpython-38.pyc and /dev/null differ diff --git a/__pycache__/pflacco_test.cpython-38.pyc b/__pycache__/pflacco_test.cpython-38.pyc deleted file mode 100644 index 930753a..0000000 Binary files a/__pycache__/pflacco_test.cpython-38.pyc and /dev/null differ diff --git a/aldes.yaml b/aldes.yaml index ab42c00..c5908d4 100644 --- a/aldes.yaml +++ b/aldes.yaml @@ -1,135 +1,8 @@ name: aldes channels: - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/ - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/ - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/Paddle/ - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/fastai/ - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/ - - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/ + - conda-forge dependencies: - - ca-certificates=2023.08.22=haa95532_0 - - openssl=1.1.1w=h2bbff1b_0 - - pip=23.3.1=py38haa95532_0 - - python=3.8.0=hff0d562_2 - - setuptools=68.0.0=py38haa95532_0 - - sqlite=3.41.2=h2bbff1b_0 - - vc=14.2=h21ff451_1 - - vs2015_runtime=14.27.29016=h5e58377_2 - - wheel=0.41.2=py38haa95532_0 + - python>=3.9,<3.12 + - pip>=23 - pip: - - absl-py==2.0.0 - - aiosignal==1.3.1 - - asttokens==2.4.1 - - astunparse==1.6.3 - - attrs==23.2.0 - - backcall==0.2.0 - - cachetools==5.3.2 - - certifi==2023.11.17 - - charset-normalizer==3.3.2 - - click==8.1.7 - - colorama==0.4.6 - - comm==0.2.2 - - contourpy==1.1.1 - - cycler==0.12.1 - - debugpy==1.8.2 - - decorator==5.1.1 - - dill==0.3.7 - - einops==0.7.0 - - et-xmlfile==1.1.0 - - executing==2.0.1 - - filelock==3.15.4 - - flatbuffers==23.5.26 - - fonttools==4.46.0 - - frozenlist==1.4.1 - - gast==0.4.0 - - google-auth==2.24.0 - - google-auth-oauthlib==1.0.0 - - google-pasta==0.2.0 - - grpcio==1.59.3 - - h5py==3.10.0 - - idna==3.6 - - importlib-metadata==7.0.0 - - importlib-resources==6.1.1 - - ioh==0.3.14 - - ipykernel==6.29.5 - - ipython==8.12.3 - - jedi==0.19.1 - - joblib==1.3.2 - - jsonschema==4.23.0 - - jsonschema-specifications==2023.12.1 - - jupyter-client==8.6.2 - - jupyter-core==5.7.2 - - keras==2.13.1 - - kiwisolver==1.4.5 - - libclang==16.0.6 - - markdown==3.5.1 - - markupsafe==2.1.3 - - matlabengineforpython==9.13 - - matplotlib==3.7.4 - - matplotlib-inline==0.1.7 - - msgpack==1.0.8 - - multiprocess==0.70.15 - - nest-asyncio==1.6.0 - - numdifftools==0.9.41 - - numpy==1.24.3 - - oauthlib==3.2.2 - - openpyxl==3.1.2 - - opt-einsum==3.3.0 - - packaging==23.2 - - pandas==2.0.3 - - parso==0.8.4 - - pflacco==1.2.2 - - pickleshare==0.7.5 - - pillow==10.1.0 - - pkgutil-resolve-name==1.3.10 - - platformdirs==4.2.2 - - prompt-toolkit==3.0.47 - - protobuf==4.25.1 - - psutil==6.0.0 - - pure-eval==0.2.2 - - pyasn1==0.5.1 - - pyasn1-modules==0.3.0 - - pydoe==0.3.8 - - pygments==2.18.0 - - pyparsing==3.1.1 - - python-dateutil==2.8.2 - - pytz==2023.3.post1 - - pywin32==306 - - pyyaml==6.0.1 - - pyzmq==26.0.3 - - ray==2.10.0 - - referencing==0.35.1 - - requests==2.31.0 - - requests-oauthlib==1.3.1 - - rpds-py==0.19.0 - - rsa==4.9 - - salib==1.4.7 - - scikit-learn==1.2.2 - - scipy==1.10.1 - - seaborn==0.13.2 - - six==1.16.0 - - stack-data==0.6.3 - - tensorboard==2.13.0 - - tensorboard-data-server==0.7.2 - - tensorboardx==2.6.2.2 - - tensorflow==2.13.0 - - tensorflow-estimator==2.13.0 - - tensorflow-intel==2.13.0 - - tensorflow-io-gcs-filesystem==0.31.0 - - termcolor==2.4.0 - - threadpoolctl==3.2.0 - - torch==1.10.0+cu102 - - torchtext==0.11.0 - - tornado==6.4.1 - - tqdm==4.66.1 - - traitlets==5.14.3 - - typing-extensions==4.5.0 - - tzdata==2023.3 - - urllib3==2.1.0 - - wcwidth==0.2.13 - - werkzeug==3.0.1 - - wrapt==1.16.0 - - zipp==3.17.0 -prefix: C:\Users\21902\.conda\envs\aldes + - -e .[test] diff --git a/aldes_setting.py b/aldes_setting.py new file mode 100644 index 0000000..2f743e0 --- /dev/null +++ b/aldes_setting.py @@ -0,0 +1,9 @@ +"""Compatibility aliases for the original standalone ALDes model.""" + +from autooptlib.aldes.vocabulary import BEGIN_INDEX, END_INDEX, VOCABULARY_SIZE + +begin_index = BEGIN_INDEX +end_index = END_INDEX +total_index = VOCABULARY_SIZE + +__all__ = ["begin_index", "end_index", "total_index"] diff --git a/conf.py b/conf.py index 46b6e00..c1aced3 100644 --- a/conf.py +++ b/conf.py @@ -1,10 +1,13 @@ -import torch +import os -# GPU device setting -device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") +from util.device import resolve_device -# model parameter setting -batch_size = 1 +# Automatically prefer NVIDIA CUDA / AMD ROCm, then Apple MPS, and finally +# CPU. Set ALDES_DEVICE=cpu/cuda/mps/rocm to override automatic selection. +device_preference = os.environ.get("ALDES_DEVICE", "auto") +device = resolve_device(device_preference) + +# Transformer architecture max_len = 50 d_model = 32 n_layers = 8 @@ -12,22 +15,22 @@ ffn_hidden = 2048 drop_prob = 0.1 -# optimizer parameter setting +# ALDes has two explicit modes. Single-problem design is the default and does +# not extract or feed landscape features. Continual design conditions the +# policy on paper-style PBO features and may use EWC between tasks. +aldes_mode = "single" # "single" or "continual" +use_ewc = True +ewc_weight = 200.0 +continual_problem_sets = ( + (1, 2, 3, 4, 5, 6, 7), + (1, 2, 11, 18, 19, 22, 23), +) + +# Optimizer and PPO settings init_lr = 5e-5 -factor = 0.9 adam_eps = 5e-9 -patience = 10 -warmup = 100 -epoch = 1000 clip = 1.0 weight_decay = 5e-4 -inf = float('inf') - -# my config -total_epoch = 50 # DEFULT 100 +total_epoch = 100 ppo_epoch = 5 batch_size_src = 16 - -model_type = 0 # 0 :transformer 1: LSTM -train_type = 0 # 0 :PPO 1: PG - diff --git a/data.py b/data.py deleted file mode 100644 index 45780de..0000000 --- a/data.py +++ /dev/null @@ -1,10 +0,0 @@ -from conf import * -from util.data_loader import DataLoader -from util.tokenizer import Tokenizer - - -src_pad_idx = None -trg_pad_idx = None -trg_sos_idx = None -enc_voc_size = 100 -dec_voc_size = 30 \ No newline at end of file diff --git a/draw/__init__.py b/draw/__init__.py new file mode 100644 index 0000000..cca2518 --- /dev/null +++ b/draw/__init__.py @@ -0,0 +1 @@ +"""Plotting notebooks and packaged ALDes reference results.""" diff --git a/draw/bloxplot.ipynb b/draw/bloxplot.ipynb index 953c108..0c04fcb 100644 --- a/draw/bloxplot.ipynb +++ b/draw/bloxplot.ipynb @@ -32,12 +32,12 @@ " datas = []\n", " for alg in algs:\n", " if alg == 'tabu_irace':\n", - " pkl_file_path = f'../matlab/result/{alg}/instance_4/' + f'f{problem_id}.pkl'\n", + " pkl_file_path = f'datas/reference_results/{alg}/instance_4/' + f'f{problem_id}.pkl'\n", " with open(pkl_file_path, 'rb') as f:\n", " # loaded_data: steps(100)*algs(16)*instance(3)*runs(5)\n", " data = pickle.load(f)\n", " else: \n", - " mat_file_path = f'../matlab/result/{alg}/instance_4/' + f'f{problem_id}.mat'\n", + " mat_file_path = f'datas/reference_results/{alg}/instance_4/' + f'f{problem_id}.mat'\n", " mat_data = scipy.io.loadmat(mat_file_path)\n", " data = -mat_data['res'][0]\n", " datas.append(data)\n", @@ -64,7 +64,7 @@ " datas = []\n", " for problem_id in [1,13,15,20]:\n", " \n", - " mat_file_path = f'../matlab/result/design/instance_4/' + f'f{problem_id}.mat'\n", + " mat_file_path = f'datas/reference_results/design/instance_4/' + f'f{problem_id}.mat'\n", " mat_data = scipy.io.loadmat(mat_file_path)\n", "\n", " data = -mat_data['res'][0]\n", @@ -115,7 +115,7 @@ "source": [ "algs = ['design','Discrete_Genetic_Algorithm','Discrete_Iterative_Local_Search','tabu_irace']\n", "display_alg_name = ['Ours', 'GA', 'ILS', 'TS']\n", - "save_path = f'result_pictures/bloxplot/'\n", + "save_path = 'paper_pictures/Supplementary_Pic/'\n", "\n", "#draw_bloxplot(algs, display_alg_name, save_path)\n", "draw_bloxplot_in_one_pic(save_path)" diff --git a/draw/continue_problem.ipynb b/draw/continue_problem.ipynb index 417c2c6..fe4aabb 100644 --- a/draw/continue_problem.ipynb +++ b/draw/continue_problem.ipynb @@ -1105,7 +1105,7 @@ " # plt.xlabel('Episode')\n", " # plt.ylabel('Performance')\n", "\n", - " plt.savefig(f'result_pictures/continue_problem\\F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')" + " plt.savefig(f'paper_pictures/continue_problem/F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')" ] }, { diff --git a/draw/convergence_curve.ipynb b/draw/convergence_curve.ipynb index 9dcd6bc..a4c553c 100644 --- a/draw/convergence_curve.ipynb +++ b/draw/convergence_curve.ipynb @@ -69,7 +69,7 @@ "# draw convergence curves of algs in paper with Pseudocode [1,13,15,20]\n", "problem_set = [1, 13, 15, 20]\n", "\n", - "data_path = 'D:\\\\01Code\\\\ALDes\\\\draw\\\\datas\\\\mats\\\\ArchSolution\\\\'\n", + "data_path = 'datas/mats/ArchSolution/'\n", "for problem in problem_set:\n", " mat_path = data_path + f'f{problem}.mat'\n", " mat_data = scipy.io.loadmat(mat_path)\n", @@ -81,7 +81,7 @@ " plt.xlabel('Iterations')\n", " plt.ylabel('Performance')\n", "\n", - " plt.savefig(f'result_pictures\\convergence_curve\\Alg{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')\n", + " plt.savefig(f'paper_pictures/Supplementary_Pic/convergence_curve/Alg{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')\n", "\n" ] } diff --git a/draw/datas/__init__.py b/draw/datas/__init__.py new file mode 100644 index 0000000..eadbc07 --- /dev/null +++ b/draw/datas/__init__.py @@ -0,0 +1 @@ +"""Data resources used by the ALDes plotting notebooks.""" diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f1.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f1.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f1.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f1.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f10.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f10.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f10.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f10.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f11.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f11.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f11.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f11.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f12.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f12.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f12.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f12.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f13.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f13.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f13.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f13.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f14.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f14.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f14.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f14.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f15.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f15.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f15.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f15.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f16.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f16.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f16.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f16.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f17.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f17.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f17.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f17.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f18.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f18.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f18.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f18.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f19.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f19.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f19.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f19.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f2.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f2.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f2.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f2.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f20.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f20.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f20.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f20.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f21.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f21.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f21.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f21.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f22.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f22.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f22.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f22.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f23.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f23.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f23.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f23.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f3.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f3.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f3.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f3.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f4.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f4.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f4.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f4.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f5.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f5.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f5.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f5.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f6.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f6.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f6.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f6.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f7.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f7.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f7.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f7.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f8.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f8.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f8.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f8.mat diff --git a/matlab/result/Discrete Simulated Annealing/instance4_default_para/f9.mat b/draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f9.mat similarity index 100% rename from matlab/result/Discrete Simulated Annealing/instance4_default_para/f9.mat rename to draw/datas/reference_results/Discrete Simulated Annealing/instance4_default_para/f9.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f1.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f1.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f1.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f1.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f10.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f10.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f10.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f10.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f11.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f11.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f11.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f11.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f12.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f12.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f12.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f12.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f13.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f13.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f13.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f13.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f14.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f14.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f14.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f14.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f15.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f15.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f15.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f15.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f16.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f16.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f16.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f16.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f17.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f17.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f17.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f17.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f18.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f18.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f18.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f18.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f19.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f19.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f19.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f19.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f2.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f2.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f2.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f2.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f20.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f20.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f20.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f20.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f21.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f21.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f21.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f21.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f22.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f22.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f22.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f22.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f23.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f23.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f23.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f23.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f3.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f3.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f3.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f3.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f4.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f4.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f4.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f4.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f5.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f5.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f5.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f5.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f6.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f6.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f6.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f6.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f7.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f7.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f7.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f7.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f8.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f8.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f8.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f8.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/f9.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f9.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/f9.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/f9.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_1/mean_var_design_data.xlsx b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_1/mean_var_design_data.xlsx rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_1/mean_var_design_data.xlsx diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f1.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f1.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f1.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f1.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f10.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f10.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f10.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f10.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f11.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f11.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f11.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f11.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f12.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f12.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f12.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f12.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f13.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f13.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f13.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f13.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f14.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f14.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f14.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f14.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f15.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f15.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f15.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f15.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f16.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f16.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f16.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f16.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f17.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f17.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f17.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f17.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f18.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f18.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f18.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f18.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f19.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f19.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f19.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f19.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f2.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f2.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f2.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f2.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f20.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f20.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f20.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f20.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f21.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f21.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f21.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f21.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f22.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f22.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f22.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f22.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f23.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f23.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f23.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f23.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f3.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f3.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f3.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f3.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f4.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f4.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f4.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f4.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f5.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f5.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f5.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f5.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f6.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f6.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f6.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f6.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f7.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f7.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f7.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f7.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f8.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f8.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f8.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f8.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/f9.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f9.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/f9.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/f9.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_2/mean_var_design_data.xlsx b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_2/mean_var_design_data.xlsx rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_2/mean_var_design_data.xlsx diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f1.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f1.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f1.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f1.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f10.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f10.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f10.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f10.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f11.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f11.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f11.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f11.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f12.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f12.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f12.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f12.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f13.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f13.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f13.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f13.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f14.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f14.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f14.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f14.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f15.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f15.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f15.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f15.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f16.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f16.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f16.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f16.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f17.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f17.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f17.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f17.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f18.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f18.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f18.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f18.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f19.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f19.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f19.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f19.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f2.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f2.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f2.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f2.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f20.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f20.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f20.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f20.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f21.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f21.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f21.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f21.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f22.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f22.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f22.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f22.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f23.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f23.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f23.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f23.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f3.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f3.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f3.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f3.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f4.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f4.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f4.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f4.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f5.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f5.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f5.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f5.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f6.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f6.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f6.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f6.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f7.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f7.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f7.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f7.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f8.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f8.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f8.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f8.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/f9.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f9.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/f9.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/f9.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_3/mean_var_design_data.xlsx b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_3/mean_var_design_data.xlsx rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_3/mean_var_design_data.xlsx diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f1.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f1.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f1.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f1.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f10.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f10.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f10.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f10.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f11.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f11.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f11.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f11.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f12.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f12.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f12.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f12.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f13.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f13.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f13.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f13.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f14.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f14.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f14.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f14.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f15.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f15.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f15.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f15.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f16.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f16.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f16.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f16.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f17.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f17.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f17.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f17.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f18.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f18.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f18.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f18.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f19.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f19.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f19.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f19.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f2.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f2.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f2.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f2.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f20.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f20.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f20.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f20.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f21.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f21.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f21.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f21.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f22.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f22.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f22.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f22.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f23.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f23.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f23.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f23.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f3.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f3.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f3.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f3.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f4.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f4.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f4.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f4.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f5.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f5.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f5.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f5.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f6.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f6.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f6.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f6.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f7.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f7.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f7.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f7.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f8.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f8.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f8.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f8.mat diff --git a/matlab/result/Discrete_Genetic_Algorithm/instance_4/f9.mat b/draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f9.mat similarity index 100% rename from matlab/result/Discrete_Genetic_Algorithm/instance_4/f9.mat rename to draw/datas/reference_results/Discrete_Genetic_Algorithm/instance_4/f9.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f1.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f1.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f1.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f1.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f10.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f10.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f10.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f10.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f11.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f11.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f11.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f11.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f12.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f12.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f12.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f12.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f13.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f13.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f13.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f13.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f14.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f14.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f14.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f14.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f15.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f15.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f15.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f15.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f16.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f16.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f16.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f16.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f17.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f17.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f17.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f17.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f18.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f18.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f18.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f18.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f19.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f19.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f19.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f19.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f2.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f2.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f2.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f2.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f20.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f20.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f20.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f20.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f21.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f21.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f21.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f21.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f22.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f22.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f22.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f22.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f23.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f23.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f23.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f23.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f3.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f3.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f3.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f3.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f4.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f4.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f4.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f4.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f5.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f5.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f5.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f5.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f6.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f6.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f6.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f6.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f7.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f7.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f7.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f7.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f8.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f8.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f8.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f8.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/f9.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f9.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/f9.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/f9.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_1/mean_var_design_data.xlsx b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_1/mean_var_design_data.xlsx rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_1/mean_var_design_data.xlsx diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f1.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f1.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f1.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f1.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f10.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f10.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f10.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f10.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f11.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f11.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f11.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f11.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f12.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f12.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f12.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f12.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f13.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f13.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f13.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f13.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f14.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f14.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f14.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f14.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f15.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f15.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f15.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f15.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f16.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f16.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f16.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f16.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f17.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f17.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f17.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f17.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f18.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f18.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f18.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f18.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f19.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f19.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f19.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f19.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f2.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f2.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f2.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f2.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f20.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f20.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f20.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f20.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f21.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f21.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f21.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f21.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f22.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f22.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f22.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f22.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f23.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f23.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f23.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f23.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f3.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f3.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f3.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f3.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f4.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f4.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f4.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f4.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f5.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f5.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f5.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f5.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f6.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f6.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f6.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f6.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f7.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f7.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f7.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f7.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f8.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f8.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f8.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f8.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/f9.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f9.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/f9.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/f9.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_2/mean_var_design_data.xlsx b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_2/mean_var_design_data.xlsx rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_2/mean_var_design_data.xlsx diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f1.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f1.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f1.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f1.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f10.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f10.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f10.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f10.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f11.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f11.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f11.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f11.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f12.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f12.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f12.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f12.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f13.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f13.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f13.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f13.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f14.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f14.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f14.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f14.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f15.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f15.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f15.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f15.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f16.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f16.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f16.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f16.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f17.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f17.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f17.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f17.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f18.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f18.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f18.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f18.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f19.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f19.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f19.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f19.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f2.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f2.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f2.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f2.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f20.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f20.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f20.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f20.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f21.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f21.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f21.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f21.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f22.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f22.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f22.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f22.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f23.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f23.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f23.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f23.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f3.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f3.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f3.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f3.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f4.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f4.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f4.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f4.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f5.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f5.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f5.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f5.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f6.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f6.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f6.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f6.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f7.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f7.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f7.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f7.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f8.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f8.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f8.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f8.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/f9.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f9.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/f9.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/f9.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_3/mean_var_design_data.xlsx b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_3/mean_var_design_data.xlsx rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_3/mean_var_design_data.xlsx diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f1.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f1.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f1.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f1.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f10.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f10.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f10.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f10.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f11.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f11.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f11.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f11.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f12.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f12.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f12.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f12.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f13.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f13.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f13.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f13.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f14.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f14.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f14.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f14.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f15.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f15.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f15.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f15.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f16.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f16.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f16.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f16.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f17.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f17.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f17.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f17.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f18.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f18.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f18.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f18.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f19.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f19.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f19.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f19.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f2.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f2.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f2.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f2.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f20.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f20.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f20.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f20.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f21.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f21.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f21.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f21.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f22.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f22.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f22.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f22.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f23.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f23.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f23.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f23.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f3.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f3.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f3.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f3.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f4.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f4.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f4.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f4.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f5.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f5.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f5.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f5.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f6.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f6.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f6.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f6.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f7.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f7.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f7.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f7.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f8.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f8.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f8.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f8.mat diff --git a/matlab/result/Discrete_Iterative_Local_Search/instance_4/f9.mat b/draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f9.mat similarity index 100% rename from matlab/result/Discrete_Iterative_Local_Search/instance_4/f9.mat rename to draw/datas/reference_results/Discrete_Iterative_Local_Search/instance_4/f9.mat diff --git a/draw/datas/reference_results/__init__.py b/draw/datas/reference_results/__init__.py new file mode 100644 index 0000000..f3cf6d4 --- /dev/null +++ b/draw/datas/reference_results/__init__.py @@ -0,0 +1 @@ +"""Historical paper results used for reproducibility comparisons.""" diff --git a/matlab/result/design/instance_1/f1.mat b/draw/datas/reference_results/design/instance_1/f1.mat similarity index 100% rename from matlab/result/design/instance_1/f1.mat rename to draw/datas/reference_results/design/instance_1/f1.mat diff --git a/matlab/result/design/instance_1/f10.mat b/draw/datas/reference_results/design/instance_1/f10.mat similarity index 100% rename from matlab/result/design/instance_1/f10.mat rename to draw/datas/reference_results/design/instance_1/f10.mat diff --git a/matlab/result/design/instance_1/f11.mat b/draw/datas/reference_results/design/instance_1/f11.mat similarity index 100% rename from matlab/result/design/instance_1/f11.mat rename to draw/datas/reference_results/design/instance_1/f11.mat diff --git a/matlab/result/design/instance_1/f12.mat b/draw/datas/reference_results/design/instance_1/f12.mat similarity index 100% rename from matlab/result/design/instance_1/f12.mat rename to draw/datas/reference_results/design/instance_1/f12.mat diff --git a/matlab/result/design/instance_1/f13.mat b/draw/datas/reference_results/design/instance_1/f13.mat similarity index 100% rename from matlab/result/design/instance_1/f13.mat rename to draw/datas/reference_results/design/instance_1/f13.mat diff --git a/matlab/result/design/instance_1/f14.mat b/draw/datas/reference_results/design/instance_1/f14.mat similarity index 100% rename from matlab/result/design/instance_1/f14.mat rename to draw/datas/reference_results/design/instance_1/f14.mat diff --git a/matlab/result/design/instance_1/f15.mat b/draw/datas/reference_results/design/instance_1/f15.mat similarity index 100% rename from matlab/result/design/instance_1/f15.mat rename to draw/datas/reference_results/design/instance_1/f15.mat diff --git a/matlab/result/design/instance_1/f16.mat b/draw/datas/reference_results/design/instance_1/f16.mat similarity index 100% rename from matlab/result/design/instance_1/f16.mat rename to draw/datas/reference_results/design/instance_1/f16.mat diff --git a/matlab/result/design/instance_1/f17.mat b/draw/datas/reference_results/design/instance_1/f17.mat similarity index 100% rename from matlab/result/design/instance_1/f17.mat rename to draw/datas/reference_results/design/instance_1/f17.mat diff --git a/matlab/result/design/instance_1/f18.mat b/draw/datas/reference_results/design/instance_1/f18.mat similarity index 100% rename from matlab/result/design/instance_1/f18.mat rename to draw/datas/reference_results/design/instance_1/f18.mat diff --git a/matlab/result/design/instance_1/f19.mat b/draw/datas/reference_results/design/instance_1/f19.mat similarity index 100% rename from matlab/result/design/instance_1/f19.mat rename to draw/datas/reference_results/design/instance_1/f19.mat diff --git a/matlab/result/design/instance_1/f2.mat b/draw/datas/reference_results/design/instance_1/f2.mat similarity index 100% rename from matlab/result/design/instance_1/f2.mat rename to draw/datas/reference_results/design/instance_1/f2.mat diff --git a/matlab/result/design/instance_1/f20.mat b/draw/datas/reference_results/design/instance_1/f20.mat similarity index 100% rename from matlab/result/design/instance_1/f20.mat rename to draw/datas/reference_results/design/instance_1/f20.mat diff --git a/matlab/result/design/instance_1/f21.mat b/draw/datas/reference_results/design/instance_1/f21.mat similarity index 100% rename from matlab/result/design/instance_1/f21.mat rename to draw/datas/reference_results/design/instance_1/f21.mat diff --git a/matlab/result/design/instance_1/f22.mat b/draw/datas/reference_results/design/instance_1/f22.mat similarity index 100% rename from matlab/result/design/instance_1/f22.mat rename to draw/datas/reference_results/design/instance_1/f22.mat diff --git a/matlab/result/design/instance_1/f23.mat b/draw/datas/reference_results/design/instance_1/f23.mat similarity index 100% rename from matlab/result/design/instance_1/f23.mat rename to draw/datas/reference_results/design/instance_1/f23.mat diff --git a/matlab/result/design/instance_1/f3.mat b/draw/datas/reference_results/design/instance_1/f3.mat similarity index 100% rename from matlab/result/design/instance_1/f3.mat rename to draw/datas/reference_results/design/instance_1/f3.mat diff --git a/matlab/result/design/instance_1/f4.mat b/draw/datas/reference_results/design/instance_1/f4.mat similarity index 100% rename from matlab/result/design/instance_1/f4.mat rename to draw/datas/reference_results/design/instance_1/f4.mat diff --git a/matlab/result/design/instance_1/f5.mat b/draw/datas/reference_results/design/instance_1/f5.mat similarity index 100% rename from matlab/result/design/instance_1/f5.mat rename to draw/datas/reference_results/design/instance_1/f5.mat diff --git a/matlab/result/design/instance_1/f6.mat b/draw/datas/reference_results/design/instance_1/f6.mat similarity index 100% rename from matlab/result/design/instance_1/f6.mat rename to draw/datas/reference_results/design/instance_1/f6.mat diff --git a/matlab/result/design/instance_1/f7.mat b/draw/datas/reference_results/design/instance_1/f7.mat similarity index 100% rename from matlab/result/design/instance_1/f7.mat rename to draw/datas/reference_results/design/instance_1/f7.mat diff --git a/matlab/result/design/instance_1/f8.mat b/draw/datas/reference_results/design/instance_1/f8.mat similarity index 100% rename from matlab/result/design/instance_1/f8.mat rename to draw/datas/reference_results/design/instance_1/f8.mat diff --git a/matlab/result/design/instance_1/f9.mat b/draw/datas/reference_results/design/instance_1/f9.mat similarity index 100% rename from matlab/result/design/instance_1/f9.mat rename to draw/datas/reference_results/design/instance_1/f9.mat diff --git a/matlab/result/design/instance_1/mean_var_design_data.xlsx b/draw/datas/reference_results/design/instance_1/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/design/instance_1/mean_var_design_data.xlsx rename to draw/datas/reference_results/design/instance_1/mean_var_design_data.xlsx diff --git a/matlab/result/design/instance_2/f1.mat b/draw/datas/reference_results/design/instance_2/f1.mat similarity index 100% rename from matlab/result/design/instance_2/f1.mat rename to draw/datas/reference_results/design/instance_2/f1.mat diff --git a/matlab/result/design/instance_2/f10.mat b/draw/datas/reference_results/design/instance_2/f10.mat similarity index 100% rename from matlab/result/design/instance_2/f10.mat rename to draw/datas/reference_results/design/instance_2/f10.mat diff --git a/matlab/result/design/instance_2/f11.mat b/draw/datas/reference_results/design/instance_2/f11.mat similarity index 100% rename from matlab/result/design/instance_2/f11.mat rename to draw/datas/reference_results/design/instance_2/f11.mat diff --git a/matlab/result/design/instance_2/f12.mat b/draw/datas/reference_results/design/instance_2/f12.mat similarity index 100% rename from matlab/result/design/instance_2/f12.mat rename to draw/datas/reference_results/design/instance_2/f12.mat diff --git a/matlab/result/design/instance_2/f13.mat b/draw/datas/reference_results/design/instance_2/f13.mat similarity index 100% rename from matlab/result/design/instance_2/f13.mat rename to draw/datas/reference_results/design/instance_2/f13.mat diff --git a/matlab/result/design/instance_2/f14.mat b/draw/datas/reference_results/design/instance_2/f14.mat similarity index 100% rename from matlab/result/design/instance_2/f14.mat rename to draw/datas/reference_results/design/instance_2/f14.mat diff --git a/matlab/result/design/instance_2/f15.mat b/draw/datas/reference_results/design/instance_2/f15.mat similarity index 100% rename from matlab/result/design/instance_2/f15.mat rename to draw/datas/reference_results/design/instance_2/f15.mat diff --git a/matlab/result/design/instance_2/f16.mat b/draw/datas/reference_results/design/instance_2/f16.mat similarity index 100% rename from matlab/result/design/instance_2/f16.mat rename to draw/datas/reference_results/design/instance_2/f16.mat diff --git a/matlab/result/design/instance_2/f17.mat b/draw/datas/reference_results/design/instance_2/f17.mat similarity index 100% rename from matlab/result/design/instance_2/f17.mat rename to draw/datas/reference_results/design/instance_2/f17.mat diff --git a/matlab/result/design/instance_2/f18.mat b/draw/datas/reference_results/design/instance_2/f18.mat similarity index 100% rename from matlab/result/design/instance_2/f18.mat rename to draw/datas/reference_results/design/instance_2/f18.mat diff --git a/matlab/result/design/instance_2/f19.mat b/draw/datas/reference_results/design/instance_2/f19.mat similarity index 100% rename from matlab/result/design/instance_2/f19.mat rename to draw/datas/reference_results/design/instance_2/f19.mat diff --git a/matlab/result/design/instance_2/f2.mat b/draw/datas/reference_results/design/instance_2/f2.mat similarity index 100% rename from matlab/result/design/instance_2/f2.mat rename to draw/datas/reference_results/design/instance_2/f2.mat diff --git a/matlab/result/design/instance_2/f20.mat b/draw/datas/reference_results/design/instance_2/f20.mat similarity index 100% rename from matlab/result/design/instance_2/f20.mat rename to draw/datas/reference_results/design/instance_2/f20.mat diff --git a/matlab/result/design/instance_2/f21.mat b/draw/datas/reference_results/design/instance_2/f21.mat similarity index 100% rename from matlab/result/design/instance_2/f21.mat rename to draw/datas/reference_results/design/instance_2/f21.mat diff --git a/matlab/result/design/instance_2/f22.mat b/draw/datas/reference_results/design/instance_2/f22.mat similarity index 100% rename from matlab/result/design/instance_2/f22.mat rename to draw/datas/reference_results/design/instance_2/f22.mat diff --git a/matlab/result/design/instance_2/f23.mat b/draw/datas/reference_results/design/instance_2/f23.mat similarity index 100% rename from matlab/result/design/instance_2/f23.mat rename to draw/datas/reference_results/design/instance_2/f23.mat diff --git a/matlab/result/design/instance_2/f3.mat b/draw/datas/reference_results/design/instance_2/f3.mat similarity index 100% rename from matlab/result/design/instance_2/f3.mat rename to draw/datas/reference_results/design/instance_2/f3.mat diff --git a/matlab/result/design/instance_2/f4.mat b/draw/datas/reference_results/design/instance_2/f4.mat similarity index 100% rename from matlab/result/design/instance_2/f4.mat rename to draw/datas/reference_results/design/instance_2/f4.mat diff --git a/matlab/result/design/instance_2/f5.mat b/draw/datas/reference_results/design/instance_2/f5.mat similarity index 100% rename from matlab/result/design/instance_2/f5.mat rename to draw/datas/reference_results/design/instance_2/f5.mat diff --git a/matlab/result/design/instance_2/f6.mat b/draw/datas/reference_results/design/instance_2/f6.mat similarity index 100% rename from matlab/result/design/instance_2/f6.mat rename to draw/datas/reference_results/design/instance_2/f6.mat diff --git a/matlab/result/design/instance_2/f7.mat b/draw/datas/reference_results/design/instance_2/f7.mat similarity index 100% rename from matlab/result/design/instance_2/f7.mat rename to draw/datas/reference_results/design/instance_2/f7.mat diff --git a/matlab/result/design/instance_2/f8.mat b/draw/datas/reference_results/design/instance_2/f8.mat similarity index 100% rename from matlab/result/design/instance_2/f8.mat rename to draw/datas/reference_results/design/instance_2/f8.mat diff --git a/matlab/result/design/instance_2/f9.mat b/draw/datas/reference_results/design/instance_2/f9.mat similarity index 100% rename from matlab/result/design/instance_2/f9.mat rename to draw/datas/reference_results/design/instance_2/f9.mat diff --git a/matlab/result/design/instance_2/mean_var_design_data.xlsx b/draw/datas/reference_results/design/instance_2/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/design/instance_2/mean_var_design_data.xlsx rename to draw/datas/reference_results/design/instance_2/mean_var_design_data.xlsx diff --git a/matlab/result/design/instance_3/f1.mat b/draw/datas/reference_results/design/instance_3/f1.mat similarity index 100% rename from matlab/result/design/instance_3/f1.mat rename to draw/datas/reference_results/design/instance_3/f1.mat diff --git a/matlab/result/design/instance_3/f10.mat b/draw/datas/reference_results/design/instance_3/f10.mat similarity index 100% rename from matlab/result/design/instance_3/f10.mat rename to draw/datas/reference_results/design/instance_3/f10.mat diff --git a/matlab/result/design/instance_3/f11.mat b/draw/datas/reference_results/design/instance_3/f11.mat similarity index 100% rename from matlab/result/design/instance_3/f11.mat rename to draw/datas/reference_results/design/instance_3/f11.mat diff --git a/matlab/result/design/instance_3/f12.mat b/draw/datas/reference_results/design/instance_3/f12.mat similarity index 100% rename from matlab/result/design/instance_3/f12.mat rename to draw/datas/reference_results/design/instance_3/f12.mat diff --git a/matlab/result/design/instance_3/f13.mat b/draw/datas/reference_results/design/instance_3/f13.mat similarity index 100% rename from matlab/result/design/instance_3/f13.mat rename to draw/datas/reference_results/design/instance_3/f13.mat diff --git a/matlab/result/design/instance_3/f14.mat b/draw/datas/reference_results/design/instance_3/f14.mat similarity index 100% rename from matlab/result/design/instance_3/f14.mat rename to draw/datas/reference_results/design/instance_3/f14.mat diff --git a/matlab/result/design/instance_3/f15.mat b/draw/datas/reference_results/design/instance_3/f15.mat similarity index 100% rename from matlab/result/design/instance_3/f15.mat rename to draw/datas/reference_results/design/instance_3/f15.mat diff --git a/matlab/result/design/instance_3/f16.mat b/draw/datas/reference_results/design/instance_3/f16.mat similarity index 100% rename from matlab/result/design/instance_3/f16.mat rename to draw/datas/reference_results/design/instance_3/f16.mat diff --git a/matlab/result/design/instance_3/f17.mat b/draw/datas/reference_results/design/instance_3/f17.mat similarity index 100% rename from matlab/result/design/instance_3/f17.mat rename to draw/datas/reference_results/design/instance_3/f17.mat diff --git a/matlab/result/design/instance_3/f18.mat b/draw/datas/reference_results/design/instance_3/f18.mat similarity index 100% rename from matlab/result/design/instance_3/f18.mat rename to draw/datas/reference_results/design/instance_3/f18.mat diff --git a/matlab/result/design/instance_3/f19.mat b/draw/datas/reference_results/design/instance_3/f19.mat similarity index 100% rename from matlab/result/design/instance_3/f19.mat rename to draw/datas/reference_results/design/instance_3/f19.mat diff --git a/matlab/result/design/instance_3/f2.mat b/draw/datas/reference_results/design/instance_3/f2.mat similarity index 100% rename from matlab/result/design/instance_3/f2.mat rename to draw/datas/reference_results/design/instance_3/f2.mat diff --git a/matlab/result/design/instance_3/f20.mat b/draw/datas/reference_results/design/instance_3/f20.mat similarity index 100% rename from matlab/result/design/instance_3/f20.mat rename to draw/datas/reference_results/design/instance_3/f20.mat diff --git a/matlab/result/design/instance_3/f21.mat b/draw/datas/reference_results/design/instance_3/f21.mat similarity index 100% rename from matlab/result/design/instance_3/f21.mat rename to draw/datas/reference_results/design/instance_3/f21.mat diff --git a/matlab/result/design/instance_3/f22.mat b/draw/datas/reference_results/design/instance_3/f22.mat similarity index 100% rename from matlab/result/design/instance_3/f22.mat rename to draw/datas/reference_results/design/instance_3/f22.mat diff --git a/matlab/result/design/instance_3/f23.mat b/draw/datas/reference_results/design/instance_3/f23.mat similarity index 100% rename from matlab/result/design/instance_3/f23.mat rename to draw/datas/reference_results/design/instance_3/f23.mat diff --git a/matlab/result/design/instance_3/f3.mat b/draw/datas/reference_results/design/instance_3/f3.mat similarity index 100% rename from matlab/result/design/instance_3/f3.mat rename to draw/datas/reference_results/design/instance_3/f3.mat diff --git a/matlab/result/design/instance_3/f4.mat b/draw/datas/reference_results/design/instance_3/f4.mat similarity index 100% rename from matlab/result/design/instance_3/f4.mat rename to draw/datas/reference_results/design/instance_3/f4.mat diff --git a/matlab/result/design/instance_3/f5.mat b/draw/datas/reference_results/design/instance_3/f5.mat similarity index 100% rename from matlab/result/design/instance_3/f5.mat rename to draw/datas/reference_results/design/instance_3/f5.mat diff --git a/matlab/result/design/instance_3/f6.mat b/draw/datas/reference_results/design/instance_3/f6.mat similarity index 100% rename from matlab/result/design/instance_3/f6.mat rename to draw/datas/reference_results/design/instance_3/f6.mat diff --git a/matlab/result/design/instance_3/f7.mat b/draw/datas/reference_results/design/instance_3/f7.mat similarity index 100% rename from matlab/result/design/instance_3/f7.mat rename to draw/datas/reference_results/design/instance_3/f7.mat diff --git a/matlab/result/design/instance_3/f8.mat b/draw/datas/reference_results/design/instance_3/f8.mat similarity index 100% rename from matlab/result/design/instance_3/f8.mat rename to draw/datas/reference_results/design/instance_3/f8.mat diff --git a/matlab/result/design/instance_3/f9.mat b/draw/datas/reference_results/design/instance_3/f9.mat similarity index 100% rename from matlab/result/design/instance_3/f9.mat rename to draw/datas/reference_results/design/instance_3/f9.mat diff --git a/matlab/result/design/instance_3/mean_var_design_data.xlsx b/draw/datas/reference_results/design/instance_3/mean_var_design_data.xlsx similarity index 100% rename from matlab/result/design/instance_3/mean_var_design_data.xlsx rename to draw/datas/reference_results/design/instance_3/mean_var_design_data.xlsx diff --git a/matlab/result/design/instance_4/f1.mat b/draw/datas/reference_results/design/instance_4/f1.mat similarity index 100% rename from matlab/result/design/instance_4/f1.mat rename to draw/datas/reference_results/design/instance_4/f1.mat diff --git a/matlab/result/design/instance_4/f10.mat b/draw/datas/reference_results/design/instance_4/f10.mat similarity index 100% rename from matlab/result/design/instance_4/f10.mat rename to draw/datas/reference_results/design/instance_4/f10.mat diff --git a/matlab/result/design/instance_4/f11.mat b/draw/datas/reference_results/design/instance_4/f11.mat similarity index 100% rename from matlab/result/design/instance_4/f11.mat rename to draw/datas/reference_results/design/instance_4/f11.mat diff --git a/matlab/result/design/instance_4/f12.mat b/draw/datas/reference_results/design/instance_4/f12.mat similarity index 100% rename from matlab/result/design/instance_4/f12.mat rename to draw/datas/reference_results/design/instance_4/f12.mat diff --git a/matlab/result/design/instance_4/f13.mat b/draw/datas/reference_results/design/instance_4/f13.mat similarity index 100% rename from matlab/result/design/instance_4/f13.mat rename to draw/datas/reference_results/design/instance_4/f13.mat diff --git a/matlab/result/design/instance_4/f14.mat b/draw/datas/reference_results/design/instance_4/f14.mat similarity index 100% rename from matlab/result/design/instance_4/f14.mat rename to draw/datas/reference_results/design/instance_4/f14.mat diff --git a/matlab/result/design/instance_4/f15.mat b/draw/datas/reference_results/design/instance_4/f15.mat similarity index 100% rename from matlab/result/design/instance_4/f15.mat rename to draw/datas/reference_results/design/instance_4/f15.mat diff --git a/matlab/result/design/instance_4/f16.mat b/draw/datas/reference_results/design/instance_4/f16.mat similarity index 100% rename from matlab/result/design/instance_4/f16.mat rename to draw/datas/reference_results/design/instance_4/f16.mat diff --git a/matlab/result/design/instance_4/f17.mat b/draw/datas/reference_results/design/instance_4/f17.mat similarity index 100% rename from matlab/result/design/instance_4/f17.mat rename to draw/datas/reference_results/design/instance_4/f17.mat diff --git a/matlab/result/design/instance_4/f18.mat b/draw/datas/reference_results/design/instance_4/f18.mat similarity index 100% rename from matlab/result/design/instance_4/f18.mat rename to draw/datas/reference_results/design/instance_4/f18.mat diff --git a/matlab/result/design/instance_4/f19.mat b/draw/datas/reference_results/design/instance_4/f19.mat similarity index 100% rename from matlab/result/design/instance_4/f19.mat rename to draw/datas/reference_results/design/instance_4/f19.mat diff --git a/matlab/result/design/instance_4/f2.mat b/draw/datas/reference_results/design/instance_4/f2.mat similarity index 100% rename from matlab/result/design/instance_4/f2.mat rename to draw/datas/reference_results/design/instance_4/f2.mat diff --git a/matlab/result/design/instance_4/f20.mat b/draw/datas/reference_results/design/instance_4/f20.mat similarity index 100% rename from matlab/result/design/instance_4/f20.mat rename to draw/datas/reference_results/design/instance_4/f20.mat diff --git a/matlab/result/design/instance_4/f21.mat b/draw/datas/reference_results/design/instance_4/f21.mat similarity index 100% rename from matlab/result/design/instance_4/f21.mat rename to draw/datas/reference_results/design/instance_4/f21.mat diff --git a/matlab/result/design/instance_4/f22.mat b/draw/datas/reference_results/design/instance_4/f22.mat similarity index 100% rename from matlab/result/design/instance_4/f22.mat rename to draw/datas/reference_results/design/instance_4/f22.mat diff --git a/matlab/result/design/instance_4/f23.mat b/draw/datas/reference_results/design/instance_4/f23.mat similarity index 100% rename from matlab/result/design/instance_4/f23.mat rename to draw/datas/reference_results/design/instance_4/f23.mat diff --git a/matlab/result/design/instance_4/f3.mat b/draw/datas/reference_results/design/instance_4/f3.mat similarity index 100% rename from matlab/result/design/instance_4/f3.mat rename to draw/datas/reference_results/design/instance_4/f3.mat diff --git a/matlab/result/design/instance_4/f4.mat b/draw/datas/reference_results/design/instance_4/f4.mat similarity index 100% rename from matlab/result/design/instance_4/f4.mat rename to draw/datas/reference_results/design/instance_4/f4.mat diff --git a/matlab/result/design/instance_4/f5.mat b/draw/datas/reference_results/design/instance_4/f5.mat similarity index 100% rename from matlab/result/design/instance_4/f5.mat rename to draw/datas/reference_results/design/instance_4/f5.mat diff --git a/matlab/result/design/instance_4/f6.mat b/draw/datas/reference_results/design/instance_4/f6.mat similarity index 100% rename from matlab/result/design/instance_4/f6.mat rename to draw/datas/reference_results/design/instance_4/f6.mat diff --git a/matlab/result/design/instance_4/f7.mat b/draw/datas/reference_results/design/instance_4/f7.mat similarity index 100% rename from matlab/result/design/instance_4/f7.mat rename to draw/datas/reference_results/design/instance_4/f7.mat diff --git a/matlab/result/design/instance_4/f8.mat b/draw/datas/reference_results/design/instance_4/f8.mat similarity index 100% rename from matlab/result/design/instance_4/f8.mat rename to draw/datas/reference_results/design/instance_4/f8.mat diff --git a/matlab/result/design/instance_4/f9.mat b/draw/datas/reference_results/design/instance_4/f9.mat similarity index 100% rename from matlab/result/design/instance_4/f9.mat rename to draw/datas/reference_results/design/instance_4/f9.mat diff --git a/matlab/result/mean_var_design_data_total.xlsx b/draw/datas/reference_results/mean_var_design_data_total.xlsx similarity index 100% rename from matlab/result/mean_var_design_data_total.xlsx rename to draw/datas/reference_results/mean_var_design_data_total.xlsx diff --git a/matlab/result/sa_irace/sa_results.csv b/draw/datas/reference_results/sa_irace/sa_results.csv similarity index 100% rename from matlab/result/sa_irace/sa_results.csv rename to draw/datas/reference_results/sa_irace/sa_results.csv diff --git a/matlab/result/tabu_irace/instance_4/f1.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f1.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f1.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f1.pkl diff --git a/matlab/result/tabu_irace/instance_4/f10.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f10.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f10.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f10.pkl diff --git a/matlab/result/tabu_irace/instance_4/f11.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f11.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f11.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f11.pkl diff --git a/matlab/result/tabu_irace/instance_4/f12.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f12.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f12.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f12.pkl diff --git a/matlab/result/tabu_irace/instance_4/f13.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f13.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f13.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f13.pkl diff --git a/matlab/result/tabu_irace/instance_4/f14.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f14.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f14.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f14.pkl diff --git a/matlab/result/tabu_irace/instance_4/f15.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f15.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f15.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f15.pkl diff --git a/matlab/result/tabu_irace/instance_4/f16.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f16.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f16.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f16.pkl diff --git a/matlab/result/tabu_irace/instance_4/f17.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f17.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f17.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f17.pkl diff --git a/matlab/result/tabu_irace/instance_4/f18.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f18.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f18.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f18.pkl diff --git a/matlab/result/tabu_irace/instance_4/f19.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f19.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f19.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f19.pkl diff --git a/matlab/result/tabu_irace/instance_4/f2.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f2.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f2.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f2.pkl diff --git a/matlab/result/tabu_irace/instance_4/f20.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f20.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f20.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f20.pkl diff --git a/matlab/result/tabu_irace/instance_4/f21.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f21.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f21.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f21.pkl diff --git a/matlab/result/tabu_irace/instance_4/f22.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f22.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f22.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f22.pkl diff --git a/matlab/result/tabu_irace/instance_4/f23.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f23.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f23.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f23.pkl diff --git a/matlab/result/tabu_irace/instance_4/f3.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f3.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f3.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f3.pkl diff --git a/matlab/result/tabu_irace/instance_4/f4.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f4.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f4.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f4.pkl diff --git a/matlab/result/tabu_irace/instance_4/f5.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f5.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f5.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f5.pkl diff --git a/matlab/result/tabu_irace/instance_4/f6.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f6.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f6.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f6.pkl diff --git a/matlab/result/tabu_irace/instance_4/f7.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f7.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f7.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f7.pkl diff --git a/matlab/result/tabu_irace/instance_4/f8.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f8.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f8.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f8.pkl diff --git a/matlab/result/tabu_irace/instance_4/f9.pkl b/draw/datas/reference_results/tabu_irace/instance_4/f9.pkl similarity index 100% rename from matlab/result/tabu_irace/instance_4/f9.pkl rename to draw/datas/reference_results/tabu_irace/instance_4/f9.pkl diff --git a/matlab/result/tabu_irace/instance_4/result.csv b/draw/datas/reference_results/tabu_irace/instance_4/result.csv similarity index 100% rename from matlab/result/tabu_irace/instance_4/result.csv rename to draw/datas/reference_results/tabu_irace/instance_4/result.csv diff --git a/matlab/result/tabu_irace/tabu_result.csv b/draw/datas/reference_results/tabu_irace/tabu_result.csv similarity index 100% rename from matlab/result/tabu_irace/tabu_result.csv rename to draw/datas/reference_results/tabu_irace/tabu_result.csv diff --git a/draw/diff_FE.ipynb b/draw/diff_FE.ipynb index 03f78f7..8f6a801 100644 --- a/draw/diff_FE.ipynb +++ b/draw/diff_FE.ipynb @@ -160,12 +160,12 @@ "name": "stdout", "output_type": "stream", "text": [ - "result_pictures/diff_FE_fig3/F1.svg\n", - "result_pictures/diff_FE_fig3/F3.svg\n", - "result_pictures/diff_FE_fig3/F14.svg\n", - "result_pictures/diff_FE_fig3/F15.svg\n", - "result_pictures/diff_FE_fig3/F17.svg\n", - "result_pictures/diff_FE_fig3/F20.svg\n" + "paper_pictures/Supplementary_Pic/diff_FE_fig3/F1.svg\n", + "paper_pictures/Supplementary_Pic/diff_FE_fig3/F3.svg\n", + "paper_pictures/Supplementary_Pic/diff_FE_fig3/F14.svg\n", + "paper_pictures/Supplementary_Pic/diff_FE_fig3/F15.svg\n", + "paper_pictures/Supplementary_Pic/diff_FE_fig3/F17.svg\n", + "paper_pictures/Supplementary_Pic/diff_FE_fig3/F20.svg\n" ] }, { @@ -237,9 +237,9 @@ "dfs = [FE_5000, FE_3000 ,FE_10000]\n", "display_name = ['FE5000','FE3000','FE10000']\n", "problem_set = [1,3,14,15,17,20]\n", - "save_path = f'result_pictures/diff_FE_fig3/'\n", + "save_path = 'paper_pictures/Supplementary_Pic/diff_FE_fig3/'\n", "\n", - "roll_and_draw_mutil(dfs,problem_set,display_name,save_path)" + "roll_and_draw_multiple(dfs,problem_set,display_name,save_path)" ] } ], diff --git a/draw/single_probelm.ipynb b/draw/single_probelm.ipynb index 15feb17..1cb89b8 100644 --- a/draw/single_probelm.ipynb +++ b/draw/single_probelm.ipynb @@ -1062,9 +1062,9 @@ " plt.xlabel('Episode')\n", " plt.ylabel('Performance')\n", " if show_std:\n", - " plt.savefig(f'result_pictures/single_problem_with_std\\F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')\n", + " plt.savefig(f'paper_pictures/single_problem_with_std/F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')\n", " else:\n", - " plt.savefig(f'result_pictures/single_problem\\F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')" + " plt.savefig(f'paper_pictures/single_problem/F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')" ] }, { @@ -1727,7 +1727,7 @@ " plt.xlabel('Episode')\n", " plt.ylabel('Performance')\n", "\n", - " plt.savefig(f'result_pictures/single_problem_in_continue/F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')" + " plt.savefig(f'paper_pictures/single_problem_in_continue/F{problem}.svg',dpi=300,format=\"svg\",bbox_inches = 'tight')" ] } ], diff --git a/draw/util.py b/draw/util.py index d7f2e6f..1c3d920 100644 --- a/draw/util.py +++ b/draw/util.py @@ -1,106 +1,129 @@ -import re -from collections import defaultdict -import os -from datetime import datetime +"""Shared data-loading and plotting helpers for the paper notebooks.""" + +from __future__ import annotations + +import copy import pickle +import re +from pathlib import Path + import matplotlib.pyplot as plt -import copy + def read_data(filename): - pattern = re.compile(r'\d+\.\d+|\d+') - keyword1 = 'total env-steps' - keyword2 = 'return mean' - total_step =[] - mean_var =[] - with open(filename, 'r', encoding='utf-8') as file: - for line in file: - if keyword1 in line: - numbers = pattern.findall(line) - total_step.append(int(numbers[-1])) - if keyword2 in line: - numbers = pattern.findall(line) - numbers = [float(num) for num in numbers] - mean_var.append(numbers) - - return_means = [d[-2] for d in mean_var] - return_stds = [d[-1] for d in mean_var] - return total_step,return_means,return_stds + pattern = re.compile(r"\d+\.\d+|\d+") + total_steps = [] + mean_variance = [] + with Path(filename).open("r", encoding="utf-8") as stream: + for line in stream: + if "total env-steps" in line: + total_steps.append(int(pattern.findall(line)[-1])) + if "return mean" in line: + mean_variance.append( + [float(number) for number in pattern.findall(line)] + ) + means = [values[-2] for values in mean_variance] + variances = [values[-1] for values in mean_variance] + return total_steps, means, variances -def read_data_for_transformer(filename): - pattern = re.compile(r'-?\d+\.\d+|-?\d+') - keyword = 'step :' - total_step =[] - data =[] - with open(filename, 'r', encoding='utf-8') as file: - for line in file: - if keyword in line: - line = line.split('step :')[1].split('Training')[0] - numbers = pattern.findall(line) - numbers = [float(num) for num in numbers] - data.append(numbers) +def read_data_for_transformer(filename): + pattern = re.compile(r"-?\d+\.\d+|-?\d+") + data = [] + with Path(filename).open("r", encoding="utf-8") as stream: + for line in stream: + if "step :" not in line: + continue + segment = line.split("step :", maxsplit=1)[1].split("Training", maxsplit=1)[ + 0 + ] + data.append([float(number) for number in pattern.findall(segment)]) return data -def plot_each(plt,steps,means,stds,label,show_stds = False): - plt.plot(steps, means, label=label,linewidth=2) + +def plot_each(plotter, steps, means, deviations, label, show_stds=False): + plotter.plot(steps, means, label=label, linewidth=2) if show_stds: - plt.fill_between(steps, - [m - s for m, s in zip(means, stds)], - [m + s for m, s in zip(means, stds)], - alpha=0.2) - -def read_from_pkl(pkls): - datas = [] - for pkl in pkls: - with open(pkl, 'rb') as f: - loaded_data = pickle.load(f) - datas.append(loaded_data) - print(len(datas)) - return datas - -def roll_and_draw(df,problem_set,save_path): - - if not os.path.exists(save_path): - os.makedirs(save_path) - - _new_df = copy.deepcopy(df) - new_df = _new_df.rolling(window=5, center=False).mean() - show_std = True + plotter.fill_between( + steps, + [mean - deviation for mean, deviation in zip(means, deviations)], + [mean + deviation for mean, deviation in zip(means, deviations)], + alpha=0.2, + ) + + +def read_from_pkl(paths): + data = [] + for path in paths: + with Path(path).open("rb") as stream: + data.append(pickle.load(stream)) + return data + + +def _prepare_output(save_path): + output = Path(save_path) + output.mkdir(parents=True, exist_ok=True) + return output + + +def roll_and_draw(frame, problem_set, save_path): + output = _prepare_output(save_path) + smoothed = copy.deepcopy(frame).rolling(window=5, center=False).mean() for problem in problem_set: plt.figure(figsize=(5, 3)) - plot_each(plt, new_df['Epoch'], new_df[f'Means_{problem}'], new_df[f'Vars_{problem}'], f'problem{problem}',show_stds=show_std) - plt.title(f'F{problem}') - plt.xlabel('Episode') - plt.ylabel('Performance') - if show_std: - plt.savefig(f'{save_path}\F{problem}.svg',dpi=300,format="svg",bbox_inches = 'tight') - else: - plt.savefig(f'{save_path}\F{problem}.svg',dpi=300,format="svg",bbox_inches = 'tight') - -def roll_and_draw_mutil(dfs,problem_set,display_name,save_path): - - if not os.path.exists(save_path): - os.makedirs(save_path) - - new_dfs = [] - for df in dfs: - _new_df = copy.deepcopy(df) - new_df = _new_df.rolling(window=5, center=False).mean() - new_dfs.append(new_df) - - show_std = True + plot_each( + plt, + smoothed["Epoch"], + smoothed[f"Means_{problem}"], + smoothed[f"Vars_{problem}"], + f"problem{problem}", + show_stds=True, + ) + plt.title(f"F{problem}") + plt.xlabel("Episode") + plt.ylabel("Performance") + plt.savefig( + output / f"F{problem}.svg", + dpi=300, + format="svg", + bbox_inches="tight", + ) + + +def roll_and_draw_multiple(frames, problem_set, display_names, save_path): + output = _prepare_output(save_path) + smoothed_frames = [ + copy.deepcopy(frame).rolling(window=5, center=False).mean() for frame in frames + ] for problem in problem_set: plt.figure(figsize=(5, 3)) - for new_df,_display_name in zip(new_dfs,display_name): - plot_each(plt, new_df['Epoch'], new_df[f'Means_{problem}'], new_df[f'Vars_{problem}'], _display_name, show_stds=show_std) - plt.title(f'F{problem}') - plt.xlabel('Episode') - plt.ylabel('Performance') + for frame, display_name in zip(smoothed_frames, display_names): + plot_each( + plt, + frame["Epoch"], + frame[f"Means_{problem}"], + frame[f"Vars_{problem}"], + display_name, + show_stds=True, + ) + plt.title(f"F{problem}") + plt.xlabel("Episode") + plt.ylabel("Performance") plt.legend() - path = f'{save_path}F{problem}.svg' - print(path) - if show_std: - plt.savefig(f'{save_path}F{problem}.svg',dpi=300,format="svg",bbox_inches = 'tight') - else: - plt.savefig(f'{save_path}F{problem}.svg',dpi=300,format="svg",bbox_inches = 'tight') \ No newline at end of file + plt.savefig( + output / f"F{problem}.svg", + dpi=300, + format="svg", + bbox_inches="tight", + ) + + +__all__ = [ + "plot_each", + "read_data", + "read_data_for_transformer", + "read_from_pkl", + "roll_and_draw", + "roll_and_draw_multiple", +] diff --git a/matlab/AutoOpt.m b/matlab/AutoOpt.m deleted file mode 100644 index 3b97fc0..0000000 --- a/matlab/AutoOpt.m +++ /dev/null @@ -1,146 +0,0 @@ -function AutoOpt(varargin) -% --------------------------Introduction----------------------------------- -% AutoOptLib is a MATLAB library for automatically designing metaheuristic -% optimization algorithms. - -% AutoOptLib is developed and actively maintained by the Swarm Intelligence -% Lab at the Department of Computer Science and Engineering, Southern -% University of Science and Technology. -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% AutoOptLib is distributed in the hope that it will be useful, but WITHOUT -% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -% FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for -% more details. You should have received a copy of the GNU General Public -% License along with this library. If not, see . - -% Please read the documentation at for a -% step-by-step user guidance. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } - -% For any question, comment or suggestion, please contact Dr. Qi Zhao at -% . -% ----------------------------Settings------------------------------------- -% Settings of the targeted problem: -% Problem : problem name -% InstanceTrain: indexes of training instances -% InstanceTest : indexes of test instances -% -% Settings of the designed algorithm(s): -% Setting.Mode : design/solve, i.e., the aim is to designing algorithm or solving problem -% Setting.AlgP : number of search pathways in a designed algorithm -% Setting.AlgQ : maximum number of search operators in a search pathway -% Setting.Archive : name of the archive(s) that will be used in the designed algorithm(s) -% Setting.LSRange : range of parameter values that make the algorithm perform local search -% Setting.IncRate : minimum rate of solutions' fitness increase during 3 consecutive iterations -% Setting.InnerFE : maximum number of function evaluations for each call of local search -% -% Settings of the design process: -% Setting.AlgN : number of algorithms to be designed -% Setting.AlgRuns : number of algorithm runs on each problem instance -% Setting.ProbN : population size of the designed algorithms on the targeted problem instances -% Setting.ProbFE : number of fitness evaluations of the designed algorithms on the targeted problem instances -% Setting.Metric : quality/runtimeFE/runtimeSec/auc, i.e., metric for evaluating algorithms' performance -% Setting.Generate: search/learn, i.e., method for generating algorithms -% Setting.Evaluate: exact/approximate/intensification/racing, i.e., method for evaluating algoritm's performance -% Setting.Compare : average/statistic, i.e., method for comparing the performance of algorithms -% Setting.AlgFE : maximum number of algorithm evaluations during the design process (termination condition of the design process) -% Setting.Tmax : maximum running time measured by the number of function evaluations or wall clock time (in second) -% Setting.Thres : the lowest acceptable performance of the designed algorithms. The performance can be the solution quality -% Setting.RacingK : number of instances evaluated before the first round of racing -% Setting.Surro : number of exact performance evaluations when using surrogate -% -% Settings of solving the targeted problem: -% Setting.Alg : algorithm file name, e.g., Algs -% -% Example of running AutoOpt: -% AutoOpt() -% AutoOpt('Mode','design','Problem','CEC2005_f1','InstanceTrain',[1,2],'InstanceTest',3) -% AutoOpt('Mode','design','Problem','CEC2005_f1','InstanceTrain',[1,3],'InstanceTest',2,'AlgN',2,'AlgFE',4,'AlgRuns',1,'Compare','average') -% AutoOpt('Mode','solve','Problem','CEC2005_f1','InstanceSolve',[1,2],'AlgFile','Algs','ProbN',10,'ProbFE',100,'AlgRuns',2) -% ------------------------------------------------------------------------- - -if nargin == 0 % call the GUI - APP; -else - % get mode - if any(strcmp(varargin,'Mode')) - Setting = struct; - ind = find(strcmp(varargin,'Mode')); - Setting.Mode = varargin{ind+1}; - else - error('Please set the mode to "design" or "solve".'); - end - - % get problem - if strcmp(Setting.Mode,'design') - [prob,instanceTrain,instanceTest] = Input(varargin,Setting,'data'); - - elseif strcmp(Setting.Mode,'solve') - [prob,instanceSolve] = Input(varargin,Setting,'data'); - end - - %get problem only use run pbo problem - if any(strcmp(varargin,'problem_id')) - ind = find(strcmp(varargin,'problem_id')); - Setting.problem_id = varargin{ind+1}; - end - - % default parameters - switch Setting.Mode - case 'design' - Setting.AlgP = 1; - Setting.AlgQ = 3; - Setting.Archive = ''; - Setting.IncRate = 0.05; - Setting.ProbN = 50; - Setting.ProbFE = 5000; - Setting.InnerFE = 100; - Setting.AlgN = 100; - Setting.AlgFE = 3200; - Setting.AlgRuns = 5; - Setting.Metric = 'quality'; % quality/runtimeFE/runtimeSec/auc - Setting.Generate = 'search'; % search/learn - Setting.Evaluate = 'exact'; % exact/approximate/intensification/racing - Setting.Compare = 'average'; % average/statistic - Setting.Tmax = []; - Setting.Thres = []; - Setting.LSRange = 0.3; - Setting.RacingK = max(1,round(length(instanceTrain)*0.2)); - Setting.Surro = Setting.ProbFE*0.3; - Setting = Input(varargin,Setting,'parameter'); % replace default parameters with user-defined ones - Setting = Input(Setting,'check'); % avoid conflicting parameter settings - [algs,algTrace] = Process(prob,instanceTrain,instanceTest,Setting); - Output(algs,algTrace,instanceTrain,instanceTest,Setting); - - case 'solve' - Setting.Mode = 'solve'; - Setting.AlgFile = ''; - Setting.AlgName = 'Continuous Genetic Algorithm'; - Setting.Metric = 'quality'; - Setting.Tmax = []; - Setting.Thres = []; - Setting.ProbN = 100; - Setting.ProbFE = 50000; - Setting.AlgRuns = 31; - Setting = Input(varargin,Setting,'parameter'); - Setting = Input(Setting,'check'); - [bestSolutions,allSolutions] = Process(prob,instanceSolve,Setting); - Output(bestSolutions,allSolutions,instanceSolve,Setting); - end -end -end \ No newline at end of file diff --git a/matlab/Components/archive_best.m b/matlab/Components/archive_best.m deleted file mode 100644 index a2e9d9a..0000000 --- a/matlab/Components/archive_best.m +++ /dev/null @@ -1,46 +0,0 @@ -function [output1,output2] = archive_best(varargin) -% Collect the best (in terms of fitness) solution of each iteration. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - CurrArchive = varargin{2}; - - Fitness = Solution.fits; - [~,best] = min(Fitness); - output1 = [CurrArchive,Solution(best)]; - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/archive_diversity.m b/matlab/Components/archive_diversity.m deleted file mode 100644 index ecdc689..0000000 --- a/matlab/Components/archive_diversity.m +++ /dev/null @@ -1,66 +0,0 @@ -function [output1,output2] = archive_diversity(varargin) -% Collect the N most diversified solutions found so far to an external -% archive. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - CurrArchive = varargin{2}; - Problem = varargin{3}; - - Solution = [Solution,CurrArchive]; - - % distance between each pair of solutions - if contains(Problem.type{1},'continuous') - dist = pdist2(Solution.decs,Solution.decs,'euclidean'); % n*n, n is the number of solutions - else - dist = pdist2(Solution.decs,Solution.decs,'hamming'); - end - - ind = [randi(length(Solution));zeros(Problem.N-1,1)]; - for i = 2:Problem.N - % sort the total distance between each solution and the archive solutions in descending order - [~,rank] = sort(sum(dist(ind(1:i-1),:),1),'descend'); - j = 1; - ind(i) = rank(j); % select the solution with the largest distance to the archive solutions - while ismember(ind(i),ind(1:i-1)) - j = j+1; - ind(i) = rank(j); - end - end - output1 = Solution(ind); - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/archive_statistic.m b/matlab/Components/archive_statistic.m deleted file mode 100644 index a6c5a9a..0000000 --- a/matlab/Components/archive_statistic.m +++ /dev/null @@ -1,47 +0,0 @@ -function [output1,output2] = archive_statistic(varargin) -% Collect the average and standard deviation of solution's fitness of each -% iteration. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - CurrArchive = varargin{2}; - - Fitness = Solution.fits; - output1 = [mean(Fitness),std(Fitness)]; - output1 = [CurrArchive;output1]; - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/archive_tabu.m b/matlab/Components/archive_tabu.m deleted file mode 100644 index 574e246..0000000 --- a/matlab/Components/archive_tabu.m +++ /dev/null @@ -1,45 +0,0 @@ -function [output1,output2] = archive_tabu(varargin) -% Collect N solutions to the tabu list. - -%------------------------------Reference----------------------------------- -% Glover F. Tabu search—part I[J]. ORSA Journal on computing, 1989, 1(3): -% 190-206. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - output1 = Solution; % prevent the search visiting the last N solutions. - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/choose_brainstorm.m b/matlab/Components/choose_brainstorm.m deleted file mode 100644 index b185559..0000000 --- a/matlab/Components/choose_brainstorm.m +++ /dev/null @@ -1,86 +0,0 @@ -function [output1,output2] = choose_brainstorm(varargin) -% Brain storm optimization's idea picking up for selecting solutions. - -%------------------------------Reference----------------------------------- -% Shi Y. An optimization algorithm based on brainstorming process[M]// -% Emerging Research on Swarm Intelligence and Algorithm Optimization. IGI -% Global, 2015: 1-35. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - - K = max(2,round(Para(1))); % number of clusters - gamma = Para(2); % probability of selecting cluster centers - - % clustering - if contains(Problem(1).type{1},'continuous') - ClusterInd = kmeans(Solution.decs,K,'Distance','sqeuclidean'); % clustering in continuous search space - else - error('choose_cluster is only available for continuous problems.'); - end - - Cluster = cell(K,1); - ClusterCenter = zeros(K,1); - SelRateCenter = zeros(K,1); - Objs = Solution.objs; - for i = 1:K - Cluster{i} = find(ClusterInd == i); % indexes of solutions belonging to cluster i - [~,ind] = min(Objs(Cluster{i},:)); % fittest solution - ClusterCenter(i) = Cluster{i}(ind); % record the fittest solution as cluster center - SelRateCenter(i) = length(Cluster{i})/length(Solution); % select centers according to their scales - Cluster{i}(ind) = []; % reserve solutions except for the center - end - temp = zeros(K,1); - for i = 1:K - temp(i) = SelRateCenter(i)./sum(SelRateCenter); - end - SelRateCenter = temp; - - % choose - index = randsrc(Problem(1).N,1,[ClusterCenter';SelRateCenter']); % select N cluster centers from 1:K, some of them may be the same - for i = 1:Problem(1).N % select cluster center with probability gamma, then replace the center with a random solution from the cluster - if rand <= gamma && ~isempty(Cluster{ClusterCenter==index(i)}) - ind = randi(numel(Cluster{ClusterCenter==index(i)})); - index(i) = Cluster{ClusterCenter==index(i)}(ind); - end - end - output1 = index; - - case 'parameter' - Problem = varargin{1}; - k_max = max(1,round(Problem(1).N/5)); % maximum number of clusters in brain storm optimization's idea picking up - output1 = [1,k_max;0,1]; % number of clusters and probability of selecting cluster center in BSO's exploration - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/choose_nich.m b/matlab/Components/choose_nich.m deleted file mode 100644 index 4b3bf67..0000000 --- a/matlab/Components/choose_nich.m +++ /dev/null @@ -1,158 +0,0 @@ -function [output1,output2] = choose_nich(varargin) -% Adaptive niching based on the nearest-better clustering. Crossover -% (if available) will be conducted between solutions from the same specie. - -%------------------------------Reference----------------------------------- -% Preuss M. Niching the CMA-ES via nearest-better clustering[C]// -% Proceedings of the 12th annual conference companion on Genetic and -% evolutionary computation. 2010: 1711-1718. - -% Yan B, Zhao Q, Li M, et al. Fitness landscape analysis and niching -% genetic approach for hybrid beamforming in RIS-aided communications[J]. -% Applied Soft Computing, 2022, 131: 109725. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - G = varargin{5}; - - disance = pdist2(Solution.decs,Solution.decs); % compute distance - species = mNBC(disance,1,-1,G,Problem.Gmax); % divide species - - index = []; - for i = 1:length(species) - currInd = species(i).idx; - currInd = currInd(randperm(numel(currInd))); - index = [index;currInd]; % gather all solutions' indexes - end - - if mod(length(index),2) == 1 % if the number of solutions is odd - odd = true; - index = [index;index(end)]; - else - odd = false; - end - - % crossover between solutions from the same specie - index = reshape(index,2,length(index)/2); - index = index'; - index = [index(:,1);index(:,2)]; - if odd == true - index(end) = []; - end - - output1 = index; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end - -function species = mNBC(disance,fai,min_size,g,gmax) -% matdis: the distance between each pair of the individuals -% fai: the weight in NBC -% min_size: the min size of the species -% D: the dimension ofthe problem -% g: the current generation - - % reset 'min_size' if 'min_size' is equal to -1 - if min_size == -1 - min_size = round(3+g/gmax*7); - end - - % find the nearest better neighour and the distance of each individual - NP = size(disance, 1); - nbc = zeros(NP, 3); - nbc(1, :) = [1 -1 0]; % the best individual do not have the nearest better neighbour - for i = 2:NP - nbc(i, 1) = i; - [nbc(i, 3), nbc(i, 2)] = min(disance(i, 1:i-1)); - end - - % set the follow value - follow = ones(NP, 1); - for i = NP:-1:2 - follow(nbc(i, 2)) = follow(nbc(i, 2)) + follow(i); % the subtree rooted at nearest better neighbour individual must contain all current individual's nodes - end - - % cut the edge from the longest to the shortest - meandis = fai * mean(nbc(2:NP, 3)); - seeds = 1; - - [~, sort_index] = sort(nbc(:, 3), 'descend'); - for i = 1:NP - if nbc(sort_index(i), 3) > meandis % one of the cut conditions - inf_index = sort_index(i); % the inferior individual - sup_index = nbc(sort_index(i), 2); % the superior individual - top_index = sup_index; % the root of the subtree which contains the inferior and superior individuals - while nbc(top_index, 2) ~= -1 - top_index = nbc(top_index, 2); - sup_index = [sup_index, top_index]; - end - - if follow(inf_index) >= min_size && follow(top_index) - follow(inf_index) >= min_size % the other of the cut conditions - % cut operator - nbc(inf_index, 2) = -1; - nbc(inf_index, 3) = 0; - % put the current seed into the set - seeds = [seeds; sort_index(i)]; - follow(sup_index) = follow(sup_index) - follow(inf_index); - end - end - end - - % set the root of subtree which contain the current individual - m = zeros(NP, 2); - m(1:NP, 1) = 1:NP; - for i = 1:NP - j = nbc(i, 2); - k = j; - while j ~= -1 - k =j; - j = nbc(j, 2); - end - if k == -1 - m(i, 2) = i; - else - m(i, 2) = k; - end - end - - % construct the result - species = struct(); - for i=1:length(seeds) - species(i).seed = seeds(i); - species(i).idx = m(m(:, 2) == seeds(i), 1); - species(i).len = length(species(i).idx); - end -end \ No newline at end of file diff --git a/matlab/Components/choose_roulette_wheel.m b/matlab/Components/choose_roulette_wheel.m deleted file mode 100644 index 3f45193..0000000 --- a/matlab/Components/choose_roulette_wheel.m +++ /dev/null @@ -1,56 +0,0 @@ -function [output1,output2] = choose_roulette_wheel(varargin) -% Roulette wheel selection. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Fitness = Solution.fits; - - % according to fitness rank - % S = 2; - % [~,rank] = sort(Fitness); % for single-objective only - % Prob = (2-S)/N + 2.*rank.*(S-1)./(N*(N-1)); - - % according to fitness proportation - Fitness = reshape(Fitness,1,[]); - Fitness = Fitness-min(min(Fitness),0)+1e-6; - Fitness = cumsum(1./Fitness); - prob = Fitness./max(Fitness); - index = arrayfun(@(S)find(rand<=prob,1),1:Problem.N); - output1 = index; - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/choose_tournament.m b/matlab/Components/choose_tournament.m deleted file mode 100644 index 98d6677..0000000 --- a/matlab/Components/choose_tournament.m +++ /dev/null @@ -1,51 +0,0 @@ -function [output1,output2] = choose_tournament(varargin) -% K-tournament selection. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Fitness = Solution.fits; - K = 2; - - MatchIndex = randi(size(Fitness,1),Problem.N,K); - Fitness = repmat(Fitness,1,K); - MatchFitness = Fitness(MatchIndex); - index = MatchIndex(MatchFitness == min(MatchFitness,[],2)); - index = index(1:Problem.N); - output1 = index; - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/choose_traverse.m b/matlab/Components/choose_traverse.m deleted file mode 100644 index d7c27ed..0000000 --- a/matlab/Components/choose_traverse.m +++ /dev/null @@ -1,43 +0,0 @@ -function [output1,output2] = choose_traverse(varargin) -% Select each of the cureent soutions. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Problem = varargin{2}; - index = 1:Problem.N; - output1 = index; - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_arithmetic.m b/matlab/Components/cross_arithmetic.m deleted file mode 100644 index 9d51e8f..0000000 --- a/matlab/Components/cross_arithmetic.m +++ /dev/null @@ -1,55 +0,0 @@ -function [output1,output2] = cross_arithmetic(varargin) -% Whole arithmetic crossover. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - Prob = Para; - Parent = Parent.decs; - N = size(Parent,1); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - - Offspring1 = Prob.*Parent1+(1-Prob).*Parent2; - Offspring2 = Prob.*Parent2+(1-Prob).*Parent1; - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - output1 = [0,0.3]; % range of crossover probability - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_order_n.m b/matlab/Components/cross_order_n.m deleted file mode 100644 index b544764..0000000 --- a/matlab/Components/cross_order_n.m +++ /dev/null @@ -1,80 +0,0 @@ -function [output1,output2] = cross_order_n(varargin) -% N-order crossover. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - n = round(Para); - Parent = Parent.decs; - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - Offspring1 = Parent1; - Offspring2 = Parent2; - - seed = zeros(Nhalf,n); - for i = 1:Nhalf - seed(i,:) = randperm(D,n); % the n points to be exchanged - end - - for i = 1:Nhalf - k = seed(i,:); - Temp = setdiff(Parent2(i,:),Parent1(i,k),'stable'); % variables of parent 2 that are not appeared in the selected segement (k) of parent 1 - ind = setdiff(1:D,k,'stable'); % indexes of variables of parent 2 that are not appeared in the selected segement (k) of parent 1 - Offspring1(i,ind) = Temp; - - Temp = setdiff(Parent1(i,:),Parent2(i,k),'stable'); % variables of parent 1 that are not appeared in the selected segement (k) of parent 2 - ind = setdiff(1:D,k,'stable'); % indexes of variables of parent 1 that are not appeared in the selected segement (k) of parent 2 - Offspring2(i,ind) = Temp; - end - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - % number of problem's decision variable - Problem = varargin{1}; - D = zeros(length(Problem),1); - for i = 1:length(Problem) - D(i) = size(Problem(i).bound,2); - end - D = min(D); - n_max = max(1,round(D*0.5)); % the maximum n in n-point crossover - output1 = [1,n_max]; % the n point - - case 'behavior' - output1 = {'LS','small';'GS','large'}; % small n values perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_order_two.m b/matlab/Components/cross_order_two.m deleted file mode 100644 index 37b8e6c..0000000 --- a/matlab/Components/cross_order_two.m +++ /dev/null @@ -1,67 +0,0 @@ -function [output1,output2] = cross_order_two(varargin) -% Two-order crossover. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Aux = varargin{4}; - Parent = Parent.decs; - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - Offspring1 = Parent1; - Offspring2 = Parent2; - for i = 1:Nhalf - k = randperm(D,2); - k = sort(k,'ascend'); - Temp = setdiff(Parent2(i,:),Parent1(i,k(1):k(2)),'stable'); % variables of parent 2 that are not appeared in the selected segement (k(1):k(2)) of parent 1 - ind = setdiff(1:D,k(1):k(2),'stable'); % indexes of variables of parent 2 that are not appeared in the selected segement (k(1):k(2)) of parent 1 - Offspring1(i,ind) = Temp; - - - k = randperm(D,2); - k = sort(k,'ascend'); - Temp = setdiff(Parent1(i,:),Parent2(i,k(1):k(2)),'stable'); % variables of parent 1 that are not appeared in the selected segement (k(1):k(2)) of parent 2 - ind = setdiff(1:D,k(1):k(2),'stable'); % indexes of variables of parent 1 that are not appeared in the selected segement (k(1):k(2)) of parent 2 - Offspring2(i,ind) = Temp; - end - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - % no parameter - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_point_n.m b/matlab/Components/cross_point_n.m deleted file mode 100644 index ec69120..0000000 --- a/matlab/Components/cross_point_n.m +++ /dev/null @@ -1,72 +0,0 @@ -function [output1,output2] = cross_point_n(varargin) -% Randomly select n indices and exchange the n elements in these n indices -% between a pair of solutions. Similar with the cross_uniform operator. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - Parent = Parent.decs; - n = max(round(Para),1); - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - k = zeros(Nhalf,n); - for i = 1:Nhalf - k(i,:) = randperm(D,n); % the n points to be exchanged - end - - Offspring1 = Parent1; - Offspring2 = Parent2; - Offspring1(:,k(:,n)) = Parent2(:,k(:,n)); - Offspring2(:,k(:,n)) = Parent1(:,k(:,n)); - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - % number of problem's decision variable - Problem = varargin{1}; - D = zeros(length(Problem),1); - for i = 1:length(Problem) - D(i) = size(Problem(i).bound,2); - end - D = min(D); - n_max = D; % the maximum n in n-point crossover - output1 = [1,n_max]; % the n point - - case 'behavior' - output1 = {'LS','small';'GS','large'}; % small n values perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_point_one.m b/matlab/Components/cross_point_one.m deleted file mode 100644 index 98befbc..0000000 --- a/matlab/Components/cross_point_one.m +++ /dev/null @@ -1,57 +0,0 @@ -function [output1,output2] = cross_point_one(varargin) -% One-point crossover. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Aux = varargin{4}; - - Parent = Parent.decs; - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - k = randi(D,Nhalf,1); - Offspring1 = Parent1; - Offspring2 = Parent2; - Offspring1(:,k:end) = Parent2(:,k:end); - Offspring2(:,k:end) = Parent1(:,k:end); - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_point_two.m b/matlab/Components/cross_point_two.m deleted file mode 100644 index c019ecc..0000000 --- a/matlab/Components/cross_point_two.m +++ /dev/null @@ -1,68 +0,0 @@ -function [output1,output2] = cross_point_two(varargin) -% The two point crossover operation in genetic algorithm. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Aux = varargin{4}; - - Parent = Parent.decs; - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - if D < 2 - error(['Two-point crossover is unavailable for 1-dimensional ' ... - 'problems. Please remove the two-point crossover from the ' ... - 'Design_Space.']) - end - - k = zeros(Nhalf,2); - for i = 1:Nhalf - k(i,:) = randperm(D,2); - end - k = sort(k,2); - - Offspring1 = Parent1; - Offspring2 = Parent2; - Offspring1(:,k(:,1):k(:,2)) = Parent2(:,k(:,1):k(:,2)); - Offspring2(:,k(:,1):k(:,2)) = Parent1(:,k(:,1):k(:,2)); - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_point_uniform.m b/matlab/Components/cross_point_uniform.m deleted file mode 100644 index e725fac..0000000 --- a/matlab/Components/cross_point_uniform.m +++ /dev/null @@ -1,60 +0,0 @@ -function [output1,output2] = cross_point_uniform(varargin) -% Uniform crossover. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - Prob = Para; - Parent = Parent.decs; - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - ind = rand(Nhalf,D) < Prob; - Offspring1 = Parent1; - Offspring2 = Parent2; - Offspring1(ind) = Parent2(ind); - Offspring2(ind) = Parent1(ind); - Offspring = [Offspring1;Offspring2]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - output1 = [0.05,0.5]; % crossover probability - - case 'behavior' - output1 = {'LS','small';'GS','large'}; % small probabilities perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/cross_sim_binary.m b/matlab/Components/cross_sim_binary.m deleted file mode 100644 index 91c2ec0..0000000 --- a/matlab/Components/cross_sim_binary.m +++ /dev/null @@ -1,64 +0,0 @@ -function [output1,output2] = cross_sim_binary(varargin) -% Simulated binary crossover. - -%------------------------------Reference----------------------------------- -% Deb K, Agrawal R B. Simulated binary crossover for continuous search -% space[J]. Complex systems, 1995, 9(2): 115-148. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - Parent = Parent.decs; - DisC = Para; - - [N,D] = size(Parent); - Parent1 = Parent(1:ceil(N/2),:); - Parent2 = Parent(floor(N/2)+1:end,:); - Nhalf = size(Parent1,1); - - beta = zeros(Nhalf,D); - mu = rand(Nhalf,D); - - beta(mu<=0.5) = (mu(mu<=0.5)*2).^(1/(1+DisC)); - beta(mu>0.5) = (2-mu(mu>0.5)*2).^(-1/(1+DisC)); - Offspring = [0.5*((1+beta).*Parent1+(1-beta).*Parent2); - 0.5*((1-beta).*Parent1+(1+beta).*Parent2)]; - output1 = Offspring(1:N,:); - output2 = Aux; - - case 'parameter' - output1 = [20,40]; % crossover distribution - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/para_cma.m b/matlab/Components/para_cma.m deleted file mode 100644 index d2b132e..0000000 --- a/matlab/Components/para_cma.m +++ /dev/null @@ -1,80 +0,0 @@ -function Aux = para_cma(varargin) -% Update CMA-ES's parameters. - -%------------------------------Reference----------------------------------- -% N. Hansen and A. Ostermeier, Completely derandomized selfadaptation in -% evolution strategies, Evolutionary Computation, 2001, 9(2): 159-195. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -Solution = varargin{1}; -Problem = varargin{2}; -Aux = varargin{3}; -type = varargin{4}; - -% prepare parameters -Disturb = Aux.cma_Disturb; -halfN = Aux.cma_halfN; -w = Aux.cma_w; -betterN = Aux.cma_betterN; -mean = Aux.cma_mean; -sigma = Aux.cma_sigma; -csigma = Aux.cma_csigma; -dsigma = Aux.cma_dsigma; -chiN = Aux.cma_chiN; -cc = Aux.cma_cc; -ccov = Aux.cma_ccov; -cmu = Aux.cma_cmu; -hth = Aux.cma_hth; -ps = Aux.cma_ps; -pc = Aux.cma_pc; -C = Aux.cma_C; - -% update parameters -switch type - case 'solution' - Fitness = Solution.fits; - case 'algorithm' - Fitness = Solution.avePerformAll; -end -[~,rank] = sort(Fitness,'ascend'); -Disturb = Disturb(rank,:); -DisturbW = w*Disturb(1:halfN,:); -mean = mean+sigma.*DisturbW; - -ps = (1-csigma)*ps+sqrt(csigma*(2-csigma)*betterN)*DisturbW/chol(C)'; -hs = norm(ps)/sqrt(1-(1-csigma)^(2*(Problem(1).Gmax+1))) < hth; -pc = (1-cc)*pc+hs*sqrt(cc*(2-cc)*betterN)*DisturbW; -delta = (1-hs)*cc*(2-cc); -C = (1-ccov-cmu)*C+ccov*(pc'*pc+delta*C); -for i = 1:halfN - C = C+cmu*w(i)*Disturb(i,:)'*Disturb(i,:); -end -[V,E] = eig(C); -if any(diag(E)<0) - C = V*max(E,0)/V; -end -sigma = sigma*exp(csigma/dsigma*(norm(ps)/chiN-1))^0.3; - -Aux.cma_mean = mean; -Aux.cma_ps = ps; -Aux.cma_pc = pc; -Aux.cma_C = C; -Aux.cma_sigma = sigma; -end \ No newline at end of file diff --git a/matlab/Components/para_pso.m b/matlab/Components/para_pso.m deleted file mode 100644 index 09eff18..0000000 --- a/matlab/Components/para_pso.m +++ /dev/null @@ -1,34 +0,0 @@ -function Aux = para_pso(varargin) -% Update pbest and gbest for PSO' particle fly operator. - -%------------------------------Reference----------------------------------- -% Shi Y, Eberhart R. A modified particle swarm optimizer[C]//1998 IEEE -% International Conference on Evolutionary Computation Proceedings. IEEE -% World Congress on Computational Intelligence (Cat. No. 98TH8360). IEEE, -% 1998: 69-73. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -Solution = varargin{1}; -Problem = varargin{2}; -Aux = varargin{3}; -Aux.Pbest = update_pairwise([Aux.Pbest,Solution],Problem,'execute'); -[~,best] = min(Aux.Pbest.objs); -Aux.Gbest = Aux.Pbest(best); -end \ No newline at end of file diff --git a/matlab/Components/reinit_continuous.m b/matlab/Components/reinit_continuous.m deleted file mode 100644 index 5390f23..0000000 --- a/matlab/Components/reinit_continuous.m +++ /dev/null @@ -1,49 +0,0 @@ -function [output1,output2] = reinit_continuous(varargin) -% Reinitialization for continuous problems. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Aux = varargin{4}; - - N = length(Solution); - Lower = Problem.bound(1,:); - Upper = Problem.bound(2,:); - output1 = unifrnd(repmat(Lower,N,1),repmat(Upper,N,1)); - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/reinit_discrete.m b/matlab/Components/reinit_discrete.m deleted file mode 100644 index 4bff7e8..0000000 --- a/matlab/Components/reinit_discrete.m +++ /dev/null @@ -1,50 +0,0 @@ -function [output1,output2] = reinit_discrete(varargin) -% Reinitialization for discrete problems. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Aux = varargin{4}; - - [N,D] = size(Solution.decs); - output1 = zeros(N,D); - for j = 1:D - output1(:,j) = randi([Problem.bound(1,j),Problem.bound(2,j)],N,1); - end - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/reinit_permutation.m b/matlab/Components/reinit_permutation.m deleted file mode 100644 index 46fd689..0000000 --- a/matlab/Components/reinit_permutation.m +++ /dev/null @@ -1,46 +0,0 @@ -function [output1,output2] = reinit_permutation(varargin) -% Reinitialization for permutation problems. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Aux = varargin{4}; - - [N,D] = size(Solution.decs); - [~,output1] = sort(rand(N,D),2); - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_cma.m b/matlab/Components/search_cma.m deleted file mode 100644 index 15d46c3..0000000 --- a/matlab/Components/search_cma.m +++ /dev/null @@ -1,134 +0,0 @@ -function [output1,output2] = search_cma(varargin) -% The evolution strategy with convariance matrix adaption. - -%------------------------------Reference----------------------------------- -% N. Hansen and A. Ostermeier, Completely derandomized selfadaptation in -% evolution strategies, Evolutionary Computation, 2001, 9(2): 159-195. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Problem = varargin{2}; - lower = Problem.bound(1,:); - upper = Problem.bound(2,:); - Aux = varargin{4}; - if ~isnumeric(Parent) - Parent = Parent.decs; - end - [N,D] = size(Parent); - - % initialize parameters - if ~isfield(Aux,'cma_halfN') - Aux.cma_halfN = round(N/2); - w = log(Aux.cma_halfN+0.5)-log(1:Aux.cma_halfN); - Aux.cma_w = w./sum(w); - Aux.cma_betterN = 1/sum(Aux.cma_w.^2); - - Aux.cma_csigma = (Aux.cma_betterN+2)/(D+Aux.cma_betterN+5); - Aux.cma_dsigma = Aux.cma_csigma+2*max(sqrt((Aux.cma_betterN-1)/(D+1))-1,0)+1; - Aux.cma_chiN = sqrt(D)*(1-1/(4*D)+1/(21*D^2)); - - Aux.cma_cc = (4+Aux.cma_betterN/D)/(4+D+2*Aux.cma_betterN/D); - Aux.cma_ccov = 2/((D+1.3)^2+Aux.cma_betterN); - Aux.cma_cmu = min(1-Aux.cma_ccov,2*(Aux.cma_betterN-2+1/Aux.cma_betterN)/((D+2)^2+2*Aux.cma_betterN/2)); - Aux.cma_hth = (1.4+2/(D+1))*Aux.cma_chiN; - - Aux.cma_mean = unifrnd(lower,upper); - Aux.cma_ps = zeros(1,D); - Aux.cma_pc = zeros(1,D); - Aux.cma_C = eye(D); - Aux.cma_sigma = 0.1*(upper-lower); - end - - % load parameters - C = Aux.cma_C; - mean = Aux.cma_mean; - sigma = Aux.cma_sigma; - - % search - Disturb = zeros(N,D); - for i = 1:N - Disturb(i,:) = mvnrnd(zeros(1,D),C); - end - output1 = mean+sigma.*Disturb; - Aux.cma_Disturb = Disturb; - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always performs global search - - case 'algorithm' - Parent = varargin{1}; - bound = varargin{2}; - Aux = varargin{3}; - lower = bound(1,:); - upper = bound(2,:); - [N,D] = size(Parent); - - % initialize parameters - if ~isfield(Aux,'cma_halfN') - Aux.cma_halfN = round(N/2); - w = log(Aux.cma_halfN+0.5)-log(1:Aux.cma_halfN); - Aux.cma_w = w./sum(w); - Aux.cma_betterN = 1/sum(Aux.cma_w.^2); - - Aux.cma_csigma = (Aux.cma_betterN+2)/(D+Aux.cma_betterN+5); - Aux.cma_dsigma = Aux.cma_csigma+2*max(sqrt((Aux.cma_betterN-1)/(D+1))-1,0)+1; - Aux.cma_chiN = sqrt(D)*(1-1/(4*D)+1/(21*D^2)); - - Aux.cma_cc = (4+Aux.cma_betterN/D)/(4+D+2*Aux.cma_betterN/D); - Aux.cma_ccov = 2/((D+1.3)^2+Aux.cma_betterN); - Aux.cma_cmu = min(1-Aux.cma_ccov,2*(Aux.cma_betterN-2+1/Aux.cma_betterN)/((D+2)^2+2*Aux.cma_betterN/2)); - Aux.cma_hth = (1.4+2/(D+1))*Aux.cma_chiN; - - Aux.cma_mean = unifrnd(lower,upper); - Aux.cma_ps = zeros(1,D); - Aux.cma_pc = zeros(1,D); - Aux.cma_C = eye(D); - Aux.cma_sigma = 0.1*(upper-lower); - end - - % load parameters - C = Aux.cma_C; - mean = Aux.cma_mean; - sigma = Aux.cma_sigma; - - % search - Disturb = zeros(N,D); - for i = 1:N - Disturb(i,:) = mvnrnd(zeros(1,D),C); - end - output1 = mean+sigma.*Disturb; - Aux.cma_Disturb = Disturb; - output2 = Aux; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_de_current.m b/matlab/Components/search_de_current.m deleted file mode 100644 index f0cc74f..0000000 --- a/matlab/Components/search_de_current.m +++ /dev/null @@ -1,61 +0,0 @@ -function [output1,output2] = search_de_current(varargin) -% The "current/1" differential mutation. -%------------------------------Reference----------------------------------- -% Storn R, Price K. Differential evolution-a simple and efficient heuristic -% for global optimization over continuous spaces[J]. Journal of Global -% Optimization, 1997, 11(4): 341-359. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - Parent = Parent.decs; - F = Para(1); - CR = Para(2); - - [N,D] = size(Parent); - Parent1 = Parent; - Parent2 = Parent(randperm(N),:); - Parent3 = Parent(randperm(N),:); - - ind = rand(N,D) < CR; - Offspring = Parent; - Offspring(ind) = Parent1(ind) + F*(Parent2(ind)-Parent3(ind)); - output1 = Offspring; - output2 = Aux; - - case 'parameter' - output1 = [0,1;0,1]; % F and CR - - case 'behavior' - output1 = {'LS','small','small';'GS','large','large'}; % small F and CR values perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_de_current_best.m b/matlab/Components/search_de_current_best.m deleted file mode 100644 index 3cf3b19..0000000 --- a/matlab/Components/search_de_current_best.m +++ /dev/null @@ -1,64 +0,0 @@ -function [output1,output2] = search_de_current_best(varargin) -% The "current-to-best/1" differential mutation. - -%------------------------------Reference----------------------------------- -% Storn R, Price K. Differential evolution-a simple and efficient heuristic -% for global optimization over continuous spaces[J]. Journal of Global -% Optimization, 1997, 11(4): 341-359. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - F = Para(1); - CR = Para(2); - [~,best] = min(Parent.fits); - GbestDec = Parent(best).dec; % the best solution - Parent = Parent.decs; - - [N,D] = size(Parent); - Parent1 = Parent; - Parent2 = repmat(GbestDec,N,1); - Parent3 = Parent1(randperm(N),:); - - ind = rand(N,D) < CR; - Offspring = Parent; - Offspring(ind) = Parent1(ind) + F*(Parent2(ind)-Parent3(ind)); - output1 = Offspring; - output2 = Aux; - - case 'parameter' - output1 = [0,1;0,1]; % F and CR - - case 'behavior' - output1 = {'LS','small','small';'GS','large','large'}; % small F and CR values perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_de_random.m b/matlab/Components/search_de_random.m deleted file mode 100644 index a5cebe8..0000000 --- a/matlab/Components/search_de_random.m +++ /dev/null @@ -1,62 +0,0 @@ -function [output1,output2] = search_de_random(varargin) -% The "random/1" differential mutation. - -%------------------------------Reference----------------------------------- -% Storn R, Price K. Differential evolution-a simple and efficient heuristic -% for global optimization over continuous spaces[J]. Journal of Global -% Optimization, 1997, 11(4): 341-359. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - F = Para(1); - CR = Para(2); - Parent = Parent.decs; - - [N,D] = size(Parent); - Parent1 = Parent(randperm(N),:); - Parent2 = Parent(randperm(N),:); - Parent3 = Parent(randperm(N),:); - - ind = rand(N,D) < CR; - Offspring = Parent; - Offspring(ind) = Parent1(ind) + F*(Parent2(ind)-Parent3(ind)); - output1 = Offspring; - output2 = Aux; - - case 'parameter' - output1 = [0,1;0,1]; % F and CR - - case 'behavior' - output1 = {'LS','small','small';'GS','large','large'}; % small F and CR values perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_eda.m b/matlab/Components/search_eda.m deleted file mode 100644 index cdd8138..0000000 --- a/matlab/Components/search_eda.m +++ /dev/null @@ -1,56 +0,0 @@ -function [output1,output2] = search_eda(varargin) -% The estimation of distribution. - -%------------------------------Reference----------------------------------- -% Baluja S, Caruana R. Removing the genetics from the standard genetic -% algorithm[M]//Machine Learning Proceedings 1995. Morgan Kaufmann, 1995: -% 38-46. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Aux = varargin{4}; - - Parent = Parent.decs; - [N,D] = size(Parent); - - output1 = zeros(N,D); - for i = 1:D - pd = fitdist(Parent(:,i),'normal'); % fit a normal distribution - output1(:,i) = random(pd,[N,1]); % sample for the fitted distribution - end - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always performs global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_insert.m b/matlab/Components/search_insert.m deleted file mode 100644 index 3265681..0000000 --- a/matlab/Components/search_insert.m +++ /dev/null @@ -1,61 +0,0 @@ -function [output1,output2] = search_insert(varargin) -% Randomly select two elements, then insert the second element to the -% position next (right side) to the first element. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Aux = varargin{4}; - - if ~isnumeric(Solution) - New = Solution.decs; - else - New = Solution; - end - [N,D] = size(New); - - for i = 1:N - CurrentNew = New(i,:); - k = randperm(D,2); % the two points particulated in insertion should be different - k = sort(k,'ascend'); - Temp = CurrentNew(k(2)); - CurrentNew(k(2)) = []; - New(i,:) = [CurrentNew(1:k(1)),Temp,CurrentNew(k(1)+1:end)]; - end - output1 = New; - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'LS';''}; % always perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_mu_cauchy.m b/matlab/Components/search_mu_cauchy.m deleted file mode 100644 index 7b5a275..0000000 --- a/matlab/Components/search_mu_cauchy.m +++ /dev/null @@ -1,67 +0,0 @@ -function [output1,output2] = search_mu_cauchy(varargin) -% The Cauchy mutation. -%------------------------------Reference----------------------------------- -% Yao X, Liu Y, Lin G. Evolutionary programming made faster[J]. IEEE -% Transactions on Evolutionary computation, 1999, 3(2): 82-102. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Aux = varargin{4}; - innerG = varargin{6}; - - if ~isnumeric(Parent) - Parent = Parent.decs; - end - [N,D] = size(Parent); - - % initialize eta - if innerG == 1 - Aux.cauchy_eta = rand(N,D); - end - - % search - Disturb = Aux.cauchy_eta.*trnd(1,N,D); - output1 = Parent+Disturb; - - % update eta - tau1 = 1/sqrt(2*sqrt(D)); - tau2 = 1/sqrt(2*D); - normal = repmat(randn(N,1),1,D); - normal_j = randn(N,D); - Aux.cauchy_eta = Aux.cauchy_eta.*exp(tau2*normal+tau1*normal_j); - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always performs global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_mu_gaussian.m b/matlab/Components/search_mu_gaussian.m deleted file mode 100644 index 86e74da..0000000 --- a/matlab/Components/search_mu_gaussian.m +++ /dev/null @@ -1,69 +0,0 @@ -function [output1,output2] = search_mu_gaussian(varargin) -% The Gaussian mutation. - -%------------------------------Reference----------------------------------- -% Fogel D B. Artificial intelligence through simulated evolution[M]. -% Wiley-IEEE Press, 1998. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Aux = varargin{4}; - innerG = varargin{6}; - - if ~isnumeric(Parent) - Parent = Parent.decs; - end - [N,D] = size(Parent); - - % initialize eta - if innerG == 1 - Aux.gaussian_eta = rand(N,D); - end - - % search - Disturb = Aux.gaussian_eta.*randn(N,D); - output1 = Parent+Disturb; - - % update eta - tau1 = 1/sqrt(2*sqrt(D)); - tau2 = 1/sqrt(2*D); - normal = repmat(randn(N,1),1,D); - normal_j = randn(N,D); - Aux.gaussian_eta = Aux.gaussian_eta.*exp(tau2*normal+tau1*normal_j); - output2 = Aux; - - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always performs global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_mu_polynomial.m b/matlab/Components/search_mu_polynomial.m deleted file mode 100644 index ca44697..0000000 --- a/matlab/Components/search_mu_polynomial.m +++ /dev/null @@ -1,90 +0,0 @@ -function [output1,output2] = search_mu_polynomial(varargin) -% The polynomial mutation. - -%------------------------------Reference----------------------------------- -% Deb K, Goyal M. A combined genetic adaptive search (GeneAS) for -% engineering design[J]. Computer Science and Informatics, 1996, 26: 30-45. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - Aux = varargin{4}; - ProbM = Para(1); - DisM = Para(2); - - if ~isnumeric(Parent) - Offspring = Parent.decs; - else - Offspring = Parent; - end - [N,D] = size(Offspring); - - Lower = repmat(Problem.bound(1,:),N,1); - Upper = repmat(Problem.bound(2,:),N,1); - - Site = rand(N,D) < ProbM; - mu = rand(N,D); - temp = Site & mu<=0.5; - Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*... - (1-(Offspring(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(DisM+1)).^(1/(DisM+1))-1); - temp = Site & mu>0.5; - Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*... - (1-(Upper(temp)-Offspring(temp))./(Upper(temp)-Lower(temp))).^(DisM+1)).^(1/(DisM+1))); - output1 = Offspring; - output2 = Aux; - - case 'parameter' - output1 = [0,0.3;20,40]; % mutation probability and distribution - - case 'behavior' - output1 = {'LS','small','large';'GS','large','small'}; % small probabilities and large distributions perform local search - - case 'algorithm' - Parent = varargin{1}; - bound = varargin{2}; - ProbM = 1; - DisM = 30; - Offspring = Parent; - [N,D] = size(Offspring); - - Lower = repmat(bound(1,:),N,1); - Upper = repmat(bound(2,:),N,1); - Site = rand(N,D) < ProbM; - mu = rand(N,D); - temp = Site & mu<=0.5; - Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*((2.*mu(temp)+(1-2.*mu(temp)).*... - (1-(Offspring(temp)-Lower(temp))./(Upper(temp)-Lower(temp))).^(DisM+1)).^(1/(DisM+1))-1); - temp = Site & mu>0.5; - Offspring(temp) = Offspring(temp)+(Upper(temp)-Lower(temp)).*(1-(2.*(1-mu(temp))+2.*(mu(temp)-0.5).*... - (1-(Upper(temp)-Offspring(temp))./(Upper(temp)-Lower(temp))).^(DisM+1)).^(1/(DisM+1))); - output1 = Offspring; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_mu_uniform.m b/matlab/Components/search_mu_uniform.m deleted file mode 100644 index 84af2a4..0000000 --- a/matlab/Components/search_mu_uniform.m +++ /dev/null @@ -1,59 +0,0 @@ -function [output1,output2] = search_mu_uniform(varargin) -% The uniform mutation. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Parent = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - Aux = varargin{4}; - - if ~isnumeric(Parent) - Offspring = Parent.decs; - else - Offspring = Parent; - end - Prob = Para; - [N,D] = size(Offspring); - - Lower = Problem.bound(1,:); - Upper = Problem.bound(2,:); - ind = rand(N,D) < Prob; - Temp = unifrnd(repmat(Lower,N,1),repmat(Upper,N,1)); - Offspring(ind) = Temp(ind); - output1 = Offspring; - output2 = Aux; - - case 'parameter' - output1 = [0,0.3]; % mutation probability - case 'behavior' - output1 = {'LS','small';'GS','large'}; % small probabilities perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end diff --git a/matlab/Components/search_pso.m b/matlab/Components/search_pso.m deleted file mode 100644 index ff218ce..0000000 --- a/matlab/Components/search_pso.m +++ /dev/null @@ -1,72 +0,0 @@ -function [output1,output2] = search_pso(varargin) -% Particle swarm optimization's particle fly operator. - -%------------------------------Reference----------------------------------- -% Shi Y, Eberhart R. A modified particle swarm optimizer[C]//1998 IEEE -% International Conference on Evolutionary Computation Proceedings. IEEE -% World Congress on Computational Intelligence (Cat. No. 98TH8360). IEEE, -% 1998: 69-73. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Para = varargin{3}; - Aux = varargin{4}; - - [N,D] = size(Solution.decs); - W = Para; % inertia weight - - % initialize pbest, gbest, and velocity - if ~isfield(Aux,'Pbest') - Aux.Pbest = Solution; % personal best solutions - Aux.Gbest = Solution(randi(N)); % global best solution - Aux.V = zeros(N,1); - end - - % particle fly - Dec = Solution.decs; - Pbest = Aux.Pbest.decs; - Gbest = Aux.Gbest.dec; - - r1 = repmat(rand(N,1),1,D); - r2 = repmat(rand(N,1),1,D); - V = W.*Aux.V+2*r1.*(Pbest-Dec)+2*r2.*(Gbest-Dec); % N*D - output1 = Dec+V; % N*D - - % update volecity - Aux.V = V; - output2 = Aux; - - case 'parameter' - output1 = [0,0.5]; % inertia weight - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_reset_creep.m b/matlab/Components/search_reset_creep.m deleted file mode 100644 index 580dd11..0000000 --- a/matlab/Components/search_reset_creep.m +++ /dev/null @@ -1,71 +0,0 @@ -function [output1,output2] = search_reset_creep(varargin) -% Add a small value (positive or negative) to each element of solutions -% with a probability, for discrete problems with ordinal attributes. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - Aux = varargin{4}; - - Prob = Para(1); - Amp = Para(2); - Amp = max(1,round((Problem.bound(2,:)-Problem.bound(1,:)+1).*Amp)); % 1*D - if ~isnumeric(Solution) - New = Solution.decs; - else - New = Solution; - end - [N,D] = size(New); - - StepSize = zeros(N,D); - for i = 1:D - StepSize(:,i) = randi(Amp(i),N,1); % sample step size for each dimension, N*D - end - ind = rand(N,D) < 0.5; % N*D logical indices - StepSize(ind) = -StepSize(ind); - Temp = New+StepSize; - Lower = repmat(Problem.bound(1,:),N,1); - Upper = repmat(Problem.bound(2,:),N,1); - Temp = max(min(Temp,Upper),Lower); - - ind = rand(N,D) < Prob; % N*D - New(ind) = Temp(ind); - output1 = New; - output2 = Aux; - - case 'parameter' - output1 = [0,0.5;0,0.5]; % probability and amplitude - - case 'behavior' - output1 = {'LS','small','small';'GS','large','large'}; % small probabilities and amplitudes perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_reset_n.m b/matlab/Components/search_reset_n.m deleted file mode 100644 index 59dd184..0000000 --- a/matlab/Components/search_reset_n.m +++ /dev/null @@ -1,74 +0,0 @@ -function [output1,output2] = search_reset_n(varargin) -% Randomly select n elements of each solution and reset them to random -% values. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - Aux = varargin{4}; - - if ~isnumeric(Solution) - New = Solution.decs; - else - New = Solution; - end - - n = max(round(Para),1); - [N,D] = size(New); - - for i = 1:N - ind = randperm(D,n); - curr = New(i,ind); - for j = 1:n - while New(i,ind(j)) == curr(j) - New(i,ind(j)) = randi([Problem.bound(1,ind(j)),Problem.bound(2,ind(j))]); - end - end - end - output1 = New; - output2 = Aux; - - case 'parameter' - % number of problem's decision variable - Problem = varargin{1}; - D = zeros(length(Problem),1); - for i = 1:length(Problem) - D(i) = size(Problem(i).bound,2); - end - D = min(D); - n_max = D; % the maximum n - output1 = [1,n_max]; - - case 'behavior' - output1 = {'LS','small';'GS','large'}; % small n values perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_reset_one.m b/matlab/Components/search_reset_one.m deleted file mode 100644 index 12c9624..0000000 --- a/matlab/Components/search_reset_one.m +++ /dev/null @@ -1,62 +0,0 @@ -function [output1,output2] = search_reset_one(varargin) -% Randomly select an element of each solution and reset it to a random -% value. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Aux = varargin{4}; - - if ~isnumeric(Solution) - New = Solution.decs; - else - New = Solution; - end - - [N,D] = size(New); - ind = randi(D,N,1); % N*1 - - for i = 1:N - curr = New(i,ind(i)); - while New(i,ind(i)) == curr - New(i,ind(i)) = randi([Problem.bound(1,ind(i)),Problem.bound(2,ind(i))]); - end - end - output1 = New; - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'LS';''}; % always perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_reset_rand.m b/matlab/Components/search_reset_rand.m deleted file mode 100644 index a39a140..0000000 --- a/matlab/Components/search_reset_rand.m +++ /dev/null @@ -1,62 +0,0 @@ -function [output1,output2] = search_reset_rand(varargin) -% Reset each element of solutions to a random value with a probability. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - Aux = varargin{4}; - - Prob = Para; - if ~isnumeric(Solution) - New = Solution.decs; - else - New = Solution; - end - [N,D] = size(New); - - Temp = zeros(N,D); - for j = 1:D - Temp(:,j) = randi([Problem.bound(1,j),Problem.bound(2,j)],N,1); - end - - ind = rand(N,D) < Prob; % N*D - New(ind) = Temp(ind); - output1 = New; - output2 = Aux; - - case 'parameter' - output1 = [0.05,0.5]; % reset probability - - case 'behavior' - output1 = {'LS','small';'GS','large'}; % samll probabilities perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_scramble.m b/matlab/Components/search_scramble.m deleted file mode 100644 index 43363ea..0000000 --- a/matlab/Components/search_scramble.m +++ /dev/null @@ -1,63 +0,0 @@ -function [output1,output2] = search_scramble(varargin) -% Scramble all the elements between two randomly selected indices of each -% solution. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Aux = varargin{4}; - - if ~isnumeric(Solution) - New = Solution.decs; - else - New = Solution; - end - [N,D] = size(New); - - for i = 1:N - k = randperm(D,2); - k = sort(k); - n = k(2)-k(1)+1; % number of elements to be scarmbled - - Temp = New(i,k(1):k(2)); - ind = randperm(n); - Temp = Temp(ind); - New(i,k(1):k(2)) = Temp; - end - output1 = New; - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_swap.m b/matlab/Components/search_swap.m deleted file mode 100644 index 70d412f..0000000 --- a/matlab/Components/search_swap.m +++ /dev/null @@ -1,56 +0,0 @@ -function [output1,output2] = search_swap(varargin) -% Swap two randomly selected elements. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Aux = varargin{4}; - - if ~isnumeric(Solution) - Solution = Solution.decs; - end - [N,D] = size(Solution); - New = Solution; - - for i = 1:N - k = randperm(D,2); - New(i,k(1)) = Solution(i,k(2)); - New(i,k(2)) = Solution(i,k(1)); - end - output1 = New; - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'LS';''}; % always perform local search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/search_swap_multi.m b/matlab/Components/search_swap_multi.m deleted file mode 100644 index 7e40256..0000000 --- a/matlab/Components/search_swap_multi.m +++ /dev/null @@ -1,61 +0,0 @@ -function [output1,output2] = search_swap_multi(varargin) -% Swap each pair of elements between two randomly selected indices. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Aux = varargin{4}; - - if ~isnumeric(Solution) - Solution = Solution.decs; - end - [N,D] = size(Solution); - New = Solution; - - for i = 1:N - k = randperm(D,2); - k = sort(k); - n = floor((k(2)-k(1)+1)/2); % number of pairs of elements to be swapped - - for j = 1:n - New(i,k(1)+j-1) = Solution(i,k(2)-j+1); - New(i,k(2)-j+1) = Solution(i,k(1)+j-1); - end - end - output1 = New; - output2 = Aux; - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';'GS'}; % always perform global search -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/update_always.m b/matlab/Components/update_always.m deleted file mode 100644 index 2d1ef10..0000000 --- a/matlab/Components/update_always.m +++ /dev/null @@ -1,44 +0,0 @@ -function [output1,output2] = update_always(varargin) -% Always select newly generated solutions. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - - output1 = Solution(end-Problem.N+1:end); - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/update_greedy.m b/matlab/Components/update_greedy.m deleted file mode 100644 index d6327ef..0000000 --- a/matlab/Components/update_greedy.m +++ /dev/null @@ -1,45 +0,0 @@ -function [output1,output2] = update_greedy(varargin) -% Select the best (in terms of fitness) N solutions. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - - [~,ind] = sort(Solution.fits,'ascend'); - output1 = Solution(ind(1:Problem.N)); - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/update_pairwise.m b/matlab/Components/update_pairwise.m deleted file mode 100644 index 68bcc16..0000000 --- a/matlab/Components/update_pairwise.m +++ /dev/null @@ -1,53 +0,0 @@ -function [output1,output2] = update_pairwise(varargin) -% Select the better solution from each pair of old and new solutions. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - - Fitness = Solution.fits; - tempN = size(Fitness,1)/2; - Old = Fitness(1:tempN); - New = Fitness(tempN+1:end); - - compare1 = Old<=New; - compare2 = Old>New; - - ind = 1:length(Solution); - ind = ind([compare1;compare2]); - output1 = Solution(ind); - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/update_round_robin.m b/matlab/Components/update_round_robin.m deleted file mode 100644 index 8dfcc55..0000000 --- a/matlab/Components/update_round_robin.m +++ /dev/null @@ -1,53 +0,0 @@ -function [output1,output2] = update_round_robin(varargin) -% Conduct update via round-robin tournament. - -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - - Fitness = Solution.fits; - K = min(10,Problem.N-1); - ind = 1:length(Solution); - win = zeros(length(Solution),1); - for i = 1:length(Solution) - win(i) = sum(Fitness(i)<=Fitness(randperm(end,K))); - end - [~,rank] = sort(win,'descend'); - ind = ind(rank(1:Problem.N)); - output1 = Solution(ind); - - case 'parameter' - % n/a - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/Components/update_simulated_annealing.m b/matlab/Components/update_simulated_annealing.m deleted file mode 100644 index 118a543..0000000 --- a/matlab/Components/update_simulated_annealing.m +++ /dev/null @@ -1,61 +0,0 @@ -function [output1,output2] = update_simulated_annealing(varargin) -% Simulated annealing's update mechanism, i.e., accept worse soluion with a -% probability. - -%------------------------------Reference----------------------------------- -% Kirkpatrick S, Gelatt Jr C D, Vecchi M P. Optimization by simulated -% annealing[J]. Science, 1983, 220(4598): 671-680. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- -mode = varargin{end}; -switch mode - case 'execute' - Solution = varargin{1}; - Problem = varargin{2}; - Para = varargin{3}; - G = varargin{5}; - - T_initial = Para; % initial temperture - T_final = 0.01; % final temperture - Rate = nthroot(T_final/T_initial,Problem.Gmax); % temperture decrease rate - T = T_initial*Rate^G; % current temperture - - Old = Solution(1:Problem.N); - New = Solution(Problem.N+1:end); - - accept = rand(Problem.N,1) < exp((Old.fits-New.fits)./abs(Old.fits+1e-6)./T); % accept worse solutions by annealing - accept(Old.fits>New.fits) = true; % always accept better solutions - Old(accept) = New(accept); - - output1 = Old; - - case 'parameter' - output1 = [0.1,1]; % initial temperture - - case 'behavior' - output1 = {'';''}; -end - -if ~exist('output1','var') - output1 = []; -end -if ~exist('output2','var') - output2 = []; -end -end \ No newline at end of file diff --git a/matlab/IOH_Test.py b/matlab/IOH_Test.py deleted file mode 100644 index c00f5b3..0000000 --- a/matlab/IOH_Test.py +++ /dev/null @@ -1,198 +0,0 @@ -import os - -import ioh -import numpy -import numpy as np -import array - -import pandas as pd - -def test(x0): - print('go!') - x0 = np.array(x0) - # In order to instantiate a problem instance, we can do the following: - problem = ioh.get_problem( - "Sphere", - instance=1, - dimension=10, - problem_class=ioh.ProblemClass.REAL - ) - # We can access the contraint information of the problem - #x0 = np.random.uniform(problem.bounds.lb, problem.bounds.ub,[10,10]) - - - # Evaluation happens like a 'normal' objective function would - return problem(x0) - -def PBO(x0,length,problem_id): - #print("test") - #print(int(problem_id)) - # In order to instantiate a problem instance, we can do the following: - problem = ioh.get_problem( - int(problem_id), - instance=1, - dimension=int(length), - problem_class=ioh.ProblemClass.PBO - ) - - problem.enforce_bounds(how=ioh.ConstraintEnforcement.SOFT, weight=1.0, exponent=1.0) - - # We can access the contraint information of the problem - population = np.array(x0).astype(int) - #print(population) - # Evaluation happens like a 'normal' objective function would - res = problem(population) - ret = array.array('d', res) - return ret - -def tabu_pbo(x0, length, problem_id): - #print("test") - #print(int(problem_id)) - # In order to instantiate a problem instance, we can do the following: - problem = ioh.get_problem( - int(problem_id), - instance=1, - dimension=int(length), - problem_class=ioh.ProblemClass.PBO - ) - - problem.enforce_bounds(how=ioh.ConstraintEnforcement.SOFT, weight=1.0, exponent=1.0) - - # We can access the contraint information of the problem - population = np.array(x0).astype(int) - #print(population) - # Evaluation happens like a 'normal' objective function would - res = problem(population) - return res - -def BBOB(x0,length,problem_id): - #print("test") - #print(int(problem_id)) - #print(length) - # In order to instantiate a problem instance, we can do the following: - problem = ioh.get_problem( - int(problem_id), - instance=1, - dimension=int(length), - problem_class=ioh.ProblemClass.BBOB - ) - - #problem.enforce_bounds(how=ioh.ConstraintEnforcement.SOFT, weight=1.0, exponent=1.0) - - # We can access the contraint information of the problem - population = np.array(x0).astype(float) - #print(population) - # Evaluation happens like a 'normal' objective function would - res = problem(population) - #print(res) - ret = array.array('d', res) - return ret -def cosntrains(): - # We take the Shere function as example - p = ioh.get_problem("Sphere", 1, 2) - # There a several strategies that modify a constraint's behavoir: - types = ( - ioh.ConstraintEnforcement.NOT, # Don't calulate the constraint function - ioh.ConstraintEnforcement.HIDDEN, # Calulate the constraint, but don't penalize - ioh.ConstraintEnforcement.SOFT, # Calculate both constraint and objective function value y, and penalize as y + p - ioh.ConstraintEnforcement.HARD, # Calulate the constraint, if there is violation, don't calculate y, and only return p - ) - for strategy in types: - p.enforce_bounds(how=strategy, weight=1.0, exponent=1.0) - print(strategy, p([7, 7]), p.constraints.violation()) -def test(): - problem = ioh.get_problem( - 1, - instance=1, - dimension=2, - problem_class=ioh.ProblemClass.BBOB - ) - - #problem.enforce_bounds(how=ioh.ConstraintEnforcement.SOFT, weight=1.0, exponent=1.0) - - while(problem.state.optimum_found!=True): - xO = np.random.random(size=[1000,2])*10-5 - xO = [-1.63514,1.14487] - #res = BBOB(xO, 2, 1) - res = problem(xO) - print(res) - #print(problem.state.current_best) - if problem.state.optimum_found ==True: - print(res) - break -def checkoptimum(): - #path =os.getcwd() - #print(os.path.abspath(os.path.dirname(os.getcwd()))) - f = open(os.path.dirname(os.getcwd()) + '/result/bbob_optimun' + '.txt', 'a') - - for i in range(1,25): - for j in [2,5,10,20]: - problem = ioh.get_problem( - i, - instance=1, - dimension=j, - problem_class=ioh.ProblemClass.BBOB - ) - print('id ={},dim={},optimum={} \n'.format(i,j,problem.optimum)) - f.write('id ={},dim={},optimum={} \n'.format(i,j,problem.optimum)) - - f.close() - -def tabu_search(tabu_list_length,tabu_list_cycle,problem_id,dim,problem_fe): - best = np.random.randint(0,2,dim) - best_fit = tabu_pbo(best, dim, problem_id) - cur_problem_fe = 0 - tabu_list = [0] * tabu_list_length - while(cur_problem_fe<=problem_fe): - neighbors = build_neighbors(best,tabu_list) - fitness = tabu_pbo(neighbors, dim, problem_id) - if max(fitness) > best_fit: - best_fit = max(fitness) - best = neighbors[fitness.index(best_fit)] - for i in range(len(tabu_list)): - if tabu_list[i]>0: - tabu_list[i] -= 1 - tabu_list[fitness.index(max(fitness))] = tabu_list_cycle - cur_problem_fe = cur_problem_fe + len(neighbors) - print('problem{1},best fitness {0} '.format(best_fit,problem_id)) - return best_fit - -def build_neighbors(X0,tabu_list): - neighbors = [] - for i in range(X0.shape[0]): - if tabu_list[i]==0: - X_temp = X0.copy() - X_temp[i] = int(not(X_temp[i])) - neighbors.append(X_temp) - return neighbors -# xO = np.random.randint(0,2,64) -# length = 64 -# PBO(xO,length,2) -#test() -#checkoptimum() -def run_tabu(): - res = np.zeros((30, 23)) - for j in range(30): - for i in range(1,24): - res[j,i-1] = tabu_search(625,3,i,625,50000) - - column_means = np.mean(res, axis=0) - - # 计算每行的方差 - column_variances = np.var(res, axis=0) - write_excel(column_means,'Tabu_mean') - write_excel(column_variances, 'Tabu_var') - print("tsa") - -def write_excel(res,shell,file_path): - res = res.reshape(1,-1) - # 将 NumPy 数组转换为 pandas 数据框架 - df = pd.DataFrame(res) - - # 打开现有的 Excel 文件 - existing_data = pd.read_excel(file_path) - - # 将新数据追加到现有数据后面 - with pd.ExcelWriter(file_path, engine='openpyxl', mode='a') as writer: - df.to_excel(writer, sheet_name=shell, index=False,header=False) -#run_tabu() \ No newline at end of file diff --git a/matlab/Main/Agent.mat b/matlab/Main/Agent.mat deleted file mode 100644 index 1731a77..0000000 Binary files a/matlab/Main/Agent.mat and /dev/null differ diff --git a/matlab/Main/CEC2005F1.m b/matlab/Main/CEC2005F1.m deleted file mode 100644 index 66a3c22..0000000 --- a/matlab/Main/CEC2005F1.m +++ /dev/null @@ -1,7 +0,0 @@ -function [outputArg1] = CEC2005F1(inputArg1) -%CEC2005F1 此处显示有关此函数的摘要 -% 此处显示详细说明 - -outputArg1 = sum(inputArg1.^2); -end - diff --git a/matlab/Main/DeterministicActor.m b/matlab/Main/DeterministicActor.m deleted file mode 100644 index d1dfce7..0000000 --- a/matlab/Main/DeterministicActor.m +++ /dev/null @@ -1,21 +0,0 @@ -actorNet =[ - featureInputLayer(15,Name="comPathIn") - selfAttentionLayer(5,15) - layerNormalizationLayer - fullyConnectedLayer(15) - reluLayer; - scalingLayer(Name="meanPathOut",Scale=ActionInfo.UpperLimit)]; - - -actorNet = dlnetwork(actorNet); -summary(actorNet) -%rlContinuousGaussianActor - -actor = rlContinuousDeterministicActor(actorNet1, ObservationInfo, ActionInfo); -actor.UseDevice = "gpu"; - -% test -result = getAction(actor,{rand(ObservationInfo.Dimension)}); -x = rand(15,1); -dlx = dlarray(x,'CB'); -result = forward(actorNet1,dlx);%} \ No newline at end of file diff --git a/matlab/Main/Gaussian.m b/matlab/Main/Gaussian.m deleted file mode 100644 index d3d7566..0000000 --- a/matlab/Main/Gaussian.m +++ /dev/null @@ -1,3 +0,0 @@ -function [y] = Gaussian(x,mu,sigma) -y = 1/(sqrt(2*pi)*sigma)*exp(-(x-mu).^2/(2*sigma^2)); -end diff --git a/matlab/Main/Positional_Encoding.m b/matlab/Main/Positional_Encoding.m deleted file mode 100644 index 0901b1a..0000000 --- a/matlab/Main/Positional_Encoding.m +++ /dev/null @@ -1,16 +0,0 @@ -function [out] = Positional_Encoding(X) -%POSITIONAL_ENCODING 此处显示有关此函数的摘要 -% 此处显示详细说明 - -length = size(X,1); - -for pos = 0:length-1 - if mod(pos,2)==1 - X(pos+1,1) = X(pos+1,1) + cos(length/(10000^((pos-1)/length))); - else - X(pos+1,1) = X(pos+1,1) + sin(length/(10000^(pos/length))); - end -end -out = X; -end - diff --git a/matlab/Main/ShowRes.m b/matlab/Main/ShowRes.m deleted file mode 100644 index 6d2e887..0000000 --- a/matlab/Main/ShowRes.m +++ /dev/null @@ -1,13 +0,0 @@ -load('20230724T151736_episode_record.mat') - -performance = [episode_record.performance]; - -reward = [episode_record.reward]; - -X = size(reward,2); - -X = 1:X; - -plot(X,performance,X,reward) - -plot(performance) \ No newline at end of file diff --git a/matlab/Main/Test.m b/matlab/Main/Test.m deleted file mode 100644 index 0d3a935..0000000 --- a/matlab/Main/Test.m +++ /dev/null @@ -1,6 +0,0 @@ -input = [1;1;1;1;1;1;1;1;1;1;1;1;1;1;1]; - -test = [1,2,3,4]; -test1 = [5,6,7]; -test2 =[test,test1]; -input = Positional_Encoding(input); \ No newline at end of file diff --git a/matlab/Main/Train.m b/matlab/Main/Train.m deleted file mode 100644 index 2c8c484..0000000 --- a/matlab/Main/Train.m +++ /dev/null @@ -1,76 +0,0 @@ -global Problem Data Setting seedTrain; - -global episode_record best_action best_p; - -global episode_ite; - -global times; - -times = datestr(now,30); - -episode_ite =0; -episode_record = struct; -best_p = 0; -rng(0); - -[Problem,Data,Setting,seedTrain] = opt_env('Mode','design','Problem','CEC2005_f1','InstanceTrain',[1,2],'InstanceTest',3); - -% get env -env = env(); - -% get net -ObservationInfo = getObservationInfo(env); -ActionInfo = getActionInfo(env); - -% bug here? 等号右侧的输出数目不足,不满足赋值要求。 -[critic,actor] = net(ObservationInfo,ActionInfo); - - -% set agent parameters -criticOptions = rlOptimizerOptions( ... - LearnRate=1e-3, ... - GradientThreshold=1); -actorOptions = rlOptimizerOptions( ... - LearnRate=2e-4, ... - GradientThreshold=1); - -agentOpts = rlPPOAgentOptions(... - SampleTime=-1,... - ActorOptimizerOptions=actorOptions,... - CriticOptimizerOptions=criticOptions,... - ExperienceHorizon=200,... - ClipFactor=0.2,... - EntropyLossWeight=0.01,... - MiniBatchSize=64,... - NumEpoch=3,... - AdvantageEstimateMethod="gae",... - GAEFactor=0.95,... - DiscountFactor=0.998); - - -agent = rlPPOAgent(actor,critic,agentOpts); - - -% Test -%getAction(agent,{rand(ObservationInfo.Dimension)}); - -% train parameters -trainOpts = rlTrainingOptions(... - MaxEpisodes=100000,... - MaxStepsPerEpisode=1,... - ScoreAveragingWindowLength=10,... - Plots="training-progress",... - StopTrainingCriteria="AverageReward",... - StopTrainingValue=10000); - -doTraining = true; - - -if doTraining - trainingStats = train(agent,env,trainOpts); - save([times ,'_Agent.mat'],'agent'); - save([times ,'_best_action.mat'],'best_action'); - save([times ,'_episode_record.mat'],'episode_record'); -else - load('Agent.mat','agent'); -end \ No newline at end of file diff --git a/matlab/Main/env.m b/matlab/Main/env.m deleted file mode 100644 index e6fcf74..0000000 --- a/matlab/Main/env.m +++ /dev/null @@ -1,17 +0,0 @@ -function [env] = env() -%ENV creat env -% 此处显示详细说明 - -ObservationInfo = rlNumericSpec([15 1]); -ObservationInfo.Name = "States"; -ObservationInfo.Description = 'done'; - -% continue 15 dim action -ActionInfo = rlNumericSpec([15 1]); -ActionInfo.Name = "Action"; -ActionInfo.LowerLimit=0; -ActionInfo.UpperLimit=1; - -env = rlFunctionEnv(ObservationInfo,ActionInfo,"myStepFunction","myResetFunction"); -end - diff --git a/matlab/Main/evaluate.m b/matlab/Main/evaluate.m deleted file mode 100644 index 51eaa57..0000000 --- a/matlab/Main/evaluate.m +++ /dev/null @@ -1,13 +0,0 @@ -load('Agent.mat','agent'); -input = [1;1;1;1;1;1;1;1;1;1;1;1;1;1;1]; -res = zeros(1,1000); -for i =1:1000 - action = getAction(agent,input); - action = action{1}; - action = sigmoid(action); - act1 = action(1:7,:); - act2 = action(9:15,:); - res(i) = sum(act1)-sum(act2); -end -plot(res) -mean(res) diff --git a/matlab/Main/myResetFunction.m b/matlab/Main/myResetFunction.m deleted file mode 100644 index b13a86e..0000000 --- a/matlab/Main/myResetFunction.m +++ /dev/null @@ -1,9 +0,0 @@ -function [InitialObservation, LoggedSignal] = myResetFunction() -% Reset function to place custom environment into a random -% initial state. - -LoggedSignal.State = [1;1;1;1;1;1;1;1;1;1;1;1;1;1;1]; -%LoggedSignal.State = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]; -InitialObservation = LoggedSignal.State; - -end diff --git a/matlab/Main/myStepFunction.m b/matlab/Main/myStepFunction.m deleted file mode 100644 index 5cad4d3..0000000 --- a/matlab/Main/myStepFunction.m +++ /dev/null @@ -1,60 +0,0 @@ -function [NextObs,Reward,IsDone,LoggedSignals] = myStepFunction(Action,LoggedSignals) - -global Problem Data Setting seedTrain; -global episode_record best_action best_p; -global episode_ite; -global times; - -episode_ite = episode_ite +1; - -Action = sigmoid(Action); -IsDone = true; - -obj = DESIGN; -Setting.Action = Action; -[performance Algs change] = obj.Get_performance(Problem,Data,Setting,seedTrain); -%performance = Get_p('Mode','design','Problem','CEC2005_f1','InstanceTrain',[1,2],'InstanceTest',3); - -baseline =0; - -if episode_ite>10 - per = [episode_record.performance]; - per = per(end-9:end); - rew =0; - for i=1:10 - rew = rew + per_to_rew(per(i)); - end - - baseline = rew/10; -end - - -Reward = per_to_rew(performance); -Reward =Reward -baseline - change*10; - - -episode_record(episode_ite).performance = performance; -episode_record(episode_ite).reward =Reward; -episode_record(episode_ite).Algs = Algs; - -per = [episode_record.performance]; -min_p = min(per); - -if performance<=min_p - episode_ite - performance - best_action = Action; - Reward = Reward*1.5; - save([times ,'_episode_record.mat'],'episode_record'); -end - - -LoggedSignals.State = [1;1;1;1;1;1;1;1;1;1;1;1;1;1;1]; -NextObs = LoggedSignals.State; - -end - -function [reward] = per_to_rew(performance) - distance = performance - (-450); - reward = ((1/distance)*450 - 1)*10; -end \ No newline at end of file diff --git a/matlab/Main/net.m b/matlab/Main/net.m deleted file mode 100644 index cabc9a7..0000000 --- a/matlab/Main/net.m +++ /dev/null @@ -1,77 +0,0 @@ -function [critic,actor] = net(ObservationInfo,ActionInfo) -%NET 此处显示有关此函数的摘要 -% 此处显示详细说明 - -% actor -% Define common input path layer -commonPath = [ - featureInputLayer(15,Name="comPathIn") - selfAttentionLayer(5,15) - layerNormalizationLayer - fullyConnectedLayer(15,'WeightsInitializer','orthogonal') - tanhLayer(Name="comPathOut");]; - -% Define mean value path -meanPath = [ - fullyConnectedLayer(15,'WeightsInitializer','orthogonal',Name="meanPathIn") - tanhLayer - fullyConnectedLayer(prod(ActionInfo.Dimension),'WeightsInitializer','orthogonal',Name="meanPathOut"); - ]; - -% Define standard deviation path -sdevPath = [ - fullyConnectedLayer(15,'WeightsInitializer','orthogonal',"Name","stdPathIn") - tanhLayer - fullyConnectedLayer(prod(ActionInfo.Dimension),'WeightsInitializer','orthogonal'); - softplusLayer(Name="stdPathOut") - ]; - -% Add layers to layerGraph object -actorNet = layerGraph(commonPath); -actorNet = addLayers(actorNet,meanPath); -actorNet = addLayers(actorNet,sdevPath); - -% Connect paths -actorNet = connectLayers(actorNet,"comPathOut","meanPathIn/in"); -actorNet = connectLayers(actorNet,"comPathOut","stdPathIn/in"); - - -actorNet = dlnetwork(actorNet); -summary(actorNet) -%plot(actorNet) - -actor = rlContinuousGaussianActor(actorNet, ObservationInfo, ActionInfo, ... - "ActionMeanOutputNames","meanPathOut",... - "ActionStandardDeviationOutputNames","stdPathOut",... - ObservationInputNames="comPathIn"); - -actor.UseDevice = "gpu"; - -%test -%x = rand(15,1); -%dlx = dlarray(x,'CB'); -%[comPathOut meanPathOut stdPathOut] = forward(actorNet,dlx,Outputs=["comPathOut" "meanPathOut" "stdPathOut"]) - - -% critic -criticNet = [ - featureInputLayer(15) - fullyConnectedLayer(50) - tanhLayer - fullyConnectedLayer(25) - tanhLayer - fullyConnectedLayer(1)]; - -criticNet = dlnetwork(criticNet); -summary(criticNet) -%plot(criticNet) - -critic = rlValueFunction(criticNet,ObservationInfo); -critic.UseDevice = "gpu"; - - -%test -%getValue(critic,{rand(ObservationInfo.Dimension)}) - -end - diff --git a/matlab/Main/opt_env.m b/matlab/Main/opt_env.m deleted file mode 100644 index 00ded0b..0000000 --- a/matlab/Main/opt_env.m +++ /dev/null @@ -1,78 +0,0 @@ -function [Problem,Data,Setting,seedTrain] = opt_env(varargin) -% Set the AutoOpt software for algorithm evaluation - -% get mode -if any(strcmp(varargin,'Mode')) - Setting = struct; - ind = find(strcmp(varargin,'Mode')); - Setting.Mode = varargin{ind+1}; -else - error('Please set the mode to "design" or "solve".'); -end - -% get problem -if strcmp(Setting.Mode,'design') - [prob,instanceTrain,instanceTest] = Input(varargin,Setting,'data'); -elseif strcmp(Setting.Mode,'solve') - [prob,~] = Input(varargin,Setting,'data'); -end - -% get problem id -if any(strcmp(varargin,'Problem_id')) - ind = find(strcmp(varargin,'Problem_id')); - Setting.Problem_id = varargin{ind+1}; -end - -if any(strcmp(varargin,'eval')) - ind = find(strcmp(varargin,'eval')); - Setting.eval = varargin{ind+1}; -end - -% default parameters -switch Setting.Mode - case 'design' - Setting.AlgP = 1; - Setting.AlgQ = 3; - Setting.Archive = ''; - Setting.IncRate = -inf; - Setting.ProbN = 50; - Setting.ProbFE = 10000; %test set 50000 train set 5000,3000,10000 - Setting.InnerFE = 200; - Setting.AlgN = 5; - Setting.AlgFE = 15000; - Setting.AlgRuns = 5; %test set 30 train set 5 - if Setting.eval== 1 - Setting.ProbFE = 50000; %test set 50000 train set 5000 - Setting.AlgRuns = 30; %test set 30 train set 5 % 1 for get convergence curve - end - Setting.Metric = 'quality'; % quality/runtimeFE/runtimeSec/auc - Setting.Generate = 'learn'; % search/learn - Setting.Evaluate = 'exact'; % exact/approximate/intensification/racing - Setting.Compare = 'average'; % average/statistic - Setting.Tmax = []; - Setting.Thres = []; - Setting.LSRange = 0.3; - Setting.RacingK = max(1,round(length(instanceTrain)*0.2)); - Setting.Surro = Setting.ProbFE*0.3; - Setting = Input(varargin,Setting,'parameter'); % replace default parameters with user-defined ones - Setting = Input(Setting,'check'); % avoid conflicting parameter settings - - %% construct training problem properties - Problem = struct('name',[],'type',[],'bound',[],'setting',{''},'N',[],'Gmax',[]); - seedTrain = randperm(numel(instanceTrain)); - seedTest = randperm(numel(instanceTest))+length(seedTrain); - instance = [instanceTrain,instanceTest]; - - for i = 1:numel(instance) - Problem(i).name = prob; - Problem(i).setting = ''; - Problem(i).N = Setting.ProbN; - Problem(i).Gmax = ceil(Setting.ProbFE/Setting.ProbN)-1; - Problem(i).problem_id = Setting.Problem_id; - end - [Problem,Data,~] = feval(str2func(Problem(1).name),Problem,instance,'construct'); % infill problems' constraints and search boundary, construct data properties - - %% design algorithms - Setting = Space(Problem,Setting); % get design space -end - diff --git a/matlab/Main/sigmoid.m b/matlab/Main/sigmoid.m deleted file mode 100644 index 1098f58..0000000 --- a/matlab/Main/sigmoid.m +++ /dev/null @@ -1,6 +0,0 @@ -function [Y] = sigmoid(X) -%SIGMOID 此处显示有关此函数的摘要 -% 此处显示详细说明 -Y = 1./(1+exp(-X)); -end - diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f1.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f1.m deleted file mode 100644 index 004a063..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f1.m +++ /dev/null @@ -1,84 +0,0 @@ -function [output1,output2,output3] = CEC2005_f1(varargin) -% The Shifted Sphere Function from the benchmark for the CEC 2005 Special -% Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('sphere_func_data'); - o = orgData.o; - Data = struct('o',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-100; - upper = zeros(1,D)+100; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -100+200*rand(1,D); - end - Data(i).o = curr_o; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - Decs = varargin{2}; - - [N,~] = size(Decs); - Decs = Decs-repmat(o,N,1); - - fit = sum(Decs.^2,2); - output1 = fit-450; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f10.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f10.m deleted file mode 100644 index 7604a79..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f10.m +++ /dev/null @@ -1,103 +0,0 @@ -function [output1,output2,output3] = CEC2005_f10(varargin) -% The Shifted Rotated Rastrigin's Function from the benchmark for the CEC -% 2005 Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('rastrigin_func_data'); - o = orgData.o; - Data = struct('o',[],'M',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-5; - upper = zeros(1,D)+5; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -5+10*rand(1,D); - end - Data(i).o = curr_o; - - if D == 2 - M = load('rastrigin_M_D2'); - M = M.M; - elseif D == 10 - M = load('rastrigin_M_D10'); - M = M.M; - elseif D == 30 - M = load('rastrigin_M_D30'); - M = M.M; - elseif D == 50 - M = load('rastrigin_M_D50'); - M = M.M; - else - M = rot_matrix(D,2); - end - Data(i).M = M; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - M = Data.M; - Decs = varargin{2}; - - [N,~] = size(Decs); - Decs = Decs-repmat(o,N,1); - Decs = Decs*M; - - fit = sum(Decs.^2-10.*cos(2.*pi.*Decs)+10,2); - output1 = fit-330; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f11.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f11.m deleted file mode 100644 index d1dbb3b..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f11.m +++ /dev/null @@ -1,120 +0,0 @@ -function [output1,output2,output3] = CEC2005_f11(varargin) -% The Shifted Rotated Weierstrass Function from the benchmark for the CEC -% 2005 Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('weierstrass_data'); - o = orgData.o; - Data = struct('o',[],'M',[],'c1',[],'c2',[],'c',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-0.5; - upper = zeros(1,D)+0.5; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -0.5+0.5*rand(1,D); - end - Data(i).o = curr_o; - - if D == 2 - M = load('weierstrass_M_D2'); - M = M.M; - elseif D == 10 - M = load('weierstrass_M_D10'); - M = M.M; - elseif D == 30 - M = load('weierstrass_M_D30'); - M = M.M; - elseif D == 50 - M = load('weierstrass_M_D50'); - M = M.M; - else - M = rot_matrix(D,5); - end - Data(i).M = M; - - a = 0.5; - b = 3; - kmax = 20; - c1 = a.^(0:kmax); - c2 = 2*pi*b.^(0:kmax); - c = -w(0.5,c1,c2); - Data(i).c1 = c1; - Data(i).c2 = c2; - Data(i).c = c; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - M = Data.M; - c1 = Data.c1; - c2 = Data.c2; - c = Data.c; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1); - Decs = Decs*M+0.5; - - fit = 0; - for i = 1:D - fit = fit+w(Decs(:,i)',c1,c2); - end - fit = fit+repmat(c*D,N,1); - output1 = fit+90; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f12.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f12.m deleted file mode 100644 index 946efac..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f12.m +++ /dev/null @@ -1,99 +0,0 @@ -function [output1,output2,output3] = CEC2005_f12(varargin) -% The Schwefel's Problem 2.13 from the benchmark for the CEC 2005 Special -% Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('schwefel_213_data'); - a = orgData.a; - b = orgData.b; - alpha = orgData.alpha; - Data = struct('a',[],'b',[],'A',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-100; - upper = zeros(1,D)+100; - Problem(i).bound = [lower;upper]; - - if length(alpha) >= D - curr_alpha = alpha(1:D); - curr_a = a(1:D,1:D); - curr_b = b(1:D,1:D); - else - curr_alpha = -3+6*rand(1,D); - curr_a = round(-100+200.*rand(D,D)); - curr_b = round(-100+200.*rand(D,D)); - end - curr_alpha = repmat(curr_alpha,D,1); - curr_A = sum(curr_a.*sin(curr_alpha)+curr_b.*cos(curr_alpha),2); - Data(i).a = curr_a; - Data(i).b = curr_b; - Data(i).A = curr_A; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - a = Data.a; - b = Data.b; - A = Data.A; - Decs = varargin{2}; - - [N,D] = size(Decs); - fit = zeros(N,1); - for i = 1:N - xx = repmat(Decs(i,:),D,1); - B = sum(a.*sin(xx)+b.*cos(xx),2); - fit(i) = sum((A-B).^2,1); - end - output1 = fit-460; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f2.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f2.m deleted file mode 100644 index 92c2aa4..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f2.m +++ /dev/null @@ -1,87 +0,0 @@ -function [output1,output2,output3] = CEC2005_f2(varargin) -% The Shifted Schwefel's Problem from the benchmark for the CEC 2005 -% Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('schwefel_102_data'); - o = orgData.o; - Data = struct('o',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-100; - upper = zeros(1,D)+100; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -100+200*rand(1,D); - end - Data(i).o = curr_o; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1); - - fit = 0; - for i = 1:D - fit = fit+sum(Decs(:,1:i),2).^2; - end - output1 = fit-450; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f3.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f3.m deleted file mode 100644 index 8419ae2..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f3.m +++ /dev/null @@ -1,108 +0,0 @@ -function [output1,output2,output3] = CEC2005_f3(varargin) -% The Shifted Rotated High Conditioned Elliptic Function 1.2 from the -% benchmark for the CEC 2005 Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('high_cond_elliptic_rot_data'); - o = orgData.o; - Data = struct('o',[],'M',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-100; - upper = zeros(1,D)+100; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -100+200*rand(1,D); - end - Data(i).o = curr_o; - - if D == 2 - M = load('elliptic_M_D2'); - M = M.M; - elseif D == 10 - M = load('elliptic_M_D10'); - M = M.M; - elseif D == 30 - M = load('elliptic_M_D30'); - M = M.M; - elseif D == 50 - M = load('elliptic_M_D50'); - M = M.M; - else - A = normrnd(0,1,D,D); - [M,~] = cGram_Schmidt(A); - end - Data(i).M = M; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - M = Data.M; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1); - Decs = Decs*M; - - a = 1e+6; - fit = 0; - for i = 1:D - fit = fit+a.^((i-1)/(D-1)).*Decs(:,i).^2; - end - output1= fit-450; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f4.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f4.m deleted file mode 100644 index 7324fe3..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f4.m +++ /dev/null @@ -1,89 +0,0 @@ -function [output1, output2, output3] = CEC2005_f4(varargin) -% The Shifted Schwefel's Problem 1.2 with Noise in Fitness from the -% benchmark for the CEC 2005 Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('schwefel_102_data'); - o = orgData.o; - Data = struct('o',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-100; - upper = zeros(1,D)+100; - Problem(i).bound = [lower;upper]; - - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -100+200*rand(1,D); - end - Data(i).o = curr_o; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1); - - fit = 0; - for i = 1:D - fit = fit+sum(Decs(:,1:i),2).^2; - end - fit = fit.*(1+0.4.*abs(normrnd(0,1,N,1))); - output1 = fit-450; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f5.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f5.m deleted file mode 100644 index cca5e02..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f5.m +++ /dev/null @@ -1,96 +0,0 @@ -function [output1, output2, output3] = CEC2005_f5(varargin) -% The Schwefel's Problem 2.6 with Global Optimum on Bounds from the -% benchmark for the CEC 2005 Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('schwefel_206_data'); - o = orgData.o; - A = orgData.A; - Data = struct('A',[],'B',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-100; - upper = zeros(1,D)+100; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - curr_A = A(1:D,1:D); - else - curr_o = -100+200*rand(1,D); - curr_A = round(-100+2*100.*rand(D,D)); - while det(curr_A) == 0 - curr_A = round(-100+2*100.*rand(D,D)); - end - end - curr_o(1:ceil(D/4)) = -100; - curr_o(max(floor(0.75*D),1):D) = 100; - curr_B = curr_A*curr_o'; - Data(i).A = curr_A; - Data(i).B = curr_B; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - A = Data.A; - B = Data.B; - Decs = varargin{2}; - [N,~] = size(Decs); - - fit = zeros(N,1); - for i = 1:N - fit(i) = max(abs(A*(Decs(i,:)')-B)); - end - output1 = fit-310; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f6.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f6.m deleted file mode 100644 index 925a71b..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f6.m +++ /dev/null @@ -1,84 +0,0 @@ -function [output1, output2, output3] = CEC2005_f6(varargin) -% The Shifted Rosenbrock's Function from the benchmark for the CEC 2005 -% Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('rosenbrock_func_data'); - o = orgData.o; - Data = struct('o',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D) - 100; - upper = zeros(1,D) + 100; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -90+180*rand(1,D); - end - Data(i).o = curr_o; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1)+1; - - fit = sum(100.*(Decs(:,1:D-1).^2-Decs(:,2:D)).^2+(Decs(:,1:D-1)-1).^2,2); - output1 = fit+390; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f7.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f7.m deleted file mode 100644 index 22d77cb..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f7.m +++ /dev/null @@ -1,108 +0,0 @@ -function [output1,output2,output3] = CEC2005_f7(varargin) -% The Shifted Rotated Griewank's Function without Bounds from the benchmark -% for the CEC 2005 Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('griewank_func_data'); - o = orgData.o; - Data = struct('o',[],'M',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D) - 600; - upper = zeros(1,D) + 600; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -600+0*rand(1,D); - end - Data(i).o = curr_o; - - if D == 2 - M = load('griewank_M_D2'); - M = M.M; - elseif D == 10 - M = load('griewank_M_D10'); - M = M.M; - elseif D == 30 - M = load('griewank_M_D30'); - M = M.M; - elseif D == 50 - M = load('griewank_M_D50'); - M = M.M; - else - M = rot_matrix(D,3); - M = M.*(1+0.3.*normrnd(0,1,D,D)); - end - Data(i).M = M; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - M = Data.M; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1); - Decs = Decs*M; - - fit = 1; - for i = 1:D - fit = fit.*cos(Decs(:,i)./sqrt(i)); - end - fit = sum(Decs.^2,2)./4000-fit+1; - output1= fit-180; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f8.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f8.m deleted file mode 100644 index 2dc8d6a..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f8.m +++ /dev/null @@ -1,106 +0,0 @@ -function [output1,output2,output3] = CEC2005_f8(varargin) -% The Shifted Rotated Ackley's Function with Global Optimum on Bounds from -% the benchmark for the CEC 2005 Special Session on Real-Parameter -% Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('ackley_func_data'); - o = orgData.o; - Data = struct('o',[],'M',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D) - 32; - upper = zeros(1,D) + 32; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -30+60*rand(1,D); - end - curr_o(2.*(1:floor(D/2))-1) = -32; - Data(i).o = curr_o; - - if D == 2 - M = load('ackley_M_D2'); - M = M.M; - elseif D == 10 - M = load('ackley_M_D10'); - M = M.M; - elseif D == 30 - M = load('ackley_M_D30'); - M = M.M; - elseif D == 50 - M = load('ackley_M_D50'); - M = M.M; - else - M = rot_matrix(D,100); - end - Data(i).M = M; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - M = Data.M; - Decs = varargin{2}; - - [N,D] = size(Decs); - Decs = Decs-repmat(o,N,1); - Decs = Decs*M; - - fit = sum(Decs.^2,2); - fit = 20-20.*exp(-0.2.*sqrt(fit./D))-exp(sum(cos(2.*pi.*Decs),2)./D)+exp(1); - output1 = fit-140; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f9.m b/matlab/Problems/CEC2005 Benchmarks/CEC2005_f9.m deleted file mode 100644 index 52d0e16..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/CEC2005_f9.m +++ /dev/null @@ -1,84 +0,0 @@ -function [output1,output2,output3] = CEC2005_f9(varargin) -% The Shifted Rastrigin's Function from the benchmark for the CEC 2005 -% Special Session on Real-Parameter Optimization. - -%------------------------------Reference----------------------------------- -% Suganthan P N, Hansen N, Liang J J, et al. Problem definitions and -% evaluation criteria for the CEC 2005 special session on real-parameter -% optimization[R]. KanGAL report, 2005. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' - type = {'continuous','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - orgData = load('rastrigin_func_data'); - o = orgData.o; - Data = struct('o',[]); - for i = 1:length(instance) - Problem(i).type = type; - - if instance(i) == 1 - D = 10; - elseif instance(i) == 2 - D = 30; - elseif instance(i) == 3 - D = 50; - else - error('Only instances 1, 2, and 3 are available.') - end - lower = zeros(1,D)-5; - upper = zeros(1,D)+5; - Problem(i).bound = [lower;upper]; - - if length(o) >= D - curr_o = o(1:D); - else - curr_o = -5+10*rand(1,D); - end - Data(i).o = curr_o; - end - output1 = Problem; - output2 = Data; - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; - o = Data.o; - Decs = varargin{2}; - ps = size(Decs,1); - - Decs = Decs-repmat(o,ps,1); - - fit = sum(Decs.^2-10.*cos(2.*pi.*Decs)+10,2); - output1 = fit-330; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/EF8F2_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/EF8F2_func_data.mat deleted file mode 100644 index 3348b60..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/EF8F2_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D10.mat deleted file mode 100644 index 1597214..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D2.mat deleted file mode 100644 index a1a9e14..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D30.mat deleted file mode 100644 index 875133b..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D50.mat deleted file mode 100644 index a5e2c19..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_func_data.mat deleted file mode 100644 index a605938..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/E_ScafferF6_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D10.mat deleted file mode 100644 index 4885b6f..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D2.mat deleted file mode 100644 index 8f39be1..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D30.mat deleted file mode 100644 index 473d707..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D50.mat deleted file mode 100644 index 4d5f6a9..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/ackley_func_data.mat deleted file mode 100644 index 4564274..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/ackley_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/cGram_Schmidt.m b/matlab/Problems/CEC2005 Benchmarks/Data/cGram_Schmidt.m deleted file mode 100644 index f7e9db0..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/Data/cGram_Schmidt.m +++ /dev/null @@ -1,16 +0,0 @@ - function [q,r] = cGram_Schmidt(A) -% Computes the QR factorization of $A$ via classical Gram Schmid - -[~,m] = size(A); -q = A; -for j = 1:m - for i = 1:j-1 - r(i,j) = q(:,j)'*q(:,i); - end - for i = 1:j-1 - q(:,j) = q(:,j)-r(i,j)*q(:,i); - end - t = norm(q(:,j),2); - q(:,j) = q(:,j)/t; - r(j,j) = t; -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D10.mat deleted file mode 100644 index 308f0f9..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D2.mat deleted file mode 100644 index 4bea55b..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D30.mat deleted file mode 100644 index b977646..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D50.mat deleted file mode 100644 index f63e234..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/elliptic_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/fbias_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/fbias_data.mat deleted file mode 100644 index a32526e..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/fbias_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/global_optima.mat b/matlab/Problems/CEC2005 Benchmarks/Data/global_optima.mat deleted file mode 100644 index 0ba8c2d..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/global_optima.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D10.mat deleted file mode 100644 index d288769..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D2.mat deleted file mode 100644 index ceb58ba..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D30.mat deleted file mode 100644 index c9aaf10..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D50.mat deleted file mode 100644 index 0950a50..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/griewank_func_data.mat deleted file mode 100644 index 72d6fb9..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/griewank_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/high_cond_elliptic_rot_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/high_cond_elliptic_rot_data.mat deleted file mode 100644 index 7ab64b3..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/high_cond_elliptic_rot_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D10.mat deleted file mode 100644 index 2efab55..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D2.mat deleted file mode 100644 index ee28b4d..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D30.mat deleted file mode 100644 index 3c086ae..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D50.mat deleted file mode 100644 index e5d67d8..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_data.mat deleted file mode 100644 index 0713d0f..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func1_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D10.mat deleted file mode 100644 index 7116e92..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D2.mat deleted file mode 100644 index 9658da8..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D30.mat deleted file mode 100644 index f0b9ec0..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D50.mat deleted file mode 100644 index 19f7602..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_data.mat deleted file mode 100644 index 44b9332..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func2_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D10.mat deleted file mode 100644 index 2ba531f..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D2.mat deleted file mode 100644 index 9a10bee..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D30.mat deleted file mode 100644 index 39703ac..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D50.mat deleted file mode 100644 index 92f62b0..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_HM_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D10.mat deleted file mode 100644 index bac8d4f..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D2.mat deleted file mode 100644 index f697c3b..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D30.mat deleted file mode 100644 index 067bd71..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D50.mat deleted file mode 100644 index 7ee34aa..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_data.mat deleted file mode 100644 index b9883a3..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func3_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D10.mat deleted file mode 100644 index 4f5743d..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D2.mat deleted file mode 100644 index 010e310..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D30.mat deleted file mode 100644 index dc68baa..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D50.mat deleted file mode 100644 index e226b14..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_data.mat deleted file mode 100644 index 14d4339..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/hybrid_func4_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D10.mat deleted file mode 100644 index f99bcb7..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D2.mat deleted file mode 100644 index cbe0462..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D30.mat deleted file mode 100644 index f09fa56..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D50.mat deleted file mode 100644 index ea65878..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_func_data.mat deleted file mode 100644 index 583fc0a..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/rastrigin_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rosenbrock_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/rosenbrock_func_data.mat deleted file mode 100644 index c591e96..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/rosenbrock_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/rot_matrix.m b/matlab/Problems/CEC2005 Benchmarks/Data/rot_matrix.m deleted file mode 100644 index 2a1e416..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/Data/rot_matrix.m +++ /dev/null @@ -1,10 +0,0 @@ -function M = rot_matrix(D,c) -A = normrnd(0,1,D,D); -P = cGram_Schmidt(A); -A = normrnd(0,1,D,D); -Q = cGram_Schmidt(A); -u = rand(1,D); -D = c.^((u-min(u))./(max(u)-min(u))); -D = diag(D); -M = P*D*Q; -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_102_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_102_data.mat deleted file mode 100644 index 80ecc6c..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_102_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_206_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_206_data.mat deleted file mode 100644 index 554f6a5..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_206_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_213_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_213_data.mat deleted file mode 100644 index 13cce27..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/schwefel_213_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/sphere_func_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/sphere_func_data.mat deleted file mode 100644 index f07418f..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/sphere_func_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/test_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/test_data.mat deleted file mode 100644 index 0f88f18..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/test_data.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/w.m b/matlab/Problems/CEC2005 Benchmarks/Data/w.m deleted file mode 100644 index 452cd4a..0000000 --- a/matlab/Problems/CEC2005 Benchmarks/Data/w.m +++ /dev/null @@ -1,5 +0,0 @@ -function y = w(x,c1,c2) -y = zeros(length(x),1); -for k = 1:length(x) - y(k) = sum(c1 .* cos(c2.*x(:,k))); -end \ No newline at end of file diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D10.mat b/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D10.mat deleted file mode 100644 index e69c0e3..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D10.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D2.mat b/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D2.mat deleted file mode 100644 index 1eea8a8..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D2.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D30.mat b/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D30.mat deleted file mode 100644 index 0b9e129..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D30.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D50.mat b/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D50.mat deleted file mode 100644 index f57bfff..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_M_D50.mat and /dev/null differ diff --git a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_data.mat b/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_data.mat deleted file mode 100644 index 75e36e9..0000000 Binary files a/matlab/Problems/CEC2005 Benchmarks/Data/weierstrass_data.mat and /dev/null differ diff --git a/matlab/Problems/Real-World/BBOB/bbob.m b/matlab/Problems/Real-World/BBOB/bbob.m deleted file mode 100644 index 867135a..0000000 --- a/matlab/Problems/Real-World/BBOB/bbob.m +++ /dev/null @@ -1,79 +0,0 @@ -function [output1,output2,output3] = bbob(varargin) -% The beanforming problem in RIS-aided communications. - -%------------------------------Reference----------------------------------- -% Yan B, Zhao Q, Li M, et al. Fitness landscape analysis and niching -% genetic approach for hybrid beamforming in RIS-aided communications[J]. -% Applied Soft Computing, 2022, 131: 109725. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' % define problem properties - Problem = varargin{1}; - instance = varargin{2}; - Data = struct('o',[]); - for i = 1:length(instance) - if instance(i) == 1 - D = 2; - elseif instance(i) == 2 - D = 5; - elseif instance(i) == 3 - D = 10; - elseif instance(i) == 4 - D = 20; - elseif instance(i) == 5 - D = 90; - else - error('Only instances 1, 2, and 3 are available.') - end - - lower = zeros(1,D)-5; - upper = zeros(1,D)+5; - - Problem(i).type = {'continuous','static','certain'}; - Problem(i).bound = [lower;upper]; - %Problem(i).problem_index = 1 - Data(i).o = Data; % do nothing but add data(i) - end - - output1 = Problem; - output2 = Data; - - case 'repair' % repair solutions - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' % evaluate solution's fitness - problem_id = varargin{3}; - Decs = varargin{2}; - [q,dim] = size(Decs); - - res = py.IOH_Test.BBOB(Decs,dim,problem_id); - res = double(res).'; - output1 = res; % matrix for saving objective function values -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Beanforming/Beanforming.mat b/matlab/Problems/Real-World/Beanforming/Beanforming.mat deleted file mode 100644 index 2170f3f..0000000 Binary files a/matlab/Problems/Real-World/Beanforming/Beanforming.mat and /dev/null differ diff --git a/matlab/Problems/Real-World/Beanforming/ULA_fun.m b/matlab/Problems/Real-World/Beanforming/ULA_fun.m deleted file mode 100644 index 69c3734..0000000 --- a/matlab/Problems/Real-World/Beanforming/ULA_fun.m +++ /dev/null @@ -1,4 +0,0 @@ -function [ h ] = ULA_fun( phi ,N) - h=exp(1j*pi*sin(phi).*(0:N-1)'); -end - diff --git a/matlab/Problems/Real-World/Beanforming/beamforming.m b/matlab/Problems/Real-World/Beanforming/beamforming.m deleted file mode 100644 index 30c0137..0000000 --- a/matlab/Problems/Real-World/Beanforming/beamforming.m +++ /dev/null @@ -1,73 +0,0 @@ -function [output1,output2,output3] = beamforming(varargin) -% The beanforming problem in RIS-aided communications. - -%------------------------------Reference----------------------------------- -% Yan B, Zhao Q, Li M, et al. Fitness landscape analysis and niching -% genetic approach for hybrid beamforming in RIS-aided communications[J]. -% Applied Soft Computing, 2022, 131: 109725. -%------------------------------Copyright----------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' % define problem properties - Problem = varargin{1}; - instance = varargin{2}; - - orgData = load('Beanforming.mat','Data'); - Data = orgData.Data((instance)); - for i = 1:length(instance) - D = size(Data(i).G,1); - phases_cnt = 2^Data(i).b-1; - lower = zeros(1,D); % 1*D, lower bound of the D-dimension decision space - upper = repmat(phases_cnt,1,D); % 1*D, upper bound of the D-dimension decision space - Problem(i).type = {'discrete','static','certain'}; - Problem(i).bound = [lower;upper]; - end - - output1 = Problem; - output2 = Data; - - case 'repair' % repair solutions - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' % evaluate solution's fitness - Data = varargin{1}; % load problem data - m = varargin{2}; % load the current solution(s) - - b = Data.b; - PT = Data.PT; - G = Data.G; - Hd = Data.Hd; - Hr = Data.Hr; - omega = Data.omega; - - sR = get_sum_rate(m,b,Hd, Hr,G,PT,omega); % calculate objective value - sR = sR'; % N*1 - - output1 = sR; % matrix for saving objective function values -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Beanforming/channel_G.m b/matlab/Problems/Real-World/Beanforming/channel_G.m deleted file mode 100644 index b006ab1..0000000 --- a/matlab/Problems/Real-World/Beanforming/channel_G.m +++ /dev/null @@ -1,4 +0,0 @@ -function G=channel_G(AP_angle,IRS_angle,G_sig,eb1,eb2,N,M) - G=eb1.*ULA_fun( IRS_angle ,N)*(ULA_fun( AP_angle ,M))'+eb2.*G_sig; -end - diff --git a/matlab/Problems/Real-World/Beanforming/channel_Hr.m b/matlab/Problems/Real-World/Beanforming/channel_Hr.m deleted file mode 100644 index a772bde..0000000 --- a/matlab/Problems/Real-World/Beanforming/channel_Hr.m +++ /dev/null @@ -1,10 +0,0 @@ -function Hr=channel_Hr(User_angle,Hr_sig,eb1,eb2,K,N) - Hr=zeros(K,N); - for k0=1:K - User_angle_k=User_angle(k0); - hr_sig=Hr_sig(k0,:); - hr=eb1.*(ULA_fun( User_angle_k ,N))'+eb2.*hr_sig; - Hr(k0,:)=hr; - end -end - diff --git a/matlab/Problems/Real-World/Beanforming/generateInstance.m b/matlab/Problems/Real-World/Beanforming/generateInstance.m deleted file mode 100644 index 74d363b..0000000 --- a/matlab/Problems/Real-World/Beanforming/generateInstance.m +++ /dev/null @@ -1,19 +0,0 @@ -function generateInstance -K = 4; -Nt = 4; -NR2 = 40:40:400; -b = 2; -SNR = 2; -PT = 10.^(SNR/10); -Data = struct; -for i = 1:numel(NR2) - [G,Hd,Hr,omega] = get_loc_pathloss_csi(K,Nt,NR2(i)); % produce the targeted problem, for b=2 - Data(i).b = b; - Data(i).PT = PT; - Data(i).G = G; - Data(i).Hd = Hd; - Data(i).Hr = Hr; - Data(i).omega = omega; -end -save('Beanforming.mat','Data'); -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Beanforming/get_loc_pathloss_csi.m b/matlab/Problems/Real-World/Beanforming/get_loc_pathloss_csi.m deleted file mode 100644 index 72789c9..0000000 --- a/matlab/Problems/Real-World/Beanforming/get_loc_pathloss_csi.m +++ /dev/null @@ -1,119 +0,0 @@ -%% -function [G, Hd, Hr, omega] = get_loc_pathloss_csi(K, Nt, NR2) -%% generate new location for the K users -Pt=zeros(K,2); -%% -Lroom=100; %Ĭ200 -Wroom=30; %Ĭ30 -k1=[1,0]; -k2=[0,1]; -R=10; -%% -for k0=1:K - r=rand(1,1)*R; - theta=rand(1,1)*2*pi; - px=r*cos(theta); - py=r*sin(theta); - pt=[Lroom,Wroom]+px*k1+py*k2; - Pt(k0,:)=pt; -end -%% -%save('user_location.mat','K','Pt','Lroom','Wroom','R'); - -plot_ind=0; -if plot_ind==1 - figure - plot(Pt(:,1),Pt(:,2),'ro'); - xlim([Lroom-R,Lroom+R]);ylim([Wroom-R,Wroom+R]); - hold on - theta=linspace(0,1,100).*2.*pi; %뾶100 - hold on - plot(Lroom+R*cos(theta),Wroom+R*sin(theta),'r.') -end - -%------------------------------------------------------------------------- -%% compute the pathloss according to the users' locations -%% -AP=[0,0]; -%% -IRS=[100,0]; -d_g=sqrt(sum(abs(AP-IRS).^2)); -L_g=path_LOS( d_g ); -%% IRS-assist link -Lu=zeros(1,K); -for k0=1:K - pt=Pt(k0,:)-IRS; - du=sqrt(sum(abs(pt).^2)); - Lu(k0)=path_LOS( du ); -end -Lu=Lu+L_g; -%% direct link -Ld=zeros(1,K); -for k0=1:K - pt=Pt(k0,:)-AP; - dk=sqrt(sum(abs(pt).^2)); - Ld(k0)=path_NLOS( dk ); -% Ld_test(k0)=path_LOS( dk ); -end -%Lu-Ld -%% -%save('user_pathloss.mat','K','Lu','Ld'); - -%------------------------------------------------------------------------- -%% Generate the channel coefficients -noise=-170+10*log10(180*1e3); %Խsum rateԽ -path_d=10.^((-noise-Ld)/10); -path_i=10.^((-noise-Lu)/10); -%% -ite=1; -%% -%% -pd=sqrt(path_d); -pd=repmat(pd.',1,Nt); -ps=sqrt(path_i); -ps=repmat(ps.',1,NR2); -%% theta_init, channel Hd -Hd_w=zeros(K,Nt,ite); - -for j0=1 - Hd=sqrt(1/2).*(randn(K,Nt)+1j.*randn(K,Nt)); - %% - Hd_w(:,:,j0)=Hd; -end -% load('CSI8(20,20)Hd_NR2_10.mat','K','NR2','Nt','Pt',... -% 'pd','ps','Hd','AP_angle','IRS_angle',... -% 'User_angle','Hd'); - -%% -eb=10; -eb2=1/(1+eb); -eb1=1-eb2; -eb1=sqrt(eb1); -eb2=sqrt(eb2); -%% channel G -AP_angle=rand(1,1); -IRS_angle=rand(1,1); -G_sig=zeros(NR2,Nt,ite); -for i0=1:ite - G_sig(:,:,i0)=sqrt(1/2).*(randn(NR2,Nt)+1j.*randn(NR2,Nt)); -end -%% channel Hr_w -User_angle=rand(1,K); -Hr_sig=zeros(K,NR2,ite); -for i0=1:ite - Hr_sig(:,:,i0)=sqrt(1/2).*(randn(K,NR2)+1j.*randn(K,NR2)); -end - -Hd=pd.*Hd_w(:,:,1); -G=channel_G(AP_angle,IRS_angle,G_sig(:,:,1),eb1,eb2,NR2,Nt); -Hr=ps.*channel_Hr(User_angle,Hr_sig(:,:,1),eb1,eb2,K,NR2); - -% Generate weights of users omega -% weight=1./((path_d)); -% omega=weight./sum(weight); -omega=ones(1, K); -%% -% save('CSI8(20,20)Hd_NR2_10.mat','K','NR2','Nt','Pt',... -% 'pd','ps','Hd','AP_angle','IRS_angle',... -% 'User_angle','Hd','Hr','G'); -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Beanforming/get_sum_rate.m b/matlab/Problems/Real-World/Beanforming/get_sum_rate.m deleted file mode 100644 index 941f46a..0000000 --- a/matlab/Problems/Real-World/Beanforming/get_sum_rate.m +++ /dev/null @@ -1,24 +0,0 @@ -function sumRs = get_sum_rate(ms,b,Hd,Hr,G,PT,omega) -[~, Nt]=size(G); -m_num=size(ms,1); -sumRs=zeros(1, m_num); -Qs = exp(1i*ms/(2^b)*2*pi); - -for mi=1:m_num - %% get hybrid CSI: F - F= Hd+Hr*diag(Qs(mi,:)')*G; - - %% get BS beamforming: VD - W=F'/(F*F'); - vk=diag(W'*W); - [vk_fill] = water_filling(PT, vk); - PKs=vk_fill./vk; - VD=W.*repmat(sqrt(PKs'),Nt,1); - - %% get sum rate - He = abs(F * VD).^2; - FV_K_others = sum(He,2) - diag(He); - R = diag(He)./( FV_K_others + 1); - sumRs(mi) = 1./sum(log(R+1).*omega'); -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Beanforming/path_LOS.m b/matlab/Problems/Real-World/Beanforming/path_LOS.m deleted file mode 100644 index c2ce8db..0000000 --- a/matlab/Problems/Real-World/Beanforming/path_LOS.m +++ /dev/null @@ -1,9 +0,0 @@ -function [ loss ] = path_LOS( d ) -% d=d/1000; -% loss=89.5 + 16.9*log10(d); -% loss=38.46 + 20*log10(d); -% loss=35.6 + 22*log10(d); %ĬϡֵԽ󣬴path lossԽ˥Խأsum rateԽС -% loss=20 + 20*log10(d); %WSR -loss=20 + 20*log10(d);%20 -end - diff --git a/matlab/Problems/Real-World/Beanforming/path_NLOS.m b/matlab/Problems/Real-World/Beanforming/path_NLOS.m deleted file mode 100644 index 21da859..0000000 --- a/matlab/Problems/Real-World/Beanforming/path_NLOS.m +++ /dev/null @@ -1,9 +0,0 @@ -function [ loss ] = path_NLOS( d ) -% d=d/1000; -% loss=147.4 +43.3*log10(d); -% loss=max(15.3 +37.6*log10(d), path_LOS( d ))+20; -% loss=max(2.7 +42.8*log10(d), path_LOS( d ))+20; -% loss=32.6 +36.7*log10(d); - loss=32.6 +36.7*log10(d); -end - diff --git a/matlab/Problems/Real-World/Beanforming/water_filling.m b/matlab/Problems/Real-World/Beanforming/water_filling.m deleted file mode 100644 index fd7c101..0000000 --- a/matlab/Problems/Real-World/Beanforming/water_filling.m +++ /dev/null @@ -1,25 +0,0 @@ -function [vk_fill] = water_filling(PT, vk) -% filling line: miu -K=numel(vk); -miu=max(vk); -if sum(miu-vk)>PT - [vkd,~]=sort(vk,'descend'); - t=1; - vka_sum=sum(miu-vk); - while vka_sum>PT && t - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' % define problem properties - Problem = varargin{1}; - instance = varargin{2}; - Data = struct('o',[]); - for i = 1:length(instance) - if instance(i) == 1 - D = 100; - elseif instance(i) == 2 - D = 225; - elseif instance(i) == 3 - D = 400; - elseif instance(i) == 4 - D = 625; - elseif instance(i) == 5 - D = 90; - else - error('Only instances 1, 2, and 3 are available.') - end - - lower = zeros(1,D); - upper = zeros(1,D)+1; - - Problem(i).type = {'discrete','static','certain'}; - Problem(i).bound = [lower;upper]; - %Problem(i).problem_index = 1 - Data(i).o = Data; % do nothing but add data(i) - end - - output1 = Problem; - output2 = Data; - - case 'repair' % repair solutions - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' % evaluate solution's fitness - problem_id = varargin{3}; - Decs = varargin{2}; - [q,dim] = size(Decs); - res = py.IOH_Test.PBO(Decs,dim,problem_id); - res = -double(res).'; - output1 = res; % matrix for saving objective function values -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Power Dispatch/DataPowerDispatch.xlsx b/matlab/Problems/Real-World/Power Dispatch/DataPowerDispatch.xlsx deleted file mode 100644 index 0c66f08..0000000 Binary files a/matlab/Problems/Real-World/Power Dispatch/DataPowerDispatch.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/Power Dispatch/PowerDispatch.m b/matlab/Problems/Real-World/Power Dispatch/PowerDispatch.m deleted file mode 100644 index 8217de3..0000000 --- a/matlab/Problems/Real-World/Power Dispatch/PowerDispatch.m +++ /dev/null @@ -1,49 +0,0 @@ -function [output1,output2,output3] = PowerDispatch(varargin) -switch varargin{end} - case 'construct' % construct problem and data - Problem = varargin{1}; - instance = varargin{2}; - - orgData = readmatrix('DataPowerDispatch.xlsx','Sheet',1); - Data = struct('orgData',[]); - - for i = 1:numel(instance) - Problem(i) = Problem(1); - Data(i).orgData = orgData; - Problem(i).bound = [orgData(:,4)';orgData(:,5)']; % bound constraint - end - - output1 = Problem(instance); - output2 = Data(instance); - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' % evaluate fitness - Data = varargin{1}.orgData; - Decs = varargin{2}; % solution set - - N = size(Decs,1); % population size - Objs = zeros(N,1); % fitness of solutions - for i = 1:N - solution = Decs(i,:); % 1*|generator| - F = zeros(1,size(Data,1)); % fuel cost of generators, 1*|generator| - for j = 1:size(Data,1) % for each generator - F(j) = Data(j,1) + Data(j,2)*solution(j) + Data(j,3)*solution(j)^2; % objective function - end - Objs(i) = sum(F); - if sum(solution) < Data(1,6) % power balance constraint - Objs(i) = 10^6; % assign an extreme large fitness value to infeasible solution - end - end - output1 = Objs; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Warehouse Management/Assign.m b/matlab/Problems/Real-World/Warehouse Management/Assign.m deleted file mode 100644 index 1a9a71f..0000000 --- a/matlab/Problems/Real-World/Warehouse Management/Assign.m +++ /dev/null @@ -1,39 +0,0 @@ -%% load data -filename = 'DataProcessed.xlsx'; -[Data,~,~] = xlsread(filename); - -%% rank products according to their future picking up frequencies, ranks are products' locations -ProdInd = unique(Data(:,1)); % all products -NumProd = length(ProdInd); % number of products -MaterInd = unique(Data(:,2)); % all materials -fr = zeros(NumProd,1); % future picking up frequency of p -for i = 1: NumProd - fr(i) = sum(Data(Data(:,1)==ProdInd(i),6)); -end -[~,loc] = sort(fr,'descend'); % locations of products, corresponding to products' indexes -temp = zeros(NumProd,1); -for i = 1:NumProd - temp(i) = find(loc==i); -end -loc = temp; - -%% assign each common material to a product, such that this common material's overall picking up distance is minimum -for i = 1:length(MaterInd) - frMater = Data(Data(:,2)==MaterInd(i),6); % future picking up frequencies of material i - if length(frMater) > 1 % if common material - ProdInd_ComMater = Data(Data(:,2)==MaterInd(i),1); % indexes of products that use the common material - dis = sum(repmat(frMater,1,NumProd) .* abs(repmat(loc(ProdInd_ComMater),1,NumProd) - repmat(loc',length(frMater),1)),1); % 1:NumProd - [~,best] = min(dis); - Data(Data(:,2)==MaterInd(i),1) = ProdInd(best); % assign a new product for the common material - end -end - -%% delete repetitive material records -for i = 1:length(MaterInd) - repMaterLine = find(Data(:,2)==MaterInd(i)); - Data(repMaterLine(2:end),:) = []; -end - -%% save data -xlswrite('DataAssigned.xlsx',Data,'Sheet1'); -xlswrite('DataAssigned.xlsx',loc,'Sheet2'); \ No newline at end of file diff --git a/matlab/Problems/Real-World/Warehouse Management/DataAssigned.xlsx b/matlab/Problems/Real-World/Warehouse Management/DataAssigned.xlsx deleted file mode 100644 index 999363e..0000000 Binary files a/matlab/Problems/Real-World/Warehouse Management/DataAssigned.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/Warehouse Management/DataClearned.xlsx b/matlab/Problems/Real-World/Warehouse Management/DataClearned.xlsx deleted file mode 100644 index 7a539e8..0000000 Binary files a/matlab/Problems/Real-World/Warehouse Management/DataClearned.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/Warehouse Management/DataOrg.xlsx b/matlab/Problems/Real-World/Warehouse Management/DataOrg.xlsx deleted file mode 100644 index e83db13..0000000 Binary files a/matlab/Problems/Real-World/Warehouse Management/DataOrg.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/Warehouse Management/DataProcessed.xlsx b/matlab/Problems/Real-World/Warehouse Management/DataProcessed.xlsx deleted file mode 100644 index 38d015c..0000000 Binary files a/matlab/Problems/Real-World/Warehouse Management/DataProcessed.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/Warehouse Management/DataStacked.mat b/matlab/Problems/Real-World/Warehouse Management/DataStacked.mat deleted file mode 100644 index dd849d8..0000000 Binary files a/matlab/Problems/Real-World/Warehouse Management/DataStacked.mat and /dev/null differ diff --git a/matlab/Problems/Real-World/Warehouse Management/Place.m b/matlab/Problems/Real-World/Warehouse Management/Place.m deleted file mode 100644 index c967d25..0000000 --- a/matlab/Problems/Real-World/Warehouse Management/Place.m +++ /dev/null @@ -1,137 +0,0 @@ -function [output1,output2,output3] = Place(varargin) -maxH = 200; -switch varargin{end} - case 'construct' % construct problem and data - type = {'permutation','sequential','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - - orgData = load('DataStacked.mat'); - Data = struct('orgData',[],'rackH',[],'maxH',[],'rackInd',[],'prodInd',[],'preSolRack',[],'preSolProd',[],'continue',[]); - - lowerH = 20; - upperH = 150; - intervalH = 10; - H = (lowerH:intervalH:upperH)'; - numH = length(H); - rackSize = [repmat(180,numH,1),repmat(60,numH,1),H;repmat(240,numH,1),repmat(120,numH,1),H;]; % sizes of all kinds of racks, [long,width,height] - rackH = rackSize(:,3); - - numInstance = size(orgData.usedRacks,2); - for i = 1:numInstance - Problem(i) = Problem(1); % a number of numProd problem instances - Problem(i).type = type; - Data(i).orgData = orgData.usedRacks(:,i); % cells, each collects indexes (can be repetitive) of all racks used for one product - Data(i).rackH = rackH; - Data(i).maxH = maxH; - Data(i).prodInd = 1; % index of the current considered product - Data(i).rackInd = Data(i).orgData{Data(i).prodInd}; % indexes of racks that the current product used - - totalH = sum(Data(i).rackH(Data(i).rackInd)); - Data(i).preSolRack = []; - Data(i).preSolProd = []; - while totalH < maxH && Data(i).prodInd < length(Data(i).orgData) - Data(i).preSolRack = [Data(i).preSolRack,Data(i).rackInd]; % a part of the solution (rack indexes) to the current problem - Data(i).preSolProd = [Data(i).preSolProd,repmat(Data(i).prodInd,1,numel(Data(i).rackInd))]; % a part of the solution (product indexes) to the current problem - Data(i).maxH = maxH-totalH; % vertical height being considered in the current problem - Data(i).prodInd = Data(i).prodInd+1; % index of the current considered product - Data(i).rackInd = Data(i).orgData{Data(i).prodInd}; - totalH = totalH+sum(Data(i).rackH(Data(i).rackInd)); - end - - Problem(i).bound = [1;numel(Data(i).rackInd)]; - - if Data(i).prodInd == length(Data(i).orgData) && totalH <= maxH - Data(i).continue = false; - else - Data(i).continue = true; - end - end - - output1 = Problem(instance); - output2 = Data(instance); - - case 'repair' - Decs = varargin{2}; - output1 = Decs; - - case 'evaluate' % evaluate fitness - Data = varargin{1}; - Decs = varargin{2}; - - N = size(Decs,1); % population size - D = size(Decs,2); % deminsion of solution, i.e., number of racks - Objs = zeros(N,1); - acc1 = zeros(N,1); - acc2 = cell(N,1); % explicit solutions, i.e., racks' placement - for i = 1: N - currH = 0; - j = 1; - k = []; - while currH < Data.maxH && j <= D - currH = currH+Data.rackH(Data.rackInd(Decs(i,j))); - k = [k,Data.rackInd(Decs(i,j))]; % indexes of racks that have been placed - if currH > Data.maxH - currH = currH-Data.rackH(Data.rackInd(Decs(i,j))); - k(end) = []; % delete the rack that cannot be placed - end - j = j+1; - end - - Objs(i) = Data.maxH - currH; - acc2{i}(1,:) = [Data.preSolRack,k]; % all racks placed in the current column - acc2{i}(2,:) = [Data.preSolProd,repmat(Data.prodInd,1,numel(k))]; % each rack's product index - end - output1 = Objs; - output3 = {acc1,acc2}; - - case 'sequence' % change time step in the problem sequence - Problem = varargin{1}; - Data = varargin{2}; - solution = varargin{3}; - - Data.maxH = maxH; - usedRackInd = solution.acc{2}(1,:); - usedRackInd = usedRackInd(solution.acc{2}(2,:)==Data.prodInd); % current product's used racks - for i = 1:numel(usedRackInd) - sameInd = find(Data.rackInd==usedRackInd(i)); - Data.rackInd(sameInd(1)) = []; - end - - totalH = sum(Data.rackH(Data.rackInd)); - Data.preSolRack = []; - Data.preSolProd = []; - while totalH < maxH && Data.prodInd < length(Data.orgData) - Data.preSolRack = [Data.preSolRack,Data.rackInd]; % a part of the solution (rack indexes) to the current problem - Data.preSolProd = [Data.preSolProd,repmat(Data.prodInd,1,numel(Data.rackInd))]; % a part of the solution (product indexes) to the current problem - Data.maxH = maxH-totalH; % vertical height being considered in the current problem - Data.prodInd = Data.prodInd+1; % index of the current considered product - Data.rackInd = Data.orgData{Data.prodInd}; - totalH = totalH+sum(Data.rackH(Data.rackInd)); - end - - while numel(Data.rackInd) == 1 && Data.prodInd < length(Data.orgData) % if only one rack for placement - Data.prodInd = Data.prodInd+1; - Data.rackInd = [Data.rackInd,Data.orgData{Data.prodInd}]; - totalH = sum(Data.rackH(Data.rackInd)); - end - - Problem.bound = [1;numel(Data.rackInd)]; - - if Data.prodInd == length(Data.orgData) && totalH <= maxH - Data.continue = false; - else - Data.continue = true; - end - - output1 = Problem; - output2 = Data; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Warehouse Management/ProcessData.m b/matlab/Problems/Real-World/Warehouse Management/ProcessData.m deleted file mode 100644 index 9fe74bd..0000000 --- a/matlab/Problems/Real-World/Warehouse Management/ProcessData.m +++ /dev/null @@ -1,66 +0,0 @@ -% prepare -days = 7; -filename = 'DataOrg.xlsx'; - -% elminate null -[~,~,raw] = xlsread(filename); -raw(strcmp(raw(:,3),'ActiveX VT_ERROR: '),:) = []; % null in size -raw(strcmp(raw(:,4),'ActiveX VT_ERROR: '),:) = []; % null in size -raw(strcmp(raw(:,5),'ActiveX VT_ERROR: '),:) = []; % null in size -raw(strcmp(raw(:,6),'ActiveX VT_ERROR: '),:) = []; % null in frequency -raw(strcmp(raw(:,7),'ActiveX VT_ERROR: '),:) = []; % null in SKU - -% elminate zeros -for i = 3:7 - tempLoc = false(size(raw,1),1); - for j = 1:size(raw,1) - if raw{j,i}==0 - tempLoc(j) = true; - end - end - raw(tempLoc,:) = []; -end - -xlswrite('DataClearned.xlsx',raw,'Sheet1'); % for restore to original names of products and materials - -raw(1,:) = []; -raw(:,8) = []; - -% keep all cells being strings -for i = 1:size(raw,1) - for j = 1:size(raw,2) - raw{i,j} = num2str(raw{i,j}); - end -end - -% give products numerical indexes -IndProd = raw(:,1); -temp = unique(IndProd); -NumIndProd = zeros(length(IndProd),1); -for i = 1:length(temp) - NumIndProd(strcmp(IndProd,temp(i))) = i; % numerical indexes of products -end - -% give materials numerical indexes -IndMater = raw(:,2); -temp = unique(IndMater); -NumIndMater = zeros(length(IndMater),1); -for i = 1:length(temp) - NumIndMater(strcmp(IndMater,temp(i))) = i; % numerical indexes of materials -end - -% load size and frequency data -NumSizeFr = str2double(raw(:,3:7)); % strings in multiple cells to doubles in a single matrix - -data = [NumIndProd,NumIndMater,NumSizeFr]; % data with indexes of products and materials - -% calculate SKU (boxes) -data(:,6) = data(:,6)./30.*days; % picking up frequencies -filename = 'Size.xlsx'; -[~,~,rawSize] = xlsread(filename); -for i = 1:length(temp) - NumMaterBox = rawSize{strcmp(rawSize(:,1),temp(i)),2}; % number of materials in one box - data(strcmp(IndMater,temp(i)),7) = ceil(data(strcmp(IndMater,temp(i)),7)./NumMaterBox); % update SKU (boxes), common material has the same SKU value in each line of the material -end -writecell -xlswrite('DataProcessed.xlsx',data,'Sheet1'); \ No newline at end of file diff --git a/matlab/Problems/Real-World/Warehouse Management/Stack.m b/matlab/Problems/Real-World/Warehouse Management/Stack.m deleted file mode 100644 index 574a64e..0000000 --- a/matlab/Problems/Real-World/Warehouse Management/Stack.m +++ /dev/null @@ -1,184 +0,0 @@ -function [output1,output2,output3] = Stack(varargin) -switch varargin{end} - case 'construct' % % construct problem and data - type = {'discrete','static','certain'}; - Problem = varargin{1}; - instance = varargin{2}; - - orgData = readmatrix('DataAssigned.xlsx','Sheet',1); - prodInd = unique(orgData(:,1)); % all products - numProd = length(prodInd); - Data = struct('orgData',[],'rackSize',[],'stackSt',[],'inFesMater',[],'cons',[]); - - lowerH = 20; - upperH = 150; - intervalH = 10; - H = (lowerH:intervalH:upperH)'; - numH = length(H); - rackSize = [repmat(180,numH,1),repmat(60,numH,1),H;repmat(240,numH,1),repmat(120,numH,1),H;]; % sizes of all kinds of racks, [long,width,height] - - for i = 1:numProd - Problem(i) = Problem(1); % a number of numProd problem instances - Problem(i).type = type; - Data(i).orgData = orgData(orgData(:,1)==prodInd(i),:); % original data about the materials of product i - - % materials' stacking strategies when using each kind of racks - boxSize = Data(i).orgData(:,3:5); % size of boxes of all materials of product i, [long,width,height] - numMater = size(Data(i).orgData,1); % number of materials - stackSt = cell(numMater,1); - cons = cell(numMater,1); - inFesMater = false(numMater,1); - for j = 1:numMater - NH = floor(rackSize(:,3)./boxSize(j,3)); - NW = zeros(size(rackSize,1),1); - NL = zeros(size(rackSize,1),1); - control = zeros(size(rackSize,1),1); % control materials' stacking directions, 1: length side of material stacks in width side of rack, 2: width side of material stacks in width side of rack - for k = 1:size(rackSize,1) - if rackSize(k,2) < min(boxSize(j,1),boxSize(j,2)) - NW(k) = 0; - elseif rackSize(k,2) >= max(boxSize(j,1),boxSize(j,2)) - if rem(rackSize(k,2),boxSize(j,1)) < rem(rackSize(k,2),boxSize(j,2)) % length side of material stacks in width side of rack - NW(k) = floor(rackSize(k,2)./boxSize(j,1)); - control(k) = 1; - else - NW(k) = floor(rackSize(k,2)./boxSize(j,2)); - control(k) = 2; - end - elseif rackSize(k,2) < boxSize(j,1) && rackSize(k,2) >= boxSize(j,2) % width side of material stacks in width side of rack - NW(k) = floor(rackSize(k,2)./boxSize(j,2)); - control(k) = 2; - elseif rackSize(k,2) >= boxSize(j,1) && rackSize(k,2) < boxSize(j,2) % length side of material stacks in width side of rack - NW(k) = floor(rackSize(k,2)./boxSize(j,1)); - control(k) = 1; - end - if NW(k) == 0 || NH(k) == 0 - NL(k) = 0; - else - NL(k) = ceil(Data(i).orgData(j,7)./NW(k)./NH(k)); - if control(k) == 1 - total_L = boxSize(j,2)*NL(k); - elseif control(k) == 2 - total_L = boxSize(j,1)*NL(k); - end - if total_L > rackSize(k,1) - NL(k) = 0; - end - end - end - stackSt{j} = [NL,NW,NH,control]; % 28*4 - cons{j} = NL.*NW.*NH==0; % 28*1 logical - if prod(sum(stackSt{j}(:,1:3))) == 0 - inFesMater(j) = true; % indexes of materials that cannot be stacked on all kinds of racks - end - end - Data(i).rackSize = rackSize; - Data(i).stackSt = stackSt; % product i's materials' stacking strategies - Data(i).inFesMater = inFesMater; % indexes of materials that cannot be stacked on all kinds of racks - Data(i).cons = cons; - - Data(i).orgData(inFesMater,:) = []; % delete unstacked materials - Data(i).stackSt(inFesMater) = []; - Data(i).cons(inFesMater) = []; - - D = size(Data(i).orgData,1); % dimension of decision space - Problem(i).bound = [ones(1,D);repmat(size(rackSize,1),1,D)]; % product i's decision space's boundry, i.e., (min, max) indexes of kinds of racks being used - end - - output1 = Problem(instance); - output2 = Data(instance); - - case 'repair' - Data = varargin{1}; - Decs = varargin{2}; - D = size(Decs,2); - Cons = Data.cons; % D*1 cells, each cell is an |Upper-Lower|*1 logic matrix - for i = 1:D - InFesValue = find(Cons{i}==1); - FesValue = find(Cons{i}==0); - for j = 1:length(InFesValue) - Decs(Decs(:,i)==InFesValue(j),i) = FesValue(randperm(length(FesValue),1)); - end - end - output1 = Decs; - - case 'evaluate' % % evaluate fitness - Data = varargin{1}; - Decs = varargin{2}; - - N = size(Decs,1); % population size - D = size(Decs,2); % deminsion of solution, i.e., number of materials - Objs = zeros(N,1); - WasteL = zeros(N,1); % totally waste lengthes of all racks used for the given product - NumRacks = cell(N,1); % number of eack kind of used racks - - materSize = Data.orgData(:,3:5); % |materials|*3, all materials' sizes - materVol = prod(materSize,2).*Data.orgData(:,7); % |materials|*1, volumn of all boxes of each material (SKU boxes) - numRack = size(Data.rackSize,1); - materL = zeros(numRack,D); % 28*|materials|, length side of each material in each kind of racks - NL = zeros(numRack,D); % 28*|materials|, number of materials stacked along the length side of each kind of racks - for i = 1:D % for each material - materL(Data.stackSt{i}(:,4)==1,i) = materSize(i,2); - materL(Data.stackSt{i}(:,4)==2,i) = materSize(i,1); - NL(:,i) = Data.stackSt{i}(:,1); - end - rackL = Data.rackSize(:,1); % 28*1, lengthes of all kinds of racks - rackVol = prod(Data.rackSize,2); % 28*1, volumns of all kinds of racks - - for i = 1: N - solution = Decs(i,:); % index of rack being used by all materials of a given product - rackInd = unique(solution); % indexes of kinds of racks being used - C = zeros(length(rackInd),1); - Clength = zeros(length(rackInd),1); - NumRack = zeros(length(rackInd),1); - for j = 1:length(rackInd) - j_materL = materL(rackInd(j),solution==rackInd(j)); % length side of the materials (belong to the given product) that use rack j - j_NL = NL(rackInd(j),solution==rackInd(j)); % number of materials stacked along the length side of rack j - j_materVol = materVol(solution==rackInd(j)); - j_rackL = rackL(rackInd(j)); % length of rack j - j_rackVol = rackVol(rackInd(j)); % volumn of rack j - - if sum(j_materL.*j_NL) <= j_rackL - C(j) = j_rackVol-sum(j_materVol); - Clength(j) = j_rackL-sum(j_materL.*j_NL); - NumRack(j) = NumRack(j)+1; - else - j_materSize = materSize(solution==rackInd(j),:); % size of single box of the materials that use rack j - [~,ind] = sort(prod(j_materSize,2),'descend'); - k = 1; % counter of materials that use rack j - currL = 0; - currVol = 0; - C(j) = 0; - while k <= length(j_materL) % while each material - while currL < j_rackL && k <= length(j_materL) - currL = currL+j_materL(ind(k))*j_NL(ind(k)); - currVol = currVol+j_materVol(ind(k)); - k = k+1; - end - if currL > j_rackL - currL = currL-sum(j_materL(ind(k-1))*j_NL(ind(k-1))); - currVol = currVol-j_materVol(ind(k-1)); - k = k-1; - end - C(j) = C(j)+(j_rackVol-currVol); - Clength(j) = Clength(j)+(j_rackL-currL); - NumRack(j) = NumRack(j)+1; - currL = 0; - currVol = 0; - end - end - end - Objs(i) = sum(C); - WasteL(i) = sum(Clength); - NumRacks{i} = NumRack; - end - output1 = Objs; - output3 = {WasteL,NumRacks}; -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/Warehouse Management/StackTraverse.m b/matlab/Problems/Real-World/Warehouse Management/StackTraverse.m deleted file mode 100644 index 3a666c6..0000000 --- a/matlab/Problems/Real-World/Warehouse Management/StackTraverse.m +++ /dev/null @@ -1,75 +0,0 @@ -function [Objs,WasteL,NumRacks] = Stack(Data,Decs) -N = size(Decs,1); % population size -D = size(Decs,2); % deminsion of solution, i.e., number of materials -Objs = zeros(N,1); -WasteL = zeros(N,1); % totally waste lengthes of all racks used for the given product -NumRacks = cell(N,1); % number of eack kind of used racks - -materSize = Data.orgData(:,3:5); % |materials|*3, all materials' sizes -materVol = prod(materSize,2).*Data.orgData(:,7); % |materials|*1, volumn of all boxes of each material (SKU boxes) -numRack = size(Data.rackSize,1); -materL = zeros(numRack,D); % 28*|materials|, length side of each material in each kind of racks -NL = zeros(numRack,D); % 28*|materials|, number of materials stacked along the length side of each kind of racks -for d = 1:D % for each material - materL(Data.stackSt{d}(:,4)==1,d) = materSize(d,2); - materL(Data.stackSt{d}(:,4)==2,d) = materSize(d,1); - NL(:,d) = Data.stackSt{d}(:,1); -end -rackL = Data.rackSize(:,1); % 28*1, lengthes of all kinds of racks -rackVol = prod(Data.rackSize,2); % 28*1, volumns of all kinds of racks - -for i = 1: N - solution = Decs(i,:); % index of rack being used by all materials of a given product - rackInd = unique(solution); % indexes of kinds of racks being used - C = zeros(length(rackInd),1); - Clength = zeros(length(rackInd),1); - NumRack = zeros(length(rackInd),1); - for j = 1:length(rackInd) - j_materL = materL(rackInd(j),solution==rackInd(j)); % length side of a single box of each material (belong to the given product) that uses rack j - j_NL = NL(rackInd(j),solution==rackInd(j)); % number of materials stacked along the length side of rack j - j_materVol = materVol(solution==rackInd(j)); - j_rackL = rackL(rackInd(j)); % length of rack j - j_rackVol = rackVol(rackInd(j)); % volumn of rack j - - if sum(j_materL.*j_NL) <= j_rackL - C(j) = j_rackVol-sum(j_materVol); - Clength(j) = j_rackL-sum(j_materL.*j_NL); - NumRack(j) = NumRack(j)+1; - else - j_materSize = materSize(solution==rackInd(j),:); % size of single box of the materials that use rack j - [~,ind] = sort(prod(j_materSize,2),'descend'); - k = 1; - stackedMaterInd = []; - currL = 0; - currVol = 0; - C(j) = 0; - while ~isempty(ind) % while each material - while currL < j_rackL && k <= numel(ind) % while each unstacked materials - currL = currL+j_materL(ind(k))*j_NL(ind(k)); - currVol = currVol+j_materVol(ind(k)); - stackedMaterInd = [stackedMaterInd,ind(k)]; - if currL > j_rackL - currL = currL-sum(j_materL(ind(k))*j_NL(ind(k))); - currVol = currVol-j_materVol(ind(k)); - stackedMaterInd(end) = []; - end - k = k+1; - end - - C(j) = C(j)+(j_rackVol-currVol); - Clength(j) = Clength(j)+(j_rackL-currL); - NumRack(j) = NumRack(j)+1; - for p = 1:length(stackedMaterInd) - ind(ind==stackedMaterInd(p)) = []; - end - k = 1; - currL = 0; - currVol = 0; - end - end - end - Objs(i) = sum(C); - WasteL(i) = sum(Clength); - NumRacks{i} = NumRack; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/blackstart/adjacent.xlsx b/matlab/Problems/Real-World/blackstart/adjacent.xlsx deleted file mode 100644 index 49df8e5..0000000 Binary files a/matlab/Problems/Real-World/blackstart/adjacent.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/blackstart/blackstart.m b/matlab/Problems/Real-World/blackstart/blackstart.m deleted file mode 100644 index f1ab954..0000000 --- a/matlab/Problems/Real-World/blackstart/blackstart.m +++ /dev/null @@ -1,454 +0,0 @@ -function [output1,output2,output3] = blackstart(varargin) -% The black start problem - -switch varargin{end} - case 'construct' - Problem = varargin{1}; - instance = varargin{2}; - % define the bound of decision space - a = 2; % number of BS - b = 8; % number of NBS - c = 21; % number of load - lower = zeros(1,a*b+b*c); % 1*D, lower bound of the D-dimension decision space - upper = ones(1,a*b+b*c); % 1*D, upper bound of the D-dimension decision space - for i = 1:length(instance) - Problem(i) = Problem(1); - Problem(i).bound = [lower;upper]; - - % define problem type in the following three cells (optional), type - % can be defined either here or in the Main file - % choices: - % first cell : 'continuous'\'discrete'\'permutation' - % second cell: 'static'\'sequential' - % third cell : 'certain'\'uncertain' - Problem(i).type = {'discrete','static','certain'}; - end - output1 = Problem; - - % load data file - orgData = case3901; - Weight = readmatrix('weight.xlsx','Sheet',1); % the weight of the Loads - Data = struct; - for k = 1:length(instance) - if k == 1 - BS = orgData.gen([1,2],:); - NBS = orgData.gen(3:10,:); - elseif k == 2 - BS = orgData.gen([3,7],:); - NBS = orgData.gen([1:2,4:6,8:10],:); - end - Load = orgData.bus([1,3,4,7,8,9,12,15,16,18,20,21,23:29,31,39],:); - branch = orgData.branch; - bus = orgData.bus; - - % calculate the distance between any two nodes - [A,indBS,indNBS,indLoad] = getAdjacent(k); - w = zeros(numel(indBS),numel(indNBS)); % for save distance between BS and NBS - l = zeros(numel(indNBS),numel(indLoad)); % for save distance between NBS and Load - BSNBSPath = cell(numel(indBS),numel(indNBS)); % for save path from BS to NBS - NBSLoadPath = cell(numel(indNBS),numel(indLoad)); % for save path from NBS to Load - for i = 1:numel(indBS) - for j = 1:numel(indNBS) - start = indBS(i); - dest = indNBS(j); - [w(i,j),BSNBSPath{i,j},~] = dijkstra(A,start,dest); - end - end - for i = 1:numel(indNBS) - for j = 1:numel(indLoad) - start = indNBS(i); - dest = indLoad(j); - [l(i,j),NBSLoadPath{i,j},~ ] = dijkstra(A,start,dest); - end - end - - Data(k).BS = BS; - Data(k).NBS = NBS; - Data(k).Load = Load; - Data(k).branch = branch; - Data(k).bus = bus; - Data(k).w = w; - Data(k).l = l; - Data(k).BSNBSPath = BSNBSPath; - Data(k).NBSLoadPath = NBSLoadPath; - Data(k).Weight = Weight; - end - output2 = Data; - - case 'repair' - Data = varargin{1}; - Decs = varargin{2}; - a = size(Data.BS,1); % number of BS - b = size(Data.NBS,1); % number of NBS - c = size(Data.Load,1); % number of load - for i = 1:size(Decs,1) - v = reshape(Decs(i,1:a*b),b,a); - v = v'; % 2*8(a*b) - h = reshape(Decs(i,a*b+1:end),c,b); - h = h'; % 8*21(b*c) - %repair the solution - % only one BS to each NBS - for g = 1:b % for each NBS - if sum(v(:,g)) > 1 - BSInd = find(v(:,g)==1); - randInd = randperm(numel(BSInd)); - v(BSInd(randInd(1:end-1)),g) = 0; - elseif sum(v(:,g)) < 1 - randInd = randi(a); - v(randInd,g) = 1; - end - end - % for each load,only one NBS to each load - for k = 1:c - if sum(h(:,k)) > 1 - NBSInd = find(h(:,k)==1); - randInd = randperm(numel(NBSInd)); - h(NBSInd(randInd(1:end-1)),k) = 0; - elseif sum(h(:,k)) < 1 - randInd = randi(b); - h(randInd,k) = 1; - end - end - %give v&h to the Decs(i) - f = v'; - f = reshape(f,1,a*b); - e = h'; - e = reshape(e,1,b*c); - Decs(i,1:a*b) = f; - Decs(i,a*b+1:end) = e; - end - output1 = Decs; - - case 'evaluate' - Data = varargin{1}; % load problem data - Decs = varargin{2}; % load the current solution(s) - - % define the objective function in the following - a = size(Data.BS,1); % number of BS - b = size(Data.NBS,1); % number of NBS - c = size(Data.Load,1); % number of load - w = Data.w; % distance between BS and NBS - l = Data.l;% distance between NBS and Load - Objs = zeros(size(Decs,1),1); - for i = 1:size(Decs,1) - v = reshape(Decs(i,1:a*b),b,a); - v = v'; % 2*8(a*b) - h = reshape(Decs(i,a*b+1:end),c,b); - h = h'; % 8*21(b*c) - F = zeros(b,1); - for j = 1:b - F(j) = v(:,j)'*w(:,j); - end - F = sum(F); - G = zeros(c,1); - for k = 1:c - G(k) = h(:,k)'*l(:,k); - end - G = sum(G); - Objs(i) = F+G; - end - - - % calculate the priority of NBS - Weight = Data.Weight; - maxW = zeros(b,1); % power of the most important load of each NBS - for i = 1:size(h,1) - indLoadThisNBS = find(h(i,:)==1); % indexes of the loads belong to NBS i - indLoadThisNBS = indLoadThisNBS'; - if isempty(indLoadThisNBS) == 0 - WeightThisNBS = Weight(indLoadThisNBS,1); - else - WeightThisNBS = 0; - end - maxW(i) = max(WeightThisNBS); - end - [~,priority] = sort(maxW,'descend'); % run NBS (index) one by one according to priority - - % define the inequal constraint(s) in the following, equal - % constraints should be transformed to inequal ones - restoredbranchInd = {}; - CV = zeros(size(Decs,1),1); - - for i = 1:size(Decs,1) - % extract the path according to solution - BSNBSInd = zeros(1,b); %ĸBSĸNBSӦλã - BSNBSPath = Data.BSNBSPath;%BS to NBS· - thisBSNBSPath = cell(b,1);%ݽ⣬ȡBStoNBS· - NBSLoadInd = zeros(1,c);%ĸNBSĸLoadӦλã - NBSLoadPath = Data.NBSLoadPath;%NBS to Load· - thisNBSLoadPath = cell(c,1);%ݽ⣬ȡNBStoLoad· - % solutionȡBSNBS· - for j = 1:size(v,2) - BSNBSInd(j) = find(v(:,j)==1); - thisBSNBSPath{j} = BSNBSPath{BSNBSInd(j),j}; - end - % solutionȡNBSLoad· - for j = 1:size(h,2) - NBSLoadInd(j) = find(h(:,j)==1); - thisNBSLoadPath{j} = NBSLoadPath{NBSLoadInd(j),j}; - end - - %¸״̬ - ubranch = zeros(size(Data.branch,1),1);% branch״̬ - ust = zeros(b,1); % starting state of NBS - uramp = zeros(b,1); % rumping state of NBS - % ubus = zeros(size(Data.bus,1),1); - % ubus(30:31) = 1; - %BSָthenBSֱlineָ(BSڵһline) - for j = 1:size(Data.BS,1) - thisBSbranchind = Data.branch(:,2)==Data.BS(j,1);%ҵBSڵȵtbusλãλҲbranchıţ - ubranch(thisBSbranchind) = 1; - end - - %line߻ָָܻ(йͬĽڵ) - %NBSȼBStoNBSeach·״̬ - for m = 1:numel(priority) - for k = 1:numel(thisBSNBSPath{priority(m)}(1:end-1)) - for j = 1:size(Data.branch,1) - if ubranch(j) == 1 - if thisBSNBSPath{priority(m)}(k) == Data.branch(j,1) - connBusInd = k;%thisBSNBSPathҵbranchjйͬڵĽڵŵλãthisBSNBSPathprioritymеĵڼ - if thisBSNBSPath{priority(m)}(connBusInd)= 1 - % ubranch(j) = 1; - % end - % end - - %for each NBSNBSlineָthenNBSָ(йͬڵ) - for n = 1:numel(priority) - thisNBSbranchind = Data.branch(:,2)==Data.NBS(priority(n),1);%ҵNBSڵͬtbusλãλǶӦbranchıţ - if sum(ubranch(thisNBSbranchind)) >= 1 - ust(priority(n)) = 1; - else - ust(priority(n)) = 0; - end - - %update the ramping state of the NBS - P_ramp = Data.NBS(:,18);%ҵP_ramp - P = Data.NBS(:,2); - if P(priority(n)) > P_ramp(priority(n)) - uramp(priority(n)) = 1; - else - uramp(priority(n)) = 0; - end - end - - orgCase = case3901; - updatedCase = orgCase; - updatedCase.branch(:,11) = ubranch; - updatedCase.gen(3:end,8) = ust; - save('newcase.mat',"updatedCase"); - %results = runpf('newcase'); - results = runpf(updatedCase); - if results.iterations == 10 - results.success - end - if results.success == 0 - CV(i) = 10^6; - continue - end - - - - - %ԼԼ - %resultsȡ - P = results.gen(:,2);%й - Q = results.gen(:,3);%޹ - Pmax = results.gen(:,9);% - % P_ramp = results.gen(:,18);%¹ - Qmax = results.gen(:,4);%޹ - V = results.bus(:,8);%ѹֵ - Vmax = results.bus(:,12);%ѹ - Vmin = results.bus(:,13);%Сѹ - %BS+NBSԼ - p1 = zeros(a+b,1); - for g = 1:a+b - if Pmax(g)-P(g)>=0 && P(g)>=0 && Qmax(g)-Q(g)>=0 && Q(g)>=0 - P(g) = P(g); - else - p1(g) = abs(Pmax(g)-P(g))+abs(P(g)); - end - p1 = sum(p1); - end - %NBSԼ - % for g = 1:b - % if (P_ramp(g)/10)*T-(P(g,t)-P(g,t-1)) >= 0&&P(g,t)-P(g,t-1) >= 0 - % P(g,t) = P(g,t); - % else - % p2 = abs((P_ramp(g)/10)*T-(P(g,t)-P(g,t-1)))+abs(P(g,t)-P(g,t-1)); - % end - % end - - %Լ·for each branch - Smax = Data.branch(:,6); - PF = results.branch(:,14); - QF = results.branch(:,15); - p3 = zeros(46,1); - for j = 1:size(Data.branch,1) - if Smax(j)^2*ubranch(j)-(PF(j)^2+QF(j)^2) < 0 - p3(j) = abs(Smax(j)^2*ubranch(j)-PF(j)^2-QF(j)^2); - end - p3 = sum(p3); - end - %ѹԼ - p4 = zeros(39,1); - for d = 1:size(Data.bus,1) - if Vmax(d)-V(d)<0 || V(d)-Vmin(d)<0 - p4(d) = abs(Vmax(d)-V(d))+abs(V(d)-Vmin(d)); - end - p4 = sum(p4); - end - - %ʽԼ - %ƽԼ - PD = Data.bus(:,3); - QD = Data.bus(:,4); - PT = results.branch(:,16); - QT = results.branch(:,17); - p2 = zeros(29,1); - p5 = zeros(29,1); - for j = 1:29 - if PD(j)>0 - connbranch1Ind = find(Data.branch(:,1)==j); - connbranch2Ind = find(Data.branch(:,2)==j); - if PD(j)+sum(PF(connbranch1Ind))+sum(PT(connbranch2Ind)) ~= 0 - p2(j) = abs(PD(j))+abs(sum(PF(connbranch1Ind)))+abs(sum(PF(connbranch2Ind))); - end - if QD(j)+sum(QF(connbranch1Ind))+sum(QT(connbranch2Ind)) ~= 0 - p5(j) = abs(QD(j))+abs(sum(QF(connbranch1Ind)))+abs(sum(QT(connbranch2Ind))); - end - end - if PD(j) == 0 - connbranch1Ind = find(Data.branch(:,1)==j); - connbranch2Ind = find(Data.branch(:,2)==j); - if sum(PF(connbranch1Ind))+sum(PT(connbranch2Ind)) ~= 0 - p2(j) = abs(sum(PF(connbranch1Ind)))+abs(sum(PF(connbranch2Ind))); - end - if sum(QF(connbranch1Ind))+sum(QT(connbranch2Ind)) ~= 0 - p5(j) = abs(sum(QF(connbranch1Ind)))+abs(sum(QT(connbranch2Ind))); - end - end - p2 = sum(p2); - p5 = sum(p5); - end - - %BSNBSĹԼ - Pramp = Data.NBS(:,18); - PBS = Data.BS(:,17); - p6 = zeros(size(Data.BS,1),1); - for j = 1:size(Data.BS,1) - BSNInd = find(v(j,:)==1); - BSNInd = BSNInd'; - if sum(Pramp(BSNInd)) > PBS(j) - p6(j) = sum(Pramp(BSNInd)) - PBS(j); - end - p6 = sum(p6); - end - - %NBSLoadĹԼ - Pout = results.gen([1:2,4:6,8:10],2); - PL = results.bus([1,3,4,7,8,9,12,15,16,18,20,21,23:29,31,39],3); - p7 = zeros(size(Data.NBS,1),1); - for j = 1:size(Data.NBS,1) - NBSLInd = find(h(j,:)==1); - NBSLInd = NBSLInd'; - if sum(PL(NBSLInd)) > Pout(j) - p7(j) = sum(PL(NBSLInd))-Pout(j); - end - p7 = sum(p7); - end - - % calculate the constraint violation in the following - CV(i) = p1+p2+p3+p4+p5+p6+p7; - end - - % collect accessory data for understanding the solutions in the - % following (optional) - - output1 = Objs; % matrix for saving objective function values - output2 = CV; % matrix for saving constraint violation values (optional) - output3 = []; % matrix or cells for saving accessory data (optional), a solution's accessory data should be saved in a row - - %output1 = output1 + output2 -end - -if ~exist('output2','var') - output2 = []; -elseif ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/blackstart/case3901.m b/matlab/Problems/Real-World/blackstart/case3901.m deleted file mode 100644 index ab17615..0000000 --- a/matlab/Problems/Real-World/blackstart/case3901.m +++ /dev/null @@ -1,205 +0,0 @@ -function mpc = case3901 -%CASE39 Power flow data for 39 bus New England system. -% Please see CASEFORMAT for details on the case file format. -% -% Data taken from [1] with the following modifications/additions: -% -% - renumbered gen buses consecutively (as in [2] and [4]) -% - added Pmin = 0 for all gens -% - added Qmin, Qmax for gens at 31 & 39 (copied from gen at 35) -% - added Vg based on V in bus data (missing for bus 39) -% - added Vg, Pg, Pd, Qd at bus 39 from [2] (same in [4]) -% - added Pmax at bus 39: Pmax = Pg + 100 -% - added line flow limits and area data from [4] -% - added voltage limits, Vmax = 1.06, Vmin = 0.94 -% - added identical quadratic generator costs -% - increased Pmax for gen at bus 34 from 308 to 508 -% (assumed typo in [1], makes initial solved case feasible) -% - re-solved power flow -% -% Notes: -% - Bus 39, its generator and 2 connecting lines were added -% (by authors of [1]) to represent the interconnection with -% the rest of the eastern interconnect, and did not include -% Vg, Pg, Qg, Pd, Qd, Pmin, Pmax, Qmin or Qmax. -% - As the swing bus, bus 31 did not include and Q limits. -% - The voltages, etc in [1] appear to be quite close to the -% power flow solution of the case before adding bus 39 with -% it's generator and connecting branches, though the solution -% is not exact. -% - Explicit voltage setpoints for gen buses are not given, so -% they are taken from the bus data, however this results in two -% binding Q limits at buses 34 & 37, so the corresponding -% voltages have probably deviated from their original setpoints. -% - The generator locations and types are as follows: -% 1 30 hydro -% 2 31 nuke01 -% 3 32 nuke02 -% 4 33 fossil02 -% 5 34 fossil01 -% 6 35 nuke03 -% 7 36 fossil04 -% 8 37 nuke04 -% 9 38 nuke05 -% 10 39 interconnection to rest of US/Canada -% -% This is a solved power flow case, but it includes the following -% violations: -% - Pmax violated at bus 31: Pg = 677.87, Pmax = 646 -% - Qmin violated at bus 37: Qg = -1.37, Qmin = 0 -% -% References: -% [1] G. W. Bills, et.al., "On-Line Stability Analysis Study" -% RP90-1 Report for the Edison Electric Institute, October 12, 1970, -% pp. 1-20 - 1-35. -% prepared by E. M. Gulachenski - New England Electric System -% J. M. Undrill - General Electric Co. -% "generally representative of the New England 345 KV system, but is -% not an exact or complete model of any past, present or projected -% configuration of the actual New England 345 KV system. -% [2] M. A. Pai, Energy Function Analysis for Power System Stability, -% Kluwer Academic Publishers, Boston, 1989. -% (references [3] as source of data) -% [3] Athay, T.; Podmore, R.; Virmani, S., "A Practical Method for the -% Direct Analysis of Transient Stability," IEEE Transactions on Power -% Apparatus and Systems , vol.PAS-98, no.2, pp.573-584, March 1979. -% URL: https://doi.org/10.1109/TPAS.1979.319407 -% (references [1] as source of data) -% [4] Data included with TC Calculator at http://www.pserc.cornell.edu/tcc/ -% for 39-bus system. - -% MATPOWER - -%% MATPOWER Case Format : Version 2 -mpc.version = '2'; - -%%----- Power Flow Data -----%% -%% system MVA base -mpc.baseMVA = 100; - -%% bus data -% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin -mpc.bus = [ - 1 1 97.6 44.2 0 0 2 1.0393836 -13.536602 345 1 1.06 0.94; - 2 1 0 0 0 0 2 1.0484941 -9.7852666 345 1 1.06 0.94; - 3 1 322 2.4 0 0 2 1.0307077 -12.276384 345 1 1.06 0.94; - 4 1 500 184 0 0 1 1.00446 -12.626734 345 1 1.06 0.94; - 5 1 0 0 0 0 1 1.0060063 -11.192339 345 1 1.06 0.94; - 6 1 0 0 0 0 1 1.0082256 -10.40833 345 1 1.06 0.94; - 7 1 233.8 84 0 0 1 0.99839728 -12.755626 345 1 1.06 0.94; - 8 1 522 176.6 0 0 1 0.99787232 -13.335844 345 1 1.06 0.94; - 9 1 6.5 -66.6 0 0 1 1.038332 -14.178442 345 1 1.06 0.94; - 10 1 0 0 0 0 1 1.0178431 -8.170875 345 1 1.06 0.94; - 11 1 0 0 0 0 1 1.0133858 -8.9369663 345 1 1.06 0.94; - 12 1 8.53 88 0 0 1 1.000815 -8.9988236 345 1 1.06 0.94; - 13 1 0 0 0 0 1 1.014923 -8.9299272 345 1 1.06 0.94; - 14 1 0 0 0 0 1 1.012319 -10.715295 345 1 1.06 0.94; - 15 1 320 153 0 0 3 1.0161854 -11.345399 345 1 1.06 0.94; - 16 1 329 32.3 0 0 3 1.0325203 -10.033348 345 1 1.06 0.94; - 17 1 0 0 0 0 2 1.0342365 -11.116436 345 1 1.06 0.94; - 18 1 158 30 0 0 2 1.0315726 -11.986168 345 1 1.06 0.94; - 19 1 0 0 0 0 3 1.0501068 -5.4100729 345 1 1.06 0.94; - 20 1 680 103 0 0 3 0.99101054 -6.8211783 345 1 1.06 0.94; - 21 1 274 115 0 0 3 1.0323192 -7.6287461 345 1 1.06 0.94; - 22 1 0 0 0 0 3 1.0501427 -3.1831199 345 1 1.06 0.94; - 23 1 247.5 84.6 0 0 3 1.0451451 -3.3812763 345 1 1.06 0.94; - 24 1 308.6 -92.2 0 0 3 1.038001 -9.9137585 345 1 1.06 0.94; - 25 1 224 47.2 0 0 2 1.0576827 -8.3692354 345 1 1.06 0.94; - 26 1 139 17 0 0 2 1.0525613 -9.4387696 345 1 1.06 0.94; - 27 1 281 75.5 0 0 2 1.0383449 -11.362152 345 1 1.06 0.94; - 28 1 206 27.6 0 0 3 1.0503737 -5.9283592 345 1 1.06 0.94; - 29 1 283.5 26.9 0 0 3 1.0501149 -3.1698741 345 1 1.06 0.94; - 30 2 0 0 0 0 2 1.0499 -7.3704746 345 1 1.06 0.94; - 31 3 9.2 4.6 0 0 1 0.982 0 345 1 1.06 0.94; - 32 2 0 0 0 0 1 0.9841 -0.1884374 345 1 1.06 0.94; - 33 2 0 0 0 0 3 0.9972 -0.19317445 345 1 1.06 0.94; - 34 2 0 0 0 0 3 1.0123 -1.631119 345 1 1.06 0.94; - 35 2 0 0 0 0 3 1.0494 1.7765069 345 1 1.06 0.94; - 36 2 0 0 0 0 3 1.0636 4.4684374 345 1 1.06 0.94; - 37 2 0 0 0 0 2 1.0275 -1.5828988 345 1 1.06 0.94; - 38 2 0 0 0 0 3 1.0265 3.8928177 345 1 1.06 0.94; - 39 2 1104 250 0 0 1 1.03 -14.535256 345 1 1.06 0.94; -]; - -%% generator data -% bus Pg Qg Qmax Qmin Vg mBase ust Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc Pstart ramp_30 ramp_q apf -mpc.gen = [ - 30 250 161.762 400 140 1.0499 100 1 1140 0 0 0 0 0 0 0 500 0 0 0 0; - 31 677.871 221.574 300 -100 0.982 100 1 700 0 0 0 0 0 0 0 500 0 0 0 0; - 32 650 206.965 300 150 0.9841 100 0 725 0 0 0 0 0 0 0 0 110 0 0 0; - 33 632 108.293 250 0 0.9972 100 0 652 0 0 0 0 0 0 0 0 110 0 0 0; - 34 508 166.688 167 0 1.0123 100 0 508 0 0 0 0 0 0 0 0 110 0 0 0; - 35 650 210.661 300 -100 1.0494 100 0 687 0 0 0 0 0 0 0 0 110 0 0 0; - 36 560 100.165 240 0 1.0636 100 0 580 0 0 0 0 0 0 0 0 110 0 0 0; - 37 540 -1.36945 250 0 1.0275 100 0 564 0 0 0 0 0 0 0 0 110 0 0 0; - 38 830 21.7327 300 -150 1.0265 100 0 865 0 0 0 0 0 0 0 0 110 0 0 0; - 39 1000 78.4674 300 -100 1.03 100 0 1100 0 0 0 0 0 0 0 0 110 0 0 0; -]; - -%% branch data -% fbus tbus r x b rateA rateB rateC ratio angle ubranch angmin angmax -mpc.branch = [ - 1 2 0.0035 0.0411 0.6987 600 600 600 0 0 0 -360 360; - 1 39 0.001 0.025 0.75 1000 1000 1000 0 0 0 -360 360; - 2 3 0.0013 0.0151 0.2572 500 500 500 0 0 0 -360 360; - 2 25 0.007 0.0086 0.146 500 500 500 0 0 0 -360 360; - 2 30 0 0.0181 0 900 900 2500 1.025 0 0 -360 360; - 3 4 0.0013 0.0213 0.2214 500 500 500 0 0 0 -360 360; - 3 18 0.0011 0.0133 0.2138 500 500 500 0 0 0 -360 360; - 4 5 0.0008 0.0128 0.1342 600 600 600 0 0 0 -360 360; - 4 14 0.0008 0.0129 0.1382 500 500 500 0 0 0 -360 360; - 5 6 0.0002 0.0026 0.0434 1200 1200 1200 0 0 0 -360 360; - 5 8 0.0008 0.0112 0.1476 900 900 900 0 0 0 -360 360; - 6 7 0.0006 0.0092 0.113 900 900 900 0 0 0 -360 360; - 6 11 0.0007 0.0082 0.1389 480 480 480 0 0 0 -360 360; - 6 31 0 0.025 0 1800 1800 1800 1.07 0 0 -360 360; - 7 8 0.0004 0.0046 0.078 900 900 900 0 0 0 -360 360; - 8 9 0.0023 0.0363 0.3804 900 900 900 0 0 0 -360 360; - 9 39 0.001 0.025 1.2 900 900 900 0 0 0 -360 360; - 10 11 0.0004 0.0043 0.0729 600 600 600 0 0 0 -360 360; - 10 13 0.0004 0.0043 0.0729 600 600 600 0 0 0 -360 360; - 10 32 0 0.02 0 900 900 2500 1.07 0 0 -360 360; - 12 11 0.0016 0.0435 0 500 500 500 1.006 0 0 -360 360; - 12 13 0.0016 0.0435 0 500 500 500 1.006 0 0 -360 360; - 13 14 0.0009 0.0101 0.1723 600 600 600 0 0 0 -360 360; - 14 15 0.0018 0.0217 0.366 600 600 600 0 0 0 -360 360; - 15 16 0.0009 0.0094 0.171 600 600 600 0 0 0 -360 360; - 16 17 0.0007 0.0089 0.1342 600 600 600 0 0 0 -360 360; - 16 19 0.0016 0.0195 0.304 600 600 2500 0 0 0 -360 360; - 16 21 0.0008 0.0135 0.2548 600 600 600 0 0 0 -360 360; - 16 24 0.0003 0.0059 0.068 600 600 600 0 0 0 -360 360; - 17 18 0.0007 0.0082 0.1319 600 600 600 0 0 0 -360 360; - 17 27 0.0013 0.0173 0.3216 600 600 600 0 0 0 -360 360; - 19 20 0.0007 0.0138 0 900 900 2500 1.06 0 0 -360 360; - 19 33 0.0007 0.0142 0 900 900 2500 1.07 0 0 -360 360; - 20 34 0.0009 0.018 0 900 900 2500 1.009 0 0 -360 360; - 21 22 0.0008 0.014 0.2565 900 900 900 0 0 0 -360 360; - 22 23 0.0006 0.0096 0.1846 600 600 600 0 0 0 -360 360; - 22 35 0 0.0143 0 900 900 2500 1.025 0 0 -360 360; - 23 24 0.0022 0.035 0.361 600 600 600 0 0 0 -360 360; - 23 36 0.0005 0.0272 0 900 900 2500 1 0 0 -360 360; - 25 26 0.0032 0.0323 0.531 600 600 600 0 0 0 -360 360; - 25 37 0.0006 0.0232 0 900 900 2500 1.025 0 0 -360 360; - 26 27 0.0014 0.0147 0.2396 600 600 600 0 0 0 -360 360; - 26 28 0.0043 0.0474 0.7802 600 600 600 0 0 0 -360 360; - 26 29 0.0057 0.0625 1.029 600 600 600 0 0 0 -360 360; - 28 29 0.0014 0.0151 0.249 600 600 600 0 0 0 -360 360; - 29 38 0.0008 0.0156 0 1200 1200 2500 1.025 0 0 -360 360; -]; - -%%----- OPF Data -----%% -%% generator cost data -% 1 startup shutdown n x1 y1 ... xn yn -% 2 startup shutdown n c(n-1) ... c0 -mpc.gencost = [ - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; - 2 0 0 3 0.01 0.3 0.2; -]; diff --git a/matlab/Problems/Real-World/blackstart/dijkstra.m b/matlab/Problems/Real-World/blackstart/dijkstra.m deleted file mode 100644 index bb78cb2..0000000 --- a/matlab/Problems/Real-World/blackstart/dijkstra.m +++ /dev/null @@ -1,67 +0,0 @@ -% ļdijkstra.m -% ʱ䣺2020912 -% Դhttps://blog.csdn.net/lishan132/article/details/108527271 -% ܣdijkstra㷨· -% distյֵ֮̾ -% path· -% Distance·µľֵ -% AڽӾ -% strat -% destյ -function [dist,resultPath,Distance] = dijkstra(A,start,dest) -% -% ʱ -% tic %ʼʱ - -% ʼ -p = size(A,1); %㶥Ŀ -S(1) = dest; %ʼSѼ뵽·еĶ -U = 1:p; %ʼUδ뵽·еĶ -U(dest) = []; %ɾյ -Distance = zeros(2,p); %ʼж㵽յdestľ -Distance(1,:) = 1:p; %ظֵһΪ -Distance(2,1:p) = A(dest,1:p); %ظֵڶΪڽӾи㵽յľ -new_Distance = Distance; -D = Distance; %ʼUж㵽յdestľ -D(:,dest) = []; %ɾUյŵյŵľ -path = zeros(2,p); %ʼ· -path(1,:) = 1:p; %ظֵһΪ -path(2,Distance(2,:)~=inf) = dest; %ֵΪʱ - -% Ѱ· -while ~isempty(U) %жUԪǷΪ - index = find(D(2,:)==min(D(2,:)),1); %ʣඥоСֵ - k = D(1,index); %ʣඥоյĶ - - %¶ - S = [S,k]; %kӵS - U(U==k) = []; %Uɾk - - % - new_Distance(2,:) = A(k,1:p)+Distance(2,k); %ͨkٴkյеֵ - D = min(Distance,new_Distance); %ԭľֵȽϣȡСֵ - - %· - path(2,D(2,:)~=Distance(2,:)) = k; %µСֵӹϵӵk - - %¾ - Distance = D; %¾Ϊе㵽յСֵ - D(:,S) = []; %ɾѼ뵽SеĶ -end -dist = Distance(2,start); %ȡָ㵽յľֵ -% toc %ʱ - -% -% fprintf('ҵ·Ϊ'); -resultPath = []; -while start ~= dest %յʱ -% fprintf('%d-->',start); %ӡǰ - resultPath = [resultPath,start]; - next = path(2,start); %뵱ǰһ - start = next; %µǰ -end -resultPath = [resultPath,start]; -% fprintf('%d\n',dest); -% fprintf('·ӦľΪ%d\n',dist); -end - \ No newline at end of file diff --git a/matlab/Problems/Real-World/blackstart/getAdjacent.m b/matlab/Problems/Real-World/blackstart/getAdjacent.m deleted file mode 100644 index 99b7864..0000000 --- a/matlab/Problems/Real-World/blackstart/getAdjacent.m +++ /dev/null @@ -1,63 +0,0 @@ -function [A,indBS,indNBS,indLoad] = getAdjacent(k) -%function [A,node] = getAdjacent -A = readmatrix('adjacent.xlsx','Sheet',1); -A(1,:) = []; % delete indexes -A(:,1) = []; % delete indexes -for i = 1:size(A,1) - for j = 1:size(A,2) - if ~isnan(A(i,j)) - A(j,i) = A(i,j); - else - A(i,j) = inf; % replace Nan with Inf - end - end -end - -% A = [0,275.5,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,167.6;%1 -% 275.5,0,101.2,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,57.6,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%2 -% inf,101.2,0,142.8,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,89.1,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%3 -% inf,inf,142.8,0,85.8,inf,inf,inf,inf,inf,inf,inf,inf,86.5,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%4 -% inf,inf,inf,85.8,0,17.4,inf,75.1,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%5 -% inf,inf,inf,inf,17.4,0,61.7,inf,inf,inf,55,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf;%6 -% inf,inf,inf,inf,inf,61.7,0,30.8,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%7 -% inf,inf,inf,inf,75.1,inf,30.8,0,243.3,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%8 -% inf,inf,inf,inf,inf,inf,inf,243.3,0,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,167.6;%9 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,0,28.8,inf,28.8,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf;%10 -% inf,inf,inf,inf,inf,55.0,inf,inf,inf,28.8,0,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%11 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,0,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%12 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,28.8,inf,10,0,67.7,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%13 -% inf,inf,inf,86.5,inf,inf,inf,inf,inf,inf,inf,inf,67.7,0,145.4,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%14 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,145.4,0,63,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%15 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,63,0,59.7,inf,130.7,inf,90.5,inf,inf,39.5,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%16 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,59.7,0,55,inf,inf,inf,inf,inf,inf,inf,inf,116,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%17 -% inf,inf,89.1,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,55,0,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%18 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,130.7,inf,inf,0,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf;%19 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,0,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf;%20 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,90.5,inf,inf,inf,inf,0,93.8,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%21 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,93.8,0,64.3,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf;%22 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,64.3,0,234.6,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf;%23 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,39.5,inf,inf,inf,inf,inf,inf,234.6,0,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%24 -% inf,57.6,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,216.5,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf;%25 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,216.5,0,98.5,317.7,418.9,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%26 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,116,inf,inf,inf,inf,inf,inf,inf,inf,98.5,0,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%27 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,317.7,inf,0,101.2,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf;%28 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,418.9,inf,101.2,0,inf,inf,inf,inf,inf,inf,inf,inf,10,inf;%29 -% inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf,inf,inf,inf,inf,inf,inf;%30 -% inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf,inf,inf,inf,inf,inf;%31 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf,inf,inf,inf,inf;%32 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf,inf,inf,inf;%33 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf,inf,inf;%34 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf,inf;%35 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf,inf;%36 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0,inf,inf;%37 -% inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,10,inf,inf,inf,inf,inf,inf,inf,inf,0,inf;%38 -% 167.6,inf,inf,inf,inf,inf,inf,inf,167.6,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,inf,0];%39 -if k == 1 % instance 1 - indBS = [30,31]; - indNBS = 32:39; -elseif k == 2 - indBS = [32,36]; - indNBS = [30:31,33:35,37:39]; -end -indLoad = [1,3,4,7,8,9,12,15,16,18,20,21,23:29,31,39]; -end \ No newline at end of file diff --git a/matlab/Problems/Real-World/blackstart/weight.xlsx b/matlab/Problems/Real-World/blackstart/weight.xlsx deleted file mode 100644 index 2416dec..0000000 Binary files a/matlab/Problems/Real-World/blackstart/weight.xlsx and /dev/null differ diff --git a/matlab/Problems/Real-World/blackstart/~$adjacent.xlsx b/matlab/Problems/Real-World/blackstart/~$adjacent.xlsx deleted file mode 100644 index 0fe2f8c..0000000 Binary files a/matlab/Problems/Real-World/blackstart/~$adjacent.xlsx and /dev/null differ diff --git a/matlab/Problems/prob_name.m b/matlab/Problems/prob_name.m deleted file mode 100644 index 8b8d1e3..0000000 --- a/matlab/Problems/prob_name.m +++ /dev/null @@ -1,83 +0,0 @@ -function [output1,output2,output3] = prob_name(varargin) -% Template for writing problem file. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'construct' % define problem properties - Problem = varargin{1}; - % define problem type in the following three cells. - % first cell : 'continuous'\'discrete'\'permutation' - % second cell: 'static'\'sequential' - % third cell : 'certain'\'uncertain' - Problem.type = {'','',''}; - - % define the bound of solution space - lower = []; % 1*D, lower bound of the D-dimension decision space - upper = []; % 1*D, upper bound of the D-dimension decision space - Problem.bound = [lower;upper]; - - % define specific settings (optional), options: - % 'dec_diff' : elements of the solution should be different w.r.t each other for discrete problems - % 'uncertain_average': averaging the fitness over multiple fitness evaluations for uncertain problems - % 'uncertain_worst' : use the worse fitness among multiple fitness evaluations as the fitness for uncertain problems - Problem.setting = {''}; % put choice(s) into the cell - - % set the number of samples for uncertain problems (optional) - Problem.sampleN = []; - - output1 = Problem; - - % load/construct data file in the following - Data = load(''); % for .mat format -% Data = readmatrix('','Sheet',1); % for .xlsx format - output2 = Data; - - case 'repair' % repair solutions - Data = varargin{1}; - Decs = varargin{2}; - % define methods for repairing solutions in the following - - output1 = Decs; - - case 'evaluate' % evaluate solution's fitness - Data = varargin{1}; % load problem data - Decs = varargin{2}; % load the current solution(s) - - % define the objective function in the following - - % define the inequal constraint(s) in the following, equal constraints should be transformed to inequal ones - - % calculate the constraint violation in the following - - % collect accessory data for understanding the solutions in the following (optional) - - output1 = ; % matrix for saving objective function values - output2 = ; % matrix for saving constraint violation values (optional) - output3 = ; % matrix or cells for saving accessory data (optional), a solution's accessory data should be saved in a row -end - -if ~exist('output2','var') - output2 = []; -end -if ~exist('output3','var') - output3 = []; -end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/DESIGN.m b/matlab/Utilities/@DESIGN/DESIGN.m deleted file mode 100644 index 6696479..0000000 --- a/matlab/Utilities/@DESIGN/DESIGN.m +++ /dev/null @@ -1,170 +0,0 @@ -% Class for designing algorithms - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -classdef DESIGN < handle - properties (SetAccess = private) - operator; - parameter; - operatorPheno; - parameterPheno; - performance; - performanceApprox; - end - - methods - %% initialize the designed algorithms - function obj = DESIGN(varargin) - if nargin > 0 - Problem = varargin{1}; - Setting = varargin{2}; - if nargin == 3 - N = varargin{3}; - else - N = Setting.AlgN; - end - obj(1,N) = DESIGN; - [Operators,Paras] = obj.Initialize(Setting,N); - [Operators,Paras] = obj.Repair(Operators,Paras,Problem,Setting); - for i = 1:N - obj(i).operator = Operators(i,:); - obj(i).parameter = Paras{i}; - [currOp,currPara] = obj.Decode(Operators(i,:),Paras{i},Problem,Setting); - obj(i).operatorPheno = currOp; - obj(i).parameterPheno = currPara; - obj(i).performance = zeros(length(Problem),Setting.AlgRuns); - obj(i).performanceApprox = zeros(length(Problem),Setting.AlgRuns); - end - end - end - - %% design new algorithms based on the current ones - function [objNew,Aux] = GetNew(obj,Problem,Setting,innerG,Aux) - [NewOp,NewPara,Aux] = obj.Disturb(Setting,innerG,Aux); - [Operators,Paras] = obj.Repair(NewOp,NewPara,Problem,Setting); - objNew(1,Setting.AlgN) = DESIGN; - for i = 1:Setting.AlgN - objNew(i).operator = Operators(i,:); - objNew(i).parameter = Paras{i}; - [currOp,currPara] = objNew.Decode(Operators(i,:),Paras{i},Problem,Setting); - objNew(i).operatorPheno = currOp; - objNew(i).parameterPheno = currPara; - objNew(i).performance = zeros(length(Problem),Setting.AlgRuns); - objNew(i).performanceApprox = zeros(length(Problem),Setting.AlgRuns); - end - end - - %% get algorithms' average performance or statistically comparing results - function value = GetPerformance(obj,Setting,seedInstance) - allPerform = zeros(numel(seedInstance)*Setting.AlgRuns,length(obj)); - for i = 1:length(obj) - % reshape algorithm i's all performance values (each run on each instance) to a column vector - if strcmp(Setting.Evaluate,'approximate') && sum(obj(i).performanceApprox,'all') ~= 0 && sum(obj(i).performance,'all') == 0 - allPerform(:,i) = reshape(obj(i).performanceApprox(seedInstance,:)',size(allPerform,1),1); - else - allPerform(:,i) = reshape(obj(i).performance(seedInstance,:)',size(allPerform,1),1); - end - end - switch Setting.Compare - case 'average' - value = mean(allPerform,1); - case 'statistic' - [~,~,stats] = friedman(allPerform,1,'off'); - value = multcompare(stats,'Display','off'); - end - end - - %% design new algorithms based on the current ones - [NewOp,NewPara,Aux] = Disturb(obj,Problem,Setting,innerG,Aux) - - %% exactly evaluate algorithms' performance - [obj,Solution] = Evaluate(obj,Problem,Data,Setting,indInstance) - - %% approximatly estimate algorithms' performance - obj = Estimate(obj,Problem,Setting,indInstance,Surrogate) - - %% select algorithms - Algs = Select(obj,Problem,Data,Setting,indInstance) - - function obj = Construct(obj,operator,parameter) - obj.operatorPheno = operator; - obj.parameterPheno = parameter; - end - - function obj = Construct2(obj,Operators,Paras,Problem,Setting) - [Operators,Paras] = obj.Repair(Operators,Paras,Problem,Setting); - obj.operator = Operators; - obj.parameter = Paras; - [currOp,currPara] = obj.Decode(Operators,Paras,Problem,Setting); - obj.operatorPheno = currOp; - obj.parameterPheno = currPara; - obj.performance = zeros(length(Problem),Setting.AlgRuns); - obj.performanceApprox = zeros(length(Problem),Setting.AlgRuns); - end - - function value = avePerformAll(obj) - value = zeros(length(obj),1); - for i = 1:length(obj) - value(i) = mean(obj(i).performance,'all'); - end - end - - function value = avePerformApproxAll(obj) - value = zeros(length(obj),1); - for i = 1:length(obj) - value(i) = mean(obj(i).performanceApprox,'all'); - end - end - - function value = avePerformPer(obj,ind) - value = zeros(length(obj),1); - for i = 1:length(obj) - value(i) = mean(obj(i).performance(ind,:)); - end - end - - function value = avePerformApproxPer(obj,ind) - value = zeros(length(obj),1); - for i = 1:length(obj) - value(i) = mean(obj(i).performanceApprox(ind,:)); - end - end - end - - methods(Static) - % initialize graph representations of the designed algorithms - [Operators,Paras] = Initialize(Problem,Setting,N) - - % repair the designed algorithms to ensure the algorithms' reasonability - [Operators,Paras,Change] = Repair(Operators,Paras,Problem,Setting) - - % decode the designed algorithms from their graph representations - [currOp,currPara] = Decode(Operators,Paras,Problem,Setting) - - % encode the action as the graph representation of the algorithm - [Operators,Paras] = Encode(Action,Setting,AlgN); - - % search algorithms via heuristics - [Algs,AlgTrace] = Search(Problem,Data,Setting,seedTrain,app,bar); - - % learn the algorithm distribution via transformer and reinforcement learning - [Algs,AlgTrace] = Learn(Problem,Data,Setting,seedTrain,app,bar); - end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Decode.m b/matlab/Utilities/@DESIGN/Decode.m deleted file mode 100644 index b27b89d..0000000 --- a/matlab/Utilities/@DESIGN/Decode.m +++ /dev/null @@ -1,84 +0,0 @@ -function [currOp,currPara] = Decode(Operator,Para,Problem,Setting) -% Decode the designed algorithm from the graph representation. -% Operator: 1*P, P search pathways -% Para : 1*P, P search pathways - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -AllOp = Setting.AllOp; -rate = Setting.IncRate; -innerGmax = ceil(Setting.Conds/Setting.ProbN); - -switch Problem(1).type{1} - case 'continuous' - indMu = find(contains(AllOp,'search_mu')); - case {'discrete','permutation'} - indMu = find(contains(AllOp,'search')); -end -indCross = find(contains(AllOp,'cross')); -currOp = cell(1,Setting.AlgP); -currPara = cell(1,Setting.AlgP); - -for i = 1:Setting.AlgP % for each search pathway - currOp{i}.Choose = AllOp{Operator{i}(1,1)}; - currOp{i}.Search = cell(size(Operator{i},1)-1,3); % number of search operators * 3 - currOp{i}.Update = AllOp{Operator{i}(end,end)}; - currOp{i}.Archive = Setting.Archive; - - currPara{i}.Choose = Para{strcmp(currOp{i}.Choose,AllOp),1}; - currPara{i}.Search = cell(size(Operator{i},1)-1,2); % number of search operators * 2 - currPara{i}.Update = Para{strcmp(currOp{i}.Update,AllOp),1}; - - j = 2; - while j <= size(Operator{i},1) - % set search operators and their parameters - thisSearchInd = Operator{i}(j,1); - thisSearchIndNext = Operator{i}(j,2); - currOp{i}.Search{j-1,1} = AllOp{thisSearchInd}; - currPara{i}.Search{j-1,1} = Para{thisSearchInd,1}; - if ismember(thisSearchInd,indCross) && ismember(thisSearchIndNext,indMu) - % put mutation operator to the second column - currOp{i}.Search{j-1,2} = AllOp{thisSearchIndNext}; - currPara{i}.Search{j-1,2} = Para{thisSearchIndNext,1}; - % set search operators' termination conditions - if strcmp(Para{thisSearchInd,2},'GS') || strcmp(Para{thisSearchIndNext,2},'GS') - currOp{i}.Search{j-1,3} = [-inf,1]; % global search operator terminates after 1 iteration - else - currOp{i}.Search{j-1,3} = [rate,innerGmax(thisSearchInd)]; - end - % jump to the row after the next row of the Operator matrix - j = j+2; - else - % set search operators' termination conditions - if strcmp(Para{thisSearchInd,2},'GS') - currOp{i}.Search{j-1,3} = [-inf,1]; - else - currOp{i}.Search{j-1,3} = [rate,innerGmax(thisSearchInd)]; - end - j = j+1; - end - end - - % delete empty rows - rowDelete = cellfun(@isempty,currOp{i}.Search(:,1)); - currOp{i}.Search(rowDelete,:) = []; - currPara{i}.Search(rowDelete,:) = []; -end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Disturb.m b/matlab/Utilities/@DESIGN/Disturb.m deleted file mode 100644 index d7fd5e2..0000000 --- a/matlab/Utilities/@DESIGN/Disturb.m +++ /dev/null @@ -1,168 +0,0 @@ -function [NewOp,NewPara,Aux]= Disturb(Algs,Setting,innerG,Aux) -% Design new algorithm(s) based on the current ones. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -OpSpace = Setting.OpSpace; -ParaSpace = Setting.ParaSpace; -ParaLocalSpace = Setting.ParaLocalSpace; - -% get indices of non-empty parameters -indNonEmptyPara = find(~cellfun(@isempty,ParaSpace)==1); - -NewOp = cell(Setting.AlgN,Setting.AlgP); -NewPara = cell(Setting.AlgN,1); -for i = 1:Setting.AlgN - thisOp = Algs(i).operator; % 1*P cells - thisPara = Algs(i).parameter; % 1*1 cells - - % extract indices of operators and non-empty parameters - indSearch = []; - for j = 1:Setting.AlgP - indSearch = [indSearch;thisOp{j}(2:end,1)]; - end - indOp = [thisOp{1}(1,1);indSearch;thisOp{1}(end,end)]; % indices of operators - indPara = indNonEmptyPara(ismember(indNonEmptyPara,indOp)); % indices of parameters - - % determine where to disturb - if innerG == 1 - if Setting.TunePara == false - probOp = 1/(numel(indOp)+numel(indPara)); % probability of disturbing an operator - probPara = probOp*numel(indPara); % probability of disturbing all parameters - prob = [repmat(probOp,1,numel(indOp)),probPara]; - if numel(OpSpace(1,1):OpSpace(1,2)) == 1 - prob(1) = 0; - end - if numel(OpSpace(2,1):OpSpace(2,2)) == 1 - prob(2:numel(indOp)-1) = 0; - end - if numel(OpSpace(3,1):OpSpace(3,2)) == 1 - prob(numel(indOp)) = 0; - end - Aux{i}.seed = randsrc(1,1,[1:numel(indOp)+1;prob./sum(prob)]); - else % always disturb parameters - Aux{i}.seed = numel(indOp)+1; - end - end - - % disturb - seed = Aux{i}.seed; - if seed <= numel(indOp) - % disturb an operator - if seed == 1 - % disturb the choose operator - indPool = OpSpace(1,1):OpSpace(1,2); - indPool(indPool == indOp(seed)) = []; - indNew = datasample(indPool,1); - for j = 1:Setting.AlgP - thisOp{j}(1,1) = indNew; - end - elseif seed == numel(indOp) - % disturb the update operator - indPool = OpSpace(3,1):OpSpace(3,2); - indPool(indPool == indOp(seed)) = []; - indNew = datasample(indPool,1); - for j = 1:Setting.AlgP - thisOp{j}(end,end) = indNew; - end - else - % disturb the search operator - if Setting.AlgP == 1 - % a single search pathway - indPool = OpSpace(2,1):OpSpace(2,2); - indPool(indPool==indOp(seed)) = []; - indNew = datasample(indPool,1); - if numel(indSearch) == 1 && numel(indSearch) < Setting.AlgQ - samplePool = [indPool,+inf]; % +inf: add an operator after the current one - elseif numel(indSearch) > 1 && numel(indSearch) < Setting.AlgQ - samplePool = [indPool,+inf,-inf]; % -inf: delete the current operator - elseif numel(indSearch) > 1 && numel(indSearch) == Setting.AlgQ - samplePool = [indPool,-inf]; - else - samplePool = indPool; - end - sampleInd = datasample(samplePool,1); - if sampleInd == +inf - thisOp{1} = [thisOp{1}(1:seed,:);zeros(1,2);thisOp{1}(seed+1:end,:)]; - thisOp{1}(seed+1,:) = [indNew,thisOp{1}(seed,2)]; - thisOp{1}(seed,2) = indNew; - elseif sampleInd == -inf - thisOp{1}(seed-1,2) = thisOp{1}(seed,2); - thisOp{1}(seed,:) = []; - else - thisOp{1}(seed,1) = indNew; - thisOp{1}(seed-1,2) = indNew; - end - else - % multiple search pathways - indPath = []; - for j = 1:Setting.AlgP - numSearch = size(thisOp{j},1)-1; % number of search operators in pathway j - indPath = [indPath,repmat(j,1,numSearch)]; % indices of search pahways that search operators belong to - end - thisPath = indPath(seed-1); - indChoose = thisOp{thisPath}(1,1); - indUpdate = thisOp{thisPath}(end,end); - currQ = randi(Setting.AlgQ); % number of search operators in the (seed-1)-th search pathway - thisOp{thisPath} = zeros(currQ+1,2); - indSearch = randi([OpSpace(2,1),OpSpace(2,2)]); - thisOp{thisPath}(1,:) = [indChoose,indSearch]; - indSearchStart = indSearch; - for k = 2:currQ - indSearchEnd = randi([OpSpace(2,1),OpSpace(2,2)]); - thisOp{thisPath}(k,:) = [indSearchStart,indSearchEnd]; - indSearchStart = indSearchEnd; - end - thisOp{thisPath}(end,:) = [indSearchStart,indUpdate]; - end - end - else - % disturb all parameters - currPara = []; - currParaSpace = []; - for j = 1:numel(indPara) % extract parameter values and parameter space - for k = 1: numel(thisPara{indPara(j),1}) % for each parameter of operator indPara(j) - currPara = [currPara,thisPara{indPara(j),1}(k)]; - end - if strcmp(thisPara{indPara(j),2},'LS') - currParaSpace = [currParaSpace;ParaLocalSpace{indPara(j)}]; - else - currParaSpace = [currParaSpace;ParaSpace{indPara(j)}]; - end - end - if Setting.AlgN == 1 - [currPara,Aux{i}] = search_cma(currPara,currParaSpace',Aux{i},'algorithm'); - else - [currPara,~] = search_mu_polynomial(currPara,currParaSpace','algorithm'); - end - % insert new parameters to NewPara - for j = 1:numel(indPara) - for k = 1:numel(thisPara{indPara(j),1}) - thisPara{indPara(j),1}(k) = currPara(1); - currPara(1) = []; - end - end - end - - for j = 1:Setting.AlgP - NewOp{i,j} = thisOp{j}; - end - NewPara{i} = thisPara; -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Encode.m b/matlab/Utilities/@DESIGN/Encode.m deleted file mode 100644 index b7e0400..0000000 --- a/matlab/Utilities/@DESIGN/Encode.m +++ /dev/null @@ -1,97 +0,0 @@ -function [Operators,Paras] = Encode(Action,Setting,AlgN) -% Encode the action to the graph representation of the algorithm. -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -OpSpace = Setting.OpSpace; -ParaSpace = Setting.ParaSpace; -Operators = cell(AlgN,Setting.AlgP); -Paras = cell(AlgN,1); -Action = reshape(Action,3,numel(Action)/3)'; % one row for one operator - -numChoose = OpSpace(1,2)-OpSpace(1,1)+1; -numSearch = OpSpace(2,2)-OpSpace(2,1)+1; -numUpdate = OpSpace(3,2)-OpSpace(3,1)+1; - -for i = 1:AlgN - %% encode operators to graph edges - for j = 1:Setting.AlgP - Operators{i,j} = zeros(Setting.AlgQ+1,2); - - % get operators' indexes - indChoose = ceil(Action(1,1)*numChoose); - indSearch = zeros(size(Action,1)-2,1); - for k = 1:length(indSearch) - indSearch(k) = ceil(Action(k+2,1)*numSearch)+numChoose; - end - indUpdate = ceil(Action(2,1)*numUpdate)+numChoose+numSearch; - - % encode indexes to graph edges - Operators{i,j}(1,:) = [indChoose,indSearch(1)]; - indSearchStart = indSearch(1); - for k = 2:numel(indSearch) - indSearchEnd = indSearch(k); - Operators{i,j}(k,:) = [indSearchStart,indSearchEnd]; - indSearchStart = indSearchEnd; - end - Operators{i,j}(end,:) = [indSearch(end),indUpdate]; - end - - %% encode parameters - % initialize all operators' parameters - tempPara = cell(length(ParaSpace),2); - indNonEmptyPara = find(~cellfun(@isempty,ParaSpace)==1); - for j = 1:numel(indNonEmptyPara) - k = indNonEmptyPara(j); - tempPara{k,1} = ParaSpace{k}(:,1)+(ParaSpace{k}(:,2)-ParaSpace{k}(:,1)).*rand(size(ParaSpace{k},1),1); - end - - % replease the involved operators' parameters with ones given by the action - j = 1; choosePara = []; - while j <= size(ParaSpace{indChoose},1) % for each parameter - choosePara = [choosePara;Action(1,1+j)]; - j = j+1; - end - if ~isempty(choosePara) - tempPara{indChoose,1} = ParaSpace{indChoose}(:,1)+choosePara.*(ParaSpace{indChoose}(:,2)-ParaSpace{indChoose}(:,1)); - end - - for j = 1:numel(indSearch) - k = 1; searchPara = []; - while k <= size(ParaSpace{indSearch(j)},1) - searchPara = [searchPara;Action(2+j,1+k)]; - k = k+1; - end - if ~isempty(searchPara) - tempPara{indSearch(j),1} = ParaSpace{indSearch(j)}(:,1)+searchPara.*(ParaSpace{indSearch(j)}(:,2)-ParaSpace{indSearch(j)}(:,1)); - end - end - - j = 1; updatePara = []; - while j <= size(ParaSpace{indUpdate},1) - updatePara = [updatePara;Action(2,1+j)]; - j = j+1; - end - if ~isempty(updatePara) - tempPara{indUpdate,1} = ParaSpace{indUpdate}(:,1)+updatePara.*(ParaSpace{indUpdate}(:,2)-ParaSpace{indUpdate}(:,1)); - end - - Paras{i} = tempPara; -end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Estimate.m b/matlab/Utilities/@DESIGN/Estimate.m deleted file mode 100644 index d469e7f..0000000 --- a/matlab/Utilities/@DESIGN/Estimate.m +++ /dev/null @@ -1,30 +0,0 @@ -function NewAlgs = Estimate(NewAlgs,Problem,Setting,indInstance,Surrogate) -% Estimate the designed algorithm's performance by a surrogate model. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -EmbedAlgs = Surrogate.UseEmbed(NewAlgs,Setting); - -for i = 1:length(NewAlgs) - for j = 1:length(Problem(indInstance)) - NewAlgs(i).performanceApprox(indInstance(j),:) = predict(Surrogate.model,EmbedAlgs(i,:)); - end -end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Evaluate.m b/matlab/Utilities/@DESIGN/Evaluate.m deleted file mode 100644 index 50f711c..0000000 --- a/matlab/Utilities/@DESIGN/Evaluate.m +++ /dev/null @@ -1,219 +0,0 @@ -function [NewAlgs,Solution] = Evaluate(NewAlgs,Problem,Data,Setting,seedInstance) -% Evaluate the designed algorithm's performance. Save all solutions -% generated during algorithm execution, for calculating landscape features. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. -%-------------------------------------------------------------------------- - -Solution = cell(numel(seedInstance),1); -for i = 1:length(NewAlgs) - Operator = NewAlgs(i).operatorPheno; - Parameter = NewAlgs(i).parameterPheno; - Performance = NewAlgs(i).performance; - for j = 1:length(Problem(seedInstance)) - this_ins_Solution = SOLVE; % for saving all solutions that the algorithm generated in the instance - switch Problem(seedInstance(j)).type{2} - case 'static' - for k = 1:Setting.AlgRuns - [ArchSolution,AllSolution,t] = RunDesign(Operator,Parameter,Problem(seedInstance(j)),Data(seedInstance(j)),Setting); - % save result for draw convergence curve in python - if Setting.AlgRuns == 1 - %save(['ArchSolution',int2str(Setting.Problem_id)],'ArchSolution'); - end - switch Setting.Metric - case 'quality' % solution quality as performance metric - Performance(seedInstance(j),k) = min(ArchSolution.fits); % best performance - case {'runtimeFE','runtimeSec'} % running time as performance metric - Performance(seedInstance(j),k) = t; - case 'auc' % AUC as performance metric - TimePoints = ceil(Setting.Tmax./Setting.ProbN); % time (Tmax) should be function evaluations when using auc - Performance(seedInstance(j),k) = 1/(sum(ArchSolution(TimePoints).fits <= Setting.Thres')/numel(TimePoints)+eps); % 1/AUC, the smaller the better performance - end - this_ins_Solution = [this_ins_Solution,AllSolution]; - end - - case 'sequential' - for k = 1:Setting.AlgRuns - while Data(seedInstance(j)).continue == true - [ArchSolution,AllSolution,t] = RunDesign(Operator,Parameter,Problem(seedInstance(j)),Data(seedInstance(j)),Setting); - switch Setting.Metric - case 'quality' - Performance(seedInstance(j),k) = Performance(seedInstance(j),k) + min(ArchSolution.fits); - case {'runtimeFE','runtimeSec'} - Performance(seedInstance(j),k) = Performance(seedInstance(j),k) + t; - case 'auc' - TimePoints = ceil(Setting.Tmax./Setting.ProbN); - Performance(seedInstance(j),k) = Performance(seedInstance(j),k) + 1/sum(ArchSolution(TimePoints).fits <= Setting.QuaThres)/numel(TimePoints); - end - % update the current instance of the problem sequence - [~,best] = min(ArchSolution.fits); - [thisProblem,thisData,~] = feval(str2func(Problem(seedInstance(j)).name),Problem(seedInstance(j)),Data(seedInstance(j)),ArchSolution(best),'sequence'); - Problem(seedInstance(j)) = thisProblem; - Data(seedInstance(j)) = thisData; - this_ins_Solution = [this_ins_Solution,AllSolution]; - end - end - end - this_ins_Solution = this_ins_Solution(2:end); % delete the first empty solution - Solution{j} = [Solution{j},this_ins_Solution]; - end - NewAlgs(i).performance = Performance; -end -end - -function [ArchSolution,AllSolution,t] = RunDesign(Operator,Para,Problem,Data,Setting) -% Problem.bound: 2*D for continuous and discrete problems, 2*1 for permutation problem -% Problm.N : number of solutions to the targeted problem instance -% Operator : 1*P, P search pathways -% Para : 1*P, P search pathways - -% initialize solution(s) -switch Problem.type{1} - case 'continuous' - Lower = Problem.bound(1,:); - Upper = Problem.bound(2,:); - dec = unifrnd(repmat(Lower,Problem.N,1),repmat(Upper,Problem.N,1)); - case 'discrete' - D = size(Problem.bound,2); % size of the solution space - dec = zeros(Problem.N,D); - for j = 1:D - dec(:,j) = randi([Problem.bound(1,j),Problem.bound(2,j)],Problem.N,1); - end - case 'permutation' - [~,dec] = sort(rand(Problem.N,Problem.bound(end)),2); -end -Solution = SOLVE(dec,Problem,Data); - -% initialize archive(s) -Archive = cell(length(Operator{1}.Archive),1); -for i = 1:length(Operator{1}.Archive) - [Archive{i},~] = feval(str2func(Operator{1}.Archive{i}),Solution,Problem,'execute'); -end -ArchSolution = Solution(randi(Problem.N)); % the best solution found at each iteration, Gmax*1 -AllSolution = Solution; % all solutions found during algorithm execution -Aux = cell(1,Setting.AlgP); -for i = 1:Setting.AlgP - Aux{i} = struct; % auxiliary structure array -end - -% iterate -G = 1; -t = 0; -switch Setting.Metric - case {'quality','auc'} - Tmax = +inf; - Thres = -inf; - case 'runtimeFE' - Tmax = ceil(Setting.Tmax./Setting.ProbN); % time changes to interation G - Thres = Setting.Thres; - case 'runtimeSec' - Tmax = Setting.Tmax; - Thres = Setting.Thres; -end -if Setting.AlgP == 1 % if the designed algorithm has a single search pathway - while G <= Problem.Gmax && t < Tmax && min(ArchSolution.fits) > Thres - tic; - for i = 1:size(Operator{1}.Search,1) % for each search operation - improve = 1; - innerG = 1; - while improve(1) >= Operator{1}.Search{i,end}(1) && innerG <= Operator{1}.Search{i,end}(2) % termination condition of search operator i - % choose where to search from - [ind,~] = feval(str2func(Operator{1}.Choose),Solution,Problem,Para{1}.Choose,Aux{1},G,innerG,Data,'execute'); - - % search from the chosen solution(s) - [New,Aux{1}] = feval(str2func(Operator{1}.Search{i,1}),Solution(ind),Problem,Para{1}.Search{i,1},Aux{1},G,innerG,Data,'execute'); - if ~isempty(Operator{1}.Search{i,2}) % if designed a sexual evolutonary algorithm with crossover and mutation - New = SOLVE.RepairSol(New,Problem); - [New,Aux{1}] = feval(str2func(Operator{1}.Search{i,2}),New,Problem,Para{1}.Search{i,2},Aux{1},G,innerG,Data,'execute'); - end - New = SOLVE(New,Problem,Data); - AllSolution = [AllSolution,New]; - - if strcmp(Operator{1}.Search{i,1},'search_pso') % update pbest and gbest for PSO' particle fly operator - Aux{1} = para_pso(New,Problem,Aux{1}); - elseif strcmp(Operator{1}.Search{i,1},'search_cma') % update parameters for CMA-ES - Aux{1} = para_cma(New,Problem,Aux{1},'solution'); - end - - % update solution(s) - [Solution,~] = feval(str2func(Operator{1}.Update),[Solution,New],Problem,Para{1}.Update,Aux{1},G,innerG,Data,'execute'); - - % update archive(s) - for j = 1:length(Operator{1}.Archive) - [Archive{i},~] = feval(str2func(Operator{1}.Archive{j}),Solution,Archive{i},Problem,'execute'); - end - [ArchSolution,~] = archive_best(Solution,ArchSolution,'execute'); - - improve = ImproveRate(Solution,improve,innerG,'solution'); - innerG = innerG+1; - G = G+1; - if strcmp(Setting.Metric,'runtimeFE') - t = G; - elseif strcmp(Setting.Metric,'runtimeSec') - t = t +toc; - end - if G > Problem.Gmax || t >= Tmax || min(ArchSolution.fits) <= Thres - break - end - end - if G > Problem.Gmax || t >= Tmax || min(ArchSolution.fits) <= Thres - break - end - end - end - -elseif Setting.AlgP > 1 % if the designed algorithm has multiple search pathways - eachN = round(Setting.ProbN*(1/Setting.AlgP)); - innerG = 1; - while G <= Problem.Gmax && t < Tmax && min(ArchSolution.fits) > Thres - tic; - % choose where to search from - [ind,~] = feval(str2func(Operator{1}.Choose),Solution,Problem,Para{1}.Choose,Aux{i},G,innerG,Data,'execute'); - - % search from the chosen solution(s) - allNew = []; - for i = 1:Setting.AlgP - % determine indices of solutions to be searched from - if i == Setting.AlgP - currInd = ind; - else - currInd = ind(1:eachN); - ind(1:eachN) = []; % delete used indices - end - % search - [New,Aux{i}] = feval(str2func(Operator{i}.Search{1}),Solution(currInd),Problem,Para{i}.Search{1},Aux{i},G,innerG,Data,'execute'); - New = SOLVE(New,Problem,Data); - if strcmp(Operator{i}.Search{1},'search_pso') % update pbest and gbest for PSO' particle fly operator - Aux{i} = para_pso(New,Problem,Aux{i}); - elseif strcmp(Operator{i}.Search{1},'search_cma') % update parameters for CMA-ES - Aux{i} = para_cma(New,Problem,Aux{i},'solution'); - end - allNew = [allNew,New]; - AllSolution = [AllSolution,allNew]; - end - - % update solution(s) - [Solution,~] = feval(str2func(Operator{1}.Update),[Solution,allNew],Problem,Para{1}.Update,Aux{i},G,innerG,Data,'execute'); - - % update archive(s) - for i = 1:length(Operator{1}.Archive) - [Archive{i},~] = feval(str2func(Operator{1}.Archive{i}),Solution,Archive{i},Problem,'execute'); - end - [ArchSolution,~] = archive_best(Solution,ArchSolution,'execute'); - - innerG = innerG+1; - G = G+1; - if strcmp(Setting.Metric,'runtimeFE') - t = G; - elseif strcmp(Setting.Metric,'runtimeSec') - t = t + toc; - end - end -end -end diff --git a/matlab/Utilities/@DESIGN/Initialize.m b/matlab/Utilities/@DESIGN/Initialize.m deleted file mode 100644 index d570deb..0000000 --- a/matlab/Utilities/@DESIGN/Initialize.m +++ /dev/null @@ -1,62 +0,0 @@ -function [Operators,Paras] = Initialize(Setting,N) -% Initialize the designed algorithm(s). - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -OpSpace = Setting.OpSpace; -ParaSpace = Setting.ParaSpace; -Operators = cell(N,Setting.AlgP); % N algorithms, each with AlgP search -% pathways. Each cell contains a number of AlgP matrix within edges of the graph -% representation of a designed algorithm -Paras = cell(N,1); % parameters of N algorithms -for i = 1:N - % initialize operators - indChoose = randi([OpSpace(1,1),OpSpace(1,2)]); % different search pathways use the same choose operator - indUpdate = randi([OpSpace(3,1),OpSpace(3,2)]); % different search pathways use the same update operator - for j = 1:Setting.AlgP -% currQ = Setting.AlgQ; - currQ = randi(Setting.AlgQ); % number of search operators in the current search pathway - Operators{i,j} = zeros(currQ+1,2); - - indSearch = randi([OpSpace(2,1),OpSpace(2,2)]); - Operators{i,j}(1,:) = [indChoose,indSearch]; - - indSearchStart = indSearch; - for k = 2:currQ - indSearchEnd = randi([OpSpace(2,1),OpSpace(2,2)]); - Operators{i,j}(k,:) = [indSearchStart,indSearchEnd]; - indSearchStart = indSearchEnd; - end - - Operators{i,j}(end,:) = [indSearchStart,indUpdate]; - end - % initialize parameters - tempPara = cell(length(ParaSpace),2); % first column of each row - % contains a cloumn vector of an operator's parameter values, - % second column will contain a string of whether the operator - % performs local or global search behavior. - indNonEmptyPara = find(~cellfun(@isempty,ParaSpace)==1); - for j = 1:numel(indNonEmptyPara) - k = indNonEmptyPara(j); - tempPara{k,1} = ParaSpace{k}(:,1)+(ParaSpace{k}(:,2)-ParaSpace{k}(:,1)).*rand(size(ParaSpace{k},1),1); - end - Paras{i} = tempPara; -end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Learn.m b/matlab/Utilities/@DESIGN/Learn.m deleted file mode 100644 index 2d2e671..0000000 --- a/matlab/Utilities/@DESIGN/Learn.m +++ /dev/null @@ -1,68 +0,0 @@ -function [Algs,AlgTrace]= Learn(Problem,Data,Setting,seedTrain,app,bar) -% Learn the algorithm distribution via transformer and reinforcement learning -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -str = 'Designing... '; -if ~isempty(app) - app.TextArea.Value = str; - drawnow; -else - waitbar(100,bar,str); -end - -% train transformer - - -Algs = getAlg(Action,Problem,Data,Setting,seedTrain); % get the algorithm from the action -p = Algs.GetPerformance(Setting,seedTrain); % algorithm's performance - - -% output the final algorithm -Algs = getAlg(Action,Problem,Data,Setting,seedTrain); -AlgTrace = Algs; -end - -function Algs = getAlg(Action,Problem,Data,Setting,seedTrain) -% get the algorithm from the action - -AlgN = 1; % number of algorithms to be evaluated -obj = DESIGN; - -% encode the action as the graph representation of the algorithm -[Operators,Paras] = obj.Encode(Action,Setting,AlgN); - -% repair the algorithm to keep it to be feasible -[Operators,Paras] = obj.Repair(Operators,Paras,Problem,Setting); - -% construct the algorithm struct -Algs(1,AlgN) = DESIGN; -for i = 1:AlgN - Algs(i).operator = Operators(i,:); - Algs(i).parameter = Paras{i}; - [currOp,currPara] = Algs.Decode(Operators(i,:),Paras{i},Problem,Setting); - Algs(i).operatorPheno = currOp; - Algs(i).parameterPheno = currPara; - Algs(i).performance = zeros(length(Problem),Setting.AlgRuns); - Algs(i).performanceApprox = zeros(length(Problem),Setting.AlgRuns); -end - -% evaluate the algorithm -Algs = Algs.Evaluate(Problem,Data,Setting,seedTrain); -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Repair.m b/matlab/Utilities/@DESIGN/Repair.m deleted file mode 100644 index 920a755..0000000 --- a/matlab/Utilities/@DESIGN/Repair.m +++ /dev/null @@ -1,132 +0,0 @@ -function [Operators,Paras,Change] = Repair(Operators,Paras,Problem,Setting) -% Ensure the designed algorithm(s) to be reasonable. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -AllOp = Setting.AllOp; -ParaLocalSpace = Setting.ParaLocalSpace; -BehavSpace = Setting.BehavSpace; -Change = 0; -Back_operators = Operators; - -switch Problem(1).type{1} - case 'continuous' - indMu = find(contains(AllOp,'search_mu')); - case {'discrete','permutation'} - indMu = find(contains(AllOp,'search')); -end -indCross = find(contains(AllOp,'cross')); - -for i = 1:size(Operators,1) - for j = 1:Setting.AlgP - % crossover should be followed by mutation - for k = 2:size(Operators{i,j},1)-1 - if ismember(Operators{i,j}(k,1),indCross) && ~ismember(Operators{i,j}(k,2),indMu) - indThisMu = datasample(indMu,1); - Operators{i,j}(k,2) = indThisMu; - Operators{i,j}(k+1,1) = indThisMu; - %debug = 1 - end - end - % crossover should not be the last search operator - if ismember(Operators{i,j}(end,1),indCross) - thisIndMu = datasample(indMu,1); - Operators{i,j}(end,1) = thisIndMu; - Operators{i,j}(end-1,2) = thisIndMu; - %debug = 2 - end - - % delete edges that the starting and end points are the same - rowDelete = Operators{i,j}(:,1)==Operators{i,j}(:,2); - Operators{i,j}(rowDelete,:) = []; - - % if search_pso is involved, it should be incorporated with choose_traverse and update_always - indPSO = find(strcmp(AllOp,'search_pso')); - if ismember(indPSO,Operators{i,j}) - indChoose = find(strcmp(AllOp,'choose_traverse')); - indUpdate = find(strcmp(AllOp,'update_always')); - % only use the first pathway's choose and update operators in algorithm performance evaluation - Operators{i,1}(1,1) = indChoose; - Operators{i,1}(end,end) = indUpdate; - Operators{i,j} = [indChoose,indPSO;indPSO,indUpdate]; - %debug = 3 - end - - % there should be at most one global search operator in a pathway - indSearch = Operators{i,j}(2:end,1); % indices of search operators - for k = 1:numel(indSearch) - Paras{i}{indSearch(k),2} = 'LS'; % set all search operators' behaviors as local search - end - for k = 1:numel(indSearch) - if isempty(BehavSpace{indSearch(k)}{2,1}) - indSearch(k) = 0; - end - end - indSearch(indSearch==0) = []; % delete operators that only behave local search - indGS = []; % indices of global search operators - - if ~isequal(Back_operators,Operators) - Change = 1; - return - end - for k = 1:numel(indSearch) - if isempty(BehavSpace{indSearch(k)}{1,1}) % if operator only behaves global search - indGS = [indGS,indSearch(k)]; - elseif any(Paras{i}{indSearch(k),1} < ParaLocalSpace{indSearch(k)}(:,1)) || any(Paras{i}{indSearch(k),1} > ParaLocalSpace{indSearch(k)}(:,2)) - % if parameters are smaller than the lower bound or larger - % than the upper bound of the parameter space for local - % search - indGS = [indGS,indSearch(k)]; - end - end - if numel(indGS) == 1 - Paras{i}{indGS,2} = 'GS'; % revise the only global search operator's behavior to global - elseif numel(indGS) > 1 % repair the global search operator to behave local search - Change = 2; - indRetain = indGS(randperm(numel(indGS),1)); % index of the retained global search operator - rowRetain = Operators{i,j}(:,1)==indRetain; - if ismember(indRetain,indCross) && ismember(Operators{i,j}(rowRetain,2),indMu) && ismember(Operators{i,j}(rowRetain,2),indGS) - % if the global search operator is a crossover and the - % crossover is followed by a global mutation, then retain - % the mutation. - indRetain = [indRetain,Operators{i,j}(rowRetain,2)]; - end - for k = 1:numel(indRetain) - Paras{i}{indRetain(k),2} = 'GS'; % change the retained global search operator's behavior to global - indGS(indGS==indRetain(k)) = []; % delete the retained global search operator - end - - for k = 1:numel(indGS) - if ~isempty(ParaLocalSpace{indGS(k)}) - % if can perform local search, initialize the parameter - % values from the parameter space for local search - lower = ParaLocalSpace{indGS(k)}(:,1); - upper = ParaLocalSpace{indGS(k)}(:,2); - Paras{i}{indGS(k),1} = lower+(upper-lower).*rand(numel(lower),1); - else - % if cannot perform local search, delete the operator - indDel = find(Operators{i,j}(:,2) == indGS(k)); - Operators{i,j}(indDel,2) = Operators{i,j}(indDel+1,2); - Operators{i,j}(indDel+1,:) = []; - end - end - end - end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Search.m b/matlab/Utilities/@DESIGN/Search.m deleted file mode 100644 index 9b9bf0c..0000000 --- a/matlab/Utilities/@DESIGN/Search.m +++ /dev/null @@ -1,139 +0,0 @@ -function [Algs,AlgTrace]= Search(Problem,Data,Setting,seedTrain,app,bar) -% Search algorithms via heuristics. -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -% initialize algorithms and evaluate their performance -AlgGmax = ceil(Setting.AlgFE/Setting.AlgN); -switch Setting.Evaluate - case {'exact','intensification'} - Algs = DESIGN(Problem,Setting); - Algs = Algs.Evaluate(Problem,Data,Setting,seedTrain); - case 'racing' - Algs = DESIGN(Problem,Setting); - Algs = Algs.Evaluate(Problem,Data,Setting,seedTrain(1:Setting.RacingK)); - case 'approximate' - Surrogate = Approximate(Problem,Data,Setting,seedTrain); % initialize surrogate model - Algs = Surrogate.data(randperm(length(Surrogate.data),Setting.AlgN)); % get initial algorithms -end - -% iterate search -G = 1; -AlgTrace = DESIGN; % for save best algorithms found at each iteration -while G <= AlgGmax - str = ['Designing... ',num2str(100*G/AlgGmax),'%']; - if ~isempty(app) - app.TextArea.Value = str; - drawnow; - else - waitbar(G/AlgGmax,bar,str); - end - improve = 1; - innerG = 1; - Aux = cell(Setting.AlgN,1); % auxiliary data - if Setting.AlgN == 1 - innerGmax = ceil(Setting.AlgFE/Setting.AlgN/10); - else % global search for designing multiple algorithms - innerGmax = 1; - end - while improve(1) >= Setting.IncRate && innerG <= innerGmax - % design new algorithms - [NewAlgs,Aux] = Algs.GetNew(Problem,Setting,innerG,Aux); - - % performance evaluation and algorithm selection - switch Setting.Evaluate - case 'exact' - NewAlgs = NewAlgs.Evaluate(Problem,Data,Setting,seedTrain); - AllAlgs = [Algs,NewAlgs]; - Algs = AllAlgs.Select(Problem,Data,Setting,seedTrain); - - case 'approximate' - % get surrogate - NewAlgs = NewAlgs.Estimate(Problem,Setting,seedTrain,Surrogate); - AllAlgs = [Algs,NewAlgs]; - Algs = AllAlgs.Select(Problem,Data,Setting,seedTrain); - % update surrogate - if ismember(G,Surrogate.exactG) - NewAlgs = NewAlgs.Evaluate(Problem,Data,Setting,seedTrain); - Surrogate = Surrogate.UpdateModel(NewAlgs,Setting); - end - - case 'intensification' - % screen survivals from new algorithms - while ~isempty(NewAlgs) && ~isempty(seedTrain) - NewAlgs = NewAlgs.Evaluate(Problem,Data,Setting,seedTrain(1)); - AllAlgs = [Algs,NewAlgs]; - NewAlgs = AllAlgs.Select(Problem,Data,Setting,seedTrain(1)); - seedTrain(1) = []; - end - % restore instance indices - seedTrain = randperm(numel(instance)); - % evaluate new incumbents (NewAlgs)' performance on all instances - for i = 1:length(NewAlgs) - for j = 1:numel(seedTrain) - if sum(NewAlgs(i).performance(seedTrain(j),:)) == 0 % if haven't evaluated on instance j - NewAlgs(i) = NewAlgs(i).Evaluate(Problem,Data,Setting,seedTrain(j)); - end - end - end - % update incumbent algorithms - Algs(randperm(Setting.AlgN,length(NewAlgs))) = NewAlgs; - - case 'racing' - % screen survivals from all algorithms (racing) - NewAlgs = NewAlgs.Evaluate(Problem,Data,Setting,seedTrain(1:Setting.RacingK)); - AllAlgs = [Algs,NewAlgs]; - Algs = AllAlgs.Select(Problem,Data,Setting,seedTrain(1:Setting.RacingK)); - seedTrain(1:Setting.RacingK) = []; - while length(Algs) > Setting.AlgN && ~isempty(seedTrain) - Algs = Algs.Select(Problem,Data,Setting,seedTrain(1)); - seedTrain(1) = []; - end - % restore instance indices - seedTrain = randperm(numel(instance)); - % delete redundant algorithms after racing - if length(Algs) > Setting.AlgN - ind = randperm(length(Algs),length(Algs)-Setting.AlgN); - Algs(ind) = []; - end - end - - % update auxiliary data - for i = 1:Setting.AlgN - if isfield(Aux{i},'cma_Disturb') % if use CMA-ES - Aux{i} = para_cmaes(Algs(i),Problem,Aux{i},'algorithm'); % update CMA-ES's parameters - end - end - - % record best algorithms at each iteration - currCompare = Setting.Compare; - Setting.Compare = 'average'; - currPerform = Algs.GetPerformance(Setting,seedTrain); - Setting.Compare = currCompare; - [~,best] = min(currPerform); - AlgTrace(G) = Algs(best); - - improve = ImproveRate(Algs,improve,innerG,'algorithm'); - innerG = innerG+1; - G = G+1; - if G > AlgGmax - break - end - end -end \ No newline at end of file diff --git a/matlab/Utilities/@DESIGN/Select.m b/matlab/Utilities/@DESIGN/Select.m deleted file mode 100644 index e4847b9..0000000 --- a/matlab/Utilities/@DESIGN/Select.m +++ /dev/null @@ -1,119 +0,0 @@ -function output = Select(AllAlgs,Problem,Data,Setting,seedInstance) -% Select promising algorithms. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -% get algorithms' performance -if strcmp(Setting.Evaluate,'racing') - for i = 1:length(AllAlgs) - for j = 1:numel(seedInstance) - if sum(AllAlgs(i).performance(seedInstance(j),:)) == 0 % if haven't evaluate on instance j - AllAlgs(i) = AllAlgs(i).Evaluate(Problem,Data,Setting,seedInstance(j)); - end - end - end -end -c = AllAlgs.GetPerformance(Setting,seedInstance); - -% select algorithms -switch Setting.Evaluate - case {'exact','approximate'} - if strcmp(Setting.Compare,'average') - [~,ind] = sort(c,'ascend'); % small s values refer to better performance - else - win = zeros(length(AllAlgs),1); - for i = 1:length(AllAlgs) - ind1 = find(c(:,1)==i); % indices of pairwise comparisions that Alg i stands on the first position - ind2 = find(c(:,2)==i); - for j = 1:numel(ind1) - if c(ind1(j),4) < 0 && c(ind1(j),6) < 0.05 % Alg i's result is better than the opponent && Alg i and the opponent are different - win(i) = win(i)+1; - end - end - for j = 1:numel(ind2) - if c(ind2(j),4) > 0 && c(ind2(j),6) < 0.05 - win(i) = win(i)+1; - end - end - end - [~,ind] = sort(win,'descend'); - end - AllAlgs = AllAlgs(ind(1:Setting.AlgN)); - output = AllAlgs; - - case 'intensification' - if strcmp(Setting.Compare,'average') - [~,ind] = sort(c,'ascend'); - deleteInd = []; - for i = 1:length(ind) - if ind(i) > length(OldAlgs) && ~any(ind(i+1:end)<=length(OldAlgs)) - deleteInd = [deleteInd,ind(i)]; - end - end - NewAlgs(deleteInd-length(OldAlgs)) = []; % delete new algorithms that are not better than all incumbents - else - rowInd = find(c(:,1)==length(OldAlgs)); - rowInd = rowInd(end); - c = c(1:rowInd,:); % reserve comparisons between old and new algorithms - win = zeros(length(AllAlgs),1); - for i = length(OldAlgs)+1:length(AllAlgs) % for each new algorithm - ind1 = find(c(:,1)==i); - ind2 = find(c(:,2)==i); - for j = 1:numel(ind1) - if c(ind1(j),4) < 0 && c(ind1(j),6) < 0.05 - win(i) = win(i)+1; - end - end - for j = 1:numel(ind2) - if c(ind2(j),4) > 0 && c(ind2(j),6) < 0.05 - win(i) = win(i)+1; - end - end - end - win(1:length(OldAlgs),:) = []; % delete information of old algorithms - NewAlgs(win==0) = []; % delete new algorithms that are not better than all incumbents - end - output = NewAlgs; - - case 'racing' - win = zeros(length(AllAlgs),1); - for i = 1:length(AllAlgs) - ind1 = find(c(:,1)==i); - ind2 = find(c(:,2)==i); - for j = 1:numel(ind1) - if c(ind1(j),4) <= 0 && c(ind1(j),6) < 0.05 % <=: not worse than - win(i) = win(i)+1; - end - end - for j = 1:numel(ind2) - if c(ind2(j),4) >= 0 && c(ind2(j),6) < 0.05 - win(i) = win(i)+1; - end - end - end - notWorseInd = find(win>0); - if numel(notWorseInd) < Setting.AlgN - worseInd = find(win==0); - notWorseInd = [notWorseInd;datasample(worseInd,Setting.AlgN-numel(notWorseInd),'Replace',false)]; - end - AllAlgs = AllAlgs(notWorseInd); - output = AllAlgs; -end -end \ No newline at end of file diff --git a/matlab/Utilities/@SOLVE/InputAlg.m b/matlab/Utilities/@SOLVE/InputAlg.m deleted file mode 100644 index 0fc19b7..0000000 --- a/matlab/Utilities/@SOLVE/InputAlg.m +++ /dev/null @@ -1,138 +0,0 @@ -function [Alg,Setting] = InputAlg(Setting) -% Set the algorithm profile for solving the targeted problem. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -if ~isempty(Setting.AlgFile) && ~strcmp(Setting.AlgFile,'None') - tempAlg = load(Setting.AlgFile); - Alg = tempAlg.algs(1); - Setting.AlgP = length(Alg.operator); -else - Setting.AlgP = 1; - currOp = cell(1,Setting.AlgP); - currPara = cell(1,Setting.AlgP); - switch Setting.AlgName - case 'Continuous Genetic Algorithm' - currOp{1}.Choose = 'choose_tournament'; - currOp{1}.Search = {'cross_sim_binary','search_mu_polynomial',[-inf,1]}; - currOp{1}.Update = 'update_round_robin'; - currPara{1}.Search = {20,[0.2;20]}; % {crossover distribution;[mutation probability; mutation distribution]} - case 'Evolutionary Programming' - currOp{1}.Choose = 'choose_tournament'; - currOp{1}.Search = {'search_mu_gaussian','',[-inf,1]}; - currOp{1}.Update = 'update_round_robin'; - case 'Fast Evolutionary Programming' - currOp{1}.Choose = 'choose_tournament'; - currOp{1}.Search = {'search_mu_cauchy','',[-inf,1]}; - currOp{1}.Update = 'update_round_robin'; - case 'CMA-ES' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_cma','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - case 'Estimation of Distribution' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_eda','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - case 'Particle Swarm Optimization' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_pso','',[-inf,1]}; - currOp{1}.Update = 'update_pairwise'; - currPara{1}.Search = {0.9,[]}; % inertia weight - case 'Differential Evolution' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_de_current','',[-inf,1]}; - currOp{1}.Update = 'update_pairwise'; - currPara{1}.Search = {[0.9,0.1],[]}; % {scaling factor, crossover probability} - case 'Continuous Random Search' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'reinit_continuous','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - - case 'Discrete Genetic Algorithm' - currOp{1}.Choose = 'choose_tournament'; - currOp{1}.Search = {'cross_point_uniform','search_reset_rand',[-inf,1]}; - currOp{1}.Update = 'update_round_robin'; - currPara{1}.Search = {0.2,0.2}; % {crossover probability, reset probability} - case 'Discrete Iterative Local Search' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_reset_one','',[0.05,10]; % [fitness improve rate,innerGmax] - 'reinit_discrete','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - case 'Discrete Simulated Annealing' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_reset_one','',[-inf,1]}; - currOp{1}.Update = 'update_simulated_annealing'; - currPara{1}.Update = 0.1; % initial temperture - case 'Discrete Random Search' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'reinit_discrete','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - - case 'Permutation Genetic Algorithm' - currOp{1}.Choose = 'choose_tournament'; - currOp{1}.Search = {'cross_order_two','search_swap',[-inf,1]}; - currOp{1}.Update = 'update_round_robin'; - case 'Permutation Iterative Local Search' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_insert','',[0.05,10]; - 'reinit_permutation','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - case 'Permutation Simulated Annealing' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_insert','',[-inf,1]}; - currOp{1}.Update = 'update_simulated_annealing'; - currPara{1}.Update = 0.1; % initial temperture - case 'Permutation Variable Neighborhood Search' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'search_swap','',[0.05,10]; - 'search_scramble','',[0.05,10]; - 'search_insert','',[0.05,10]}; - currOp{1}.Update = 'update_greedy'; - case 'Permutation Random Search' - currOp{1}.Choose = 'choose_traverse'; - currOp{1}.Search = {'reinit_permutation','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - case 'ICA' - currOp{1}.Choose = 'choose_ica'; - currOp{1}.Search = {'search_ica','',[-inf,1]}; - currOp{1}.Update = 'update_greedy'; - currPara{1}.Choose = 10; % inertia weight - currPara{1}.Search = {[0.6,0.5],[]}; % [p1,alpha] - end - - for i = 1:Setting.AlgP - if ~isfield(currOp{i},'Archive') - currOp{i}.Archive = ''; - end - if ~isfield(currPara{i},'Choose') - currPara{i}.Choose = []; - end - if ~isfield(currPara{i},'Search') - currPara{i}.Search = cell(size(currOp{1}.Search,1),2); - end - if ~isfield(currPara{i},'Update') - currPara{i}.Update = []; - end - end - - Alg = DESIGN; - Alg = Alg.Construct(currOp,currPara); -end -end \ No newline at end of file diff --git a/matlab/Utilities/@SOLVE/RepairSol.m b/matlab/Utilities/@SOLVE/RepairSol.m deleted file mode 100644 index 6d49328..0000000 --- a/matlab/Utilities/@SOLVE/RepairSol.m +++ /dev/null @@ -1,45 +0,0 @@ -function decs = RepairSol(decs,Problem) -% Repair infeasible solutions. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch Problem.type{1} - case 'continuous' - Lower = Problem.bound(1,:); - Upper = Problem.bound(2,:); - decs = max(min(decs,Upper),Lower); % limit solutions within decision space - case 'discrete' - if contains(Problem.setting,'dec_diff') % if elements of a solution should be different with respect to each other - [N,D] = size(decs); - for i = 1:N - [~,ind] = unique(decs(i,:),'stable'); - while numel(ind) < D - DupInd = setdiff(1:D,ind); - for j = 1:numel(DupInd) - decs(i,DupInd(j)) = randperm(Problem.bound(2,DupInd(j)),1); - end - [~,ind] = unique(decs(i,:),'stable'); - end - end - end - case 'permutation' - % don't need to do anything -end -end \ No newline at end of file diff --git a/matlab/Utilities/@SOLVE/RunAlg.m b/matlab/Utilities/@SOLVE/RunAlg.m deleted file mode 100644 index 7dcf071..0000000 --- a/matlab/Utilities/@SOLVE/RunAlg.m +++ /dev/null @@ -1,236 +0,0 @@ -function [bestSolutions,allSolutions] = RunAlg(Alg,Problem,Data,app,Setting) -% Solve the targeted problem instances by a designed algorithm. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -Operator = Alg.operatorPheno; -Parameter = Alg.parameterPheno; -bestSolutions = SOLVE; % the best solution at the final iteration of each algorithm run -allSolutions = SOLVE; % the best solution at each iteration of the best algorithm run (obtains the best solutions among all runs) -tic; -str = 'Initializing...'; -if ~isempty(app) - app.TextArea.Value = str; - drawnow; -else - bar = waitbar(0,str); -end -counter = 1; -for i = 1:length(Problem) - currSolutions = cell(Setting.AlgRuns,1); - fitnessSequence = zeros(Setting.AlgRuns,1); - for j = 1:Setting.AlgRuns - switch Problem(i).type{2} - case 'static' - [ArchSolution,t] = RunDesign(Operator,Parameter,Problem(i),Data(i),Setting); - currSolutions{j} = ArchSolution(2:end); % best solutions at each iteration of the current algorithm run - [~,best] = min(ArchSolution.fits); - bestSolutions(i,j) = ArchSolution(best); - - case 'sequential' - currProblem = Problem(i); - currData = Data(i); - currSolution = SOLVE; - k = 1; - while currData.continue == true - [ArchSolution,t] = RunDesign(Operator,Parameter,currProblem,currData,Setting); - [~,best] = min(ArchSolution.fits); - currSolution(k) = ArchSolution(best); - k = k+1; - - % update the current instance of the problem sequence - [~,best] = min(ArchSolution.fits); - [currProblem,currData,~] = feval(str2func(Problem(i).name),currProblem,currData,ArchSolution(best),'sequence'); - end - currSolutions{j} = currSolution; % final solutions of all subproblems obtained in the current algorithm run - fitnessSequence(j) = sum(currSolution.fits); - end - str = ['Solving... ',num2str(100*counter/(length(Problem)*Setting.AlgRuns)),'%']; - if ~isempty(app) - app.TextArea.Value = str; - drawnow; - else - waitbar(counter/(length(Problem)*Setting.AlgRuns),bar,str); - end - counter = counter+1; - end - switch Problem(i).type{2} - case 'static' - [~,best] = min(bestSolutions(i,:).fits); - allSolutions(i,1:length(currSolutions{1})) = currSolutions{best}; % solutions at each iteration of the best algorithm run - case 'sequential' - [~,best] = min(fitnessSequence); - allSolutions(i,1:length(currSolutions{1})) = currSolutions{best}; % solutions at the final iteration of each subproblem of the best algorithm run - end -end -str = 'Complete'; -if ~isempty(app) - app.TextArea.Value = str; - drawnow; -else - waitbar(100,bar,str); -end -toc; -end - -function [ArchSolution,t] = RunDesign(Operator,Para,Problem,Data,Setting) -% initialize solution(s) -switch Problem.type{1} - case 'continuous' - Lower = Problem.bound(1,:); - Upper = Problem.bound(2,:); - dec = unifrnd(repmat(Lower,Problem.N,1),repmat(Upper,Problem.N,1)); - case 'discrete' - D = size(Problem.bound,2); % size of the solution space - dec = zeros(Problem.N,D); - for j = 1:D - dec(:,j) = randi([Problem.bound(1,j),Problem.bound(2,j)],Problem.N,1); - end - case 'permutation' - [~,dec] = sort(rand(Problem.N,Problem.bound(end)),2); -end -Solution = SOLVE(dec,Problem,Data); - -% initialize archive(s) -Archive = cell(length(Operator{1}.Archive),1); -for i = 1:length(Operator{1}.Archive) - [Archive{i},~] = feval(str2func(Operator{1}.Archive{i}),Solution,Problem,'execute'); -end -ArchSolution = Solution(randi(Problem.N)); % the best solution found at each iteration, Gmax*1 -Aux = cell(1,Setting.AlgP); -for i = 1:Setting.AlgP - Aux{i} = struct; % auxiliary structure array -end - -% iterate -G = 1; -t = 0; -switch Setting.Metric - case {'quality','auc'} - Tmax = +inf; - Thres = -inf; - case 'runtimeFE' - Tmax = ceil(Setting.Tmax./Setting.ProbN); % time changes to interation G - Thres = Setting.Thres; - case 'runtimeSec' - Tmax = Setting.Tmax; - Thres = Setting.Thres; -end -if Setting.AlgP == 1 % if the designed algorithm has a single search pathway - while G <= Problem.Gmax && t < Tmax && min(ArchSolution.fits) > Thres - tic; - for i = 1:size(Operator{1}.Search,1) - improve = 1; - innerG = 1; - while improve(1) >= Operator{1}.Search{i,end}(1) && innerG <= Operator{1}.Search{i,end}(2) % termination condition of search operator i - % choose where to search from - [ind,~] = feval(str2func(Operator{1}.Choose),Solution,Problem,Para{1}.Choose,Aux{1},G,innerG,Data,'execute'); - - - % search from the chosen solution(s) - [New,Aux{1}] = feval(str2func(Operator{1}.Search{i,1}),Solution(ind),Problem,Para{1}.Search{i,1},Aux{1},G,innerG,Data,'execute'); - - if ~isempty(Operator{1}.Search{i,2}) % if designed a sexual evolutonary algorithm with crossover and mutation - New = SOLVE.RepairSol(New,Problem); - [New,Aux{1}] = feval(str2func(Operator{1}.Search{i,2}),New,Problem,Para{1}.Search{i,2},Aux{1},G,innerG,Data,'execute'); - end - New = SOLVE(New,Problem,Data); - - if strcmp(Operator{1}.Search{i,1},'search_pso') % update pbest and gbest for PSO' particle fly operator - Aux{1} = para_pso(New,Problem,Aux{1}); - elseif strcmp(Operator{1}.Search{i,1},'search_cma') % update parameters for CMA-ES - Aux{1} = para_cma(New,Problem,Aux{1},'solution'); - end - - % update solution(s) - [Solution,~] = feval(str2func(Operator{1}.Update),[Solution,New],Problem,Para{1}.Update,Aux{1},G,innerG,Data,'execute'); - - % update archive(s) - for j = 1:length(Operator{1}.Archive) - [Archive{i},~] = feval(str2func(Operator{1}.Archive{j}),Solution,Archive{i},Problem,'execute'); - end - [ArchSolution,~] = archive_best(Solution,ArchSolution,'execute'); - - improve = ImproveRate(Solution,improve,innerG,'solution'); - innerG = innerG+1; - G = G+1; - if strcmp(Setting.Metric,'runtimeFE') - t = G; - elseif strcmp(Setting.Metric,'runtimeSec') - t = t +toc; - end - if G > Problem.Gmax || t >= Tmax || min(ArchSolution.fits) <= Thres - break - end - end - if G > Problem.Gmax || t >= Tmax || min(ArchSolution.fits) <= Thres - break - end - end - end - -elseif Setting.AlgP > 1 % if the designed algorithm has multiple search pathways - eachN = round(Setting.ProbN*(1/Setting.AlgP)); - innerG = 1; - while G <= Problem.Gmax && t < Tmax && min(ArchSolution.fits) > Thres - tic; - % choose where to search from - [ind,~] = feval(str2func(Operator{1}.Choose),Solution,Problem,Para{1}.Choose,Aux{i},G,innerG,Data,'execute'); - - % search from the chosen solution(s) - allNew = []; - for i = 1:Setting.AlgP - % determine indices of solutions to be searched from - if i == Setting.AlgP - currInd = ind; - else - currInd = ind(1:eachN); - ind(1:eachN) = []; % delete used indices - end - % search - [New,Aux{i}] = feval(str2func(Operator{i}.Search{1}),Solution(currInd),Problem,Para{i}.Search{1},Aux{i},G,innerG,Data,'execute'); - New = SOLVE(New,Problem,Data); - if strcmp(Operator{i}.Search{1},'search_pso') % update pbest and gbest for PSO' particle fly operator - Aux{i} = para_pso(New,Problem,Aux{i}); - elseif strcmp(Operator{i}.Search{1},'search_cma') % update parameters for CMA-ES - Aux{i} = para_cma(New,Problem,Aux{i},'solution'); - end - allNew = [allNew,New]; - end - - % update solution(s) - [Solution,~] = feval(str2func(Operator{1}.Update),[Solution,allNew],Problem,Para{1}.Update,Aux{i},G,innerG,Data,'execute'); - - % update archive(s) - for i = 1:length(Operator{1}.Archive) - [Archive{i},~] = feval(str2func(Operator{1}.Archive{i}),Solution,Archive{i},Problem,'execute'); - end - [ArchSolution,~] = archive_best(Solution,ArchSolution,'execute'); - - innerG = innerG+1; - G = G+1; - if strcmp(Setting.Metric,'runtimeFE') - t = G; - elseif strcmp(Setting.Metric,'runtimeSec') - t = t +toc; - end - end -end -end \ No newline at end of file diff --git a/matlab/Utilities/@SOLVE/SOLVE.m b/matlab/Utilities/@SOLVE/SOLVE.m deleted file mode 100644 index 1e5971d..0000000 --- a/matlab/Utilities/@SOLVE/SOLVE.m +++ /dev/null @@ -1,111 +0,0 @@ -% Class for solving the targeted problem. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -classdef SOLVE < handle - properties(SetAccess = private) - dec; % decision variables - obj; % objective values - con; % constraint violations - fit; % solution's fitness (considering constraint violations) - acc; % accessory data - end - - methods - % construct solutions - function solution = SOLVE(dec,Problem,Data) - if nargin > 0 - solution(1,size(dec,1)) = SOLVE; - dec = solution.RepairSol(dec,Problem); - switch Problem.type{3} - case 'certain' - dec = feval(str2func(Problem.name),Data,dec,'repair'); % repair solutions - %Problem.problem_id=3; - [obj,con,acc] = feval(str2func(Problem.name),Data,dec,Problem.problem_id,'evaluate'); % evaluate fitness - case 'uncertain' % for uncertain problems - obj = zeros(Problem.sampleN,1); - con = zeros(Problem.sampleN,1); - for i = 1:ProblemsampleN - [obj(i),con(i),acc] = feval(str2func(Problem.name),Data,dec,'evaluate'); - end - if contains(Problem.setting,'uncertain_average') - obj = mean(obj,1); - con = mean(con,1); - elseif contains(Problem.setting,'uncertain_worst') - obj = max(obj,[],1); - con = max(con,[],1); - end - end - for i = 1:length(solution) - solution(i).dec = dec(i,:); - solution(i).obj = obj(i,:); - if ~isempty(con) - solution(i).con = con(i,:); - else - solution(i).con = 0; - end - Con = sum(max(0,solution(i).con)); - feasible = Con<= 0; - %solution(i).fit = feasible.*solution(i).obj+~feasible.*(Con+1e8); - solution(i).fit = solution(i).obj+~feasible.*(Con); - if ~isempty(acc) - solution(i).acc = cell(1,length(acc)); - for j = 1:length(acc) - if iscell(acc{j}) - solution(i).acc{j} = acc{j}{i}; - elseif ismatrix(acc{j}) - solution(i).acc{j} = acc{j}(i,:); - else - error('Accessory data should be saved in cell or matrix format.'); - end - end - end - end - end - end - - function value = decs(solution) - value = cat(1,solution.dec); - end - - function value = objs(solution) - value = cat(1,solution.obj); - end - - function value = cons(solution) - value = cat(1,solution.con); - end - - function value = fits(solution) - value = cat(1,solution.fit); - end - end - - methods(Static) - % ensure solutions to be feasible - dec = RepairSol(dec,Problem) - - % input algorithm - [Alg,Setting] = InputAlg(Setting) - - % solve the targeted problem instances by the designed algorithm(s). - [bestSolutions,allSolutions] = RunAlg(Alg,ProblemSolve,DataSolve,app,Setting) - end -end \ No newline at end of file diff --git a/matlab/Utilities/Others/APP/APP.mlapp b/matlab/Utilities/Others/APP/APP.mlapp deleted file mode 100644 index c3215ee..0000000 Binary files a/matlab/Utilities/Others/APP/APP.mlapp and /dev/null differ diff --git a/matlab/Utilities/Others/APP/Open.jpeg b/matlab/Utilities/Others/APP/Open.jpeg deleted file mode 100644 index 41504c1..0000000 Binary files a/matlab/Utilities/Others/APP/Open.jpeg and /dev/null differ diff --git a/matlab/Utilities/Others/APP/Run.png b/matlab/Utilities/Others/APP/Run.png deleted file mode 100644 index 4867957..0000000 Binary files a/matlab/Utilities/Others/APP/Run.png and /dev/null differ diff --git a/matlab/Utilities/Others/Approximate.m b/matlab/Utilities/Others/Approximate.m deleted file mode 100644 index 26e44ac..0000000 --- a/matlab/Utilities/Others/Approximate.m +++ /dev/null @@ -1,97 +0,0 @@ -% Class for estimating the designed algorithm's performance. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- -classdef Approximate < handle - properties - data; - embedding; - model; - randSeed; - exactG; - end - - methods - function obj = Approximate(Problem,Data,Setting,indInstance) - if nargin > 0 - obj = Approximate; - % seed for disrupting the order of elements in the vector representation of algorithms - if Setting.AlgP == 1 % one search pathway - obj.randSeed = randperm((Setting.AlgQ+2)*3); - else % multiple search pathways - obj.randSeed = randperm((Setting.AlgP+2)*3); - end - - % determine iterations with exact performance estimations - ExactGmax = Setting.Surro/Setting.AlgN; - AlgGmax = ceil(Setting.AlgFE/Setting.AlgN); - obj.exactG = 1:AlgGmax/ExactGmax:AlgGmax; - - % get training data of surrogate - TrainAlgs1 = DESIGN(Problem,Setting,500); - obj.data = TrainAlgs1.Evaluate(Problem,Data,Setting,indInstance); % exactly evaluate performance - - % train embedding - TrainAlgs2 = DESIGN(Problem,Setting,1000); - obj.embedding = obj.GetEmbed(TrainAlgs2,Setting); - - % train surrogate - obj.model = obj.GetModel(obj.data,Setting); - end - end - - function EmbedMap = GetEmbed(obj,data,Setting) - EmbedMap = Embedding(data,Setting,obj,'get'); - end - - function EmbedAlgs = UseEmbed(obj,data,Setting) - EmbedAlgs = Embedding(data,Setting,obj,'use'); - end - - function Model = GetModel(obj,data,Setting) - % train a random forest surrogate to estimate algorithms' performance - EmbedAlgs = Embedding(data,Setting,obj,'use'); % get the embeded algorithms - Labels = data.avePerformAll; % all algorithms' average performance on all instances - Model = TreeBagger(1000,EmbedAlgs,Labels,'Method','regression','MinLeafSize',5); % train a random forest surrogate - end - - function obj = UpdateModel(obj,Algs,Setting) - % Update the surrogate model during the design process. - N = Setting.AlgN; - a = Algs.avePerformAll; - b = Algs.avePerformApproxAll; - total = 0; - error = 0; - indNew = []; - for i = 1:N - for j = i+1:N - res = xor(a(i) - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -randSeed = Surrogate.randSeed; -layer = 2; % number of auto-encoder layers -p = 0.3; % corrupt probability -lower = 1; -upper = size(Algs(1).parameter,1); - -% get vector representations of the designed algorithms -if Setting.AlgP == 1 % one search pathway - for i = 1:length(Algs) - operator = zeros(1,Setting.AlgQ+2); % vector representation of operators - operator(1) = Algs(i).operator{1}(1,1); - operator(2:size(Algs(i).operator{1},1)) = Algs(i).operator{1}(2:end,1); - operator(end) = Algs(i).operator{1}(end,2); - - parameter = zeros(2,Setting.AlgQ+2); % vector representation of parameters - for j = 1:Setting.AlgQ+2 - if operator(j) ~= 0 - for k = 1:numel(Algs(i).parameter{operator(j),1}) - parameter(k,j) = Algs(i).parameter{operator(j),1}(k); - end - end - end - parameter = reshape(parameter,1,(Setting.AlgQ+2)*2); - - operator = (operator-min(operator))./(max(operator)-min(operator)); % normilize to [0,1] - tempAlg = [operator,parameter]; - tempAlg = tempAlg(randSeed); % disrupt the order of elements in the vector representation - tempAlg = reshape(tempAlg,numel(randSeed)/3,3); % for reducting dimensionality of the vector representation - VectorAlgs(:,3*i-2:3*i) = tempAlg; - end -else % multiple search pathways - for i = 1:length(Algs) - operator = zeros(1,Setting.AlgP+2); - operator(1) = Algs(i).operator{1}(1,1); - for j = 1:Setting.AlgP - operator(j+1) = Algs(i).operator{j}(2,1); - end - operator(end) = Algs(i).operator{1}(end,2); - - parameter = zeros(2,Setting.AlgP+2); % each operator has at most 2 parameters - for j = 1:numel(Algs(i).parameter{operator(1),1}) % choose operator's parameter(s) - parameter(j,1) = Algs(i).parameter{operator(1),1}(j); - end - for j = 1:Setting.AlgP % search operators' parameter(s) - for k = 1:numel(Algs(i).parameter{operator(j+1),1}) - parameter(k,j+1) = Algs(i).parameter{operator(j+1),1}(k); - end - end - for j = 1:numel(Algs(i).parameter{operator(end),1}) % update operator's parameter(s) - parameter(j,end) = Algs(i).parameter{operator(end),1}(j); - end - parameter = reshape(parameter,1,(Setting.AlgP+2)*2); - - operator = (operator-lower)./(upper-lower); % normilize to [0,1] - tempAlg = [operator,parameter]; - tempAlg = tempAlg(randSeed); % disrupt the order of elements in the vector representation - tempAlg = reshape(tempAlg,numel(randSeed)/3,3); % for reducting dimensionality of the vector representation - VectorAlgs(:,3*i-2:3*i) = tempAlg; - end -end - -switch mode - case 'get' % get the embedding mapping by mSDA - [EmbedMap,~] = mSDA(VectorAlgs,p,layer); - output = EmbedMap; - case 'use' % use the mapping to embed algorithms - EmbedMap = Surrogate.embedding; - temp = [VectorAlgs;ones(1,length(Algs)*3)]; - wx = EmbedMap(:,:,1)*temp; - argslist = zeros(numel(randSeed)/3,length(Algs)); - for i = 1:length(Algs) - argslist(:,i) = wx(:,3*i-2)+wx(:,3*i-1)+wx(:,3*i); - end - wx = argslist/3; - wx = tanh(wx); - layer = size(EmbedMap,3); - for i = 2:layer - wx = [wx;ones(1,length(Algs))]; - wx = EmbedMap(:,:,i)*wx; - wx = tanh(wx); - end - EmbedAlgs = wx'; - output = EmbedAlgs; -end -end - -function [Ws,hs] = mSDA(X,p,l) -[d,n] = size(X); -n = n/3; -Ws = zeros(d,d+1,l); -hs = zeros(d,n,l+1); -%hs(:,:,1) = X; -[Ws(:,:,1),hs(:,:,1+1)] = mDA_de(X,p); -for t = 2:l - [Ws(:,:,t),hs(:,:,t+1)] = mDA(hs(:,:,t),p); -end -end - -function [W,h] = mDA_de(X,p) -X = [X;ones(1,size(X,2))]; -d = size(X,1); -q = [ones(d-1,1).*(1-p); 1]; -S = X*X'; -Q = S.*(q*q'); -Q(1:d+1:end) = q.*diag(S); -P = S.*repmat(q',d,1); -W = P(1:end-1,:)/(Q+1e-5*eye(d)); - -length = size(X,2)/3; -h = zeros(d-1,length); -wx = W*X; -for i = 1:length - temp = wx(:,3*i-2:3*i); - temp = temp(:,1)+temp(:,2)+temp(:,3); - h(:,i) = temp/3; -end -h = tanh(h); -%h = tanh(W*X); -end - -function [W,h] = mDA(X,p) -X = [X;ones(1,size(X,2))]; -d = size(X,1); -q = [ones(d-1,1).*(1-p); 1]; -S = X*X'; -Q = S.*(q*q'); -Q(1:d+1:end) = q.*diag(S); -P = S.*repmat(q',d,1); -W = P(1:end-1,:)/(Q+1e-5*eye(d)); -h = tanh(W*X); -end diff --git a/matlab/Utilities/Others/ImproveRate.m b/matlab/Utilities/Others/ImproveRate.m deleted file mode 100644 index 5c6851c..0000000 --- a/matlab/Utilities/Others/ImproveRate.m +++ /dev/null @@ -1,51 +0,0 @@ -function improve = ImproveRate(Solution,improve,innerG,type) -% Calculate the designed algorithm's performance improvement rate during k -% consecutive iterations. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -k = 3; - -% initialize -if innerG == 1 - improve = [1,zeros(1,k)]; % [fitness improve rate, fitness 1, 2, ..., k] -end - -% keep the best fitness found at the latest k iteration in the improve vector -switch type - case 'solution' - Con = sum(max(0,Solution.cons),2); - Feasible = Con <= 0; - Fitness = Feasible.*Solution.objs + ~Feasible.*(Con+1e8); - case 'algorithm' - Fitness = Solution.avePerformAll; -end -improve = [improve,min(Fitness)]; -improve(2) = []; - -% calculate the fitness improve rate -if innerG >= k - tempRate = zeros(1,k-1); - for i = 2:k - tempRate(i-1) = (improve(i)-improve(i+1))./improve(i); - end - improve(1) = max(tempRate); -end -end \ No newline at end of file diff --git a/matlab/Utilities/Others/Input.m b/matlab/Utilities/Others/Input.m deleted file mode 100644 index bd825da..0000000 --- a/matlab/Utilities/Others/Input.m +++ /dev/null @@ -1,270 +0,0 @@ -function varargout = Input(varargin) -% Process the input of algorithm design. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -switch varargin{end} - case 'data' - value = varargin{1}; - Setting = varargin{2}; - % input problem - if any(strcmp(value,'Problem')) - ind = find(strcmp(value,'Problem')); - prob = value{ind+1}; - varargout{1} = prob; - else - error('Please set the targeted problem.'); - end - if strcmp(Setting.Mode,'design') && any(strcmp(value,'InstanceTrain')) && any(strcmp(value,'InstanceTest')) - ind = find(strcmp(value,'InstanceTrain')); - instanceTrain = value{ind+1}; % indexes of problem instances for designing algorithm - ind = find(strcmp(value,'InstanceTest')); - instanceTest = value{ind+1}; % indexes of problem instances for testing the designed algorithm - varargout{2} = instanceTrain; - varargout{3} = instanceTest; - elseif strcmp(Setting.Mode,'solve') && any(strcmp(value,'InstanceSolve')) - ind = find(strcmp(value,'InstanceSolve')); - instanceSolve = value{ind+1}; % indexes of problem instances to be solved - varargout{2} = instanceSolve; - else - error('Please set the targeted problem instance indexes.'); - end - - case 'parameter' - value = varargin{1}; - Setting = varargin{2}; - - if any(strcmp(value,'AlgP')) - ind = find(strcmp(value,'AlgP')); - Setting.AlgP = value{ind+1}; - end - if any(strcmp(value,'AlgQ')) - ind = find(strcmp(value,'AlgQ')); - Setting.AlgQ = value{ind+1}; - end - if any(strcmp(value,'Archive')) - ind = find(strcmp(value,'Archive')); - Setting.Archive = value{ind+1}; - end - if any(strcmp(value,'LSRange')) - ind = find(strcmp(value,'LSRange')); - Setting.LSRange = value{ind+1}; - end - if any(strcmp(value,'IncRate')) - ind = find(strcmp(value,'IncRate')); - Setting.IncRate = value{ind+1}; - end - if any(strcmp(value,'ProbN')) - ind = find(strcmp(value,'ProbN')); - Setting.ProbN = value{ind+1}; - end - if any(strcmp(value,'ProbFE')) - ind = find(strcmp(value,'ProbFE')); - Setting.ProbFE = value{ind+1}; - end - if any(strcmp(value,'InnerFE')) - ind = find(strcmp(value,'InnerFE')); - Setting.InnerFE = value{ind+1}; - end - if any(strcmp(value,'AlgN')) - ind = find(strcmp(value,'AlgN')); - Setting.AlgN = value{ind+1}; - end - if any(strcmp(value,'AlgFE')) - ind = find(strcmp(value,'AlgFE')); - Setting.AlgFE = value{ind+1}; - end - if any(strcmp(value,'AlgRuns')) - ind = find(strcmp(value,'AlgRuns')); - Setting.AlgRuns = value{ind+1}; - end - if any(strcmp(value,'Metric')) - ind = find(strcmp(value,'Metric')); - Setting.Metric = value{ind+1}; - end - if any(strcmp(value,'Compare')) - ind = find(strcmp(value,'Compare')); - Setting.Compare = value{ind+1}; - end - if any(strcmp(value,'Evaluate')) - ind = find(strcmp(value,'Evaluate')); - Setting.Evaluate = value{ind+1}; - end - if any(strcmp(value,'Tmax')) - ind = find(strcmp(value,'Tmax')); - Setting.Tmax = value{ind+1}; - end - if any(strcmp(value,'Thres')) - ind = find(strcmp(value,'Thres')); - Setting.Thres = value{ind+1}; - end - if any(strcmp(value,'RacingK')) - ind = find(strcmp(value,'RacingK')); - Setting.RacingK = value{ind+1}; - end - if any(strcmp(value,'Surro')) - ind = find(strcmp(value,'Surro')); - Setting.Surro = value{ind+1}; - end - if any(strcmp(value,'AlgFile')) - ind = find(strcmp(value,'AlgFile')); - Setting.AlgFile = value{ind+1}; - end - if any(strcmp(value,'AlgName')) - ind = find(strcmp(value,'AlgName')); - Setting.AlgName = value{ind+1}; - end - varargout{1} = Setting; - - case 'check' - Setting = varargin{1}; - switch Setting.Mode - case 'design' - % AlgP or AlgQ should be equal to 1 - if Setting.AlgP > 1 && Setting.AlgQ > 1 - error(['Setting.AlgP or Setting.AlgQ should be equal to 1 - ' ... - 'For algorithms with multiple search pathways (AlgP>1), ' ... - 'each search pathway should have only one search operator (AlgQ=1). ' ... - 'For algorithms with a single search pathway (AlgP=1), ' ... - 'the search pathway can have multiple search operators (AlgQ>=1).']) - end - - % set Tmax and Thres when using runtimeFE or runtimeSec as the performance metric - if strcmp(Setting.Metric,'runtimeFE') && isempty(Setting.Tmax) - Setting.Tmax = Setting.ProbFE; - end - if strcmp(Setting.Metric,'runtimeFE') && isempty(Setting.Thres) - error(['Please set "Setting.Thres" as the lowest acceptable performance ' ... - 'of the design algorithms, the performance can be the solution quality.']) - end - if strcmp(Setting.Metric,'runtimeSec') && isempty(Setting.Tmax) - error('Please set "Setting.Tmax" as the maximum runtime (seconds).') - end - if strcmp(Setting.Metric,'runtimeSec') && isempty(Setting.Thres) - error(['Please set "Setting.Thres" as the lowest acceptable performance ' ... - 'of the design algorithms, the performance can be the solution quality.']) - end - - % time (Tmax) should be function evaluations when using auc - if strcmp(Setting.Metric,'auc') && numel(Setting.Tmax) <= 1 - error(['"Setting.Tmax" should contain multiple time points. The time ' ... - 'points should the numbers of function evaluations spent during ' ... - 'the alorithm execution.']) - end - - % thresholds should be corresponding to time points when using auc - if strcmp(Setting.Metric,'auc') && numel(Setting.Thres) ~= numel(Setting.Tmax) - error(['The number of thresholds in "Setting.Thres" should be equal to ' ... - 'the number of time points in "Setting.Tmax". "Setting.Thres" ' ... - 'refers to the lowest acceptable performance of the design' ... - ' algorithms, the performance can be the solution quality.']) - end - - % the "racing" evaluation method should be used with the "statictic" algorithm comparing method - if strcmp(Setting.Evaluate,'racing') && ~strcmp(Setting.Compare,'statistic') - error(['The "racing" evaluation method should be used with the ' ... - 'algorithm comparing method of "statistic". ']) - end - - % should set RacingK when using the "racing" evaluation method - if strcmp(Setting.Evaluate,'racing') && isempty(Setting.RacingK) - error(['Please set "Setting.K" as the number of instances evaluated ' ... - 'before the first round of racing.']) - end - - % should set Surro when using the "approximate" evaluation method - if strcmp(Setting.Evaluate,'approximate') && isempty(Setting.Surro) - error(['Please set "Setting.Surro" as the number of exact performance evaluations' ... - ' when using surrogate.']) - end - - % it is not necessary to use "statistic" algorithm comparing method when using the "approximate" evaluation method - if strcmp(Setting.Evaluate,'approximate') && strcmp(Setting.Compare,'statistic') - error(['It is not necessary to use the "statistic" algorithm ' ... - 'comparing method when using the "approximate" evaluation method.']) - end - - % should run the design multiple times when using the "statistic" comparsion method - if strcmp(Setting.Compare,'statistic') && Setting.AlgRuns == 1 - error(['Please run the design multiple times (Setting.AlgRuns>1)' ... - ' when using the "statistic" comparsion method.']) - end - - % better to have a large population size when involving the EDA operator - if Setting.ProbN < 5 && Setting.AlgP > 1 - warning(['It is better to have a large population size if ' ... - 'involving the EDA operator']) - end - - % AlgP cannot be very large - if Setting.AlgQ > 4 - warning(['AlgQ is recommended to be larger than 4 for ' ... - 'discrete and permutation problems due to the lack' ... - ' of so many search operators']) - end - - % better to have a large number of training intrances or have a large number of algorithm runs, in order to make the statistical test discriminative - if strcmp(Setting.Compare,'statistic') - warning(['It is better to have a large number of training intrances ' ... - 'or have a large number of algorithm runs (set AlgRun to a large number), ' ... - 'in order to make the statistical test discriminative.']); - end - - case 'solve' - % should specify the file or name of the algorithm being used - if isempty(Setting.AlgFile) && isempty(Setting.AlgName) - error(['Please specify an algorithm file in Setting.AlgFile or ' ... - 'specify an algorithm name in Setting.AlgName.']) - end - - % set Tmax and Thres when using runtimeFE or runtimeSec as the performance metric - if strcmp(Setting.Metric,'runtimeFE') && isempty(Setting.Tmax) - Setting.Tmax = Setting.ProbFE; - end - if strcmp(Setting.Metric,'runtimeFE') && isempty(Setting.Thres) - error(['Please set "Setting.Thres" as the lowest acceptable performance ' ... - 'of the design algorithms, the performance can be the solution quality.']) - end - if strcmp(Setting.Metric,'runtimeSec') && isempty(Setting.Tmax) - error('Please set "Setting.Tmax" as the maximum runtime (seconds).') - end - if strcmp(Setting.Metric,'runtimeSec') && isempty(Setting.Thres) - error(['Please set "Setting.Thres" as the lowest acceptable performance ' ... - 'of the design algorithms, the performance can be the solution quality.']) - end - - % time (Tmax) should be function evaluations when using auc - if strcmp(Setting.Metric,'auc') && numel(Setting.Tmax) <= 1 - error(['"Setting.Tmax" should contain multiple time points. The time ' ... - 'points should the numbers of function evaluations spent during ' ... - 'the alorithm execution.']) - end - - % thresholds should be corresponding to time points when using auc - if strcmp(Setting.Metric,'auc') && numel(Setting.Thres) ~= numel(Setting.Tmax) - error(['The number of thresholds in "Setting.Thres" should be equal to ' ... - 'the number of time points in "Setting.Tmax". "Setting.Thres" ' ... - 'refers to the lowest acceptable performance of the design' ... - ' algorithms, the performance can be the solution quality.']) - end - end - varargout{1} = Setting; -end -end \ No newline at end of file diff --git a/matlab/Utilities/Others/Output.m b/matlab/Utilities/Others/Output.m deleted file mode 100644 index 4f8d392..0000000 --- a/matlab/Utilities/Others/Output.m +++ /dev/null @@ -1,191 +0,0 @@ -function Output(varargin) -% Save and output the results. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -Setting = varargin{end}; -switch Setting.Mode - case 'design' - algs = varargin{1}; - algTrace = varargin{2}; - instanceTrain = varargin{3}; - instanceTest = varargin{4}; - if nargin > 5 - app = varargin{end-1}; - end - - % delete previous files - delete('Algs.xlsx') - - % save algorithm representations - save('Algs.mat','algs'); - - %% save final algorithms' pseudocode - allCode = cell(50,Setting.AlgN); - for i = 1:Setting.AlgN - code = pseudocode(algs(i),Setting,i,'final'); - if length(code) > size(allCode,1) - error('Please set the number of rows of "allCode" larger than the length of "code".'); - end - allCode(1:length(code),i) = code; - % display on GUI - if i == 1 && exist('app','var') - app.TextArea2.Value = code; - end - end - writecell(allCode,'Algs.xlsx','Sheet','Final Algs'); - - %% save final algorithms' performance - firstRow = cell(1,Setting.AlgN+1); - firstRow{1} = 'Instance Index'; - firstRow{2} = 'Best Algorithm'; - for i = 2:Setting.AlgN - firstRow{i+1} = ['Algorithm ',num2str(i)]; - end - sheetName = 'Perf of Final Algs'; - writecell(firstRow,'Algs.xlsx','Sheet',sheetName,'Range','A1'); - - firstColumn = repmat(instanceTest',1,Setting.AlgRuns); - firstColumn = reshape(firstColumn',length(instanceTest)*Setting.AlgRuns,1); - writematrix(firstColumn,'Algs.xlsx','Sheet',sheetName,'Range','A2'); - - performance = zeros(numel(instanceTest)*Setting.AlgRuns,length(algs)); - for i = 1:length(algs) - % reshape algorithm i's all performance values (each run on each instance) to a column vector - performance(:,i) = reshape(algs(i).performance(numel(instanceTrain)+1:numel(instanceTrain)+numel(instanceTest),:)',size(performance,1),1); - end - - writematrix(performance,'Algs.xlsx','Sheet',sheetName,'Range','B2'); - - %% save pseudocode of the best algorithms found at each iteration of design - allCode = cell(50,length(algTrace)); - for i = 1:length(algTrace) - code = pseudocode(algTrace(i),Setting,i,'iterate'); - if length(code) > size(allCode,1) - error('Please set the number of rows of "allCode" larger than the length of "code".'); - end - allCode(1:length(code),i) = code; - end - writecell(allCode,'Algs.xlsx','Sheet','Best Algs at Iteration'); - - %% save performance of the best algorithms found at each iteration of design - firstRow = cell(1,length(algTrace)+1); - firstRow{1} = 'Instance Index'; - for i = 1:length(algTrace) - firstRow{i+1} = ['Algorithm at Iteration ',num2str(i)]; - end - sheetName = 'Perf of Best Algs at Iteration'; - writecell(firstRow,'Algs.xlsx','Sheet',sheetName,'Range','A1'); - - firstColumn = repmat(instanceTrain',1,Setting.AlgRuns); - firstColumn = reshape(firstColumn',length(instanceTrain)*Setting.AlgRuns,1); - writematrix(firstColumn,'Algs.xlsx','Sheet',sheetName,'Range','A2'); - - performTrace = zeros(numel(instanceTrain)*Setting.AlgRuns,length(algTrace)); - for i = 1:length(algTrace) - % reshape algorithm i's all performance values (each run on each instance) to a column vector - performTrace(:,i) = reshape(algTrace(i).performance(1:numel(instanceTrain),:)',size(performTrace,1),1); - end - writematrix(performTrace,'Algs.xlsx','Sheet',sheetName,'Range','B2'); - - %% depict the convergence curve of the design process - performTrace = mean(performTrace,1); - curve = plot(1:length(performTrace),performTrace); - xlabel('Iterations'); - ylabel('Performance'); - title('Convergence Curve of the Design Process'); - saveas(curve,'Convergence Curve of the Design Process'); - close; - - case 'solve' - bestSolutions = varargin{1}; - allSolutions = varargin{2}; - instance = varargin{3}; - - % delete previous files - delete('Solutions.xlsx') - - name = strcat(Setting.AlgName,int2str(Setting.problem_id)); - % save original format of solutions - save(name,'bestSolutions','allSolutions'); - - %% save solutions and fitness obtained in the best run on each problem instance - numIterations = size(allSolutions,2); - solutions = cell(1+length(instance),2+numIterations); - solutions{1,1} = 'Instance Index'; - solutions{1,2} = 'Best Solution'; - fitness = cell(1+length(instance),2+numIterations); - fitness{1,1} = 'Instance Index'; - fitness{1,2} = 'Best Solution'; - constraint = cell(1+length(instance),2+numIterations); - constraint{1,1} = 'Instance Index'; - constraint{1,2} = 'Best Solution'; - for i = 1:numIterations - solutions{1,2+i} = ['Iteration ',num2str(i)]; - fitness{1,2+i} = ['Iteration ',num2str(i)]; - constraint{1,2+i} = ['Iteration ',num2str(i)]; - end - for i = 1:length(instance) - solutions{1+i,1} = instance(i); - fitness{1+i,1} = instance(i); - constraint{1+i,1} = instance(i); - [~,best] = min(allSolutions(i,:).fits); - solutions{1+i,2} = num2str(allSolutions(i,best).dec); - fitness{1+i,2} = num2str(allSolutions(i,best).fit); - constraint{1+i,2} = num2str(allSolutions(i,best).con); - for j = 1:numIterations - solutions{1+i,2+j} = num2str(allSolutions(i,j).dec); - fitness{1+i,2+j} = num2str(allSolutions(i,j).fit); - constraint{1+i,2+j} = num2str(allSolutions(i,j).con); - end - % depict convergence curves - if i <= 20 - curve = plot(1:numIterations,allSolutions(i,:).fits); - xlabel('Iterations'); - ylabel('Fitness'); - title(['Convergence Curve of Instance ',num2str(instance(i))]); - saveas(curve,['Convergence Curve of Instance ',num2str(instance(i))]); - close; - else - warning('Only display the first 20 instances for saving computational resources.') - end - end - writecell(solutions,'Solutions.xlsx','Sheet','Solutions','Range','A1'); - writecell(fitness,'Solutions.xlsx','Sheet','Fitness','Range','A1'); - writecell(constraint,'Solutions.xlsx','Sheet','Constraint Violation','Range','A1'); - - %% save fitness of all runs on each problem instance - fitnessAll = cell(1+length(instance),3+Setting.AlgRuns); - fitnessAll{1,1} = 'Instance Index'; - fitnessAll{1,2} = 'Mean'; - fitnessAll{1,3} = 'Std'; - for i = 1:Setting.AlgRuns - fitnessAll{1,3+i} = ['Run ',num2str(i)]; - end - for i = 1:length(instance) - fitnessAll{1+i,1} = instance(i); - fitnessAll{1+i,2} = num2str(mean(bestSolutions(i,:).fits)); - fitnessAll{1+i,3} = num2str(std(bestSolutions(i,:).fits)); - for j = 1:Setting.AlgRuns - fitnessAll{1+i,3+j} = num2str(bestSolutions(i,j).fit); - end - end - writecell(fitnessAll,'Solutions.xlsx','Sheet','Fitness of All Runs','Range','A1'); -end \ No newline at end of file diff --git a/matlab/Utilities/Others/Process.m b/matlab/Utilities/Others/Process.m deleted file mode 100644 index eda2c6c..0000000 --- a/matlab/Utilities/Others/Process.m +++ /dev/null @@ -1,119 +0,0 @@ -function [output1,output2] = Process(varargin) -% The main process of algorithm design and problem solving. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -if strcmp(varargin{1}(end:-1:end-1),'m.') - varargin{1}(end:-1:end-1)=[]; % delete '.m' -end -Setting = varargin{end}; -switch Setting.Mode - case 'design' - tic; - str = 'Initializing...'; - if nargin > 4 - app = varargin{end-1}; - app.TextArea.Value = str; - drawnow; - bar = []; - else - app = []; - bar = waitbar(0,str); - end - %% construct training problem properties - Problem = struct('name',[],'type',[],'bound',[],'setting',{''},'N',[],'Gmax',[]); - instanceTrain = varargin{2}; - instanceTest = varargin{3}; - seedTrain = randperm(numel(instanceTrain)); - seedTest = randperm(numel(instanceTest))+length(seedTrain); - instance = [instanceTrain,instanceTest]; - for i = 1:numel(instance) - Problem(i).name = varargin{1}; - Problem(i).setting = ''; - Problem(i).N = Setting.ProbN; - Problem(i).Gmax = ceil(Setting.ProbFE/Setting.ProbN); - Problem(i).problem_id = Setting.problem_id; - end - [Problem,Data,~] = feval(str2func(Problem(1).name),Problem,instance,'construct'); % infill problems' constraints and search boundary, construct data properties - - - %% design algorithms - Setting = Space(Problem,Setting); % get design space - obj = DESIGN; - switch Setting.Generate - case 'search' % search algorithms via heuristics - [Algs,AlgTrace] = obj.Search(Problem,Data,Setting,seedTrain,app,bar); - - case 'learn' % learn the algorithm distribution via transformer and reinforcement learning - [Algs,AlgTrace] = obj.Learn(Problem,Data,Setting,seedTrain,app,bar); - case 'get-p' - output1 = obj.Get_performance(Problem,Data,Setting,seedTrain); - return; - end - - %% test the designed algorithms - str = 'Testing... '; - if ~isempty(app) - app.TextArea.Value = str; - drawnow; - else - waitbar(100,bar,str); - end - Setting.Evaluate = 'exact'; - Algs = Algs.Evaluate(Problem,Data,Setting,seedTest); - Algs = Algs.Select(Problem,Data,Setting,seedTest); % sort algorithms in descending order in terms of their performance - output1 = Algs; % final algorithms - output2 = AlgTrace; % best algorithms found at each iteration of design - - str = 'Complete'; - if ~isempty(app) - app.TextArea.Value = str; - drawnow; - else - waitbar(100,bar,str); - end - toc; - - case 'solve' - %% construct problem properties - ProblemSolve = struct('name',[],'type',[],'bound',[],'setting',{''},'N',[],'Gmax',[]); - instanceSolve = varargin{2}; - for i = 1:numel(instanceSolve) - ProblemSolve(i).name = varargin{1}; - ProblemSolve(i).setting = ''; - ProblemSolve(i).N = Setting.ProbN; - ProblemSolve(i).Gmax = ceil(Setting.ProbFE/Setting.ProbN); - ProblemSolve(i).problem_id =Setting.problem_id; - end - [ProblemSolve,DataSolve,~] = feval(str2func(ProblemSolve(1).name),ProblemSolve,instanceSolve,'construct'); % infill problems' constraints and search boundary, construct data properties - - %% solve the problem - Solution = SOLVE; - [Alg,Setting] = Solution.InputAlg(Setting); % algorithm profile - if nargin > 3 - app = varargin{end-1}; - [bestSolutions,allSolutions] = Solution.RunAlg(Alg,ProblemSolve,DataSolve,app,Setting); - else - [bestSolutions,allSolutions] = Solution.RunAlg(Alg,ProblemSolve,DataSolve,[],Setting); - end - output1 = bestSolutions; % the best solution at the final iteration of each algorithm run - output2 = allSolutions; % the best solution at each iteration of the best algorithm run -end -end \ No newline at end of file diff --git a/matlab/Utilities/Others/pseudocode.m b/matlab/Utilities/Others/pseudocode.m deleted file mode 100644 index 2e5471f..0000000 --- a/matlab/Utilities/Others/pseudocode.m +++ /dev/null @@ -1,219 +0,0 @@ -function Code = pseudocode(algorithm,Setting,algInd,state) -% Output the pseudocode of the designed algorithm. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -% prepare choose -choose = algorithm.operatorPheno{1}.Choose; -choose = [choose,'(']; -parameter = algorithm.parameterPheno{1}.Choose; -for j = 1:numel(parameter) - temp = num2str(parameter(j)); - choose = [choose,temp,',']; -end -choose = [' S = ',choose,'S)']; - -% prepare update -update = algorithm.operatorPheno{1}.Update; -update = [update,'(']; -parameter = algorithm.parameterPheno{1}.Update; -for j = 1:numel(parameter) - temp = num2str(parameter(j)); - update = [update,temp,',']; -end -update = [' S = ',update,'S,S_new)']; - -% prepare archive -if ~isempty(algorithm.operatorPheno{1}.Archive) - archive = algorithm.operatorPheno{1}.Archive; - archive = [' A = ',archive,'(A,S)']; -end - -if Setting.AlgP == 1 - Code = cell(4+7*size(algorithm.operatorPheno{1}.Search,1),1); - k = 1; - - % first row - switch state - case 'final' - if algInd == 1 - Code{k} = 'Best algorithm:'; k = k+1; - else - Code{k} = ['Algorithm ',num2str(algInd),':']; k = k+1; - end - case 'iterate' - Code{k} = ['Algorithm at Iteration ',num2str(algInd),':']; k = k+1; - end - - % initialize - Code{k} = 'S = initialize()'; k = k+1; - - % archive - if ~isempty(algorithm.operatorPheno{1}.Archive) - Code{k} = archive; k = k+1; - end - - % while - Code{k} = 'while algorithm termination condition not met'; k = k+1; - - % for each search operation - for j = 1:size(algorithm.operatorPheno{1}.Search,1) - % prepare search - termninate1 = num2str(algorithm.operatorPheno{1}.Search{j,end}(1)); - termninate2 = num2str(algorithm.operatorPheno{1}.Search{j,end}(2)); - search = algorithm.operatorPheno{1}.Search{j,1}; - parameter = algorithm.parameterPheno{1}.Search{j,1}; - search = [search,'(']; - for l = 1:numel(parameter) - temp = num2str(parameter(l)); - search = [search,temp,',']; - end - search = [' S_new = ',search,'S)']; - % if is a sexual evolutonary algorithm with crossover and mutation - if ~isempty(algorithm.operatorPheno{1}.Search{j,2}) - search2 = algorithm.operatorPheno{1}.Search{j,2}; - parameter2 = algorithm.parameterPheno{1}.Search{j,2}; - search2 = [search2,'(']; - for l = 1:numel(parameter2) - temp = num2str(parameter2(l)); - search2 = [search2,temp,',']; - end - search2 = [' S_new = ',search2,'S_new)']; - end - - % search - if algorithm.operatorPheno{1}.Search{j,end}(2) == 1 % global search - Code{k} = choose; k = k+1; - Code{k} = search; k = k+1; - if ~isempty(algorithm.operatorPheno{1}.Search{j,2}) - Code{k} = search2; k = k+1; - end - Code{k} = update; k = k+1; - if ~isempty(algorithm.operatorPheno{1}.Archive) - Code{k} = archive; k = k+1; - end - else % ierative local search - Code{k} = [' while solution improvement>',termninate1,' or inner_iteration<=',termninate2]; k = k+1; - Code{k} = [' ',choose]; k = k+1; - Code{k} = [' ',search]; k = k+1; - if ~isempty(algorithm.operatorPheno{1}.Search{j,2}) - Code{k} = [' ',search2]; k = k+1; - end - Code{k} = [' ',update]; k = k+1; - if ~isempty(algorithm.operatorPheno{1}.Archive) - Code{k} = [' ',archive]; k = k+1; - end - Code{k} = ' end while'; k = k+1; - end - end - Code{k} = 'end while'; -else - Code = cell(7+2*Setting.AlgP,1); - k = 1; - - % first row - switch state - case 'final' - if algInd == 1 - Code{k} = 'Best algorithm:'; k = k+1; - else - Code{k} = ['Algorithm ',num2str(algInd),':']; k = k+1; - end - case 'iterate' - Code{k} = ['Algorithm at Iteration ',num2str(algInd),':']; k = k+1; - end - - % initialize - Code{k} = 'S = initialize()'; k = k+1; - - % archive - if ~isempty(algorithm.operatorPheno{1}.Archive) - Code{k} = archive; k = k+1; - end - - % while - Code{k} = 'while algorithm termination condition not met'; k = k+1; - - % choose - Code{k} = choose; k = k+1; - - % prepare subpopulation - dividePop = ' {S1,'; - for j = 2:Setting.AlgP - dividePop = [dividePop,'S',num2str(j),',']; - end - dividePop = [dividePop(1:end-1),'} = S']; - mergePop = ' S_new = {S1_new,'; - for j = 2:Setting.AlgP - mergePop = [mergePop,'S',num2str(j),'_new,']; - end - mergePop = [mergePop(1:end-1),'}']; - - % divide population - Code{k} = dividePop; k = k+1; - - % for each search pathway - for j = 1:Setting.AlgP - % prepare search - search = algorithm.operatorPheno{j}.Search{1}; - parameter = algorithm.parameterPheno{j}.Search{1}; - search = [search,'(']; - for l = 1:numel(parameter) - temp = num2str(parameter(l)); - search = [search,temp,',']; - end - search = [' S',num2str(j),'_new = ',search,'S',num2str(j),')']; - % if is a sexual evolutonary algorithm with crossover and mutation - if ~isempty(algorithm.operatorPheno{j}.Search{2}) - search2 = algorithm.operatorPheno{j}.Search{2}; - parameter2 = algorithm.parameterPheno{j}.Search{2}; - search2 = [search2,'(']; - for l = 1:numel(parameter2) - temp = num2str(parameter2(l)); - search2 = [search2,temp,',']; - end - search2 = [' S',num2str(j),'_new = ',search2,'S',num2str(j),')']; - end - - % search - Code{k} = search; k = k+1; - if ~isempty(algorithm.operatorPheno{j}.Search{2}) - Code{k} = search2; k = k+1; - end - end - - % merge subpopulation - Code{k} = mergePop; k = k+1; - - % update - Code{k} = update; k = k+1; - - % archive - if ~isempty(algorithm.operatorPheno{1}.Archive) - Code{k} = archive; k = k+1; - end - - Code{k} = 'end while'; -end - -% delete empty rows -rowDelete = cellfun(@isempty,Code(:,1)); -Code(rowDelete,:) = []; -end \ No newline at end of file diff --git a/matlab/Utilities/Solutions.xlsx b/matlab/Utilities/Solutions.xlsx deleted file mode 100644 index 294e586..0000000 Binary files a/matlab/Utilities/Solutions.xlsx and /dev/null differ diff --git a/matlab/Utilities/Space.m b/matlab/Utilities/Space.m deleted file mode 100644 index 3acde8f..0000000 --- a/matlab/Utilities/Space.m +++ /dev/null @@ -1,84 +0,0 @@ -function Setting = Space(Problem,Setting) -% Define the design space. - -%----------------------------Copyright------------------------------------- -% Copyright (C) <2023> - -% AutoOptLib is a free software. You can use, redistribute, and/or modify -% it under the terms of the GNU General Public License as published by the -% Free Software Foundation, either version 3 of the License, or any later -% version. - -% Please reference the paper below if using AutoOptLib in your publication: -% @article{zhao2023autooptlib, -% title={AutoOptLib: A Library of Automatically Designing Metaheuristic -% Optimization Algorithms in Matlab}, -% author={Zhao, Qi and Yan, Bai and Hu, Taiwei and Chen, Xianglong and -% Yang, Jian and Shi, Yuhui}, -% journal={arXiv preprint arXiv:2303.06536}, -% year={2023} -% } -%-------------------------------------------------------------------------- - -% operater space -switch Problem(1).type{1} - case 'continuous' - Choose = {'choose_traverse';'choose_tournament';'choose_roulette_wheel';'choose_brainstorm';'choose_nich'}; - Search = {'search_pso';'search_de_current';'search_de_current_best';'search_de_random'; - 'cross_arithmetic';'cross_sim_binary';'cross_point_one';'cross_point_two'; - 'cross_point_uniform';'search_mu_gaussian';'search_mu_cauchy';'search_mu_polynomial'; - 'search_mu_uniform';'search_eda';'search_cma';'reinit_continuous'}; - Update = {'update_greedy';'update_round_robin';'update_pairwise';'update_always';'update_simulated_annealing'}; - - case 'discrete' - Choose = {'choose_traverse';'choose_tournament';'choose_roulette_wheel';'choose_nich'}; - Search = {'cross_point_one';'cross_point_two';'cross_point_n';'cross_point_uniform';'search_reset_one'; - 'search_reset_n';'search_reset_rand';'reinit_discrete'}; - Update = {'update_greedy';'update_round_robin';'update_pairwise';'update_always';'update_simulated_annealing'}; - - case 'permutation' - Choose = {'choose_traverse';'choose_tournament';'choose_roulette_wheel';'choose_nich'}; - Search = {'cross_order_two';'cross_order_n';'search_swap';'search_swap_multi'; - 'search_scramble';'search_insert';'reinit_permutation'}; - Update = {'update_greedy';'update_round_robin';'update_pairwise';'update_always';'update_simulated_annealing'}; -end -Setting.TunePara = false; % true/false, turn to true if perform hyperparameter configuration - -OpSpace = [1,length(Choose); - length(Choose)+1,length(Choose)+length(Search); - length(Choose)+length(Search)+1,length(Choose)+length(Search)+length(Update)]; % each row reports the search space of one kind of operaters, e.g., the search space of Choose is intergers from 1 to 4. -AllOp = [Choose;Search;Update]; - -% parameter and behavior space -ParaSpace = cell(length(AllOp),1); % parameter space -ParaLocalSpace = cell(length(AllOp),1); % parameter space for performing local search -BehavSpace = cell(length(AllOp),1); % search behaviors -for i = 1:length(AllOp) - [thisParaSpace,~] = feval(str2func(AllOp{i}),Problem,'parameter'); - [thisBehavSpace,~] = feval(str2func(AllOp{i}),'behavior'); - ParaSpace{i} = thisParaSpace; - BehavSpace{i} = thisBehavSpace; - if ~isempty(thisBehavSpace{1,1}) && ~isempty(thisParaSpace) % if the operator can perform local search and has parameter(s) - if isempty(thisBehavSpace{2,1}) % if only performs local search - thisParaLocalSpace = thisParaSpace; - else - thisParaLocalSpace = zeros(size(thisParaSpace)); - for j = 1:size(thisParaLocalSpace,1) % for each parameter of operator i - lower = thisParaSpace(j,1); - upper = thisParaSpace(j,2); - trend = thisBehavSpace{1,j+1}; % parameter setting for local search - if strcmp(trend,'small') - thisParaLocalSpace(j,:) = [lower,lower+(upper-lower)*Setting.LSRange]; - elseif strcmp(trend,'large') - thisParaLocalSpace(j,:) = [upper-upper*Setting.LSRange,upper]; - end - end - end - ParaLocalSpace{i} = thisParaLocalSpace; - end -end -Setting.OpSpace = OpSpace; -Setting.AllOp = AllOp; -Setting.ParaSpace = ParaSpace; -Setting.ParaLocalSpace = ParaLocalSpace; -Setting.BehavSpace = BehavSpace; \ No newline at end of file diff --git a/matlab/__pycache__/IOH_Test.cpython-36.pyc b/matlab/__pycache__/IOH_Test.cpython-36.pyc deleted file mode 100644 index 3789ecb..0000000 Binary files a/matlab/__pycache__/IOH_Test.cpython-36.pyc and /dev/null differ diff --git a/matlab/__pycache__/IOH_Test.cpython-38.pyc b/matlab/__pycache__/IOH_Test.cpython-38.pyc deleted file mode 100644 index db02938..0000000 Binary files a/matlab/__pycache__/IOH_Test.cpython-38.pyc and /dev/null differ diff --git a/matlab/__pycache__/IOH_Test.cpython-39.pyc b/matlab/__pycache__/IOH_Test.cpython-39.pyc deleted file mode 100644 index e5d7902..0000000 Binary files a/matlab/__pycache__/IOH_Test.cpython-39.pyc and /dev/null differ diff --git a/matlab/eval_alg.m b/matlab/eval_alg.m deleted file mode 100644 index 51167b0..0000000 --- a/matlab/eval_alg.m +++ /dev/null @@ -1,205 +0,0 @@ -exact_datas_from_ArchSolution(); -function run_compare_alg() -alglist = ["Discrete Genetic Algorithm","Discrete Iterative Local Search","Discrete Simulated Annealing"]; -alglist = ["Discrete Simulated Annealing"]; -for instance =1:3 - for i = 1:numel(alglist) - media_res=[]; - for j = 2:23 - AutoOpt('Mode','solve','Problem','pbo','InstanceSolve',[4],'AlgName',alglist(i),'ProbN',50000,'ProbFE',50,'AlgRuns',30,'problem_id',j); - res =[]; - load(strcat(alglist(i),int2str(j))); - [x, y] = size(bestSolutions); - for ii =1: y - res(ii)=cat(1,bestSolutions(1,ii).fit); - end - path = strcat('result/',strrep(alglist(i), ' ', '_'),'/instance_',int2str(instance),'/'); - % 确保路径存在 - if ~exist(path, 'dir') - mkdir(path); - addpath(genpath('result')); - end - fullpath = strcat(path,'f',int2str(j)); - save(fullpath,'res') - disp(fullpath); - media_res(j)=median(res); - end - end -end -end - -function cal_compare_mean_var() - alglist = ["Discrete Genetic Algorithm", "Discrete Iterative Local Search","Discrete Simulated Annealing"]; - - for instance = 1:3 - for i = 1:numel(alglist) - total_mean = []; - total_var = []; - for j = 1:23 - path = strcat('result/',strrep(alglist(i), ' ', '_'),'/instance_',int2str(instance),'/'); - fullpath = strcat(path,'f',int2str(j)); - load(fullpath); - total_mean(1,j) = -mean(res); %performance为了最小化问题取反,这里取反为正常值 - total_var(1,j) = var(res); - end - % 写入均值矩阵到 Excel 文件的第一个工作表 - filename = strcat(path,'mean_var_design_data.xlsx'); % Excel 文件名 - mean_sheet = 'Mean'; % 均值工作表名称 - xlswrite(filename, total_mean, mean_sheet); - - % 写入方差矩阵到 Excel 文件的第二个工作表 - var_sheet = 'Variance'; % 方差工作表名称 - xlswrite(filename, total_var, var_sheet); - end -end - -end - -function run_design_alg() -B{1}=[2,13,7,24,9,18,8]; -B{2}=[2,13,4,9,19]; -B{3}=[1,12,7,26,8]; -B{4}=[2,11,4,9,18,8]; -B{5}=[1,12,5,8]; -B{6}=[0,12,7,25,8]; -B{7}=[0,11,5,8]; -B{8}=[2,11,5,8]; -B{9}=[3,11,7,24,8]; -B{10}=[1,13,7,24,8]; -B{11}=[2,11,7,18,9,18]; -B{12}=[2,13,7,18,9,18]; -B{13}=[2,14,5,9,18]; -B{14}=[1,13,7,23,9,20]; -B{15}=[1,13,5,8,9,20]; -B{16}=[2,14,7,19,9,19]; -B{17}=[0,11,6,21,9,20]; -B{18}=[2,14,4,8]; -B{19}=[2,14,4,8]; -B{20}=[2,12,7,26,9,18,8]; -B{21}=[2,12,5,8]; -B{22}=[0,12,7,25,8]; -B{23}=[1,11,7,21,8]; - -%for another run: -% B{2}=[2, 15, 18, 7, 18, 9, 18]; -% B{3}=[2, 13, 8, 4, 9, 18]; -% B{4}=[ 2, 11, 10, 7, 19, 8]; -% B{5}=[2, 15, 24, 4, 8]; -% B{6}=[1, 11, 7, 26, 8]; -% B{7}=[2, 13, 8, 5, 9, 18,]; -% -% B{8}=[2, 11, 5, 8]; -% B{9}=[ 2, 13, 9, 18, 5, 8]; -% B{10}=[1, 15, 21, 7, 23, 8]; -% B{11}=[2, 11, 9, 18, 4, 8]; -% B{12}=[2, 15, 22, 4, 9, 18]; -% B{13}=[2, 14, 5, 9, 18]; -% B{14}=[1, 11, 7, 25, 9, 20]; -% B{15}=[2, 11, 5, 9, 19]; -% B{16}=[ 0, 12, 7, 24, 9, 19]; -% B{17}=[3, 15, 19, 5, 8, 9, 20]; -% B{18}=[2, 15, 25, 5, 9, 19, 8]; -% B{19}=[2, 14, 5, 8]; -% B{20}=[2, 11, 9, 21, 7, 20]; -% B{21}=[2, 11, 7, 26, 8]; -% B{22}=[1, 12, 5, 8]; -% B{23}=[1, 12, 7, 24, 8]; - -for j = 4 %1:3 - indices = [1, 13, 15, 20]; - for i = indices % 1:23 - info = ['instance:',int2str(j),' problem:',int2str(i)]; - disp(info) - %datestr(now()) - [performance, change,solution] = get_per(B{i},i,[j],1); - continue; - path = ['result/design/instance_',int2str(j),'/']; - % 确保路径存在 - if ~exist(path, 'dir') - mkdir(path); - addpath(genpath('result')); - end - fullpath = [path,'f',int2str(i)]; - res = performance(1,:); - % save original format of solutions - save(fullpath,'res'); - %datestr(now()) - end -end -end - -function cal_design_mean_var() -total_mean = []; -total_var = []; -for i = 1:3 - for j = 1:23 - path = ['result/design/instance_',int2str(i),'/f',int2str(j)]; - load(path); - total_mean(1,j) = -mean(res); - total_var(1,j) = var(res); - end - - % 写入均值矩阵到 Excel 文件的第一个工作表 - filename = ['result/design/instance_',int2str(i),'/mean_var_design_data.xlsx']; % Excel 文件名 - mean_sheet = 'Mean'; % 均值工作表名称 - xlswrite(filename, total_mean, mean_sheet); - - % 写入方差矩阵到 Excel 文件的第二个工作表 - var_sheet = 'Variance'; % 方差工作表名称 - xlswrite(filename, total_var, var_sheet); - end -end - -function run_train_in_one_design_alg() -B{1}=[1,11,7,26,8]; -B{2}=[2,13,7,26,8,9,18]; -B{3}=[1,11,7,26,8]; -B{4}=[1,11,7,26,8]; -B{5}=[1,11,7,26,8]; -B{6}=[1,11,7,26,8]; -B{7}=[1,11,7,26,8]; -B{8}=[1,11,7,26,8]; -B{9}=[3,11,7,24,8]; -B{10}=[1,13,7,24,8]; -B{11}=[2,11,7,18,9,18]; -B{12}=[2,13,7,18,9,18]; -B{13}=[2,14,5,9,18]; -B{14}=[1,13,7,23,9,20]; -B{15}=[1,13,5,8,9,20]; -B{16}=[2,14,7,19,9,19]; -B{17}=[0,11,6,21,9,20]; -B{18}=[2,14,4,8]; -B{19}=[2,14,4,8]; -B{20}=[2,12,7,26,9,18,8]; -B{21}=[2,12,5,8]; -B{22}=[0,12,7,25,8]; -B{23}=[1,11,7,21,8]; - for i = 1:1:8 - i - datestr(now()) - [performance, change,solution] = get_per(B{i},i,[4],1); - name = 'result/train_in_one'+int2str(i); - res = performance(1,:); - % save original format of solutions - save(name,'res'); - datestr(now()) - end - - end - -function run_autoopt_for_pbo() -AutoOpt('Mode','design','Problem','pbo','InstanceTrain',[1,2,3],'InstanceTest',4,'problem_id',1) -end - -function exact_datas_from_ArchSolution() - data_path = '../draw/datas/mats/ArchSolution/'; - problem_set = [1,13,15,20] - for problem = problem_set - path = [data_path,'ArchSolution',int2str(problem),'.mat'] - load(path); - res = [ArchSolution(1,:).fit]; - save([data_path,'f',int2str(problem)],'res') - end - -end - diff --git a/matlab/get_perf.m b/matlab/get_perf.m deleted file mode 100644 index a2c6666..0000000 --- a/matlab/get_perf.m +++ /dev/null @@ -1,122 +0,0 @@ -function performance = get_perf(seq,problem_id,instanceTrain,eval) -% get the performance of the designed algorithm - -addpath(genpath('Utilities')); -addpath(genpath('Problems')); -addpath(genpath('Main')); -addpath(genpath('Components')); -addpath(genpath('C:\Program Files\MATLAB\R2020b\toolbox\matpower7.1')); -warning('off') - -% seq = [1.0,29.0, 9.0,19.0,29.0, 12.0,29.0]; % simple one search operator -% seq = [2.0,29.0, 5.0,29.0, 10.0,20.0,29.0, 13.0,29.0]; % simple GA -% seq = [3.0,31.0,21.0, 8.0,29.0, 11.0,29.0, 14.0,29.0]; % with fork -% seq = [0.0,29.0, 8.0,30.0,21.0, 11.0,29.0, 16.0,19.0,29.0]; % with iterate -% seq = [3.0,31.0,20.0,8.0,29.0,12.0,29.0]; - -% instanceTrain = 1; -% problem_id = 0; -% eval = 0; - -% setting -problem = 'pbo'; % target problem, pbo/beamforming/blackstart -seq_max_comp = 6; % maximun number of components in a sequence -num_comp = 17; % number of candidate components -other_token = {'begin';'end';1;2;3;4;5;6;7;8;9;10;'forward';'iterate';'fork'}; % tokens that not involved in the matlab AutoOpt software -values = {0;0;0;0; 0;0;1;1;0;1;1;0; 0;0;0;0;1; 0;0;0;0;0;0;0;0;0;0;0;0; 0;1;1}; % number of hyperparameters of each token -dict_conds = [0.01,0.05,0.1,0.15,0.2]; % candidate count conditions -dict_forks = 1:seq_max_comp; % hyperparameters of fork pointer - -% prepare -switch problem - case 'pbo' - [Problem,Data,Setting,seedTrain] = opt_env('Mode','design','Problem','pbo','InstanceTrain',instanceTrain,'InstanceTest',1,'Problem_id',problem_id,'eval',eval); - case 'beamforming' - [Problem,Data,Setting,seedTrain] = opt_env('Mode','design','Problem','beamforming','InstanceTrain',instanceTrain,'InstanceTest',3,'Problem_id',problem_id,'eval',eval); - case 'blackstart' - [Problem,Data,Setting,seedTrain] = opt_env('Mode','design','Problem','blackstart','InstanceTrain',instanceTrain,'InstanceTest',[],'Problem_id',problem_id,'eval',eval); -end -seq = seq + 1; % python list from 0, add 1 in matlab -keys = [Setting.AllOp;other_token]; % all tokens -dict = [keys,values]; % for decoding the sequence representation of the designed algorithm - -% decode the sequence -indOp = []; % indexes of components -Paras = cell(num_comp,2); % 17 components' hyperparameters -Conds = zeros(num_comp,1); % 17 components, each has 1 condition -ParaSpace = Setting.ParaSpace; -indPtr = []; % indexes of pointers -paraPtr = []; % conditions associated with the iterate pointer or hyperparameter of the fork pointer -i = 1; -while i <= length(seq) - thisToken = seq(i); - numPara = dict{thisToken,2}; % number of hyperparameters of this token - - if thisToken <= num_comp % if component - indOp = [indOp,thisToken]; - if numPara > 0 - tempPara = zeros(numel(numPara),1); - for j = 1:numel(numPara) - para = dict{seq(i+j),1}; % the next token - tempPara(j) = ParaSpace{thisToken}(:,1) + (ParaSpace{thisToken}(:,2)-ParaSpace{thisToken}(:,1))/9.*(para-1); % min+(max-min)/9*(para-1) - end - Paras{thisToken,1} = tempPara; - i = i+1+numel(numPara); - else - i = i+1; - end - elseif thisToken > size(keys,1)-3 % if pointer - indPtr = [indPtr,thisToken]; - if numPara == 1 % iterate or fork pointer - para = dict{seq(i+1),1}; - if thisToken == size(keys,1)-1 % if iterate pointer, para is the count condition - para = dict_conds(para); - elseif thisToken == size(keys,1) % if fork pointer, para is the hyperparameter of fork - para = dict_forks(para) - 1; % dict_forks(para); - end - paraPtr = [paraPtr,para]; - i = i+2; - elseif numPara == 0 % forward pointer - paraPtr = [paraPtr,0]; - i = i+1; - end - end -end - -indFork = find(indPtr==32); % indexes (in indOp) of components that are associated with the fork pointer -Setting.AlgP = numel(indFork)+1; % number of branches determined by the fork pointer -Operators = cell(1,Setting.AlgP); -for i = 1:Setting.AlgP - % for the fork pointer and its hyperparameter - if i == 1 % the first branch (whole sequence) - indOpTemp = indOp; - else % sequence segments determined by fork - paraPtr(indFork(i-1)) = min(paraPtr(indFork(i-1)),length(indOp)); - indOpTemp = [indOp(1:indFork(i-1)),indOp(paraPtr(indFork(i-1)):end)]; - end - - opAdjMat = []; % operators' graph representation (adjacent matrix) to fit the AutoOpt software - for j = 1:length(indOpTemp)-1 - opAdjMat = [opAdjMat;indOpTemp(1,j:j+1)]; - end - Operators{i} = opAdjMat; - - % for the forward and iterate pointers and the count condition - indSearch = indOpTemp(2:end-1); % indexes of search operators - for k = 1:numel(indSearch) - if indPtr(k+1) == size(keys,1)-1 % if the search component is associated with the iterate pointer - Paras{indSearch(k),2} = 'LS'; % the search component iterate - Conds(indSearch(k)) = paraPtr(k+1)*Setting.ProbFE; - elseif indPtr(k+1) == size(keys,1)-2 % if the search component is associated with the forward pointer - Paras{indSearch(k),2} = 'GS'; % the search component forward - end - end -end -Setting.Conds = Conds; - -% evaluate the designed algorithm by the AutoOpt software -Alg = DESIGN; -Alg = Alg.Construct2(Operators,Paras,Problem,Setting); -[Alg,~] = Alg.Evaluate(Problem,Data,Setting,seedTrain); -performance = Alg.performance; -end \ No newline at end of file diff --git a/matlab/irace_sa.py b/matlab/irace_sa.py deleted file mode 100644 index 5630ff8..0000000 --- a/matlab/irace_sa.py +++ /dev/null @@ -1,218 +0,0 @@ -import os -import ioh -import numpy -import numpy as np -import array -import random -import pandas as pd -from irace import irace -import math -import matplotlib.pyplot as plt -import socket -import pickle - -sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -# 设置接收数据的超时时间为 5 秒 -sock.settimeout(600) - # 连接到服务器 -server_address = ('192.168.1.109', 30000) -sock.connect(server_address) - -const_problem_id = 1 -const_problem_dim = 1 # for matlab dim 1,2,3 for train,4 for test [100 225 400 625] -dim_to_normal = [100, 225, 400, 625] -const_FE = 50000 - -random.seed(0) - -parameters_table = ''' -T "" r (0.01, 0.05) -''' - -default_values = ''' -T -0.03 -''' - -# These are dummy "instances", we are tuning only on a single function. -instances = np.arange(100) - -# See https://mlopez-ibanez.github.io/irace/reference/defaultScenario.html -scenario = dict( - instances = instances, - maxExperiments = 200, - debugLevel = 3, - digits = 5, - parallel=1, # It can run in parallel ! - logFile = "") - - -def socket_sa(T): - try: - message = f"{T},{const_problem_id},{const_problem_dim}" - # 发送指令给 MATLAB 服务器 - sock.sendall(message.encode()) - - # 等待并接收响应 - data = sock.recv(1024) - print('Received:', data.decode()) - - except socket.timeout: - print('Socket timed out while waiting for response') - return float(data.decode()) - -def sa_pbo(x0, length, problem_id): - #print("test") - #print(int(problem_id)) - # In order to instantiate a problem instance, we can do the following: - problem = ioh.get_problem( - int(problem_id), - instance=1, - dimension=int(length), - problem_class=ioh.ProblemClass.PBO - ) - - problem.enforce_bounds(how=ioh.ConstraintEnforcement.SOFT, weight=1.0, exponent=1.0) - - # We can access the contraint information of the problem - population = np.array(x0).astype(int) - #print(population) - # Evaluation happens like a 'normal' objective function would - res = problem(population) - neg_res = [-x for x in res] - return neg_res - - -def sa(problem_id,dim,problem_fe,T): - problem_fe = 50000 - prob_N = 50 - Tf = 0.01 - Gmax = problem_fe/prob_N - - cur_problem_fe = 0 - # calculate iters - alpha = (Tf/T)**(1/Gmax) - now_x = [] - for i in range(prob_N): - x = np.random.randint(0,2,dim) - now_x.append(x) - best = 0 - current_fe = 0 - G = 0 - record = [] # record each iter best - record_new = [] # record each iter best - # annealing - while T > Tf and cur_problem_fe < problem_fe: - # iteration - f_now = sa_pbo(now_x, dim, problem_id) - record.append(min(f_now)) - new_x = get_new_x(now_x) - f_new = sa_pbo(new_x, dim, problem_id) - record_new.append(min(f_new)) - accept = Metrospolis(T,f_now, f_new) - - for i in range(len(accept)): - if random.random() < accept[i]: - now_x[i]=new_x[i] - if min(f_new) 0: - # Some configurations produced a warning, but the values are within the limits. That seems a bug in scipy. TODO: Report the bug to scipy. - print(f'{experiment["configuration"]}') - pass - #res = sa(const_problem_id,const_problem_dim,const_FE,**experiment['configuration']) - res = socket_sa(**experiment['configuration']) - return dict(cost=res) - - - -def run_irace(): - tuner = irace(scenario, parameters_table, target_runner) - tuner.set_initial_from_str(default_values) - best_confs = tuner.run() - total_res = [] - print(f'best_cofs:{best_confs}') - - for epoch in range(30): - res = socket_sa(best_confs['T'][0]) - #res = sa(const_problem_id,const_problem_dim,const_FE,best_confs['T'][0]) - total_res.append(res) - return total_res - -#df = pd.read_csv('/home/booze/code/ALDes/sa_results.csv') -df = pd.DataFrame(columns=['Problem', 'dim', 'Mean', 'Variance']) -df.to_csv('matlab/result/sa_irace/instance_4/result.csv', index=False) -for _dim in [4]: - for _problem_id in range(1,24): - const_problem_id = _problem_id - const_problem_dim = _dim - res = run_irace() - dump_file = f'matlab/result/sa_irace/instance_4/f{_problem_id}.pkl' - with open(dump_file, 'wb') as f: - # 使用pickle.dump()将字典对象序列化并保存到文件中 - pickle.dump(res, f) - means = np.mean(res) - variances = np.var(res) - df = df._append({ - 'Problem': _problem_id, - 'dim': dim_to_normal[_dim-1], - 'Mean': means, - 'Variance': variances - }, ignore_index=True) - df.to_csv('matlab/result/sa_irace/instance_4/result.csv', index=False) - - diff --git a/matlab/irace_tabu.py b/matlab/irace_tabu.py deleted file mode 100644 index 3fef8ad..0000000 --- a/matlab/irace_tabu.py +++ /dev/null @@ -1,188 +0,0 @@ -import os -import ioh -import numpy as np -import array - -import pandas as pd -from irace import irace -import pickle - -const_problem_id = 1 -const_problem_dim = 100 -const_FE = 50000 -def write_excel(res,shell): - res = res.reshape(1,-1) - # 将 NumPy 数组转换为 pandas 数据框架 - df = pd.DataFrame(res) - - # 打开现有的 Excel 文件 - excel_file = 'D:/01Code/transformer-rl-3/mean_var_data.xlsx' - existing_data = pd.read_excel(excel_file) - - # 将新数据追加到现有数据后面 - with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a') as writer: - df.to_excel(writer, sheet_name=shell, index=False,header=False) - -def tabu_pbo(x0, length, problem_id): - #print("test") - #print(int(problem_id)) - # In order to instantiate a problem instance, we can do the following: - problem = ioh.get_problem( - int(problem_id), - instance=1, - dimension=int(length), - problem_class=ioh.ProblemClass.PBO - ) - - problem.enforce_bounds(how=ioh.ConstraintEnforcement.SOFT, weight=1.0, exponent=1.0) - - # We can access the contraint information of the problem - population = np.array(x0).astype(int) - #print(population) - # Evaluation happens like a 'normal' objective function would - res = problem(population) - return res - -def tabu_search(problem_id,dim,problem_fe,tabu_list_length,tabu_list_cycle): - tabu_list_length = int(tabu_list_length) - tabu_list_cycle = int(tabu_list_cycle) - best = np.random.randint(0,2,dim) - best_fit = tabu_pbo(best, dim, problem_id) - cur_problem_fe = 0 - tabu_list = [0] * dim - tabu_list = np.array(tabu_list) - while(cur_problem_fe<=problem_fe): - neighbors = build_neighbors(best,tabu_list) - fitness = tabu_pbo(neighbors, dim, problem_id) - if max(fitness) > best_fit: - best_fit = max(fitness) - best = neighbors[fitness.index(best_fit)] - - for i in range(len(tabu_list)): - if tabu_list[i]>0: - tabu_list[i] -= 1 - #计算禁忌的个数 - count_nonzero = np.count_nonzero(tabu_list) - if count_nonzero==tabu_list_length:#禁忌表已满,减去最早加入的那个 - non_zero_elements = tabu_list[tabu_list!=0] - min_non_zero_value = np.min(non_zero_elements) - # 找到不为零的最小值的索引 - min_non_zero_index = np.where(tabu_list == min_non_zero_value)[0][0] - # 将该元素置为零 - tabu_list[min_non_zero_index] = 0 - #加入最好邻域解对应的tabu - tabu_list[fitness.index(max(fitness))] = tabu_list_cycle - cur_problem_fe = cur_problem_fe + len(neighbors) - print('problem{1},dim {2},best fitness {0} '.format(best_fit,problem_id,dim)) - return best_fit - -def build_neighbors(X0,tabu_list): - neighbors = [] - for i in range(X0.shape[0]): - if tabu_list[i]==0: - X_temp = X0.copy() - X_temp[i] = int(not(X_temp[i])) - neighbors.append(X_temp) - return neighbors - -def run_tabu(): - res = np.zeros((30, 23)) - for j in range(30): - for i in range(1,24): - res[j,i-1] = tabu_search(i,625,50000,625,3) - - column_means = np.mean(res, axis=0) - - # 计算每行的方差 - column_variances = np.var(res, axis=0) - write_excel(column_means,'Tabu_mean') - write_excel(column_variances, 'Tabu_var') - print("tsa") - - -# This target_runner is over-complicated on purpose to show what is possible. -def target_runner(experiment, scenario): - if scenario['debugLevel'] > 0: - # Some configurations produced a warning, but the values are within the limits. That seems a bug in scipy. TODO: Report the bug to scipy. - print(f'{experiment["configuration"]}') - res = tabu_search(const_problem_id,const_problem_dim,const_FE,**experiment['configuration']) - - return dict(cost=-res) - - -parameters_table = ''' -tabu_list_length "" i (1, 625) -tabu_list_cycle "" i (1, 100) -''' - -default_values = ''' -tabu_list_length tabu_list_cycle -10 3 -''' - -# These are dummy "instances", we are tuning only on a single function. -instances = np.arange(100) - -# See https://mlopez-ibanez.github.io/irace/reference/defaultScenario.html -scenario = dict( - instances = instances, - maxExperiments = 100, - debugLevel = 3, - digits = 5, - parallel=10, # It can run in parallel ! - logFile = "") - -def run_irace(): - tuner = irace(scenario, parameters_table, target_runner) - tuner.set_initial_from_str(default_values) - best_confs = tuner.run() - - total_res = [] - # Pandas DataFrame - print(best_confs) - #for i in range(len(best_confs)): - #only use the first - #print(f'tabu_list_length:{best_confs['tabu_list_length'][0]}, tabu_list_cycle:{best_confs['tabu_list_cycle'][0]}') - for epoch in range(30): - res = tabu_search(const_problem_id,const_problem_dim,const_FE,best_confs['tabu_list_length'][0],best_confs['tabu_list_cycle'][0]) - total_res.append(res) - return total_res - - -def write_excel(res,shell,path): - # 将 NumPy 数组转换为 pandas 数据框架 - df = pd.DataFrame(res) - - # 打开现有的 Excel 文件 - existing_data = pd.read_excel(path) - - # 将新数据追加到现有数据后面 - with pd.ExcelWriter(path, engine='openpyxl', mode='a') as writer: - df.to_excel(writer, sheet_name=shell, index=False,header=False) - -df = pd.DataFrame(columns=['Problem', 'dim', 'Mean', 'Variance']) -df.to_csv('../matlab/result/tabu_irace/instance_4/result.csv', index=False) -#df = pd.read_csv('/home/booze/code/ALDes/tabu_result.csv') -for _dim in [625]: - for _problem_id in range(1,24): - const_problem_dim = _dim - const_problem_id = _problem_id - print(f'current problem dim,id: {const_problem_dim} , {const_problem_id}') - res = run_irace() - - dump_file = f'../matlab/result/tabu_irace/instance_4/f{_problem_id}.pkl' - with open(dump_file, 'wb') as f: - # 使用pickle.dump()将字典对象序列化并保存到文件中 - pickle.dump(res, f) - - means = np.mean(res) - variances = np.var(res) - - df = df._append({ - 'Problem': _problem_id, - 'dim': _dim, - 'Mean': means, - 'Variance': variances - }, ignore_index=True) - - df.to_csv('../matlab/result/tabu_irace/instance_4/result.csv', index=False) \ No newline at end of file diff --git a/matlab/python_matlab.py b/matlab/python_matlab.py deleted file mode 100644 index 8fc10b9..0000000 --- a/matlab/python_matlab.py +++ /dev/null @@ -1,14 +0,0 @@ -import matlab.engine -import matlab -import os - -eng = matlab.engine.start_matlab() -# 此地址为test.m文件存放的地址 -work_path = os.getcwd() + "\\matlab" -eng.cd(work_path) - -a = matlab.double([0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5]) - -#c = eng.get_per(a) -result = eng.sa_for_python() -print(result) \ No newline at end of file diff --git a/matlab/sa_socket.m b/matlab/sa_socket.m deleted file mode 100644 index a913e35..0000000 --- a/matlab/sa_socket.m +++ /dev/null @@ -1,60 +0,0 @@ -try - % 创建一个 TCP/IP 服务器对象,监听所有 IP 地址上的端口 30000 - t = tcpip('0.0.0.0', 30000, 'NetworkRole', 'server'); - t.Timeout = 10; % 设置超时时间为 10 秒 - - % 打开 TCP/IP 连接,等待客户端连接 - fopen(t); - disp('MATLAB server is waiting for connection...'); - - % 无限循环以处理客户端请求 - while true - % 检查是否有可用数据 - if t.BytesAvailable > 0 - % 从连接中读取所有可用数据 - data = fread(t, t.BytesAvailable); - - % 将读取的数据转换为字符串 - command = char(data'); - % 解析接收到的整数 - numbers = str2double(strsplit(command, ',')); - T = numbers(1); - problem_id = numbers(2); - problem_dim = numbers(3); - % 打印接收到的命令(仅用于调试) - disp(['Received command: ', command]); - - % 如果接收到 'exit' 命令,则退出循环 - if strcmp(command, 'exit') - break; - else - % 计算命令结果(注意:此处使用 eval 是不安全的,仅用于示例) - %result = eval(command); - AutoOpt('Mode','solve','Problem','pbo','InstanceSolve',[problem_dim],'AlgName',"Discrete Simulated Annealing",'inital_t',T,'ProbN',50,'ProbFE',50000,'AlgRuns',1,'problem_id',problem_id); - load(strcat("Discrete Simulated Annealing",int2str(problem_id))); - res =[]; - [x, y] = size(bestSolutions); - for ii =1: y - res(ii)=cat(1,bestSolutions(1,ii).fit); - end - % 将结果转换为字符串并发送回客户端 - fwrite(t, num2str(median(res))); - disp(median(res)); - end - else - % 暂停片刻以避免忙等待 - pause(0.1); - end - end -catch ME - disp('An error occurred:'); - disp(ME.message); -end - -% 确保在任何情况下都能关闭连接并清理对象 -if exist('t', 'var') && isvalid(t) - fclose(t); - delete(t); - clear t; -end -disp('MATLAB server has stopped.'); diff --git a/matlab/test_function.m b/matlab/test_function.m deleted file mode 100644 index f3ae998..0000000 --- a/matlab/test_function.m +++ /dev/null @@ -1,14 +0,0 @@ - -addpath(genpath('Utilities')); -addpath(genpath('Problems')); -addpath(genpath('Main')); -addpath(genpath('Components')); - -% 没开一次matlab 只执行一次 -%pyversion('C:\Users\21902\.conda\envs\trrl\python.exe') - -%py.IOH_Test.cosntrains() -%res = py.IOH_Test.test() -seq =[ 0, 31, 24, 7, 23, 31, 24, 9, 23, 31, 24, 6, 23, 31, 24, 8, 29, 14, 29]; -problem_id = 8; -performance = get_perf(seq,problem_id,[4],1) \ No newline at end of file diff --git a/matlab_setting.py b/matlab_setting.py deleted file mode 100644 index 29cf870..0000000 --- a/matlab_setting.py +++ /dev/null @@ -1,113 +0,0 @@ -import warnings - -problem_type = 'discrete' # continuous/discrete - - -def is_ls_para(opera_index, para_index, para_num=1): - # para_num ,first para or second para - if opera_index == 6 or opera_index == 7 or opera_index == 8: # ls:0-0.3 paraSpace:0-1 - return ~(para_index > 30) - - if opera_index == 13 or opera_index == 17: # 13: ls:0-0.15 paraSpace:0-0.5 #17: ls:0-0.9 paraSpace:0-0.3 - return ~(para_index > 30) - - if opera_index == 16: # ls:0-0.09;28-40 paraSpace:0-0.3;20-40 - if para_num == 1: - return ~(para_index > 30) - elif para_num == 2: - return (para_index > 30) - - if opera_index == 17: # ls:0-0.9 paraSpace:0-0.3 - return ~(para_index > 30) - - -def dis_is_ls_opera(opera_index, para_index, para_num=1): - if opera_index == 4 or opera_index == 5 or opera_index == 10: - return False - elif opera_index == 8: - return True - else: - return ~(para_index > 20) - - -operator_para = { - "choose_traverse": 0, # 0 - "choose_tournament": 0, # 1 - "choose_roulette_wheel": 0, # 2 - "choose_nich": 0, # 3 - - 'cross_point_one': 0, # 4 - 'cross_point_two': 0, # 5 - 'cross_point_n': 1, # 6 - 'cross_point_uniform': 1, # 7 - 'search_reset_one': 0, # 8 - 'search_reset_n': 1, # 9 - 'search_reset_rand': 1, # 10 - 'reinit_discrete': 0, # 11 - - 'update_greedy': 0, # 12 - 'update_round_robin': 0, # 13 - 'update_pairwise': 0, # 14 - 'update_always': 0, # 15 - 'update_simulated_annealing': 1, # 16 - - "begin": 0, # 17 - "end": 0, # 18 - "0.1": 0, # 19 - "0.2": 0, # 20 - "0.3": 0, # 21 - "0.4": 0, # 22 - "0.5": 0, # 23 - "0.6": 0, # 24 - "0.7": 0, # 25 - "0.8": 0, # 26 - "0.9": 0, # 27 - "1.0": 0, # 28 - - "forward": 0, # 29, count condition as 1 execution time - "iterate": 1, # 30, with 5 candidate count conditions - "fork": 1, # 31, count condition as 1 execution time -} # 32 in total - -voc_size = operator_para.__len__() -voc_list = list(operator_para.keys()) -need_para_list = list(operator_para.values()) -choose_begin = 0 -choose_num = 4 -choose_end = 4 -update_begin = 12 -update_num = 5 -update_end = 16 -para_begin = 19 -para_num = 10 -para_end = 28 -search_begin = 4 -search_num = 8 -search_end = 11 -cross_begin = 4 -cross_num = 4 -cross_end = 7 -mu_begin = 8 -mu_num = 3 -mu_end = 10 -operators_begin = 0 -operators_num = 17 -operators_end = 16 -ptrs_begin = 29 -ptrs_num = 3 -ptrs_end = 31 -begin_index = 17 -end_index = 18 -total_index = 32 - -forward_index = 29 -iterate_index = 30 -fork_index = 31 - -# para decide opera is LS or GS -LS_range = 0.3 -# operators only can be Global Search ,python index,from 0 begin -only_gs_opera_index = [4, 5, 11] -gs_or_ls_opera_index = [6, 7, 9, 10] -max_operators = 6 -gs_para_begin = 22 \ No newline at end of file diff --git a/models/__pycache__/__init__.cpython-38.pyc b/models/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 605866d..0000000 Binary files a/models/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/models/blocks/__pycache__/__init__.cpython-38.pyc b/models/blocks/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index c5bc27f..0000000 Binary files a/models/blocks/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/models/blocks/__pycache__/decoder_layer.cpython-38.pyc b/models/blocks/__pycache__/decoder_layer.cpython-38.pyc deleted file mode 100644 index 1ff4bc9..0000000 Binary files a/models/blocks/__pycache__/decoder_layer.cpython-38.pyc and /dev/null differ diff --git a/models/blocks/__pycache__/encoder_layer.cpython-38.pyc b/models/blocks/__pycache__/encoder_layer.cpython-38.pyc deleted file mode 100644 index 102cc73..0000000 Binary files a/models/blocks/__pycache__/encoder_layer.cpython-38.pyc and /dev/null differ diff --git a/models/blocks/decoder_layer.py b/models/blocks/decoder_layer.py index dbc6d5b..1515495 100644 --- a/models/blocks/decoder_layer.py +++ b/models/blocks/decoder_layer.py @@ -1,4 +1,3 @@ -import torch from torch import nn from models.layers.layer_norm import LayerNorm @@ -6,9 +5,7 @@ from models.layers.position_wise_feed_forward import PositionwiseFeedForward - class DecoderLayer(nn.Module): - def __init__(self, d_model, ffn_hidden, n_head, drop_prob): super(DecoderLayer, self).__init__() self.self_attention = MultiHeadAttention(d_model=d_model, n_head=n_head) @@ -19,7 +16,9 @@ def __init__(self, d_model, ffn_hidden, n_head, drop_prob): self.norm2 = LayerNorm(d_model=d_model) self.dropout2 = nn.Dropout(p=drop_prob) - self.ffn = PositionwiseFeedForward(d_model=d_model, hidden=ffn_hidden, drop_prob=drop_prob) + self.ffn = PositionwiseFeedForward( + d_model=d_model, hidden=ffn_hidden, drop_prob=drop_prob + ) self.norm3 = LayerNorm(d_model=d_model) self.dropout3 = nn.Dropout(p=drop_prob) @@ -31,13 +30,13 @@ def forward(self, dec, trg_mask): x = self.self_attention(q=dec, k=dec, v=dec, mask=trg_mask) # 2. add and norm - #x = self.dropout1(x) + # x = self.dropout1(x) x = self.norm1(x + _x) # 5. positionwise feed forward network _x = x x = self.ffn(x) - + # 6. add and norm x = self.norm3(x + _x) diff --git a/models/blocks/encoder_layer.py b/models/blocks/encoder_layer.py deleted file mode 100644 index 716ad5e..0000000 --- a/models/blocks/encoder_layer.py +++ /dev/null @@ -1,39 +0,0 @@ -import torch -from torch import nn - -from models.layers.layer_norm import LayerNorm -from models.layers.multi_head_attention import MultiHeadAttention -from models.layers.position_wise_feed_forward import PositionwiseFeedForward - - -class EncoderLayer(nn.Module): - - def __init__(self, d_model, ffn_hidden, n_head, drop_prob): - super(EncoderLayer, self).__init__() - self.attention = MultiHeadAttention(d_model=d_model, n_head=n_head) - self.norm1 = LayerNorm(d_model=d_model) - self.dropout1 = nn.Dropout(p=drop_prob) - - self.ffn = PositionwiseFeedForward(d_model=d_model, hidden=ffn_hidden, drop_prob=drop_prob) - self.norm2 = LayerNorm(d_model=d_model) - #self.dropout2 = nn.Dropout(p=drop_prob) - - def forward(self, x, src_mask): - # 1. compute self attention - _x = x - x = self.attention(q=x, k=x, v=x, mask=src_mask) - - # 2. add and norm - #x = self.dropout1(x) - x = self.norm1(x + _x) - - # 3. positionwise feed forward network - _x = x - x = self.ffn(x) - - # 4. add and norm - #x = self.dropout2(x) - x = self.norm2(x + _x) - - return x - diff --git a/models/embedding/__init__.py b/models/embedding/__init__.py index d5b062b..89f1cc0 100644 --- a/models/embedding/__init__.py +++ b/models/embedding/__init__.py @@ -2,4 +2,4 @@ @author : Hyunwoong @when : 2019-10-22 @homepage : https://github.com/gusdnd852 -""" \ No newline at end of file +""" diff --git a/models/embedding/__pycache__/__init__.cpython-38.pyc b/models/embedding/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 4b4fc38..0000000 Binary files a/models/embedding/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/models/embedding/__pycache__/positional_encoding.cpython-38.pyc b/models/embedding/__pycache__/positional_encoding.cpython-38.pyc deleted file mode 100644 index 2f94a3c..0000000 Binary files a/models/embedding/__pycache__/positional_encoding.cpython-38.pyc and /dev/null differ diff --git a/models/embedding/__pycache__/token_embeddings.cpython-38.pyc b/models/embedding/__pycache__/token_embeddings.cpython-38.pyc deleted file mode 100644 index cf08364..0000000 Binary files a/models/embedding/__pycache__/token_embeddings.cpython-38.pyc and /dev/null differ diff --git a/models/embedding/__pycache__/transformer_embedding.cpython-38.pyc b/models/embedding/__pycache__/transformer_embedding.cpython-38.pyc deleted file mode 100644 index 0d08c0a..0000000 Binary files a/models/embedding/__pycache__/transformer_embedding.cpython-38.pyc and /dev/null differ diff --git a/models/embedding/positional_encoding.py b/models/embedding/positional_encoding.py index 2b64ea4..9006c3e 100644 --- a/models/embedding/positional_encoding.py +++ b/models/embedding/positional_encoding.py @@ -18,8 +18,7 @@ def __init__(self, d_model, max_len, device): super(PositionalEncoding, self).__init__() # same size with input matrix (for adding with input matrix) - self.encoding = torch.zeros(max_len, d_model, device=device) - self.encoding.requires_grad = False # we don't need to compute gradient + encoding = torch.zeros(max_len, d_model, device=device) pos = torch.arange(0, max_len, device=device) pos = pos.float().unsqueeze(dim=1) @@ -29,8 +28,9 @@ def __init__(self, d_model, max_len, device): # 'i' means index of d_model (e.g. embedding size = 50, 'i' = [0,50]) # "step=2" means 'i' multiplied with two (same with 2 * i) - self.encoding[:, 0::2] = torch.sin(pos / (10000 ** (_2i / d_model))) - self.encoding[:, 1::2] = torch.cos(pos / (10000 ** (_2i / d_model))) + encoding[:, 0::2] = torch.sin(pos / (10000 ** (_2i / d_model))) + encoding[:, 1::2] = torch.cos(pos / (10000 ** (_2i / d_model))) + self.register_buffer("encoding", encoding, persistent=False) # compute positional encoding to consider positional information of words def forward(self, x): diff --git a/models/embedding/token_embeddings.py b/models/embedding/token_embeddings.py index 62f3285..40a5ff3 100644 --- a/models/embedding/token_embeddings.py +++ b/models/embedding/token_embeddings.py @@ -3,6 +3,7 @@ @when : 2019-10-24 @homepage : https://github.com/gusdnd852 """ + from torch import nn @@ -19,4 +20,6 @@ class for token embedding that included positional information :param vocab_size: size of vocabulary :param d_model: dimensions of model """ - super(TokenEmbedding, self).__init__(vocab_size, d_model, padding_idx=1) + # ALDes has no padding token. Index 1 is choose_tournament and must + # receive gradients like every other vocabulary entry. + super(TokenEmbedding, self).__init__(vocab_size, d_model) diff --git a/models/embedding/transformer_embedding.py b/models/embedding/transformer_embedding.py index 8efc847..4b9e1e8 100644 --- a/models/embedding/transformer_embedding.py +++ b/models/embedding/transformer_embedding.py @@ -26,4 +26,4 @@ def forward(self, x): tok_emb = self.tok_emb(x) pos_emb = self.pos_emb(x) - return tok_emb + pos_emb + return self.drop_out(tok_emb + pos_emb) diff --git a/models/layers/__pycache__/__init__.cpython-38.pyc b/models/layers/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index d68c8a1..0000000 Binary files a/models/layers/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/models/layers/__pycache__/layer_norm.cpython-38.pyc b/models/layers/__pycache__/layer_norm.cpython-38.pyc deleted file mode 100644 index 8311673..0000000 Binary files a/models/layers/__pycache__/layer_norm.cpython-38.pyc and /dev/null differ diff --git a/models/layers/__pycache__/multi_head_attention.cpython-38.pyc b/models/layers/__pycache__/multi_head_attention.cpython-38.pyc deleted file mode 100644 index 2247e4d..0000000 Binary files a/models/layers/__pycache__/multi_head_attention.cpython-38.pyc and /dev/null differ diff --git a/models/layers/__pycache__/position_wise_feed_forward.cpython-38.pyc b/models/layers/__pycache__/position_wise_feed_forward.cpython-38.pyc deleted file mode 100644 index 7b83f65..0000000 Binary files a/models/layers/__pycache__/position_wise_feed_forward.cpython-38.pyc and /dev/null differ diff --git a/models/layers/__pycache__/scale_dot_product_attention.cpython-38.pyc b/models/layers/__pycache__/scale_dot_product_attention.cpython-38.pyc deleted file mode 100644 index 89923f8..0000000 Binary files a/models/layers/__pycache__/scale_dot_product_attention.cpython-38.pyc and /dev/null differ diff --git a/models/layers/multi_head_attention.py b/models/layers/multi_head_attention.py index a53af8f..57d0eaa 100644 --- a/models/layers/multi_head_attention.py +++ b/models/layers/multi_head_attention.py @@ -4,7 +4,6 @@ class MultiHeadAttention(nn.Module): - def __init__(self, d_model, n_head): super(MultiHeadAttention, self).__init__() self.n_head = n_head diff --git a/models/layers/position_wise_feed_forward.py b/models/layers/position_wise_feed_forward.py index 139f009..c506916 100644 --- a/models/layers/position_wise_feed_forward.py +++ b/models/layers/position_wise_feed_forward.py @@ -2,7 +2,6 @@ class PositionwiseFeedForward(nn.Module): - def __init__(self, d_model, hidden, drop_prob=0.1): super(PositionwiseFeedForward, self).__init__() self.linear1 = nn.Linear(d_model, hidden) @@ -13,6 +12,6 @@ def __init__(self, d_model, hidden, drop_prob=0.1): def forward(self, x): x = self.linear1(x) x = self.relu(x) - #x = self.dropout(x) + # x = self.dropout(x) x = self.linear2(x) return x diff --git a/models/layers/scale_dot_product_attention.py b/models/layers/scale_dot_product_attention.py index c2065a7..827dbf1 100644 --- a/models/layers/scale_dot_product_attention.py +++ b/models/layers/scale_dot_product_attention.py @@ -3,46 +3,30 @@ @when : 2019-10-22 @homepage : https://github.com/gusdnd852 """ + import math from torch import nn class ScaleDotProductAttention(nn.Module): - """ - compute scale dot product attention - - Query : given sentence that we focused on (decoder) - Key : every sentence to check relationship with Qeury(encoder) - Value : every sentence same with Key (encoder) - """ + """Compute scaled dot-product attention.""" def __init__(self): super(ScaleDotProductAttention, self).__init__() self.softmax = nn.Softmax(dim=-1) - def forward(self, q, k, v, mask=None, e=1e-12): - # input is 4 dimension tensor - # [batch_size, head, length, d_tensor] - batch_size, head, length, d_tensor = k.size() - - # 1. dot product Query with Key^T to compute similarity - k_t = k.transpose(2, 3) # transpose - score = (q @ k_t) / math.sqrt(d_tensor) # scaled dot product + def forward(self, q, k, v, mask=None): + # Inputs have shape [batch, head, sequence length, head dimension]. + d_tensor = k.size(-1) - # bug here? our mask make rows all zero but after softmax get a average value + k_t = k.transpose(2, 3) + score = (q @ k_t) / math.sqrt(d_tensor) - # 2. apply masking (opt) if mask is not None: score = score.masked_fill(mask == 0, -10000) - # 3. pass them softmax to make [0, 1] range score = self.softmax(score) - - # softmax make 0-row get a average value,here make these 0-value-rows change to zero again, not sure if there right - - #score = score.masked_fill(mask == 0,0) - # 4. multiply with Value v = score @ v return v, score diff --git a/models/model/__pycache__/__init__.cpython-38.pyc b/models/model/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 5eb2534..0000000 Binary files a/models/model/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/models/model/__pycache__/decoder.cpython-38.pyc b/models/model/__pycache__/decoder.cpython-38.pyc deleted file mode 100644 index 05f0650..0000000 Binary files a/models/model/__pycache__/decoder.cpython-38.pyc and /dev/null differ diff --git a/models/model/__pycache__/encoder.cpython-38.pyc b/models/model/__pycache__/encoder.cpython-38.pyc deleted file mode 100644 index e0eba69..0000000 Binary files a/models/model/__pycache__/encoder.cpython-38.pyc and /dev/null differ diff --git a/models/model/__pycache__/transformer.cpython-38.pyc b/models/model/__pycache__/transformer.cpython-38.pyc deleted file mode 100644 index 261e7e6..0000000 Binary files a/models/model/__pycache__/transformer.cpython-38.pyc and /dev/null differ diff --git a/models/model/decoder.py b/models/model/decoder.py index a009f42..e1d091f 100644 --- a/models/model/decoder.py +++ b/models/model/decoder.py @@ -1,537 +1,134 @@ +"""Autoregressive decoder used by the standalone ALDes training script.""" + +from __future__ import annotations + +import math + import numpy as np import torch from torch import nn -import torch.nn.functional as F -from torch.distributions import Categorical + +from aldes_setting import end_index +from autooptlib.aldes.vocabulary import allowed_next_tokens from models.blocks.decoder_layer import DecoderLayer from models.embedding.transformer_embedding import TransformerEmbedding -from torch.distributions.normal import Normal -from numpy import* -from torch.nn import Parameter -from matlab_setting import * -use_Point = False - - -class GatingMechanism(torch.nn.Module): - def __init__(self, d_input, bg=0.1): - super(GatingMechanism, self).__init__() - self.Wr = torch.nn.Linear(d_input, d_input) - self.Ur = torch.nn.Linear(d_input, d_input) - self.Wz = torch.nn.Linear(d_input, d_input) - self.Uz = torch.nn.Linear(d_input, d_input) - self.Wg = torch.nn.Linear(d_input, d_input) - self.Ug = torch.nn.Linear(d_input, d_input) - self.bg = bg - self.sigmoid = torch.nn.Sigmoid() - self.tanh = torch.nn.Tanh() - def forward(self, x, y): - r = self.sigmoid(self.Wr(y) + self.Ur(x)) - z = self.sigmoid(self.Wz(y) + self.Uz(x) - self.bg) - h = self.tanh(self.Wg(y) + self.Ug(torch.mul(r, x))) - g = torch.mul(1 - z, x) + torch.mul(z, h) - return g class Decoder(nn.Module): - def __init__(self, dec_voc_size, max_len, d_model, ffn_hidden, n_head, n_layers, drop_prob, device): + def __init__( + self, + dec_voc_size, + max_len, + d_model, + ffn_hidden, + n_head, + n_layers, + drop_prob, + device, + condition_on_features=False, + ): super().__init__() - self.emb = TransformerEmbedding(d_model=d_model, - drop_prob=drop_prob, - max_len=max_len, - vocab_size=dec_voc_size, - device=device) - - self.layers = nn.ModuleList([DecoderLayer(d_model=d_model, - ffn_hidden=ffn_hidden, - n_head=n_head, - drop_prob=drop_prob) - for _ in range(n_layers)]) - + self.emb = TransformerEmbedding( + d_model=d_model, + drop_prob=drop_prob, + max_len=max_len, + vocab_size=dec_voc_size, + device=device, + ) + self.layers = nn.ModuleList( + [ + DecoderLayer( + d_model=d_model, + ffn_hidden=ffn_hidden, + n_head=n_head, + drop_prob=drop_prob, + ) + for _ in range(n_layers) + ] + ) self.linear = nn.Linear(d_model, dec_voc_size) - self.sigmoid = nn.Sigmoid() - self.softmax =nn.Softmax(dim=2) self.device = device + self.max_len = max_len + self.condition_on_features = condition_on_features + self.feature_projection = ( + nn.Linear(d_model, d_model) if condition_on_features else None + ) self.temp = 1.0 - self.input_linear = nn.Linear(d_model, d_model) - self.action_linear = nn.Conv1d(d_model, d_model, 1, 1) - self.V = Parameter(torch.FloatTensor(d_model), requires_grad=True) - self.tanh = nn.Tanh() - self.attn = nn.Linear(d_model, d_model) - - # Initialize vector V - nn.init.uniform(self.V, -1, 1) - - self.gate = GatingMechanism(d_model) - - def get_action(self, model_output, action = None): - - model_output = torch.squeeze(model_output) - sdv = model_output[1::2] - mean = model_output[0::2] - # here use exp make sure its positive - sdv = torch.exp(sdv) - - probs = Normal(mean, sdv) - if action is None: - action = probs.sample() - - return action, probs.log_prob(action), probs.entropy() - - def pointer(self, out, action_emb): - out = self.input_linear(out).expand(-1,action_emb.size(1),-1) - out = out.permute(0, 2, 1) - action_emb = action_emb.permute(0,2,1) - action_emb = self.action_linear(action_emb) - # (batch, 1, hidden_dim) - V = self.V.unsqueeze(0).expand(action_emb.size(0), -1).unsqueeze(1) - - # (batch, seq_len) - att = torch.bmm(V, self.tanh(out + action_emb)).squeeze(1) - return att - def forward(self, trg, enc_src, action_emb,trg_mask, src_mask,action = None,inference = False): - - action_p=[] - action_log_p=[] - operator_num = torch.zeros(trg.shape,dtype=torch.int64).to(self.device) - need_para_num = torch.zeros(trg.shape,dtype=torch.int64).to(self.device) - action_index = torch.zeros(trg.shape).to(self.device) # 'begin' - last_opera_index =torch.zeros(trg.shape,dtype=torch.int64).to(self.device) - last_normal_opera_index = torch.zeros(trg.shape,dtype=torch.int64).to(self.device) - have_gs = torch.zeros(trg.shape, dtype=torch.int64).to(self.device) - action_index[:,:]=begin_index - last_opera_index[:,:]=begin_index - finished = torch.zeros(trg.shape).to(self.device) - all_finished = torch.ones(trg.shape).to(self.device) + def forward( + self, + trg, + enc_src, + action_emb, + trg_mask, + src_mask, + action=None, + inference=False, + ): + del action_emb, trg_mask, src_mask + action_p = [] + action_log_p = [] ppo_index = 1 - #for i in range(0,16): - while(True): - #code here : drop finished row - #unfinished_index,last_opera_index,last_normal_opera_index, operator_num,need_para_num, unfinished_trg,unfinished_have_gs,unfinished_action_emb,unfinished_enc_src\ - # = self.choose_unfinished(finished,have_gs,last_opera_index,last_normal_opera_index,operator_num,need_para_num,trg,action_emb,enc_src) - - input = self.emb(trg) - - #input = torch.cat((unfinished_enc_src, trg_emb), dim=1) + while True: + if trg.shape[1] >= self.max_len: + raise RuntimeError("ALDes generation reached max_len before end.") + + decoder_input = self.emb(trg) + if self.condition_on_features: + if enc_src is None: + raise ValueError("Continual ALDes mode requires problem features.") + feature = enc_src + if feature.ndim == 3: + feature = feature.mean(dim=1) + if feature.ndim != 2 or feature.shape[-1] != decoder_input.shape[-1]: + raise ValueError( + "Problem features must have shape (batch, 32) or " + "(batch, samples, 32)." + ) + decoder_input = decoder_input + self.feature_projection( + feature + ).unsqueeze(1) for layer in self.layers: - input = layer(input,trg_mask = None) - - # pass to LM head - output = self.linear(input) - output = output[:,-1:,:] - #mask = self.get_mask_mat(unfinished_trg, action_index, last_opera_index,last_normal_opera_index, operator_num, need_para_num, unfinished_have_gs, finished).to(self.device) - mask = self.get_mask(trg) - mask = torch.unsqueeze(mask,1) - output = output.masked_fill(mask == 0, -math.inf) - # See https://discuss.pytorch.org/t/bad-behavior-of-multinomial-function/10232 - _log_p = torch.log_softmax(output / self.temp, dim=-1) - distribution = _log_p.exp() - if torch.isnan(distribution).any() or torch.isinf(distribution).any(): - print("nan or inf") + decoder_input = layer(decoder_input, trg_mask=None) + output = self.linear(decoder_input[:, -1:, :]) + mask = self.get_mask(trg).unsqueeze(1) + output = output.masked_fill(~mask, -math.inf) + log_probabilities = torch.log_softmax(output / self.temp, dim=-1) + probabilities = log_probabilities.exp() if action is None: - action_index = distribution.squeeze(1).multinomial(1) - if inference is True:action_index = torch.argmax(distribution.squeeze(1), dim=1).unsqueeze(1) - while not mask.squeeze(1).gather(1, action_index).data.all(): - print('Sampled bad values, resampling!') - action_index = output.multinomial(1).squeeze(1) - if inference is True: action_index = torch.argmax(distribution.squeeze(1), dim=1).unsqueeze(1) + if inference: + action_index = probabilities.argmax(dim=-1) + else: + action_index = probabilities.squeeze(1).multinomial(1) else: - # action should be full rows - unfinished_index = torch.where(finished == 0)[0] - temp_action = torch.index_select(action, 0, unfinished_index) - action_index = temp_action[:,ppo_index] # "begin" is first + if ppo_index >= action.shape[1]: + raise ValueError("Replay action ends before the end token.") + action_index = action[:, ppo_index].unsqueeze(1) ppo_index += 1 - action_index = action_index.unsqueeze(1) - - # Get log_p corresponding to selected actions - p = distribution[0, 0, action_index] - log_p = _log_p.gather(2, action_index.unsqueeze(-1)).squeeze(-1) + probability = probabilities.gather(2, action_index.unsqueeze(-1)).squeeze( + -1 + ) + log_probability = log_probabilities.gather( + 2, action_index.unsqueeze(-1) + ).squeeze(-1) trg = torch.cat([trg, action_index], dim=1) - action_p.append(p) - action_log_p.append(log_p) + action_p.append(probability) + action_log_p.append(log_probability) if torch.all(action_index == end_index): break - trg = self.check_pointer(trg) - return trg, torch.stack(action_p,1),torch.stack(action_log_p,1) - - # if pointer point more than the alg operator length, fix it - def check_pointer(self,cur_alg): - dim0, dim1 = cur_alg.shape - for i in range(dim0): - cur_opera_num = 0 - cur_operas = [] - for action in cur_alg[i]: - if operators_begin <= action <= operators_end: - cur_opera_num += 1 - cur_operas.append(action) + return trg, torch.stack(action_p, 1), torch.stack(action_log_p, 1) - positions = torch.nonzero(torch.eq(cur_alg[i], fork_index)) - for position in positions: - if cur_alg[i][position + 1] > para_begin + cur_opera_num - 1: - cur_alg[i][position + 1] = para_begin + cur_opera_num - 1 + @staticmethod + def check_pointer(cur_alg): + """Compatibility no-op; AutoOptLib safely interprets fork targets.""" return cur_alg def get_mask(self, cur_alg): - - dim0,dim1 = cur_alg.shape - # 0 means action is masked - mask = torch.zeros([dim0, voc_size], dtype=torch.double).to(self.device) - for i in range(dim0): - last_action = cur_alg[i][-1] - - # first action must be 'choose' - if last_action == begin_index: - mask[i][choose_begin:choose_end] = 1 - continue - - # last action is "end" - if last_action == end_index: - mask[i][end_index] = 1 - continue - - tmp = -1 - # last not para action is operator or ptr - last_opera_or_ptrs = True - last_opera = None - last_ptrs = None - while True: - if operators_begin <= cur_alg[i][tmp] <= operators_end and last_opera is None: - last_opera = cur_alg[i][tmp] - if ptrs_begin <= cur_alg[i][tmp] <= ptrs_end and last_ptrs is None: - last_ptrs = cur_alg[i][tmp] - if (last_ptrs is not None and last_opera is not None) or cur_alg[i][tmp] == begin_index: - break - tmp -= 1 - tmp = -1 - while True: - if operators_begin <= cur_alg[i][tmp] <= operators_end: - last_opera_or_ptrs = True - break - if ptrs_begin <= cur_alg[i][tmp] <= ptrs_end: - last_opera_or_ptrs = False - break - tmp -= 1 - - - # calculate total operators of cur alg - tmp = -1 - cur_opera_num = 0 - cur_operas = [] - for action in cur_alg[i]: - if operators_begin <= action <= operators_end: - cur_opera_num += 1 - cur_operas.append(action) - - operator_need_para = False - need_operator_or_end = False - # last action is operator - if operators_begin <= last_action <= operators_end: - if need_para_list[last_action] != 0: - mask[i][para_begin:para_end + 1] = 1 - operator_need_para = True - else: - # operator have no para, need pointer - if choose_begin <= last_action <= choose_end: - mask[i][forward_index] = 1 - mask[i][fork_index] = 1 - elif search_begin <= last_action <= search_end: - mask[i][ptrs_begin:ptrs_end + 1] = 1 - elif update_begin <= last_action <= update_end: - mask[i][forward_index] = 1 - #mask[i][iterate_index] = 1 - - # last action is para - elif para_begin <= last_action <= para_end: - para_enough = False - # para of operator - if last_opera_or_ptrs: - if para_begin <= cur_alg[i][-2] <= para_end: - para_enough = True - else: - if need_para_list[last_opera] == 1: - para_enough = True - if para_enough: - # opear,para,need ptr - if choose_begin <= last_opera <= choose_end: - mask[i][forward_index] = 1 - mask[i][fork_index] = 1 - elif search_begin <= last_opera <= search_end: - mask[i][ptrs_begin:ptrs_end + 1] = 1 - elif update_begin <= last_opera <= update_end: - mask[i][forward_index] = 1 - mask[i][iterate_index] = 1 - else: - mask[i][para_begin:para_end + 1] = 1 - operator_need_para = True - # para of ptrs - else: - # ptrs most have one para, next is operator/end - need_operator_or_end = True - - # last action is pointer - elif ptrs_begin <= last_action <= ptrs_end: - if last_action == forward_index: - # forward have no condition - need_operator_or_end = True - elif last_action == iterate_index: - # iterate only follow para in 1-5 - mask[i][para_begin:para_begin + 5] = 1 - elif last_action == fork_index: - mask[i][para_begin + cur_opera_num + 1 : para_begin + max_operators] = 1 - if para_begin + cur_opera_num + 1 >= max_operators : - mask[i][:] = 0 - mask[i][para_begin + max_operators - 1] = 1 - - if need_operator_or_end: - if cur_opera_num == 1: - mask[i][search_begin:search_end + 1] = 1 - # first search not be mu - mask[i][mu_begin:mu_end + 1] = 0 - elif 1 < cur_opera_num < max_operators - 2: - mask[i][search_begin:search_end + 1] = 1 - mask[i][update_begin:update_end + 1] = 1 - elif cur_opera_num >= max_operators - 2: - mask[i] = 0 - mask[i][update_begin:update_end + 1] = 1 - - if update_begin <= last_opera <= update_end: - mask[i][:] = 0 - mask[i][end_index] = 1 - - # if last operator is crossover,next must be mutation - if cross_begin <= last_opera <= cross_end: - mask[i][:] = 0 - mask[i][mu_begin:mu_end + 1] = 1 - # mask already selected operators - for select_opeartor in cur_operas: - mask[i][select_opeartor] = 0 - - # here need mask global para or operator - have_global_opera = False - for j in range(len(cur_alg[i])): - action = cur_alg[i][j] - if operators_begin <= action <= operators_end: - if action in only_gs_opera_index: - have_global_opera = True - # no para search only be local - elif need_para_list[action] >= 1: - # all search most have one para, para>0.3 is GS - if j != len(cur_alg[i]) -1 and cur_alg[i][j+1] >= gs_para_begin: - have_global_opera = True - if have_global_opera: - mask[i][only_gs_opera_index] = 0 - if operator_need_para: - mask[i][para_begin:gs_para_begin] = 0 - - if mask[i].sum() == 0: - print("all mask ! ERROR") - - return mask - - - - - - - - - - def get_mask_mat(self, trg, action_index,last_opera_index,last_normal_opera_index, operator_num, need_para_num,have_gs,finished): - - dim0,dim1 = trg.shape - - last_is_prts = (last_opera_index >= ptrs_begin) * (last_opera_index <= ptrs_begin + ptrs_num - 1) - last_normal_is_cross = (last_normal_opera_index<=cross_begin+cross_num-1) * (last_normal_opera_index>=cross_begin) - - # 0 is masked - mask = torch.ones([dim0,voc_size],dtype=torch.double).to(self.device) - - # mask parameter - mask[:,para_begin:para_begin+para_num] = torch.where(need_para_num!=0, mask[:,para_begin:para_begin+para_num],0.) - - # mask choose operator - choose_cond = (operator_num == 0) * (need_para_num == 0) - mask[:, choose_begin:choose_begin + choose_num] = torch.where(choose_cond, mask[:, choose_begin:choose_begin + choose_num], 0.) - # mask update operator - selet_cond = (operator_num == 1) * (need_para_num == 0) - mask[:, update_begin:update_begin+update_num] = torch.where(selet_cond, mask[:, update_begin:update_begin+update_num], 0.) - - # mask search operator - search_cond = (operator_num >= 2) * (need_para_num == 0) - mask[:, search_begin:search_begin + search_num] = torch.where(search_cond, mask[:, search_begin:search_begin + search_num], 0.) - # crossover must followed by mutation,if last operator is crossover, mask operators unless mutation - cross_cond = last_normal_is_cross* (need_para_num == 0) - # first mask all operator and unmask mutation - mask[:, search_begin:search_begin + search_num] = torch.where(cross_cond, 0. ,mask[:, search_begin:search_begin + search_num]) - mask[:, mu_begin:mu_begin+mu_num] = torch.where(cross_cond,1.,mask[:, mu_begin:mu_begin+mu_num]) - - #first search not be mutation - first_search = (operator_num == 2) - mask[:, mu_begin:mu_begin + mu_num] = torch.where(first_search, 0., mask[:, mu_begin:mu_begin + mu_num]) - - # mask seleted operator, not contain ptrs - for i in range(dim0): - for j in range(dim1): - opera = trg[i][j].item() - if opera<=operators_num: mask[i,opera] = 0. - - # alg have search, choose, update, can end, add "End" - mask[:,end_index]=0 - temp = torch.ones([dim0,total_index],dtype=torch.double).to(self.device) - can_end = (operator_num >=4) * (need_para_num ==0) * (~last_normal_is_cross) *(last_is_prts) - mask[:,end_index:end_index+1] = torch.where(can_end ,temp[:,end_index:end_index+1],mask[:,end_index:end_index+1]) - - # last operator cant be cross - last_opera = (operator_num >=8)*(need_para_num == 0) - mask[:, cross_begin:cross_begin +cross_num] = torch.where(last_opera,0.,mask[:, cross_begin:cross_begin +cross_num]) - - # force select ptrs after search opera and para - need_ptrs = (need_para_num == 0) * (last_opera_index >= search_begin) * (last_opera_index <= search_begin + search_num - 1) - need_ptr_mask = torch.zeros([dim0,total_index],dtype=torch.double).to(self.device) - need_ptr_mask[:, ptrs_begin : ptrs_begin + ptrs_num] = 1 - mask[:,:] = torch.where(need_ptrs,need_ptr_mask,mask) - - # last operator is ptr, next should not still ptr - mask[:, ptrs_begin:ptrs_begin + ptrs_num] = torch.where(last_is_prts, 0., - mask[:, ptrs_begin:ptrs_begin + ptrs_num]) - # if need parameter or cant be a full alg(choose,update,search), mask ptr - need_para = (need_para_num != 0) | (operator_num<3) - mask[:, ptrs_begin:ptrs_begin + ptrs_num] = torch.where(need_para, 0., - mask[:, ptrs_begin:ptrs_begin + ptrs_num]) - # force choose end - # make sure last operator is ptrs,and last normal operator is not crossover, then can choose 'end' - need_end = (operator_num >=8) * (need_para_num == 0) * last_is_prts * (~last_normal_is_cross) - need_end_mask = torch.zeros([dim0,total_index],dtype=torch.double).to(self.device) - need_end_mask[:,end_index] = 1 - mask[:,:] = torch.where(need_end,need_end_mask,mask) - - # mask pso - if discrete ==False: - mask[:,5] = 0. - - # mask global search operator - need_mask_opera = (have_gs == 1)*(need_para_num == 0) - mask[:,only_gs_opera_index] = torch.where(need_mask_opera,0.,mask[:,only_gs_opera_index]) - # mask global search parameter - need_mask_para = (have_gs == 1)*(need_para_num != 0) - dim0,dim1 = need_mask_para.shape - for i in range(dim0): - if ~need_mask_para[i,0]: continue - if discrete==False: - if last_opera_index[i] == 6 or last_opera_index[i] == 7 or last_opera_index[i] == 8: - mask[i,31:] = 0 - elif last_opera_index[i] == 13 or last_opera_index[i] == 17: - mask[i, 31:] = 0 - elif last_opera_index[i] == 16: - if need_para_num[i,0] == 2: - mask[i, 31:] = 0 - elif need_para_num[i,0] == 1: - mask[i, 28:31] = 0 - else: - if last_opera_index[i] == 6 or last_opera_index[i] == 7 or last_opera_index[i] == 9: - mask[i, 21:27] = 0 - - if ~torch.sum(mask, dim=1).all(): - print("have all zeros row!") - return mask - - def judge_GS(self, have_gs, need_para_num, last_opera_index, trg): - # judge alg have Global Search or not - need_judge = (have_gs == 0) * (need_para_num == 0) * (last_opera_index >= search_begin) * ( - last_opera_index <= search_begin + search_num - 1) - dim0,dim1 = need_judge.shape - for i in range(dim0): - if ~need_judge[i,0]:continue - last_opera_index_i = last_opera_index[i, 0] - if only_gs_opera_index.__contains__(last_opera_index_i): - have_gs[i, 0] = 1 - else: - para_num = operator_para[voc_list[last_opera_index_i]] - - if discrete==False: - if para_num == 1: - para_index = trg[i, -1: ] - have_gs[i, 0] = ~is_ls_para(last_opera_index_i,para_index) + 0 - elif para_num == 2: - para_index_1 = trg[i, -2:-1] - para_index_2 = trg[i, -1:] - one = ~is_ls_para(last_opera_index_i, para_index_1) + 0 - two = ~is_ls_para(last_opera_index_i, para_index_2,2) + 0 - have_gs[i, 0] = one|two + 0 - else: - if para_num == 1: - para_index = trg[i, -1: ] - have_gs[i, 0] = ~dis_is_ls_opera(last_opera_index_i,para_index) + 0 - - return have_gs - - def choose_unfinished(self,finished,have_gs,last_opera_index,last_normal_opera_index,operator_num,need_para_num,trg,action_emb,enc_src): - unfinished_index = torch.where(finished == 0)[0] - last_opera_index = torch.index_select(last_opera_index, 0, unfinished_index) - last_normal_opera_index = torch.index_select(last_normal_opera_index, 0, unfinished_index) - operator_num = torch.index_select(operator_num, 0, unfinished_index) - need_para_num = torch.index_select(need_para_num, 0, unfinished_index) - unfinished_trg = torch.index_select(trg, 0, unfinished_index) - unfinished_have_gs = torch.index_select(have_gs, 0, unfinished_index) - unfinished_action_emb = torch.index_select(action_emb, 0, unfinished_index) - unfinished_enc_src = torch.index_select(enc_src, 0, unfinished_index) - return unfinished_index,last_opera_index,last_normal_opera_index,operator_num,need_para_num,unfinished_trg,unfinished_have_gs,unfinished_action_emb,unfinished_enc_src - - def update_cur_alg_info(self,finished,unfinished_index,last_opera_index,last_normal_opera_index,operator_num,need_para_num,p,log_p,action_index,action_p,action_log_p,trg): - # update info of cur alg - is_opera = ((action_index >= operators_begin) * (action_index <= operators_begin + operators_num - 1)) | ((action_index >= ptrs_begin) * (action_index <= ptrs_begin + ptrs_num - 1)) - last_opera_index = torch.tensor(where(is_opera.cpu(), action_index.cpu(), last_opera_index.cpu())).to( - self.device) - # operator without ptrs - is_normal_opera = ((action_index >= operators_begin) * (action_index <= operators_begin + operators_num - 1)) - last_normal_opera_index = torch.tensor(where(is_normal_opera.cpu(), action_index.cpu(), last_normal_opera_index.cpu())).to( - self.device) - operator_num = torch.tensor(where(is_opera.cpu(), operator_num.cpu() + 1, operator_num.cpu())).to(self.device) - dim0, dim1 = is_opera.shape - for i in range(dim0): - if is_opera[i, 0]: - need_para_num[i, 0] = operator_para[voc_list[action_index[i, 0]]] - - is_para = (action_index >= para_begin) * (action_index <= para_begin + para_num - 1) - need_para_num = torch.tensor(where(is_para.cpu(), need_para_num.cpu() - 1, need_para_num.cpu())).to( - self.device) - - - # cat finished and unfinished rows to keep matrix - cat_last_opera_index = torch.zeros(finished.shape, dtype=torch.int64).to(self.device) - cat_last_opera_index.scatter_(0, torch.unsqueeze(unfinished_index, 1), last_opera_index) - cat_last_normal_opera_index = torch.zeros(finished.shape, dtype=torch.int64).to(self.device) - cat_last_normal_opera_index.scatter_(0, torch.unsqueeze(unfinished_index, 1), last_normal_opera_index) - cat_operator_num = torch.zeros(finished.shape, dtype=torch.int64).to(self.device) - cat_operator_num.scatter_(0, torch.unsqueeze(unfinished_index, 1), operator_num) - cat_need_para_num = torch.zeros(finished.shape, dtype=torch.int64).to(self.device) - cat_need_para_num.scatter_(0, torch.unsqueeze(unfinished_index, 1), need_para_num) - last_opera_index = cat_last_opera_index - last_normal_opera_index = cat_last_normal_opera_index - operator_num = cat_operator_num - need_para_num = cat_need_para_num - - # cat finished and unfinished rows to keep matrix - cat_p = torch.ones(finished.shape).to(self.device) - cat_p.scatter_(0, torch.unsqueeze(unfinished_index, 1), p) - cat_log_p = torch.zeros(finished.shape).to(self.device) - cat_log_p.scatter_(0, torch.unsqueeze(unfinished_index, 1), log_p) - cat_action_index = torch.zeros(finished.shape, dtype=torch.int64).to(self.device) - cat_action_index[:, :] = end_index - cat_action_index.scatter_(0, torch.unsqueeze(unfinished_index, 1), action_index) - - action_p.append(cat_p) - action_log_p.append(cat_log_p) - trg = torch.cat([trg, cat_action_index], dim=1) - - finished = torch.tensor(where(cat_action_index.cpu() == end_index, 1, finished.cpu())).to(self.device) - - return last_opera_index,last_normal_opera_index,operator_num,need_para_num,action_p,action_log_p,trg,finished - - + rows = [allowed_next_tokens(row.detach().cpu().numpy()) for row in cur_alg] + return torch.as_tensor(np.stack(rows), dtype=torch.bool, device=self.device) diff --git a/models/model/encoder.py b/models/model/encoder.py deleted file mode 100644 index 0070a55..0000000 --- a/models/model/encoder.py +++ /dev/null @@ -1,33 +0,0 @@ -from torch import nn - -from models.blocks.encoder_layer import EncoderLayer -from models.embedding.transformer_embedding import TransformerEmbedding - - -class Encoder(nn.Module): - - def __init__(self, enc_voc_size, max_len, d_model, ffn_hidden, n_head, n_layers, drop_prob, device): - super().__init__() - n_layers = 1 # force layers =1 - self.emb = TransformerEmbedding(d_model=d_model, - max_len=max_len, - vocab_size=enc_voc_size, - drop_prob=drop_prob, - device=device) - - self.layers = nn.ModuleList([EncoderLayer(d_model=d_model, - ffn_hidden=ffn_hidden, - n_head=n_head, - drop_prob=drop_prob) - for _ in range(n_layers)]) - - def forward(self, x, src_mask): - - # no need of emb - x = self.emb(x) - - # add a dim here,because emb(x) will add dim and we dont need that - for layer in self.layers: - x = layer(x, src_mask) - - return x \ No newline at end of file diff --git a/models/model/transformer.py b/models/model/transformer.py index fbd0496..46d4492 100644 --- a/models/model/transformer.py +++ b/models/model/transformer.py @@ -1,57 +1,55 @@ -import torch from torch import nn from models.model.decoder import Decoder -from models.model.encoder import Encoder class Transformer(nn.Module): - - def __init__(self, src_pad_idx, trg_pad_idx, trg_sos_idx, enc_voc_size, dec_voc_size, d_model, n_head, max_len, - ffn_hidden, n_layers, drop_prob, device): + """Decoder-only Transformer policy used by ALDes.""" + + def __init__( + self, + dec_voc_size, + d_model, + n_head, + max_len, + ffn_hidden, + n_layers, + drop_prob, + device, + condition_on_features=False, + ): super().__init__() - self.src_pad_idx = src_pad_idx - self.trg_pad_idx = trg_pad_idx - self.trg_sos_idx = trg_sos_idx self.device = device - self.encoder = Encoder(d_model=d_model, - n_head=n_head, - max_len=max_len, - ffn_hidden=ffn_hidden, - enc_voc_size=enc_voc_size, - drop_prob=drop_prob, - n_layers=n_layers, - device=device) - - self.decoder = Decoder(d_model=d_model, - n_head=n_head, - max_len=max_len, - ffn_hidden=ffn_hidden, - dec_voc_size=dec_voc_size, - drop_prob=drop_prob, - n_layers=n_layers, - device=device) - - def forward(self, src, trg, action_emb,action = None,reference = False): - action_emb_mask = None - action_emb = self.encoder(action_emb, action_emb_mask) - - src_mask = None - trg_mask = None - - enc_src = src - output = self.decoder(trg, enc_src, action_emb,trg_mask, src_mask,action,reference) - return output - - def make_src_mask(self, src): - src_mask = (src != self.src_pad_idx).unsqueeze(1).unsqueeze(2) - - # here dont need pading,once we input one vector of proble repesent - src_mask[:,:,:,:] =1 - return src_mask - - def make_trg_mask(self, trg): - trg_len = trg.shape[1] - trg_sub_mask = torch.tril(torch.ones(trg_len, trg_len)).bool().to(self.device) - trg_mask = trg_sub_mask - return trg_mask \ No newline at end of file + self.decoder = Decoder( + d_model=d_model, + n_head=n_head, + max_len=max_len, + ffn_hidden=ffn_hidden, + dec_voc_size=dec_voc_size, + drop_prob=drop_prob, + n_layers=n_layers, + device=device, + condition_on_features=condition_on_features, + ) + + def forward( + self, + features, + target, + attention_positions, + action=None, + reference=False, + ): + # ``attention_positions`` is retained in the public call signature for + # compatibility with the original ALDes training loop. The decoder + # derives positional information internally. + del attention_positions + return self.decoder( + target, + features, + None, + None, + None, + action, + reference, + ) diff --git a/pflacco_feature.py b/pflacco_feature.py index afaa6f4..6865dcd 100644 --- a/pflacco_feature.py +++ b/pflacco_feature.py @@ -1,111 +1,136 @@ -from datetime import datetime +"""Paper-style landscape features used only by continual ALDes training.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Iterable + +import numpy as np import pandas as pd -from pflacco.classical_ela_features import * -from pflacco.sampling import create_initial_sample -from ioh import get_problem, ProblemType -import ioh -from sklearn.preprocessing import StandardScaler - - -def test_pflacco(): - features = [] - # Get all 24 single-objective noiseless BBOB function in dimension 2 and 3 for the first five instances. - for fid in range(1,25): - for dim in [2, 3]: - for iid in range(1, 6): - # Get optimization problem - #problem = get_problem(fid, iid, dim, problem_type = ProblemType.BBOB) - problem = ioh.get_problem( - fid, - instance=iid, - dimension=dim, - problem_class=ioh.ProblemClass.BBOB - ) - # Create sample - X = create_initial_sample(dim, lower_bound = -5, upper_bound = 5) - y = X.apply(lambda x: problem(x), axis = 1) - - # Calculate ELA features - ela_meta = calculate_ela_meta(X, y) - ela_distr = calculate_ela_distribution(X, y) - ela_level = calculate_ela_level(X, y) - nbc = calculate_nbc(X, y) - disp = calculate_dispersion(X, y) - ic = calculate_information_content(X, y, seed = 100) - - # Store results in pandas dataframe - data = pd.DataFrame({**ic, **ela_meta, **ela_distr, **nbc, **disp, **{'fid': fid}, **{'dim': dim}, **{'iid': iid}}, index = [0]) - features.append(data) - - features = pd.concat(features).reset_index(drop = True) - - print(features) - -# input solution: x-y-x-y-... + +from autooptlib.aldes import extract_pbo_features + +ELA_DIR = Path("ela") + + def cal_feature(solution): - for i in range(0,len(solution),2): - x = pd.DataFrame(np.array(solution[i])[0:10,:]) - y= (np.array(solution[i+1])[0:10,:]).squeeze() - ela_meta = calculate_ela_meta(x, y) - return ela_meta - - # x:10*200--》60s - # 10*400-->1088s - - -def cal_PBO_feature(problem_id,instance,dim,seed): - print("\nbegin_{0}_{1}_{2}_{3}_".format(problem_id,instance,dim,seed)+ datetime.now().strftime("%Y-%m-%d %H:%M:%S")) - X = np.random.randint(0, 2, [10*dim,dim]) - problem = ioh.get_problem( - problem_id, - instance=instance, - dimension=dim, - problem_class=ioh.ProblemClass.BBOB + """Retain the small compatibility helper used by older experiments.""" + + from pflacco.classical_ela_features import calculate_ela_meta + + result = None + for index in range(0, len(solution), 2): + decisions = pd.DataFrame(np.asarray(solution[index])[:10, :]) + objectives = np.asarray(solution[index + 1])[:10].squeeze() + result = calculate_ela_meta(decisions, objectives) + return result + + +def save_ela( + problem_ids: Iterable[int] = range(1, 24), + *, + seed: int = 1, +) -> None: + """Extract and persist continual-task features and reusable populations.""" + + ELA_DIR.mkdir(parents=True, exist_ok=True) + dimensions = {1: 100, 2: 225, 3: 400} + for problem_id in problem_ids: + results = { + instance: extract_pbo_features( + int(problem_id), + instance=1, + dimension=dimension, + trials=5, + sample_factor=100, + feature_dim=32, + population_size=50, + seed=seed + 100 * int(problem_id) + instance, + ) + for instance, dimension in dimensions.items() + } + result = results[1] + if any(item.feature_names != result.feature_names for item in results.values()): + raise ValueError("PBO dimensions produced incompatible feature schemas.") + averaged_features = np.mean( + np.vstack([item.features for item in results.values()]), axis=0 + ) + pd.DataFrame([averaged_features], columns=result.feature_names).to_csv( + ELA_DIR / f"ela_result{problem_id}.csv", index=False + ) + np.savez_compressed( + ELA_DIR / f"initial_population{problem_id}.npz", + **{ + f"instance_{instance - 1}": item.initial_populations + for instance, item in results.items() + }, + ) + + +def transform(*, auto_generate: bool = True) -> np.ndarray: + """Load and standardize the 23 continual-task feature vectors.""" + + paths = [ELA_DIR / f"ela_result{problem}.csv" for problem in range(1, 24)] + missing = [path for path in paths if not path.exists()] + if missing: + if not auto_generate: + raise FileNotFoundError(f"Missing ALDes feature file: {missing[0]}") + save_ela() + frames = [pd.read_csv(path) for path in paths] + columns = list(frames[0].columns) + if any(list(frame.columns) != columns for frame in frames[1:]): + raise ValueError("Saved ALDes feature files do not share one schema.") + matrix = np.vstack([frame.iloc[0].to_numpy(dtype=float) for frame in frames]) + mean = matrix.mean(axis=0) + scale = matrix.std(axis=0) + scale[scale == 0] = 1.0 + return ((matrix - mean) / scale).astype(np.float32) + + +def load_standardized_features( + problem_ids: Iterable[int], *, auto_generate: bool = True +) -> dict[int, np.ndarray]: + """Fit feature scaling on only the continual tasks seen so far.""" + + ids = list(dict.fromkeys(int(problem_id) for problem_id in problem_ids)) + if not ids: + raise ValueError("At least one seen problem is required.") + paths = {problem_id: ELA_DIR / f"ela_result{problem_id}.csv" for problem_id in ids} + missing_ids = [ + problem_id for problem_id, path in paths.items() if not path.exists() + ] + if missing_ids: + if not auto_generate: + raise FileNotFoundError(f"Missing {paths[missing_ids[0]]}") + save_ela(missing_ids) + frames = {problem_id: pd.read_csv(path) for problem_id, path in paths.items()} + columns = list(frames[ids[0]].columns) + if any(list(frame.columns) != columns for frame in frames.values()): + raise ValueError("Saved ALDes feature files do not share one schema.") + matrix = np.vstack( + [frames[problem_id].iloc[0].to_numpy(dtype=float) for problem_id in ids] ) - Y = problem(X) - - x = pd.DataFrame(X) - y = (np.array(Y)).squeeze() - nbc = calculate_nbc(x, y) - ic = calculate_information_content(x, y, seed=100) - ela_meta = calculate_ela_meta(x, y) - #ela_distr = calculate_ela_distribution(x, y) - #ela_level = calculate_ela_level(x, y) - - disp = calculate_dispersion(x, y,dist_method = 'hamming') - - data = pd.DataFrame({**ic, **ela_meta, **nbc, **disp, **{'fid': problem_id}, **{'dim': dim}, **{'iid': instance}, **{'seed': seed}}, - index=[0]) - #print(data) - print("end" + datetime.now().strftime("%Y-%m-%d %H:%M:%S")) - return data -#test_pflacco() -def save_ela(): - medians = [] - for problem in range(1,24,1): - features = [] - for dim in [100]: - for seed in range(1,6,1): - data = cal_PBO_feature(problem,1,dim,seed) - features.append(data) - - features = pd.concat(features).reset_index(drop = True) - median = pd.DataFrame(features.median()) - median.T.to_csv("ela/ela_result{0}.csv".format(problem)) - #medians = pd.concat(medians).reset_index(drop=True) - #medians.to_csv("ela_result.csv") - - - -def transform(): - elas = [] - for problem in range(1,24,1): - ela = pd.read_csv("ela/ela_result{0}.csv".format(problem), index_col=0) - elas.append(ela) - elas = pd.concat(elas).reset_index(drop=True) - - scaler = StandardScaler() - X_train = scaler.fit_transform(elas) - - feature = X_train[:,:-4] - return feature + mean = matrix.mean(axis=0) + scale = matrix.std(axis=0) + scale[scale == 0] = 1.0 + standardized = ((matrix - mean) / scale).astype(np.float32) + return {problem_id: standardized[index] for index, problem_id in enumerate(ids)} + + +def load_initial_populations(problem_id: int) -> dict[int, np.ndarray]: + """Load the five sampled populations associated with one feature vector.""" + + path = ELA_DIR / f"initial_population{int(problem_id)}.npz" + if not path.exists(): + raise FileNotFoundError( + f"Missing {path}; run pflacco_feature.py for continual training first." + ) + with np.load(path, allow_pickle=False) as payload: + return { + int(name.rsplit("_", 1)[1]): np.array(payload[name], copy=True) + for name in payload.files + } + + +if __name__ == "__main__": + save_ela() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..73978d2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,71 @@ +[build-system] +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "aldes" +version = "2.0.0" +description = "Pure-Python ALDes for automated metaheuristic algorithm design" +readme = "README.md" +requires-python = ">=3.9,<3.12" +license = "Apache-2.0" +license-files = ["LICENSE"] +authors = [ + { name = "Qi Zhao" }, + { name = "Tengfei Liu" }, + { name = "Bai Yan" }, + { name = "Qiqi Duan" }, + { name = "Jian Yang" }, + { name = "Yuhui Shi" }, +] +dependencies = [ + "autooptlib[aldes] @ git+https://github.com/auto4opt/AutoOptLib.git@v1.3.0", + "numpy>=1.23,<3", + "scipy>=1.9,<2", +] + +[project.optional-dependencies] +test = [ + "build>=1.2,<2", + "pytest>=8,<9", + "ruff>=0.9,<1", + "twine>=5,<7", +] +plot = [ + "jupyter>=1,<2", + "matplotlib>=3.7,<4", + "seaborn>=0.12,<1", +] + +[project.scripts] +aldes-train = "train:main" +aldes-paper-subset = "run_paper_subset:main" + +[project.urls] +Paper = "https://doi.org/10.1109/TEVC.2024.3464677" +Repository = "https://github.com/auto4opt/ALDes" +Issues = "https://github.com/auto4opt/ALDes/issues" + +[tool.setuptools] +py-modules = [ + "EWC", + "aldes_setting", + "conf", + "pflacco_feature", + "run_paper_subset", + "train", +] + +[tool.setuptools.packages.find] +where = ["."] +include = ["draw*", "models*", "util*"] + +[tool.setuptools.package-data] +"draw.datas.reference_results" = ["**/*.csv", "**/*.mat", "**/*.pkl", "**/*.xlsx"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ruff] +target-version = "py39" +extend-exclude = ["draw/*.ipynb"] diff --git a/run_design_algs.py b/run_design_algs.py deleted file mode 100644 index d77a993..0000000 --- a/run_design_algs.py +++ /dev/null @@ -1,153 +0,0 @@ -import os - -import matlab.engine -import matlab - -import numpy as np -import re -import ray -import pickle -from concurrent.futures import ThreadPoolExecutor, as_completed -import time -import pandas as pd - -eng = matlab.engine.start_matlab() -# 此地址为test.m文件存放的地址 -work_path = os.getcwd() + "\\matlab" -eng.cd(work_path) - -def run(alg): - action = alg.action - problem_id = alg.problem_id - seed = alg.seed - save_path = alg.save_path - # delet first one "Begin" - action.pop(0) - # delet "End" - while (action[len(action) - 1] == 17): - action.pop() # delet last one - - alg = matlab.double(initializer=action) - - # default eval setting - instances = matlab.double([4]) - eval = 1 - - [performance, change,solution] = eng.get_per(alg, problem_id, instances, eval, nargout=3) - - performance = np.array(performance) - performance = performance[0] - - dump_file = save_path + f'seed{seed}_problem{problem_id}_res.pkl' - with open(dump_file, 'wb') as f: - # 使用pickle.dump()将字典对象序列化并保存到文件中 - pickle.dump(performance, f) - return performance - -class Alg: - def __init__(self, action, problem_id, seed, path): - self.action = action - self.problem_id = problem_id - self.seed = seed - self.save_path = path - -def read_algs(path, seeds, problem_set): - total_algs = [] - pattern = re.compile(r'\d+\.\d+|\d+') - - log_file = path + 'log.txt' - with open(log_file, 'r', encoding='utf-8') as f: - keyword = 'train over action:' - lines = f.readlines() - - index = 0 - for seed in seeds: - for problem_id in problem_set: - while index < len(lines): - line = lines[index] - if keyword in line: - index += 1 - numbers_of_alg = pattern.findall(lines[index]) - # convert str list to int list - numbers_of_alg = list(map(int, numbers_of_alg)) - - alg = Alg(numbers_of_alg, problem_id,seed,path) - total_algs.append(alg) - break - index += 1 - - return total_algs - -# ray sames not suit with matlab -def ray_parral(): - num_workers = 8 - while True: - num_runs_left = len(total_algs) - num_processes = min(num_workers, num_runs_left) - - total_works = [] - for _ in range(num_processes): - alg = total_algs.pop() - total_works.append(run.remote(alg.alg, alg.problem_id, alg.seed, save_path)) - - # collect results - outputs = ray.get(total_works) - - -def run_parral(seeds, problem_set, path): - seeds = [1, 2, 3, 4, 5] - problem_set = [1, 3, 14, 15, 17, 20] - - total_algs = read_algs(path, seeds, problem_set) - - #total_algs = total_algs[-6:] # run seed5 algs - # 创建一个包含3个线程的线程池 - with ThreadPoolExecutor(max_workers=6) as executor: - # 提交任务到线程池 - futures = [executor.submit(run, alg) for alg in total_algs] - - # 使用 as_completed 方法获取任务结果 - for future in as_completed(futures): - result = future.result() - print(result) - -def load_pkls(path, seeds, problem_set): - df = pd.DataFrame(columns=['Problem', 'seed', 'dim', 'Mean', 'Variance']) - df.to_csv(path + 'result.csv', index=False) - - for problem in problem_set: - datas = [] - for seed in seeds: - file_name = f'seed{seed}_problem{problem}_res.pkl' - file_path = path + file_name - - with open(file_path, 'rb') as f: - # loaded_data: steps(100)*algs(16)*instance(3)*runs(5) - data = pickle.load(f) - datas.append(data) - - datas = np.array(datas) - mean = -datas.mean() - var = datas.var() - - df = df._append({ - 'Problem': problem, - 'seed': seed, - 'dim': 625, - 'Mean': mean, - 'Variance': var - }, ignore_index=True) - df.to_csv(path + 'result.csv', index=False) -if __name__ == '__main__': - - seeds = [1, 2, 3, 4, 5] - seeds = [1] - problem_set = [1, 3, 14, 15, 17, 20] - FE3000_path = 'D:\\01Code\\ALDes\\draw\\datas\\pkls\\3000FE\\' - FE10000_path = 'D:\\01Code\\ALDes\\draw\\datas\\pkls\\10000FE\\' - - #run_parral(seeds, problem_set,FE3000_path) - - load_pkls(FE3000_path, seeds, problem_set) - - diff --git a/run_paper_subset.py b/run_paper_subset.py new file mode 100644 index 0000000..deb9730 --- /dev/null +++ b/run_paper_subset.py @@ -0,0 +1,223 @@ +"""Run a time-bounded subset of the published ALDes PBO experiment. + +Every completed training trial keeps the paper's per-trial protocol intact. +The wall-clock budget only determines whether another whole problem is started. +""" + +from __future__ import annotations + +import argparse +from importlib.resources import files +import json +import os +import platform +import statistics +import time +from datetime import datetime +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from scipy.io import loadmat +from scipy.stats import mannwhitneyu + +import train as aldes_train +from aldes_setting import begin_index +from autooptlib.aldes.vocabulary import TOKEN_BY_INDEX, normalize_sequence +from conf import batch_size_src, clip, device, ppo_epoch, total_epoch +from util.device import describe_device +from util.my_util import seed_torch + + +DEFAULT_PROBLEMS = (1, 14, 15) +DEFAULT_REFERENCE_DIR = Path( + str(files("draw.datas.reference_results").joinpath("design", "instance_4")) +) + + +def _parse_problems(value: str) -> list[int]: + problems = [int(item.strip()) for item in value.split(",") if item.strip()] + if not problems or any(problem < 1 or problem > 23 for problem in problems): + raise argparse.ArgumentTypeError( + "problems must be comma-separated IDs in 1..23" + ) + return problems + + +def _json_default(value: Any) -> Any: + if isinstance(value, (np.integer, np.floating)): + return value.item() + if isinstance(value, np.ndarray): + return value.tolist() + if isinstance(value, Path): + return str(value) + raise TypeError(f"Cannot serialize {type(value).__name__}") + + +def _write_json(path: Path, payload: dict[str, Any]) -> None: + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text( + json.dumps(payload, indent=2, default=_json_default) + "\n", + encoding="utf-8", + ) + temporary.replace(path) + + +def _reference_result(reference_dir: Path, problem_id: int) -> np.ndarray: + source = reference_dir / f"f{problem_id}.mat" + values = np.asarray(loadmat(source)["res"], dtype=float).reshape(-1) + # AutoOptLib minimizes the negated IOH objective; the paper reports the + # original maximization orientation. + return -values + + +def _summary(values: np.ndarray) -> dict[str, float | int]: + return { + "runs": int(values.size), + "mean": float(np.mean(values)), + "sample_variance": float(np.var(values, ddof=1)), + "sample_std": float(np.std(values, ddof=1)), + "minimum": float(np.min(values)), + "maximum": float(np.max(values)), + } + + +def _model_inputs() -> tuple[None, torch.Tensor, torch.Tensor]: + target = torch.tensor([[begin_index]], device=device).repeat(batch_size_src, 1) + attention = torch.arange(0, 27, dtype=torch.int, device=device) + attention = attention.unsqueeze(0).repeat(batch_size_src, 1) + return None, target, attention + + +def _run_trial( + problem_id: int, + seed: int, + reference_dir: Path, +) -> dict[str, Any]: + started = time.monotonic() + aldes_train.evaluation_round = 0 + aldes_train.logs.seed = seed + aldes_train.logs.problem_id = problem_id + seed_torch(seed) + + model, optimizer = aldes_train.get_model("single") + source, target, attention = _model_inputs() + action = aldes_train.train( + model, optimizer, clip, problem_id, source, target, attention + ) + + test_mean, test_values = aldes_train.get_performance(action, problem_id, eval=1) + del test_mean + local = -np.asarray(test_values[0], dtype=float).reshape(-1) + reference = _reference_result(reference_dir, problem_id) + local_summary = _summary(local) + reference_summary = _summary(reference) + mean_gap = float(local_summary["mean"] - reference_summary["mean"]) + relative_gap = mean_gap / max(abs(float(reference_summary["mean"])), 1e-12) + test = mannwhitneyu(local, reference, alternative="two-sided") + + normalized_action = normalize_sequence(action.detach().cpu().numpy()[0]) + elapsed = time.monotonic() - started + return { + "problem_id": problem_id, + "seed": seed, + "elapsed_seconds": elapsed, + "action_tokens": normalized_action, + "action_names": [TOKEN_BY_INDEX[token].name for token in normalized_action], + "local_values": local, + "local": local_summary, + "paper_reference_values": reference, + "paper_reference": reference_summary, + "mean_gap_local_minus_paper": mean_gap, + "relative_mean_gap": relative_gap, + "mann_whitney_u": float(test.statistic), + "mann_whitney_p": float(test.pvalue), + } + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--problems", + type=_parse_problems, + default=list(DEFAULT_PROBLEMS), + help="comma-separated PBO IDs (default: 1,14,15)", + ) + parser.add_argument("--seed", type=int, default=1) + parser.add_argument("--time-budget-minutes", type=float, default=60.0) + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help="default: experiments/paper_subset_", + ) + parser.add_argument( + "--reference-dir", + type=Path, + default=DEFAULT_REFERENCE_DIR, + ) + args = parser.parse_args(argv) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + output_dir = args.output_dir or Path("experiments") / f"paper_subset_{timestamp}" + output_dir.mkdir(parents=True, exist_ok=False) + reference_dir = args.reference_dir + budget_seconds = args.time_budget_minutes * 60.0 + experiment_started = time.monotonic() + + payload: dict[str, Any] = { + "status": "running", + "created_at": datetime.now().astimezone().isoformat(), + "requested_problems": args.problems, + "seed": args.seed, + "time_budget_seconds": budget_seconds, + "protocol": { + "training_epochs": total_epoch, + "algorithms_per_epoch": batch_size_src, + "ppo_updates_per_epoch": ppo_epoch, + "training_instances": [1, 2, 3], + "training_runs_per_instance": 5, + "training_evaluations_per_run": 5_000, + "test_instance": 4, + "test_runs": 30, + "test_evaluations_per_run": 50_000, + "population_size": 50, + }, + "environment": { + "python": platform.python_version(), + "torch": torch.__version__, + "platform": platform.platform(), + "machine": platform.machine(), + "cpu_count": os.cpu_count(), + "evaluation_workers": os.environ.get("ALDES_EVAL_WORKERS", "auto"), + "training_device": describe_device(device), + }, + "paper_reference_dir": os.path.relpath(reference_dir, Path.cwd()), + "results": [], + "skipped_problems": [], + } + results_path = output_dir / "results.json" + _write_json(results_path, payload) + + durations: list[float] = [] + for index, problem_id in enumerate(args.problems): + elapsed = time.monotonic() - experiment_started + remaining = budget_seconds - elapsed + if durations and remaining < statistics.median(durations): + payload["skipped_problems"] = args.problems[index:] + break + result = _run_trial(problem_id, args.seed, reference_dir) + durations.append(float(result["elapsed_seconds"])) + payload["results"].append(result) + payload["elapsed_seconds"] = time.monotonic() - experiment_started + _write_json(results_path, payload) + + payload["elapsed_seconds"] = time.monotonic() - experiment_started + payload["status"] = "completed" + _write_json(results_path, payload) + print(f"Structured results: {results_path.resolve()}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_aldes.py b/tests/test_aldes.py new file mode 100644 index 0000000..0d52f85 --- /dev/null +++ b/tests/test_aldes.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import numpy as np +import pytest +import torch + +import conf +import run_paper_subset +import train as training_script +from EWC import EWC +from autooptlib.aldes import EvaluationConfig, validate_sequence +from autooptlib.aldes.evaluator import ( + _evaluate_pbo_sequences, + _resolve_evaluation_workers, +) +from models.model.transformer import Transformer +from util import device as device_module + + +def _model(*, continual: bool = False) -> Transformer: + return Transformer( + dec_voc_size=32, + d_model=32, + n_head=4, + max_len=50, + ffn_hidden=64, + n_layers=1, + drop_prob=0.0, + device=torch.device("cpu"), + condition_on_features=continual, + ) + + +def _inputs(batch_size: int = 4): + target = torch.full((batch_size, 1), 17, dtype=torch.long) + attention = torch.arange(27).repeat(batch_size, 1) + return target, attention + + +def test_device_selection_prioritizes_accelerators(monkeypatch): + monkeypatch.setattr(device_module.torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(device_module, "_mps_available", lambda: True) + assert device_module.resolve_device().type == "cuda" + + monkeypatch.setattr(device_module.torch.cuda, "is_available", lambda: False) + assert device_module.resolve_device().type == "mps" + + monkeypatch.setattr(device_module, "_mps_available", lambda: False) + assert device_module.resolve_device().type == "cpu" + + +def test_cli_defaults_to_one_problem_and_one_seed(): + args = training_script.build_parser().parse_args([]) + assert args.mode == "single" + assert args.problems is None + assert args.seeds == [1] + + +def test_cli_rejects_unknown_pbo_problem(): + with pytest.raises(SystemExit): + training_script.build_parser().parse_args(["--problems", "24"]) + + +def test_paper_reference_data_is_packaged_and_loadable(): + reference_dir = run_paper_subset.DEFAULT_REFERENCE_DIR + assert reference_dir.is_dir() + assert run_paper_subset._reference_result(reference_dir, 1).size == 30 + + +def test_main_uses_safe_single_problem_default(monkeypatch): + calls = [] + training_script.EWC_ = object() + training_script.current_initial_populations = object() + monkeypatch.setattr(training_script, "seed_torch", lambda seed: None) + monkeypatch.setattr( + training_script, + "train_separately", + lambda problems, evaluate_test=False: calls.append((problems, evaluate_test)), + ) + + training_script.main([]) + + assert calls == [([1], False)] + assert training_script.EWC_ is None + assert training_script.current_initial_populations is None + + +def test_unavailable_explicit_accelerator_fails_clearly(monkeypatch): + monkeypatch.setattr(device_module.torch.cuda, "is_available", lambda: False) + monkeypatch.setattr(device_module, "_mps_available", lambda: False) + with pytest.raises(RuntimeError, match="cannot access"): + device_module.resolve_device("cuda") + with pytest.raises(RuntimeError, match="does not provide"): + device_module.resolve_device("mps") + + +def test_cpu_evaluation_worker_selection(monkeypatch): + monkeypatch.delenv("ALDES_EVAL_WORKERS", raising=False) + monkeypatch.setattr("autooptlib.aldes.evaluator.os.cpu_count", lambda: 10) + assert _resolve_evaluation_workers(None, 16) == 10 + assert _resolve_evaluation_workers(20, 4) == 4 + assert _resolve_evaluation_workers(1, 16) == 1 + monkeypatch.setenv("ALDES_EVAL_WORKERS", "2") + assert _resolve_evaluation_workers(None, 16) == 2 + with pytest.raises(ValueError, match="positive integer"): + _resolve_evaluation_workers(0, 4) + + +def test_parallel_cpu_evaluation_matches_serial(): + actions = np.asarray( + [ + [17, 0, 29, 8, 29, 12, 29, 18], + [17, 1, 29, 11, 29, 12, 29, 18], + ] + ) + config = EvaluationConfig( + population_size=4, + evaluations=20, + runs=2, + seed=19, + ) + serial = _evaluate_pbo_sequences(actions, 1, [1], config, workers=1) + parallel = _evaluate_pbo_sequences(actions, 1, [1], config, workers=2) + + np.testing.assert_array_equal(serial[0], parallel[0]) + for serial_values, parallel_values in zip(serial[1], parallel[1]): + np.testing.assert_array_equal(serial_values, parallel_values) + + +def test_single_problem_mode_is_default_and_ignores_features(): + assert conf.aldes_mode == "single" + model = _model() + assert model.decoder.emb.tok_emb.padding_idx is None + target, attention = _inputs() + + model.eval() + with torch.no_grad(): + actions, _, sampled_log_probability = model(None, target, attention) + _, _, replay_log_probability = model(None, target, attention, action=actions) + + for sequence in actions: + validate_sequence(sequence.tolist()) + torch.testing.assert_close( + sampled_log_probability, replay_log_probability, rtol=0, atol=1e-6 + ) + + +def test_continual_mode_requires_and_uses_problem_features(): + torch.manual_seed(4) + model = _model(continual=True) + target, attention = _inputs() + zeros = torch.zeros(4, 1, 32) + ones = torch.ones(4, 1, 32) + + with pytest.raises(ValueError, match="requires problem features"): + model(None, target, attention) + + model.eval() + with torch.no_grad(): + actions, _, sampled_log_probability = model(zeros, target, attention) + _, _, replay_log_probability = model(zeros, target, attention, action=actions) + _, _, changed_log_probability = model(ones, target, attention, action=actions) + + torch.testing.assert_close( + sampled_log_probability, replay_log_probability, rtol=0, atol=1e-6 + ) + assert not torch.equal(replay_log_probability, changed_log_probability) + + +def test_ewc_fisher_and_penalty_are_finite(): + model = _model() + target, attention = _inputs() + actions, _, log_probability = model(None, target, attention) + del actions + (-log_probability.sum(dim=1).mean()).backward() + + ewc = EWC(model) + ewc.update_diag_fisher(model) + assert torch.isfinite(ewc.penalty(model)) + assert all( + torch.isfinite(value).all() for value in ewc._precision_matrices.values() + ) + + +class _MemoryLog: + seed = 1 + problem_id = 1 + + def write_log(self, _message): + pass + + def dump_log(self, _experience): + pass + + +def test_one_ppo_update_runs_without_matlab(monkeypatch): + torch.manual_seed(8) + model = _model() + optimizer = torch.optim.Adam(model.parameters(), lr=5e-5) + target, attention = _inputs() + + def objective(actions, _problem_id): + costs = np.asarray(actions.detach().sum(dim=1), dtype=float) + return costs.tolist(), [np.asarray([cost]) for cost in costs] + + monkeypatch.setattr(training_script, "logs", _MemoryLog()) + monkeypatch.setattr(training_script, "get_performance", objective) + monkeypatch.setattr(training_script, "EWC_", None) + inferred = training_script.PPO( + model, + optimizer, + clip=1.0, + total_epoch=1, + ppo_epoch=1, + baseline=None, + clip_coef=0.2, + src=None, + trg=target, + att_src=attention, + problem_id=1, + ) + + assert inferred.shape[0] == 1 + validate_sequence(inferred[0].tolist()) diff --git a/train.py b/train.py index 3e6aab4..bbb1c1d 100644 --- a/train.py +++ b/train.py @@ -1,27 +1,48 @@ -import os +import argparse import time +from pathlib import Path + +import torch +from torch import nn from torch.optim import Adam -from data import * +from aldes_setting import begin_index, total_index +from conf import ( + adam_eps, + aldes_mode, + batch_size_src, + clip, + continual_problem_sets, + d_model, + device, + drop_prob, + ewc_weight, + ffn_hidden, + init_lr, + max_len, + n_heads, + n_layers, + ppo_epoch, + total_epoch, + use_ewc, + weight_decay, +) +from EWC import EWC from models.model.transformer import Transformer -from util.bleu import idx_to_word, get_bleu -import matlab.engine -import matlab -from matlab_setting import * -from EWC import * -from pflacco_feature import cal_feature, transform -from util.my_util import * +from autooptlib.aldes import evaluate_pbo_actions +from pflacco_feature import ( + load_initial_populations, + load_standardized_features, +) +from util.device import describe_device +from util.my_util import RunLogger, seed_torch -useEWC = False EWC_ = None +current_initial_populations = None +evaluation_round = 0 -eng = matlab.engine.start_matlab() -# matlab root dir -work_path = os.getcwd() + "\\matlab" -eng.cd(work_path) - -logs = my_log() +logs = RunLogger() def count_parameters(model): @@ -29,96 +50,106 @@ def count_parameters(model): def initialize_weights(m): - if hasattr(m, 'weight') and m.weight.dim() > 1: - nn.init.kaiming_uniform(m.weight.data) - - -def get_model(): - if model_type == 0: - model = Transformer(src_pad_idx=src_pad_idx, - trg_pad_idx=trg_pad_idx, - trg_sos_idx=trg_sos_idx, - d_model=d_model, - enc_voc_size=total_index, # enc_voc_size, - dec_voc_size=total_index, # voc_size, - max_len=max_len, - ffn_hidden=ffn_hidden, - n_head=n_heads, - n_layers=n_layers, - drop_prob=drop_prob, - device=device).to(device) - - print(f'The model has {count_parameters(model):,} trainable parameters') - model.apply(initialize_weights) - optimizer = Adam(params=model.parameters(), - lr=init_lr, - weight_decay=weight_decay, - eps=adam_eps) - else: - pass + if hasattr(m, "weight") and m.weight is not None and m.weight.dim() > 1: + nn.init.kaiming_uniform_(m.weight.data) + + +def get_model(mode=None): + mode = aldes_mode if mode is None else str(mode).lower() + if mode not in {"single", "continual"}: + raise ValueError("ALDes mode must be 'single' or 'continual'.") + model = Transformer( + d_model=d_model, + dec_voc_size=total_index, + max_len=max_len, + ffn_hidden=ffn_hidden, + n_head=n_heads, + n_layers=n_layers, + drop_prob=drop_prob, + device=device, + condition_on_features=(mode == "continual"), + ).to(device) + + print( + f"The model has {count_parameters(model):,} trainable parameters " + f"on {describe_device(device)}" + ) + model.apply(initialize_weights) + optimizer = Adam( + params=model.parameters(), + lr=init_lr, + weight_decay=weight_decay, + eps=adam_eps, + ) return model, optimizer def get_performance(action, problem_id, eval=0): - # call matlab funtion get performance - mean_performances = [] - performances = [] + """Evaluate generated actions with the Python AutoOptLib backend.""" + global evaluation_round + evaluation_seed = None + if logs.seed >= 0: + evaluation_seed = int(logs.seed) * 1_000_000 + evaluation_round + evaluation_round += 1 + mean_performances, performances = evaluate_pbo_actions( + action, + problem_id, + evaluate_test=bool(eval), + seed=evaluation_seed, + initial_populations=current_initial_populations, + workers=None, + ) if eval == 1: - action = action[0:3] - for j in range(action.shape[0]): - # get performance and reward - alg_list = action[j, :].reshape(-1).tolist() - - # delet first one "Begin" - alg_list.pop(0) - # delet "End" - while (alg_list[len(alg_list) - 1] == end_index): - alg_list.pop() # delet last one - # print(alg_list) - alg = matlab.double(initializer=alg_list) - if eval == 0: - instances = matlab.double([1, 2, 3]) - else: - instances = matlab.double([4]) - performance = eng.get_perf(alg, problem_id, instances, eval, nargout=1) - - if eval == 0: - performance = np.array(performance) - performance = performance[0:3] - else: - performance = np.array(performance) - performance = performance[0] - # performance = np.array(performance) #first row is instanceTrain , second is instanceTest, do not use Test - mean_performance = performance.mean() - mean_performances.append(mean_performance) - performances.append(performance) - if eval == 1: - logs.write_log("problem_" + (problem_id).__str__() + " result:\n" + str(performance)) - logs.write_log("problem_" + (problem_id).__str__() + " result mean:\n" + str(mean_performance)) + for mean_performance, performance in zip(mean_performances, performances): + logs.write_log( + "problem_" + str(problem_id) + " result:\n" + str(performance) + ) + logs.write_log( + "problem_" + str(problem_id) + " result mean:\n" + str(mean_performance) + ) return mean_performances, performances -def PPO(model, optimizer, clip, total_epoch, ppo_epoch, baseline, clip_coef, src, trg, att_src, problem_id): +def PPO( + model, + optimizer, + clip, + total_epoch, + ppo_epoch, + baseline, + clip_coef, + src, + trg, + att_src, + problem_id, +): ewc_loss = None global EWC_ action_total_list = [] log_performances = [] # ppo for i in range(total_epoch): + progress = i / max(1, total_epoch - 1) + learning_rate = init_lr * (1.0 - progress) + for group in optimizer.param_groups: + group["lr"] = learning_rate since = time.time() + model.eval() with torch.no_grad(): action, action_p, action_log_p = model(src, trg, att_src) action_log_p = torch.squeeze(action_log_p, 2) logs.write_log("action in train: \n" + str(action[0:5])) - logs.write_log("action_p in train: \n " + str(torch.squeeze(action_p[0:5], 2))) + logs.write_log( + "action_p in train: \n " + str(torch.squeeze(action_p[0:5], 2)) + ) action_total_list += action.tolist() mean_performances, performances = get_performance(action, problem_id) log_performances.append(performances) logs.write_log("performances in train: \n " + str(performances[0:5])) - mean_performances = torch.tensor(mean_performances) - cost = mean_performances.to(device) + model_device = next(model.parameters()).device + cost = torch.as_tensor(mean_performances, device=model_device) if baseline is None: baseline = cost.mean() else: @@ -127,19 +158,20 @@ def PPO(model, optimizer, clip, total_epoch, ppo_epoch, baseline, clip_coef, src # ppo update for j in range(ppo_epoch): - - _, new_action_p, new_action_log_p = model(src, trg, att_src, action) + _, _, new_action_log_p = model(src, trg, att_src, action) new_action_log_p = torch.squeeze(new_action_log_p, 2) logratio = new_action_log_p.sum(1) - action_log_p.sum(1) ratio = logratio.exp() pg_loss1 = (cost - baseline) * ratio - pg_loss2 = (cost - baseline) * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef) + pg_loss2 = (cost - baseline) * torch.clamp( + ratio, 1 - clip_coef, 1 + clip_coef + ) loss = torch.max(pg_loss1, pg_loss2).mean() if EWC_ is not None: ewc_loss = EWC_.penalty(model) - loss += ewc_loss + loss += ewc_weight * ewc_loss optimizer.zero_grad() loss.backward() @@ -147,225 +179,323 @@ def PPO(model, optimizer, clip, total_epoch, ppo_epoch, baseline, clip_coef, src optimizer.step() if ewc_loss is not None: - logs.write_log(('step :', round((i / total_epoch) * 100, 2), - '% , ewc_loss :', ewc_loss.item()).__str__()) - print('step :', round((i / total_epoch) * 100, 2), - '% , ewc_loss :', ewc_loss.item()) + logs.write_log( + ( + "step :", + round((i / total_epoch) * 100, 2), + "% , ewc_loss :", + ewc_loss.item(), + ).__str__() + ) + print( + "step :", + round((i / total_epoch) * 100, 2), + "% , ewc_loss :", + ewc_loss.item(), + ) time_elapsed = time.time() - since - print('step :', round((i / total_epoch) * 100, 2), - '% , loss :', loss.item(), - ', cost_mean :', cost.mean().item(), - ', baseline :', baseline.item(), - ',Training complete in {:.0f}m {:.0f}s'.format( - time_elapsed // 60, time_elapsed % 60) - ) - logs.write_log(('step :', round((i / total_epoch) * 100, 2), - '% , loss :', loss.item(), - ', cost_mean :', cost.mean().item(), - ', baseline :', baseline.item(), - ',Training complete in {:.0f}m {:.0f}s'.format( - time_elapsed // 60, time_elapsed % 60) - ).__str__()) + print( + "step :", + round((i / total_epoch) * 100, 2), + "% , loss :", + loss.item(), + ", cost_mean :", + cost.mean().item(), + ", baseline :", + baseline.item(), + ",Training complete in {:.0f}m {:.0f}s".format( + time_elapsed // 60, time_elapsed % 60 + ), + ) + logs.write_log( + ( + "step :", + round((i / total_epoch) * 100, 2), + "% , loss :", + loss.item(), + ", cost_mean :", + cost.mean().item(), + ", baseline :", + baseline.item(), + ",Training complete in {:.0f}m {:.0f}s".format( + time_elapsed // 60, time_elapsed % 60 + ), + ).__str__() + ) logs.dump_log(log_performances) + model.eval() + with torch.no_grad(): + inferred_action, _, _ = model(src, trg, att_src, reference=True) + return inferred_action[:1] + + +def PPO_get_ewc( + model, + optimizer, + clip, + total_epoch, + ppo_epoch, + baseline, + clip_coef, + src, + trg, + att_src, + problem_id, +): + del clip, total_epoch, ppo_epoch + model.eval() + with torch.no_grad(): + action, _, action_log_p = model(src, trg, att_src) + action_log_p = torch.squeeze(action_log_p, 2) + + mean_performances, _ = get_performance(action, problem_id) + model_device = next(model.parameters()).device + cost = torch.as_tensor(mean_performances, device=model_device) + if baseline is None: + baseline = cost.mean() + else: + baseline = 0.8 * baseline + 0.2 * cost.mean() + baseline = baseline.detach() - return action - - -def PPO_get_ewc(model, optimizer, clip, total_epoch, ppo_epoch, baseline, clip_coef, src, trg, att_src, problem_id): - # ppo - for i in range(1): - since = time.time() - with torch.no_grad(): - action, action_p, action_log_p = model(src, trg, att_src) - action_log_p = torch.squeeze(action_log_p, 2) - - mean_performances, performances = get_performance(action, problem_id) - mean_performances = torch.tensor(mean_performances) - cost = mean_performances.to(device) - if baseline is None: - baseline = cost.mean() - else: - baseline = 0.8 * baseline + 0.2 * cost.mean() - baseline = baseline.detach() - - # ppo update - for j in range(1): - _, new_action_p, new_action_log_p = model(src, trg, att_src, action) - new_action_log_p = torch.squeeze(new_action_log_p, 2) - logratio = new_action_log_p.sum(1) - action_log_p.sum(1) - ratio = logratio.exp() + _, _, new_action_log_p = model(src, trg, att_src, action) + new_action_log_p = torch.squeeze(new_action_log_p, 2) + logratio = new_action_log_p.sum(1) - action_log_p.sum(1) + ratio = logratio.exp() - pg_loss1 = (cost - baseline) * ratio - pg_loss2 = (cost - baseline) * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef) - loss = torch.max(pg_loss1, pg_loss2).mean() + pg_loss1 = (cost - baseline) * ratio + pg_loss2 = (cost - baseline) * torch.clamp(ratio, 1 - clip_coef, 1 + clip_coef) + loss = torch.max(pg_loss1, pg_loss2).mean() - optimizer.zero_grad() - loss.backward() - EWC_.update_diag_fisher(model) + optimizer.zero_grad() + loss.backward() + EWC_.update_diag_fisher(model) return action def train(model, optimizer, clip, problem_id, src, trg, att_src): - model.train() + # PPO old/new policy likelihoods must use the same deterministic network + # mode; gradients still propagate while the module is in eval mode. + model.eval() baseline = None clip_coef = 0.2 - if train_type == 0: - action = PPO(model, optimizer, clip, total_epoch, ppo_epoch, baseline, clip_coef, src, trg, att_src, problem_id) - - return action + return PPO( + model, + optimizer, + clip, + total_epoch, + ppo_epoch, + baseline, + clip_coef, + src, + trg, + att_src, + problem_id, + ) + + +def train_separately(problem_ids=None, *, evaluate_test=False): + """Train independent policies for one or more PBO problems. + + The default is intentionally one problem. Single-problem design returns + the inferred action directly and does not need a model checkpoint. + """ - -def evaluate(model, iterator, criterion): - model.eval() - epoch_loss = 0 - batch_bleu = [] - with torch.no_grad(): - for i, batch in enumerate(iterator): - src = batch.src - trg = batch.trg - output = model(src, trg[:, :-1]) - output_reshape = output.contiguous().view(-1, output.shape[-1]) - trg = trg[:, 1:].contiguous().view(-1) - - loss = criterion(output_reshape, trg) - epoch_loss += loss.item() - - total_bleu = [] - for j in range(batch_size): - try: - trg_words = idx_to_word(batch.trg[j], loader.target.vocab) - output_words = output[j].max(dim=1)[1] - output_words = idx_to_word(output_words, loader.target.vocab) - bleu = get_bleu(hypotheses=output_words.split(), reference=trg_words.split()) - total_bleu.append(bleu) - except: - pass - - total_bleu = sum(total_bleu) / len(total_bleu) - batch_bleu.append(total_bleu) - - batch_bleu = sum(batch_bleu) / len(batch_bleu) - return epoch_loss / len(iterator), batch_bleu - - -def train_separately(): print("Train separately") logs.write_log("Train separately") - problem_set = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21] - problem_nums = 0 - input_src = [] + problem_set = [1] if problem_ids is None else [int(item) for item in problem_ids] + actions = {} for problem_id in problem_set: logs.problem_id = problem_id print("Train problem_" + problem_id.__str__()) logs.write_log("Train problem_" + problem_id.__str__()) - model, optimizer = get_model() + model, optimizer = get_model("single") - src = torch.randn(10, d_model).to(device) # 512->30 + src = None trg = torch.tensor([begin_index]).to(device) trg = trg.unsqueeze(dim=0) # train with batch - src = src.repeat(batch_size_src, 1, 1) trg = trg.repeat(batch_size_src, 1) - att_src = torch.range(0, 26, 1, dtype=torch.int).to(device) + att_src = torch.arange(0, 27, 1, dtype=torch.int).to(device) att_src = att_src.unsqueeze(dim=0) att_src = att_src.repeat(batch_size_src, 1) - input_src.append(src) logs.write_log("model input :\n" + str(src)) action = train(model, optimizer, clip, problem_id, src, trg, att_src) - + actions[problem_id] = action.detach().cpu() logs.write_log("train over action: \n" + str(action)) + print(f"problem_{problem_id} inferred action: {action[0].tolist()}") - # get_performance(action,problem_id,eval=1) + if evaluate_test: + get_performance(action, problem_id, eval=1) + return actions -def train_in_one(): +def train_in_one(problem_sequence=None, *, checkpoint_dir=None): + """Train one feature-conditioned policy across a problem sequence.""" + print("Train In One") logs.write_log("Train In One") input_src = {} - model, optimizer = get_model() - global EWC_ - problem_set = [1, 2, 11, 18, 19, 22, 23] - problem_nums = 0 - feature = transform() - for problem_id in problem_set: - src = torch.from_numpy(feature[problem_id - 1][0:d_model].reshape(1, d_model)).to(torch.float32).to(device) - src = src.repeat(batch_size_src, 1, 1) - - input_src[problem_id] = src - for problem_id in problem_set: + model, optimizer = get_model("continual") + global EWC_, current_initial_populations + if problem_sequence is None: + problem_sequence = [ + problem_id + for problem_set in continual_problem_sets + for problem_id in problem_set + ] + else: + problem_sequence = [int(problem_id) for problem_id in problem_sequence] + seen_problem_ids = [] + for stage, problem_id in enumerate(problem_sequence, start=1): + active_problem_ids = list(dict.fromkeys(seen_problem_ids + [problem_id])) + feature = load_standardized_features(active_problem_ids) + for active_id, vector in feature.items(): + src = torch.from_numpy(vector[:d_model].reshape(1, d_model)) + src = src.to(torch.float32).to(device) + input_src[active_id] = src.repeat(batch_size_src, 1, 1) logs.problem_id = problem_id - problem_nums += 1 print("Train problem_" + problem_id.__str__()) logs.write_log("Train problem_" + problem_id.__str__()) + current_initial_populations = load_initial_populations(problem_id) trg = torch.tensor([begin_index]).to(device) trg = trg.unsqueeze(dim=0) # train with batch trg = trg.repeat(batch_size_src, 1) - att_src = torch.range(0, 26, 1, dtype=torch.int).to(device) + att_src = torch.arange(0, 27, 1, dtype=torch.int).to(device) att_src = att_src.unsqueeze(dim=0) att_src = att_src.repeat(batch_size_src, 1) - action = train(model, optimizer, clip, problem_id, input_src[problem_id], trg, att_src) - - # logs.write_log("train over action: \n"+str(action)) - if useEWC is True: + action = train( + model, optimizer, clip, problem_id, input_src[problem_id], trg, att_src + ) + logs.write_log("train over action: \n" + str(action)) + if use_ewc is True: print("Cal EWC______________________") EWC_ = EWC(model) - for i in problem_set: + fisher_problem_ids = list(dict.fromkeys(seen_problem_ids + [problem_id])) + for i in fisher_problem_ids: + current_initial_populations = load_initial_populations(i) temp_src = input_src[i] - PPO_get_ewc(model, optimizer, clip, total_epoch, ppo_epoch, None, 0.2, temp_src, trg, att_src, i) - if i == problem_id: break + PPO_get_ewc( + model, + optimizer, + clip, + total_epoch, + ppo_epoch, + None, + 0.2, + temp_src, + trg, + att_src, + i, + ) for key in EWC_._precision_matrices: - EWC_._precision_matrices[key] = EWC_._precision_matrices[key] / (problem_nums) - - torch.save(model.state_dict(), 'logs/' + "train_in_one/" + problem_id.__str__() + '.pt') + EWC_._precision_matrices[key] = EWC_._precision_matrices[key] / len( + fisher_problem_ids + ) + seen_problem_ids.append(problem_id) + + if checkpoint_dir is not None: + output = Path(checkpoint_dir) + output.mkdir(parents=True, exist_ok=True) + torch.save( + model.state_dict(), + output / f"stage{stage}_problem{problem_id}.pt", + ) logs.write_log("EWC TEST : train over problem : " + (problem_id).__str__()) for key, value in input_src.items(): - old_action, action_p, action_log_p = model(input_src[key], trg, att_src, reference=True) + current_initial_populations = load_initial_populations(key) + old_action, _, _ = model(input_src[key], trg, att_src, reference=True) logs.write_log("problem_" + key.__str__() + " action:\n" + str(old_action)) get_performance(old_action[0:1], key, eval=1) - - -def test(): - model, optimizer = get_model() - model.load_state_dict( - torch.load(r'D:\01Code\transformer-rl-3\logs\Transformer_PPO\100_32\1_11_17_12_11\train_in_one.pt')) - input_src = [] - problem_set = [2, 3, 4, 5, 6, 7, 8, 9, 10] - problem_nums = 0 - for problem_id in problem_set: - src = torch.randn(30, d_model).to(device) # 512->30 - trg = torch.tensor([begin_index]).to(device) - trg = trg.unsqueeze(dim=0) - # train with batch - src = src.repeat(batch_size_src, 1, 1) - trg = trg.repeat(batch_size_src, 1) - - att_src = torch.range(0, 26, 1, dtype=torch.int).to(device) - att_src = att_src.unsqueeze(dim=0) - att_src = att_src.repeat(batch_size_src, 1) - input_src.append(src) - - with torch.no_grad(): - action, action_p, action_log_p = model(src, trg, att_src) - action_log_p = torch.squeeze(action_log_p, 2) - - mean_performances, performances = get_performance(action, problem_id) - mean_performances = torch.tensor(mean_performances) - - -if __name__ == '__main__': - for seed in range(1, 6, 1): + current_initial_populations = None + + +def _id_list(value): + """Parse a comma-separated list of positive integer IDs.""" + + try: + values = [int(item.strip()) for item in value.split(",") if item.strip()] + except ValueError as exc: + raise argparse.ArgumentTypeError( + "IDs must be comma-separated integers." + ) from exc + if not values or any(item <= 0 for item in values): + raise argparse.ArgumentTypeError( + "At least one positive integer ID is required." + ) + return values + + +def _problem_list(value): + values = _id_list(value) + if any(item > 23 for item in values): + raise argparse.ArgumentTypeError("PBO problem IDs must be in 1..23.") + return values + + +def build_parser(): + parser = argparse.ArgumentParser(description="Train the pure-Python ALDes policy.") + parser.add_argument( + "--mode", + choices=("single", "continual"), + default=aldes_mode, + help="single designs from scratch for each problem; continual reuses one policy", + ) + parser.add_argument( + "--problems", + type=_problem_list, + default=None, + help="comma-separated PBO IDs (single-mode default: 1)", + ) + parser.add_argument( + "--seeds", + type=_id_list, + default=[1], + help="comma-separated training seeds (default: 1)", + ) + parser.add_argument( + "--evaluate-test", + action="store_true", + help="run the paper's 30-run test after single-problem training", + ) + parser.add_argument( + "--checkpoint-dir", + type=Path, + default=None, + help="optional continual-mode state-dictionary output directory", + ) + return parser + + +def main(argv=None): + """Command-line entry point with a safe one-problem, one-seed default.""" + + args = build_parser().parse_args(argv) + if args.mode == "single" and args.checkpoint_dir is not None: + raise SystemExit("--checkpoint-dir is only available in continual mode.") + + global EWC_, current_initial_populations, evaluation_round + for seed in args.seeds: + EWC_ = None + current_initial_populations = None + evaluation_round = 0 logs.seed = seed - logs.write_log('seed is {}'.format(seed)) + logs.write_log(f"seed is {seed}") seed_torch(seed) - #train_in_one() - train_separately() + if args.mode == "continual": + train_in_one(args.problems, checkpoint_dir=args.checkpoint_dir) + else: + train_separately(args.problems or [1], evaluate_test=args.evaluate_test) + + +if __name__ == "__main__": + main() diff --git a/util/__init__.py b/util/__init__.py index cbea971..bb98588 100644 --- a/util/__init__.py +++ b/util/__init__.py @@ -2,4 +2,4 @@ @author : Hyunwoong @when : 2019-10-28 @homepage : https://github.com/gusdnd852 -""" \ No newline at end of file +""" diff --git a/util/__pycache__/__init__.cpython-38.pyc b/util/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index fa71b17..0000000 Binary files a/util/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/util/__pycache__/bleu.cpython-38.pyc b/util/__pycache__/bleu.cpython-38.pyc deleted file mode 100644 index 5581fc4..0000000 Binary files a/util/__pycache__/bleu.cpython-38.pyc and /dev/null differ diff --git a/util/__pycache__/data_loader.cpython-38.pyc b/util/__pycache__/data_loader.cpython-38.pyc deleted file mode 100644 index 3cc3dc7..0000000 Binary files a/util/__pycache__/data_loader.cpython-38.pyc and /dev/null differ diff --git a/util/__pycache__/my_util.cpython-38.pyc b/util/__pycache__/my_util.cpython-38.pyc deleted file mode 100644 index 41dc7ec..0000000 Binary files a/util/__pycache__/my_util.cpython-38.pyc and /dev/null differ diff --git a/util/__pycache__/tokenizer.cpython-38.pyc b/util/__pycache__/tokenizer.cpython-38.pyc deleted file mode 100644 index c558f43..0000000 Binary files a/util/__pycache__/tokenizer.cpython-38.pyc and /dev/null differ diff --git a/util/bleu.py b/util/bleu.py deleted file mode 100644 index c1af8b8..0000000 --- a/util/bleu.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -@author : Hyunwoong -@when : 2019-12-22 -@homepage : https://github.com/gusdnd852 -""" -import math -from collections import Counter - -import numpy as np - - -def bleu_stats(hypothesis, reference): - """Compute statistics for BLEU.""" - stats = [] - stats.append(len(hypothesis)) - stats.append(len(reference)) - for n in range(1, 5): - s_ngrams = Counter( - [tuple(hypothesis[i:i + n]) for i in range(len(hypothesis) + 1 - n)] - ) - r_ngrams = Counter( - [tuple(reference[i:i + n]) for i in range(len(reference) + 1 - n)] - ) - - stats.append(max([sum((s_ngrams & r_ngrams).values()), 0])) - stats.append(max([len(hypothesis) + 1 - n, 0])) - return stats - - -def bleu(stats): - """Compute BLEU given n-gram statistics.""" - if len(list(filter(lambda x: x == 0, stats))) > 0: - return 0 - (c, r) = stats[:2] - log_bleu_prec = sum( - [math.log(float(x) / y) for x, y in zip(stats[2::2], stats[3::2])] - ) / 4. - return math.exp(min([0, 1 - float(r) / c]) + log_bleu_prec) - - -def get_bleu(hypotheses, reference): - """Get validation BLEU score for dev set.""" - stats = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) - for hyp, ref in zip(hypotheses, reference): - stats += np.array(bleu_stats(hyp, ref)) - return 100 * bleu(stats) - - -def idx_to_word(x, vocab): - words = [] - for i in x: - word = vocab.itos[i] - if '<' not in word: - words.append(word) - words = " ".join(words) - return words diff --git a/util/data_loader.py b/util/data_loader.py deleted file mode 100644 index d91f9a3..0000000 --- a/util/data_loader.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -@author : Hyunwoong -@when : 2019-10-29 -@homepage : https://github.com/gusdnd852 -""" -from torchtext.legacy.data import Field, BucketIterator -from torchtext.legacy.datasets.translation import Multi30k - - -class DataLoader: - source: Field = None - target: Field = None - - def __init__(self, ext, tokenize_en, tokenize_de, init_token, eos_token): - self.ext = ext - self.tokenize_en = tokenize_en - self.tokenize_de = tokenize_de - self.init_token = init_token - self.eos_token = eos_token - print('dataset initializing start') - - def make_dataset(self): - if self.ext == ('.de', '.en'): - self.source = Field(tokenize=self.tokenize_de, init_token=self.init_token, eos_token=self.eos_token, - lower=True, batch_first=True) - self.target = Field(tokenize=self.tokenize_en, init_token=self.init_token, eos_token=self.eos_token, - lower=True, batch_first=True) - - elif self.ext == ('.en', '.de'): - self.source = Field(tokenize=self.tokenize_en, init_token=self.init_token, eos_token=self.eos_token, - lower=True, batch_first=True) - self.target = Field(tokenize=self.tokenize_de, init_token=self.init_token, eos_token=self.eos_token, - lower=True, batch_first=True) - - train_data, valid_data, test_data = Multi30k.splits(exts=self.ext, fields=(self.source, self.target)) - return train_data, valid_data, test_data - - def build_vocab(self, train_data, min_freq): - self.source.build_vocab(train_data, min_freq=min_freq) - self.target.build_vocab(train_data, min_freq=min_freq) - - def make_iter(self, train, validate, test, batch_size, device): - train_iterator, valid_iterator, test_iterator = BucketIterator.splits((train, validate, test), - batch_size=batch_size, - device=device) - print('dataset initializing done') - return train_iterator, valid_iterator, test_iterator diff --git a/util/device.py b/util/device.py new file mode 100644 index 0000000..9df3aae --- /dev/null +++ b/util/device.py @@ -0,0 +1,65 @@ +"""Portable PyTorch device selection for ALDes training.""" + +from __future__ import annotations + +import torch + + +def _mps_available() -> bool: + backend = getattr(torch.backends, "mps", None) + return bool(backend is not None and backend.is_available()) + + +def resolve_device(requested: str | torch.device = "auto") -> torch.device: + """Select CUDA/ROCm, Apple MPS, or CPU in that priority order. + + PyTorch's ROCm build intentionally exposes AMD GPUs through the + ``torch.cuda`` API, so the CUDA branch covers both NVIDIA and AMD. + """ + + name = str(requested).strip().lower() + if name in {"", "auto"}: + if torch.cuda.is_available(): + return torch.device("cuda:0") + if _mps_available(): + return torch.device("mps") + return torch.device("cpu") + + if name in {"amd", "rocm", "hip"}: + if not torch.cuda.is_available() or torch.version.hip is None: + raise RuntimeError( + "AMD GPU acceleration requires a ROCm-enabled PyTorch build." + ) + return torch.device("cuda:0") + + device = torch.device(name) + if device.type == "cuda" and not torch.cuda.is_available(): + raise RuntimeError( + "CUDA/ROCm was requested, but this PyTorch installation cannot " + "access a compatible GPU." + ) + if device.type == "mps" and not _mps_available(): + raise RuntimeError( + "MPS was requested, but this PyTorch installation or Mac does " + "not provide the MPS backend." + ) + if device.type not in {"cpu", "cuda", "mps"}: + raise ValueError("ALDES_DEVICE must be auto, cpu, cuda, cuda:N, mps, or rocm.") + return device + + +def describe_device(device: torch.device) -> str: + """Return a concise human-readable accelerator description.""" + + if device.type == "cuda": + backend = "AMD ROCm" if torch.version.hip is not None else "NVIDIA CUDA" + index = ( + device.index if device.index is not None else torch.cuda.current_device() + ) + return f"{backend}: {torch.cuda.get_device_name(index)}" + if device.type == "mps": + return "Apple MPS" + return "CPU" + + +__all__ = ["describe_device", "resolve_device"] diff --git a/util/epoch_timer.py b/util/epoch_timer.py deleted file mode 100644 index 314dab7..0000000 --- a/util/epoch_timer.py +++ /dev/null @@ -1,12 +0,0 @@ -""" -@author : Hyunwoong -@when : 2019-10-29 -@homepage : https://github.com/gusdnd852 -""" - - -def epoch_time(start_time, end_time): - elapsed_time = end_time - start_time - elapsed_mins = int(elapsed_time / 60) - elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) - return elapsed_mins, elapsed_secs diff --git a/util/my_util.py b/util/my_util.py index ad81a9c..e543257 100644 --- a/util/my_util.py +++ b/util/my_util.py @@ -1,56 +1,52 @@ -import torch -import torch.nn as nn -import torch.optim as optim -from torch.distributions.normal import Normal +from __future__ import annotations + +import pickle from datetime import datetime -import os +from pathlib import Path +from typing import Any + import numpy as np -import pickle +import torch + -def _get_action(model_output): - # 偶数列 - mean = model_output[:, 1::2] - # 奇数列 - sdv = model_output[:, 0::2] - # here use exp make sure its positive - sdv = torch.exp(sdv) - - probs = Normal(mean, sdv) - action = probs.sample() - action = torch.sigmoid(action) - return action, probs.log_prob(action).sum(1), probs.entropy().sum(1) - -def seed_torch(seed=2): #1029 - np.random.seed(seed) - torch.manual_seed(seed) - torch.cuda.manual_seed(seed) - torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. - torch.backends.cudnn.benchmark = False - torch.backends.cudnn.deterministic = True - -class my_log(): - def __init__(self): - now = datetime.now() # 获得当前时间 - global_timestr = now.strftime("%m_%d_%H_%M") - self.log_dir = f'logs/{global_timestr}/' - os.makedirs(self.log_dir) - self.log_file = self.log_dir + 'log.txt' - +def seed_torch(seed: int = 2) -> None: + """Seed the random-number generators used by ALDes.""" + + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.benchmark = False + torch.backends.cudnn.deterministic = True + mps = getattr(torch, "mps", None) + if mps is not None and torch.backends.mps.is_available(): + mps.manual_seed(seed) + + +class RunLogger: + """Write human-readable logs and raw PPO histories for one process.""" + + def __init__(self, root: str | Path = "logs") -> None: + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + self.log_dir = Path(root) / timestamp + self.log_file = self.log_dir / "log.txt" self.problem_id = -1 self.seed = -1 - - def write_log(self,info): - f = open(self.log_file, 'a') - now = datetime.now() # 获得当前时间 - timestr = now.strftime("%m_%d_%H_%M") - f.write('\n' + timestr + ":"+info) - f.close() - - def dump_log(self,experience): - dump_file = self.log_dir + f'seed{self.seed}_problem{self.problem_id}_.pkl' - with open(dump_file, 'wb') as f: - # 使用pickle.dump()将字典对象序列化并保存到文件中 - pickle.dump(experience, f) - + def write_log(self, info: Any) -> None: + self.log_dir.mkdir(parents=True, exist_ok=True) + timestamp = datetime.now().isoformat(timespec="seconds") + with self.log_file.open("a", encoding="utf-8") as stream: + stream.write(f"\n{timestamp}: {info}") + + def dump_log(self, experience: Any) -> None: + self.log_dir.mkdir(parents=True, exist_ok=True) + dump_file = self.log_dir / ( + f"seed{self.seed}_problem{self.problem_id}_training.pkl" + ) + with dump_file.open("wb") as stream: + pickle.dump(experience, stream) + +__all__ = ["RunLogger", "seed_torch"] diff --git a/util/tokenizer.py b/util/tokenizer.py deleted file mode 100644 index c71d578..0000000 --- a/util/tokenizer.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -@author : Hyunwoong -@when : 2019-10-29 -@homepage : https://github.com/gusdnd852 -""" -#import spacy - - -class Tokenizer: - - def __init__(self): - self.spacy_de = None - self.spacy_en = None - #self.spacy_de = spacy.load('de_core_news_sm') - #self.spacy_en = spacy.load('en_core_web_sm') - - def tokenize_de(self, text): - """ - Tokenizes German text from a string into a list of strings - """ - return [tok.text for tok in self.spacy_de.tokenizer(text)] - - def tokenize_en(self, text): - """ - Tokenizes English text from a string into a list of strings - """ - return [tok.text for tok in self.spacy_en.tokenizer(text)]