-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathEpanetModel.cpp
executable file
·1413 lines (1181 loc) · 45.9 KB
/
EpanetModel.cpp
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
//
// EpanetModel.cpp
// epanet-rtx
//
// Created by the EPANET-RTX Development Team
// See README.md and license.txt for more information
//
#include <cstdlib>
#include <cmath>
#include <sstream>
#include <iostream>
#include "EpanetModel.h"
#include "rtxMacros.h"
#include <CurveFunction.h>
#include <types.h>
#include <boost/filesystem.hpp>
using namespace RTX;
using namespace TSF;
using namespace std;
#define SMALL 0.001
EpanetModel::EpanetModel() : Model() {
// nothing to do, right?
_enOpened = false;
_enModel = NULL;
// EN_API_CHECK( EN_newModel(&_enModel), "EN_newModel");
}
EpanetModel::~EpanetModel() {
this->closeEngine();
if (_enOpened) {
EN_API_CHECK( EN_close(_enModel), "EN_close");
}
// EN_API_CHECK(EN_freeModel(_enModel), "EN_freeModel");
}
EpanetModel::EpanetModel(const EpanetModel& o) {
cout << "copy ctor : EpanetModel" << endl;
this->useEpanetFile(o._modelFile);
this->createRtxWrappers();
}
EN_Project EpanetModel::epanetModelPointer() {
return _enModel;
}
EpanetModel::EpanetModel(const std::string& filename) {
try {
this->useEpanetFile(filename);
this->createRtxWrappers();
}
catch(const std::string& errStr) {
std::cerr << "ERROR: ";
throw RtxException("File Loading Error: " + errStr);
}
}
#pragma mark - Loading
void EpanetModel::useEpanetModel(EN_Project model, string path) {
Units volumeUnits(0);
this->_enModel = model;
_modelFile = path;
// get units from epanet
int flowUnitType = 0;
bool isSI = false;
int qualCode, traceNode;
char chemName[56], chemUnits[56];
EN_API_CHECK( EN_getqualinfo(_enModel, &qualCode, chemName, chemUnits, &traceNode), "EN_getqualinfo" );
string chemUnitsStr(chemUnits);
if (chemUnitsStr == "hrs") {
chemUnitsStr = "hr";
}
//Units qualUnits = Units::unitOfType(chemUnitsStr);
//this->setQualityUnits(qualUnits);
EN_API_CHECK( EN_getflowunits(_enModel, &flowUnitType), "EN_getflowunits");
switch (flowUnitType)
{
case EN_LPS:
case EN_LPM:
case EN_MLD:
case EN_CMH:
case EN_CMD:
isSI = true;
break;
default:
isSI = false;
}
switch (flowUnitType) {
case EN_LPS:
setFlowUnits(TSF_LITER_PER_SECOND);
break;
case EN_MLD:
setFlowUnits(TSF_MILLION_LITER_PER_DAY);
break;
case EN_CMH:
setFlowUnits(TSF_CUBIC_METER_PER_HOUR);
break;
case EN_CMD:
setFlowUnits(TSF_CUBIC_METER_PER_DAY);
break;
case EN_GPM:
setFlowUnits(TSF_GALLON_PER_MINUTE);
break;
case EN_MGD:
setFlowUnits(TSF_MILLION_GALLON_PER_DAY);
break;
case EN_IMGD:
setFlowUnits(TSF_IMPERIAL_MILLION_GALLON_PER_DAY);
break;
case EN_AFD:
setFlowUnits(TSF_ACRE_FOOT_PER_DAY);
default:
break;
}
if (isSI) {
setHeadUnits(TSF_METER);
setPressureUnits(TSF_KILOPASCAL);
volumeUnits = TSF_CUBIC_METER;
}
else {
setHeadUnits(TSF_FOOT);
setPressureUnits(TSF_PSI);
volumeUnits = TSF_CUBIC_FOOT;
}
this->setVolumeUnits(volumeUnits);
// what units are quality in? who knows!
//this->setQualityUnits(TSF_MICROSIEMENS_PER_CM);
//EN_API_CHECK(EN_setqualtype(_enModel, CHEM, (char*)"rtxConductivity", (char*)"us/cm", (char*)""), "EN_setqualtype");
// get simulation parameters
{
long enTimeStep;
EN_API_CHECK(EN_gettimeparam(_enModel, EN_HYDSTEP, &enTimeStep), "EN_gettimeparam EN_HYDSTEP");
this->setHydraulicTimeStep((int)enTimeStep);
long enQStep;
EN_API_CHECK(EN_gettimeparam(_enModel, EN_QUALSTEP, &enQStep), "EN_gettimeparam EN_QUALSTEP");
this->setQualityTimeStep((int)enQStep);
}
{
long reportStep;
EN_API_CHECK(EN_gettimeparam(_enModel, EN_REPORTSTEP, &reportStep), "EN_gettimeparam EN_REPORTSTEP");
this->setReportTimeStep((int)reportStep);
}
int nodeCount, tankCount, linkCount;
char enName[RTX_MAX_CHAR_STRING];
EN_API_CHECK( EN_getcount(_enModel, EN_NODECOUNT, &nodeCount), "EN_getcount EN_NODECOUNT" );
EN_API_CHECK( EN_getcount(_enModel, EN_TANKCOUNT, &tankCount), "EN_getcount EN_TANKCOUNT" );
EN_API_CHECK( EN_getcount(_enModel, EN_LINKCOUNT, &linkCount), "EN_getcount EN_LINKCOUNT" );
// store the original number of simple controls, since we'll be adding new ones
int controlCount;
EN_API_CHECK( EN_getcount(_enModel, EN_CONTROLCOUNT, &controlCount), "EN_getcount EN_CONTROLCOUNT" );
_controlCount = controlCount;
// create lookup maps for name->index
for (int iNode=1; iNode <= nodeCount; iNode++) {
EN_API_CHECK( EN_getnodeid(_enModel, iNode, enName), "EN_getnodeid" );
// and keep track of the epanet-toolkit index of this element
_nodeIndex[string(enName)] = iNode;
}
for (int iLink = 1; iLink <= linkCount; iLink++) {
EN_API_CHECK(EN_getlinkid(_enModel, iLink, enName), "EN_getlinkid");
// keep track of this element index
_linkIndex[string(enName)] = iLink;
}
// get the valve types
for(Valve::_sp v : this->valves()) {
int enIdx = _linkIndex[v->name()];
int type = EN_PIPE;
EN_getlinktype(_enModel, enIdx, &type);
if (type == EN_PIPE) {
// should not happen
continue;
}
v->valveType = (int)type;
}
// consistency checking (should add more)
for(Node::_sp n : this->nodes()) {
double elev;
auto en_idx = _nodeIndex[n->name()];
EN_getnodevalue(_enModel, en_idx, EN_ELEVATION, &elev);
if ( abs(elev - n->elevation()) > SMALL) {
cout << "ERROR: Database elevation inconsistent with model for node " << n->name() << EOL;
auto badElevationErr = string("Database elevation inconsistent with model for node ") + n->name();
throw(badElevationErr);
}
}
for (Pipe::_sp p : this->pipes()) {
auto en_idx = _linkIndex[p->name()];
double mloss;
EN_getlinkvalue(_enModel, en_idx, EN_MINORLOSS, &mloss);
p->setMinorLoss(mloss);
}
cout << "copying comments" << endl;
// copy my comments into the model
for(Node::_sp n : this->nodes()) {
this->setComment(n, n->userDescription());
}
for(Link::_sp l : this->links()) {
this->setComment(l, l->userDescription());
}
}
void EpanetModel::useEpanetFile(const std::string& filename) {
EN_Project model;
EN_createproject(&model);
try {
// set up temp path for report file so EPANET does not mess with stdout buffer
boost::filesystem::path rptPath = boost::filesystem::temp_directory_path();
rptPath /= "en_report.txt";
cout << rptPath << endl;
EN_API_CHECK( EN_open(model, (char*)filename.c_str(), (char*)rptPath.c_str(), (char*)""), "EN_open" );
} catch (const std::string& errStr) {
cerr << "model not formatted correctly. " << errStr << endl;
throw "model not formatted correctly. " + errStr;
}
this->useEpanetModel(model, filename);
}
void EpanetModel::initEngine() {
if (_enOpened) {
EN_API_CHECK(EN_initH(_enModel, 10), "EN_initH");
EN_API_CHECK(EN_initQ(_enModel, EN_NOSAVE), "EN_initQ");
return;
}
try {
EN_API_CHECK(EN_openH(_enModel), "EN_openH");
EN_API_CHECK(EN_initH(_enModel, 10), "EN_initH");
EN_API_CHECK(EN_openQ(_enModel), "EN_openQ");
EN_API_CHECK(EN_initQ(_enModel, EN_NOSAVE), "EN_initQ");
} catch (...) {
cerr << "warning: epanet opened improperly" << endl;
}
this->applyInitialQuality();
_enOpened = true;
}
void EpanetModel::closeEngine() {
if (_enOpened) {
try {
EN_API_CHECK( EN_closeQ(_enModel), "EN_closeQ");
EN_API_CHECK( EN_closeH(_enModel), "EN_closeH");
} catch (...) {
cerr << "warning: epanet closed improperly" << endl;
}
_enOpened = false;
}
}
void EpanetModel::createRtxWrappers() {
int curveCount, nodeCount, tankCount, linkCount;
try {
EN_API_CHECK( EN_getcount(_enModel, EN_CURVECOUNT, &curveCount), "EN_getcount EN_CURVECOUNT");
EN_API_CHECK( EN_getcount(_enModel, EN_NODECOUNT, &nodeCount), "EN_getcount EN_NODECOUNT" );
EN_API_CHECK( EN_getcount(_enModel, EN_TANKCOUNT, &tankCount), "EN_getcount EN_TANKCOUNT" );
EN_API_CHECK( EN_getcount(_enModel, EN_LINKCOUNT, &linkCount), "EN_getcount EN_LINKCOUNT" );
} catch (...) {
throw "Could not create wrappers";
}
map<int,Curve::_sp> namedCurves;
for (int iCurve = 1; iCurve <= curveCount; ++iCurve) {
double *xVals, *yVals;
int nPoints;
char buf[1024];
int err = 0;
err = EN_getcurvelen(_enModel, iCurve, &nPoints);
xVals = (double*)calloc(nPoints, sizeof(double));
yVals = (double*)calloc(nPoints, sizeof(double));
err = EN_getcurve(_enModel, iCurve, buf, &nPoints, xVals, yVals);
if (err) {
throw("could not find curve " + to_string(iCurve));
}
map<double,double> curveData;
for (int iPoint = 0; iPoint < nPoints; ++iPoint) {
curveData[xVals[iPoint]] = yVals[iPoint];
}
Curve::_sp newCurve( new Curve );
newCurve->curveData = curveData;
newCurve->inputUnits = TSF_DIMENSIONLESS;
newCurve->outputUnits = TSF_DIMENSIONLESS;
newCurve->name = string(buf);
this->addCurve(newCurve);
namedCurves[iCurve] = newCurve;
free(xVals);
free(yVals);
}
// create nodes
for (int iNode=1; iNode <= nodeCount; iNode++) {
char enName[RTX_MAX_CHAR_STRING];
double x,y,z; // rtx coordinates
int nodeType; // epanet node type code
string nodeName, comment;
Junction::_sp newJunction;
Reservoir::_sp newReservoir;
Tank::_sp newTank;
char enComment[MAXMSG+1];
// get relevant info from EPANET toolkit
EN_API_CHECK( EN_getnodeid(_enModel, iNode, enName), "EN_getnodeid" );
EN_API_CHECK( EN_getnodevalue(_enModel, iNode, EN_ELEVATION, &z), "EN_getnodevalue EN_ELEVATION");
EN_API_CHECK( EN_getnodetype(_enModel, iNode, &nodeType), "EN_getnodetype");
EN_API_CHECK( EN_getcoord(_enModel, iNode, &x, &y), "EN_getcoord");
EN_API_CHECK( EN_getcomment(_enModel, EN_NODE, iNode, enComment), "EN_getnodecomment");
nodeName = string(enName);
comment = string(enComment);
double minLevel = 0, maxLevel = 0, tankDiam = 0;
switch (nodeType) {
case EN_TANK:
{
newTank.reset( new Tank(nodeName) );
// get tank geometry from epanet and pass it along
// todo -- geometry
addTank(newTank);
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_MAXLEVEL, &maxLevel), "EN_getnodevalue(EN_MAXLEVEL)");
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_MINLEVEL, &minLevel), "EN_getnodevalue(EN_MINLEVEL)");
newTank->setMinMaxLevel(minLevel, maxLevel);
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_TANKDIAM, &tankDiam), "EN_getnodevalue(EN_TANKDIAM)");
newTank->setEnProperties(0.0, tankDiam);
newTank->level()->setUnits(headUnits());
newTank->flowCalc()->setUnits(flowUnits());
newTank->volumeCalc()->setUnits(volumeUnits());
newTank->flow()->setUnits(flowUnits());
newTank->volume()->setUnits(volumeUnits());
Curve::_sp volumeCurve;
double volumeCurveIndex;
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_VOLCURVE, &volumeCurveIndex), "EN_getnodevalue EN_VOLCURVE");
if (volumeCurveIndex > 0) {
// curved tank
volumeCurve = namedCurves[volumeCurveIndex];
}
else {
// it's a cylindrical tank - invent a curve
double minVolume, maxVolume;
double minLevel, maxLevel;
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_MAXLEVEL, &maxLevel), "EN_MAXLEVEL");
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_MINLEVEL, &minLevel), "EN_MINLEVEL");
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_MINVOLUME, &minVolume), "EN_MINVOLUME");
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_MAXVOLUME, &maxVolume), "EN_MAXVOLUME");
volumeCurve.reset( new Curve );
volumeCurve->curveData[minLevel] = minVolume;
volumeCurve->curveData[maxLevel] = maxVolume;
stringstream ss;
ss << "Tank " << newTank->name() << " Cylindrical Curve";
volumeCurve->name = ss.str();
this->addCurve(volumeCurve); // unnamed curve: add cylindrical curve to list
}
volumeCurve->inputUnits = this->headUnits();
volumeCurve->outputUnits = this->volumeUnits();
// set tank geometry
newTank->setGeometry(volumeCurve);
newJunction = newTank;
break;
}
case EN_RESERVOIR:
newReservoir.reset( new Reservoir(nodeName) );
addReservoir(newReservoir);
newJunction = newReservoir;
break;
case EN_JUNCTION:
newJunction.reset( new Junction(nodeName) );
addJunction(newJunction);
break;
default:
throw "Node Type Unknown";
} // switch nodeType
// set units for new element
newJunction->head()->setUnits(headUnits());
newJunction->pressure()->setUnits(pressureUnits());
newJunction->demand()->setUnits(flowUnits());
newJunction->quality()->setUnits(qualityUnits());
// newJunction is the generic (base-class) pointer to the specific object,
// so we can use base-class methods to set some parameters.
newJunction->setElevation(z);
newJunction->setCoordinates(Node::location_t(x, y));
// Initial quality specified in input data
double initQual;
EN_API_CHECK(EN_getnodevalue(_enModel, iNode, EN_INITQUAL, &initQual), "EN_INITQUAL");
newJunction->state_quality = initQual;
// Base demand is sum of all demand categories, accounting for patterns
double demand = 0, categoryDemand = 0, avgPatternValue = 0;
int numDemands = 0, patternIdx = 0;
EN_API_CHECK( EN_getnumdemands(_enModel, iNode, &numDemands), "EN_getnumdemands()");
for (int demandIdx = 1; demandIdx <= numDemands; demandIdx++) {
EN_API_CHECK( EN_getbasedemand(_enModel, iNode, demandIdx, &categoryDemand), "EN_getbasedemand()" );
EN_API_CHECK( EN_getdemandpattern(_enModel, iNode, demandIdx, &patternIdx), "EN_getdemandpattern()");
avgPatternValue = 1.0;
if (patternIdx > 0) { // Not the default "pattern" = 1
EN_API_CHECK( EN_getaveragepatternvalue(_enModel, patternIdx, &avgPatternValue), "EN_getaveragepatternvalue()");
}
demand += categoryDemand * avgPatternValue;
}
newJunction->setBaseDemand(demand);
newJunction->setUserDescription(comment);
} // for iNode
// create links
for (int iLink = 1; iLink <= linkCount; iLink++) {
char enLinkName[RTX_MAX_CHAR_STRING+1], enFromName[RTX_MAX_CHAR_STRING+1], enToName[RTX_MAX_CHAR_STRING+1], enComment[RTX_MAX_CHAR_STRING+1];
int enFrom, enTo;
int linkType;
double length, diameter, status, rough, mloss, setting, curveIdx;
string linkName, comment;
Node::_sp startNode, endNode;
Pipe::_sp newPipe;
Pump::_sp newPump;
Valve::_sp newValve;
// a bunch of epanet api calls to get properties from the link
EN_API_CHECK(EN_getlinkid(_enModel, iLink, enLinkName), "EN_getlinkid");
EN_API_CHECK(EN_getlinktype(_enModel, iLink, &linkType), "EN_getlinktype");
EN_API_CHECK(EN_getlinknodes(_enModel, iLink, &enFrom, &enTo), "EN_getlinknodes");
EN_API_CHECK(EN_getnodeid(_enModel, enFrom, enFromName), "EN_getnodeid - enFromName");
EN_API_CHECK(EN_getnodeid(_enModel, enTo, enToName), "EN_getnodeid - enToName");
EN_API_CHECK(EN_getlinkvalue(_enModel, iLink, EN_DIAMETER, &diameter), "EN_getlinkvalue EN_DIAMETER");
EN_API_CHECK(EN_getlinkvalue(_enModel, iLink, EN_LENGTH, &length), "EN_getlinkvalue EN_LENGTH");
EN_API_CHECK(EN_getlinkvalue(_enModel, iLink, EN_INITSTATUS, &status), "EN_getlinkvalue EN_STATUS");
EN_API_CHECK(EN_getlinkvalue(_enModel, iLink, EN_ROUGHNESS, &rough), "EN_getlinkvalue EN_ROUGHNESS");
EN_API_CHECK(EN_getlinkvalue(_enModel, iLink, EN_MINORLOSS, &mloss), "EN_getlinkvalue EN_MINORLOSS");
EN_API_CHECK(EN_getlinkvalue(_enModel, iLink, EN_INITSETTING, &setting), "EN_getlinkvalue EN_INITSETTING");
EN_API_CHECK(EN_getcomment(_enModel, EN_LINK, iLink, enComment), "EN_getlinkcomment");
linkName = string(enLinkName);
comment = string(enComment);
// get node pointers
startNode = nodeWithName(string(enFromName));
endNode = nodeWithName(string(enToName));
if (! (startNode && endNode) ) {
std::cerr << "could not find nodes for link " << linkName << std::endl;
throw "nodes not found";
}
// create the new specific type and add it.
// newPipe becomes the generic (base-class) pointer in all cases.
switch (linkType) {
case EN_PIPE:
newPipe.reset( new Pipe(linkName) );
newPipe->setNodes(startNode, endNode);
addPipe(newPipe);
break;
case EN_PUMP:
newPump.reset( new Pump(linkName) );
newPump->setNodes(startNode, endNode);
newPipe = newPump;
addPump(newPump);
{
// has curve?
int err = EN_getlinkvalue(_enModel, iLink, EN_PUMP_HCURVE, &curveIdx);
if (err == 0) {
Curve::_sp pumpCurve = namedCurves[(int)curveIdx];
if (pumpCurve) {
pumpCurve->inputUnits = this->flowUnits();
pumpCurve->outputUnits = this->headUnits();
newPump->setHeadCurve(pumpCurve);
}
}
err = EN_getlinkvalue(_enModel, iLink, EN_PUMP_ECURVE, &curveIdx);
if (err == 0) {
Curve::_sp effCurve = namedCurves[(int)curveIdx];
if (effCurve) {
effCurve->inputUnits = this->flowUnits();
effCurve->outputUnits = TSF_DIMENSIONLESS;
newPump->setEfficiencyCurve(effCurve);
}
}
}
break;
case EN_CVPIPE:
case EN_PSV:
case EN_PRV:
case EN_FCV:
case EN_PBV:
case EN_TCV:
case EN_GPV:
newValve.reset( new Valve(linkName) );
newValve->setNodes(startNode, endNode);
newValve->valveType = (int)linkType;
newValve->fixedSetting = setting;
newPipe = newValve;
addValve(newValve);
break;
default:
std::cerr << "could not find pipe type" << std::endl;
break;
} // switch linkType
// now that the pipe is created, set some basic properties.
newPipe->setDiameter(diameter);
newPipe->setLength(length);
newPipe->setRoughness(rough);
newPipe->setMinorLoss(mloss);
if (status == 0) {
newPipe->setFixedStatus(Pipe::CLOSED);
}
newPipe->flow()->setUnits(flowUnits());
newPipe->setUserDescription(comment);
} // for iLink
}
void EpanetModel::overrideControls() {
// set up counting variables for creating model elements.
int nodeCount, tankCount;
try {
EN_API_CHECK( EN_getcount(_enModel, EN_NODECOUNT, &nodeCount), "EN_getcount EN_NODECOUNT" );
EN_API_CHECK( EN_getcount(_enModel, EN_TANKCOUNT, &tankCount), "EN_getcount EN_TANKCOUNT" );
// eliminate all patterns and control rules
int nPatterns;
double sourcePat;
double zeroPattern[2];
zeroPattern[0] = 0;
// clear all patterns, set to zero. we do this to get rid of extra demand patterns set in [DEMANDS],
// since there's no other way to get to them using the toolkit.
EN_API_CHECK( EN_getcount(_enModel, EN_PATCOUNT, &nPatterns), "EN_getcount(EN_PATCOUNT)" );
for (int i=1; i<=nPatterns; i++) {
EN_API_CHECK( EN_setpattern(_enModel, i, zeroPattern, 1), "EN_setpattern" );
}
for(int iNode = 1; iNode <= nodeCount ; iNode++) {
// set pattern to index 0 (unity multiplier). this also rids us of any multiple demand patterns.
EN_API_CHECK( EN_setnodevalue(_enModel, iNode, EN_PATTERN, 0 ), "EN_setnodevalue(EN_PATTERN)" ); // demand patterns to unity
EN_API_CHECK( EN_setnodevalue(_enModel, iNode, EN_BASEDEMAND, 0. ), "EN_setnodevalue(EN_BASEDEMAND)" ); // set base demand to zero
// look for a quality source and nullify its existance
int errCode = EN_getnodevalue(_enModel, iNode, EN_SOURCEPAT, &sourcePat);
if (errCode != 240 /* == nonexistent source */) {
EN_API_CHECK( EN_setnodevalue(_enModel, iNode, EN_SOURCETYPE, EN_CONCEN), "EN_setnodevalue(EN_SOURCETYPE)" );
EN_API_CHECK( EN_setnodevalue(_enModel, iNode, EN_SOURCEQUAL, 0.), "EN_setnodevalue(EN_SOURCEQUAL)" );
EN_API_CHECK( EN_setnodevalue(_enModel, iNode, EN_SOURCEPAT, 0.), "EN_setnodevalue(EN_SOURCEPAT)" );
}
}
// set the global demand multiplier is unity as well.
EN_setoption(_enModel, EN_DEMANDPATTERN, 0); // set default pattern to internal
EN_setoption(_enModel, EN_DEMANDMULT, 1.);
// disregard controls and rules.
this->disableControls();
}
catch(string error) {
std::cerr << "ERROR: " << error;
throw RtxException();
}
// base class implementation
Model::overrideControls();
}
#pragma mark - Protected Methods:
std::ostream& EpanetModel::toStream(std::ostream &stream) {
// epanet-specific printing
stream << "Epanet Model File: " << endl;
Model::toStream(stream);
return stream;
}
#pragma mark Setters
/* setting simulation parameters */
void EpanetModel::setQualityOptions(QualityType qt, const std::string& traceNode) {
int epanet_qualcode = 0;
switch (qt) {
case None:
epanet_qualcode = 0;
break;
case Age:
epanet_qualcode = 2;
break;
case Trace:
epanet_qualcode = 3;
break;
default:
throw logic_error("unknown quality code");
break;
}
char traceNodeId[MAXID+1];
strncpy(traceNodeId, traceNode.c_str(), MAXID);
char blank[] = "";
int err = EN_setqualtype(_enModel, epanet_qualcode, blank, blank, traceNodeId);
try {
EN_API_CHECK(err, "setQualityOptions");
} catch (const std::string& err) {
cerr << "Error setting quality options: " << err << endl;
}
switch (qt) {
case Model::Age:
this->setQualityUnits(TSF_HOUR);
break;
case Model::Trace:
this->setQualityUnits(TSF_DIMENSIONLESS);
break;
default:
break;
}
}
Model::QualityType EpanetModel::qualityType() {
int code = 0, nodeIndex = 0;
int err = EN_getqualtype(_enModel, &code, &nodeIndex);
EN_API_CHECK(err, "qualityType");
switch (code) {
case 0:
return Model::None;
case 2:
return Model::Age;
case 3:
return Model::Trace;
default:
throw logic_error("unknown quality code");
break;
}
return Model::UNKNOWN;
}
std::string EpanetModel::qualityTraceNode() {
int code = 0, nodeIndex = 0;
int err = EN_getqualtype(_enModel, &code, &nodeIndex);
EN_API_CHECK(err, "qualityTraceNode");
char id[MAXID+1];
EN_API_CHECK( EN_getnodeid(_enModel, nodeIndex, id), "EN_getnodeid()" );
string traceNodeId = string(id);
return traceNodeId;
}
void EpanetModel::setReservoirHead(const string& reservoir, double level) {
setNodeValue(EN_TANKLEVEL, reservoir, level);
}
void EpanetModel::setReservoirQuality(const string& reservoir, double quality) {
setNodeValue(EN_INITQUAL, reservoir, quality); // set initquality in case setpoint is lower than old value
setNodeValue(EN_SOURCETYPE, reservoir, CONCEN);
setNodeValue(EN_SOURCEQUAL, reservoir, quality);
// if this is a tank, we must override the tank's concentration using private EPANET internals.
const int nJuncs = _enModel->network.Njuncs;
const int nodeIndex = _nodeIndex[reservoir];
if (nodeIndex > nJuncs) {
Stank *tanks = _enModel->network.Tank;
tanks[nodeIndex - nJuncs].C = quality;
_enModel->quality.NodeQual[nodeIndex] = quality / _enModel->Ucf[QUALITY];
}
}
void EpanetModel::setTankLevel(const string& tank, double level) {
// just refer to the reservoir method, since in epanet they are the same thing.
setReservoirHead(tank, level);
}
void EpanetModel::setJunctionDemand(const string& junction, double demand) {
int nodeIndex = _nodeIndex[junction];
// Junction demand is total demand - so deal with multiple categories by clearing them out.
int numDemands = 0;
EN_API_CHECK( EN_getnumdemands(_enModel, nodeIndex, &numDemands), "EN_getnumdemands()");
if (numDemands == 0) {
cerr << "epanet offers no base demand for this junction: " << junction << endl;
return;
}
// First demand category is the default one... per EPANET convention... and the one RTX wants to manipulate.
EN_API_CHECK( EN_setbasedemand(_enModel, nodeIndex, 1, demand), "EN_setbasedemand()" );
// and then set all other demand category multipliers to zero
for (int demandIdx = 2; demandIdx <= numDemands; demandIdx++) {
EN_API_CHECK( EN_setbasedemand(_enModel, nodeIndex, demandIdx, 0.0), "EN_setbasedemand()" );
}
}
void EpanetModel::setJunctionQuality(const std::string& junction, double quality) {
// todo - add more source types, depending on time series dimension?
setNodeValue(EN_INITQUAL, junction, quality); // set initquality in case setpoint is lower than old value
setNodeValue(EN_SOURCETYPE, junction, FLOWPACED);
setNodeValue(EN_SOURCEQUAL, junction, quality);
}
void EpanetModel::setPipeStatus(const string& pipe, Pipe::status_t status) {
setLinkValue(EN_STATUS, pipe, status);
}
void EpanetModel::setPipeStatusControl(const std::string& pipe, Pipe::status_t status, enableControl_t enableStatus) {
int linkIndex = _linkIndex[pipe];
int enEnableStatus = (enableStatus == enable) ? 1 : 0;
double en_status = (status == Pipe::status_t::CLOSED) ? EN_SET_CLOSED : EN_SET_OPEN;
if (_statusControlIndex.count(pipe) == 0) {
// if this element doesn't have a control, add one
int cindex;
EN_API_CHECK(EN_addcontrol(_enModel, EN_TIMER, linkIndex, (EN_API_FLOAT_TYPE)en_status, 0, (EN_API_FLOAT_TYPE)0.0, &cindex), "EN_addcontrol");
_statusControlIndex[pipe] = cindex;
EN_API_CHECK(EN_setcontrolenabled(_enModel, cindex, enEnableStatus), "EN_setControlEnabled");
}
else {
// set the control
int cindex = _statusControlIndex[pipe];
EN_API_CHECK(EN_setcontrol(_enModel, cindex, EN_TIMER, linkIndex, (EN_API_FLOAT_TYPE)en_status, 0, (EN_API_FLOAT_TYPE)0.0), "EN_setcontrol");
EN_API_CHECK(EN_setcontrolenabled(_enModel, cindex, enEnableStatus), "EN_setControlEnabled");
}
}
void EpanetModel::setPumpStatus(const string& pump, Pipe::status_t status) {
// call the setPipeStatus method, since they are the same in epanet.
setPipeStatus(pump, status);
}
void EpanetModel::setPumpStatusControl(const string& pump, Pipe::status_t status, enableControl_t enableStatus) {
// call the setPipeStatusControl method, since they are the same in epanet.
setPipeStatusControl(pump, status, enableStatus);
}
void EpanetModel::setPumpSetting(const string& pump, double setting) {
setLinkValue(EN_SETTING, pump, setting);
}
void EpanetModel::setPumpSettingControl(const string& pump, double setting, enableControl_t enableStatus) {
int linkIndex = _linkIndex[pump];
int enEnableStatus = (enableStatus == enable) ? 1 : 0;
if (_settingControlIndex.count(pump) == 0) {
// if this element doesn't have a control, add one
int cindex;
EN_API_CHECK(EN_addcontrol(_enModel, EN_TIMER, linkIndex, (EN_API_FLOAT_TYPE)setting, 0, (EN_API_FLOAT_TYPE)0.0, &cindex), "EN_addcontrol");
_settingControlIndex[pump] = cindex;
EN_API_CHECK(EN_setcontrolenabled(_enModel, cindex, enEnableStatus), "EN_setControlEnabled");
}
else {
// set the control
int cindex = _settingControlIndex[pump];
try {
EN_API_CHECK(EN_setcontrol(_enModel, cindex, EN_TIMER, linkIndex, (EN_API_FLOAT_TYPE)setting, 0, (EN_API_FLOAT_TYPE)0.0), "EN_setcontrol");
EN_API_CHECK(EN_setcontrolenabled(_enModel, cindex, enEnableStatus), "EN_setControlEnabled");
} catch (const std::string& errorMessage) {
stringstream ss;
ss << std::string(errorMessage) << EOL;
this->logLine(ss.str());
}
}
}
void EpanetModel::setValveSetting(const string& valve, double setting) {
setLinkValue(EN_SETTING, valve, setting);
}
void EpanetModel::setValveSettingControl(const string& valve, double setting, enableControl_t enableStatus) {
// call the setPumpSettingControl method, since they are the same in epanet.
setPumpSettingControl(valve, setting, enableStatus);
}
#pragma mark Getters
double EpanetModel::junctionDemand(const string &junction) {
return getNodeValue(EN_DEMAND, junction);
}
double EpanetModel::junctionHead(const string &junction) {
return getNodeValue(EN_HEAD, junction);
}
double EpanetModel::junctionPressure(const string &junction) {
return getNodeValue(EN_PRESSURE, junction);
}
double EpanetModel::junctionQuality(const string &junction) {
return getNodeValue(EN_QUALITY, junction);
}
double EpanetModel::tankInletQuality(const string& tank) {
// approximation: get flow in adjacent links, any quality going into the tank can be average flow-weighted.
auto t = dynamic_pointer_cast<Tank>(this->nodeWithName(tank));
double qualityIn = 0.0;
double totalFlowIn = 0.0;
for (auto l : t->links()) {
auto p = dynamic_pointer_cast<Pipe>(l);
auto flow = p->state_flow;
// ignore very small flows.
if (fabs(flow) < SMALL) {
continue;
}
// if flow is into the tank from this link.
// create a flow-weighted sum of qualities into the tank.
// flow towards the tank
if (p->to() == t && flow > 0) {
qualityIn += dynamic_pointer_cast<Junction>(p->from())->state_quality * flow;
totalFlowIn += flow;
}
// also flow towards the tank
else if (p->from() == t && flow < 0) {
qualityIn += dynamic_pointer_cast<Junction>(p->to())->state_quality * (-flow);
totalFlowIn += (-flow);
}
}
// complete the flow-weighted averaging.
qualityIn = qualityIn / totalFlowIn;
if (qualityIn == 0) {
return NAN;
}
else {
return qualityIn;
}
}
double EpanetModel::reservoirLevel(const string &reservoir) {
return getNodeValue(EN_TANKLEVEL, reservoir);
}
double EpanetModel::tankLevel(const string &tank) {
return junctionHead(tank) - nodeWithName(tank)->elevation(); // node elevation & head in same Epanet units
}
double EpanetModel::tankVolume(const string& tank) {
return getNodeValue(EN_TANKVOLUME, tank);
}
double EpanetModel::tankFlow(const string& tank) {
return getNodeValue(EN_DEMAND, tank);
}
double EpanetModel::pipeFlow(const string &pipe) {
return getLinkValue(EN_FLOW, pipe);
}
double EpanetModel::pipeStatus(const string &pipe) {
return getLinkValue(EN_STATUS, pipe);
}
double EpanetModel::pipeSetting(const string &pipe) {
return getLinkValue(EN_SETTING, pipe);
}
double EpanetModel::pipeEnergy(const string &name) {
return getLinkValue(EN_ENERGY, name);
}
#pragma mark - Sim options
void EpanetModel::enableControls() {
for (int i = 1; i <= _controlCount; ++i) {
EN_setcontrolenabled(_enModel, i, EN_TRUE);
}
int nC;
EN_getcount(_enModel, EN_RULECOUNT, &nC);
for (int i = 1; i <= nC; ++i) {
EN_setruleenabled(_enModel, i, EN_TRUE);
}
}
void EpanetModel::disableControls() {
for (int i = 1; i <= _controlCount; ++i) {
EN_setcontrolenabled(_enModel, i, EN_FALSE);
}
int nC;
EN_getcount(_enModel, EN_RULECOUNT, &nC);
for (int i = 1; i <= nC; ++i) {
EN_setruleenabled(_enModel, i, EN_FALSE);
}
}
#pragma mark Simulation Methods
bool EpanetModel::solveSimulation(time_t time) {
bool success = true;
long timestep;
int errorCode;
// set the current epanet-time to zero, since we override epanet-time.
setCurrentSimulationTime( time );
EN_API_CHECK(EN_settimeparam(_enModel, EN_HTIME, 0), "EN_settimeparam(EN_HTIME)");
EN_API_CHECK(EN_settimeparam(_enModel, EN_QTIME, 0), "EN_settimeparam(EN_QTIME)");
// solve the hydraulics
errorCode = EN_runH(_enModel, ×tep);
// check for success
success = this->_didConverge(time, errorCode);
if (errorCode > 0) {
char errorMsg[256];
EN_geterror(errorCode, errorMsg, 255);
struct tm * timeinfo = localtime (&time);
stringstream ss;
ss << std::string(errorMsg) << " :: " << asctime(timeinfo);
this->logLine(ss.str());
}
if (errorCode == 110) {
// ill conditioning can be helped by resetting some things
this->applyInitialTankLevels();
this->closeEngine();
this->initEngine();
errorCode = EN_runH(_enModel, ×tep);
if (errorCode > 0) {
char errorMsg[256];
EN_geterror(errorCode, errorMsg, 255);
struct tm * timeinfo = localtime (&time);
stringstream ss;
ss << "Re-setting did not help in this case... " << std::string(errorMsg) << " :: " << asctime(timeinfo);
this->logLine(ss.str());
}
}
// how to deal with lack of hydraulic convergence here - reset boundary/initial conditions?
if (this->shouldRunWaterQuality()) {
EN_API_CHECK(EN_runQ(_enModel, ×tep), "EN_runQ");
}
if (false) {
// log some info like DMA demands
for (auto dma : this->dmas()) {
double entotal = 0, rtxtotal = 0;
auto dmaName = dma->name();