-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer.cpp
More file actions
1373 lines (1257 loc) · 49.6 KB
/
Copy pathbuffer.cpp
File metadata and controls
1373 lines (1257 loc) · 49.6 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
/***************************************************************************
* *
* Copyright (C) 2007-2015 by frePPLe bv *
* *
* Permission is hereby granted, free of charge, to any person obtaining *
* a copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to *
* the following conditions: *
* *
* The above copyright notice and this permission notice shall be *
* included in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE *
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION *
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION *
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
***************************************************************************/
#include "frepple/model.h"
namespace frepple {
template <class Buffer>
Tree utils::HasName<Buffer>::st;
const MetaCategory* Buffer::metadata;
const MetaClass *BufferDefault::metadata, *BufferInfinite::metadata,
*OperationInventory::metadata, *OperationDelivery::metadata;
OperationFixedTime* Buffer::uninitializedProducing = nullptr;
int Buffer::initialize() {
// Initialize the metadata
metadata = MetaCategory::registerCategory<Buffer>("buffer", "buffers", reader,
finder);
registerFields<Buffer>(const_cast<MetaCategory*>(metadata));
uninitializedProducing = new OperationFixedTime();
// Initialize the Python class
auto& x = FreppleCategory<Buffer>::getPythonType();
x.addMethod("decoupledLeadTime", &getDecoupledLeadTimePython, METH_VARARGS,
"return the decoupled lead time");
x.addMethod("availableonhand", &availableOnhandPython, METH_VARARGS,
"return the available onhand at a specific date");
x.addMethod("inspect", inspectPython, METH_VARARGS,
"debugging function to print the inventory profile");
return FreppleCategory<Buffer>::initialize();
}
int BufferDefault::initialize() {
// Initialize the metadata
BufferDefault::metadata = MetaClass::registerClass<BufferDefault>(
"buffer", "buffer_default", Object::create<BufferDefault>, true);
// Initialize the Python class
return FreppleClass<BufferDefault, Buffer>::initialize();
}
int BufferInfinite::initialize() {
// Initialize the metadata
metadata = MetaClass::registerClass<BufferInfinite>(
"buffer", "buffer_infinite", Object::create<BufferInfinite>);
// Initialize the Python class
return FreppleClass<BufferInfinite, Buffer>::initialize();
}
int OperationInventory::initialize() {
// Initialize the metadata
metadata = MetaClass::registerClass<OperationInventory>(
"operation", "operation_inventory");
registerFields<OperationInventory>(const_cast<MetaClass*>(metadata));
// Initialize the Python class
auto& x = FreppleCategory<OperationInventory>::getPythonType();
x.setName("operation_inventory");
x.setDoc("frePPLe operation_inventory");
x.supportgetattro();
x.supportsetattro();
x.addMethod("decoupledLeadTime", &getDecoupledLeadTimePython, METH_VARARGS,
"return the total lead time");
x.addMethod("setFence", &setFencePython, METH_VARARGS,
"Update the fence based on date");
x.addMethod("getFence", &getFencePython, METH_NOARGS,
"Retrieve the fence date");
metadata->setPythonClass(x);
return x.typeReady();
}
int OperationDelivery::initialize() {
// Initialize the metadata
metadata = MetaClass::registerClass<OperationDelivery>(
"operation", "operation_delivery", Object::create<OperationDelivery>);
registerFields<OperationDelivery>(const_cast<MetaClass*>(metadata));
// Initialize the Python class
auto& x = PythonExtension<
FreppleClass<OperationDelivery, Operation>>::getPythonType();
x.addMethod("decoupledLeadTime", &getDecoupledLeadTimePython, METH_VARARGS,
"return the total lead time");
x.addMethod("setFence", &setFencePython, METH_VARARGS,
"Update the fence based on date");
x.addMethod("getFence", &getFencePython, METH_NOARGS,
"Retrieve the fence date");
return FreppleClass<OperationDelivery, Operation>::initialize();
}
OperationDelivery::OperationDelivery() {
setHidden(true);
setDetectProblems(false);
// When we set the size minimum to 0 for the automatically created
// delivery operations, they will be constrained by the minimum shipment
// size specified on the demand.
setSizeMinimum(0.0);
initType(metadata);
setDuration(Demand::getDefaultDeliveryDuration());
}
void OperationDelivery::setBuffer(Buffer* buf) {
// Validate the input
if (getBuffer() == buf)
return;
else if (!buf)
throw DataException("A delivery operation can't point to a null buffer");
else if (getBuffer())
throw DataException("Buffer can be set only once on a delivery operation");
// Update the operation
setName("Ship " + string(buf->getName()));
setLocation(buf->getLocation());
// Add a flow consuming from the buffer
new FlowStart(this, buf, -1);
}
Buffer* OperationDelivery::getBuffer() const {
auto tmp = getFlows().begin();
return tmp == getFlows().end() ? nullptr : tmp->getBuffer();
}
void Buffer::inspect(const string& msg, const short i) const {
indent indentstring(i);
logger << indentstring << " Inspecting buffer " << getName() << ": ";
if (!msg.empty()) logger << msg;
logger << '\n';
double curmin = 0.0;
double curmax = 0.0;
for (const auto& oo : getFlowPlans()) {
if (oo.getEventType() == 3)
curmin = oo.getMin();
else if (oo.getEventType() == 4)
curmax = oo.getMax();
logger << indentstring << " " << oo.getDate()
<< " qty:" << oo.getQuantity() << ", oh:" << oo.getOnhand();
if (curmin) logger << ", min:" << curmin;
if (curmax) logger << ", max:" << curmax;
switch (oo.getEventType()) {
case 1:
logger << ", " << oo.getOperationPlan() << '\n';
break;
case 2:
logger << ", set onhand to " << oo.getOnhand() << '\n';
break;
case 3:
logger << ", update minimum to " << oo.getMin() << '\n';
break;
case 4:
logger << ", update maximum to " << oo.getMax() << '\n';
}
}
}
PyObject* Buffer::inspectPython(PyObject* self, PyObject* args) {
try {
// Pick up the buffer
Buffer* buf = nullptr;
PythonData c(self);
if (c.check(Buffer::metadata))
buf = static_cast<Buffer*>(self);
else
throw LogicException("Invalid buffer type");
// Parse the argument
char* msg = nullptr;
if (!PyArg_ParseTuple(args, "|s:inspect", &msg)) return nullptr;
buf->inspect(msg ? msg : "");
return Py_BuildValue("");
} catch (...) {
PythonType::evalException();
return nullptr;
}
}
void Buffer::setItem(Item* i, bool recompute) {
if (it == i)
// No change
return;
// Unlink from previous item
if (it) {
if (it->firstItemBuffer == this)
it->firstItemBuffer = nextItemBuffer;
else {
Buffer* buf = it->firstItemBuffer;
while (buf && buf->nextItemBuffer != this) buf = buf->nextItemBuffer;
if (!buf) throw LogicException("corrupted buffer list for an item");
buf->nextItemBuffer = nextItemBuffer;
}
}
// Link at new item
it = i;
if (it) {
nextItemBuffer = it->firstItemBuffer;
it->firstItemBuffer = this;
}
// Mark changed
setChanged();
if (recompute) HasLevel::triggerLazyRecomputation();
}
void Buffer::setOnHand(double f) {
// The dummy operation to model the inventory may need to be created
Operation* o = Operation::find("Inventory " + string(getName()));
Flow* fl;
if (!o) {
// Stop here if the quantity is 0
if (!f) return;
// Create a fixed time operation with zero leadtime, hidden from the xml
// output, hidden for the solver, and without problem detection.
o = new OperationInventory(this);
fl = new FlowEnd(o, this, 1);
} else
// Find the flow of this operation
fl = const_cast<Flow*>(&*(o->getFlows().begin()));
// Check valid pointers
if (!fl || !o)
throw LogicException("Failed creating inventory operation for '" +
getName() + "'");
// Make sure the sign of the flow is correct: +1 or -1.
fl->setQuantity(f >= 0.0 ? 1.0 : -1.0);
// Create a dummy operationplan on the inventory operation
OperationPlan::iterator i(o);
if (i == OperationPlan::end()) {
// No operationplan exists yet
auto opplan = o->createOperationPlan(fabs(f), Date::infinitePast,
Date::infinitePast, getBatch());
opplan->setClosed(true);
opplan->activate();
opplan->setRawReference(getName());
} else {
// Update the existing operationplan
i->setClosed(false);
i->setQuantity(fabs(f));
i->setClosed(true);
}
setChanged();
}
OperationInventory::OperationInventory(Buffer* buf) {
setName("Inventory " + string(buf->getName()));
setHidden(true);
setDetectProblems(false);
setSizeMinimum(0);
initType(metadata);
}
Buffer* OperationInventory::getBuffer() const {
return getFlows().begin()->getBuffer();
}
double Buffer::getOnHand() const {
string invop = "Inventory " + string(getName());
for (const auto& flowplan : flowplans) {
if (flowplan.getDate())
return 0.0; // Inventory event is always at start of horizon
if (flowplan.getEventType() != 1) continue;
const auto* fp = static_cast<const FlowPlan*>(&flowplan);
if (fp->getFlow()->getOperation()->getName() == invop &&
fabs(fp->getQuantity()) > ROUNDING_ERROR)
return fp->getQuantity();
}
return 0.0;
}
double Buffer::getOnHand(Date d, bool after) const {
if (d == Date::infiniteFuture) {
auto tmp = flowplans.rbegin();
return tmp == flowplans.end() ? 0.0 : tmp->getOnhand();
}
double tmp(0.0);
for (const auto& flowplan : flowplans) {
if ((after && flowplan.getDate() > d) ||
(!after && flowplan.getDate() >= d))
// Found a flowplan with a later date.
// Return the onhand after the previous flowplan.
return tmp;
tmp = flowplan.getOnhand();
}
// Found no flowplan: either we have specified a date later than the
// last flowplan, either there are no flowplans at all.
return tmp;
}
double Buffer::getOnHand(Date d1, Date d2, bool min, bool use_safetystock,
bool include_proposed_po) const {
// Swap parameters if required
if (d2 < d1) swap(d1, d2);
// Loop through all flowplans
double tmp(0.0), record(0.0), safetystock(0.0), proposed_po(0.0);
Date d, prev_Date;
for (auto oo = flowplans.begin(); true; ++oo) {
if (oo == flowplans.end() || oo->getDate() > d) {
// Date has now changed or we have arrived at the end
if (prev_Date <= d1)
// Not in active Date range: we simply follow the onhand profile
record = tmp;
else {
// In the active range: check if new record
if (min) {
if (tmp < record) record = tmp;
} else {
if (tmp > record) record = tmp;
}
}
// Are we done now?
if (prev_Date > d2 || oo == flowplans.end()) return record;
d = oo->getDate();
}
// new safety stock value
if (use_safetystock && oo->getEventType() == 3) safetystock = oo->getMin();
// Proposed purchase orders special case
if (oo != flowplans.end()) {
auto opplan = oo->getOperationPlan();
if (opplan && oo->getQuantity() > 0.0 && opplan->getProposed() &&
opplan->getOperation()->hasType<OperationItemSupplier>())
proposed_po += oo->getQuantity();
}
tmp = oo->getOnhand() - (use_safetystock ? safetystock : 0);
if (!include_proposed_po) tmp -= proposed_po;
prev_Date = oo->getDate();
}
// The above for-loop controls the exit. This line of code is never reached.
throw LogicException("Unreachable code reached");
}
void Buffer::setMinimum(double m) {
// There is already a minimum calendar.
if (min_cal) {
// We update the field, but don't use it yet.
min_val = m;
return;
}
// Mark as changed
setChanged();
// Set field
min_val = m;
// Create or update a single timeline min event
for (auto& flowplan : flowplans)
if (flowplan.getEventType() == 3) {
// Update existing event
static_cast<flowplanlist::EventMinQuantity*>(&flowplan)->setMin(min_val);
return;
}
// Create new event
auto newEvent = new flowplanlist::EventMinQuantity(
Plan::instance().getCurrent(), &flowplans, min_val);
flowplans.insert(newEvent);
}
void Buffer::setMinimumCalendar(Calendar* cal) {
// Resetting the same calendar
if (min_cal == cal) return;
// Mark as changed
setChanged();
// Delete previous events.
for (auto oo = flowplans.begin(); oo != flowplans.end();) {
flowplanlist::Event* tmp = &*oo;
++oo;
if (tmp->getEventType() == 3) {
flowplans.erase(tmp);
delete tmp;
}
}
// Null pointer passed. Change back to time independent min.
if (!cal) {
min_cal = nullptr;
setMinimum(min_val);
return;
}
// Create timeline structures for every event. A new entry is created only
// when the value changes.
min_cal = cal;
double curMin = 0.0;
for (Calendar::EventIterator x(min_cal); x.getDate() < Date::infiniteFuture;
++x)
if (curMin != x.getValue()) {
curMin = x.getValue();
auto* newBucket =
new flowplanlist::EventMinQuantity(x.getDate(), &flowplans, curMin);
flowplans.insert(newBucket);
}
min_cal->clearEventList();
}
void Buffer::setMaximum(double m) {
// There is already a maximum calendar.
if (max_cal) {
// We update the field, but don't use it yet.
max_val = m;
return;
}
// Mark as changed
setChanged();
// Set field
max_val = m;
// Create or update a single timeline max event
for (auto oo = flowplans.begin(); oo != flowplans.end(); oo++)
if (oo->getEventType() == 4) {
if (max_val > ROUNDING_ERROR) {
// Update existing event
static_cast<flowplanlist::EventMaxQuantity*>(&*oo)->setMax(max_val);
} else {
// Delete existing event
flowplans.erase(&(*oo));
delete &(*(oo++));
}
return;
}
// Create new event
if (max_val > ROUNDING_ERROR) {
auto newEvent = new flowplanlist::EventMaxQuantity(
Plan::instance().getCurrent(), &flowplans, max_val);
flowplans.insert(newEvent);
}
}
void Buffer::setMaximumCalendar(Calendar* cal) {
// Resetting the same calendar
if (max_cal == cal) return;
// Mark as changed
setChanged();
// Delete previous events.
for (auto oo = flowplans.begin(); oo != flowplans.end();)
if (oo->getEventType() == 4) {
flowplans.erase(&(*oo));
delete &(*(oo++));
} else
++oo;
// Null pointer passed. Change back to time independent max.
if (!cal) {
setMaximum(max_val);
return;
}
// Create timeline structures for every bucket. A new entry is created only
// when the value changes.
max_cal = cal;
double curMax = 0.0;
for (Calendar::EventIterator x(max_cal); x.getDate() < Date::infiniteFuture;
++x)
if (curMax != x.getValue()) {
curMax = x.getValue();
auto* newBucket =
new flowplanlist::EventMaxQuantity(x.getDate(), &flowplans, curMax);
flowplans.insert(newBucket);
}
max_cal->clearEventList();
}
void Buffer::deleteOperationPlans(bool deleteLocked) {
// Delete the operationplans
for (auto& flow : flows)
OperationPlan::deleteOperationPlans(flow.getOperation(), deleteLocked);
// Mark to recompute the problems
setChanged();
}
Buffer::~Buffer() {
// Delete all operationplans.
// An alternative logic would be to delete only the flowplans for this
// buffer and leave the rest of the plan untouched. The currently
// implemented method is way more drastic...
deleteOperationPlans(true);
// The Flow objects are automatically deleted by the destructor of the
// Association list class.
// Unlink from the item
if (it) {
if (it->firstItemBuffer == this)
it->firstItemBuffer = nextItemBuffer;
else {
Buffer* buf = it->firstItemBuffer;
while (buf && buf->nextItemBuffer != this) buf = buf->nextItemBuffer;
if (!buf)
logger << "Error: Corrupted buffer list for an item\n";
else
buf->nextItemBuffer = nextItemBuffer;
}
}
// Remove the inventory operation
Operation* invoper = Operation::find("Inventory " + string(getName()));
if (invoper) delete invoper;
// Problems are automatically deleted by the HasProblem class.
// Constraints need to be cleared explicitly.
Problem::clearConstraints(*this);
}
void Buffer::followPegging(PeggingIterator& iter, FlowPlan* curflowplan,
double qty, double offset, short lvl) {
if (!curflowplan->getOperationPlan()->getQuantity() ||
curflowplan->getBuffer()->getTool())
// Flowplans with quantity 0 have no pegging.
// Flowplans for buffers representing tools have no pegging either.
return;
// Did we reach the maximum depth we want to visit
if (iter.getMaxLevel() != -1 && lvl > iter.getMaxLevel()) return;
if (curflowplan->getBuffer()->hasType<BufferInfinite>() &&
((curflowplan->getQuantity() < 0 && !iter.isDownstream()) ||
(curflowplan->getQuantity() > 0 && iter.isDownstream())))
// No pegging across infinite buffers
return;
Buffer::flowplanlist::iterator f = getFlowPlans().begin(curflowplan);
if (curflowplan->getQuantity() < -ROUNDING_ERROR && !iter.isDownstream()) {
// CASE 1:
// This is a flowplan consuming from a buffer. Navigating upstream means
// finding the flowplans producing this consumed material.
double scale = -curflowplan->getQuantity() /
curflowplan->getOperationPlan()->getQuantity();
double startQty =
f->getCumulativeConsumed() + f->getQuantity() + offset * scale;
double endQty = startQty + qty * scale;
if (f->getCumulativeProduced() <= startQty + ROUNDING_ERROR) {
// CASE 1A: Not produced enough yet: move forward
while (f != getFlowPlans().end() &&
f->getCumulativeProduced() <= startQty)
++f;
while (f != getFlowPlans().end() &&
((f->getQuantity() <= 0 && f->getCumulativeProduced() < endQty) ||
(f->getQuantity() > 0 &&
f->getCumulativeProduced() - f->getQuantity() < endQty))) {
if (f->getQuantity() > ROUNDING_ERROR) {
double newqty = f->getQuantity();
double newoffset = 0.0;
if (f->getCumulativeProduced() - f->getQuantity() < startQty) {
newoffset =
startQty - (f->getCumulativeProduced() - f->getQuantity());
newqty -= newoffset;
}
if (f->getCumulativeProduced() > endQty)
newqty -= f->getCumulativeProduced() - endQty;
OperationPlan* opplan =
dynamic_cast<const FlowPlan*>(&(*f))->getOperationPlan();
OperationPlan* topopplan = opplan->getTopOwner();
if (topopplan->getOperation()->hasType<OperationSplit>() ||
(iter.getMaxLevel() > 0))
if (opplan->getOwner() &&
opplan->getOwner()
->getOperation()
->hasType<OperationRouting>() &&
!(iter.getMaxLevel() > 0))
topopplan = opplan->getOwner();
else
topopplan = opplan;
iter.updateStack(
topopplan, topopplan->getQuantity() * newqty / f->getQuantity(),
topopplan->getQuantity() * newoffset / f->getQuantity(), lvl,
curflowplan->getDate() - f->getDate());
}
++f;
}
} else {
// CASE 1B: Produced too much already: move backward
while (f != getFlowPlans().end() &&
((f->getQuantity() <= 0 && f->getCumulativeProduced() > endQty) ||
(f->getQuantity() > 0 &&
f->getCumulativeProduced() - f->getQuantity() > endQty)))
--f;
while (f != getFlowPlans().end() &&
f->getCumulativeProduced() > startQty) {
if (f->getQuantity() > ROUNDING_ERROR) {
double newqty = f->getQuantity();
double newoffset = 0.0;
if (f->getCumulativeProduced() - f->getQuantity() < startQty) {
newoffset =
startQty - (f->getCumulativeProduced() - f->getQuantity());
newqty -= newoffset;
}
if (f->getCumulativeProduced() > endQty)
newqty -= f->getCumulativeProduced() - endQty;
OperationPlan* opplan =
dynamic_cast<FlowPlan*>(&(*f))->getOperationPlan();
OperationPlan* topopplan = opplan->getTopOwner();
if (topopplan->getOperation()->hasType<OperationSplit>() ||
(iter.getMaxLevel() > 0))
if (opplan->getOwner() &&
opplan->getOwner()
->getOperation()
->hasType<OperationRouting>() &&
!(iter.getMaxLevel() > 0))
topopplan = opplan->getOwner();
else
topopplan = opplan;
iter.updateStack(
topopplan, topopplan->getQuantity() * newqty / f->getQuantity(),
topopplan->getQuantity() * newoffset / f->getQuantity(), lvl,
curflowplan->getDate() - f->getDate());
}
--f;
}
}
return;
}
if (curflowplan->getQuantity() > ROUNDING_ERROR && iter.isDownstream()) {
// CASE 2:
// This is a flowplan producing in a buffer. Navigating downstream means
// finding the flowplans consuming this produced material.
double scale = curflowplan->getQuantity() /
curflowplan->getOperationPlan()->getQuantity();
double startQty =
f->getCumulativeProduced() - f->getQuantity() + offset * scale;
double endQty = startQty + qty * scale;
if ((f->getQuantity() <= 0 &&
f->getCumulativeConsumed() + f->getQuantity() < endQty) ||
(f->getQuantity() > 0 && f->getCumulativeConsumed() < endQty &&
!(f->getCumulativeConsumed() >
f->getCumulativeProduced() - f->getQuantity()))) {
// CASE 2A: Not consumed enough yet: move forward
while (f != getFlowPlans().end() &&
f->getCumulativeConsumed() <= startQty)
++f;
while (f != getFlowPlans().end() &&
((f->getQuantity() <= 0 &&
f->getCumulativeConsumed() + f->getQuantity() < endQty) ||
(f->getQuantity() > 0 && f->getCumulativeConsumed() < endQty))) {
if (f->getQuantity() < -ROUNDING_ERROR) {
double newqty = -f->getQuantity();
double newoffset = 0.0;
if (f->getCumulativeConsumed() + f->getQuantity() < startQty) {
newoffset =
startQty - (f->getCumulativeConsumed() + f->getQuantity());
newqty -= newoffset;
}
if (f->getCumulativeConsumed() > endQty)
newqty -= f->getCumulativeConsumed() - endQty;
OperationPlan* opplan =
dynamic_cast<FlowPlan*>(&(*f))->getOperationPlan();
OperationPlan* topopplan = opplan->getTopOwner();
if (topopplan->getOperation()->hasType<OperationSplit>() ||
(iter.getMaxLevel() > 0))
if (opplan->getOwner() && opplan->getOwner()
->getOperation()
->hasType<OperationRouting>()) {
for (OperationPlan::iterator j(opplan->getOwner());
j != OperationPlan::end(); ++j) {
if (j->getReference() == opplan->getReference())
topopplan = opplan->getOwner();
else
topopplan = opplan;
break;
}
} else
topopplan = opplan;
iter.updateStack(
topopplan, -topopplan->getQuantity() * newqty / f->getQuantity(),
-topopplan->getQuantity() * newoffset / f->getQuantity(), lvl,
f->getDate() - curflowplan->getDate());
}
++f;
}
} else {
// CASE 2B: Consumed too much already: move backward
while (f != getFlowPlans().end() &&
((f->getQuantity() <= 0 &&
f->getCumulativeConsumed() + f->getQuantity() < endQty) ||
(f->getQuantity() > 0 && f->getCumulativeConsumed() < endQty &&
!(f->getCumulativeConsumed() >
f->getCumulativeProduced() - f->getQuantity()))))
--f;
while (f != getFlowPlans().end() &&
f->getCumulativeConsumed() > startQty) {
if (f->getQuantity() < -ROUNDING_ERROR) {
double newqty = -f->getQuantity();
double newoffset = 0.0;
if (f->getCumulativeConsumed() + f->getQuantity() < startQty)
newqty -=
startQty - (f->getCumulativeConsumed() + f->getQuantity());
if (f->getCumulativeConsumed() > endQty)
newqty -= f->getCumulativeConsumed() - endQty;
OperationPlan* opplan =
dynamic_cast<FlowPlan*>(&(*f))->getOperationPlan();
OperationPlan* topopplan = opplan->getTopOwner();
if (topopplan->getOperation()->hasType<OperationSplit>() ||
(iter.getMaxLevel() > 0))
if (opplan->getOwner() && opplan->getOwner()
->getOperation()
->hasType<OperationRouting>()) {
for (OperationPlan::iterator j(opplan->getOwner());
j != OperationPlan::end(); ++j) {
if (j->getReference() == opplan->getReference())
topopplan = opplan->getOwner();
else
topopplan = opplan;
break;
}
} else
topopplan = opplan;
iter.updateStack(
topopplan, -topopplan->getQuantity() * newqty / f->getQuantity(),
-topopplan->getQuantity() * newoffset / f->getQuantity(), lvl,
f->getDate() - curflowplan->getDate());
}
--f;
}
}
}
}
Buffer* Buffer::findOrCreate(Item* itm, Location* loc) {
if (!itm || !loc) return nullptr;
// Return existing buffer if it exists
Item::bufferIterator buf_iter(itm);
while (Buffer* tmpbuf = buf_iter.next()) {
if (tmpbuf->getLocation() == loc && !tmpbuf->getBatch()) return tmpbuf;
}
// Create a new buffer with a unique name
stringstream o;
o << itm->getName() << " @ " << loc->getName();
Buffer* b;
while ((b = find(o.str()))) o << '*';
b = new BufferDefault();
b->setItem(itm);
b->setLocation(loc);
b->setName(o.str());
return b;
}
Buffer* Buffer::findOrCreate(Item* itm, Location* loc,
const PooledString& batch) {
if (!itm || !loc) return nullptr;
// Return existing buffer if it exists
Buffer* generic = nullptr;
Item::bufferIterator buf_iter(itm);
while (Buffer* tmpbuf = buf_iter.next()) {
if (tmpbuf->getLocation() == loc) {
if (tmpbuf->getBatch() == batch)
return tmpbuf;
else if (!tmpbuf->getBatch())
generic = tmpbuf;
}
}
// Create a new buffer with a unique name
stringstream o;
o << itm->getName();
if (batch && itm->hasType<ItemMTO>()) o << " @ " << batch;
o << " @ " << loc->getName();
Buffer* b = find(o.str());
if (!b) {
b = new BufferDefault();
b->setName(o.str());
}
b->setItem(itm, !batch && !itm->hasType<ItemMTO>());
b->setLocation(loc, !batch && !itm->hasType<ItemMTO>());
if (batch && itm->hasType<ItemMTO>()) {
b->setBatch(batch);
if (generic) b->copyLevelAndCluster(generic);
}
return b;
}
bool Buffer::hasConsumingFlows() const {
for (const auto& fl : getFlows())
if (fl.isConsumer()) return true;
return false;
}
void Buffer::buildProducingOperation() {
if (producing_operation && producing_operation != uninitializedProducing &&
!producing_operation->getHidden())
// Leave manually specified producing operations alone
return;
// Loop over this item and all its parent items
Item* item = getItem();
while (item) {
// Loop over all suppliers of this item+location combination
Item::supplierlist::const_iterator supitem_iter =
item->getSupplierIterator();
while (ItemSupplier* supitem = supitem_iter.next()) {
if (supitem->getPriority() == 0) continue;
// Verify whether the ItemSupplier is applicable to the buffer location
// We need to reject the following 2 mismatches:
// - buffer location is not null, and is not the ItemSupplier location
// - buffer location is null, and the ItemSupplier location isn't
if (supitem->getLocation()) {
if ((getLocation() && getLocation() != supitem->getLocation()) ||
!getLocation())
continue;
}
// Check if there is already a producing operation referencing this
// ItemSupplier
if (producing_operation &&
producing_operation != uninitializedProducing) {
if (producing_operation->hasType<OperationItemSupplier>()) {
auto* o = static_cast<OperationItemSupplier*>(producing_operation);
if (o->getItemSupplier() == supitem)
// Already exists
continue;
} else {
bool exists = false;
SubOperation::iterator subiter(
producing_operation->getSubOperations());
while (SubOperation* o = subiter.next())
if (o->getOperation()->hasType<OperationItemSupplier>()) {
auto* s = static_cast<OperationItemSupplier*>(o->getOperation());
if (s->getItemSupplier() == supitem) {
// Already exists
exists = true;
break;
}
}
if (exists) continue;
}
}
// New operation needs to be created
OperationItemSupplier* oper =
OperationItemSupplier::findOrCreate(supitem, this);
// Merge the new operation in an alternate operation if required
if (producing_operation &&
producing_operation != uninitializedProducing) {
// We're not the first
auto* subop = new SubOperation();
subop->setOperation(oper);
subop->setPriority(supitem->getPriority());
subop->setEffective(supitem->getEffective());
if (!producing_operation->hasType<OperationAlternate>()) {
// We are the second: create an alternate and add 2 suboperations
auto* superop = new OperationAlternate();
stringstream o;
o << "Replenish " << getName();
superop->setName(o.str());
superop->setHidden(true);
if (oper->getSearch() != SearchMode::PRIORITY)
superop->setSearch(oper->getSearch());
auto* subop2 = new SubOperation();
subop2->setOperation(producing_operation);
// Note that priority and effectivity are at default values.
// If not, the alternate would already have been created.
subop2->setOwner(superop);
producing_operation = superop;
subop->setOwner(producing_operation);
} else {
// We are third or later: just add a suboperation
if (producing_operation->getSubOperations().size() > 100) {
new ProblemInvalidData(
this,
string("Excessive replenishments defined for '") + getName() +
"'",
"material", Date::infinitePast, Date::infiniteFuture);
return;
} else {
subop->setOwner(producing_operation);
if (oper->getSearch() != SearchMode::PRIORITY)
producing_operation->setSearch(oper->getSearch());
}
}
} else {
// We are the first: only create an operationItemSupplier instance
if (supitem->getEffective() == DateRange() &&
supitem->getPriority() == 1 &&
oper->getSearch() == SearchMode::PRIORITY)
// Use a single operation. If an alternate is required later on
// we know it has the default priority, serach mode and effectivity.
producing_operation = oper;
else {
// Already create an alternate now
auto* superop = new OperationAlternate();
producing_operation = superop;
stringstream o;
o << "Replenish " << getName();
superop->setName(o.str());
superop->setHidden(true);
if (oper->getSearch() != SearchMode::PRIORITY)
superop->setSearch(oper->getSearch());
auto* subop = new SubOperation();
subop->setOperation(oper);
subop->setPriority(supitem->getPriority());
subop->setEffective(supitem->getEffective());
subop->setOwner(superop);
}
}
} // End loop over itemsuppliers
// Loop over all item distributions to replenish this item+location
// combination
auto itemdist_iter = item->getDistributionIterator();
while (ItemDistribution* itemdist = itemdist_iter.next()) {
if (itemdist->getPriority() == 0) continue;
// Verify whether the ItemDistribution is applicable to the buffer
// location We need to reject the following 2 mismatches:
// - buffer location is not null, and is the ItemDistribution
// destination location
// - buffer location is null, and the ItemDistribution destination
// location isn't
if (getLocation() == itemdist->getOrigin()) continue;
if (itemdist->getDestination()) {
if ((getLocation() && getLocation() != itemdist->getDestination()) ||
!getLocation())
continue;
}
if (!itemdist->getOrigin()) continue;
// Check if there is already a producing operation referencing this
// ItemDistribution
if (producing_operation &&
producing_operation != uninitializedProducing) {
if (producing_operation->hasType<OperationItemDistribution>()) {
auto* o =
static_cast<OperationItemDistribution*>(producing_operation);
if (o->getItemDistribution() == itemdist)
// Already exists
continue;
} else {
bool exists = false;
SubOperation::iterator subiter(
producing_operation->getSubOperations());
while (SubOperation* o = subiter.next())
if (o->getOperation()->hasType<OperationItemDistribution>()) {
auto* s =
static_cast<OperationItemDistribution*>(o->getOperation());
if (s->getItemDistribution() == itemdist) {
// Already exists
exists = true;
break;
}
}
if (exists) continue;
}
}
// New operation needs to be created
Buffer* originbuf = findOrCreate(getItem(), &*itemdist->getOrigin());
Operation* oper =
OperationItemDistribution::findOrCreate(itemdist, originbuf, this);
// Merge the new operation in an alternate operation if required
if (producing_operation &&
producing_operation != uninitializedProducing) {
// We're not the first
auto* subop = new SubOperation();