-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample1_set_up_milpnet.py
1340 lines (1032 loc) · 60.1 KB
/
example1_set_up_milpnet.py
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
import gurobipy as gp
from gurobipy import GRB
import numpy as np
import scipy.sparse as sp
import wntr
import networkx as nx
import time
from scipy.optimize import curve_fit
pipe_valves = []
# function to calculate Hazen-Williams coefficient K for each pipe
def calc_K(L, D, R):
alpha = 10.66
e1 = 1.852
e2 = 4.87
return (alpha*L)/((R**e1)*(D**e2))
# function to calculate slope through single point on curve
def one_point_linear(Q_op, dH_op, K):
e1 = 1.852
slope = K * e1 * abs(Q_op) ** (e1-1)
intercept = dH_op - Q_op*slope
return slope, intercept
# function to calculate slope through single point on curve
def two_point_linear(Q_op, dH_op, K, range_Q):
e1 = 1.852
Q_1 = Q_op*(1-range_Q)
Q_2 = Q_op*(1+range_Q)
dH_1 = np.sign(Q_1) * K * abs(Q_1)**e1
dH_2 = np.sign(Q_2)* K * abs(Q_2)**e1
slope = (dH_2 - dH_1)/(Q_2 - Q_1)
intercept = dH_2 - Q_2*slope
return slope, intercept
# function to calculate and store new K~ value for each pipe and build incidence matrix
def extract_params(wn):
e1 = 1.852
e2 = 4.87
alpha = 10.67
#create name list variables
node_names = wn.node_name_list
pipe_names = wn.pipe_name_list
link_names = []
#number of each element - to demarcate sections of A21
num_nodes = wn.num_nodes
num_junc = wn.num_junctions
num_pipes = wn.num_pipes
#find incidence matrix and A21 matrix
pipe_tp =[]
pipe_tp2 = []
for link_name, link in wn.pipes():
pipe_tp.append(link.start_node_name)
pipe_tp2.append(link.end_node_name)
link_names.append(link_name)
new_pipes_list = tuple(zip(pipe_tp, pipe_tp2))
for link_name, link in wn.pumps(): # added pumps to inc_mat
pipe_tp.append(link.start_node_name)
pipe_tp2.append(link.end_node_name)
link_names.append(link_name)
for link_name, link in wn.valves(): # added pumps to inc_mat
pipe_tp.append(link.start_node_name)
pipe_tp2.append(link.end_node_name)
link_names.append(link_name)
link_list = tuple(zip(pipe_tp, pipe_tp2))
#extract A21 matrix
G = wn.get_graph()
inc_mat = sp.csr_matrix.toarray(nx.incidence_matrix(G,nodelist = node_names, edgelist = link_list, oriented=True))
A21 = inc_mat[0:num_junc,:]
K = np.zeros((num_pipes,1))
for i in range(num_pipes):
L = wn.get_link(pipe_names[i]).length
D = wn.get_link(pipe_names[i]).diameter
R = wn.get_link(pipe_names[i]).roughness
K[i] = (alpha*L)/((R**e1)*(D**e2))
return A21, K, inc_mat, node_names, link_names
# function to extract junction heads and reservoir/tank heads
def extract_d_h(wn, results, inc_mat, mult_ts):
#number of each element - to demarcate sections of A21
num_nodes = wn.num_nodes
junc_names = wn.junction_name_list
num_junc = wn.num_junctions
#retrieve known heads and demands from inp file
special_heads = np.zeros((num_nodes-num_junc,1))
heads_count = 0
ts = wn.options.time.report_timestep
#returns list of junction demands
junc_demands = np.zeros((num_junc,1))
for i in range(num_junc):
junc_demands[i] = results.node['demand'].loc[ts*mult_ts, junc_names[i]]
#stores head of reservoirs
for res_name, res in wn.reservoirs():
special_heads[heads_count] = results.node['head'].loc[ts*mult_ts, res_name]
heads_count = heads_count+1
#stores head of tanks
for tank_name, tank in wn.tanks():
special_heads[heads_count] = results.node['head'].loc[ts*mult_ts, tank_name]
heads_count = heads_count+1
special_heads_vec = -inc_mat.T[:,num_junc:num_nodes] @ (special_heads)
return junc_demands, special_heads_vec
# function to build K value if we linearize with a one-point or two-point approximation
def build_K_star(wn, results, inc_mat, mult_ts, K, op, range_Q, mid_point):
ts = wn.options.time.report_timestep
num_pipes = wn.num_pipes
num_links = wn.num_links
K_star = np.zeros((num_links,1))
K_int = np.zeros((num_links,1))
Q_test = results.link['flowrate'] # .loc[ts*mult_ts,:]
heads = results.node['head'] # .loc[ts*mult_ts,:]
Q_op = []
dH_op = []
if mid_point == True:
for i in range(num_pipes):
Q_op.append(0.5*(np.max(Q_test.loc[:,wn.pipe_name_list[i]]) + np.min(Q_test.loc[:,wn.pipe_name_list[i]])))
dH_op.append(np.sign(Q_op[i])*K[i]*abs(Q_op[i])**1.852)
else:
Q_op = Q_test.loc[op*ts, :]
dH_op = - inc_mat.T @ heads.loc[op*ts, :]
if range_Q == None:
for i in range(num_pipes):
K_s, K_i = one_point_linear(Q_op[i], dH_op[i], K[i])
K_star[i] = (K_s)
K_int[i] = (K_i)
else:
for i in range(num_pipes):
K_s, K_i = two_point_linear(Q_op[i], dH_op[i], K[i], range_Q)
K_star[i] = (K_s)
K_int[i] = (K_i)
return K_star, K_int
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx], idx
def pump_func(x, a, b):
return a - b * x**2
def piecewise_pump(p1, pump):
if len(pump.get_pump_curve().points) == 1:
A1, B1 = pump.get_pump_curve().points[0][0], pump.get_pump_curve().points[0][1]
A2, B2 = 0, 4*B1/3
A3, B3 = 2*A1, 0
xdata = [A1, A2, A3]
ydata = [B1, B2, B3]
elif len(pump.get_pump_curve().points) == 3:
A1, B1 = pump.get_pump_curve().points[0][0], pump.get_pump_curve().points[0][1]
A2, B2 = pump.get_pump_curve().points[1][0], pump.get_pump_curve().points[1][1]
A3, B3 = pump.get_pump_curve().points[2][0], pump.get_pump_curve().points[2][1]
xdata = [A1, A2, A3]
ydata = [B1, B2, B3]
else:
xdata = []
ydata = []
for k in range(len(pump.get_pump_curve().points)):
xdata.append(pump.get_pump_curve().points[k][0])
ydata.append(pump.get_pump_curve().points[k][1])
popt, pcov = curve_fit(pump_func, xdata, ydata)
A, B = popt[0], popt[1]
brackets = np.linspace(0,np.sqrt(A/B),p1+1)
H= A - B*brackets**2
return brackets, H
def piecewise_pipe(p2, results, pipe, K, range_Qp = None):
largest_q = np.max(results.link['flowrate'].loc[:,pipe])
smallest_q = np.min(results.link['flowrate'].loc[:,pipe])
q_bound = max(abs(largest_q), abs(smallest_q))
if range_Qp != None:
q_bound = q_bound*(1+range_Qp)
brackets = np.linspace(-q_bound, q_bound, p2+1)
if abs(brackets[1]-brackets[0]) < 10**(-6):
q_bound = np.mean(np.mean(results.link['flowrate']))
brackets = np.linspace(-q_bound, q_bound, p2+1)
H = np.sign(brackets)*K*abs(brackets)**1.852
plt_brackets = np.linspace(-1.5*q_bound, 1.5*q_bound, 100)
return brackets, H
# In[] Store pump cuve points to be used in PWL function
def run_gurobi(inp_file, no_ts = 3, num_pipe_seg = 3, num_pump_seg = 5, RELAX = 1, pump_on = False,
pump_off = False, gate_valves = [], gv_on = False, gv_off = False):
p1 = num_pump_seg
p2 = num_pipe_seg
pipe_valves = gate_valves
# Run hydraulic simulation and store results
wn = wntr.network.WaterNetworkModel(inp_file)
sim = wntr.sim.EpanetSimulator(wn)
results = sim.run_sim()
junc_names = wn.junction_name_list
node_names = wn.node_name_list
pipe_names = wn.pipe_name_list
num_junc = wn.num_junctions
num_pipes = wn.num_pipes
num_res = len(wn.reservoir_name_list)
num_tanks = len(wn.tank_name_list)
num_pumps = len(wn.pump_name_list)
num_valves = len(wn.valve_name_list)
num_links = len(wn.link_name_list)
# Time configuration
x_val = len(results.node['head'].loc[:, junc_names[0]])
time_step = wn.options.time.report_timestep
# mult_ts = 3600/time_step
mult_ts = 0
# x_plot = np.linspace(0,(x_val-1)/mult_ts,x_val)
report_time_step = wn.options.time.report_timestep
if no_ts == None:
no_ts = int(wn.options.time.duration/report_time_step)
Q_TS = np.zeros((num_pipes, no_ts))
QP_TS = np.zeros((num_pumps, no_ts))
QV_TS = np.zeros((num_valves, no_ts))
H_TS = np.zeros((num_junc, no_ts))
HPi_TS = np.zeros((num_pipes, no_ts))
HP_TS = np.zeros((num_pumps, no_ts))
HV_TS = np.zeros((num_valves, no_ts))
HT_TS = np.zeros((num_tanks, no_ts+1))
pump_x = []
pump_y = []
pipe_x = []
pipe_y = []
valve_x = []
valve_y = []
tank_elv = []
valve_dict = {}
A21, K, inc_mat, node_names, link_names = extract_params(wn)
junc_demands, special_heads_vec = extract_d_h(wn, results, inc_mat, mult_ts)
# K_star, K_int = build_K_star(wn, results, inc_mat, mult_ts, K, op, range_Q, mid_point)
for _, pump in wn.pumps():
x,y = piecewise_pump(p1, pump)
pump_x.append(x)
pump_y.append(y)
for i in range(num_pipes):
pipe = wn.pipe_name_list[i]
x,y = piecewise_pipe(p2, results, pipe, K[i])
pipe_x.append(x)
pipe_y.append(y)
for _, tank in wn.tanks():
tank_elv.append(tank.elevation)
for valve_name, valve in wn.valves():
#valve_x
valve_dict[valve_name] = {'Start node': valve.start_node_name,
'End node': valve.end_node_name,
'Setting': valve.setting,
'Type': valve.valve_type,
'Minor loss': valve.minor_loss,
'Start node index': wn.junction_name_list.index(valve.start_node_name),
'End node index': wn.junction_name_list.index(valve.end_node_name)}
# In[] Extract control rules and store in a dictionary
time_controls_dict = {}
event_controls_dict = {}
time_controls_compiled = {}
events_controls_pairs = {}
time_controls_link_list = []
event_controls_link_list = []
for i in range(len(wn.control_name_list)):
pattern = "'(.*?)'"
cont = wn.get_control(wn.control_name_list[i])
cont_str = str(cont)
contr_list = cont_str.split()
# print(cont_str)
# time-based controls
if 'TIME' in cont_str:
link_name = contr_list[7] # link name
sim_time = contr_list[4] # time
stat = contr_list[8] # status? setting?
stat_val = contr_list[10]
ctrl_name = 'Control {}'.format(i)
time_controls_dict[ctrl_name] = {'Link': link_name,
'Time': sim_time,
'Stat': stat,
'Stat val': stat_val}
if link_name not in time_controls_link_list:
time_controls_link_list.append(link_name)
# event-based controls
else:
node_name = contr_list[2]
link_name = contr_list[8]
node_level = contr_list[5]
sense = contr_list[4]
stat = contr_list[9]
stat_val = contr_list[11]
event_controls_dict['Control {}'.format(i)] = {'Link': link_name,
'Node': node_name,
'Sense': sense,
'Level': node_level,
'Stat': stat,
'Stat val': stat_val}
if link_name not in event_controls_link_list:
event_controls_link_list.append(link_name)
# store all time controls in one dict
for link in time_controls_link_list:
times_list_stat = [1- int(results.link['status'].loc[0,link])]
times_list_time = [0]
for key in list(time_controls_dict.keys()):
if time_controls_dict[key]['Link'] == link:
# dt_val = datetime.datetime.strptime(time_controls_dict[key]['Time'], "%H:%M:%S")
# time_val = int(datetime.timedelta(hours=dt_val.hour, minutes=dt_val.minute, seconds=dt_val.second).total_seconds())
# time_cont = float(time_val)/report_time_step
dt_list = time_controls_dict[key]['Time'].split(":")
dt_time = int(dt_list[0])*3600 + int(dt_list[1])*60 + int(dt_list[2])
time_cont = float(dt_time)/report_time_step
if time_cont <= no_ts:
if time_controls_dict[key]['Stat'] == 'status' or time_controls_dict[key]['Stat'] == 'STATUS':
if time_controls_dict[key]['Stat val'] == 'Open' or time_controls_dict[key]['Stat val'] == 'OPEN': # check if other stat vals are possible
times_list_stat.append(0)
else:
times_list_stat.append(1)
times_list_time.append(int(time_cont))
stat_array = np.zeros((no_ts))
for i in range(len(times_list_stat)-1):
stat_array[times_list_time[i]:times_list_time[i+1]] = times_list_stat[i]
stat_array[times_list_time[-1]:] = times_list_stat[-1]
time_controls_compiled[link] = {'Status':stat_array}
# store coupled event-based controls together
ev_pair_count = 0
ev_pair_list = []
above_list = ['>', 'ABOVE']
below_list = ['<', 'BELOW']
closed_list = ['Closed', 'CLOSED']
open_list = ['OPEN', 'Opened', 'Open']
for key in list(event_controls_dict.keys()):
for key_2 in list(event_controls_dict.keys()):
if key != key_2:
dict1 = event_controls_dict[key]
dict2 = event_controls_dict[key_2]
link, node = dict1['Link'], dict1['Node']
link_2, node_2 = dict2['Link'], dict2['Node']
if link == link_2 and node == node_2:
if (link,node) not in ev_pair_list:
# add other possibilites? setting for each kind of valve
# if status == link status
if dict1['Stat'] == 'status' or dict1['Stat'] == 'STATUS':
val1 = wn.get_node(node).elevation + float(dict1['Level'])
val2 = wn.get_node(node).elevation + float(dict2['Level'])
init = str(wn.get_link(link).initial_status) # results.link['status'].loc[0, link]
if init == 'Closed' or init :
init_stat = 1
if init == 'Open':
init_stat = 0
if dict1['Sense'] in above_list and dict1['Stat val'] in closed_list:
# print('yo')
events_controls_pairs[ev_pair_count] = {'Link': link,
'Node': node,
'Upper lim': val1,
'Lower lim': val2,
'Upper lim stat': 1, # this is the value that will go to y
'Lower lim stat': 0,
'Link initial status': init_stat} # this is the value that will go to y0
if dict1['Sense'] in above_list and dict1['Stat val'] in open_list: #unlikely
events_controls_pairs[ev_pair_count] = {'Link': link,
'Node': node,
'Upper lim': val1,
'Lower lim': val2,
'Upper lim stat': 0, # this is the value that will go to y
'Lower lim stat': 1,
'Link initial status': init_stat} # this is the value that will go to y0
if dict1['Sense'] in below_list and dict1['Stat val'] in closed_list: #unlikely
events_controls_pairs[ev_pair_count] = {'Link': link,
'Node': node,
'Upper lim': val2,
'Lower lim': val1,
'Upper lim stat': 0, # this is the value that will go to y
'Lower lim stat': 1,
'Link initial status': init_stat}
if dict1['Sense'] in below_list and dict1['Stat val'] in open_list:
events_controls_pairs[ev_pair_count] = {'Link': link,
'Node': node,
'Upper lim': val2,
'Lower lim': val1,
'Upper lim stat': 1, # this is the value that will go to y
'Lower lim stat': 0,
'Link initial status': init_stat}
ev_pair_count += 1
ev_pair_list.append((link,node))
# In[] compile lists of special links and their indices
# pumps, tank inlet, valves, other links in controls
special_link_list = []
special_link_index_list = []
unique_ctrl_link_list = []
unique_ctrl_ind_list = []
unique_pipe_valve_list = []
pipe_valve_ind_list = []
u_tank_count = 0
u_tank_link_list = []
u_tank_ind_list = []
# pumps
for pump_name,_ in wn.pumps():
special_link_list.append(pump_name)
special_link_index_list.append(link_names.index(pump_name))
# tank inlet pipes
for i in range(len(link_names)):
for j in range(num_tanks):
tank = wn.tank_name_list[j]
link = wn.get_link(link_names[i])
if link.start_node_name == tank or link.end_node_name == tank:
u_tank_count += 1
u_tank_link_list.append(link_names[i])
u_tank_ind_list.append(i)
if link_names[i] not in special_link_list:
special_link_list.append(link_names[i])
special_link_index_list.append(link_names.index(link_names[i]))
# valves
for valve_name,_ in wn.valves():
if valve_name not in special_link_list:
special_link_list.append(valve_name)
special_link_index_list.append(link_names.index(valve_name))
# time based controls
for link in time_controls_link_list:
if link not in special_link_list:
special_link_list.append(link)
special_link_index_list.append(link_names.index(link))
unique_ctrl_link_list.append(link)
# event based controls
for link in event_controls_link_list:
if link not in special_link_list:
special_link_list.append(link)
special_link_index_list.append(link_names.index(link))
unique_ctrl_link_list.append(link)
unique_ctrl_ind_list.append(link_names.index(link))
# pipe valves
for link in pipe_valves:
if link not in special_link_list:
special_link_list.append(link)
special_link_index_list.append(link_names.index(link))
unique_pipe_valve_list.append(link)
pipe_valve_ind_list.append(link_names.index(link))
num_unique_ctrl_links = len(unique_ctrl_link_list)
num_pipe_valves = len(unique_pipe_valve_list)
# In[]
# Build matrices and solve
A12 = A21.T
KA11 = np.zeros((num_links,num_links)) # not populated by K star
#build energy conservation rhs
energy_rhs = special_heads_vec # no K int here!
#build A_link submatrix
A_link = np.identity(num_links)
for i in range(num_pipes, num_links):
A_link[i,i] = -1
u_count = num_pumps + u_tank_count + num_valves + num_unique_ctrl_links + num_pipe_valves
u_block = np.zeros((num_links, u_count))
for i in range(num_pumps):
j = num_pipes + i
u_block[j][i] = 1 # we do this to avoid problems that might arise because of names (eg. there might be both a pipe 1 and a valve 1)
for i in range(u_tank_count):
j = u_tank_ind_list[i]
u_block[j][num_pumps + i] = 1
for i in range(num_valves):
j = num_pipes + num_pumps + i
u_block[j][num_pumps + u_tank_count + i] = 1
for i in range(num_unique_ctrl_links):
j = unique_ctrl_ind_list[i]
u_block[j][num_pumps + u_tank_count + num_valves + i] = 1
for i in range(num_pipe_valves):
j = pipe_valve_ind_list[i]
u_block[j][num_pumps + u_tank_count + num_valves + num_unique_ctrl_links] = 1
#build w block matrix
w_block = np.zeros((num_links, num_valves))
for i in range(num_valves):
j = num_pipes + num_pumps + i
w_block[j][i] = -1
up_TS = np.zeros((num_pumps, no_ts))
ut_TS = np.zeros((u_tank_count, no_ts))
uv_TS = np.zeros((num_valves, no_ts))
uu_TS = np.zeros((num_unique_ctrl_links, no_ts))
upv_TS = np.zeros((num_pipe_valves, no_ts))
#build tank volume continuity equation
Vt = np.zeros((num_tanks, num_links))
Htanks = np.zeros((num_tanks, 1))
for j in range(len(wn.tank_name_list)):
tank = wn.get_node(wn.tank_name_list[j])
tank_ind = num_junc + num_res + j
prev_tank_head = np.array(inc_mat[tank_ind,:])[np.newaxis] @ special_heads_vec
diam = tank.diameter
Htanks[j] = - prev_tank_head
Vt[j,:] = np.array(inc_mat[tank_ind,:])[np.newaxis]*(time_step/(np.pi*(diam/2)**2)) #check sign
HT_TS[j,0] = -prev_tank_head
# build A submatrix
A_sub = np.block([[KA11, A12, A_link, u_block, w_block, np.zeros((num_links,num_tanks))], # delta H = H1 - H2 + u ...
[A21, np.zeros((num_junc,num_junc)), np.zeros((num_junc,num_links)), np.zeros((num_junc, u_count)), np.zeros((num_junc, num_valves)), np.zeros((num_junc, num_tanks))], # sum of Q = d
[-Vt, np.zeros((num_tanks,num_junc)), np.zeros((num_tanks,num_links)), np.zeros((num_tanks, u_count)), np.zeros((num_tanks, num_valves)), np.identity(num_tanks) ]]) # tank storage
# build b submatrix
b_sub = np.vstack((energy_rhs, junc_demands, Htanks)) #check sign
A = A_sub # just in case there's only one time step
b = b_sub
# Build master matrices
for i in range(1,no_ts):
# Update RHS vector
mult_ts = i
num_nodes = wn.num_nodes
num_junc = wn.num_junctions
num_pipes = wn.num_pipes
A_dim0 = A.shape[0]
A_dim1 = A.shape[1]
special_heads = np.zeros((num_res,1))
heads_count = 0
junc_demands = np.zeros((num_junc,1))
for j in range(num_junc):
junc_demands[j] = results.node['demand'].loc[i*time_step, junc_names[j]] # update junctions
#stores head of reservoirs
for res_name, res in wn.reservoirs():
special_heads[heads_count] = results.node['head'].loc[i*time_step, res_name]
heads_count = heads_count+1
special_heads_vec = - inc_mat.T[:, num_junc : num_junc + num_res] @ (special_heads)
# build energy conservation rhs
energy_rhs = special_heads_vec
Vt = np.zeros((num_tanks, num_links))
Htanks = np.zeros((num_tanks, 1))
A_tank = inc_mat[num_nodes - num_tanks : num_nodes,:].T
for j in range(len(wn.tank_name_list)):
tank = wn.get_node(wn.tank_name_list[j])
tank_ind = num_junc + num_res + j
diam = tank.diameter
Vt[j,:] = np.array(inc_mat[tank_ind,:])[np.newaxis]*(time_step/(np.pi*(diam/2)**2))
# build A submatrix
A_tank_block = np.vstack((A_tank, np.zeros((num_junc, num_tanks)), -np.identity(num_tanks)))
A_sub1 = np.hstack((A_tank_block, A_sub))
# build b submatrix
b_sub1 = np.vstack((energy_rhs, junc_demands, np.zeros((num_tanks,1))))
# define A and b
A = np.block([[A, np.zeros((A_dim0, A_sub1.shape[1] - num_tanks))],
[np.zeros((A_sub1.shape[0], A_dim1 - num_tanks)), A_sub1]])
b = np.vstack((b, b_sub1))
# In[] Build Gurobi optimization problem
# Build right hand side
rhs = []
for i in range(len(b)):
rhs.append(b[i][0])
rhs = np.array(rhs)
no_cons = A.shape[1] # should be (num_junc + 2 * num_links + num_tanks) * no_ts
Q_pipes, Q_pumps, Q_valves = {}, {}, {} # flowrates
H_nodes, H_pipes, H_pumps, H_valves = {}, {}, {}, {} # heads and head differences
u_pumps, u_tanks, u_valves, u_conts, u_pvalves, w_valves = {}, {}, {}, {}, {}, {} # u slack values
H_tanks = {} # tank heads
y_pumps, y_tanks, y_controls, y_pvalves = {}, {}, {}, {} # on/off variables
z1_cont, z2_cont, z3_cont, z4_cont = {}, {}, {}, {} # control rules binary variables
z1_inlet, z2_inlet, z3_inlet, z4_inlet = {}, {}, {}, {} # tank inlet pipe binary variables
v1, v2, v3 = {}, {}, {} # valve status binary variables
# Define bounds
lbounds_qpipes, ubounds_qpipes = [], []
lbounds_qpumps, ubounds_qpumps = [], []
lbounds_qvalves, ubounds_qvalves = [], []
lbounds_hnodes, ubounds_hnodes = [], []
lbounds_hpipes, ubounds_hpipes = [], []
lbounds_hpumps, ubounds_hpumps = [], []
lbounds_hvalves, ubounds_hvalves = [], []
lbounds_upumps, ubounds_upumps = [], []
lbounds_utanks, ubounds_utanks = [], []
lbounds_uvalves, ubounds_uvalves = [], []
lbounds_ucont, ubounds_ucont = [], []
lbounds_upvalves, ubounds_upvalves = [], []
lbounds_wvalves, ubounds_wvalves = [], []
lbounds_htanks, ubounds_htanks = [], []
largest_q = max(np.max(results.link['flowrate']))
smallest_q = min(np.min(results.link['flowrate']))
q_bound = max(abs(largest_q), abs(smallest_q))
h_bound = max(np.max(results.node['head']))
for i in range(num_pipes):
lbounds_qpipes.append(-2 * q_bound)
ubounds_qpipes.append(2 * q_bound)
for i in range(num_pumps):
lbounds_qpumps.append(0)
ubounds_qpumps.append(pump_x[i][len(pump_x[0])-1])
for i in range(num_valves):
lbounds_qvalves.append(0)
ubounds_qvalves.append(q_bound)
for i in range(num_junc):
lbounds_hnodes.append(wn.get_node(wn.junction_name_list[i]).elevation) # forcing pressures to be >= 0
ubounds_hnodes.append(2 * h_bound)
for i in range(num_pipes):
lbounds_hpipes.append(-2 * h_bound)
ubounds_hpipes.append(2 * h_bound)
for i in range(num_pumps):
lbounds_hpumps.append(0)
ubounds_hpumps.append(pump_y[i][0])
for i in range(num_valves):
lbounds_hvalves.append(-2 * h_bound)
ubounds_hvalves.append(2 * h_bound)
for i in range(num_pumps):
lbounds_upumps.append(-h_bound)
ubounds_upumps.append(h_bound)
for i in range(u_tank_count):
lbounds_utanks.append(-h_bound)
ubounds_utanks.append(h_bound)
for i in range(num_valves):
lbounds_uvalves.append(-h_bound)
ubounds_uvalves.append(h_bound)
for i in range(num_unique_ctrl_links):
lbounds_ucont.append(-h_bound)
ubounds_ucont.append(h_bound)
for i in range(num_pipe_valves):
lbounds_upvalves.append(-h_bound)
ubounds_upvalves.append(h_bound)
for i in range(num_valves):
lbounds_wvalves.append(0)
ubounds_wvalves.append(h_bound)
for i in range(num_tanks):
tank = wn.get_node(wn.tank_name_list[i])
lbounds_htanks.append(tank.elevation + tank.min_level)
ubounds_htanks.append(tank.elevation + tank.max_level)
# Define some constants
eps_flow = 0.000001
eps_head = 0.1
M = h_bound * 1.1
# M_q = q_bound * 1.1
try:
t1 = time.time()
#####################################################################################################################################################################################
# Create a new model
m = gp.Model("Net1")
m.reset()
#####################################################################################################################################################################################
# Create variables
for i in range(no_ts):
Q_pipes[i] = m.addMVar(shape = num_pipes, lb=lbounds_qpipes, ub=ubounds_qpipes, vtype=GRB.CONTINUOUS, name="Q_pipes {}".format(i))
if num_pumps > 0:
Q_pumps[i] = m.addMVar(shape = num_pumps, lb=lbounds_qpumps, ub=ubounds_qpumps, vtype=GRB.CONTINUOUS, name="Q_pumps {}".format(i))
if num_valves > 0:
Q_valves[i] = m.addMVar(shape = num_valves, lb=lbounds_qvalves, ub=ubounds_qvalves, vtype=GRB.CONTINUOUS, name="Q_valves {}".format(i))
H_nodes[i] = m.addMVar(shape = num_junc, lb=lbounds_hnodes, ub=ubounds_hnodes, vtype=GRB.CONTINUOUS, name="H_nodes {}".format(i))
H_pipes[i] = m.addMVar(shape = num_pipes, lb=lbounds_hpipes, ub=ubounds_hpipes, vtype=GRB.CONTINUOUS, name="H_pipes {}".format(i))
if num_pumps > 0:
H_pumps[i] = m.addMVar(shape = num_pumps, lb=lbounds_hpumps, ub=ubounds_hpumps, vtype=GRB.CONTINUOUS, name="H_pumps {}".format(i))
if num_valves > 0:
H_valves[i] = m.addMVar(shape = num_valves, lb=lbounds_hvalves, ub=ubounds_hvalves, vtype=GRB.CONTINUOUS, name="H_valves {}".format(i))
if num_pumps > 0:
u_pumps[i] = m.addMVar(shape = num_pumps, lb=lbounds_upumps, ub=ubounds_upumps, vtype=GRB.CONTINUOUS, name="u_pump {}".format(i))
u_tanks[i] = m.addMVar(shape = u_tank_count, lb=lbounds_utanks, ub=ubounds_utanks, vtype=GRB.CONTINUOUS, name="u_tanks {}".format(i))
if num_valves > 0:
u_valves[i] = m.addMVar(shape = num_valves, lb=lbounds_uvalves, ub=ubounds_uvalves, vtype=GRB.CONTINUOUS, name="u_valves {}".format(i))
if num_unique_ctrl_links > 0:
u_conts[i] = m.addMVar(shape = num_unique_ctrl_links, lb=lbounds_ucont, ub=ubounds_ucont, vtype=GRB.CONTINUOUS, name="u_conts {}".format(i))
if num_pipe_valves > 0:
u_pvalves[i] = m.addMVar(shape = num_pipe_valves, lb=lbounds_upvalves, ub=ubounds_upvalves, vtype=GRB.CONTINUOUS, name="u_pvalves {}".format(i))
if num_valves > 0:
w_valves[i] = m.addMVar(shape = num_valves, lb=lbounds_wvalves, ub=ubounds_wvalves, vtype=GRB.CONTINUOUS, name="w_valves {}".format(i))
H_tanks[i] = m.addMVar(shape = num_tanks, lb=lbounds_htanks, ub=ubounds_htanks, vtype=GRB.CONTINUOUS, name="H_tanks {}".format(i+1))
#####################################################################################################################################################################################
# Load all current variable into one vector x_A
m.update()
x_A = gp.MVar(m.getVars())
m.update()
#####################################################################################################################################################################################
# MATRIX CONSTRAINTS (head loss, mass balance, tank storage)
m.addConstr(A @ x_A == rhs, name = "block") # for mass balance, head loss, tank storage constraints
m.update()
#####################################################################################################################################################################################
# PWL PIPE HEAD LOSS CONSTRAINTS
for i in range(no_ts):
for j in range(num_pipes):
m.addGenConstrPWL(Q_pipes[i][j], H_pipes[i][j], pipe_x[j], pipe_y[j])
#####################################################################################################################################################################################
# PWL PUMP HEAD GAIN CONSTRAINTS
if num_pumps > 0:
for i in range(no_ts):
for j in range(num_pumps):
m.addGenConstrPWL(Q_pumps[i][j], H_pumps[i][j], pump_x[j], pump_y[j])
#####################################################################################################################################################################################
# ALLOW PUMP TO DISCONNECT
if num_pumps > 0:
for i in range(no_ts):
y_pumps[i] = m.addMVar(num_pumps, vtype = GRB.BINARY, name = "y_pumps {}".format(i))
# Initial conditions for the pump and tank inlet pipe
for i in range(num_pumps):
stat = str(wn.get_link(wn.pump_name_list[i]).initial_status)
# print('stat', stat)
if stat == 'Open' or stat == 0:
m.addConstr(y_pumps[0][i] == 0)
m.addConstr(u_pumps[0][i] == 0)
else:
m.addConstr(y_pumps[0][i] == 1)
m.addConstr(Q_pumps[0][i] == 0)
for i in range(no_ts):
for j in range(num_pumps):
# Define big M value
M = max(ubounds_upumps) + 5
m.addConstr(-Q_pumps[i][j] - M*(1-y_pumps[i][j]) <= 0)
m.addConstr(Q_pumps[i][j] - M*(1-y_pumps[i][j]) <= 0)
m.addConstr((y_pumps[i][j] == 0) >> (u_pumps[i][j] == 0))
m.addConstr((y_pumps[i][j] == 1) >> (Q_pumps[i][j] == 0))
## forcing pump 1 to be open the whole time
if pump_on == True:
for i in range(no_ts):
m.addConstr(y_pumps[i][0] == 0)
## forcing pump 1 to be open the whole time
if pump_off == True:
for i in range(no_ts):
m.addConstr(y_pumps[i][0] == 1)
#####################################################################################################################################################################################
# FORCE TANK INLET PIPE TO CLOSE ONLY IF TANK LEVEL HITS MAX OR MIN
for i in range(no_ts):
y_tanks[i] = m.addMVar(u_tank_count, vtype = GRB.BINARY, name = "y tanks {}".format(i))
z1_inlet[i] = m.addMVar(u_tank_count, vtype = GRB.BINARY, name = "z1_inlet {}".format(i))
z2_inlet[i] = m.addMVar(u_tank_count, vtype = GRB.BINARY, name = "z2_inlet {}".format(i))
for i in range(u_tank_count):
m.addConstr(y_tanks[0][i] == 0) ####### edit this at some point! to reflect actual starting
m.addConstr(u_tanks[0][i] == 0)
m.addConstr(z1_inlet[0][i] == 0)
m.addConstr(z2_inlet[0][i] == 1)
for i in range(1,no_ts):
for j in range(num_tanks):
ind = u_tank_ind_list[j]
up_bd = ubounds_htanks[j]
lo_bd = lbounds_htanks[j]
M_tank = up_bd - lo_bd + 500
# I tank level greater than or equal to upper bound
m.addConstr(H_tanks[i-1][j] >= up_bd - M_tank*(1-z1_inlet[i][j]))
m.addConstr(H_tanks[i-1][j] + eps_head <= up_bd + M_tank*z1_inlet[i][j])
# II tank level greater than lower lim
m.addConstr(H_tanks[i-1][j] >= lo_bd - M_tank*(1-z2_inlet[i][j]) + eps_head)
m.addConstr(H_tanks[i-1][j] <= lo_bd + M_tank*z2_inlet[i][j])
# III tank level between lower and upper lim
m.addConstr(y_tanks[i][j] == z1_inlet[i][j] - z2_inlet[i][j] + 1, name = "III {}".format(i)) # is this right?
# IV putting it all together
m.addConstr(-Q_pipes[i][ind] - M_tank*(1-y_tanks[i][j]) <= 0)
m.addConstr(Q_pipes[i][ind] - M_tank*(1-y_tanks[i][j]) <= 0) ##### try to change M val here
m.addConstr((y_tanks[i][j] == 0) >> (u_tanks[i][j] == 0))
m.addConstr((y_tanks[i][j] == 1) >> (Q_pipes[i][ind] == 0))
#####################################################################################################################################################################################
# VALVE STATUS RULES
if num_valves > 0:
for i in range(no_ts):
v1[i] = m.addMVar(num_valves, vtype = GRB.BINARY, name = "v1 {}".format(i))
v2[i] = m.addMVar(num_valves, vtype = GRB.BINARY, name = "v2 {}".format(i))
v3[i] = m.addMVar(num_valves, vtype = GRB.BINARY, name = "v3 {}".format(i))
for i in range(no_ts):
for j in range(num_valves):
valve_name = wn.valve_name_list[j]
M = M_tank
# PRV
if valve_dict[valve_name]['Type'] == 'PRV':
start_ind = valve_dict[valve_name]['Start node index']
end_ind = valve_dict[valve_name]['End node index']
Hset_start = wn.get_node(valve_dict[valve_name]['End node']).elevation + valve_dict[valve_name]['Setting']
Hset_end = wn.get_node(valve_dict[valve_name]['End node']).elevation + valve_dict[valve_name]['Setting']
#1
m.addConstr(v1[i][j] + v2[i][j] + v3[i][j] == 1, name = 'Valve status')
# 2
m.addConstr(-M*v3[i][j] <= u_valves[i][j])
m.addConstr(u_valves[i][j] <= M*v3[i][j])
# 3
# m.addConstr(-M*(1-v3[i][j]) <= Q_valves[i][j])
# m.addConstr(Q_valves[i][j] <= M*(1-v3[i][j]))
#4
m.addConstr(H_nodes[i][start_ind] - H_nodes[i][end_ind] >= -M*v3[i][j])
#5
m.addConstr(H_nodes[i][start_ind] - H_nodes[i][end_ind] + eps_head* v3[i][j] <= M*(1-v3[i][j]))
#6
m.addConstr(Hset_start - H_nodes[i][start_ind] >= -M*(1-v2[i][j]) - M*v1[i][j] + eps_head*v2[i][j])
#7
m.addConstr(Hset_start - H_nodes[i][start_ind] <= M*(1-v1[i][j]) + M*v2[i][j])
#8
m.addConstr(w_valves[i][j] <= M*v1[i][j] )# + v2[i][j])
# m.addConstr(w_valves[i][j] >= -eps_head * v2[i][j])
#9
m.addConstr(Hset_end*v1[i][j] - M*v2[i][j] - M*v3[i][j] <= H_nodes[i][end_ind])
m.addConstr(H_nodes[i][end_ind] <= Hset_end*v1[i][j] + M*v2[i][j] + M*v3[i][j])
# # 10
m.addConstr((v1[i][j] == 1) >> (Q_valves[i][j] >= eps_flow))
m.addConstr((v1[i][j] == 1) >> (u_valves[i][j] == 0))
m.addConstr((v2[i][j] == 1) >> (Q_valves[i][j] >= eps_flow))
m.addConstr((v2[i][j] == 1) >> (u_valves[i][j] == 0))
m.addConstr((v3[i][j] == 1) >> (Q_valves[i][j] == 0))
if valve_dict[valve_name]['Minor loss'] == 0:
m.addConstr((v2[i][j] == 1) >> (H_nodes[i][start_ind] == H_nodes[i][end_ind]))
# else: flesh this out later!
#####################################################################################################################################################################################
# ALLOW GATE VALVE TO DISCONNECT
if num_pipe_valves > 0:
for i in range(no_ts):
y_pvalves[i] = m.addMVar(num_pipe_valves, vtype = GRB.BINARY, name = "y_pvalve{}".format(i))
# Initial conditions for the pump and tank inlet pipe
for i in range(num_pipe_valves):
stat = str(wn.get_link(unique_pipe_valve_list[i]).initial_status)
# print('Stat', stat)
if stat == 'Open' or stat == 0:
m.addConstr(y_pvalves[0][i] == 0)
m.addConstr(u_pvalves[0][i] == 0)
else:
m.addConstr(y_pvalves[0][i] == 1)
m.addConstr(Q_pipes[0][pipe_valve_ind_list[i]] == 0)
for i in range(no_ts):
for j in range(num_pipe_valves):
# Define big M value