-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpegging.cpp
More file actions
450 lines (398 loc) · 15.7 KB
/
Copy pathpegging.cpp
File metadata and controls
450 lines (398 loc) · 15.7 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
/***************************************************************************
* *
* 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 {
const MetaCategory* PeggingIterator::metadata;
const MetaCategory* PeggingDemandIterator::metadata;
thread_local MemoryPool<PeggingIterator::state> PeggingIterator::peggingpool;
int PeggingIterator::initialize() {
// Initialize the pegging metadata
PeggingIterator::metadata =
MetaCategory::registerCategory<PeggingIterator>("pegging", "peggings");
registerFields<PeggingIterator>(const_cast<MetaCategory*>(metadata));
// Initialize the Python type
auto& x = PythonExtension<PeggingIterator>::getPythonType();
x.setName("peggingIterator");
x.setDoc("frePPLe iterator for operationplan pegging");
x.supportgetattro();
x.supportiter();
PeggingIterator::metadata->setPythonClass(x);
return x.typeReady();
}
int PeggingDemandIterator::initialize() {
// Initialize the pegging metadata
PeggingDemandIterator::metadata =
MetaCategory::registerCategory<PeggingDemandIterator>("demandpegging",
"demandpeggings");
registerFields<PeggingDemandIterator>(const_cast<MetaCategory*>(metadata));
// Initialize the Python type
auto& x = PythonExtension<PeggingDemandIterator>::getPythonType();
x.setName("peggingDemandIterator");
x.setDoc("frePPLe iterator for demand pegging");
x.supportgetattro();
x.supportiter();
PeggingDemandIterator::metadata->setPythonClass(x);
return x.typeReady();
}
PeggingIterator& PeggingIterator::operator=(const PeggingIterator& c) {
downstream = c.downstream;
firstIteration = c.firstIteration;
first = c.first;
second_pass = c.second_pass;
maxlevel = c.maxlevel;
states = c.states;
states_sorted = c.states_sorted;
return *this;
}
PeggingIterator::PeggingIterator(const Demand* d, short maxLvl)
: states(PeggingIterator::peggingpool),
states_sorted(PeggingIterator::peggingpool),
downstream(false),
firstIteration(true),
first(false),
second_pass(false),
maxlevel(maxLvl) {
initType(metadata);
const Demand::OperationPlanList& deli = d->getDelivery();
for (auto opplaniter : deli) {
OperationPlan* t = opplaniter->getTopOwner();
updateStack(t, t->getQuantity(), 0.0, 0, 0L);
}
// Bring all pegging information to a second stack.
// Only in this way can we avoid that the same operationplan is returned
// multiple times
while (operator bool()) {
/* Check if already found in the vector. */
bool found = false;
state& curtop = states.back();
for (auto it = states_sorted.begin(); it != states_sorted.end() && !found;
++it)
if (it->opplan == curtop.opplan) {
// Update existing element in sorted stack
it->quantity += curtop.quantity;
if (it->level > curtop.level) it->level = curtop.level;
found = true;
}
if (!found)
// New element in sorted stack
states_sorted.insert(curtop.opplan, curtop.quantity, curtop.offset,
curtop.level, curtop.gap);
if (downstream)
++*this;
else
--*this;
}
// The normal iteration will use the sorted results
second_pass = true;
}
PeggingIterator::PeggingIterator(const OperationPlan* opplan, bool b,
short maxlevel)
: states(PeggingIterator::peggingpool),
states_sorted(PeggingIterator::peggingpool),
downstream(b),
firstIteration(true),
first(false),
second_pass(false),
maxlevel(maxlevel) {
initType(metadata);
if (!opplan) return;
if (opplan->getTopOwner()->getOperation()->hasType<OperationSplit>() ||
maxlevel > 0)
updateStack(opplan, opplan->getQuantity(), 0.0, 0, 0L);
else
updateStack(opplan->getTopOwner(), opplan->getTopOwner()->getQuantity(),
0.0, 0, 0L);
}
PeggingIterator::PeggingIterator(const FlowPlan* fp, bool b)
: states(PeggingIterator::peggingpool),
states_sorted(PeggingIterator::peggingpool),
downstream(b),
firstIteration(true),
first(false),
second_pass(false),
maxlevel(-1) {
initType(metadata);
if (!fp) return;
if (maxlevel > 0)
updateStack(fp->getOperationPlan(), fp->getOperationPlan()->getQuantity(),
0.0, 0, 0L);
else
updateStack(fp->getOperationPlan()->getTopOwner(),
fp->getOperationPlan()->getQuantity(), 0.0, 0, 0L);
}
PeggingIterator::PeggingIterator(LoadPlan* lp, bool b)
: states(PeggingIterator::peggingpool),
states_sorted(PeggingIterator::peggingpool),
downstream(b),
firstIteration(true),
first(false),
second_pass(false),
maxlevel(-1) {
initType(metadata);
if (!lp) return;
if (maxlevel > 0)
updateStack(lp->getOperationPlan(), lp->getOperationPlan()->getQuantity(),
0.0, 0, 0L);
else
updateStack(lp->getOperationPlan()->getTopOwner(),
lp->getOperationPlan()->getQuantity(), 0.0, 0, 0L);
}
PeggingIterator& PeggingIterator::operator--() {
// Second pass
if (second_pass) {
states_sorted.pop_front();
return *this;
}
// Validate
if (states.empty())
throw LogicException("Incrementing the iterator beyond it's end");
if (downstream) throw LogicException("Decrementing a downstream iterator");
// Mark the top entry in the stack as invalid, so it can be reused.
first = true;
// Find other operationplans to add to the stack
state& t = states.back(); // Copy the top element
followPegging(t.opplan, t.quantity, t.offset, t.level);
// Pop invalid top entry from the stack.
// This will happen if we didn't find an operationplan to replace the
// top entry.
if (first) states.pop_back();
return *this;
}
PeggingIterator& PeggingIterator::operator++() {
// Second pass
if (second_pass) {
states_sorted.pop_front();
return *this;
}
// Validate
if (states.empty())
throw LogicException("Incrementing the iterator beyond it's end");
if (!downstream) throw LogicException("Incrementing an upstream iterator");
// Mark the top entry in the stack as invalid, so it can be reused.
first = true;
// Find other operationplans to add to the stack
state& t = states.back(); // Copy the top element
followPegging(t.opplan, t.quantity, t.offset, t.level);
// Pop invalid top entry from the stack.
// This will happen if we didn't find an operationplan to replace the
// top entry.
if (first) states.pop_back();
return *this;
}
void PeggingIterator::followPegging(const OperationPlan* op, double qty,
double offset, short lvl) {
// Zero quantity operationplans don't have further pegging
if (!op->getQuantity()) return;
// Did we reach the maximum depth we want to visit
// If the operation is hidden, we allow one more level
if (maxlevel != -1 && lvl > maxlevel && !op->getOperation()->getHidden())
return;
// For each flowplan ask the buffer to find the pegged operationplans.
if (downstream)
for (auto i = op->beginFlowPlans(); i != op->endFlowPlans(); ++i) {
if (i->getQuantity() > ROUNDING_ERROR) // Producing flowplan
i->getFlow()->getBuffer()->followPegging(*this, &*i, qty, offset,
lvl + 1);
}
else
for (auto i = op->beginFlowPlans(); i != op->endFlowPlans(); ++i) {
if (i->getQuantity() < -ROUNDING_ERROR) // Consuming flowplan
i->getFlow()->getBuffer()->followPegging(*this, &*i, qty, offset,
lvl + 1);
}
// Push child operationplans on the stack.
// The pegged quantity is equal to the ratio of the quantities of the
// parent and child operationplan.
if (maxlevel > 0) {
if (lvl <= maxlevel - 1 || op->getOperation()->getHidden()) {
// DOWNSTREAM
if (downstream) {
// In downstream, a routing operation will send its first step
if (op->getOperation()->hasType<OperationRouting>()) {
for (OperationPlan::iterator j(op); j != OperationPlan::end(); ++j) {
updateStack(&*j, qty * j->getQuantity() / op->getQuantity(),
offset * j->getQuantity() / op->getQuantity(), lvl + 1,
0L);
break;
}
}
// In downstream, a routing suboperation will send the next suboperation
if (op->getOwner() &&
op->getOwner()->getOperation()->hasType<OperationRouting>() &&
op->getNextSubOpplan()) {
updateStack(
op->getNextSubOpplan(),
qty * op->getNextSubOpplan()->getQuantity() / op->getQuantity(),
offset * op->getNextSubOpplan()->getQuantity() /
op->getQuantity(),
lvl + 1, 0L);
}
} else {
// UPSTREAM
// In upstream, a routing operation will send its last step
if (op->getOperation()->hasType<OperationRouting>()) {
OperationPlan* opplan_last = nullptr;
for (OperationPlan::iterator j(op); j != OperationPlan::end(); ++j) {
opplan_last = &*j;
}
if (opplan_last)
updateStack(opplan_last,
qty * opplan_last->getQuantity() / op->getQuantity(),
offset * opplan_last->getQuantity() / op->getQuantity(),
lvl + 1, 0L);
}
// In upstream, a routing suboperation will send the previous
// suboperation
if (op->getOwner() &&
op->getOwner()->getOperation()->hasType<OperationRouting>() &&
op->getPrevSubOpplan()) {
updateStack(
op->getPrevSubOpplan(),
qty * op->getPrevSubOpplan()->getQuantity() / op->getQuantity(),
offset * op->getPrevSubOpplan()->getQuantity() /
op->getQuantity(),
lvl + 1, 0L);
}
}
}
} else {
for (OperationPlan::iterator j(op); j != OperationPlan::end(); ++j) {
updateStack(&*j, qty * j->getQuantity() / op->getQuantity(),
offset * j->getQuantity() / op->getQuantity(), lvl + 1, 0L);
}
}
// Push dependencies on the stack.
for (auto d : op->getDependencies()) {
auto o = downstream ? d->getSecond() : d->getFirst();
auto exists = visited.find(o);
if (exists != visited.end()) continue;
visited.insert(o);
if (downstream && d->getFirst() == op && (maxlevel == -1 || lvl < maxlevel))
updateStack(d->getSecond(),
qty * d->getSecond()->getQuantity() / op->getQuantity(),
offset * d->getSecond()->getQuantity() / op->getQuantity(),
lvl + 1, 0L);
else if (!downstream && d->getSecond() == op &&
(maxlevel == -1 || lvl < maxlevel))
updateStack(d->getFirst(),
qty * d->getFirst()->getQuantity() / op->getQuantity(),
offset * d->getFirst()->getQuantity() / op->getQuantity(),
lvl + 1, 0L);
}
}
PeggingIterator* PeggingIterator::next() {
if (firstIteration)
firstIteration = false;
else if (downstream)
++*this;
else
--*this;
if (!operator bool())
return nullptr;
else
return this;
}
void PeggingIterator::updateStack(const OperationPlan* op, double qty, double o,
short lvl, Duration gap) {
// Avoid very small pegging quantities
if (qty < ROUNDING_ERROR) return;
// Check for loops in the pegging
for (auto & state : states) {
if (state.opplan == op && abs(state.quantity - qty) < ROUNDING_ERROR &&
abs(state.offset - o) < ROUNDING_ERROR) // We've been here before...
return;
}
if (first) {
// Update the current top element of the stack
state& t = states.back();
t.opplan = op;
t.quantity = qty;
t.offset = o;
t.level = lvl;
t.gap = gap;
first = false;
} else
// We need to create a new element on the stack
states.insert(op, qty, o, lvl, gap);
}
PeggingDemandIterator::PeggingDemandIterator(const OperationPlan* opplan) {
initType(metadata);
// a map to track the demands pegged to that opplan
// for every demand we are also tracking the different delivery orders
// in another map with the pegged offet and qty from that delivery order
map<Demand*, map<const OperationPlan*, vector<pair<double, double>>>> mapvar;
// Walk over all downstream operationplans till demands are found
for (PeggingIterator p(opplan); p; ++p) {
const OperationPlan* m = p.getOperationPlan();
if (!m || (m != m->getTopOwner())) continue;
Demand* dmd = m->getTopOwner()->getDemand();
if (dmd && p.getQuantity() > ROUNDING_ERROR)
mapvar[dmd][m].emplace_back(
make_pair(p.getOffset(), p.getOffset() + p.getQuantity()));
}
// Iterate over all demands and compute the pegged quantity
// by excluding overlapping intervals
for (const auto& it : mapvar) {
double quantity = 0.0;
for (auto& it2 : it.second) {
quantity +=
sumOfIntervals(const_cast<vector<pair<double, double>>&>(it2.second));
}
dmds.insert({it.first, quantity});
}
}
PeggingDemandIterator* PeggingDemandIterator::next() {
if (first) {
iter = dmds.begin();
first = false;
} else
++iter;
if (iter == dmds.end()) return nullptr;
return this;
}
double PeggingDemandIterator::sumOfIntervals(
vector<pair<double, double>>& intervals) {
if (intervals.empty()) return 0.0;
// Sort intervals by their starting point
sort(intervals.begin(), intervals.end());
double totalSum = 0.0;
double currentStart = intervals[0].first;
double currentEnd = intervals[0].second;
for (size_t i = 1; i < intervals.size(); ++i) {
double start = intervals[i].first;
double end = intervals[i].second;
if (start <= currentEnd) { // Overlapping intervals
currentEnd = max(currentEnd, end);
} else { // Non-overlapping interval
totalSum += currentEnd - currentStart;
currentStart = start;
currentEnd = end;
}
}
// Add the last merged interval
totalSum += currentEnd - currentStart;
return totalSum;
}
} // namespace frepple