-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_problem.py
More file actions
80 lines (66 loc) · 2.1 KB
/
setup_problem.py
File metadata and controls
80 lines (66 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import json
import uuid
from pathlib import Path
from random import randint, seed
MAX_CAPACITY = 250
NB_ITEMS = 50
MAX_WEIGHT = 50
MAX_PROFIT = 50
def parameter_knapsack(
max_capacity=MAX_CAPACITY,
nb_items=NB_ITEMS,
max_weight=MAX_WEIGHT,
max_profit=MAX_PROFIT,
parameters_seed=None,
output_dir="parameters"
):
# Setting random seed
if parameters_seed is not None:
seed(parameters_seed)
capacity = randint(a=int(max_capacity/2), b=max_capacity)
items = [
{
"weight": randint(a=int(max_weight/2), b=max_weight),
"profit": randint(a=1, b=max_profit)
}
for _ in range(nb_items)
]
parameters_id = f"knapsack_{capacity}_{nb_items}_{uuid.uuid4().hex[:8]}"
parameters = {
"id": parameters_id,
"capacity": capacity,
"items": items,
"metadata": {
"nb_items": nb_items,
"seed": parameters_seed
},
}
output_path = Path(output_dir)
# Store parameters for loading
json_file = output_path / f"{parameters_id}.json"
with open(json_file, "w") as f:
json.dump(parameters, f, indent=2)
return json_file
def batch_generate(
n_instances,
max_capacity=None,
nb_items=None,
max_weight=None,
max_profit=None,
parameters_seed=None,
output_dir=None
):
for i in range(n_instances):
# Unique seed per instance for reproducibility
instance_seed = parameters_seed + i if parameters_seed is not None else None
parameter_knapsack(
max_capacity=max_capacity if max_capacity is not None else MAX_CAPACITY,
nb_items=nb_items if nb_items is not None else NB_ITEMS,
max_weight=max_weight if max_weight is not None else MAX_WEIGHT,
max_profit=max_profit if max_profit is not None else MAX_PROFIT,
parameters_seed=instance_seed,
output_dir=output_dir if output_dir is not None else None
)
def load_parameters(filepath):
with open(filepath, "r") as f:
return json.load(f)