-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
367 lines (306 loc) · 9.56 KB
/
solution.py
File metadata and controls
367 lines (306 loc) · 9.56 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
from pydantic import BaseModel, Field, computed_field
from enum import StrEnum, IntEnum
from typing import Literal
"""
Assumptions:
------------
All values in this script assume dimension units are:
- w/h/l : cm
- mass : kg
Any values that are negative or zero will be automatically
rejected and will result in a pydantic.ValidationError
"""
class Constraints:
"""
Defines hard-coded constraints for the given problem:
- A package is bulky if volume >= 1,000,000 cm^3
* A package can also be bulky if a dimension >= 150 cm
- A package is heavy if mass >= 20kg
"""
MAX_STANDARD_VOLUME : float = 1e6 # cm^3
MAX_STANDARD_DIMENSION_LENGTH : float = 150.0 # cm
MAX_STANDARD_MASS : float = 20.0 # kg
class VolumeLabel(StrEnum):
STANDARD = 'STANDARD'
BULKY = 'BULKY'
class MassLabel(StrEnum):
STANDARD = 'STANDARD'
HEAVY = 'HEAVY'
class PackageLabel(IntEnum):
STANDARD = 1
SPECIAL = 2
REJECTED = 3
class Volume(BaseModel):
value : float = Field(..., gt=0.)
label : VolumeLabel
class StandardVolume(Volume):
value : float = Field(
...
, gt=0.
, lt=Constraints.MAX_STANDARD_VOLUME
)
label : VolumeLabel = VolumeLabel.STANDARD
class BulkyVolume(Volume):
label : VolumeLabel = VolumeLabel.BULKY
VolumeT = (
StandardVolume | BulkyVolume
)
class VolumeConsumer(BaseModel):
volume : VolumeT
class Dimension(BaseModel):
width : float = Field(..., gt=0.)
height : float = Field(..., gt=0.)
length : float = Field(..., gt=0.)
@computed_field
@property
def volume(self) -> VolumeT:
return VolumeConsumer(
volume={
'value': (
self.width
* self.height
* self.length
)
}
).volume
class StandardDimension(Dimension):
width : float = Field(
...
, gt=0.
, lt=Constraints.MAX_STANDARD_DIMENSION_LENGTH
)
height : float = Field(
...
, gt=0.
, lt=Constraints.MAX_STANDARD_DIMENSION_LENGTH
)
length : float = Field(
...
, gt=0.
, lt=Constraints.MAX_STANDARD_DIMENSION_LENGTH
)
class BulkyDimension(Dimension):
...
DimensionT = (
StandardDimension | BulkyDimension
)
class DimensionConsumer(BaseModel):
dimension : DimensionT
@classmethod
def from_args(
cls, *
, width : int | float
, height : int | float
, length : int | float
) -> DimensionT:
return cls(
dimension={
'width': width
, 'height': height
, 'length': length
}
).dimension
class Package(BaseModel):
dimension : DimensionT
volume : VolumeT
mass : float
label : PackageLabel
class StandardPackage(Package):
dimension : StandardDimension
volume : StandardVolume
mass : float = Field(
...
, gt=0.
, lt=Constraints.MAX_STANDARD_MASS
)
label : PackageLabel = PackageLabel.STANDARD
class BulkyPackage(Package):
dimension : DimensionT
volume : VolumeT
mass : float = Field(
...
, gt=0.
, lt=Constraints.MAX_STANDARD_MASS
)
label : PackageLabel = PackageLabel.SPECIAL
class HeavyPackage(StandardPackage):
"""
Note: we're using StandardPackage to avoid
re-writing the same dimension/volume types again,
since a heavy package is only heavy when having
standard dimensions/volume (otherwise it's considered rejected)
"""
mass : float = Field(..., ge=Constraints.MAX_STANDARD_MASS)
label : PackageLabel = PackageLabel.SPECIAL
class RejectedPackage(Package):
dimension : DimensionT
volume : VolumeT
mass : float = Field(..., ge=Constraints.MAX_STANDARD_MASS)
label : PackageLabel = PackageLabel.REJECTED
# Define the generic Package Type, in this problem domain
# a package can be one of the following:
# - Standard
# - Heavy -> Special
# - Bulky -> Special
# - Rejected
PackageT = (
StandardPackage
| HeavyPackage
| BulkyPackage
| RejectedPackage
)
class PackageConsumer(BaseModel):
package : PackageT
@classmethod
def from_args(
cls, *
, mass : int | float
, **dimensions
) -> PackageT:
dim = DimensionConsumer.from_args(
**dimensions
)
return cls(package={
'dimension': dim
, 'volume': dim.volume
, 'mass': mass
}).package
"""
Implementation of sort just involves casting the arguments into a PackageT
the optional ret_type parameter allows caller control of how
the result is returned, with options to return:
- label name (the enum name)
- label value (the value of the enum, int for plotting purposes)
- label enum
- model (PackageT)
The default selection is name to adhere to the takehome requirements
"""
def sort(
width : int | float
, height : int | float
, length : int | float
, mass : int | float
, ret_type : str = 'name'
) -> PackageT | PackageLabel | str | int:
pkg = PackageConsumer.from_args(
width=width
, height=height
, length=length
, mass=mass
)
match ret_type:
case 'label':
return pkg.label # PackageLabel
case 'pkg' | 'package':
return pkg # PackageT
case 'label value' | 'value' | 'lblvalue':
return pkg.label.value # int
case 'label name' | 'name' | 'lblname':
return pkg.label.name # str
case _:
raise ValueError(f"{re_type} is not a valid return type!")
# --------------- TESTING ---------------- #
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
def simple_test():
"""
Creates the full combination space (or product) of
dims x dims x dims x masses and runs the sort operation
"""
dims = [10, 50, 100, 150]
masses = [5, 10, 20, 25]
results = {}
for w, h, l, m in product(dims, dims, dims, masses):
results[(w, h, l, m)] = sort(w, h, l, m, 'package')
return results
def failing_test1():
"""
Raises ValidationError due to zero width
"""
sort(0, 10, 10, 1)
def failing_test2():
"""
Raises ValidationError due to zero width and negative height
"""
sort(0, -1, 10, 1)
def sort_for_meshgrid(
w, h, l, m
):
"""
Wrapper function of sort, required for meshgrid testing
sets the `ret_type` to value to produce an int result
"""
return sort(w, h, l, m, 'value')
def test_sorting_on_meshgrid():
"""
Creates a 4D meshgrid of shape (dims, dims, dims, masses)
and runs a "vectorized" version of sort to produce a
4D result array. Also returns the dimensions and masses
to be used for plotting purposes
The dimensions width, length, height (w/l/h) are chosen
arbitrarily since we are re-using `dims` across 3D.
"""
dims = np.array([1, 5, 50, 100, 150, 200, 1000])
masses = np.array([1, 5, 10, 15, 20, 25, 50])
W, L, H, M = np.meshgrid(dims, dims, dims, masses)
vectorized = np.vectorize(sort_for_meshgrid)
return vectorized(W, L, H, M), dims, masses
def viz():
"""
Stitches together multiple 4D -> 2D sub-arrays
into one giant 2D array to produce a giant
grid plot of results. Each grid item in the
rendered plot is a "patch" of the WxH result sub-array
indexed at a given length and mass. This lets us view
multiple slices of the 4D array in one figure, without
having to inspect multiple subplots.
Hard-coded to currently vary the length & mass
over height & width. Since l/w/h are all the same,
this rendered slice of the full 4D result array
is enough to showcase the problem domain for a wide
variety of inputs.
"""
result, dims, masses = test_sorting_on_meshgrid()
n_w, n_l, n_h, n_m = result.shape
# Flatten the data by stitching slices over W × H
# for each (L, M) combination
# Resulting shape will be (n_w * n_l, n_h * n_m)
stitched = np.zeros((n_w * n_l, n_h * n_m))
for i_l in range(n_l):
for i_m in range(n_m):
slice_wh = result[:, i_l, :, i_m]
row_start = i_l * n_w
row_end = (i_l + 1) * n_w
col_start = i_m * n_h
col_end = (i_m + 1) * n_h
stitched[row_start:row_end, col_start:col_end] = slice_wh
fig, ax = plt.subplots(figsize=(10, 8))
im = ax.imshow(stitched, cmap='viridis', origin='lower', aspect='auto')
for i in range(1, n_l):
ax.axhline(i * n_w - 0.5, color='white', linewidth=0.5)
for j in range(1, n_m):
ax.axvline(j * n_h - 0.5, color='white', linewidth=0.5)
ax.set_xticks([i * n_h + n_h / 2 for i in range(n_m)])
ax.set_xticklabels([f"M={m}" for m in masses], rotation=45)
ax.set_yticks([i * n_w + n_w / 2 for i in range(n_l)])
ax.set_yticklabels([f"L={l}" for l in dims])
ax.set_title("Package Sorting Results: WxH slices arranged by LxM")
fig.colorbar(im, ax=ax, label='Result Value')
plt.tight_layout()
plt.show()
def run_all_tests():
def run_failed_test(func):
try:
func()
except Exception as e:
return e
results = [
('simple_test', simple_test())
, ('sort_for_meshgrid', test_sorting_on_meshgrid())
]
failures = [
('failing_test1', run_failed_test(failing_test1))
, ('failing_test2', run_failed_test(failing_test2))
]
return results, failures