-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemand.cpp
More file actions
368 lines (320 loc) · 12.9 KB
/
Copy pathdemand.cpp
File metadata and controls
368 lines (320 loc) · 12.9 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
/***************************************************************************
* *
* 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 Demand>
Tree utils::HasName<Demand>::st;
const MetaCategory* Demand::metadata;
const MetaClass* DemandDefault::metadata;
const MetaClass* DemandGroup::metadata;
OperationFixedTime* Demand::uninitializedDelivery = nullptr;
Duration Demand::DefaultDeliveryDuration = 0L;
int Demand::initialize() {
// Initialize the metadata
metadata = MetaCategory::registerCategory<Demand>("demand", "demands", reader,
finder);
registerFields<Demand>(const_cast<MetaCategory*>(metadata));
// Initialize the Python class
auto& x = FreppleCategory<Demand>::getPythonType();
x.addMethod("addConstraint", addConstraint, METH_VARARGS,
"add a constraint to the demand");
uninitializedDelivery = new OperationFixedTime();
// Initialize the Python class
return FreppleCategory<Demand>::initialize();
}
int DemandDefault::initialize() {
// Initialize the metadata
DemandDefault::metadata = MetaClass::registerClass<DemandDefault>(
"demand", "demand_default", Object::create<DemandDefault>, true);
registerFields<DemandDefault>(const_cast<MetaClass*>(metadata));
// Initialize the Python class
return FreppleClass<DemandDefault, Demand>::initialize();
}
int DemandGroup::initialize() {
// Initialize the metadata
DemandGroup::metadata = MetaClass::registerClass<DemandGroup>(
"demand", "demand_group", Object::create<DemandGroup>);
registerFields<DemandGroup>(const_cast<MetaClass*>(metadata));
// Initialize the Python class
return FreppleClass<DemandGroup, Demand>::initialize();
}
void Demand::setQuantity(double f) {
// Reject negative quantities, and no-change updates
double delta(f - qty);
if (f < 0.0 || fabs(delta) < ROUNDING_ERROR) return;
// Update the quantity
qty = f;
}
Demand::~Demand() {
// Remove the delivery operationplans
deleteOperationPlans(true);
// Unlink from the item
if (it) {
if (it->firstItemDemand == this)
it->firstItemDemand = nextItemDemand;
else {
Demand* dmd = it->firstItemDemand;
while (dmd && dmd->nextItemDemand != this) dmd = dmd->nextItemDemand;
if (!dmd)
logger << "corrupted demand list for an item\n";
else
dmd->nextItemDemand = nextItemDemand;
}
}
// Decrement demand count on the customer
if (cust) cust->decNumberOfDemands();
}
void Demand::deleteOperationPlans(bool deleteLocked, CommandManager* cmds) {
// Delete all delivery operationplans.
// Note that an extra loop is used to assure that our iterator doesn't get
// invalidated during the deletion.
while (true) {
// Find a candidate to delete
OperationPlan* candidate = nullptr;
for (auto& i : deli)
if (deleteLocked || i->getProposed()) {
candidate = i;
break;
}
if (!candidate) break;
if (cmds)
// Use delete command
cmds->add(new CommandDeleteOperationPlan(candidate));
else
// Delete immediately
delete candidate;
}
}
void Demand::removeDelivery(OperationPlan* o) {
// Valid opplan check
if (!o) return;
// See if the demand field on the operationplan points to this demand
if (o->dmd != this)
throw LogicException("Delivery operationplan incorrectly registered");
// Remove the reference on the operationplan
o->dmd = nullptr; // Required to avoid endless loop
o->setDemand(nullptr);
// Remove from the list
deli.remove(o);
}
const Demand::OperationPlanList& Demand::getDelivery() const {
// Sorting the deliveries by the end date
const_cast<Demand*>(this)->deli.sort(
[](OperationPlan*& lhs, OperationPlan*& rhs) {
return lhs->getEnd() != rhs->getEnd() ? lhs->getEnd() > rhs->getEnd()
: *lhs < *rhs;
});
return deli;
}
OperationPlan* Demand::getLatestDelivery() const {
const Demand::OperationPlanList& l = getDelivery();
return l.empty() ? nullptr : *(l.begin());
}
OperationPlan* Demand::getEarliestDelivery() const {
const Demand::OperationPlanList& l = getDelivery();
OperationPlan* last = nullptr;
for (auto i : l) last = i;
return last;
}
void Demand::addDelivery(OperationPlan* o) {
// Dummy call to this function
if (!o) return;
// Check if it is already in the list.
// If it is, simply exit the function. No need to give a warning message
// since it's harmless.
for (auto& i : deli)
if (i == o) return;
// Add to the list of delivery operationplans.
deli.push_front(o);
// Create link between operationplan and demand
o->setDemand(this);
// Check validity of operation being used
Operation* tmpOper = getDeliveryOperation();
if (tmpOper && tmpOper != o->getOperation())
logger << "Warning: Delivery Operation '" << o->getOperation()
<< "' different than expected '" << tmpOper << "' for demand '"
<< this << "'\n";
}
Operation* Demand::getDeliveryOperation() const {
// Case 1: Operation specified on the demand itself,
// or the delivery operation was computed earlier.
if (oper && oper != uninitializedDelivery) return oper;
// Case 2: Create a delivery operation automatically
if (!getItem()) {
// Not possible to create an operation when we don't know the item
const_cast<Demand*>(this)->oper = nullptr;
return nullptr;
}
Location* l = getLocation();
if (!l) {
// Single location only?
Location::iterator l_iter = Location::begin();
if (l_iter != Location::end()) {
l = &*l_iter;
if (++l_iter != Location::end())
// No, multiple locations
l = nullptr;
}
}
if (l) {
// Search for buffers for the requested item and location.
// We want the generic buffer, and not any of the mto-buffers.
bool ok = true;
Buffer* buf = nullptr;
Item::bufferIterator buf_iter(getItem());
while (Buffer* tmpbuf = buf_iter.next()) {
if (tmpbuf->getLocation() == l && !tmpbuf->getBatch()) {
if (buf) {
// Second buffer found. We don't know which one to pick - abort.
ok = false;
break;
} else
buf = tmpbuf;
}
}
if (ok) {
if (!buf)
// Create a new buffer
buf = Buffer::findOrCreate(getItem(), l);
// Find an existing operation consuming from this buffer
const_cast<Demand*>(this)->oper =
Operation::find("Ship " + string(buf->getName()));
if (!oper) {
const_cast<Demand*>(this)->oper = new OperationDelivery();
static_cast<OperationDelivery*>(const_cast<Demand*>(this)->oper)
->setBuffer(buf);
}
// Success!
return oper;
}
}
// Case 4: Tough luck. Not possible to ship this demand.
const_cast<Demand*>(this)->oper = nullptr;
return nullptr;
}
double Demand::getPlannedQuantity() const {
double delivered(0.0);
for (auto i : deli) delivered += i->getQuantity();
return delivered;
}
PyObject* Demand::addConstraint(PyObject* self, PyObject* args,
PyObject* kwds) {
try {
// Pick up the demand
auto* dmd = static_cast<Demand*>(self);
if (!dmd) throw LogicException("Can't add a contraint to a null demand");
// Parse the arguments
char* pytype = nullptr;
char* pyowner = nullptr;
PyObject* pystart = nullptr;
PyObject* pyend = nullptr;
static const char* kwlist[] = {"type", "owner", "start", "end", nullptr};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss|OO:addConstraint",
const_cast<char**>(kwlist), &pytype,
&pyowner, &pystart, &pyend))
return nullptr;
string cnstrnt_type;
if (pytype) cnstrnt_type = pytype;
string cnstrnt_owner;
if (pyowner) cnstrnt_owner = pyowner;
Date cnstrnt_start = Date::infinitePast;
if (pystart) cnstrnt_start = PythonData(pystart).getDate();
Date cnstrnt_end = Date::infiniteFuture;
if (pyend) cnstrnt_end = PythonData(pyend).getDate();
// Add the new constraint
Problem* cnstrnt = nullptr;
if (cnstrnt_type == ProblemBeforeCurrent::metadata->type) {
Operation* obj = Operation::findFromName(cnstrnt_owner);
if (!obj) throw DataException("Can't find constraint owner");
cnstrnt = dmd->getConstraints().push(ProblemBeforeCurrent::metadata, obj,
cnstrnt_start, cnstrnt_end);
} else if (cnstrnt_type == ProblemCapacityOverload::metadata->type) {
Resource* obj = Resource::find(cnstrnt_owner);
if (!obj) throw DataException("Can't find constraint owner");
cnstrnt = dmd->getConstraints().push(ProblemCapacityOverload::metadata,
obj, cnstrnt_start, cnstrnt_end);
} else if (cnstrnt_type == ProblemMaterialShortage::metadata->type) {
Buffer* obj = Buffer::findFromName(cnstrnt_owner);
if (!obj) throw DataException("Can't find constraint owner");
cnstrnt = dmd->getConstraints().push(ProblemMaterialShortage::metadata,
obj, cnstrnt_start, cnstrnt_end);
} else if (cnstrnt_type == ProblemAwaitSupply::metadata->type) {
Buffer* obj_buffer = Buffer::findFromName(cnstrnt_owner);
if (obj_buffer)
cnstrnt =
dmd->getConstraints().push(ProblemAwaitSupply::metadata, obj_buffer,
cnstrnt_start, cnstrnt_end);
else {
Operation* obj_operation = Operation::findFromName(cnstrnt_owner);
if (obj_operation)
cnstrnt = dmd->getConstraints().push(ProblemAwaitSupply::metadata,
obj_operation, cnstrnt_start,
cnstrnt_end);
else
throw DataException("Can't find constraint owner");
}
} else if (cnstrnt_type == ProblemSyncDemand::metadata->type) {
Demand* obj = Demand::find(cnstrnt_owner);
if (!obj) throw DataException("Can't find constraint owner");
cnstrnt = dmd->getConstraints().push(ProblemSyncDemand::metadata, obj,
cnstrnt_start, cnstrnt_end);
} else
throw DataException("Invalid constraint type");
Py_IncRef(cnstrnt);
return cnstrnt;
} catch (...) {
PythonType::evalException();
return nullptr;
}
}
PeggingIterator Demand::getPegging() const { return PeggingIterator(this); }
PeggingIterator Demand::getPeggingFirstLevel() const {
return PeggingIterator(this, 0);
}
Problem::List::iterator Demand::getConstraintIterator() const {
return constraints.begin();
}
int DemandGroup::getPriority() const {
int lowest = INT_MAX;
for (auto m = getMembers(); m != end(); ++m) {
if (m->getPriority() < lowest) lowest = m->getPriority();
};
return lowest;
}
void DemandGroup::setPriority(int i) {
Demand::setPriority(i);
for (auto m = getMembers(); m != end(); ++m) m->setPriority(i);
}
Date DemandGroup::getDue() const {
auto latest = Date::infiniteFuture;
for (auto m = getMembers(); m != end(); ++m) {
if (m->getDue() < latest) latest = m->getDue();
};
return latest;
}
void DemandGroup::setDue(Date d) {
for (auto m = getMembers(); m != end(); ++m) m->setDue(d);
}
} // namespace frepple