-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsupplyChain.py
More file actions
1689 lines (1530 loc) · 84.3 KB
/
supplyChain.py
File metadata and controls
1689 lines (1530 loc) · 84.3 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 29 13:38:59 2017
@author: Nat
"""
from mesa import Agent, Model
from mesa.time import SimultaneousActivation
import random
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
import numpy as np
from collections import Counter
import pandas as pd
from sklearn.linear_model import LinearRegression as lr
import os
os.chdir('D:\\projects\\mesa')
import warnings
warnings.filterwarnings('ignore')
import re
class Transportation(Agent):
def __init__(self, unique_id, model, specialFreight = False, speed = 1,
priceIncreaseFactor = 10, reliability = 0.9,
weightCapacity = 10000, volumeCapacity = 10000, singleTripMode = True):
super().__init__(unique_id, model)
self.pos = (0, 0)
self.weightCapacity = weightCapacity # as absolute units
self.volumeCapacity = volumeCapacity # as absolute units
self.utilizedWeight = 0 # as absolute units
self.utilizedVolume = 0 # as absolute units
self.reliability = reliability # e.g. 0.9 is 90%
self.unitWeightPrice = speed / 100 # price per weight unit per distance unit, related to speed / transport mode
self.unitVolumePrice = speed / 100
self.priceIncreaseFactor = priceIncreaseFactor
self.volumeDiscount = {0:0, 50:0.1, 80:0.15, 95:0.2} # if utilized capacity > percentage, then price is discounted by decimal
self.minUtilizationToSail = self.model.rules.minTranspUtilization # minimum utiliation percentage to sail, e.g. 50 is 50%
self.fixedIntervalToSail = 7 # only sail every fixed time units
self.speed = speed # grid to travel per time unit
self.origin = (0, 0) # to be defined when created according to plant location
self.destination = (1, 1) # to be defined when created according to customer location
self.intransit = False
self.specialFreight = specialFreight
self.listOfProducts = []
self.totalTransportCost = 0
self.nrOfTrips = 0
self.originDelay = 0 # of delays in origin
self.transitDelay = 0
self.singleTripMode = singleTripMode # if no return trip designed in the system, then True
def step(self):
if self.pos == self.origin: # load if transport is not moving in origin
self.load()
if self.pos == self.destination: # unload if transport is not moving in destination
self.unload()
if self.intransit is False:
self.setsail()
def advance(self):
self.move()
def load(self):
tmp = list(self.model.grid[self.origin[0]][self.origin[1]])
listOfProducts = [product for product in tmp if isinstance(product, Product) and product.intransit is False]
if len(tmp) == 0:
return
loadingSequence = sortAgent(listOfProducts, 'priority', reverse = False)
for i in loadingSequence:
product = listOfProducts[i]
if product.weight * product.quantity > self.weightCapacity - self.utilizedWeight:
return
self.listOfProducts.append(product)
self.utilizedWeight = self.utilizedWeight + product.weight * product.quantity
self.utilizedVolume = self.utilizedVolume + product.volume * product.quantity
product.intransit = True
def unload(self):
# find warehouse in neighborhood
content = self.model.grid.get_cell_list_contents(self.get_neighborhood())
whs = [agent for agent in content if isinstance(agent, Warehouse)][0]
for product in self.listOfProducts:
product.warehouse = whs
self.model.grid.move_agent(product, whs.pos)
product.availableInStorage = True
whs.utilization = whs.utilization + \
product.volume / whs.stackLayer * product.quantity
whs.listOfProducts.append(product)
self.calTransportCost() # calculate cost upon arrival
self.nrOfTrips = self.nrOfTrips + 1
self.intransit = False
if self.singleTripMode:
self.resetPosition(self.origin, self.destination)
else:
# reverse privious origin and destination pair for the new trip
self.resetPosition(self.destination, self.origin)
def setsail(self):
reachedWeightLimit = self.utilizedWeight / self.weightCapacity * 100 > self.minUtilizationToSail
reachedVolumeLimit = self.utilizedVolume / self.weightCapacity * 100 > self.minUtilizationToSail
isScheduledDate = np.mod(self.model.schedule.time, self.fixedIntervalToSail) == 0
if (self.specialFreight) or (isScheduledDate and (reachedWeightLimit or reachedVolumeLimit)):
self.intransit = True
def move(self):
if self.intransit is False:
return
for i in range(self.speed):
if self.pos == self.destination:
return
possible_steps = self.get_neighborhood()
shortestDistance = np.argmin(self.calDistance(possible_steps))
new_position = possible_steps[shortestDistance]
if random.randrange(0, 100) <= self.reliability * 100:
self.model.grid.move_agent(self, new_position)
self.pos = new_position
for product in self.listOfProducts:
product.move(new_position)
else:
if self.pos == self.origin:
self.originDelay = self.originDelay + 1
self.intransit = False # if not leaving origin: reset intransit to False
else:
self.transitDelay = self.transitDelay + 1
def calDistance(self, listOfCells):
distance = []
for cell in listOfCells:
distance.append(np.sqrt(np.power(cell[0] - self.destination[0],2) +
np.power(cell[1] - self.destination[1],2)))
return distance
def calTransportCost(self):
totalDistance = self.calDistance([self.origin])[0]
if self.specialFreight:
tmpUnitWeightPrice = self.unitWeightPrice * self.priceIncreaseFactor
tmpUnitVolumePrice = self.unitVolumePrice * self.priceIncreaseFactor
else:
tmpUnitWeightPrice = self.unitWeightPrice
tmpUnitVolumePrice = self.unitVolumePrice
# calculate price after volume discount
quantityStep = np.array(sorted(self.volumeDiscount.keys()))
utilized = max(self.utilizedVolume / self.volumeCapacity * 100, self.utilizedWeight / self.weightCapacity * 100)
discount = self.volumeDiscount.get(quantityStep[sum(utilized > quantityStep) - 1])
tmpUnitWeightPrice = tmpUnitWeightPrice * (1 - discount) * totalDistance
tmpUnitVolumePrice = tmpUnitVolumePrice * (1 - discount) * totalDistance
for product in self.listOfProducts:
product.transportCost += max(product.weight * product.quantity * tmpUnitWeightPrice,
product.volume * product.quantity * tmpUnitVolumePrice)
product.transportCostForAllocation += product.transportCost
self.totalTransportCost = self.totalTransportCost + product.transportCost
def get_neighborhood(self):
return self.model.grid.get_neighborhood(
self.pos, moore = True, include_center = False)
def resetPosition(self, origin, destination):
# to reuse the vessel for simulation if there is no return trip designed in the system
self.origin = origin
self.destination = destination
self.intransit = False
self.specialFreight = False
self.listOfProducts = []
self.utilizedWeight = 0 # as absolute units
self.utilizedVolume = 0 # as absolute units
self.model.grid.move_agent(self, self.origin)
#%%
class Product(Agent):
def __init__(self, unique_id, model, quantity = 1, supplier = None,
weight = 1, volume = 1):
super().__init__(unique_id, model)
# intrinsic product characteristics
self.name = None # product code. the unique id is also with batch information.
self.weight = weight # unit weight
self.volume = volume # unit volume
self.value = 1 # unit value
self.supplier = supplier
self.decayRate = 0.001 # absolute value every time unit to subtract from shelfLifeLeft.
# when down to zero the product should be scrapped
# supply chain characteristics
self.order = None
self.deliveredQuantity = quantity # quantity originally delivered with the order
self.quantity = quantity # actual quantity (e.g. after consumption or after order split)
self.priority = 999 # the smaller the number, the higher the loading priority
self.shelfLifeLeft = 1
self.pos = None
self.intransit = False
self.warehouse = None
self.active = True # if scrapped or delivered, then active is False
self.availableInStorage = False
self.bookedForCustomer = False
self.scrapped = False
# financial characteristics
# all are total costs of the batch
self.purchaseCost = 0 # calculated by supplier
self.transportCost = 0 # calculated by spediteur
self.capitalCost = 0
self.storageCost = 0 # calculated by warehouse
self.scrapCost = 0
# dynamic costs in case of order split or consumption
self.purchaseCostForAllocation = 0 # proportional to original cost if material is consumed
self.transportCostForAllocation = 0 # proportional to original cost if material is consumed
def step(self):
if not self.active:
return
self.shelfLifeLeft = self.shelfLifeLeft - self.decayRate
def advance(self):
if self.shelfLifeLeft == 0:
self.scrapped = True
self.active = False
self.availableInStorage = False
self.calScrapCost()
self.calCapitalCost()
def move(self, new_position):
self.model.grid.move_agent(self, new_position)
self.pos = new_position
def split(self, partialQuantity):
if partialQuantity >= self.quantity:
return
product = Product(self.name + str(self.model.num_product), self.model,
quantity = partialQuantity, supplier = self.supplier,
weight = self.weight, volume = self.volume)
product.name = self.name
product.value = self.value
product.decayRate = self.decayRate # absolute value every time unit to subtract from shelfLifeLeft.
# when down to zero the product should be scrapped
# supply chain characteristics
product.order = self.order
product.priority = self.priority# the smaller the number, the higher the loading priority
product.shelfLifeLeft = self.shelfLifeLeft
product.pos = self.pos
product.intransit = self.intransit
product.warehouse = self.warehouse
product.active = self.active # if scrapped or delivered, then active is False
product.availableInStorage = self.availableInStorage
product.bookedForCustomer = self.bookedForCustomer
product.scrapped = self.scrapped
# financial characteristics
# all are total costs of the batch
product.purchaseCost = self.purchaseCost * partialQuantity / self.quantity
product.transportCost = self.transportCost * partialQuantity / self.quantity
product.capitalCost = self.capitalCost * partialQuantity / self.quantity
product.storageCost = self.storageCost * partialQuantity / self.quantity
product.scrapCost = self.scrapCost * partialQuantity / self.quantity
product.purchaseCostForAllocation = self.purchaseCostForAllocation * partialQuantity / self.quantity
product.transportCostForAllocation = self.transportCostForAllocation * partialQuantity / self.quantity
self.quantity = self.quantity - partialQuantity
self.deliveredQuantity = self.quantity
self.purchaseCost = self.purchaseCost - product.purchaseCost
self.transportCost = self.transportCost - product.transportCost
self.capitalCost = self.capitalCost - product.capitalCost
self.storageCost = self.storageCost - product.storageCost
self.scrapCost = self.scrapCost - product.scrapCost
self.purchaseCostForAllocation = self.purchaseCostForAllocation - product.purchaseCostForAllocation
self.transportCostForAllocation = self.transportCostForAllocation - product.transportCostForAllocation
self.model.schedule.add(product)
self.model.num_product = self.model.num_product + 1
self.model.grid.place_agent(product, self.pos)
return [self, product]
def calCapitalCost(self):
self.capitalCost = self.capitalCost + \
self.value * self.quantity * self.model.rules.companyInterestRate
def calScrapCost(self):
return self.value * self.quantity
#%%
class Warehouse(Agent):
def __init__(self, unique_id, model):
super().__init__(unique_id, model)
self.pos = (0, 0)
self.defaultPrice = 1
self.overCapacityPrice = 1.2
self.unitPrice = self.defaultPrice
self.capacity = 10000
self.utilization = 0
self.priceIncreaseFactor = 2
self.stackLayer = 2
self.listOfProducts = []
self.totalStorageCost = 0
def step(self):
if self.utilization > self.capacity:
self.unitPrice = self.defaultPrice
else:
self.unitPrice = self.overCapacityPrice
def advance(self):
self.calStorageCost()
def calStorageCost(self):
for product in self.listOfProducts:
if product.active:
product.storageCost = self.unitPrice / self.stackLayer * \
product.volume * product.quantity
self.totalStorageCost = self.totalStorageCost + product.storageCost
#%%
class Supplier(Agent):
def __init__(self, unique_id, model):
super().__init__(unique_id, model)
self.name = None
self.pos = (0, 0)
self.productCatalog = None
self.orders = None
self.reliability = 0.9
self.utilization = 0
self.dailyCapacity = 10000000
def calPurchaseCost(self, productName, quantity):
catalog = self.productCatalog[self.productCatalog['MATERIAL_CODE'] == productName]
discountLevel = np.array(catalog['volumeDiscountCode'])
idx = np.sum(discountLevel <= quantity) - 1
applicablePrice = np.array(catalog.loc[catalog['volumeDiscountCode'] == discountLevel[idx],'unitPrice'])[0]
return applicablePrice * quantity
def produce(self):
# TODO: add capacity constraint
if self.orders is None:
return
self.orders.index = np.arange(0, self.orders.shape[0])
openOrder = self.orders[(self.orders['RPD'] <= self.model.schedule.time) &
(self.orders['actualProductionDate'] == -1)]
openOrder.sort_values(by = 'RPD', ascending = True, inplace = True)
if openOrder.shape[0] == 0:
return
for i in range(openOrder.shape[0]):
# simulate reliability
if random.randrange(0, 100) > self.reliability * 100:
continue
line = pd.DataFrame([openOrder.iloc[i, :]])
idx = line.index
quantity = np.array(line.loc[:,'quantity'])[0]
orderID = np.array(line.loc[:,'orderID'])[0]
if self.utilization + quantity > self.dailyCapacity:
# TODO: add split-order rules
continue
productName = np.array(line.loc[:, 'MATERIAL_CODE'])[0]
record = self.model.setup.product[self.model.setup.product['MATERIAL_CODE'] == productName]
if record.shape[0] > 0:
wgt = int(np.array(record.weight)[0])
vol = int(np.array(record.volume)[0])
else:
wgt = self.model.rules.default_weight # default
vol = self.model.rules.default_volume # default
product = Product('material' + str(self.model.num_product),
self.model,
quantity = quantity,
supplier = self.unique_id,
weight = wgt,
volume = vol)
product.name = productName
product.purchaseCost += self.calPurchaseCost(product.name, product.quantity) # total purchase cost of the batch
product.purchaseCostForAllocation = product.purchaseCost
# TODO: add consideration of incoterms and its influence on price / costing
product.value = product.purchaseCost / quantity # unit value of the product
if orderID is not None:
content = self.model.grid.get_cell_list_contents(self.pos)
for order in content:
if isinstance(order, Order) and order.unique_id == orderID:
product.order = order
product.bookedForCustomer = True
product.priority = product.order.RPD
break
self.model.schedule.add(product)
self.model.grid.place_agent(product, self.pos)
self.model.num_product = self.model.num_product + 1
self.utilization = self.utilization + quantity
self.orders.loc[idx, 'actualProductionDate'] = self.model.schedule.time
def manageVMI(self):
#TODO: add vendor managed inventory
return
def readInOrders(self):
orders = [x for x in self.model.grid[self.pos[0]][self.pos[1]] if isinstance(x, Order)]
openOrders = [x for x in orders if sum(x.orderLines['quantity']) > 0]
currentOpenOrders = [x for x in openOrders if x.creationDate == self.model.schedule.time]
if len(currentOpenOrders) == 0:
return
priority = sortAgent(currentOpenOrders, 'RPD', reverse = True) # least important first to be scheduled in backwards scheduling
demand = []
for i in priority:
record = currentOpenOrders[i].orderLines.loc[:, ['MATERIAL_CODE','quantity']]
record['RPD'] = currentOpenOrders[i].RPD
record['orderID'] = currentOpenOrders[i].unique_id
if len(demand) == 0:
demand = record
else:
demand = pd.concat([demand, record], axis = 0)
demand['actualProductionDate'] = -1
self.orders = demand.copy()
def step(self):
self.readInOrders()
self.manageVMI()
self.produce()
def advance(self):
self.utilization = 0
return
class MaterialPlanner(Agent):
def __init__(self, unique_id, model, plant = None):
super().__init__(unique_id, model)
self.pos = (0, 0)
self.responsibleRawMaterial = list()
self.reliability = 0.9
self.demand = None
self.currentMaterialPlan = None
self.plant = plant
self.kpi = None
self.planningHorizon = 14
self.orderLines = None
def BOMexplosion(self):
productionPlan = self.plant.productionPlan[self.plant.productionPlan['actualProduction'] == -1]
if productionPlan.shape[0] == 0:
return
BOM = self.model.setup.BOM.copy()
BOM = BOM[~BOM['rawMaterial'].isnull()]
coln = BOM.columns.tolist()
coln[coln.index('FG')] = 'MATERIAL_CODE'
coln[coln.index('quantity')] = 'RMquantity'
BOM.columns = coln
df = productionPlan.merge(BOM, how = 'inner', on = 'MATERIAL_CODE')
df['RMrequiredQty'] = df['RMquantity'] * df['quantity']
df = df.loc[:,['plannedProduction', 'rawMaterial', 'RMrequiredQty']].groupby(
['plannedProduction', 'rawMaterial'], as_index = False).sum()
df.sort_values('plannedProduction', inplace = True)
return df
def updateMaterialPlan(self):
materialBOM = self.BOMexplosion()
respMaterialBOM = materialBOM[materialBOM['rawMaterial'].isin(self.responsibleRawMaterial)]
# match material in stock with planned production date and quantity
mat = list(set(respMaterialBOM['rawMaterial']))
content = self.model.grid[self.pos[0]][self.pos[1]]
rawMaterial = [x for x in content if isinstance(x, Product) and x.name in mat]
names = [x.name for x in rawMaterial]
qty = [x.quantity for x in rawMaterial]
df = pd.DataFrame({'rawMaterial': names, 'availableQty': qty})
df = df.groupby('rawMaterial', as_index = False).sum()
for i in range(respMaterialBOM.shape[0]):
if df.shape[0] == 0:
break
material = respMaterialBOM.iloc[i, respMaterialBOM.columns.tolist().index('rawMaterial')]
required = respMaterialBOM.iloc[i, respMaterialBOM.columns.tolist().index('RMrequiredQty')]
available = np.array(df.loc[df['rawMaterial'] == material, 'availableQty'])
if len(available) == 0:
continue
respMaterialBOM.iloc[i, respMaterialBOM.columns.tolist().index(
'RMrequiredQty')] = required - np.min([required, available])
df.loc[df['rawMaterial'] == material, 'availableQty'] = available - np.min([required, available])
if np.sum(df['availableQty']) == 0:
break
respMaterialBOM = respMaterialBOM[respMaterialBOM['RMrequiredQty'] > 0]
if respMaterialBOM.shape[0] == 0:
return
# match stock-in-transit with planned production date and quantity
inTransit = pd.DataFrame([], columns = ['rawMaterial', 'availableQty', 'CRD'])
tup = self.model.setup.supplier.apply(lambda row: (row.x, row.y),axis = 1).tolist()
content = self.model.grid.iter_cell_list_contents(tup)
matOrders = [x for x in content if isinstance(x, Order) and x.fulfilled is False]
for openOrder in matOrders:
for prod in openOrder.listOfProducts:
if not prod.pos == self.pos:
tmp = pd.DataFrame([[prod.name, prod.quantity, openOrder.CRD]],
columns = ['rawMaterial', 'availableQty', 'CRD'],
index = [inTransit.shape[0] + 1])
inTransit = pd.concat([inTransit, tmp], axis = 0)
inTransit = inTransit.groupby(['rawMaterial','CRD'], as_index = False).sum()
try:
inTransit.sort_values('CRD', inplace = True)
except KeyError:
inTransit = pd.DataFrame([], columns = ['rawMaterial', 'availableQty', 'CRD'])
for i in range(respMaterialBOM.shape[0]):
if inTransit.shape[0] == 0:
break
plannedDate = respMaterialBOM.iloc[i, respMaterialBOM.columns.tolist().index('plannedProduction')]
material = respMaterialBOM.iloc[i, respMaterialBOM.columns.tolist().index('rawMaterial')]
try:
earliestArrival = np.array(inTransit.loc[inTransit['rawMaterial'] == material, 'CRD'])[0]
except IndexError:
earliestArrival = self.model.schedule.time + self.planningHorizon + 1
# available quantity will not be offset if planned arrival is later than planned production date
if plannedDate < earliestArrival:
continue
required = respMaterialBOM.iloc[i, respMaterialBOM.columns.tolist().index('RMrequiredQty')]
available = inTransit.loc[(inTransit['rawMaterial'] == material) &
(inTransit['CRD'] <= plannedDate), 'availableQty']
respMaterialBOM.iloc[i,
respMaterialBOM.columns.tolist().index('RMrequiredQty')] = required - np.min([required, np.sum(available)])
for j in available.index:
inTransit.loc[inTransit.index == j, 'availableQty'] = available[j] - np.min([required, available[j]])
required = required - np.min([required, available[j]])
inTransit = inTransit[inTransit['availableQty'] > 0]
if inTransit.shape[0] == 0:
break
respMaterialBOM = respMaterialBOM[respMaterialBOM['RMrequiredQty'] > 0]
if respMaterialBOM.shape[0] == 0:
return
coln= respMaterialBOM.columns.tolist()
coln[coln.index('plannedProduction')] = 'CRD'
coln[coln.index('rawMaterial')] = 'MATERIAL_CODE'
coln[coln.index('RMrequiredQty')] = 'quantity'
respMaterialBOM.columns = coln
self.demand = respMaterialBOM.copy()
def placeOrder(self):
orderLines = self.demand.copy()
# determine supplier and order quantity
# TODO: add choice of supplier based on e.g. price or reliability / quality
# TODO: add ordering strategy e.g. MOQ
supplierCatalog = self.model.setup.supplierCatalog.copy()
catalog = supplierCatalog.loc[supplierCatalog['MATERIAL_CODE'].isin(orderLines['MATERIAL_CODE']),
['MATERIAL_CODE','supplierName']]
catalog.drop_duplicates(inplace = True)
check = catalog.groupby('MATERIAL_CODE').count()
multipleSource = orderLines.loc[orderLines['MATERIAL_CODE'].isin(check[check['supplierName'] > 1].index),:]
singleSource = orderLines[~orderLines.index.isin(multipleSource.index)]
singleSource = singleSource.merge(catalog, how = 'left', on = 'MATERIAL_CODE')
singleSource['origin'] = singleSource['supplierName']
singleSource.drop('supplierName', axis = 1, inplace = True)
try:
multipleSource = self.selectSupplierByCost(multipleSource)
except KeyError:
multipleSource = pd.DataFrame([], columns = singleSource.columns)
orderLines = pd.concat([singleSource, multipleSource], axis = 0)
# add columns to comply with order format in Setup.orderLines
requiredCol = self.model.setup.orderLines.columns.tolist()
orderLines['dest'] = self.plant.unique_id
# orders will be added to Setup.orderLines and will be created by
# SupplyChainModel.createOrder() in the next model.schedule.step()
orderLines['orderCreateDate'] = self.model.schedule.time + 1
orderLines = orderLines.loc[:, requiredCol]
# create orders within planning horizon. rest is forecast and only stored in MaterialPlanner.orderLines
if self.orderLines is None:
previousOrders = pd.DataFrame([], columns = orderLines.columns)
else:
previousOrders = self.orderLines.loc[self.orderLines['CRD'] <= self.model.schedule.time + self.planningHorizon]
self.orderLines = orderLines.copy()
# only pass delta to the supplier.
# the last day within planning horizon (model.schedule.time + MaterialPlanner.planningHorizon + 1) is full order
coln= previousOrders.columns.tolist()
coln[coln.index('quantity')] = 'oldQty'
previousOrders.columns = coln
previousOrders.drop('orderCreateDate', axis = 1, inplace = True)
orderLines.drop('orderCreateDate', axis = 1, inplace = True)
groupCol = orderLines.columns.tolist()
groupCol.remove('quantity')
delta = orderLines.merge(previousOrders, on = groupCol, how = 'outer')
delta.fillna(0, inplace = True)
# delta is one day longer than previousOrders, therefore the last day of planningHorizon is with
# full order quantity from the new orderLines.
delta = delta[delta['CRD'] <= self.model.schedule.time + self.planningHorizon + 1]
# delete consumed amount in the day's production
presentDay = delta[delta['CRD'] == self.model.schedule.time]
future = delta[delta['CRD'] > self.model.schedule.time]
future['quantity'] = future['quantity'] - future['oldQty']
delta = pd.concat([presentDay, future], axis = 0)
delta.drop('oldQty', axis = 1, inplace = True)
# check if there are changes within frozen period
# TODO: decide if to use special freight when there is demand increase within frozen period
reducedDemand = delta.loc[(delta['CRD'] <= self.model.schedule.time + self.planningHorizon) &
(delta['quantity'] < 0), :]
delta = delta[~delta.index.isin(reducedDemand.index)]
reducedDemand['CRD'] = self.model.schedule.time + self.planningHorizon + 1
delta = pd.concat([delta, reducedDemand], axis = 0)
delta['orderCreateDate'] = self.model.schedule.time + 1
delta = delta[delta['quantity'] != 0]
delta['type'] = 'materialOrder'
self.model.setup.orderLines = pd.concat([self.model.setup.orderLines, delta], axis = 0)
def selectSupplierByCost(self, _orderLines, minObs = 5):
groupCol = _orderLines.columns.tolist()
groupCol.remove('quantity')
orderLines = _orderLines.groupby(groupCol).sum()
material = list(set(orderLines['MATERIAL_CODE']))
supplierCatalog = self.model.setup.supplier
result = []
for i in range(len(material)):
mat = [x for x in self.model.schedule.agents if
isinstance(x, Product) and
x.name == material[i] and
x.supplier is not None and
x.purchaseCost > 0 and
x.transportCost > 0]
tmp = orderLines[orderLines['MATERIAL_CODE'] == material[i]]
# check if there are new suppliers
availableSupplier = set(supplierCatalog.loc[supplierCatalog['MATERIAL_CODE'] == material[i], 'supplierName'])
sup = [x.supplier for x in mat]
counter = Counter(sup)
# if there are new suppliers which have no previous delivery, or if minimum observation point (number of
# orders per supplier) is smaller than minObs, then randomly select one supplier from available suppliers
if min(counter.values()) < minObs or len(availableSupplier - set(sup)) > 0:
availableSupplier = list(availableSupplier)
tmp['origin'] = tmp.apply(lambda row: availableSupplier[random.randint(0, len(availableSupplier) - 1)], axis = 1)
if len(result) == 0:
result = tmp.copy()
else:
result = pd.concat([result, tmp], axis = 1)
continue
# if there are enough observation points to do regression
availableSupplier = list(availableSupplier)
crd = [x.order.CRD for x in mat]
crd = list(map(int, crd))
qty = [x.deliveredQuantity for x in mat]
cost = [x.purchaseCost + x.transportCost for x in mat]
hist = pd.DataFrame({'CRD': crd,'quantity': qty,'supplierName': sup,'cost': cost})
hist = pd.get_dummies(hist)
fcst = pd.DataFrame([], columns = hist.columns)
for j in range(len(availableSupplier)):
tmp0 = tmp.copy()
tmp0['supplierName'] = availableSupplier[j]
tmp0['cost'] = 0
tmp0 = pd.get_dummies(tmp0)
tmp0 = tmp0.loc[:, hist.columns]
fcst = pd.concat([fcst, tmp0], axis = 0)
fcst.fillna(0, inplace = True)
# regress to find cost for specific suppliers
coln = hist.columns.tolist()
coln.remove('cost')
coln.remove('CRD')
lrmodel = lr()
modelfit = lrmodel.fit(hist.loc[:, coln], hist.loc[:, 'cost'])
pred = modelfit.predict(fcst.loc[:, coln])
fcst['cost'] = pred
# sort by lowest cost first, and return supplier with lowest cost
fcst.sort_values(['CRD','cost'], inplace = True)
fcst = fcst.groupby(['CRD', 'quantity'], as_index = False).first()
# get supplier name from one-hot dummies
pos = fcst.iloc[:, -len(availableSupplier):]
fcst['origin'] = pos.apply(lambda row: availableSupplier[row.tolist().index(1)], axis= 1)
tmp = tmp.merge(fcst.loc[:, ['CRD','quantity', 'origin']],
how = 'left', on = ['CRD','quantity'])
if len(result) == 0:
result = tmp.copy()
else:
result = pd.concat([result, tmp], axis = 1)
return result
def step(self):
return
def advance(self):
self.productionPlan = self.plant.productionPlan.copy()
self.updateMaterialPlan()
self.placeOrder()
#%%
class MarketPlanner(Agent):
def __init__(self, unique_id, model, whs = None):
super().__init__(unique_id, model)
self.pos = (0, 0)
self.responsibleProductGroup = list()
self.responsibleRegion = list()
self.reliability = 0.9
self.marketplanDir = None # folder where all historical plans are
self.currentMarketPlan = None
self.whs = whs
self.kpi = None
self.planningInterval = 15
self.planningHorizon = 25 # minumum planning horizon, within which the market plan is not considered
def step(self):
# TODO: schedule market planning to once per month
if np.mod(self.model.schedule.time, self.planningInterval) == 0:
self.updatePlan()
self.passOrder()
def advance(self):
self.kpi = self.calKpi()
def updatePlan(self):
'''
update market plan.
forecast algorithm can be plugged in here as one option.
'''
# read in previous forecast
try:
previousPlan = pd.read_csv(self.marketplanDir + 'marketPlan_' +
str(self.model.schedule.time - self.planningInterval) + '.csv')
except FileNotFoundError:
previousPlan = self.currentMarketPlan
coln = ['originRegion','destRegion','forecastProduct','CRD','customer']
previousPlan = previousPlan.loc[:,coln + ['quantity']]
previousPlan.columns = coln + ['oldQuantity']
# create current forecast.
# here run whatever algorithm
# TODO: add the whatever algorithm
# for simulation purpose: no update of market plan
try:
self.currentMarketPlan = pd.read_csv(self.marketplanDir + 'marketPlan_' +
str(self.model.schedule.time) + '.csv')
self.currentMarketPlan['createDate'] = self.model.schedule.time
# write to disk the complete current market plan
self.currentMarketPlan.to_csv(self.marketplanDir + 'marketPlan_' +
str(self.model.schedule.time) + '.csv', index = False)
# pass on the delta market plan
delta = self.currentMarketPlan.merge(previousPlan, how = 'outer', on = coln)
delta.fillna(0, inplace = True)
delta['quantity'] = delta['quantity'] - delta['oldQuantity']
delta.drop('oldQuantity', axis = 1, inplace = True)
self.currentMarketPlan = delta.copy()
except FileNotFoundError:
self.currentMarketPlan['quantity'] = 0
def calKpi(self):
'''
get business KPI value
'''
#TODO: add kpi calculation methods
return 'NA'
def passOrder(self):
'''
split order and give order to corresponding production scheduler
planningHorizon:
earliest RPD date from current date to consider long term market planning.
any time unit before the planning horizon does not take market planning as reference,
but actual orders.
'''
currentPlan = self.currentMarketPlan[(self.currentMarketPlan['destRegion'].isin(self.responsibleRegion)) &
(self.currentMarketPlan['forecastProduct'].isin(self.responsibleProductGroup)) &
(self.currentMarketPlan['RPD'] >= self.model.schedule.time + self.planningHorizon) &
(self.currentMarketPlan['quantity'] != 0)]
groups = currentPlan.groupby('originRegion')
plants = self.model.setup.plant.copy()
for region in set(currentPlan['originRegion']):
x = int(plants.loc[(plants['plantRegion'] == region), 'x'])
y = int(plants.loc[(plants['plantRegion'] == region), 'y'])
plan = groups.get_group(region)
plan['RPD'] = plan['RPD'].apply(int)
content = self.model.grid[x][y]
productionscheduler = [x for x in content if isinstance(x, ProductionScheduler)]
productionscheduler = productionscheduler[0]
if productionscheduler.marketPlan.shape[0] > 0:
productionscheduler.marketPlan = pd.concat([productionscheduler.marketPlan,plan], axis = 0)
else:
productionscheduler.marketPlan = plan
class Order(Agent):
def __init__(self, unique_id, model, orderLines):
super().__init__(unique_id, model)
self.name = 'customerOrder'
self.pos = (0, 0)
self.listOfProducts = []
self.orderLines = orderLines.copy() # list of product names and quantities
self.originRegion = np.array(self.getFirstLine(orderLines)['origin'])[0]
self.destRegion = np.array(self.getFirstLine(orderLines)['dest'])[0]
self.creationDate = np.array(self.getFirstLine(orderLines)['orderCreateDate'])[0]
self.CRD = np.array(self.getFirstLine(orderLines)['CRD'])[0]
self.RPD = None
self.ASD = None
self.ATA = None
self.productAllocatedToOrder = False
self.fulfilled = False
self.onTimeInFull = False
self.specialFreight = False
def getFirstLine(self, orderLines):
if orderLines.shape[0] == 1:
return orderLines
else:
return pd.DataFrame([orderLines.iloc[0,:]])
def fulfillOrder(self):
self.fulfilled = True
self.ATA = self.model.schedule.time
if self.ATA <= self.CRD:
self.onTimeInFull = True
for product in self.listOfProducts:
product.active = False
product.availableInStorage = False
def step(self):
if self.fulfilled:
return
self.productAllocatedToOrder = np.sum(self.orderLines['quantity']) == 0
if (self.productAllocatedToOrder) and (self.ASD is None):
# set actual shipping date to when product becomes available for the order
self.ASD = self.model.schedule.time
availability = [x.availableInStorage for x in self.listOfProducts]
if (self.productAllocatedToOrder) and (np.all(availability)):
self.fulfillOrder()
def advance(self):
return
#%%
class ProductionScheduler(Agent):
def __init__(self, unique_id, model, plantAgent):
super().__init__(unique_id, model)
self.pos = (0, 0)
self.productionPlan = pd.DataFrame([]) # final production plan as passed on to plant production
self.plant = plantAgent
self.marketPlan = pd.DataFrame([]) # original as per market planner
self.productionPlanDir = None
self.reliability = 0.9
self.capacityRedLight = list()
self.fulfillmentRedLight = list()
self.minProdBatch = 100
self.availCap = 0.8 # capacity upper limit for planning
self.scheduleNonAdherence = 0 # number of planned production orders which are not executed as planned
def readInOrders(self):
orders = [x for x in self.model.grid[self.pos[0]][self.pos[1]] if isinstance(x, Order)]
openOrders = [x for x in orders if sum(x.orderLines['quantity']) > 0]
currentOpenOrders = [x for x in openOrders if x.creationDate == self.model.schedule.time]
if len(currentOpenOrders) == 0:
return
priority = sortAgent(currentOpenOrders, 'RPD', reverse = True) # least important first to be scheduled in backwards scheduling
plan = self.productionPlan.copy()
for i in priority:
line = pd.DataFrame([], columns = self.productionPlan.columns.tolist())
for row in range(currentOpenOrders[i].orderLines.shape[0]):
record = currentOpenOrders[i].orderLines.iloc[row, :]
line['MATERIAL_CODE'] = [record['MATERIAL_CODE']]
line['createDate'] = [self.model.schedule.time]
line['RPD'] = [currentOpenOrders[i].RPD]
line['priority'] = [999]
line['customerOrder'] = [currentOpenOrders[i].unique_id]
line['actualProduction'] = [-1]
line['quantity'] = [int(record['quantity'] / self.minProdBatch) * self.minProdBatch]
line['plannedProduction'] = [self.model.schedule.time]
# backwards planning. check if the day is already overcapacity. if so, go backwards one more day for more capacity.
if currentOpenOrders[i].RPD <= self.model.schedule.time:
# TODO: warning system and corresponding mitigation to be defined.
self.fulfillmentRedLight.append(currentOpenOrders[i].unique_id)
else:
for i in np.arange(1, currentOpenOrders[i].RPD - self.model.schedule.time):
# backwards planning to search for capacity until current time unit.
if (sum(plan.loc[plan['plannedProduction'] == currentOpenOrders[i].RPD - i,
'quantity']) + np.array(line['quantity'])[0]) > self.plant.dailyCapacity:
continue
else:
line['plannedProduction'] = [currentOpenOrders[i].RPD - i]
break
plan = pd.concat([plan, line])
if sum(plan.loc[plan['plannedProduction'] == self.model.schedule.time,
'quantity']) > self.plant.dailyCapacity:
# TODO: warning system and corresponding mitigation to be defined.
self.capacityRedLight.append(self.model.schedule.time)
self.productionPlan = plan.copy()
def getFinishedGoodsRatio(self, cutoffDays = 120):
group = self.model.setup.orderLines[self.model.schedule.time -
self.model.setup.orderLines['orderCreateDate'] <= cutoffDays].groupby(
'MATERIAL_CODE', as_index = False).sum()
matchingTbl = self.model.setup.productHierarchy
group = group.merge(matchingTbl, on = 'MATERIAL_CODE', how = 'left')
bigGroup = group.groupby('forecastProduct', as_index = False).sum()
bigGroup = bigGroup.loc[:, ['forecastProduct', 'quantity']]
bigGroup.columns = ['forecastProduct', 'totalQuantity']
group = group.merge(bigGroup, on = 'forecastProduct', how = 'left')
group['ratio'] = group.apply(lambda row: row['quantity'] / row['totalQuantity'], axis = 1)
return group.loc[:, ['MATERIAL_CODE','ratio']]
def splitMarketPlan(self, cutoffDays = 120, planUnit = 'monthly'):
'''
split market plans to production quantity per time unit, same format as production plan
available capacity:
daily capacity upper limit to plan for long-term market forecast.
0.8 means 80% of self.plant.dailyCapacity will be planned for market forecast.
cutoffDays:
number of days in history to take as reference for detailed MATERIAL_CODE level
quantity split.
output: new production plan with market forecast included
'''
if self.marketPlan.shape[0] == 0:
return
# TODO: add other market plan split rules
planningInterval = 30 # default is monthly
if planUnit == 'weekly':
planningInterval = 7
if planUnit == 'seasonal':
planningInterval = 90
if planUnit == 'annual':
planningInterval = 365
ratio = self.getFinishedGoodsRatio(cutoffDays)
group = self.marketPlan.groupby(['RPD','forecastProduct'], as_index = False).sum()
colnames = group.columns.tolist()
colnames[colnames.index('quantity')] = 'totalQuantity'
group.columns = colnames
matchingTbl = self.model.setup.productHierarchy.copy()
group = group.merge(matchingTbl, how = 'left', on = 'forecastProduct')
group = group.merge(ratio, how = 'left', on = 'MATERIAL_CODE')
group['quantity'] = group['totalQuantity'] * group['ratio']
group['quantity'] = group['quantity'].apply(int)
group = group.loc[:, ['RPD','MATERIAL_CODE', 'quantity']]
dailyCap = self.plant.dailyCapacity * self.availCap
plan = self.productionPlan.copy()
for dueDate in set(group['RPD']):
rpdGroup = group[group['RPD'] == dueDate]
totalPlanned = np.sum(rpdGroup['quantity'])
nrPeriods = int(np.ceil(totalPlanned / dailyCap))
if nrPeriods > planningInterval:
#TODO: warning system and corresponding mitigation to be defined.
self.capacityRedLight.append(dueDate)
for prod in rpdGroup['MATERIAL_CODE'].tolist():
quantityToBePlanned = np.array(rpdGroup.loc[rpdGroup['MATERIAL_CODE'] == prod, 'quantity'])[0]
quantityLeft = quantityToBePlanned
if quantityLeft < 0:
# reduced forecast: delta passed from market planner is negative
_quantityLeft = int(np.abs(quantityLeft) / self.minProdBatch) * self.minProdBatch
for j in range(dueDate - self.model.schedule.time - 1):
if _quantityLeft <= 0:
break
record = plan.loc[(plan['MATERIAL_CODE'] == prod) &
(plan['plannedProduction'] == dueDate - j) &
(plan['customerOrder'] == -1) &
(plan['actualProduction'] == -1),:]
if record.shape[0] == 0:
continue
for k in range(record.shape[0]):
qty = record.iloc[k, record.columns.tolist().index('quantity')]
record.iloc[k, record.columns.tolist().index('quantity')] = np.max([0, qty - _quantityLeft])
_quantityLeft = _quantityLeft - qty
if _quantityLeft <= 0:
break
plan.loc[plan.index.isin(record.index),'quantity'] = record['quantity']
plan.loc[plan.index.isin(record.index),'actualProduction'] = -99
for i in range(dueDate - self.model.schedule.time - 1):
# check if all required quantity for the specific material and RPD are planned
# because of the round-up to minimum production batch, quantity may be all planned in less than nrPeriods.
if quantityLeft <= 0:
break
line = pd.DataFrame([], columns = self.productionPlan.columns.tolist())
line['MATERIAL_CODE'] = [prod]
line['createDate'] = [self.model.schedule.time]
line['plannedProduction'] = [dueDate - i - 1]
line['RPD'] = [dueDate - i]
line['priority'] = [999]
line['customerOrder'] = [-1]
line['actualProduction'] = [-1]
qty = int(np.ceil(quantityToBePlanned / planningInterval / self.minProdBatch)) * self.minProdBatch
if quantityLeft < qty - self.minProdBatch:
line['quantity'] = [int(np.ceil(quantityLeft / self.minProdBatch)) * self.minProdBatch]
else:
line['quantity'] = [qty]
# backwards planning. check if the day is already overcapacity. if so, go backwards one more day for more capacity.
if (sum(plan.loc[plan['plannedProduction'] == dueDate - i - 1,'quantity']) + np.array(line['quantity'])[0]) >= self.plant.dailyCapacity:
# if backwards planning has planned more than 30 days back:
if i >= 30: