Repository navigation
Expand file tree
/
Copy pathinput_loader.py
More file actions
316 lines (271 loc) · 10.4 KB
/
Copy pathinput_loader.py
File metadata and controls
316 lines (271 loc) · 10.4 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
308
309
310
311
312
313
314
315
316
from __future__ import annotations
from pathlib import Path
from typing import Iterable, List, Sequence, Tuple, Optional, Any
import json
from datetime import datetime, date
def load_plants_arrays(plants_file: str | Path) -> Tuple[List[str], List[int], List[List[str]]]:
"""Load plant data from a JSON file and return arrays expected by the optimizer.
Parameters
----------
plants_file : str | Path
Path to the JSON file containing a list of plant objects with keys:
- "plant_name": str
- "plant_quantity_capacity": int
- "allowedModels": list[str]
Returns
-------
Tuple[List[str], List[int], List[List[str]]]
- plant_names: list of plant labels (as strings)
- plant_quantity_capacities: list of capacities per plant (ints)
- allowed_model_names_per_plant: list of lists of allowed model names per plant
Raises
------
FileNotFoundError
If the given file path does not exist.
ValueError
If the JSON structure is invalid or missing required keys.
"""
path = Path(plants_file)
if not path.exists():
raise FileNotFoundError(f"plants file not found: {path}")
with path.open("r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in plants file: {path}") from exc
if not isinstance(data, list):
raise ValueError("Plants JSON must be a list of objects.")
plant_names: List[str] = []
plant_quantity_capacities: List[int] = []
allowed_model_names_per_plant: List[List[str]] = []
for idx, obj in enumerate(data):
if not isinstance(obj, dict):
raise ValueError(f"Plant entry at index {idx} must be an object.")
if "plant_name" not in obj or "plant_quantity_capacity" not in obj or "allowedModels" not in obj:
raise ValueError(
f"Plant entry at index {idx} missing required keys ('plant_name', 'plant_quantity_capacity', 'allowedModels')."
)
name = str(obj["plant_name"]) # normalize to str
cap_raw = obj["plant_quantity_capacity"]
if not isinstance(cap_raw, int):
try:
cap = int(cap_raw)
except Exception as exc:
raise ValueError(f"Capacity for plant '{name}' must be an integer; got {cap_raw!r}.") from exc
else:
cap = cap_raw
models_raw = obj["allowedModels"]
if isinstance(models_raw, (str, bytes)):
raise ValueError(f"allowedModels for plant '{name}' must be a list of strings, not a string.")
try:
models_list = list(models_raw)
except Exception as exc:
raise ValueError(f"allowedModels for plant '{name}' must be an iterable of strings.") from exc
plant_names.append(name)
plant_quantity_capacities.append(cap)
allowed_model_names_per_plant.append(models_list)
return plant_names, plant_quantity_capacities, allowed_model_names_per_plant
def load_items_arrays(items_file: str | Path) -> Tuple[List[str], List[str], List[int], List[int], List[str]]:
"""Load items from a FLATTENED JSON and produce arrays for the optimizer.
Accepted input shape (flattened only)
------------------------------------
{
"items": [
{
"order": "1",
"dueDate": "YYYY-MM-DD",
"modelFamily": "...",
"model": "...",
"submodel": "...",
"quantity": 10
}, ...
]
}
Returns
-------
Tuple[List[str], List[str], List[int], List[int], List[str]]
- item_names: unique item labels
- model_names: per item, taken from the "model" field
- item_quantities: per item quantity (int)
- due_date_boosts: per item integer boost in [0, 100], linearly mapped from due dates
with 100 when due date is 100 days overdue (now - 100), 0 when due date is 100 days ahead (now + 100),
and 50 when due date is today.
- order_ids: per item order identifier (stringified)
Raises
------
FileNotFoundError
If the given file path does not exist.
ValueError
If the JSON structure or dates are invalid.
"""
path = Path(items_file)
if not path.exists():
raise FileNotFoundError(f"items file not found: {path}")
with path.open("r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in items file: {path}") from exc
if not isinstance(data, dict):
raise ValueError("Items JSON must be an object with key 'items'.")
def _parse_date(d: str) -> date:
try:
return datetime.strptime(d, "%Y-%m-%d").date()
except Exception as exc:
raise ValueError(f"Invalid dueDate format (expected YYYY-MM-DD): {d!r}") from exc
def _boost_for_due(due: date, today: date) -> int:
days = (due - today).days
# clamp to [-100, 100]
if days < -100:
days = -100
elif days > 100:
days = 100
# linear map: overdue -100 -> 100, today -> 50, ahead +100 -> 0
# Equivalent formula: boost = ((-days + 100) / 200) * 100
boost = ((-days + 100) / 200.0) * 100.0
return int(round(boost))
today = date.today()
item_names: List[str] = []
model_names: List[str] = []
item_quantities: List[int] = []
due_date_boosts: List[int] = []
order_ids: List[str] = []
# sequence counter for unique item_names
seq = 0
def _push_item(it: dict, *, ctx: str) -> Tuple[str, str, str, int, Optional[Any], Optional[str]]:
nonlocal seq
# Validate common fields
fam = it.get("modelFamily")
mod = it.get("model")
sub = it.get("submodel")
qty = it.get("quantity")
if not isinstance(fam, str) or not isinstance(mod, str) or not isinstance(sub, str):
raise ValueError(f"Item {ctx} must have string fields modelFamily/model/submodel.")
if qty is None:
raise ValueError(f"Item {ctx} missing 'quantity'.")
if not isinstance(qty, int):
try:
qty = int(qty)
except Exception as exc:
raise ValueError(f"Item {ctx} has non-integer quantity: {qty!r}.") from exc
# Order id and due date may be on the item (flattened) or provided by caller (legacy)
ord_id_raw = it.get("order")
due_str_item = it.get("dueDate")
if due_str_item is not None and not isinstance(due_str_item, str):
raise ValueError(f"Item {ctx} 'dueDate' must be a string when present.")
return fam, mod, sub, qty, ord_id_raw, due_str_item
def _append_outputs(*, fam: str, mod: str, sub: str, qty: int, ord_id_raw: Any, due_str: str) -> None:
nonlocal seq
model_name = mod
item_name = f"{fam}_{model_name}_{sub}#{seq}"
seq += 1
# Normalize order id
ord_id = str(ord_id_raw) if ord_id_raw is not None else ""
boost_val = _boost_for_due(_parse_date(due_str), today)
item_names.append(item_name)
model_names.append(model_name)
item_quantities.append(qty)
due_date_boosts.append(boost_val)
order_ids.append(ord_id)
items_obj = data.get("items", None)
if not isinstance(items_obj, list):
raise ValueError("Items JSON must contain 'items' as a list of objects.")
# Flattened schema only
for ii, it in enumerate(items_obj):
if not isinstance(it, dict):
raise ValueError(f"Item at index {ii} must be an object.")
fam, mod, sub, qty, ord_id_raw, due_str_item = _push_item(it, ctx=f"index {ii}")
if not isinstance(due_str_item, str):
raise ValueError(f"Item at index {ii} missing valid 'dueDate'.")
_append_outputs(fam=fam, mod=mod, sub=sub, qty=qty, ord_id_raw=ord_id_raw, due_str=due_str_item)
return item_names, model_names, item_quantities, due_date_boosts, order_ids
def load_Settings(settings_file: str | Path) -> dict[str, float]:
"""Load nonnegative parameters from a JSON settings file.
This reads objective/structural weights and soft/hard minimum thresholds used by the optimizer.
All required keys must be present. Values must be numeric (int or float) and >= 0.
Expected keys (all REQUIRED):
- "fill_weight"
- "due_date_boost_weight"
- "quantity_weight"
- "w_model_name_group"
- "w_model_order_id_group"
- "w_minimize_plants"
- "w_soft_min_qty_of_items_same_model_name_in_a_plant" (weight of the soft min penalty)
- "soft_min_qty_of_items_same_model_name_in_a_plant" (soft threshold; 0 disables)
- "min_allowed_qty_of_items_same_model_name_in_a_plant" (hard threshold; 0 disables)
- "time_limit_s" (solver time limit in seconds; required)
Parameters
----------
settings_file : str | Path
Path to a JSON file containing zero or more of the keys above.
Returns
-------
dict[str, float]
A mapping of validated weights for all required keys.
Raises
------
FileNotFoundError
If the given file path does not exist.
ValueError
If the JSON is invalid, not an object, or any present weight is non-numeric or negative.
"""
path = Path(settings_file)
if not path.exists():
raise FileNotFoundError(f"settings file not found: {path}")
with path.open("r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in settings file: {path}") from exc
if not isinstance(data, dict):
raise ValueError("Settings JSON must be an object with weight keys.")
# Required keys (weights, thresholds, and solver controls)
required_keys = {
"fill_weight",
"due_date_boost_weight",
"quantity_weight",
"w_model_name_group",
"w_model_order_id_group",
"w_minimize_plants",
"w_soft_min_qty_of_items_same_model_name_in_a_plant",
"soft_min_qty_of_items_same_model_name_in_a_plant",
"min_allowed_qty_of_items_same_model_name_in_a_plant",
"time_limit_s",
}
# Ensure all required keys are present
missing = [k for k in sorted(required_keys) if k not in data]
if missing:
raise ValueError(
"Settings JSON is missing required keys: " + ", ".join(missing)
)
weights: dict[str, float] = {}
for k in sorted(required_keys):
v = data[k]
# Validate numeric and >= 0
if isinstance(v, bool): # exclude bools (subclass of int)
raise ValueError(f"Weight '{k}' must be numeric (int/float) and >= 0; got bool {v!r}.")
try:
val = float(v)
except Exception as exc:
raise ValueError(f"Weight '{k}' must be numeric (int/float); got {v!r}.") from exc
if val < 0:
raise ValueError(f"Weight '{k}' must be >= 0; got {val}.")
weights[k] = val
# Optional solver control: random seed only
# - random_seed: int >= 0 (0 lets solver decide, >0 fixes randomness)
optional_numeric_keys = [
"random_seed",
]
for ok in optional_numeric_keys:
if ok in data:
v = data[ok]
if isinstance(v, bool):
raise ValueError(f"Optional setting '{ok}' must be numeric (int/float) and >= 0; got bool {v!r}.")
try:
val = float(v)
except Exception as exc:
raise ValueError(f"Optional setting '{ok}' must be numeric (int/float); got {v!r}.") from exc
if val < 0:
raise ValueError(f"Optional setting '{ok}' must be >= 0; got {val}.")
weights[ok] = val
return weights