136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307 | class KnapsackDomain(Domain):
__capacity_approaches = ("evolved", "percentage", "fixed")
def __init__(
self,
dimension: int = 50,
min_p: int = 1,
min_w: int = 1,
max_p: int = 1_000,
max_w: int = 1_000,
capacity_approach: str = "evolved",
max_capacity: int = int(1e5),
capacity_ratio: float = 0.8,
seed: Optional[int] = None,
):
self.min_p = min_p
self.min_w = min_w
self.max_p = max_p
self.max_w = max_w
self.max_capacity = max_capacity
if capacity_ratio < 0.0 or capacity_ratio > 1.0 or not float(capacity_ratio):
self.capacity_ratio = 0.8 # Default
msg = "The capacity ratio must be a float number in the range [0.0-1.0]. Set as 0.8 as default."
print(msg)
else:
self.capacity_ratio = capacity_ratio
if capacity_approach not in self.__capacity_approaches:
msg = f"The capacity approach {capacity_approach} is not available. Please choose between {self.__capacity_approaches}. Evolved approach set as default."
print(msg)
self._capacity_approach = "evolved"
else:
self._capacity_approach = capacity_approach
bounds = [(1.0, self.max_capacity)] + [
(min_w, max_w) if i % 2 == 0 else (min_p, max_p)
for i in range(2 * dimension)
]
super().__init__(
dimension=dimension,
bounds=bounds,
name="KP",
feat_names="capacity,max_p,max_w,min_p,min_w,avg_eff,mean,std".split(","),
seed=seed,
)
@property
def capacity_approach(self):
return self._capacity_approach
@capacity_approach.setter
def capacity_approach(self, app):
"""Setter for the Maximum capacity generator approach.
It forces to update the variable to one of the specify values
Args:
app (str): Approach for setting the capacity. It should be fixed, evolved or percentage.
"""
if app not in self.__capacity_approaches:
msg = f"The capacity approach {app} is not available. Please choose between {self.__capacity_approaches}. Evolved approach set as default."
print(msg)
self._capacity_approach = "evolved"
else:
self._capacity_approach = app
def generate_instances(self, n: int = 1) -> List[Instance]:
"""Generates N instances for the domain.
Args:
n (int, optional): Number of instances to generate. Defaults to 1.
Returns:
List[Instance]: A list of Instance objects created from the raw numpy generation
"""
weights_and_profits = np.empty(shape=(n, self.dimension * 2), dtype=np.int32)
weights_and_profits[:, 0::2] = self._rng.integers(
low=self.min_w, high=self.max_w, size=(n, self.dimension)
)
weights_and_profits[:, 1::2] = self._rng.integers(
low=self.min_p, high=self.max_p, size=(n, self.dimension)
)
# Assume fixed
capacities = np.full(n, fill_value=self.max_capacity, dtype=np.int32)
match self.capacity_approach:
case "evolved":
capacities[:] = self._rng.integers(1, self.max_capacity, size=n)
case "percentage":
capacities[:] = (
np.sum(weights_and_profits[:, 1::2], axis=1) * self.capacity_ratio
).astype(np.int32)
return list(
Instance(i) for i in np.column_stack((capacities, weights_and_profits))
)
def extract_features(
self, instances: Sequence[Instance] | np.ndarray
) -> np.ndarray:
"""Extract the features of the instance based on the domain
Args:
instances (Sequence[Instance]): Instances to extract the features from.
Returns:
ArrayLike: 2d array with the features of each instance
"""
if not isinstance(instances, np.ndarray):
instances = np.asarray(instances, copy=True)
features = np.empty(shape=(len(instances), 8), dtype=np.float32)
weights = instances[:, 1::2]
profits = instances[:, 2::2]
features[:, 0] = instances[:, 0] # Qs
features[:, 1] = np.max(profits, axis=1)
features[:, 2] = np.max(weights, axis=1)
features[:, 3] = np.min(profits, axis=1)
features[:, 4] = np.min(weights, axis=1)
features[:, 5] = np.mean(profits / weights)
features[:, 6] = np.mean(instances[:, 1:], axis=1)
features[:, 7] = np.std(instances[:, 1:], axis=1)
return features
def extract_features_as_dict(
self, instances: Sequence[Instance] | np.ndarray
) -> List[Dict[str, np.float32]]:
"""Creates a dictionary with the features of the instance.
The key are the names of each feature and the values are
the values extracted from instance.
Args:
instances (Sequence[Instance]): Instances to extract the features from. They should in the an array form.
Returns:
Dict[str, float]: Dictionary with the names/values of each feature
"""
features = self.extract_features(instances)
named_features: list[dict[str, np.float32]] = [{}] * len(features)
for i, feats in enumerate(features):
named_features[i] = {k: v for k, v in zip(self.feat_names, feats)}
return named_features
def generate_problems_from_instances(
self, instances: Sequence[Instance] | np.ndarray
) -> List:
"""Generates a List of Knapsack objects from the instances
Args:
instances (Sequence[Instance]): Instances to create the problems from
Returns:
List: List containing len(instances) objects of type Knapsack
"""
if not isinstance(instances, np.ndarray):
instances = np.asarray(instances)
capacities = instances[:, 0].astype(int)
weights = instances[:, 1::2].astype(int)
profits = instances[:, 2::2].astype(int)
# Sets the capacity according to the method
if self.capacity_approach == "percentage":
capacities[:] = (np.sum(weights, axis=1) * self.capacity_ratio).astype(
np.int32
)
elif self.capacity_approach == "fixed":
capacities[:] = self.max_capacity
return list(
Knapsack(profits=profits[i], weights=weights[i], capacity=capacities[i])
for i in range(len(instances))
)
|