Qi Liu commited on
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .DS_Store +0 -0
- README.md +209 -3
- bpp_offline_aco/.DS_Store +0 -0
- bpp_offline_aco/dataset/test1000_dataset.npz +3 -0
- bpp_offline_aco/dataset/test120_dataset.npz +3 -0
- bpp_offline_aco/dataset/test500_dataset.npz +3 -0
- bpp_offline_aco/dataset/train500_dataset.npz +3 -0
- bpp_offline_aco/dataset/val1000_dataset.npz +3 -0
- bpp_offline_aco/dataset/val120_dataset.npz +3 -0
- bpp_offline_aco/dataset/val500_dataset.npz +3 -0
- bpp_offline_aco/eval.py +393 -0
- bpp_offline_aco/evaluation_description.txt +397 -0
- bpp_offline_aco/external_knowledge.txt +2 -0
- bpp_offline_aco/function_description.txt +7 -0
- bpp_offline_aco/generate_dataset.py +49 -0
- bpp_offline_aco/problem_description.txt +6 -0
- bpp_offline_aco/seed_solution.py +4 -0
- bpp_offline_aco/seed_solution_idea.txt +1 -0
- bpp_offline_aco/settings.yaml +2 -0
- bpp_online/.DS_Store +0 -0
- bpp_online/dataset/weibull_100k_test.pickle +3 -0
- bpp_online/dataset/weibull_10k_test.pickle +3 -0
- bpp_online/dataset/weibull_5k_test.pickle +3 -0
- bpp_online/dataset/weibull_5k_train.pickle +3 -0
- bpp_online/dataset/weibull_5k_val.pickle +3 -0
- bpp_online/eval.py +193 -0
- bpp_online/evaluation_description.txt +197 -0
- bpp_online/function_description.txt +7 -0
- bpp_online/generate_dataset.py +96 -0
- bpp_online/problem_description.txt +3 -0
- bpp_online/readme.md +1 -0
- bpp_online/seed_solution.py +16 -0
- bpp_online/seed_solution_idea.txt +1 -0
- bpp_online/settings.yaml +2 -0
- cvrp_aco/.DS_Store +0 -0
- cvrp_aco/dataset/test100_dataset.npy +3 -0
- cvrp_aco/dataset/test20_dataset.npy +3 -0
- cvrp_aco/dataset/test50_dataset.npy +3 -0
- cvrp_aco/dataset/train50_dataset.npy +3 -0
- cvrp_aco/dataset/val100_dataset.npy +3 -0
- cvrp_aco/dataset/val20_dataset.npy +3 -0
- cvrp_aco/dataset/val50_dataset.npy +3 -0
- cvrp_aco/eval.py +333 -0
- cvrp_aco/evaluation_description.txt +337 -0
- cvrp_aco/external_knowledge.txt +2 -0
- cvrp_aco/function_description.txt +8 -0
- cvrp_aco/generate_dataset.py +51 -0
- cvrp_aco/problem_description.txt +3 -0
- cvrp_aco/seed_solution.py +4 -0
- cvrp_aco/seed_solution_idea.txt +2 -0
.DS_Store
ADDED
|
Binary file (14.3 kB). View file
|
|
|
README.md
CHANGED
|
@@ -1,3 +1,209 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Benchmark Problems
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
This benchmark is adapted from [**ReEvo**](https://ai4co.github.io/reevo/)[1], which originally consists of six types of combinatorial optimization problems (COPs). We have extended the benchmark by adding a cooperative driving problem that involves complex simulation environments using [SUMO](https://eclipse.dev/sumo/).
|
| 6 |
+
|
| 7 |
+
## Table of Contents
|
| 8 |
+
|
| 9 |
+
1. [Types of Functions to Evolve](#types-of-functions-to-evolve)
|
| 10 |
+
2. [Problem Details](#problem-details)
|
| 11 |
+
3. [How to Customize Your Own Benchmark](#how-to-customize-your-own-benchmark)
|
| 12 |
+
4. [References](#references)
|
| 13 |
+
|
| 14 |
+
## Types of Functions to Evolve
|
| 15 |
+
|
| 16 |
+
The functions to evolve are categorized into three groups:
|
| 17 |
+
|
| 18 |
+
### Classical Metaheuristics (ACO / GA / GLS)
|
| 19 |
+
- **Ant Colony Optimization (ACO)**[2]: Evolve ACO heuristic components, such as the computation of desirability and pheromone guidance.
|
| 20 |
+
- **Guided Local Search (GLS)**[3]: Evolve the penalty heuristic that guides perturbations during GLS.
|
| 21 |
+
- **Genetic Algorithm (GA)**[4]: Evolve GA-related operators and heuristics (the domain-specific logic within the GA pipeline, as defined by the problem wrapper).
|
| 22 |
+
|
| 23 |
+
### Attention Reshaping in Neural Combinatorial Optimization (POMO / LEHD)
|
| 24 |
+
- **Policy Optimization with Multiple Optima (POMO)**[5]: A reinforcement learning training and inference framework for neural constructive solvers that exploits symmetry and uses multiple rollouts from different starting conditions to stabilize and improve solution quality. We evolve attention reshaping heuristics inserted into the neural solver (not the model weights). For POMO settings, download checkpoints from the [official repository](https://github.com/yd-kwon/POMO) and place them in the corresponding directories (e.g., place `checkpoint-3100.pt` for TSP at `problems/tsp_pomo/checkpoints/checkpoint-3100.pt`).
|
| 25 |
+
|
| 26 |
+
- **Neural Combinatorial Optimization with Light Encoder, Heavy Decoder (LEHD)**[6]: This approach shifts modeling capacity into the decoder while keeping the encoder lightweight, aiming for better generalization and scaling in constructive routing solvers. We evolve attention reshaping heuristics. For LEHD settings, download checkpoints and data from the [official repository](https://github.com/CIAM-Group/NCO_code/tree/main/single_objective/LEHD) and place them in the corresponding directories.
|
| 27 |
+
|
| 28 |
+
### Direct Solution Construction Heuristics
|
| 29 |
+
We can evolve functions that directly construct solutions. For example:
|
| 30 |
+
- For online bin packing problems, evolve the function that generates priority scores for each bin; the solver then selects the bin with the highest priority.
|
| 31 |
+
- For cooperative driving problems, evolve the function that generates actions for all drivers.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
## Problem Details
|
| 35 |
+
|
| 36 |
+
The benchmark problems are stored at `[project_root]/problems`. Detailed descriptions of each problem are provided below.
|
| 37 |
+
|
| 38 |
+
### Traveling Salesman Problems (TSPs)
|
| 39 |
+
The Traveling Salesman Problem (TSP) is a classic optimization challenge that seeks the shortest possible route for a salesman to visit each city in a list exactly once and return to the origin city.
|
| 40 |
+
|
| 41 |
+
- **TSP via Ant Colony Optimization (`tsp_aco`)**: Find the shortest path that visits all given nodes and returns to the starting node. ACO implementations are adapted from [DeepACO](https://github.com/henry-yeh/DeepACO)[2].
|
| 42 |
+
- **TSP via Guided Local Search (`tsp_gls`)**: Use Guided Local Search (GLS)[3] to find the shortest path.
|
| 43 |
+
- **TSP via LEHD (`tsp_lehd`)**: Use LEHD[6] to find the shortest path.
|
| 44 |
+
- **TSP via POMO (`tsp_pomo`)**: Use POMO[5] to find the shortest path.
|
| 45 |
+
- **TSP via Constructive Routing Solvers (`tsp_constructive`)**: Evolve functions that directly construct solutions for TSP.
|
| 46 |
+
|
| 47 |
+
### Capacitated Vehicle Routing Problems (CVRPs)
|
| 48 |
+
The Capacitated Vehicle Routing Problem (CVRP) extends the TSP by adding constraints on vehicle capacity. Each vehicle can carry a limited load, and the objective is to minimize the total distance traveled while delivering goods to various locations.
|
| 49 |
+
|
| 50 |
+
- **CVRP via Ant Colony Optimization (`cvpr_aco`)**: Solve CVRP using Ant Colony Optimization (ACO)[2].
|
| 51 |
+
- **CVRP via LEHD (`cvpr_lehd`)**: Solve CVRP using LEHD[6].
|
| 52 |
+
- **CVRP via POMO (`cvpr_pomo`)**: Solve CVRP using POMO[5].
|
| 53 |
+
|
| 54 |
+
### Bin Packing Problems (BPPs)
|
| 55 |
+
The Bin Packing Problem requires packing objects of different volumes into a finite number of bins or containers of fixed volume to minimize the number of bins used. This problem is widely applicable in manufacturing, shipping, and storage optimization.
|
| 56 |
+
|
| 57 |
+
- **BPP via Ant Colony Optimization (`bpp_offline_aco`)**
|
| 58 |
+
- **Online BPP (`bpp_online`) via Priority Score Heuristics**
|
| 59 |
+
|
| 60 |
+
### Orienteering Problems (OPs)
|
| 61 |
+
In the Orienteering Problem (OP), the goal is to maximize the total score collected by visiting nodes while subject to a maximum tour length constraint.
|
| 62 |
+
|
| 63 |
+
- **OP for Routing Problems via Ant Colony Optimization (`op_aco`)**
|
| 64 |
+
|
| 65 |
+
### Multiple Knapsack Problems (MKPs)
|
| 66 |
+
The Multiple Knapsack Problem (MKP) involves distributing a set of items, each with a given weight and value, among multiple knapsacks to maximize the total value without exceeding the capacity of any knapsack.
|
| 67 |
+
|
| 68 |
+
- **MKP via Ant Colony Optimization (`mkp_aco`)**: Solve MKP using Ant Colony Optimization (ACO)[2].
|
| 69 |
+
|
| 70 |
+
### Decap Placement Problem (DPPs)
|
| 71 |
+
The Decap Placement Problem (DPP) is a critical hardware design optimization issue that involves finding the optimal placement of decoupling capacitors (decap) within a power distribution network (PDN) to enhance power integrity (PI). Decoupling capacitors are hardware components that help reduce power noise and ensure a stable power supply to operating integrated circuits in hardware devices such as CPUs, GPUs, and AI accelerators.
|
| 72 |
+
|
| 73 |
+
- **Decap Placement Problem (DPP) for Electronic Design Automation (EDA) Problems via Genetic Algorithm (GA)[4] (`dpp_ga`)**
|
| 74 |
+
|
| 75 |
+
### Cooperative Driving Problem (CDPs)
|
| 76 |
+
The Cooperative Driving Problem (CDP) is a complex optimization challenge that involves optimizing the driving behavior of multiple vehicles on a road segment.
|
| 77 |
+
|
| 78 |
+
- **Cooperative Driving Problem (CDP) (`driving`)**: Evolve functions that directly construct driving actions for each time step.
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
## How to Customize Your Own Benchmark
|
| 84 |
+
|
| 85 |
+
### Command line arguments requirements (same for all problems)
|
| 86 |
+
Command line arguments:
|
| 87 |
+
1. `root_dir`: the project root directory; knowing project root can help you to load data; default: current working directory (os.getcwd());
|
| 88 |
+
Eval script need this to load dataset since eval script may be generated and stored in a different location to support parallelism;
|
| 89 |
+
2. `file_output_prefix`: the output file prefix: this prefix can be used to save output files during evaluation for inspection purposes;
|
| 90 |
+
we use prefix since you may want more than just a folder name; say you may want to add solution id to the output filename;
|
| 91 |
+
file will be saved by: `with open(f"{file_output_prefix}<filename>", 'w'):\n...`;
|
| 92 |
+
absolute path is recommended;
|
| 93 |
+
default: '', which means just save to current working directory;
|
| 94 |
+
3. `mode`: train or val; default: val;
|
| 95 |
+
4. `problem_size`; default: 50 (Note: this value differs for each problem!);
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
### How to run
|
| 99 |
+
You can manually run the script this way:
|
| 100 |
+
```
|
| 101 |
+
python eval.py \
|
| 102 |
+
--root_dir=<path_to_project_root> \
|
| 103 |
+
--file_output_prefix=<path_to_output_file> \
|
| 104 |
+
--mode=val \
|
| 105 |
+
--problem_size=50
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
`Evaluator` class will run eval script like this:
|
| 109 |
+
```
|
| 110 |
+
subprocess.run([
|
| 111 |
+
'python', 'script.py',
|
| 112 |
+
'--root_dir', '/path/to/project',
|
| 113 |
+
'--file_output_prefix', '/path/to/outputs/exp1_',
|
| 114 |
+
],
|
| 115 |
+
text=True,
|
| 116 |
+
timeout=self.timeout_seconds, # timeout seconds
|
| 117 |
+
cwd=os.getcwd(),
|
| 118 |
+
env=env, # python env
|
| 119 |
+
stdout=f,
|
| 120 |
+
stderr=f
|
| 121 |
+
)
|
| 122 |
+
```
|
| 123 |
+
Note:
|
| 124 |
+
Evaluator won't specify `mode` and `problem_size`;
|
| 125 |
+
Since evaluator is intended for general purpose, we assume it does not know any problem detail.
|
| 126 |
+
This makes it easier for you to add new problems - you don't need to modify the `Evaluator` class.
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
### Output requirements (same for all problems)
|
| 130 |
+
Eval script should print out `metrics`,`features`, and `score`;
|
| 131 |
+
1. `metrics`: a dict that map test name (str) to metrics (Dict),
|
| 132 |
+
or a dict that maps performance index name to values;
|
| 133 |
+
`metrics` dict is used for user and AI agent inspection;
|
| 134 |
+
It's optional but we strongly recommend you to prepare a detailed metrics for each problem; as this can help LLM to better understand the solution performance!
|
| 135 |
+
2. `features`: a tuple of ints that represents the features of the solution;
|
| 136 |
+
`features` tuple is used for solution storage in the solution database;
|
| 137 |
+
Features is generally generated from metrics, possibly with some added feature;
|
| 138 |
+
but Evaluator will not assume any conversion method; you need to specify it yourself.
|
| 139 |
+
Features could be set to `None` if you don't want to specify feature; in that case MAP-Elite will be disabled;
|
| 140 |
+
3. `score`: a float that represents the score of the solution;
|
| 141 |
+
`score` is used for as the fitness score.
|
| 142 |
+
It's required. It's usually generated from metrics; but Evaluator will not assume any conversion method; you need to specify it yourself.
|
| 143 |
+
|
| 144 |
+
Example:
|
| 145 |
+
Assume the following variables are generated during eval script:
|
| 146 |
+
```
|
| 147 |
+
metrics = {
|
| 148 |
+
"critical_ttc_count": 28,
|
| 149 |
+
"collisions": 0,
|
| 150 |
+
"emergencyStops": 0,
|
| 151 |
+
"emergencyBraking": 4,
|
| 152 |
+
"teleports": 0,
|
| 153 |
+
"avg_speed": 12.51,
|
| 154 |
+
"speed_variance": 16.22
|
| 155 |
+
}
|
| 156 |
+
features = (2, 0, 1, 4)
|
| 157 |
+
score = 12.34
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
Then stdout should be:
|
| 161 |
+
```
|
| 162 |
+
...
|
| 163 |
+
__SANDBOX_RESULT__
|
| 164 |
+
|
| 165 |
+
__METRICS_START__
|
| 166 |
+
<print(repr(metrics))>
|
| 167 |
+
__METRICS_END__
|
| 168 |
+
|
| 169 |
+
__FEATURES_START__
|
| 170 |
+
<print(repr(features))>
|
| 171 |
+
__FEATURES_END__
|
| 172 |
+
|
| 173 |
+
__SCORE_START__
|
| 174 |
+
<print(repr(score))>
|
| 175 |
+
__SCORE_END__
|
| 176 |
+
|
| 177 |
+
__SANDBOX_SUCCESS__
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
### Dynamic solution function loading
|
| 181 |
+
Solution function scripts will be generated on the fly and loaded dynamically.
|
| 182 |
+
To enable parallelism, we will save different solution script to different files. Hence `Evaluator` will need to load the solution script dynamically.
|
| 183 |
+
Keep the line below unchanged:
|
| 184 |
+
```
|
| 185 |
+
import seed_solution as solution_module
|
| 186 |
+
```
|
| 187 |
+
Say, one solution script is generated as `solution_0905.py`;
|
| 188 |
+
Then the above line will be replaced by:
|
| 189 |
+
```
|
| 190 |
+
import solution_0905 as solution_module
|
| 191 |
+
```
|
| 192 |
+
and the new eval script will be saved locally and got run.
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
## References
|
| 198 |
+
|
| 199 |
+
[1] Ye, H., Wang, J., Cao, Z., Berto, F., Hua, C., Kim, H., Park, J., & Song, G. (2024). Reevo: Large language models as hyper-heuristics with reflective evolution. *Advances in Neural Information Processing Systems*, 37, 43571–43608.
|
| 200 |
+
|
| 201 |
+
[2] Ye, H., Wang, J., Cao, Z., Liang, H., & Li, Y. (2023). DeepACO: Neural-enhanced ant systems for combinatorial optimization. *Advances in Neural Information Processing Systems*, 36, 43706–43728.
|
| 202 |
+
|
| 203 |
+
[3] Voudouris, C., & Tsang, E. (1999). Guided local search and its application to the traveling salesman problem. *European Journal of Operational Research*, 113(2), 469–499.
|
| 204 |
+
|
| 205 |
+
[4] Park, H., Kim, H., Kim, H., Park, J., Choi, S., Kim, J., Son, K., Suh, H., Kim, T., Ahn, J., & Kim, J. (2023, October). Versatile genetic algorithm-bayesian optimization (GA-BO) bi-level optimization for decoupling capacitor placement. In *2023 IEEE 32nd Conference on Electrical Performance of Electronic Packaging and Systems (EPEPS)* (pp. 1–3). IEEE.
|
| 206 |
+
|
| 207 |
+
[5] Kwon, Y. D., Choo, J., Kim, B., Yoon, I., Gwon, Y., & Min, S. (2020). POMO: Policy optimization with multiple optima for reinforcement learning. *Advances in Neural Information Processing Systems*, 33, 21188–21198.
|
| 208 |
+
|
| 209 |
+
[6] Luo, F., Lin, X., Liu, F., Zhang, Q., & Wang, Z. (2023). Neural combinatorial optimization with heavy decoder: Toward large scale generalization. *Advances in Neural Information Processing Systems*, 36, 8845–8864.
|
bpp_offline_aco/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
bpp_offline_aco/dataset/test1000_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64ea8870b7858c3ff824a3661ff98e78affb55316ef0e31e37760b9e6fd0422b
|
| 3 |
+
size 512268
|
bpp_offline_aco/dataset/test120_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fe96e289874e9808c037af6e78831dd9e92484efb9e4da5696ec071dc8b9dbae
|
| 3 |
+
size 61708
|
bpp_offline_aco/dataset/test500_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5002d16ca7f59f3f46257176f416e5d7856ddf4be0655660acf2b6f64d8143d3
|
| 3 |
+
size 256268
|
bpp_offline_aco/dataset/train500_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f19298b958c2bde265a3226ff21ef4daa7c35a90aed4598a17637ee4c5016638
|
| 3 |
+
size 20268
|
bpp_offline_aco/dataset/val1000_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6e3a8b7361f8a2642f6d82ba0fab970c1365f659a54b3ebe737eb5727dcf9f8c
|
| 3 |
+
size 512268
|
bpp_offline_aco/dataset/val120_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0986f1708f6dc0d9dd48fc49c40597ed6623fece7f6ee6c14f54ddc6cf763c9d
|
| 3 |
+
size 61708
|
bpp_offline_aco/dataset/val500_dataset.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4652c48c92c8b9d71d328313f7835aa86be9146ef5817478feb95a2f08dbc2a3
|
| 3 |
+
size 256268
|
bpp_offline_aco/eval.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation script for BPP-Offline-ACO problem
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import traceback
|
| 5 |
+
from math import floor
|
| 6 |
+
import argparse
|
| 7 |
+
from typing import NamedTuple, Tuple, List, Annotated, Dict, Any
|
| 8 |
+
import numpy as np
|
| 9 |
+
import numpy.typing as npt
|
| 10 |
+
import seed_solution as solution_module # Note: solution module script is generated and saved on the fly
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# =====Load function to evolve=====
|
| 14 |
+
problem = "bpp_offline_aco"
|
| 15 |
+
heuristics = getattr(solution_module, "heuristics") # Get function to evolve
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# =====Configuration and Parameters=====
|
| 19 |
+
IntArray = npt.NDArray[np.int_]
|
| 20 |
+
FloatArray = npt.NDArray[np.float64]
|
| 21 |
+
|
| 22 |
+
class BPPInstance(NamedTuple):
|
| 23 |
+
n: int
|
| 24 |
+
capacity: int
|
| 25 |
+
demands: npt.NDArray[np.int_]
|
| 26 |
+
|
| 27 |
+
DEMAND_LOW = 20
|
| 28 |
+
DEMAND_HIGH = 100
|
| 29 |
+
CAPACITY = 150
|
| 30 |
+
|
| 31 |
+
dataset_conf = {
|
| 32 |
+
'train': (500,),
|
| 33 |
+
'val': (120, 500), # 120, 500, 1000
|
| 34 |
+
'test': (120, 500), # 120, 500, 1000
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# =====Utility Functions=====
|
| 39 |
+
def load_dataset(fp) -> list[BPPInstance]:
|
| 40 |
+
data = np.load(fp)
|
| 41 |
+
demands = data['demands']
|
| 42 |
+
instances = []
|
| 43 |
+
n = demands.shape[1]
|
| 44 |
+
for demand in demands:
|
| 45 |
+
instance = BPPInstance(n, CAPACITY, demand)
|
| 46 |
+
instances.append(instance)
|
| 47 |
+
return instances
|
| 48 |
+
|
| 49 |
+
def organize_path(path: IntArray) -> Tuple[int, IntArray]:
|
| 50 |
+
order = {}
|
| 51 |
+
result = np.zeros_like(path)
|
| 52 |
+
for i, v in enumerate(path):
|
| 53 |
+
if v in order:
|
| 54 |
+
result[i] = order[v]
|
| 55 |
+
else:
|
| 56 |
+
result[i] = order[v] = len(order)
|
| 57 |
+
return len(order), result
|
| 58 |
+
|
| 59 |
+
def calculate_path_cost_fitness(vacancies: IntArray, capacity: int) -> Tuple[int, float]:
|
| 60 |
+
occupied = (capacity - vacancies[vacancies!=capacity]).astype(float)
|
| 61 |
+
cost = len(occupied)
|
| 62 |
+
result = ((occupied/capacity)**2).sum().item()/cost
|
| 63 |
+
return cost, result
|
| 64 |
+
|
| 65 |
+
def calculate_path_fitness(vacancies: List[int], capacity: int) -> float:
|
| 66 |
+
occupied = capacity - np.array(vacancies, dtype=float)
|
| 67 |
+
result = ((occupied/capacity)**2).sum().item()/len(vacancies)
|
| 68 |
+
return result
|
| 69 |
+
|
| 70 |
+
def greedy_sample(prob: FloatArray) -> int:
|
| 71 |
+
return prob.argmax().item()
|
| 72 |
+
|
| 73 |
+
def random_sample(prob: FloatArray) -> int:
|
| 74 |
+
# not used, `random_sample_discrete_distribution` is a faster implementation
|
| 75 |
+
sampled = np.random.choice(prob.size, p=prob/prob.sum())
|
| 76 |
+
return sampled
|
| 77 |
+
|
| 78 |
+
def random_sample_discrete_distribution(prob: FloatArray) -> int:
|
| 79 |
+
# prob_exp = np.exp(prob-prob.max())
|
| 80 |
+
# prob_exp[prob==0] = 0
|
| 81 |
+
# np.random.choice is somehow slow
|
| 82 |
+
cumprob = np.cumsum(prob)
|
| 83 |
+
sampled = np.searchsorted(cumprob, next(uniform_generator)*cumprob[-1]).item()
|
| 84 |
+
return sampled if sampled<len(cumprob) else len(cumprob)-1
|
| 85 |
+
|
| 86 |
+
def uniform_number_generator(batch_size = 500):
|
| 87 |
+
# it's also slow to generate random numbers one by one
|
| 88 |
+
while 1:
|
| 89 |
+
numbers = np.random.random(batch_size)
|
| 90 |
+
for n in numbers:
|
| 91 |
+
yield n.item()
|
| 92 |
+
|
| 93 |
+
uniform_generator = uniform_number_generator()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# =====ACO class=====
|
| 97 |
+
class ACO(object):
|
| 98 |
+
def __init__(self,
|
| 99 |
+
demand: IntArray, # (n, )
|
| 100 |
+
heuristic: FloatArray, # (n, n)
|
| 101 |
+
capacity: int,
|
| 102 |
+
n_ants=20,
|
| 103 |
+
decay=0.95,
|
| 104 |
+
alpha=1,
|
| 105 |
+
beta=1,
|
| 106 |
+
greedy = False
|
| 107 |
+
):
|
| 108 |
+
|
| 109 |
+
self.problem_size = len(demand)
|
| 110 |
+
self.capacity = capacity
|
| 111 |
+
self.demand = demand
|
| 112 |
+
assert self.demand.max() <= self.capacity
|
| 113 |
+
|
| 114 |
+
self.n_ants = n_ants
|
| 115 |
+
self.decay = decay
|
| 116 |
+
self.alpha = alpha
|
| 117 |
+
self.beta = beta
|
| 118 |
+
|
| 119 |
+
self.pheromone: FloatArray = np.ones((self.problem_size, self.problem_size)) # problem_size x self.problem_size
|
| 120 |
+
heuristic[heuristic > 1e6] = 1e6
|
| 121 |
+
heuristic[heuristic < 1e-6] = 1e-6
|
| 122 |
+
heuristic = heuristic/heuristic.max() # normalize
|
| 123 |
+
heuristic[heuristic < 1e-6] = 1e-6
|
| 124 |
+
self.heuristic: FloatArray = heuristic # problem_size x self.problem_size
|
| 125 |
+
|
| 126 |
+
self.shortest_path: IntArray = np.arange(self.problem_size)
|
| 127 |
+
self.best_cost = self.problem_size
|
| 128 |
+
|
| 129 |
+
self._ordinal: IntArray = np.arange(self.problem_size, dtype=int) # for indexing
|
| 130 |
+
self.greedy_mode = greedy
|
| 131 |
+
|
| 132 |
+
def run(self, iterations: int) -> Tuple[int, IntArray]:
|
| 133 |
+
for _ in range(iterations):
|
| 134 |
+
prob = self.pheromone**self.alpha * self.heuristic**self.beta
|
| 135 |
+
paths, costs, fitnesses = self.gen_paths(self.n_ants, prob)
|
| 136 |
+
best_index = costs.argmin()
|
| 137 |
+
best_cost = costs[best_index].item()
|
| 138 |
+
if best_cost < self.best_cost:
|
| 139 |
+
self.shortest_path = paths[best_index]
|
| 140 |
+
self.best_cost = best_cost
|
| 141 |
+
self.update_pheronome(paths, fitnesses)
|
| 142 |
+
assert self.is_valid_path(self.shortest_path)
|
| 143 |
+
# cost, path = organize_path(self.shortest_path)
|
| 144 |
+
# assert cost >= np.ceil(np.sum(self.demand).astype(float)/self.capacity).item()
|
| 145 |
+
return organize_path(self.shortest_path)
|
| 146 |
+
|
| 147 |
+
def sample_only(self, count: int) -> Tuple[int, IntArray]:
|
| 148 |
+
self.greedy_mode = True
|
| 149 |
+
paths, costs, _ = self.gen_paths(count, self.heuristic)
|
| 150 |
+
best_index = costs.argmin()
|
| 151 |
+
best_path = paths[best_index]
|
| 152 |
+
assert self.is_valid_path(best_path)
|
| 153 |
+
return organize_path(best_path)
|
| 154 |
+
|
| 155 |
+
def update_pheronome(self, paths: List[IntArray], fitnesses: FloatArray):
|
| 156 |
+
delta_phe = np.zeros_like(self.pheromone) # problem_size x problem_size
|
| 157 |
+
for path, f in zip(paths, fitnesses):
|
| 158 |
+
delta_phe[path[:, None]==path[None, :]] += f / self.n_ants
|
| 159 |
+
self.pheromone *= self.decay
|
| 160 |
+
self.pheromone += delta_phe
|
| 161 |
+
|
| 162 |
+
def gen_paths(self, count: int, prob: FloatArray) -> Tuple[List[IntArray], IntArray, FloatArray]:
|
| 163 |
+
paths, costs, fitnesses = [], [], []
|
| 164 |
+
for _ in range(count):
|
| 165 |
+
path, cost, fitness = self.sample_path(prob)
|
| 166 |
+
paths.append(path)
|
| 167 |
+
costs.append(cost)
|
| 168 |
+
fitnesses.append(fitness)
|
| 169 |
+
return paths, np.array(costs, dtype=int), np.array(fitnesses, dtype=float)
|
| 170 |
+
|
| 171 |
+
def sample_path(self, prob: FloatArray
|
| 172 |
+
) -> Tuple[
|
| 173 |
+
Annotated[IntArray, "sampled path"],
|
| 174 |
+
Annotated[int, "used bins"],
|
| 175 |
+
Annotated[float, "fitness"]]:
|
| 176 |
+
|
| 177 |
+
if self.greedy_mode:
|
| 178 |
+
sample_func = greedy_sample
|
| 179 |
+
else:
|
| 180 |
+
sample_func = random_sample_discrete_distribution
|
| 181 |
+
|
| 182 |
+
path = np.ones(self.problem_size, dtype=int)*-1 # x=path[i] => put item i in bin x
|
| 183 |
+
valid_items = np.ones(self.problem_size, dtype=bool)
|
| 184 |
+
current_bin = item_count = 0
|
| 185 |
+
vacancies = []
|
| 186 |
+
bin_vacancy = self.capacity
|
| 187 |
+
bin_items = np.zeros_like(valid_items)
|
| 188 |
+
|
| 189 |
+
for _ in range(self.problem_size):
|
| 190 |
+
mask = np.bitwise_and(self.demand <= bin_vacancy, valid_items)
|
| 191 |
+
if not np.any(mask): # no valid item
|
| 192 |
+
# move to the next bin
|
| 193 |
+
vacancies.append(bin_vacancy)
|
| 194 |
+
bin_vacancy, item_count = self.capacity, 0
|
| 195 |
+
current_bin += 1
|
| 196 |
+
bin_items[:] = False
|
| 197 |
+
# uniformly select one
|
| 198 |
+
selected = self.random_select(valid_items)
|
| 199 |
+
else:
|
| 200 |
+
if item_count == 0:
|
| 201 |
+
selected = self.random_select(mask)
|
| 202 |
+
else:
|
| 203 |
+
item_prob = (prob[bin_items].sum(0)/item_count+1e-5) * mask
|
| 204 |
+
selected = sample_func(item_prob)
|
| 205 |
+
|
| 206 |
+
# put item in this bin
|
| 207 |
+
bin_items[selected] = True
|
| 208 |
+
bin_vacancy -= self.demand[selected]
|
| 209 |
+
valid_items[selected] = False
|
| 210 |
+
path[selected] = current_bin
|
| 211 |
+
item_count += 1
|
| 212 |
+
|
| 213 |
+
vacancies.append(bin_vacancy)
|
| 214 |
+
fitness = calculate_path_fitness(vacancies, self.capacity)
|
| 215 |
+
return path, len(vacancies), fitness
|
| 216 |
+
|
| 217 |
+
def random_select(self, mask: npt.NDArray[np.bool_]) -> int:
|
| 218 |
+
valid = self._ordinal[mask]
|
| 219 |
+
return valid[floor(next(uniform_generator)*len(valid))].item()
|
| 220 |
+
# return valid[np.random.randint(0, len(valid))].item()
|
| 221 |
+
|
| 222 |
+
def is_valid_path(self, path: IntArray) -> bool:
|
| 223 |
+
# not used
|
| 224 |
+
if path.shape[0] != self.problem_size:
|
| 225 |
+
return False
|
| 226 |
+
bins, path = organize_path(path)
|
| 227 |
+
occupied = np.zeros(bins, dtype=int)
|
| 228 |
+
for i, v in enumerate(path):
|
| 229 |
+
if v<0:
|
| 230 |
+
return False
|
| 231 |
+
occupied[v] += self.demand[i]
|
| 232 |
+
if occupied[v] > self.capacity:
|
| 233 |
+
return False
|
| 234 |
+
return True
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# =====Evaluation function=====
|
| 238 |
+
N_ITERATIONS = 15
|
| 239 |
+
N_ANTS = 20
|
| 240 |
+
SAMPLE_COUNT = 200
|
| 241 |
+
|
| 242 |
+
def evaluate_heuristic(inst: BPPInstance, mode = 'sample'):
|
| 243 |
+
heu = heuristics(inst.demands.copy(), inst.capacity) # normalized in ACO
|
| 244 |
+
assert tuple(heu.shape) == (inst.n, inst.n)
|
| 245 |
+
assert 0 < heu.max() < np.inf
|
| 246 |
+
aco = ACO(inst.demands, heu.astype(float), capacity = inst.capacity, n_ants=N_ANTS, greedy=False)
|
| 247 |
+
if mode == 'sample':
|
| 248 |
+
obj, _ = aco.sample_only(SAMPLE_COUNT)
|
| 249 |
+
else:
|
| 250 |
+
obj, _ = aco.run(N_ITERATIONS)
|
| 251 |
+
return obj
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
# =====Helper functions=====
|
| 255 |
+
def get_feature(metrics: Dict[int, float]) -> Tuple[int, ...]:
|
| 256 |
+
"""
|
| 257 |
+
Convert the metrics dict to a feature vector
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 261 |
+
|
| 262 |
+
Returns:
|
| 263 |
+
(tuple): a tuple of discretized scores sorted by problem size
|
| 264 |
+
"""
|
| 265 |
+
scores = metrics.values()
|
| 266 |
+
features = tuple([int(x) for x in scores])
|
| 267 |
+
return features
|
| 268 |
+
|
| 269 |
+
def get_score(metrics: Dict[int, float]) -> float:
|
| 270 |
+
"""
|
| 271 |
+
Convert the metrics dict to a score
|
| 272 |
+
|
| 273 |
+
Args:
|
| 274 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 275 |
+
|
| 276 |
+
Returns:
|
| 277 |
+
(float): a score
|
| 278 |
+
"""
|
| 279 |
+
return sum(metrics.values()) / len(metrics)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
# =====Main function=====
|
| 283 |
+
if __name__ == "__main__":
|
| 284 |
+
# -----Parse command line arguments (same for all problems)-----
|
| 285 |
+
parser = argparse.ArgumentParser(description='Evaluation script.')
|
| 286 |
+
parser.add_argument(
|
| 287 |
+
'--root_dir',
|
| 288 |
+
type=str,
|
| 289 |
+
default=os.getcwd(),
|
| 290 |
+
help='Project root directory for loading data (default: current working directory)'
|
| 291 |
+
)
|
| 292 |
+
parser.add_argument(
|
| 293 |
+
'--file_output_prefix',
|
| 294 |
+
type=str,
|
| 295 |
+
default='',
|
| 296 |
+
help='Output file prefix for saving evaluation results. '
|
| 297 |
+
'Absolute path recommended. Files saved as {prefix}filename '
|
| 298 |
+
'(default: empty string, saves to current directory)')
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
'--mode',
|
| 301 |
+
type=str,
|
| 302 |
+
default='val',
|
| 303 |
+
choices=['train', 'val'],
|
| 304 |
+
help='Execution mode: train or val (default: val)'
|
| 305 |
+
)
|
| 306 |
+
parser.add_argument(
|
| 307 |
+
'--problem_size',
|
| 308 |
+
type=int,
|
| 309 |
+
default=50, # Customize this to your needs
|
| 310 |
+
help='Problem size parameter'
|
| 311 |
+
)
|
| 312 |
+
# Parse arguments
|
| 313 |
+
args = parser.parse_args()
|
| 314 |
+
root_dir = args.root_dir
|
| 315 |
+
file_output_prefix = args.file_output_prefix
|
| 316 |
+
mode = args.mode
|
| 317 |
+
problem_size = args.problem_size
|
| 318 |
+
method = 'aco'
|
| 319 |
+
# Print parsed arguments for verification
|
| 320 |
+
print(f"root_dir: {root_dir}")
|
| 321 |
+
print(f"file_output_prefix: {file_output_prefix}")
|
| 322 |
+
print(f"mode: {mode}")
|
| 323 |
+
#print(f"problem_size: {problem_size}")
|
| 324 |
+
|
| 325 |
+
# -----Run the evaluation-----
|
| 326 |
+
# Run two instances: 120, 500; execution time: 125s
|
| 327 |
+
try:
|
| 328 |
+
basepath = os.path.join(root_dir, "problems", problem)
|
| 329 |
+
|
| 330 |
+
if not os.path.isfile(os.path.join(basepath, f"dataset/train{dataset_conf['train'][0]}_dataset.npz")):
|
| 331 |
+
raise ValueError("Dataset does not exist. Please generate it first.")
|
| 332 |
+
|
| 333 |
+
if mode == 'train':
|
| 334 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npz")
|
| 335 |
+
dataset = load_dataset(dataset_path)
|
| 336 |
+
n_instances = len(dataset)
|
| 337 |
+
|
| 338 |
+
print(f"[*] Dataset loaded: {dataset_path} with {n_instances} instances.")
|
| 339 |
+
|
| 340 |
+
objs = []
|
| 341 |
+
for i, instance in enumerate(dataset):
|
| 342 |
+
obj = evaluate_heuristic(instance, mode=method)
|
| 343 |
+
print(f"[*] Instance {i}: {obj}")
|
| 344 |
+
objs.append(obj)
|
| 345 |
+
|
| 346 |
+
print("[*] Average:")
|
| 347 |
+
print(np.mean(objs))
|
| 348 |
+
|
| 349 |
+
else: # mood == 'val'
|
| 350 |
+
metrics = {}
|
| 351 |
+
for problem_size in dataset_conf['val']:
|
| 352 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npz")
|
| 353 |
+
dataset = load_dataset(dataset_path)
|
| 354 |
+
n_instances = dataset[0].n
|
| 355 |
+
print(f"[*] Evaluating {dataset_path}")
|
| 356 |
+
|
| 357 |
+
objs = []
|
| 358 |
+
for i, instance in enumerate(dataset):
|
| 359 |
+
obj = evaluate_heuristic(instance, mode=method)
|
| 360 |
+
objs.append(obj)
|
| 361 |
+
|
| 362 |
+
print(f"[*] Average for problem size {problem_size}: {np.mean(objs)}")
|
| 363 |
+
metrics[problem_size] = float(np.mean(objs))
|
| 364 |
+
|
| 365 |
+
if metrics:
|
| 366 |
+
features = get_feature(metrics)
|
| 367 |
+
score = get_score(metrics)
|
| 368 |
+
else:
|
| 369 |
+
features = None
|
| 370 |
+
score = None
|
| 371 |
+
|
| 372 |
+
# -----Print results to stdout (same for all problems)-----
|
| 373 |
+
print('__SANDBOX_RESULT__')
|
| 374 |
+
print('__METRICS_START__')
|
| 375 |
+
print(repr(metrics))
|
| 376 |
+
print('__METRICS_END__')
|
| 377 |
+
|
| 378 |
+
print('__FEATURES_START__')
|
| 379 |
+
print(repr(features))
|
| 380 |
+
print('__FEATURES_END__')
|
| 381 |
+
|
| 382 |
+
print('__SCORE_START__')
|
| 383 |
+
print(repr(score))
|
| 384 |
+
print('__SCORE_END__')
|
| 385 |
+
|
| 386 |
+
print('__SANDBOX_SUCCESS__')
|
| 387 |
+
|
| 388 |
+
except Exception as e:
|
| 389 |
+
print('__SANDBOX_ERROR__:')
|
| 390 |
+
print(f'Error type: {type(e).__name__}')
|
| 391 |
+
print(f'Error message: {str(e)}')
|
| 392 |
+
print('Full traceback:')
|
| 393 |
+
traceback.print_exc()
|
bpp_offline_aco/evaluation_description.txt
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The evaluation script for the problem is described below.
|
| 2 |
+
|
| 3 |
+
```python
|
| 4 |
+
# Evaluation script for BPP-Offline-ACO problem
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
from math import floor
|
| 9 |
+
import argparse
|
| 10 |
+
from typing import NamedTuple, Tuple, List, Annotated, Dict, Any
|
| 11 |
+
import numpy as np
|
| 12 |
+
import numpy.typing as npt
|
| 13 |
+
import seed_solution as solution_module # Note: solution module script is generated and saved on the fly
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# =====Load function to evolve=====
|
| 17 |
+
problem = "bpp_offline_aco"
|
| 18 |
+
heuristics = getattr(solution_module, "heuristics") # Get function to evolve
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# =====Configuration and Parameters=====
|
| 22 |
+
IntArray = npt.NDArray[np.int_]
|
| 23 |
+
FloatArray = npt.NDArray[np.float_]
|
| 24 |
+
|
| 25 |
+
class BPPInstance(NamedTuple):
|
| 26 |
+
n: int
|
| 27 |
+
capacity: int
|
| 28 |
+
demands: npt.NDArray[np.int_]
|
| 29 |
+
|
| 30 |
+
DEMAND_LOW = 20
|
| 31 |
+
DEMAND_HIGH = 100
|
| 32 |
+
CAPACITY = 150
|
| 33 |
+
|
| 34 |
+
dataset_conf = {
|
| 35 |
+
'train': (500,),
|
| 36 |
+
'val': (120, 500), # 120, 500, 1000
|
| 37 |
+
'test': (120, 500), # 120, 500, 1000
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# =====Utility Functions=====
|
| 42 |
+
def load_dataset(fp) -> list[BPPInstance]:
|
| 43 |
+
data = np.load(fp)
|
| 44 |
+
demands = data['demands']
|
| 45 |
+
instances = []
|
| 46 |
+
n = demands.shape[1]
|
| 47 |
+
for demand in demands:
|
| 48 |
+
instance = BPPInstance(n, CAPACITY, demand)
|
| 49 |
+
instances.append(instance)
|
| 50 |
+
return instances
|
| 51 |
+
|
| 52 |
+
def organize_path(path: IntArray) -> Tuple[int, IntArray]:
|
| 53 |
+
order = {}
|
| 54 |
+
result = np.zeros_like(path)
|
| 55 |
+
for i, v in enumerate(path):
|
| 56 |
+
if v in order:
|
| 57 |
+
result[i] = order[v]
|
| 58 |
+
else:
|
| 59 |
+
result[i] = order[v] = len(order)
|
| 60 |
+
return len(order), result
|
| 61 |
+
|
| 62 |
+
def calculate_path_cost_fitness(vacancies: IntArray, capacity: int) -> Tuple[int, float]:
|
| 63 |
+
occupied = (capacity - vacancies[vacancies!=capacity]).astype(float)
|
| 64 |
+
cost = len(occupied)
|
| 65 |
+
result = ((occupied/capacity)**2).sum().item()/cost
|
| 66 |
+
return cost, result
|
| 67 |
+
|
| 68 |
+
def calculate_path_fitness(vacancies: List[int], capacity: int) -> float:
|
| 69 |
+
occupied = capacity - np.array(vacancies, dtype=float)
|
| 70 |
+
result = ((occupied/capacity)**2).sum().item()/len(vacancies)
|
| 71 |
+
return result
|
| 72 |
+
|
| 73 |
+
def greedy_sample(prob: FloatArray) -> int:
|
| 74 |
+
return prob.argmax().item()
|
| 75 |
+
|
| 76 |
+
def random_sample(prob: FloatArray) -> int:
|
| 77 |
+
# not used, `random_sample_discrete_distribution` is a faster implementation
|
| 78 |
+
sampled = np.random.choice(prob.size, p=prob/prob.sum())
|
| 79 |
+
return sampled
|
| 80 |
+
|
| 81 |
+
def random_sample_discrete_distribution(prob: FloatArray) -> int:
|
| 82 |
+
# prob_exp = np.exp(prob-prob.max())
|
| 83 |
+
# prob_exp[prob==0] = 0
|
| 84 |
+
# np.random.choice is somehow slow
|
| 85 |
+
cumprob = np.cumsum(prob)
|
| 86 |
+
sampled = np.searchsorted(cumprob, next(uniform_generator)*cumprob[-1]).item()
|
| 87 |
+
return sampled if sampled<len(cumprob) else len(cumprob)-1
|
| 88 |
+
|
| 89 |
+
def uniform_number_generator(batch_size = 500):
|
| 90 |
+
# it's also slow to generate random numbers one by one
|
| 91 |
+
while 1:
|
| 92 |
+
numbers = np.random.random(batch_size)
|
| 93 |
+
for n in numbers:
|
| 94 |
+
yield n.item()
|
| 95 |
+
|
| 96 |
+
uniform_generator = uniform_number_generator()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# =====ACO class=====
|
| 100 |
+
class ACO(object):
|
| 101 |
+
def __init__(self,
|
| 102 |
+
demand: IntArray, # (n, )
|
| 103 |
+
heuristic: FloatArray, # (n, n)
|
| 104 |
+
capacity: int,
|
| 105 |
+
n_ants=20,
|
| 106 |
+
decay=0.95,
|
| 107 |
+
alpha=1,
|
| 108 |
+
beta=1,
|
| 109 |
+
greedy = False
|
| 110 |
+
):
|
| 111 |
+
|
| 112 |
+
self.problem_size = len(demand)
|
| 113 |
+
self.capacity = capacity
|
| 114 |
+
self.demand = demand
|
| 115 |
+
assert self.demand.max() <= self.capacity
|
| 116 |
+
|
| 117 |
+
self.n_ants = n_ants
|
| 118 |
+
self.decay = decay
|
| 119 |
+
self.alpha = alpha
|
| 120 |
+
self.beta = beta
|
| 121 |
+
|
| 122 |
+
self.pheromone: FloatArray = np.ones((self.problem_size, self.problem_size)) # problem_size x self.problem_size
|
| 123 |
+
heuristic[heuristic > 1e6] = 1e6
|
| 124 |
+
heuristic[heuristic < 1e-6] = 1e-6
|
| 125 |
+
heuristic = heuristic/heuristic.max() # normalize
|
| 126 |
+
heuristic[heuristic < 1e-6] = 1e-6
|
| 127 |
+
self.heuristic: FloatArray = heuristic # problem_size x self.problem_size
|
| 128 |
+
|
| 129 |
+
self.shortest_path: IntArray = np.arange(self.problem_size)
|
| 130 |
+
self.best_cost = self.problem_size
|
| 131 |
+
|
| 132 |
+
self._ordinal: IntArray = np.arange(self.problem_size, dtype=int) # for indexing
|
| 133 |
+
self.greedy_mode = greedy
|
| 134 |
+
|
| 135 |
+
def run(self, iterations: int) -> Tuple[int, IntArray]:
|
| 136 |
+
for _ in range(iterations):
|
| 137 |
+
prob = self.pheromone**self.alpha * self.heuristic**self.beta
|
| 138 |
+
paths, costs, fitnesses = self.gen_paths(self.n_ants, prob)
|
| 139 |
+
best_index = costs.argmin()
|
| 140 |
+
best_cost = costs[best_index].item()
|
| 141 |
+
if best_cost < self.best_cost:
|
| 142 |
+
self.shortest_path = paths[best_index]
|
| 143 |
+
self.best_cost = best_cost
|
| 144 |
+
self.update_pheronome(paths, fitnesses)
|
| 145 |
+
assert self.is_valid_path(self.shortest_path)
|
| 146 |
+
# cost, path = organize_path(self.shortest_path)
|
| 147 |
+
# assert cost >= np.ceil(np.sum(self.demand).astype(float)/self.capacity).item()
|
| 148 |
+
return organize_path(self.shortest_path)
|
| 149 |
+
|
| 150 |
+
def sample_only(self, count: int) -> Tuple[int, IntArray]:
|
| 151 |
+
self.greedy_mode = True
|
| 152 |
+
paths, costs, _ = self.gen_paths(count, self.heuristic)
|
| 153 |
+
best_index = costs.argmin()
|
| 154 |
+
best_path = paths[best_index]
|
| 155 |
+
assert self.is_valid_path(best_path)
|
| 156 |
+
return organize_path(best_path)
|
| 157 |
+
|
| 158 |
+
def update_pheronome(self, paths: List[IntArray], fitnesses: FloatArray):
|
| 159 |
+
delta_phe = np.zeros_like(self.pheromone) # problem_size x problem_size
|
| 160 |
+
for path, f in zip(paths, fitnesses):
|
| 161 |
+
delta_phe[path[:, None]==path[None, :]] += f / self.n_ants
|
| 162 |
+
self.pheromone *= self.decay
|
| 163 |
+
self.pheromone += delta_phe
|
| 164 |
+
|
| 165 |
+
def gen_paths(self, count: int, prob: FloatArray) -> Tuple[List[IntArray], IntArray, FloatArray]:
|
| 166 |
+
paths, costs, fitnesses = [], [], []
|
| 167 |
+
for _ in range(count):
|
| 168 |
+
path, cost, fitness = self.sample_path(prob)
|
| 169 |
+
paths.append(path)
|
| 170 |
+
costs.append(cost)
|
| 171 |
+
fitnesses.append(fitness)
|
| 172 |
+
return paths, np.array(costs, dtype=int), np.array(fitnesses, dtype=float)
|
| 173 |
+
|
| 174 |
+
def sample_path(self, prob: FloatArray
|
| 175 |
+
) -> Tuple[
|
| 176 |
+
Annotated[IntArray, "sampled path"],
|
| 177 |
+
Annotated[int, "used bins"],
|
| 178 |
+
Annotated[float, "fitness"]]:
|
| 179 |
+
|
| 180 |
+
if self.greedy_mode:
|
| 181 |
+
sample_func = greedy_sample
|
| 182 |
+
else:
|
| 183 |
+
sample_func = random_sample_discrete_distribution
|
| 184 |
+
|
| 185 |
+
path = np.ones(self.problem_size, dtype=int)*-1 # x=path[i] => put item i in bin x
|
| 186 |
+
valid_items = np.ones(self.problem_size, dtype=bool)
|
| 187 |
+
current_bin = item_count = 0
|
| 188 |
+
vacancies = []
|
| 189 |
+
bin_vacancy = self.capacity
|
| 190 |
+
bin_items = np.zeros_like(valid_items)
|
| 191 |
+
|
| 192 |
+
for _ in range(self.problem_size):
|
| 193 |
+
mask = np.bitwise_and(self.demand <= bin_vacancy, valid_items)
|
| 194 |
+
if not np.any(mask): # no valid item
|
| 195 |
+
# move to the next bin
|
| 196 |
+
vacancies.append(bin_vacancy)
|
| 197 |
+
bin_vacancy, item_count = self.capacity, 0
|
| 198 |
+
current_bin += 1
|
| 199 |
+
bin_items[:] = False
|
| 200 |
+
# uniformly select one
|
| 201 |
+
selected = self.random_select(valid_items)
|
| 202 |
+
else:
|
| 203 |
+
if item_count == 0:
|
| 204 |
+
selected = self.random_select(mask)
|
| 205 |
+
else:
|
| 206 |
+
item_prob = (prob[bin_items].sum(0)/item_count+1e-5) * mask
|
| 207 |
+
selected = sample_func(item_prob)
|
| 208 |
+
|
| 209 |
+
# put item in this bin
|
| 210 |
+
bin_items[selected] = True
|
| 211 |
+
bin_vacancy -= self.demand[selected]
|
| 212 |
+
valid_items[selected] = False
|
| 213 |
+
path[selected] = current_bin
|
| 214 |
+
item_count += 1
|
| 215 |
+
|
| 216 |
+
vacancies.append(bin_vacancy)
|
| 217 |
+
fitness = calculate_path_fitness(vacancies, self.capacity)
|
| 218 |
+
return path, len(vacancies), fitness
|
| 219 |
+
|
| 220 |
+
def random_select(self, mask: npt.NDArray[np.bool_]) -> int:
|
| 221 |
+
valid = self._ordinal[mask]
|
| 222 |
+
return valid[floor(next(uniform_generator)*len(valid))].item()
|
| 223 |
+
# return valid[np.random.randint(0, len(valid))].item()
|
| 224 |
+
|
| 225 |
+
def is_valid_path(self, path: IntArray) -> bool:
|
| 226 |
+
# not used
|
| 227 |
+
if path.shape[0] != self.problem_size:
|
| 228 |
+
return False
|
| 229 |
+
bins, path = organize_path(path)
|
| 230 |
+
occupied = np.zeros(bins, dtype=int)
|
| 231 |
+
for i, v in enumerate(path):
|
| 232 |
+
if v<0:
|
| 233 |
+
return False
|
| 234 |
+
occupied[v] += self.demand[i]
|
| 235 |
+
if occupied[v] > self.capacity:
|
| 236 |
+
return False
|
| 237 |
+
return True
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# =====Evaluation function=====
|
| 241 |
+
N_ITERATIONS = 15
|
| 242 |
+
N_ANTS = 20
|
| 243 |
+
SAMPLE_COUNT = 200
|
| 244 |
+
|
| 245 |
+
def evaluate_heuristic(inst: BPPInstance, mode = 'sample'):
|
| 246 |
+
heu = heuristics(inst.demands.copy(), inst.capacity) # normalized in ACO
|
| 247 |
+
assert tuple(heu.shape) == (inst.n, inst.n)
|
| 248 |
+
assert 0 < heu.max() < np.inf
|
| 249 |
+
aco = ACO(inst.demands, heu.astype(float), capacity = inst.capacity, n_ants=N_ANTS, greedy=False)
|
| 250 |
+
if mode == 'sample':
|
| 251 |
+
obj, _ = aco.sample_only(SAMPLE_COUNT)
|
| 252 |
+
else:
|
| 253 |
+
obj, _ = aco.run(N_ITERATIONS)
|
| 254 |
+
return obj
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# =====Helper functions=====
|
| 258 |
+
def get_feature(metrics: Dict[int, float]) -> Tuple[int, ...]:
|
| 259 |
+
"""
|
| 260 |
+
Convert the metrics dict to a feature vector
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 264 |
+
|
| 265 |
+
Returns:
|
| 266 |
+
(tuple): a tuple of discretized scores sorted by problem size
|
| 267 |
+
"""
|
| 268 |
+
scores = metrics.values()
|
| 269 |
+
features = tuple([int(x) for x in scores])
|
| 270 |
+
return features
|
| 271 |
+
|
| 272 |
+
def get_score(metrics: Dict[int, float]) -> float:
|
| 273 |
+
"""
|
| 274 |
+
Convert the metrics dict to a score
|
| 275 |
+
|
| 276 |
+
Args:
|
| 277 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
(float): a score
|
| 281 |
+
"""
|
| 282 |
+
return sum(metrics.values()) / len(metrics)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# =====Main function=====
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
# -----Parse command line arguments (same for all problems)-----
|
| 288 |
+
parser = argparse.ArgumentParser(description='Evaluation script.')
|
| 289 |
+
parser.add_argument(
|
| 290 |
+
'--root_dir',
|
| 291 |
+
type=str,
|
| 292 |
+
default=os.getcwd(),
|
| 293 |
+
help='Project root directory for loading data (default: current working directory)'
|
| 294 |
+
)
|
| 295 |
+
parser.add_argument(
|
| 296 |
+
'--file_output_prefix',
|
| 297 |
+
type=str,
|
| 298 |
+
default='',
|
| 299 |
+
help='Output file prefix for saving evaluation results. '
|
| 300 |
+
'Absolute path recommended. Files saved as {prefix}filename '
|
| 301 |
+
'(default: empty string, saves to current directory)')
|
| 302 |
+
parser.add_argument(
|
| 303 |
+
'--mode',
|
| 304 |
+
type=str,
|
| 305 |
+
default='val',
|
| 306 |
+
choices=['train', 'val'],
|
| 307 |
+
help='Execution mode: train or val (default: val)'
|
| 308 |
+
)
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
'--problem_size',
|
| 311 |
+
type=int,
|
| 312 |
+
default=50, # Customize this to your needs
|
| 313 |
+
help='Problem size parameter'
|
| 314 |
+
)
|
| 315 |
+
# Parse arguments
|
| 316 |
+
args = parser.parse_args()
|
| 317 |
+
root_dir = args.root_dir
|
| 318 |
+
file_output_prefix = args.file_output_prefix
|
| 319 |
+
mode = args.mode
|
| 320 |
+
problem_size = args.problem_size
|
| 321 |
+
method = 'aco'
|
| 322 |
+
# Print parsed arguments for verification
|
| 323 |
+
print(f"root_dir: {root_dir}")
|
| 324 |
+
print(f"file_output_prefix: {file_output_prefix}")
|
| 325 |
+
print(f"mode: {mode}")
|
| 326 |
+
#print(f"problem_size: {problem_size}")
|
| 327 |
+
|
| 328 |
+
# -----Run the evaluation-----
|
| 329 |
+
# Run two instances: 120, 500; execution time: 125s
|
| 330 |
+
try:
|
| 331 |
+
basepath = os.path.join(root_dir, "problems", problem)
|
| 332 |
+
|
| 333 |
+
if not os.path.isfile(os.path.join(basepath, f"dataset/train{dataset_conf['train'][0]}_dataset.npz")):
|
| 334 |
+
raise ValueError("Dataset does not exist. Please generate it first.")
|
| 335 |
+
|
| 336 |
+
if mode == 'train':
|
| 337 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npz")
|
| 338 |
+
dataset = load_dataset(dataset_path)
|
| 339 |
+
n_instances = len(dataset)
|
| 340 |
+
|
| 341 |
+
print(f"[*] Dataset loaded: {dataset_path} with {n_instances} instances.")
|
| 342 |
+
|
| 343 |
+
objs = []
|
| 344 |
+
for i, instance in enumerate(dataset):
|
| 345 |
+
obj = evaluate_heuristic(instance, mode=method)
|
| 346 |
+
print(f"[*] Instance {i}: {obj}")
|
| 347 |
+
objs.append(obj)
|
| 348 |
+
|
| 349 |
+
print("[*] Average:")
|
| 350 |
+
print(np.mean(objs))
|
| 351 |
+
|
| 352 |
+
else: # mood == 'val'
|
| 353 |
+
metrics = {}
|
| 354 |
+
for problem_size in dataset_conf['val']:
|
| 355 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npz")
|
| 356 |
+
dataset = load_dataset(dataset_path)
|
| 357 |
+
n_instances = dataset[0].n
|
| 358 |
+
print(f"[*] Evaluating {dataset_path}")
|
| 359 |
+
|
| 360 |
+
objs = []
|
| 361 |
+
for i, instance in enumerate(dataset):
|
| 362 |
+
obj = evaluate_heuristic(instance, mode=method)
|
| 363 |
+
objs.append(obj)
|
| 364 |
+
|
| 365 |
+
print(f"[*] Average for {problem_size}: {np.mean(objs)}")
|
| 366 |
+
metrics[problem_size] = np.mean(objs)
|
| 367 |
+
|
| 368 |
+
if metrics:
|
| 369 |
+
features = get_feature(metrics)
|
| 370 |
+
score = get_score(metrics)
|
| 371 |
+
else:
|
| 372 |
+
features = None
|
| 373 |
+
score = None
|
| 374 |
+
|
| 375 |
+
# -----Print results to stdout (same for all problems)-----
|
| 376 |
+
print('__SANDBOX_RESULT__')
|
| 377 |
+
print('__METRICS_START__')
|
| 378 |
+
print(repr(metrics))
|
| 379 |
+
print('__METRICS_END__')
|
| 380 |
+
|
| 381 |
+
print('__FEATURES_START__')
|
| 382 |
+
print(repr(features))
|
| 383 |
+
print('__FEATURES_END__')
|
| 384 |
+
|
| 385 |
+
print('__SCORE_START__')
|
| 386 |
+
print(repr(score))
|
| 387 |
+
print('__SCORE_END__')
|
| 388 |
+
|
| 389 |
+
print('__SANDBOX_SUCCESS__')
|
| 390 |
+
|
| 391 |
+
except Exception as e:
|
| 392 |
+
print('__SANDBOX_ERROR__:')
|
| 393 |
+
print(f'Error type: {type(e).__name__}')
|
| 394 |
+
print(f'Error message: {str(e)}')
|
| 395 |
+
print('Full traceback:')
|
| 396 |
+
traceback.print_exc()
|
| 397 |
+
```
|
bpp_offline_aco/external_knowledge.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
- Try combining various factors to determine how promising it is to select an edge.
|
| 2 |
+
- Try sparsifying the matrix by setting unpromising elements to zero.
|
bpp_offline_aco/function_description.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Suppose `n` represents the number of items in the problem. The heuristics function takes as input a `demand` array of shape (n,) and an integer as the capacity of every bin, and it returns a `heuristics` array of shape (n,n).
|
| 2 |
+
`heuristics[i][j]` indicates how promising it is to put item i and item j in the same bin.
|
| 3 |
+
|
| 4 |
+
### Solution Function Signature:
|
| 5 |
+
```python
|
| 6 |
+
def heuristics(demand: np.ndarray, capacity: int) -> np.ndarray:
|
| 7 |
+
```
|
bpp_offline_aco/generate_dataset.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple
|
| 2 |
+
import numpy as np
|
| 3 |
+
import numpy.typing as npt
|
| 4 |
+
|
| 5 |
+
class BPPInstance(NamedTuple):
|
| 6 |
+
n: int
|
| 7 |
+
capacity: int
|
| 8 |
+
demands: npt.NDArray[np.int_]
|
| 9 |
+
|
| 10 |
+
# Emanuel Falkenauer. A hybrid grouping genetic algorithm for bin packing. Journal of Heuristics,2:5–30, 1996.
|
| 11 |
+
|
| 12 |
+
DEMAND_LOW = 20
|
| 13 |
+
DEMAND_HIGH = 100
|
| 14 |
+
CAPACITY = 150
|
| 15 |
+
dataset_conf = {
|
| 16 |
+
'train': (500,),
|
| 17 |
+
'val': (120, 500, 1000),
|
| 18 |
+
'test': (120, 500, 1000),
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
def generate_dataset(filepath, n, batch_size=64):
|
| 22 |
+
demands = np.random.randint(low=DEMAND_LOW, high=DEMAND_HIGH+1, size=(batch_size, n))
|
| 23 |
+
np.savez(filepath, demands = demands)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def generate_datasets(basepath = None):
|
| 27 |
+
import os
|
| 28 |
+
basepath = basepath or os.path.join(os.path.dirname(__file__), "dataset")
|
| 29 |
+
os.makedirs(basepath, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
for mood, problem_sizes in dataset_conf.items():
|
| 32 |
+
np.random.seed(len(mood))
|
| 33 |
+
for n in problem_sizes:
|
| 34 |
+
filepath = os.path.join(basepath, f"{mood}{n}_dataset.npz")
|
| 35 |
+
generate_dataset(filepath, n, batch_size=5 if mood =='train' else 64)
|
| 36 |
+
|
| 37 |
+
def load_dataset(fp) -> list[BPPInstance]:
|
| 38 |
+
data = np.load(fp)
|
| 39 |
+
demands = data['demands']
|
| 40 |
+
instances = []
|
| 41 |
+
n = demands.shape[1]
|
| 42 |
+
for demand in demands:
|
| 43 |
+
instance = BPPInstance(n, CAPACITY, demand)
|
| 44 |
+
instances.append(instance)
|
| 45 |
+
return instances
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
generate_datasets()
|
bpp_offline_aco/problem_description.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The Bin Packing Problem (BPP) is a combinatorial optimization challenge where items of varying sizes must be packed into bins of fixed capacity, minimizing the number of bins used while respecting capacity constraints.
|
| 2 |
+
In the offline version, all item sizes are known in advance, allowing for more sophisticated packing strategies.
|
| 3 |
+
We use Ant Colony Optimization (ACO) to solve this problem, where artificial ants probabilistically construct packing solutions guided by pheromone trails and heuristic information.
|
| 4 |
+
Each ant builds a solution by sequentially assigning items to bins based on a probability distribution that combines pheromone intensity and heuristic desirability.
|
| 5 |
+
Your task is to evolve a `heuristics` function that generates an n×n heuristic matrix to guide ant movement, where n is the number of items.
|
| 6 |
+
The goal of minimizing the average number of bins used across all instances (called "score" or "objective" of solution).
|
bpp_offline_aco/seed_solution.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
def heuristics(demand: np.ndarray, capacity: int) -> np.ndarray:
|
| 4 |
+
return np.tile(demand/demand.max(), (demand.shape[0], 1))
|
bpp_offline_aco/seed_solution_idea.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
This simple heuristic prioritizes larger items by giving them higher heuristic values, encouraging ants to pack larger items together first.
|
bpp_offline_aco/settings.yaml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"function_to_evolve": "heuristics"
|
| 2 |
+
"obj_type": "min"
|
bpp_online/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
bpp_online/dataset/weibull_100k_test.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:22018e0ffa54cd405e0bd6102fe687b3d716802ee4785fca5613337937c2f485
|
| 3 |
+
size 800292
|
bpp_online/dataset/weibull_10k_test.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0393be2ce402cfca3a7a56b5e791c0c0e6af5bb5293401e8b5d9322d96b65601
|
| 3 |
+
size 400556
|
bpp_online/dataset/weibull_5k_test.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e5df0be286b0bcbc6a680fb875490b651d49bcac4b31e4c3ef7b1349d31ab028
|
| 3 |
+
size 200529
|
bpp_online/dataset/weibull_5k_train.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:50ce65b6c06d940a746f200482e158d25e86ba5760cadfbae677c27596a8f0f2
|
| 3 |
+
size 200534
|
bpp_online/dataset/weibull_5k_val.pickle
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c3374f60053947b3424ec64fa799eca2de03edd8dae103e4e1c2ab97f2b28b02
|
| 3 |
+
size 200524
|
bpp_online/eval.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation script for online binpacking problem.
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import traceback
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pickle
|
| 7 |
+
import argparse
|
| 8 |
+
from typing import Dict, Tuple, List, Any
|
| 9 |
+
import seed_solution as solution_module # Note: solution module script is generated and saved on the fly
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# =====Load function to evolve=====
|
| 13 |
+
problem = "bpp_online"
|
| 14 |
+
priority = getattr(solution_module, "priority") # Get function to evolve
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# =====Binpacking functions=====
|
| 18 |
+
def get_valid_bin_indices(item: float, bins: np.ndarray) -> np.ndarray:
|
| 19 |
+
"""
|
| 20 |
+
Returns indices of bins that have sufficient capacity for a given item.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
item: Size of the item to place (float)
|
| 24 |
+
bins: NumPy array of remaining bin capacities (float array)
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
NumPy array of indices where bins have capacity >= item size
|
| 28 |
+
"""
|
| 29 |
+
return np.nonzero((bins - item) >= 0)[0]
|
| 30 |
+
|
| 31 |
+
def online_binpack(items: tuple[float], bins: np.ndarray) -> tuple[list[list[float]], np.ndarray]:
|
| 32 |
+
"""
|
| 33 |
+
Performs online bin-packing of items into bins using a priority heuristic.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
items: Tuple of item sizes to pack (float values)
|
| 37 |
+
bins: NumPy array of initial bin capacities (float array)
|
| 38 |
+
|
| 39 |
+
Returns:
|
| 40 |
+
Tuple of (packing, remaining_capacities):
|
| 41 |
+
- packing: List of lists, where each inner list contains items in a bin
|
| 42 |
+
- remaining_capacities: Updated bin capacities after packing
|
| 43 |
+
"""
|
| 44 |
+
# Track which items are added to each bin.
|
| 45 |
+
packing = [[] for _ in bins]
|
| 46 |
+
# Add items to bins.
|
| 47 |
+
for item in items:
|
| 48 |
+
# Extract bins that have sufficient space to fit item.
|
| 49 |
+
valid_bin_indices = get_valid_bin_indices(item, bins)
|
| 50 |
+
# Score each bin based on heuristic.
|
| 51 |
+
priorities = priority(item, bins[valid_bin_indices])
|
| 52 |
+
# Add item to bin with highest priority.
|
| 53 |
+
best_bin = valid_bin_indices[np.argmax(priorities)]
|
| 54 |
+
bins[best_bin] -= item
|
| 55 |
+
packing[best_bin].append(item)
|
| 56 |
+
# Remove unused bins from packing.
|
| 57 |
+
packing = [bin_items for bin_items in packing if bin_items]
|
| 58 |
+
return packing, bins
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ======Evaluation function=====
|
| 62 |
+
def get_feature(metrics: Dict[int, float]) -> Tuple[int, ...]:
|
| 63 |
+
"""
|
| 64 |
+
Convert the metrics dict to a feature vector
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 68 |
+
|
| 69 |
+
Returns:
|
| 70 |
+
(tuple): a tuple of discretized scores sorted by problem size
|
| 71 |
+
"""
|
| 72 |
+
scores = metrics.values()
|
| 73 |
+
features = tuple([int(x) for x in scores])
|
| 74 |
+
return features
|
| 75 |
+
|
| 76 |
+
def evaluate(instances: dict) -> float:
|
| 77 |
+
"""Evaluate heuristic function on a set of online binpacking instances."""
|
| 78 |
+
# List storing number of bins used for each instance.
|
| 79 |
+
num_bins = []
|
| 80 |
+
metrics = {}
|
| 81 |
+
# Perform online binpacking for each instance.
|
| 82 |
+
for name in instances:
|
| 83 |
+
if name == 'l1_bound': # Skip l1_bound; l1_bound is a float that represents the L1 lower bound (best performance) for benchmarking
|
| 84 |
+
continue
|
| 85 |
+
instance = instances[name]
|
| 86 |
+
capacity = instance['capacity'] # Initial capacity of each bin; note: each bin has the same capacity
|
| 87 |
+
items = instance['items'] # Items to pack
|
| 88 |
+
items = np.array(items) if isinstance(items, list) else items # Convert to NumPy array
|
| 89 |
+
# Create num_items bins so there will always be space for all items,
|
| 90 |
+
# regardless of packing order. Array has shape (num_items,).
|
| 91 |
+
bins = np.array([capacity for _ in range(instance['num_items'])])
|
| 92 |
+
# Pack items into bins and return remaining capacity in bins_packed, which
|
| 93 |
+
# has shape (num_items,).
|
| 94 |
+
_, bins_packed = online_binpack(items.astype(float), bins)
|
| 95 |
+
# If remaining capacity in a bin is equal to initial capacity, then it is unused. Count number of used bins.
|
| 96 |
+
num_bins.append((bins_packed != capacity).sum())
|
| 97 |
+
metrics[name] = float(num_bins[-1])
|
| 98 |
+
# return negative of average number of bins used across instances (as we want to minimize number of bins).
|
| 99 |
+
return np.mean(num_bins), metrics
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# =======Main function=====
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
# -----Parse command line arguments (same for all problems)-----
|
| 105 |
+
parser = argparse.ArgumentParser(description='Evaluation script.')
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
'--root_dir',
|
| 108 |
+
type=str,
|
| 109 |
+
default=os.getcwd(),
|
| 110 |
+
help='Project root directory for loading data (default: current working directory)'
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
'--file_output_prefix',
|
| 114 |
+
type=str,
|
| 115 |
+
default='',
|
| 116 |
+
help='Output file prefix for saving evaluation results. '
|
| 117 |
+
'Absolute path recommended. Files saved as {prefix}filename '
|
| 118 |
+
'(default: empty string, saves to current directory)')
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
'--mode',
|
| 121 |
+
type=str,
|
| 122 |
+
default='val',
|
| 123 |
+
choices=['train', 'val'],
|
| 124 |
+
help='Execution mode: train or val (default: val)'
|
| 125 |
+
)
|
| 126 |
+
parser.add_argument(
|
| 127 |
+
'--problem_size',
|
| 128 |
+
type=int,
|
| 129 |
+
default=100, # Customize this to your needs
|
| 130 |
+
help='Problem size parameter'
|
| 131 |
+
)
|
| 132 |
+
# Parse arguments
|
| 133 |
+
args = parser.parse_args()
|
| 134 |
+
root_dir = args.root_dir
|
| 135 |
+
file_output_prefix = args.file_output_prefix
|
| 136 |
+
mode = args.mode
|
| 137 |
+
problem_size = args.problem_size
|
| 138 |
+
# Print parsed arguments for verification
|
| 139 |
+
print(f"root_dir: {root_dir}")
|
| 140 |
+
print(f"file_output_prefix: {file_output_prefix}")
|
| 141 |
+
print(f"mode: {mode}")
|
| 142 |
+
#print(f"problem_size: {problem_size}")
|
| 143 |
+
|
| 144 |
+
# -----Run the evaluation-----
|
| 145 |
+
# Execution time: 7s
|
| 146 |
+
try:
|
| 147 |
+
basepath = os.path.join(root_dir, "problems", problem)
|
| 148 |
+
file_name = f"weibull_5k_{mode}.pickle" # it contains multiple instances; each instance has 5000 items; bin capacity is 100
|
| 149 |
+
dataset_path = os.path.join(basepath, "dataset", file_name)
|
| 150 |
+
|
| 151 |
+
dataset = pickle.load(open(dataset_path, 'rb'))
|
| 152 |
+
|
| 153 |
+
# Evaluate heuristic function on dataset
|
| 154 |
+
avg_num_bins, metrics = evaluate(dataset)
|
| 155 |
+
l1_bound = dataset['l1_bound']
|
| 156 |
+
excess = (avg_num_bins - l1_bound) / l1_bound
|
| 157 |
+
print(file_name)
|
| 158 |
+
print(f'\t Average number of bins: {avg_num_bins}')
|
| 159 |
+
print(f'\t Lower bound on optimum: {l1_bound}')
|
| 160 |
+
print(f'\t Excess: {100 * excess:.2f}%')
|
| 161 |
+
|
| 162 |
+
print("[*] Average:")
|
| 163 |
+
print(excess * 100)
|
| 164 |
+
|
| 165 |
+
if metrics:
|
| 166 |
+
features = get_feature(metrics)
|
| 167 |
+
score = avg_num_bins
|
| 168 |
+
else:
|
| 169 |
+
features = None
|
| 170 |
+
score = None
|
| 171 |
+
|
| 172 |
+
# -----Print results to stdout (same for all problems)-----
|
| 173 |
+
print('__SANDBOX_RESULT__')
|
| 174 |
+
print('__METRICS_START__')
|
| 175 |
+
print(repr(metrics))
|
| 176 |
+
print('__METRICS_END__')
|
| 177 |
+
|
| 178 |
+
print('__FEATURES_START__')
|
| 179 |
+
print(repr(features))
|
| 180 |
+
print('__FEATURES_END__')
|
| 181 |
+
|
| 182 |
+
print('__SCORE_START__')
|
| 183 |
+
print(repr(score))
|
| 184 |
+
print('__SCORE_END__')
|
| 185 |
+
|
| 186 |
+
print('__SANDBOX_SUCCESS__')
|
| 187 |
+
|
| 188 |
+
except Exception as e:
|
| 189 |
+
print('__SANDBOX_ERROR__:')
|
| 190 |
+
print(f'Error type: {type(e).__name__}')
|
| 191 |
+
print(f'Error message: {str(e)}')
|
| 192 |
+
print('Full traceback:')
|
| 193 |
+
traceback.print_exc()
|
bpp_online/evaluation_description.txt
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The evaluation script for the problem is described below.
|
| 2 |
+
|
| 3 |
+
```python
|
| 4 |
+
# Evaluation script for online binpacking problem.
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pickle
|
| 10 |
+
import argparse
|
| 11 |
+
from typing import Dict, Tuple, List, Any
|
| 12 |
+
import seed_solution as solution_module # Note: solution module script is generated and saved on the fly
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# =====Load function to evolve=====
|
| 16 |
+
problem = "bpp_online"
|
| 17 |
+
priority = getattr(solution_module, "priority") # Get function to evolve
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# =====Binpacking functions=====
|
| 21 |
+
def get_valid_bin_indices(item: float, bins: np.ndarray) -> np.ndarray:
|
| 22 |
+
"""
|
| 23 |
+
Returns indices of bins that have sufficient capacity for a given item.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
item: Size of the item to place (float)
|
| 27 |
+
bins: NumPy array of remaining bin capacities (float array)
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
NumPy array of indices where bins have capacity >= item size
|
| 31 |
+
"""
|
| 32 |
+
return np.nonzero((bins - item) >= 0)[0]
|
| 33 |
+
|
| 34 |
+
def online_binpack(items: tuple[float], bins: np.ndarray) -> tuple[list[list[float]], np.ndarray]:
|
| 35 |
+
"""
|
| 36 |
+
Performs online bin-packing of items into bins using a priority heuristic.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
items: Tuple of item sizes to pack (float values)
|
| 40 |
+
bins: NumPy array of initial bin capacities (float array)
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
Tuple of (packing, remaining_capacities):
|
| 44 |
+
- packing: List of lists, where each inner list contains items in a bin
|
| 45 |
+
- remaining_capacities: Updated bin capacities after packing
|
| 46 |
+
"""
|
| 47 |
+
# Track which items are added to each bin.
|
| 48 |
+
packing = [[] for _ in bins]
|
| 49 |
+
# Add items to bins.
|
| 50 |
+
for item in items:
|
| 51 |
+
# Extract bins that have sufficient space to fit item.
|
| 52 |
+
valid_bin_indices = get_valid_bin_indices(item, bins)
|
| 53 |
+
# Score each bin based on heuristic.
|
| 54 |
+
priorities = priority(item, bins[valid_bin_indices])
|
| 55 |
+
# Add item to bin with highest priority.
|
| 56 |
+
best_bin = valid_bin_indices[np.argmax(priorities)]
|
| 57 |
+
bins[best_bin] -= item
|
| 58 |
+
packing[best_bin].append(item)
|
| 59 |
+
# Remove unused bins from packing.
|
| 60 |
+
packing = [bin_items for bin_items in packing if bin_items]
|
| 61 |
+
return packing, bins
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ======Evaluation function=====
|
| 65 |
+
def get_feature(metrics: Dict[int, float]) -> Tuple[int, ...]:
|
| 66 |
+
"""
|
| 67 |
+
Convert the metrics dict to a feature vector
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
(tuple): a tuple of discretized scores sorted by problem size
|
| 74 |
+
"""
|
| 75 |
+
scores = metrics.values()
|
| 76 |
+
features = tuple([int(x) for x in scores])
|
| 77 |
+
return features
|
| 78 |
+
|
| 79 |
+
def evaluate(instances: dict) -> float:
|
| 80 |
+
"""Evaluate heuristic function on a set of online binpacking instances."""
|
| 81 |
+
# List storing number of bins used for each instance.
|
| 82 |
+
num_bins = []
|
| 83 |
+
metrics = {}
|
| 84 |
+
# Perform online binpacking for each instance.
|
| 85 |
+
for name in instances:
|
| 86 |
+
if name == 'l1_bound': # Skip l1_bound; l1_bound is a float that represents the L1 lower bound (best performance) for benchmarking
|
| 87 |
+
continue
|
| 88 |
+
instance = instances[name]
|
| 89 |
+
capacity = instance['capacity'] # Initial capacity of each bin; note: each bin has the same capacity
|
| 90 |
+
items = instance['items'] # Items to pack
|
| 91 |
+
items = np.array(items) if isinstance(items, list) else items # Convert to NumPy array
|
| 92 |
+
# Create num_items bins so there will always be space for all items,
|
| 93 |
+
# regardless of packing order. Array has shape (num_items,).
|
| 94 |
+
bins = np.array([capacity for _ in range(instance['num_items'])])
|
| 95 |
+
# Pack items into bins and return remaining capacity in bins_packed, which
|
| 96 |
+
# has shape (num_items,).
|
| 97 |
+
_, bins_packed = online_binpack(items.astype(float), bins)
|
| 98 |
+
# If remaining capacity in a bin is equal to initial capacity, then it is unused. Count number of used bins.
|
| 99 |
+
num_bins.append((bins_packed != capacity).sum())
|
| 100 |
+
metrics[name] = num_bins[-1]
|
| 101 |
+
# return negative of average number of bins used across instances (as we want to minimize number of bins).
|
| 102 |
+
return np.mean(num_bins), metrics
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# =======Main function=====
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
# -----Parse command line arguments (same for all problems)-----
|
| 108 |
+
parser = argparse.ArgumentParser(description='Evaluation script.')
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
'--root_dir',
|
| 111 |
+
type=str,
|
| 112 |
+
default=os.getcwd(),
|
| 113 |
+
help='Project root directory for loading data (default: current working directory)'
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
'--file_output_prefix',
|
| 117 |
+
type=str,
|
| 118 |
+
default='',
|
| 119 |
+
help='Output file prefix for saving evaluation results. '
|
| 120 |
+
'Absolute path recommended. Files saved as {prefix}filename '
|
| 121 |
+
'(default: empty string, saves to current directory)')
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
'--mode',
|
| 124 |
+
type=str,
|
| 125 |
+
default='val',
|
| 126 |
+
choices=['train', 'val'],
|
| 127 |
+
help='Execution mode: train or val (default: val)'
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
'--problem_size',
|
| 131 |
+
type=int,
|
| 132 |
+
default=100, # Customize this to your needs
|
| 133 |
+
help='Problem size parameter'
|
| 134 |
+
)
|
| 135 |
+
# Parse arguments
|
| 136 |
+
args = parser.parse_args()
|
| 137 |
+
root_dir = args.root_dir
|
| 138 |
+
file_output_prefix = args.file_output_prefix
|
| 139 |
+
mode = args.mode
|
| 140 |
+
problem_size = args.problem_size
|
| 141 |
+
# Print parsed arguments for verification
|
| 142 |
+
print(f"root_dir: {root_dir}")
|
| 143 |
+
print(f"file_output_prefix: {file_output_prefix}")
|
| 144 |
+
print(f"mode: {mode}")
|
| 145 |
+
#print(f"problem_size: {problem_size}")
|
| 146 |
+
|
| 147 |
+
# -----Run the evaluation-----
|
| 148 |
+
# Execution time: 7s
|
| 149 |
+
try:
|
| 150 |
+
basepath = os.path.join(root_dir, "problems", problem)
|
| 151 |
+
file_name = f"weibull_5k_{mode}.pickle" # it contains multiple instances; each instance has 5000 items; bin capacity is 100
|
| 152 |
+
dataset_path = os.path.join(basepath, "dataset", file_name)
|
| 153 |
+
|
| 154 |
+
dataset = pickle.load(open(dataset_path, 'rb'))
|
| 155 |
+
|
| 156 |
+
# Evaluate heuristic function on dataset
|
| 157 |
+
avg_num_bins, metrics = evaluate(dataset)
|
| 158 |
+
l1_bound = dataset['l1_bound']
|
| 159 |
+
excess = (avg_num_bins - l1_bound) / l1_bound
|
| 160 |
+
print(file_name)
|
| 161 |
+
print(f'\t Average number of bins: {avg_num_bins}')
|
| 162 |
+
print(f'\t Lower bound on optimum: {l1_bound}')
|
| 163 |
+
print(f'\t Excess: {100 * excess:.2f}%')
|
| 164 |
+
|
| 165 |
+
print("[*] Average:")
|
| 166 |
+
print(excess * 100)
|
| 167 |
+
|
| 168 |
+
if metrics:
|
| 169 |
+
features = get_feature(metrics)
|
| 170 |
+
score = avg_num_bins
|
| 171 |
+
else:
|
| 172 |
+
features = None
|
| 173 |
+
score = None
|
| 174 |
+
|
| 175 |
+
# -----Print results to stdout (same for all problems)-----
|
| 176 |
+
print('__SANDBOX_RESULT__')
|
| 177 |
+
print('__METRICS_START__')
|
| 178 |
+
print(repr(metrics))
|
| 179 |
+
print('__METRICS_END__')
|
| 180 |
+
|
| 181 |
+
print('__FEATURES_START__')
|
| 182 |
+
print(repr(features))
|
| 183 |
+
print('__FEATURES_END__')
|
| 184 |
+
|
| 185 |
+
print('__SCORE_START__')
|
| 186 |
+
print(repr(score))
|
| 187 |
+
print('__SCORE_END__')
|
| 188 |
+
|
| 189 |
+
print('__SANDBOX_SUCCESS__')
|
| 190 |
+
|
| 191 |
+
except Exception as e:
|
| 192 |
+
print('__SANDBOX_ERROR__:')
|
| 193 |
+
print(f'Error type: {type(e).__name__}')
|
| 194 |
+
print(f'Error message: {str(e)}')
|
| 195 |
+
print('Full traceback:')
|
| 196 |
+
traceback.print_exc()
|
| 197 |
+
```
|
bpp_online/function_description.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The priority function takes as input an item and an array of bins_remain_cap (containing the remaining capacity of each bin) and returns a priority score for each bin.
|
| 2 |
+
The bin with the highest priority score will be selected for the item.
|
| 3 |
+
|
| 4 |
+
### Solution Function Signature
|
| 5 |
+
```python
|
| 6 |
+
def priority(item: float, bins_remain_cap: np.ndarray) -> np.ndarray:
|
| 7 |
+
```
|
bpp_online/generate_dataset.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pickle
|
| 4 |
+
|
| 5 |
+
# Parameters for Weibull distribution
|
| 6 |
+
shape_param = 3
|
| 7 |
+
scale_param = 45
|
| 8 |
+
max_item_size = 100
|
| 9 |
+
bin_capacity = 100
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def generate_weibull_instances(num_instances, num_items, shape, scale, max_size):
|
| 13 |
+
instances = []
|
| 14 |
+
for _ in range(num_instances):
|
| 15 |
+
# Sampling from Weibull distribution
|
| 16 |
+
samples = np.random.weibull(shape, num_items) * scale
|
| 17 |
+
|
| 18 |
+
# Clipping and rounding
|
| 19 |
+
items = np.clip(samples, None, max_size)
|
| 20 |
+
items = np.round(items).astype(int)
|
| 21 |
+
|
| 22 |
+
instances.append(items)
|
| 23 |
+
return instances
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def l1_bound(items: tuple[int, ...], capacity: int) -> float:
|
| 27 |
+
"""Computes L1 lower bound on OPT for bin packing.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
items: Tuple of items to pack into bins.
|
| 31 |
+
capacity: Capacity of bins.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
Lower bound on number of bins required to pack items.
|
| 35 |
+
"""
|
| 36 |
+
return np.ceil(np.sum(items) / capacity)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def l1_bound_dataset(instances: dict) -> float:
|
| 40 |
+
"""Computes the mean L1 lower bound across a dataset of bin packing instances.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
instances: Dictionary containing a set of bin packing instances.
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Average L1 lower bound on number of bins required to pack items.
|
| 47 |
+
"""
|
| 48 |
+
l1_bounds = []
|
| 49 |
+
for name in instances:
|
| 50 |
+
instance = instances[name]
|
| 51 |
+
l1_bounds.append(l1_bound(instance['items'], instance['capacity']))
|
| 52 |
+
return np.mean(l1_bounds)
|
| 53 |
+
|
| 54 |
+
def generate_datasets():
|
| 55 |
+
basepath = os.path.dirname(__file__)
|
| 56 |
+
os.makedirs(os.path.join(basepath, "dataset"), exist_ok=True)
|
| 57 |
+
|
| 58 |
+
# Generating datasets
|
| 59 |
+
training_data = generate_weibull_instances(5, 5000, shape_param, scale_param, max_item_size)
|
| 60 |
+
validation_data = generate_weibull_instances(5, 5000, shape_param, scale_param, max_item_size)
|
| 61 |
+
test_data_5k = generate_weibull_instances(5, 5000, shape_param, scale_param, max_item_size)
|
| 62 |
+
test_data_10k = generate_weibull_instances(5, 10000, shape_param, scale_param, max_item_size)
|
| 63 |
+
test_data_100k = generate_weibull_instances(1, 100000, shape_param, scale_param, max_item_size)
|
| 64 |
+
|
| 65 |
+
# Saving datasets as pickle files, e.g {train_i: {capacity: 100, num_items: 5000, items: [1, 2, 3, ...]},...}
|
| 66 |
+
weibull_5k_train = {'train_' + str(i): {'capacity': bin_capacity, 'num_items': len(training_data[i]), 'items': training_data[i]} for i in range(len(training_data))}
|
| 67 |
+
weibull_5k_val = {'val_' + str(i): {'capacity': bin_capacity, 'num_items': len(validation_data[i]), 'items': validation_data[i]} for i in range(len(validation_data))}
|
| 68 |
+
weibull_5k_test = {'test_' + str(i): {'capacity': bin_capacity, 'num_items': len(test_data_5k[i]), 'items': test_data_5k[i]} for i in range(len(test_data_5k))}
|
| 69 |
+
weibull_10k_test = {'test_' + str(i): {'capacity': bin_capacity, 'num_items': len(test_data_10k[i]), 'items': test_data_10k[i]} for i in range(len(test_data_10k))}
|
| 70 |
+
weibull_100k_test = {'test_' + str(i): {'capacity': bin_capacity, 'num_items': len(test_data_100k[i]), 'items': test_data_100k[i]} for i in range(len(test_data_100k))}
|
| 71 |
+
|
| 72 |
+
# Note that weibull_5k_test is provided by Romera-Paredes et al. (https://github.com/google-deepmind/funsearch/blob/main/bin_packing/bin_packing.ipynb).
|
| 73 |
+
|
| 74 |
+
# Add l1_bound to each dataset
|
| 75 |
+
weibull_5k_train['l1_bound'] = l1_bound_dataset(weibull_5k_train)
|
| 76 |
+
weibull_5k_val['l1_bound'] = l1_bound_dataset(weibull_5k_val)
|
| 77 |
+
weibull_5k_test['l1_bound'] = l1_bound_dataset(weibull_5k_test)
|
| 78 |
+
weibull_10k_test['l1_bound'] = l1_bound_dataset(weibull_10k_test)
|
| 79 |
+
weibull_100k_test['l1_bound'] = l1_bound_dataset(weibull_100k_test)
|
| 80 |
+
|
| 81 |
+
print(weibull_5k_train['l1_bound'])
|
| 82 |
+
print(weibull_5k_val['l1_bound'])
|
| 83 |
+
print(weibull_5k_test['l1_bound'])
|
| 84 |
+
print(weibull_10k_test['l1_bound'])
|
| 85 |
+
print(weibull_100k_test['l1_bound'])
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# Saving datasets as pickle files
|
| 89 |
+
pickle.dump(weibull_5k_train, open(os.path.join(basepath, 'dataset/weibull_5k_train.pickle'), 'wb'))
|
| 90 |
+
pickle.dump(weibull_5k_val, open(os.path.join(basepath,'dataset/weibull_5k_val.pickle'), 'wb'))
|
| 91 |
+
pickle.dump(weibull_5k_test, open(os.path.join(basepath,'dataset/weibull_5k_test.pickle'), 'wb'))
|
| 92 |
+
pickle.dump(weibull_10k_test, open(os.path.join(basepath,'dataset/weibull_10k_test.pickle'), 'wb'))
|
| 93 |
+
pickle.dump(weibull_100k_test, open(os.path.join(basepath,'dataset/weibull_100k_test.pickle'), 'wb'))
|
| 94 |
+
|
| 95 |
+
if __name__ == "__main__":
|
| 96 |
+
generate_datasets()
|
bpp_online/problem_description.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The Online Bin Packing Problem (BPP) is a combinatorial optimization challenge where items of varying sizes arrive sequentially and must be packed into bins of fixed capacity, with the goal of minimizing the total number of bins used while respecting capacity constraints.
|
| 2 |
+
Items must be assigned to bins immediately upon arrival without knowledge of future items, making it an online decision problem.
|
| 3 |
+
We use evolutionary search to develop a `priority` heuristic function that give priority scores to available bins based on the current item size and remaining bin capacities, with the goal of minimizing the average number of bins needed across instances (called "score" or "objective" of solution) while approaching the theoretical lower bound.
|
bpp_online/readme.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
We refer to [Romera-Paredes, B. et al. Mathematical discoveries from program search with large language models. Nature (2023)](https://github.com/google-deepmind/funsearch) for eval.py, test.ipynb, gen_inst.py, and seed.txt.
|
bpp_online/seed_solution.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
def priority(item: float, bins_remain_cap: np.ndarray) -> np.ndarray:
|
| 4 |
+
"""
|
| 5 |
+
Best Fit heuristic: prioritize bins with smallest remaining capacity that can still fit the item.
|
| 6 |
+
"""
|
| 7 |
+
scores = np.zeros_like(bins_remain_cap)
|
| 8 |
+
|
| 9 |
+
# Can the bin fit the item?
|
| 10 |
+
feasible = bins_remain_cap >= item
|
| 11 |
+
|
| 12 |
+
# For feasible bins: higher priority to bins with LESS remaining space
|
| 13 |
+
# Invert the capacity so smaller remaining = higher score
|
| 14 |
+
scores = np.where(feasible, -bins_remain_cap, -np.inf)
|
| 15 |
+
|
| 16 |
+
return scores
|
bpp_online/seed_solution_idea.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Best Fit heuristic: prioritize bins with smallest remaining capacity that can still fit the item.
|
bpp_online/settings.yaml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"function_to_evolve": "priority"
|
| 2 |
+
"obj_type": "min"
|
cvrp_aco/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
cvrp_aco/dataset/test100_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7fcf40e6bee3d9b798513a92017eab592539f8226529b696b95475a47a43167d
|
| 3 |
+
size 155264
|
cvrp_aco/dataset/test20_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:de6479d4ee48422e8ffb652e9ad7fa92dcad1be6894547f2267007b97e19b3de
|
| 3 |
+
size 32384
|
cvrp_aco/dataset/test50_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3370bac48fa37c6d6f23c122a3803e9500fdaaaa57de20c519fe90f57bfd7fa8
|
| 3 |
+
size 78464
|
cvrp_aco/dataset/train50_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:caf38e123b53da4fefda9a988da5f029267d78daf0995d2b68721f6ca8b46452
|
| 3 |
+
size 12368
|
cvrp_aco/dataset/val100_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5151fa344020005f2f1c402642d421feac2f1fb21db949013a0e611ac1f01df5
|
| 3 |
+
size 155264
|
cvrp_aco/dataset/val20_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:766597c294673aa329738b988f9ebd6f02ddd87cb62a6e2c0008b4c974ffa5bb
|
| 3 |
+
size 32384
|
cvrp_aco/dataset/val50_dataset.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c43d1e429036ad6672ac4699e1890edb6349431f501724ec80848f9fd17fde91
|
| 3 |
+
size 78464
|
cvrp_aco/eval.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation script for CVRP-ACO problem
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import traceback
|
| 5 |
+
import numpy as np
|
| 6 |
+
import argparse
|
| 7 |
+
from typing import Dict, List, Tuple, Any
|
| 8 |
+
import torch
|
| 9 |
+
from torch.distributions import Categorical
|
| 10 |
+
from scipy.spatial import distance_matrix
|
| 11 |
+
import inspect
|
| 12 |
+
import seed_solution as solution_module # Note: solution module script is generated and saved on the fly
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# =====Load function to evolve=====
|
| 16 |
+
problem = "cvrp_aco"
|
| 17 |
+
heuristics = getattr(solution_module, "heuristics") # Get function to evolve
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# =====ACO class=====
|
| 21 |
+
class ACO():
|
| 22 |
+
def __init__(self, # 0: depot
|
| 23 |
+
distances, # (n, n) distance matrix between all nodes
|
| 24 |
+
demand, # (n, ) demand at each node (0 for depot)
|
| 25 |
+
heuristic, # (n, n) heuristic matrix guiding ant movement
|
| 26 |
+
capacity, # vehicle capacity constraint
|
| 27 |
+
n_ants=30, # number of ants in colony
|
| 28 |
+
decay=0.9, # pheromone evaporation rate
|
| 29 |
+
alpha=1, # pheromone importance factor
|
| 30 |
+
beta=1, # heuristic importance factor
|
| 31 |
+
device='cpu', # computation device
|
| 32 |
+
):
|
| 33 |
+
self.problem_size = len(distances) # number of nodes including depot
|
| 34 |
+
self.distances = torch.tensor(distances, device=device) if not isinstance(distances, torch.Tensor) else distances
|
| 35 |
+
self.demand = torch.tensor(demand, device=device) if not isinstance(demand, torch.Tensor) else demand
|
| 36 |
+
self.capacity = capacity
|
| 37 |
+
|
| 38 |
+
self.n_ants = n_ants
|
| 39 |
+
self.decay = decay # pheromone evaporation: τ = τ * decay
|
| 40 |
+
self.alpha = alpha # controls pheromone influence: τ^α
|
| 41 |
+
self.beta = beta # controls heuristic influence: η^β
|
| 42 |
+
|
| 43 |
+
self.pheromone = torch.ones_like(self.distances) # initial pheromone matrix
|
| 44 |
+
self.heuristic = torch.tensor(heuristic, device=device) if not isinstance(heuristic, torch.Tensor) else heuristic
|
| 45 |
+
|
| 46 |
+
self.shortest_path = None # best solution found
|
| 47 |
+
self.lowest_cost = float('inf') # cost of best solution
|
| 48 |
+
|
| 49 |
+
self.device = device
|
| 50 |
+
|
| 51 |
+
@torch.no_grad()
|
| 52 |
+
def run(self, n_iterations):
|
| 53 |
+
"""Main ACO loop: run for n_iterations"""
|
| 54 |
+
for _ in range(n_iterations):
|
| 55 |
+
paths = self.gen_path() # generate paths for all ants
|
| 56 |
+
costs = self.gen_path_costs(paths) # compute total distance for each ant
|
| 57 |
+
|
| 58 |
+
best_cost, best_idx = costs.min(dim=0) # find best ant in this iteration
|
| 59 |
+
if best_cost < self.lowest_cost: # update global best if improved
|
| 60 |
+
self.shortest_path = paths[:, best_idx]
|
| 61 |
+
self.lowest_cost = best_cost
|
| 62 |
+
|
| 63 |
+
self.update_pheronome(paths, costs) # update pheromone trails
|
| 64 |
+
|
| 65 |
+
return self.lowest_cost # return best cost found
|
| 66 |
+
|
| 67 |
+
@torch.no_grad()
|
| 68 |
+
def update_pheronome(self, paths, costs):
|
| 69 |
+
'''
|
| 70 |
+
Update pheromone trails using ant solutions.
|
| 71 |
+
Pheromone update rule: τ_ij = τ_ij * decay + Σ(Δτ_ij^k) where Δτ_ij^k = Q/L_k
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
paths: torch tensor with shape (problem_size, n_ants) - complete paths for all ants
|
| 75 |
+
costs: torch tensor with shape (n_ants,) - total distance for each ant
|
| 76 |
+
'''
|
| 77 |
+
self.pheromone = self.pheromone * self.decay # evaporation: τ = τ * ρ
|
| 78 |
+
for i in range(self.n_ants):
|
| 79 |
+
path = paths[:, i] # path for ant i
|
| 80 |
+
cost = costs[i] # total distance for ant i
|
| 81 |
+
# Add pheromone to edges used by this ant: Δτ = Q/L (Q=1 here)
|
| 82 |
+
# path[:-1] gives current nodes, torch.roll(path, shifts=-1)[:-1] gives next nodes
|
| 83 |
+
self.pheromone[path[:-1], torch.roll(path, shifts=-1)[:-1]] += 1.0/cost
|
| 84 |
+
self.pheromone[self.pheromone < 1e-10] = 1e-10 # prevent pheromone from going to zero
|
| 85 |
+
|
| 86 |
+
@torch.no_grad()
|
| 87 |
+
def gen_path_costs(self, paths):
|
| 88 |
+
"""Compute total distance for each ant's path"""
|
| 89 |
+
u = paths.permute(1, 0) # shape: (n_ants, max_seq_len) - transpose for easier indexing
|
| 90 |
+
v = torch.roll(u, shifts=-1, dims=1) # shift to get next node in sequence
|
| 91 |
+
# Sum distances between consecutive nodes (excluding last to first wrap-around)
|
| 92 |
+
return torch.sum(self.distances[u[:, :-1], v[:, :-1]], dim=1)
|
| 93 |
+
|
| 94 |
+
def gen_path(self):
|
| 95 |
+
"""Generate complete paths for all ants using constructive heuristic"""
|
| 96 |
+
actions = torch.zeros((self.n_ants,), dtype=torch.long, device=self.device) # all ants start at depot (node 0)
|
| 97 |
+
visit_mask = torch.ones(size=(self.n_ants, self.problem_size), device=self.device) # 1=unvisited, 0=visited
|
| 98 |
+
visit_mask = self.update_visit_mask(visit_mask, actions) # mark depot as visited
|
| 99 |
+
used_capacity = torch.zeros(size=(self.n_ants,), device=self.device) # current load for each ant
|
| 100 |
+
|
| 101 |
+
used_capacity, capacity_mask = self.update_capacity_mask(actions, used_capacity) # update capacity constraints
|
| 102 |
+
|
| 103 |
+
paths_list = [actions] # paths_list[i] contains the ith move for all ants
|
| 104 |
+
|
| 105 |
+
done = self.check_done(visit_mask, actions)
|
| 106 |
+
while not done:
|
| 107 |
+
actions = self.pick_move(actions, visit_mask, capacity_mask) # probabilistic node selection
|
| 108 |
+
paths_list.append(actions) # record move
|
| 109 |
+
visit_mask = self.update_visit_mask(visit_mask, actions) # update visited nodes
|
| 110 |
+
used_capacity, capacity_mask = self.update_capacity_mask(actions, used_capacity) # update capacity
|
| 111 |
+
done = self.check_done(visit_mask, actions) # check termination
|
| 112 |
+
|
| 113 |
+
return torch.stack(paths_list) # shape: (seq_len, n_ants)
|
| 114 |
+
|
| 115 |
+
def pick_move(self, prev, visit_mask, capacity_mask):
|
| 116 |
+
"""Probabilistic node selection using transition probability: p_ij ∝ τ_ij^α * η_ij^β"""
|
| 117 |
+
pheromone = self.pheromone[prev] # shape: (n_ants, p_size) - pheromone on edges from current nodes
|
| 118 |
+
heuristic = self.heuristic[prev] # shape: (n_ants, p_size) - heuristic values from current nodes
|
| 119 |
+
# Transition probability: p_ij = (τ_ij^α * η_ij^β) / Σ(τ_ik^α * η_ik^β)
|
| 120 |
+
# Masked by visit_mask (unvisited nodes) and capacity_mask (feasible nodes)
|
| 121 |
+
dist = ((pheromone ** self.alpha) * (heuristic ** self.beta) * visit_mask * capacity_mask) # shape: (n_ants, p_size)
|
| 122 |
+
dist = Categorical(dist) # create categorical distribution
|
| 123 |
+
actions = dist.sample() # shape: (n_ants,) - sample next node for each ant
|
| 124 |
+
return actions
|
| 125 |
+
|
| 126 |
+
def update_visit_mask(self, visit_mask, actions):
|
| 127 |
+
"""Update mask of unvisited nodes after moving to new nodes"""
|
| 128 |
+
visit_mask[torch.arange(self.n_ants, device=self.device), actions] = 0 # mark new nodes as visited
|
| 129 |
+
visit_mask[:, 0] = 1 # depot can always be revisited (for returning/starting new route)
|
| 130 |
+
# Exception: if ant returns to depot AND still has unvisited customers, don't allow immediate return
|
| 131 |
+
# This prevents depot-depot cycles when work remains
|
| 132 |
+
visit_mask[(actions==0) * (visit_mask[:, 1:]!=0).any(dim=1), 0] = 0
|
| 133 |
+
return visit_mask
|
| 134 |
+
|
| 135 |
+
def update_capacity_mask(self, cur_nodes, used_capacity):
|
| 136 |
+
'''
|
| 137 |
+
Update vehicle capacity constraints and create mask of feasible next nodes.
|
| 138 |
+
|
| 139 |
+
Args:
|
| 140 |
+
cur_nodes: shape (n_ants, ) - current node for each ant
|
| 141 |
+
used_capacity: shape (n_ants, ) - current load for each ant
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
used_capacity: updated capacity after visiting cur_nodes
|
| 145 |
+
capacity_mask: mask where 1=feasible (demand ≤ remaining capacity), 0=infeasible
|
| 146 |
+
'''
|
| 147 |
+
capacity_mask = torch.ones(size=(self.n_ants, self.problem_size), device=self.device)
|
| 148 |
+
# update capacity: reset to 0 when returning to depot, add demand of current node
|
| 149 |
+
used_capacity[cur_nodes==0] = 0 # reset load when returning to depot
|
| 150 |
+
used_capacity = used_capacity + self.demand[cur_nodes] # add demand of current node
|
| 151 |
+
|
| 152 |
+
# update capacity_mask: mask out nodes whose demand exceeds remaining capacity
|
| 153 |
+
remaining_capacity = self.capacity - used_capacity # (n_ants,) - remaining capacity for each ant
|
| 154 |
+
remaining_capacity_repeat = remaining_capacity.unsqueeze(-1).repeat(1, self.problem_size) # (n_ants, p_size)
|
| 155 |
+
demand_repeat = self.demand.unsqueeze(0).repeat(self.n_ants, 1) # (n_ants, p_size) - demand of all nodes
|
| 156 |
+
capacity_mask[demand_repeat > remaining_capacity_repeat] = 0 # mask infeasible nodes
|
| 157 |
+
|
| 158 |
+
return used_capacity, capacity_mask
|
| 159 |
+
|
| 160 |
+
def check_done(self, visit_mask, actions):
|
| 161 |
+
"""Check termination condition: all customers visited and all ants at depot"""
|
| 162 |
+
# All customers (nodes 1..n) visited AND all ants currently at depot (node 0)
|
| 163 |
+
return (visit_mask[:, 1:] == 0).all() and (actions == 0).all()
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# =====Evaluation function=====
|
| 167 |
+
N_ITERATIONS = 50 # number of ACO iterations
|
| 168 |
+
N_ANTS = 30 # number of ants in colony
|
| 169 |
+
CAPACITY = 50 # vehicle capacity
|
| 170 |
+
|
| 171 |
+
def evaluate_heuristic(node_pos, demand):
|
| 172 |
+
"""Evaluate a heuristic function using ACO on a CVRP instance"""
|
| 173 |
+
# Compute distance matrix between all nodes
|
| 174 |
+
dist_mat = distance_matrix(node_pos, node_pos)
|
| 175 |
+
dist_mat[np.diag_indices_from(dist_mat)] = 1 # set diagonal to 1 (avoid division by zero in heuristics)
|
| 176 |
+
|
| 177 |
+
# Call the heuristic function (evolved code) with appropriate arguments
|
| 178 |
+
# The heuristic function can have different signatures (2 or 4 args)
|
| 179 |
+
if len(inspect.getfullargspec(heuristics).args) == 4:
|
| 180 |
+
# Signature: heuristics(dist_mat, node_pos, demand, capacity)
|
| 181 |
+
heu = heuristics(dist_mat.copy(), node_pos.copy(), demand.copy(), CAPACITY) + 1e-9
|
| 182 |
+
elif len(inspect.getfullargspec(heuristics).args) == 2:
|
| 183 |
+
# Signature: heuristics(dist_mat, normalized_demand)
|
| 184 |
+
heu = heuristics(dist_mat.copy(), demand / CAPACITY) + 1e-9
|
| 185 |
+
|
| 186 |
+
heu[heu < 1e-9] = 1e-9 # ensure heuristic values are positive
|
| 187 |
+
|
| 188 |
+
# Run ACO with the computed heuristic matrix
|
| 189 |
+
aco = ACO(dist_mat, demand, heu, CAPACITY, n_ants=N_ANTS)
|
| 190 |
+
obj = aco.run(N_ITERATIONS) # get best solution cost
|
| 191 |
+
return obj
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# =====Helper functions=====
|
| 195 |
+
def get_feature(metrics: Dict[int, float]) -> Tuple[int, ...]:
|
| 196 |
+
"""
|
| 197 |
+
Convert the metrics dict to a feature vector
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
(tuple): a tuple of discretized scores sorted by problem size
|
| 204 |
+
"""
|
| 205 |
+
scores = metrics.values()
|
| 206 |
+
features = tuple([int(x) for x in scores])
|
| 207 |
+
return features
|
| 208 |
+
|
| 209 |
+
def get_score(metrics: Dict[int, float]) -> float:
|
| 210 |
+
"""
|
| 211 |
+
Convert the metrics dict to a score
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
(float): a score
|
| 218 |
+
"""
|
| 219 |
+
return sum(metrics.values()) / len(metrics)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# =====Main function=====
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
# -----Parse command line arguments (same for all problems)-----
|
| 225 |
+
parser = argparse.ArgumentParser(description='Evaluation script.')
|
| 226 |
+
parser.add_argument(
|
| 227 |
+
'--root_dir',
|
| 228 |
+
type=str,
|
| 229 |
+
default=os.getcwd(),
|
| 230 |
+
help='Project root directory for loading data (default: current working directory)'
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
'--file_output_prefix',
|
| 234 |
+
type=str,
|
| 235 |
+
default='',
|
| 236 |
+
help='Output file prefix for saving evaluation results. '
|
| 237 |
+
'Absolute path recommended. Files saved as {prefix}filename '
|
| 238 |
+
'(default: empty string, saves to current directory)')
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
'--mode',
|
| 241 |
+
type=str,
|
| 242 |
+
default='val',
|
| 243 |
+
choices=['train', 'val'],
|
| 244 |
+
help='Execution mode: train or val (default: val)'
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
'--problem_size',
|
| 248 |
+
type=int,
|
| 249 |
+
default=50, # Customize this to your needs
|
| 250 |
+
help='Problem size parameter'
|
| 251 |
+
)
|
| 252 |
+
# Parse arguments
|
| 253 |
+
args = parser.parse_args()
|
| 254 |
+
root_dir = args.root_dir
|
| 255 |
+
file_output_prefix = args.file_output_prefix
|
| 256 |
+
mode = args.mode
|
| 257 |
+
problem_size = args.problem_size
|
| 258 |
+
# Print parsed arguments for verification
|
| 259 |
+
print(f"root_dir: {root_dir}")
|
| 260 |
+
print(f"file_output_prefix: {file_output_prefix}")
|
| 261 |
+
print(f"mode: {mode}")
|
| 262 |
+
#print(f"problem_size: {problem_size}")
|
| 263 |
+
|
| 264 |
+
# -----Run the evaluation-----
|
| 265 |
+
# Run instances: 20, 50, 100; execution time: 170s
|
| 266 |
+
try:
|
| 267 |
+
basepath = os.path.join(root_dir, "problems", problem)
|
| 268 |
+
if not os.path.isfile(os.path.join(basepath, "dataset/train50_dataset.npy")):
|
| 269 |
+
raise FileNotFoundError("[!] Dataset not found.")
|
| 270 |
+
|
| 271 |
+
if mode == 'train':
|
| 272 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npy")
|
| 273 |
+
dataset = np.load(dataset_path)
|
| 274 |
+
demands, node_positions = dataset[:, :, 0], dataset[:, :, 1:]
|
| 275 |
+
|
| 276 |
+
n_instances = node_positions.shape[0]
|
| 277 |
+
print(f"[*] Dataset loaded: {dataset_path} with {n_instances} instances.")
|
| 278 |
+
|
| 279 |
+
objs = []
|
| 280 |
+
for i, (node_pos, demand) in enumerate(zip(node_positions, demands)):
|
| 281 |
+
obj = evaluate_heuristic(node_pos, demand)
|
| 282 |
+
print(f"[*] Instance {i}: {obj}")
|
| 283 |
+
objs.append(obj.item())
|
| 284 |
+
|
| 285 |
+
print("[*] Average:")
|
| 286 |
+
print(np.mean(objs))
|
| 287 |
+
else: # mode: "val"
|
| 288 |
+
metrics = {}
|
| 289 |
+
for problem_size in [20, 50]: # options: 20, 50, 100
|
| 290 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npy")
|
| 291 |
+
dataset = np.load(dataset_path)
|
| 292 |
+
demands, node_positions = dataset[:, :, 0], dataset[:, :, 1:]
|
| 293 |
+
|
| 294 |
+
n_instances = node_positions.shape[0]
|
| 295 |
+
print(f"[*] Evaluating {dataset_path}")
|
| 296 |
+
|
| 297 |
+
objs = []
|
| 298 |
+
for i, (node_pos, demand) in enumerate(zip(node_positions, demands)):
|
| 299 |
+
obj = evaluate_heuristic(node_pos, demand)
|
| 300 |
+
objs.append(obj.item())
|
| 301 |
+
|
| 302 |
+
print(f"[*] Average for {problem_size}: {np.mean(objs)}")
|
| 303 |
+
metrics[problem_size] = float(np.mean(objs))
|
| 304 |
+
|
| 305 |
+
if metrics:
|
| 306 |
+
features = get_feature(metrics)
|
| 307 |
+
score = get_score(metrics)
|
| 308 |
+
else:
|
| 309 |
+
features = None
|
| 310 |
+
score = None
|
| 311 |
+
|
| 312 |
+
# -----Print results to stdout (same for all problems)-----
|
| 313 |
+
print('__SANDBOX_RESULT__')
|
| 314 |
+
print('__METRICS_START__')
|
| 315 |
+
print(repr(metrics))
|
| 316 |
+
print('__METRICS_END__')
|
| 317 |
+
|
| 318 |
+
print('__FEATURES_START__')
|
| 319 |
+
print(repr(features))
|
| 320 |
+
print('__FEATURES_END__')
|
| 321 |
+
|
| 322 |
+
print('__SCORE_START__')
|
| 323 |
+
print(repr(score))
|
| 324 |
+
print('__SCORE_END__')
|
| 325 |
+
|
| 326 |
+
print('__SANDBOX_SUCCESS__')
|
| 327 |
+
|
| 328 |
+
except Exception as e:
|
| 329 |
+
print('__SANDBOX_ERROR__:')
|
| 330 |
+
print(f'Error type: {type(e).__name__}')
|
| 331 |
+
print(f'Error message: {str(e)}')
|
| 332 |
+
print('Full traceback:')
|
| 333 |
+
traceback.print_exc()
|
cvrp_aco/evaluation_description.txt
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The evaluation script for the problem is described below.
|
| 2 |
+
|
| 3 |
+
```python
|
| 4 |
+
# Evaluation script for CVRP-ACO problem
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
import numpy as np
|
| 9 |
+
import argparse
|
| 10 |
+
from typing import Dict, List, Tuple, Any
|
| 11 |
+
import torch
|
| 12 |
+
from torch.distributions import Categorical
|
| 13 |
+
from scipy.spatial import distance_matrix
|
| 14 |
+
import inspect
|
| 15 |
+
import seed_solution as solution_module # Note: solution module script is generated and saved on the fly
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# =====Load function to evolve=====
|
| 19 |
+
problem = "cvrp_aco"
|
| 20 |
+
heuristics = getattr(solution_module, "heuristics") # Get function to evolve
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# =====ACO class=====
|
| 24 |
+
class ACO():
|
| 25 |
+
def __init__(self, # 0: depot
|
| 26 |
+
distances, # (n, n) distance matrix between all nodes
|
| 27 |
+
demand, # (n, ) demand at each node (0 for depot)
|
| 28 |
+
heuristic, # (n, n) heuristic matrix guiding ant movement
|
| 29 |
+
capacity, # vehicle capacity constraint
|
| 30 |
+
n_ants=30, # number of ants in colony
|
| 31 |
+
decay=0.9, # pheromone evaporation rate
|
| 32 |
+
alpha=1, # pheromone importance factor
|
| 33 |
+
beta=1, # heuristic importance factor
|
| 34 |
+
device='cpu', # computation device
|
| 35 |
+
):
|
| 36 |
+
self.problem_size = len(distances) # number of nodes including depot
|
| 37 |
+
self.distances = torch.tensor(distances, device=device) if not isinstance(distances, torch.Tensor) else distances
|
| 38 |
+
self.demand = torch.tensor(demand, device=device) if not isinstance(demand, torch.Tensor) else demand
|
| 39 |
+
self.capacity = capacity
|
| 40 |
+
|
| 41 |
+
self.n_ants = n_ants
|
| 42 |
+
self.decay = decay # pheromone evaporation: τ = τ * decay
|
| 43 |
+
self.alpha = alpha # controls pheromone influence: τ^α
|
| 44 |
+
self.beta = beta # controls heuristic influence: η^β
|
| 45 |
+
|
| 46 |
+
self.pheromone = torch.ones_like(self.distances) # initial pheromone matrix
|
| 47 |
+
self.heuristic = torch.tensor(heuristic, device=device) if not isinstance(heuristic, torch.Tensor) else heuristic
|
| 48 |
+
|
| 49 |
+
self.shortest_path = None # best solution found
|
| 50 |
+
self.lowest_cost = float('inf') # cost of best solution
|
| 51 |
+
|
| 52 |
+
self.device = device
|
| 53 |
+
|
| 54 |
+
@torch.no_grad()
|
| 55 |
+
def run(self, n_iterations):
|
| 56 |
+
"""Main ACO loop: run for n_iterations"""
|
| 57 |
+
for _ in range(n_iterations):
|
| 58 |
+
paths = self.gen_path() # generate paths for all ants
|
| 59 |
+
costs = self.gen_path_costs(paths) # compute total distance for each ant
|
| 60 |
+
|
| 61 |
+
best_cost, best_idx = costs.min(dim=0) # find best ant in this iteration
|
| 62 |
+
if best_cost < self.lowest_cost: # update global best if improved
|
| 63 |
+
self.shortest_path = paths[:, best_idx]
|
| 64 |
+
self.lowest_cost = best_cost
|
| 65 |
+
|
| 66 |
+
self.update_pheronome(paths, costs) # update pheromone trails
|
| 67 |
+
|
| 68 |
+
return self.lowest_cost # return best cost found
|
| 69 |
+
|
| 70 |
+
@torch.no_grad()
|
| 71 |
+
def update_pheronome(self, paths, costs):
|
| 72 |
+
'''
|
| 73 |
+
Update pheromone trails using ant solutions.
|
| 74 |
+
Pheromone update rule: τ_ij = τ_ij * decay + Σ(Δτ_ij^k) where Δτ_ij^k = Q/L_k
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
paths: torch tensor with shape (problem_size, n_ants) - complete paths for all ants
|
| 78 |
+
costs: torch tensor with shape (n_ants,) - total distance for each ant
|
| 79 |
+
'''
|
| 80 |
+
self.pheromone = self.pheromone * self.decay # evaporation: τ = τ * ρ
|
| 81 |
+
for i in range(self.n_ants):
|
| 82 |
+
path = paths[:, i] # path for ant i
|
| 83 |
+
cost = costs[i] # total distance for ant i
|
| 84 |
+
# Add pheromone to edges used by this ant: Δτ = Q/L (Q=1 here)
|
| 85 |
+
# path[:-1] gives current nodes, torch.roll(path, shifts=-1)[:-1] gives next nodes
|
| 86 |
+
self.pheromone[path[:-1], torch.roll(path, shifts=-1)[:-1]] += 1.0/cost
|
| 87 |
+
self.pheromone[self.pheromone < 1e-10] = 1e-10 # prevent pheromone from going to zero
|
| 88 |
+
|
| 89 |
+
@torch.no_grad()
|
| 90 |
+
def gen_path_costs(self, paths):
|
| 91 |
+
"""Compute total distance for each ant's path"""
|
| 92 |
+
u = paths.permute(1, 0) # shape: (n_ants, max_seq_len) - transpose for easier indexing
|
| 93 |
+
v = torch.roll(u, shifts=-1, dims=1) # shift to get next node in sequence
|
| 94 |
+
# Sum distances between consecutive nodes (excluding last to first wrap-around)
|
| 95 |
+
return torch.sum(self.distances[u[:, :-1], v[:, :-1]], dim=1)
|
| 96 |
+
|
| 97 |
+
def gen_path(self):
|
| 98 |
+
"""Generate complete paths for all ants using constructive heuristic"""
|
| 99 |
+
actions = torch.zeros((self.n_ants,), dtype=torch.long, device=self.device) # all ants start at depot (node 0)
|
| 100 |
+
visit_mask = torch.ones(size=(self.n_ants, self.problem_size), device=self.device) # 1=unvisited, 0=visited
|
| 101 |
+
visit_mask = self.update_visit_mask(visit_mask, actions) # mark depot as visited
|
| 102 |
+
used_capacity = torch.zeros(size=(self.n_ants,), device=self.device) # current load for each ant
|
| 103 |
+
|
| 104 |
+
used_capacity, capacity_mask = self.update_capacity_mask(actions, used_capacity) # update capacity constraints
|
| 105 |
+
|
| 106 |
+
paths_list = [actions] # paths_list[i] contains the ith move for all ants
|
| 107 |
+
|
| 108 |
+
done = self.check_done(visit_mask, actions)
|
| 109 |
+
while not done:
|
| 110 |
+
actions = self.pick_move(actions, visit_mask, capacity_mask) # probabilistic node selection
|
| 111 |
+
paths_list.append(actions) # record move
|
| 112 |
+
visit_mask = self.update_visit_mask(visit_mask, actions) # update visited nodes
|
| 113 |
+
used_capacity, capacity_mask = self.update_capacity_mask(actions, used_capacity) # update capacity
|
| 114 |
+
done = self.check_done(visit_mask, actions) # check termination
|
| 115 |
+
|
| 116 |
+
return torch.stack(paths_list) # shape: (seq_len, n_ants)
|
| 117 |
+
|
| 118 |
+
def pick_move(self, prev, visit_mask, capacity_mask):
|
| 119 |
+
"""Probabilistic node selection using transition probability: p_ij ∝ τ_ij^α * η_ij^β"""
|
| 120 |
+
pheromone = self.pheromone[prev] # shape: (n_ants, p_size) - pheromone on edges from current nodes
|
| 121 |
+
heuristic = self.heuristic[prev] # shape: (n_ants, p_size) - heuristic values from current nodes
|
| 122 |
+
# Transition probability: p_ij = (τ_ij^α * η_ij^β) / Σ(τ_ik^α * η_ik^β)
|
| 123 |
+
# Masked by visit_mask (unvisited nodes) and capacity_mask (feasible nodes)
|
| 124 |
+
dist = ((pheromone ** self.alpha) * (heuristic ** self.beta) * visit_mask * capacity_mask) # shape: (n_ants, p_size)
|
| 125 |
+
dist = Categorical(dist) # create categorical distribution
|
| 126 |
+
actions = dist.sample() # shape: (n_ants,) - sample next node for each ant
|
| 127 |
+
return actions
|
| 128 |
+
|
| 129 |
+
def update_visit_mask(self, visit_mask, actions):
|
| 130 |
+
"""Update mask of unvisited nodes after moving to new nodes"""
|
| 131 |
+
visit_mask[torch.arange(self.n_ants, device=self.device), actions] = 0 # mark new nodes as visited
|
| 132 |
+
visit_mask[:, 0] = 1 # depot can always be revisited (for returning/starting new route)
|
| 133 |
+
# Exception: if ant returns to depot AND still has unvisited customers, don't allow immediate return
|
| 134 |
+
# This prevents depot-depot cycles when work remains
|
| 135 |
+
visit_mask[(actions==0) * (visit_mask[:, 1:]!=0).any(dim=1), 0] = 0
|
| 136 |
+
return visit_mask
|
| 137 |
+
|
| 138 |
+
def update_capacity_mask(self, cur_nodes, used_capacity):
|
| 139 |
+
'''
|
| 140 |
+
Update vehicle capacity constraints and create mask of feasible next nodes.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
cur_nodes: shape (n_ants, ) - current node for each ant
|
| 144 |
+
used_capacity: shape (n_ants, ) - current load for each ant
|
| 145 |
+
|
| 146 |
+
Returns:
|
| 147 |
+
used_capacity: updated capacity after visiting cur_nodes
|
| 148 |
+
capacity_mask: mask where 1=feasible (demand ≤ remaining capacity), 0=infeasible
|
| 149 |
+
'''
|
| 150 |
+
capacity_mask = torch.ones(size=(self.n_ants, self.problem_size), device=self.device)
|
| 151 |
+
# update capacity: reset to 0 when returning to depot, add demand of current node
|
| 152 |
+
used_capacity[cur_nodes==0] = 0 # reset load when returning to depot
|
| 153 |
+
used_capacity = used_capacity + self.demand[cur_nodes] # add demand of current node
|
| 154 |
+
|
| 155 |
+
# update capacity_mask: mask out nodes whose demand exceeds remaining capacity
|
| 156 |
+
remaining_capacity = self.capacity - used_capacity # (n_ants,) - remaining capacity for each ant
|
| 157 |
+
remaining_capacity_repeat = remaining_capacity.unsqueeze(-1).repeat(1, self.problem_size) # (n_ants, p_size)
|
| 158 |
+
demand_repeat = self.demand.unsqueeze(0).repeat(self.n_ants, 1) # (n_ants, p_size) - demand of all nodes
|
| 159 |
+
capacity_mask[demand_repeat > remaining_capacity_repeat] = 0 # mask infeasible nodes
|
| 160 |
+
|
| 161 |
+
return used_capacity, capacity_mask
|
| 162 |
+
|
| 163 |
+
def check_done(self, visit_mask, actions):
|
| 164 |
+
"""Check termination condition: all customers visited and all ants at depot"""
|
| 165 |
+
# All customers (nodes 1..n) visited AND all ants currently at depot (node 0)
|
| 166 |
+
return (visit_mask[:, 1:] == 0).all() and (actions == 0).all()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# =====Evaluation function=====
|
| 170 |
+
N_ITERATIONS = 50 # number of ACO iterations
|
| 171 |
+
N_ANTS = 30 # number of ants in colony
|
| 172 |
+
CAPACITY = 50 # vehicle capacity
|
| 173 |
+
|
| 174 |
+
def evaluate_heuristic(node_pos, demand):
|
| 175 |
+
"""Evaluate a heuristic function using ACO on a CVRP instance"""
|
| 176 |
+
# Compute distance matrix between all nodes
|
| 177 |
+
dist_mat = distance_matrix(node_pos, node_pos)
|
| 178 |
+
dist_mat[np.diag_indices_from(dist_mat)] = 1 # set diagonal to 1 (avoid division by zero in heuristics)
|
| 179 |
+
|
| 180 |
+
# Call the heuristic function (evolved code) with appropriate arguments
|
| 181 |
+
# The heuristic function can have different signatures (2 or 4 args)
|
| 182 |
+
if len(inspect.getfullargspec(heuristics).args) == 4:
|
| 183 |
+
# Signature: heuristics(dist_mat, node_pos, demand, capacity)
|
| 184 |
+
heu = heuristics(dist_mat.copy(), node_pos.copy(), demand.copy(), CAPACITY) + 1e-9
|
| 185 |
+
elif len(inspect.getfullargspec(heuristics).args) == 2:
|
| 186 |
+
# Signature: heuristics(dist_mat, normalized_demand)
|
| 187 |
+
heu = heuristics(dist_mat.copy(), demand / CAPACITY) + 1e-9
|
| 188 |
+
|
| 189 |
+
heu[heu < 1e-9] = 1e-9 # ensure heuristic values are positive
|
| 190 |
+
|
| 191 |
+
# Run ACO with the computed heuristic matrix
|
| 192 |
+
aco = ACO(dist_mat, demand, heu, CAPACITY, n_ants=N_ANTS)
|
| 193 |
+
obj = aco.run(N_ITERATIONS) # get best solution cost
|
| 194 |
+
return obj
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# =====Helper functions=====
|
| 198 |
+
def get_feature(metrics: Dict[int, float]) -> Tuple[int, ...]:
|
| 199 |
+
"""
|
| 200 |
+
Convert the metrics dict to a feature vector
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
(tuple): a tuple of discretized scores sorted by problem size
|
| 207 |
+
"""
|
| 208 |
+
scores = metrics.values()
|
| 209 |
+
features = tuple([int(x) for x in scores])
|
| 210 |
+
return features
|
| 211 |
+
|
| 212 |
+
def get_score(metrics: Dict[int, float]) -> float:
|
| 213 |
+
"""
|
| 214 |
+
Convert the metrics dict to a score
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
metrics (dict): A mapping of test problem size (int) to a score (float).
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
(float): a score
|
| 221 |
+
"""
|
| 222 |
+
return sum(metrics.values()) / len(metrics)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# =====Main function=====
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
# -----Parse command line arguments (same for all problems)-----
|
| 228 |
+
parser = argparse.ArgumentParser(description='Evaluation script.')
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
'--root_dir',
|
| 231 |
+
type=str,
|
| 232 |
+
default=os.getcwd(),
|
| 233 |
+
help='Project root directory for loading data (default: current working directory)'
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument(
|
| 236 |
+
'--file_output_prefix',
|
| 237 |
+
type=str,
|
| 238 |
+
default='',
|
| 239 |
+
help='Output file prefix for saving evaluation results. '
|
| 240 |
+
'Absolute path recommended. Files saved as {prefix}filename '
|
| 241 |
+
'(default: empty string, saves to current directory)')
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
'--mode',
|
| 244 |
+
type=str,
|
| 245 |
+
default='val',
|
| 246 |
+
choices=['train', 'val'],
|
| 247 |
+
help='Execution mode: train or val (default: val)'
|
| 248 |
+
)
|
| 249 |
+
parser.add_argument(
|
| 250 |
+
'--problem_size',
|
| 251 |
+
type=int,
|
| 252 |
+
default=50, # Customize this to your needs
|
| 253 |
+
help='Problem size parameter'
|
| 254 |
+
)
|
| 255 |
+
# Parse arguments
|
| 256 |
+
args = parser.parse_args()
|
| 257 |
+
root_dir = args.root_dir
|
| 258 |
+
file_output_prefix = args.file_output_prefix
|
| 259 |
+
mode = args.mode
|
| 260 |
+
problem_size = args.problem_size
|
| 261 |
+
# Print parsed arguments for verification
|
| 262 |
+
print(f"root_dir: {root_dir}")
|
| 263 |
+
print(f"file_output_prefix: {file_output_prefix}")
|
| 264 |
+
print(f"mode: {mode}")
|
| 265 |
+
#print(f"problem_size: {problem_size}")
|
| 266 |
+
|
| 267 |
+
# -----Run the evaluation-----
|
| 268 |
+
# Run instances: 20, 50, 100; execution time: 170s
|
| 269 |
+
try:
|
| 270 |
+
basepath = os.path.join(root_dir, "problems", problem)
|
| 271 |
+
if not os.path.isfile(os.path.join(basepath, "dataset/train50_dataset.npy")):
|
| 272 |
+
raise FileNotFoundError("[!] Dataset not found.")
|
| 273 |
+
|
| 274 |
+
if mode == 'train':
|
| 275 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npy")
|
| 276 |
+
dataset = np.load(dataset_path)
|
| 277 |
+
demands, node_positions = dataset[:, :, 0], dataset[:, :, 1:]
|
| 278 |
+
|
| 279 |
+
n_instances = node_positions.shape[0]
|
| 280 |
+
print(f"[*] Dataset loaded: {dataset_path} with {n_instances} instances.")
|
| 281 |
+
|
| 282 |
+
objs = []
|
| 283 |
+
for i, (node_pos, demand) in enumerate(zip(node_positions, demands)):
|
| 284 |
+
obj = evaluate_heuristic(node_pos, demand)
|
| 285 |
+
print(f"[*] Instance {i}: {obj}")
|
| 286 |
+
objs.append(obj.item())
|
| 287 |
+
|
| 288 |
+
print("[*] Average:")
|
| 289 |
+
print(np.mean(objs))
|
| 290 |
+
else: # mode: "val"
|
| 291 |
+
metrics = {}
|
| 292 |
+
for problem_size in [20, 50]: # options: 20, 50, 100
|
| 293 |
+
dataset_path = os.path.join(basepath, f"dataset/{mode}{problem_size}_dataset.npy")
|
| 294 |
+
dataset = np.load(dataset_path)
|
| 295 |
+
demands, node_positions = dataset[:, :, 0], dataset[:, :, 1:]
|
| 296 |
+
|
| 297 |
+
n_instances = node_positions.shape[0]
|
| 298 |
+
print(f"[*] Evaluating {dataset_path}")
|
| 299 |
+
|
| 300 |
+
objs = []
|
| 301 |
+
for i, (node_pos, demand) in enumerate(zip(node_positions, demands)):
|
| 302 |
+
obj = evaluate_heuristic(node_pos, demand)
|
| 303 |
+
objs.append(obj.item())
|
| 304 |
+
|
| 305 |
+
print(f"[*] Average for {problem_size}: {np.mean(objs)}")
|
| 306 |
+
metrics[problem_size] = np.mean(objs)
|
| 307 |
+
|
| 308 |
+
if metrics:
|
| 309 |
+
features = get_feature(metrics)
|
| 310 |
+
score = get_score(metrics)
|
| 311 |
+
else:
|
| 312 |
+
features = None
|
| 313 |
+
score = None
|
| 314 |
+
|
| 315 |
+
# -----Print results to stdout (same for all problems)-----
|
| 316 |
+
print('__SANDBOX_RESULT__')
|
| 317 |
+
print('__METRICS_START__')
|
| 318 |
+
print(repr(metrics))
|
| 319 |
+
print('__METRICS_END__')
|
| 320 |
+
|
| 321 |
+
print('__FEATURES_START__')
|
| 322 |
+
print(repr(features))
|
| 323 |
+
print('__FEATURES_END__')
|
| 324 |
+
|
| 325 |
+
print('__SCORE_START__')
|
| 326 |
+
print(repr(score))
|
| 327 |
+
print('__SCORE_END__')
|
| 328 |
+
|
| 329 |
+
print('__SANDBOX_SUCCESS__')
|
| 330 |
+
|
| 331 |
+
except Exception as e:
|
| 332 |
+
print('__SANDBOX_ERROR__:')
|
| 333 |
+
print(f'Error type: {type(e).__name__}')
|
| 334 |
+
print(f'Error message: {str(e)}')
|
| 335 |
+
print('Full traceback:')
|
| 336 |
+
traceback.print_exc()
|
| 337 |
+
```
|
cvrp_aco/external_knowledge.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
- Try combining various factors to determine how promising it is to select an edge.
|
| 2 |
+
- Try sparsifying the matrix by setting unpromising elements to zero.
|
cvrp_aco/function_description.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The `heuristics` function takes as input a distance matrix (shape: n by n), Euclidean coordinates of nodes (shape: n by 2), a vector of customer demands (shape: n), and the integer capacity of vehicle capacity.
|
| 2 |
+
It returns prior indicators of how promising it is to include each edge in a solution.
|
| 3 |
+
The return is of the same shape as the distance_matrix. The depot node is indexed by 0.
|
| 4 |
+
|
| 5 |
+
### Solution Function Signature
|
| 6 |
+
```python
|
| 7 |
+
def heuristics(distance_matrix: np.ndarray, coordinates: np.ndarray, demands: np.ndarray, capacity: int) -> np.ndarray:
|
| 8 |
+
```
|
cvrp_aco/generate_dataset.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
CAPACITY = 50
|
| 5 |
+
DEMAND_LOW = 1
|
| 6 |
+
DEMAND_HIGH = 9
|
| 7 |
+
DEPOT_COOR = [0.5, 0.5]
|
| 8 |
+
|
| 9 |
+
def gen_instance(n):
|
| 10 |
+
locations = np.random.rand(n, 2)
|
| 11 |
+
demands = np.random.randint(low=DEMAND_LOW, high=DEMAND_HIGH+1, size=n)
|
| 12 |
+
depot = np.array([DEPOT_COOR])
|
| 13 |
+
all_locations = np.concatenate((depot, locations), axis=0)
|
| 14 |
+
all_demands = np.concatenate((np.zeros(1,), demands))
|
| 15 |
+
return np.concatenate((all_demands.reshape(-1, 1), all_locations), axis=1)
|
| 16 |
+
|
| 17 |
+
def generate_datasets():
|
| 18 |
+
basepath = os.path.dirname(__file__)
|
| 19 |
+
os.makedirs(os.path.join(basepath, "dataset"), exist_ok=True)
|
| 20 |
+
|
| 21 |
+
np.random.seed(1234)
|
| 22 |
+
|
| 23 |
+
for problem_size in [50]:
|
| 24 |
+
n_instances = 10
|
| 25 |
+
dataset = []
|
| 26 |
+
for i in range(n_instances):
|
| 27 |
+
inst = gen_instance(problem_size)
|
| 28 |
+
dataset.append(inst)
|
| 29 |
+
dataset = np.array(dataset)
|
| 30 |
+
np.save(os.path.join(basepath, f'dataset/train{problem_size}_dataset.npy'), dataset)
|
| 31 |
+
|
| 32 |
+
for problem_size in [20, 50, 100]:
|
| 33 |
+
n_instances = 64
|
| 34 |
+
dataset = []
|
| 35 |
+
for i in range(n_instances):
|
| 36 |
+
inst = gen_instance(problem_size)
|
| 37 |
+
dataset.append(inst)
|
| 38 |
+
dataset = np.array(dataset)
|
| 39 |
+
np.save(os.path.join(basepath, f'dataset/val{problem_size}_dataset.npy'), dataset)
|
| 40 |
+
|
| 41 |
+
for problem_size in [20, 50, 100]:
|
| 42 |
+
n_instances = 64
|
| 43 |
+
dataset = []
|
| 44 |
+
for i in range(n_instances):
|
| 45 |
+
inst = gen_instance(problem_size)
|
| 46 |
+
dataset.append(inst)
|
| 47 |
+
dataset = np.array(dataset)
|
| 48 |
+
np.save(os.path.join(basepath, f'dataset/test{problem_size}_dataset.npy'), dataset)
|
| 49 |
+
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
generate_datasets()
|
cvrp_aco/problem_description.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The Capacitated Vehicle Routing Problem (CVRP) is a combinatorial optimization challenge where vehicles with limited capacity must deliver goods from a central depot to multiple customer locations, minimizing total travel distance while respecting vehicle capacity constraints.
|
| 2 |
+
We use Ant Colony Optimization (ACO) to solve this problem, where artificial ants probabilistically construct routes guided by pheromone trails and heuristic information.
|
| 3 |
+
Your task is to evolve a `heuristics` function that generates a heuristic matrix to guide ant movement, with the goal of minimizing the total distance traveled across all vehicle routes (called "score" or "objective" of solution).
|
cvrp_aco/seed_solution.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
def heuristics(distance_matrix: np.ndarray, coordinates: np.ndarray, demands: np.ndarray, capacity: int) -> np.ndarray:
|
| 4 |
+
return 1 / distance_matrix
|
cvrp_aco/seed_solution_idea.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This heuristic implementation uses a simple inverse distance approach: heuristics = 1 / distance_matrix.
|
| 2 |
+
This creates a heuristic matrix where closer nodes have higher heuristic values, guiding ants to prefer shorter edges during path construction.
|