-
Notifications
You must be signed in to change notification settings - Fork 1
/
OPF_algs.py
executable file
·1686 lines (1421 loc) · 71.3 KB
/
OPF_algs.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
#!/usr/bin/python
__author__ = 'Majid Khonji'
import numpy as np
import time
import instance as a
import logging
import networkx as nx
import util as u
import itertools
import copy
import sys
try:
import gurobipy as gbp
except ImportError:
logging.warning("Grubi not available!!")
# minimization version (naive bruteforce)
# consider all integral demands
# mode=['naive', 'frac_only']
def PTAS(ins, epsilon = 0.0001, max_guessed_set_size=None, use_LP=True, mode='frac_only'):
if max_guessed_set_size == None:
max_guessed_set_size = ins.n
t1 = time.time()
best_sol = a.OPF_sol();
best_sol.obj = np.inf
solf = min_OPF_OPT(ins, guess_x={}, fractional=True)
sol = round_OPF(ins, use_LP=use_LP, guess_x={})
if not sol.succeed:
return sol
enumeration_set = ins.I
if mode == 'frac_only':
enumeration_set = [k for k in ins.I if ins.rounding_tolerance < solf.x[k] < 1 - ins.rounding_tolerance]
try_count = 1
if(sol.obj <= (1+epsilon)* solf.obj ):
sol.try_count = try_count
sol.try_residue_count = 1
best_sol.running_time = time.time() - t1
return sol
if sol.obj < best_sol.obj and sol.succeed:
best_sol = sol
best_sol.guess_I1 = {}
best_sol.guess_I2 = {}
solution_found = False
try_residue_count = 0
for size in np.arange(1, max_guessed_set_size + 1):
for guess_I1 in itertools.combinations(enumeration_set, size):
try_count += 1
try_residue_count += 1
min_util = np.min([ins.loads_utilities[k] for k in guess_I1])
guess_I2 = {k: 0 for k in np.setdiff1d(ins.I, guess_I1) if ins.loads_utilities[k] <= min_util}
guess_x = {k: 1 for k in guess_I1}
for k in guess_I2:
guess_x[k] = 0
print guess_I1
print len(guess_x)
sol = round_OPF(ins, use_LP=use_LP, guess_x=guess_x)
if sol.succeed:
if sol.obj < best_sol.obj:
best_sol = sol
best_sol.guess_I1 = guess_I1
best_sol.guess_I2 = guess_I2
print 'obj', best_sol.obj, '| frac_obj', solf.obj, "| acheived e", 1-((1+epsilon)* solf.obj)/best_sol.obj
if best_sol.obj <= (1+epsilon)* solf.obj:
print "solution found!"
solution_found = True
break
if solution_found:
break
try_residue_count = 0
best_sol.running_time = time.time() - t1
best_sol.try_count = try_count
best_sol.try_residue_count = try_residue_count
best_sol.guessed_set_size = size
return best_sol
def PTAS_rand_sample(ins, epsilon = 0.1, max_tries = np.infty, use_LP=True, mode='frac_only'):
#assert (2*ins.topology.graph["m"]+len(ins.leaf_nodes))/epsilon < ins.n, 'Very small epsilon %f'% epsilon
max_set_size = (2*ins.topology.graph["m"]+len(ins.leaf_nodes))/epsilon
if max_set_size > ins.n:
max_set_size = ins.n
t1 = time.time()
solf = min_OPF_OPT(ins, guess_x={}, fractional=True)
best_sol = round_OPF(ins, use_LP=use_LP, guess_x={})
try_count = 1
guess_I1 = {}
guess_I2 = {}
size=0
while best_sol.obj > (1+epsilon)* solf.obj and best_sol.succeed and try_count <= max_tries:
size = np.random.randint(1,max_set_size)
guess_I1 = np.random.choice(ins.n, size, replace=False)
#print guess_I1
# print 'obj', best_sol.obj, '| frac_obj', solf.obj, "| acheived e", 1-((1+epsilon)* solf.obj)/best_sol.obj
sys.stdout.write('.')
try_count += 1
min_util = np.min([ins.loads_utilities[k] for k in guess_I1])
guess_I2 = {k: 0 for k in np.setdiff1d(ins.I, guess_I1) if ins.loads_utilities[k] <= min_util}
guess_x = {k: 1 for k in guess_I1}
for k in guess_I2:
guess_x[k] = 0
#print len(guess_x), 'size =', size
if u.check_opf_sol_feasibility(ins, guess_x):
sol = round_OPF(ins, use_LP=use_LP, guess_x=guess_x)
if sol.succeed:
if sol.obj < best_sol.obj:
best_sol = sol
print ''
best_sol.guess_I1 = guess_I1
best_sol.guess_I2 = guess_I2
best_sol.running_time = time.time() - t1
best_sol.try_count = try_count
best_sol.guessed_set_size = size
return best_sol
# we use the same objective as min_OPF_OPT: penalty + loss + 1
# some nasty tricks: if solve_remaining fails, we take loss from the fractional solution (its a bound, right?)
def round_OPF(ins, use_LP=True, guess_x={}, alg='min_OPF_round', frac_sol = None):
T = ins.topology
t1 = time.time()
sol = None
if frac_sol == None:
if not ins.util_max_objective:
sol = min_OPF_OPT(ins, guess_x=guess_x, fractional=True)
elif ins.util_max_objective and ins.drop_l_terms:
sol = max_sOPF_OPT(ins, guess_x=guess_x, fractional=True)
else:
sol = copy.copy(frac_sol)
sol.frac_comp_count = 0
if sol.succeed:
# print 'calling lp'
customers = np.setdiff1d(ins.I, guess_x)
sol_lp = sol
if use_LP:
sol_lp = _LP(ins, sol, customers)
if sol_lp.succeed:
for k in customers:
sol.x[k] = sol_lp.x[k]
for k in customers:
if ins.rounding_tolerance < sol.x[k] < 1 - ins.rounding_tolerance:
sol.x[k] = 0
sol.frac_comp_count += 1
elif sol.x[k] >= 1-ins.rounding_tolerance:
sol.x[k] = 1
elif sol.x[k] <= ins.rounding_tolerance:
sol.x[k] = 0
sol.running_time = time.time() - t1
if ins.util_max_objective:
obj = 0
for k in range(ins.n):
obj += sol.x[k] * ins.loads_utilities[k]
sol.obj = obj
sol.frac_comp_percentage = sol.frac_comp_count / (ins.n * 1.) * 100
return sol
else:
if ins.drop_l_terms_obj:
obj = 0
for k in range(ins.n):
obj += (1 - sol.x[k]) * ins.loads_utilities[k]
sol.obj = obj
sol.frac_comp_percentage = sol.frac_comp_count / (ins.n * 1.) * 100
return sol
else:
obj = 0
sol2 = _solve_remaining(ins, guess_x=sol.x)
if sol2.succeed:
pass
obj += T.graph['S_base'] * sol2.obj
else:
obj += T.graph['S_base'] * u.obj_min_loss_penalty(ins, sol, output='loss')
sol2.x = sol.x
sol2.succeed = True
sol2.obj = obj
sol2.frac_comp_count = sol.frac_comp_count
sol2.frac_comp_percentage = sol2.frac_comp_count / (ins.n * 1.) * 100
sol2.running_time = time.time() - t1
return sol2
sol.succeed = False
return sol
def _LP(ins, sol, customers=[], alg='lp'):
t1 = time.time()
T = ins.topology
m = gbp.Model("lp")
u.gurobi_setting(m)
x = {}
for k in customers: x[k] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="x[%d]" % k)
if ins.util_max_objective:
obj = gbp.quicksum(x[k] * ins.loads_utilities[k] for k in customers)
m.setObjective(obj, gbp.GRB.MAXIMIZE)
else:
obj = gbp.quicksum((1 - x[k]) * ins.loads_utilities[k] for k in customers)
m.setObjective(obj, gbp.GRB.MINIMIZE)
if ins.cons == '' or ins.cons == 'C':
for e in T.edges():
# print "edge ", e
edge_customers = np.intersect1d(customers, T[e[0]][e[1]]['K'])
C_P = np.sum([sol.x[k] * ins.loads_P[k] for k in edge_customers])
# print C_P
lhs_P = gbp.quicksum([x[k] * ins.loads_P[k] for k in edge_customers])
m.addConstr(lhs_P, gbp.GRB.LESS_EQUAL, C_P, "Cp_%s" % str(e))
C_Q = np.sum([sol.x[k] * ins.loads_Q[k] for k in edge_customers])
lhs_Q = gbp.quicksum([x[k] * ins.loads_Q[k] for k in edge_customers])
m.addConstr(lhs_Q, gbp.GRB.LESS_EQUAL, C_Q, "Cq_%s" % str(e))
if not ins.drop_l_terms and (ins.cons == '' or ins.cons == 'V'):
for l in ins.leaf_nodes:
C_V = np.sum([ins.Q[(k, l)] * sol.x[k] for k in customers])
lhs_V = gbp.quicksum([ins.Q[(k, l)] * x[k] for k in customers])
m.addConstr(lhs_V, gbp.GRB.LESS_EQUAL, C_V, "Cv_%s" % str(l))
for k in customers:
m.addConstr(x[k] <= 1, "x[%d]: ub")
# m.addConstr(x[k] >= 0, "x[%d]: lb")
m.update()
# m.computeIIS()
# m.write("model.ilp")
m.optimize()
sol = a.OPF_sol()
sol.running_time = time.time() - t1
sol.gurobi_model = m
if u.gurobi_handle_errors(m, algname=alg):
sol.obj = obj.getValue()
sol.x = {k: x[k].x for k in customers}
# logging.info("\tx = %s" % str(sol.x))
# logging.info("\t{k: x_k>0} = %s" % str([k for k in range(ins.n) if sol.x[k] > 0]))
sol.succeed = True
else:
sol.succeed = False
return sol
# minimizes loss
def _solve_remaining(ins, guess_x={}, alg="solve_remaining"):
t1 = time.time()
T = ins.topology
m = gbp.Model("qcp")
u.gurobi_setting(m)
x = guess_x
v = {}
v[0] = ins.v_0
l = {}
P = {}
Q = {}
for i in T.nodes()[1:]:
v[i] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="v_%d" % i)
for e in T.edges(): l[e] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="l_%s" % str(e))
for e in T.edges(): P[e] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="P_%s" % str(e))
for e in T.edges(): Q[e] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="Q_%s" % str(e))
# m.update()
########## Objective #######
root_edge = (0, T.edge[0].keys()[0])
# obj = gbp.quicksum((1 - x[k]) * ins.loads_utilities[k] for k in range(ins.n)) + (ins.gen_cost) * P[
# root_edge]
# obj = ins.gen_cost * P[root_edge]
obj = gbp.quicksum([T[e[0]][e[1]]['z'][0] * l[e] for e in T.edges()])
m.setObjective(obj, gbp.GRB.MINIMIZE)
for e in T.edges():
z = T[e[0]][e[1]]['z']
subtree_edges = nx.bfs_edges(T, e[1])
m.addQConstr(l[e] * v[e[0]], gbp.GRB.GREATER_EQUAL, (P[e] * P[e] + Q[e] * Q[e]),
"l_%s" % str(e)) # l= |S|^2/ v_i
# rhs_P = l[e] * z[0] + gbp.quicksum([x[i] * ins.loads_P[i] for i in T.node[e[1]]['N']]) + gbp.quicksum(
# [P[(e[1], h)] for h in T.edge[e[1]].keys() ])
# rhs_P = l[e] * z[0] + gbp.quicksum([x[i] * ins.loads_P[i] for i in T.node[e[1]]['N']]) + gbp.quicksum(
# [P[(e[1], h)] for h in T.edge[e[1]].keys() if len(T.edge[e[1]]) > 1])
rhs_P = l[e] * z[0] + gbp.quicksum([x[k] * ins.loads_P[k] for k in T[e[0]][e[1]]['K']]) + gbp.quicksum(
[l[h] * z[0] for h in subtree_edges])
m.addConstr(P[e], gbp.GRB.EQUAL, rhs_P, "P_%s " % str(e))
# rhs_Q = l[e] * z[1] + gbp.quicksum([x[i] * ins.loads_Q[i] for i in T.node[e[1]]['N']]) + gbp.quicksum(
# [Q[(e[1], h)] for h in T.edge[e[1]].keys()])
# rhs_Q = l[e] * z[1] + gbp.quicksum([x[i] * ins.loads_Q[i] for i in T.node[e[1]]['N']]) + gbp.quicksum(
# [Q[(e[1], h)] for h in T.edge[e[1]].keys() if len(T.edge[e[1]]) > 1])
rhs_Q = l[e] * z[1] + gbp.quicksum([x[k] * ins.loads_Q[k] for k in T[e[0]][e[1]]['K']]) + gbp.quicksum(
[l[h] * z[1] for h in subtree_edges])
m.addConstr(Q[e], gbp.GRB.EQUAL, rhs_Q, "Q_%s " % str(e))
rhs_v = v[e[0]] + (z[0] ** 2 + z[1] ** 2) * l[e] - 2 * (z[0] * P[e] + z[1] * Q[e])
m.addConstr(v[e[1]], gbp.GRB.EQUAL, rhs_v, "v_%d " % e[1])
# m.update()
if ins.cons == 'C' or ins.cons == '':
m.addQConstr(P[e] * P[e] + Q[e] * Q[e], gbp.GRB.LESS_EQUAL, T[e[0]][e[1]]['C'] ** 2,
"C_%s" % str(e)) # capacity constraint
if ins.cons == 'V' or ins.cons == '':
m.addConstr(v[e[1]], gbp.GRB.GREATER_EQUAL, ins.v_min, "v_%d bound" % e[1]) # voltage constraint
m.addConstr(v[e[1]] >= 0, "v_%d+" % e[1])
m.addConstr(l[e] >= 0, "l_%s+" % str(e))
m.update()
# m.computeIIS()
# m.write("model.ilp")
m.optimize()
sol = a.OPF_sol()
sol.running_time = time.time() - t1
sol.gurobi_model = m
if u.gurobi_handle_errors(m, algname=alg):
sol.obj = obj.getValue()
sol.x = {k: x[k] for k in range(ins.n)}
sol.l = l
sol.P = P
sol.Q = Q
sol.v = v
first_node = T.edge[0].keys()[0]
sol.P_0 = P[(0, first_node)].X
logging.info("\tx = %s" % str(sol.x))
logging.info("\t{k: x_k>0} = %s" % str([k for k in range(ins.n) if sol.x[k] > 0]))
sol.succeed = True
else:
sol.succeed = False
return sol
def round_EV_scheduling4(ins, guess_x={}, round_x_after_y=True):
t1 = time.time()
sol = max_ev_scheduling_OPT(ins, guess_x=guess_x, fractional=True)
frac_sol = copy.deepcopy(sol)
sol.frac_sol = frac_sol
sol.frac_x_comp_count = 0
sol.frac_y_comp_count = 0
sol.rounded_up_count = 0
sol.rounded_down_count = 0
sol.count_y_due_to_rounded_x = 0
sol.count_rounded_up_y_due_to_rounded_x = 0
sol.customer_satisfy_ratio = {}
energy_usage = {}
energy_usage_frac_sol = {}
if sol.succeed:
# customers = np.setdiff1d(np.arange(ins.n), guess_x)
customers = np.arange(ins.n)
sol.total_ev_charge_at_time_frac_sol = {}
for t in np.arange(ins.scheduling_horizon):
sol.total_ev_charge_at_time_frac_sol[t] = np.sum([ins.charging_rates[c] * sol.x[(k, c, t)]
for k in ins.customers_at_time[t] for c in
ins.customer_charging_options[k]])
# calculated energy user of each customer
for k in customers:
energy_usage[k] = 0
energy_usage_frac_sol[k] = 0
if ins.rounding_tolerance < sol.y[k] < 1 - ins.rounding_tolerance:
# sol.y[k] = 0
sol.frac_y_comp_count += 1
# is_y_rounded = True
for t in ins.customer_charging_time_path[k]:
for c in ins.customer_charging_options[k]:
energy_usage_frac_sol[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
# if is_y_rounded:
# sol.x[(k, c, t)] = 0
#### Greedy 4 rounding
charging_cost = {k:sol.x[(k, c, t)]*ins.cost_rate_matrix[c,t] for k in customers for t in ins.customer_charging_time_path[k] for c in ins.customer_charging_options[k]}
list_cost= {k:ins.customer_utilities[k]*sol.y[k]- charging_cost[k] for k in customers}
sorted_customers = [k for k, v in sorted(list_cost.iteritems(), key=lambda (k, v): (v, k), reverse=True)]
total_ev_power_at_time = {t:0 for t in np.arange(ins.scheduling_horizon)}
energy_usage = {k:0 for k in customers}
for k in sorted_customers:
time_list_cost= {(c,t): sol.x[k,c,t] for c in ins.customer_charging_options[k] for t in ins.customer_charging_time_path[k]}
sorted_time_option = {r:v for r, v in sorted(time_list_cost.iteritems(), key=lambda (r, v): (v, r), reverse=True) if v != 0}
for (c,t) in sorted_time_option:
if ins.rounding_tolerance < sol.x[(k, c, t)] < 1 - ins.rounding_tolerance:
sol.frac_x_comp_count += 1
other_chg_options = np.setdiff1d(ins.customer_charging_options[k], [c])
total_ev_power_after_rounding_up = total_ev_power_at_time[t] + ins.charging_rates[c]
usage_after_rounding_up = energy_usage[k] + ins.charging_rates[c]*ins.step_length
usage_after_rounding_down = energy_usage[k]
if total_ev_power_after_rounding_up <= (
ins.capacity_over_time[t] - ins.base_load_over_time[t]) and usage_after_rounding_down < \
ins.customer_usage[k] :
sol.x[k,c,t] = 1
energy_usage[k] = usage_after_rounding_up
total_ev_power_at_time[t] = total_ev_power_after_rounding_up
# print(' + x[%d,%d,%d] rounded up'%(k,c,t), sol.x[k,c,t])
# print(' --- x[%d,%d,%d] rounded down'%(k,c_,t), sol.x[k,c_,t])
else:
sol.x[k,c, t] = 0
# print(' + x[%d,%d,%d] rounded down'%(k,c,t), sol.x[k,c,t])
if sol.x[k,c,t] >= 1-ins.rounding_tolerance:
for c_ in other_chg_options:
sol.x[(k, c_, t)] = 0
# set y variable
sol.customer_satisfy_ratio[k] = energy_usage[k]/ins.customer_usage[k]
if energy_usage[k] < ins.customer_usage[k] - ins.rounding_tolerance:
sol.y[k] = 0
sol.count_y_due_to_rounded_x += 1
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
energy_usage[k] -= sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
sol.x[(k, c, t)] = 0
else:
sol.y[k]=1
sol.count_rounded_up_y_due_to_rounded_x += 1
sol.running_time = time.time() - t1
# calculate new obj
obj = 0
for k in np.arange(ins.n):
obj += ins.customer_utilities[k] * sol.y[k]
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
obj -= sol.x[(k, c, t)] * ins.cost_rate_matrix[c, t]
# calculate P
P = {}
for t in np.arange(ins.scheduling_horizon):
P[t] = ins.base_load_over_time[t]
for k in ins.customers_at_time[t]:
for c in ins.customer_charging_options[k]:
P[t] += sol.x[(k, c, t)] * ins.charging_rates[c]
sol.frac_obj = sol.obj
sol.obj = obj
sol.customer_energy_usage = energy_usage
sol.customer_energy_usage_frac_sol = energy_usage_frac_sol
sol.P = P
sol.ar = sol.obj/sol.frac_obj
sol.running_time = time.time() - t1
return sol
def round_EV_scheduling3(ins, guess_x={}, round_x_after_y=True):
t1 = time.time()
sol = max_ev_scheduling_OPT(ins, guess_x=guess_x, fractional=True)
frac_sol = copy.deepcopy(sol)
sol.frac_sol = frac_sol
sol.frac_x_comp_count = 0
sol.frac_y_comp_count = 0
sol.rounded_up_count = 0
sol.rounded_down_count = 0
sol.count_y_due_to_rounded_x = 0
sol.count_rounded_up_y_due_to_rounded_x = 0
sol.customer_satisfy_ratio = {}
energy_usage = {}
energy_usage_frac_sol = {}
if sol.succeed:
# customers = np.setdiff1d(np.arange(ins.n), guess_x)
customers = np.arange(ins.n)
sol.total_ev_charge_at_time_frac_sol = {}
for t in np.arange(ins.scheduling_horizon):
sol.total_ev_charge_at_time_frac_sol[t] = np.sum([ins.charging_rates[c] * sol.x[(k, c, t)]
for k in ins.customers_at_time[t] for c in
ins.customer_charging_options[k]])
# calculated energy user of each customer
for k in customers:
energy_usage[k] = 0
energy_usage_frac_sol[k] = 0
if ins.rounding_tolerance < sol.y[k] < 1 - ins.rounding_tolerance:
# sol.y[k] = 0
sol.frac_y_comp_count += 1
# is_y_rounded = True
for t in ins.customer_charging_time_path[k]:
for c in ins.customer_charging_options[k]:
energy_usage_frac_sol[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
# if is_y_rounded:
# sol.x[(k, c, t)] = 0
#### Greedy 3 rounding
charging_cost = {k:sol.x[(k, c, t)]*ins.cost_rate_matrix[c,t] for k in customers for t in ins.customer_charging_time_path[k] for c in ins.customer_charging_options[k]}
list_cost= {k:ins.customer_utilities[k]*sol.y[k]- charging_cost[k] for k in customers}
sorted_customers = [k for k, v in sorted(list_cost.iteritems(), key=lambda (k, v): (v, k), reverse=True)]
total_ev_power_at_time = {t:0 for t in np.arange(ins.scheduling_horizon)}
energy_usage = {k:0 for k in customers}
for k in sorted_customers:
for t in ins.customer_charging_time_path[k]:
options = [sol.x[k, cc, t] for cc in ins.customer_charging_options[k]]
max_idx = np.argmax(options)
c = ins.customer_charging_options[k][max_idx]
if ins.rounding_tolerance < sol.x[(k, c, t)] < 1 - ins.rounding_tolerance:
sol.frac_x_comp_count += 1
other_chg_options = np.setdiff1d(ins.customer_charging_options[k], [c])
total_ev_power_after_rounding_up = total_ev_power_at_time[t] + ins.charging_rates[c]
usage_after_rounding_up = energy_usage[k] + ins.charging_rates[c]*ins.step_length
usage_after_rounding_down = energy_usage[k]
if total_ev_power_after_rounding_up <= (
ins.capacity_over_time[t] - ins.base_load_over_time[t]) and usage_after_rounding_down < \
ins.customer_usage[k] :
sol.x[k,c,t] = 1
energy_usage[k] = usage_after_rounding_up
total_ev_power_at_time[t] = total_ev_power_after_rounding_up
# print(' + x[%d,%d,%d] rounded up'%(k,c,t), sol.x[k,c,t])
# print(' --- x[%d,%d,%d] rounded down'%(k,c_,t), sol.x[k,c_,t])
else:
sol.x[k,c, t] = 0
# print(' + x[%d,%d,%d] rounded down'%(k,c,t), sol.x[k,c,t])
if sol.x[k,c,t] >= 1-ins.rounding_tolerance:
for c_ in other_chg_options:
sol.x[(k, c_, t)] = 0
# set y variable
sol.customer_satisfy_ratio[k] = energy_usage[k]/ins.customer_usage[k]
if energy_usage[k] < ins.customer_usage[k] - ins.rounding_tolerance:
sol.y[k] = 0
sol.count_y_due_to_rounded_x += 1
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
energy_usage[k] -= sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
sol.x[(k, c, t)] = 0
else:
sol.y[k]=1
sol.count_rounded_up_y_due_to_rounded_x += 1
sol.running_time = time.time() - t1
# calculate new obj
obj = 0
for k in np.arange(ins.n):
obj += ins.customer_utilities[k] * sol.y[k]
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
obj -= sol.x[(k, c, t)] * ins.cost_rate_matrix[c, t]
# calculate P
P = {}
for t in np.arange(ins.scheduling_horizon):
P[t] = ins.base_load_over_time[t]
for k in ins.customers_at_time[t]:
for c in ins.customer_charging_options[k]:
P[t] += sol.x[(k, c, t)] * ins.charging_rates[c]
sol.frac_obj = sol.obj
sol.obj = obj
sol.customer_energy_usage = energy_usage
sol.customer_energy_usage_frac_sol = energy_usage_frac_sol
sol.P = P
sol.ar = sol.obj/sol.frac_obj
sol.running_time = time.time() - t1
return sol
def round_EV_scheduling2(ins, guess_x={}, round_x_after_y=True):
t1 = time.time()
sol = max_ev_scheduling_OPT(ins, guess_x=guess_x, fractional=True)
frac_sol = copy.deepcopy(sol)
sol.frac_sol = frac_sol
sol.frac_x_comp_count = 0
sol.frac_y_comp_count = 0
sol.rounded_up_count = 0
sol.rounded_down_count = 0
energy_usage = {}
energy_usage_frac_sol = {}
if sol.succeed:
# customers = np.setdiff1d(np.arange(ins.n), guess_x)
customers = np.arange(ins.n)
sol.total_ev_charge_at_time_frac_sol = {}
for t in np.arange(ins.scheduling_horizon):
sol.total_ev_charge_at_time_frac_sol[t] = np.sum([ins.charging_rates[c] * sol.x[(k, c, t)]
for k in ins.customers_at_time[t] for c in
ins.customer_charging_options[k]])
# round y then all its x's
# calculated energy user of each customer
for k in customers:
energy_usage[k] = 0
energy_usage_frac_sol[k] = 0
if ins.rounding_tolerance < sol.y[k] < 1 - ins.rounding_tolerance:
# sol.y[k] = 0
sol.frac_y_comp_count += 1
# is_y_rounded = True
for t in ins.customer_charging_time_path[k]:
for c in ins.customer_charging_options[k]:
energy_usage_frac_sol[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
# if is_y_rounded:
# sol.x[(k, c, t)] = 0
energy_usage[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
#### Greedy rounding
total_ev_power_at_time = sol.total_ev_charge_at_time_frac_sol.copy()
for t in np.arange(ins.scheduling_horizon):
# max_chg_option = {}
# for k in ins.customers_at_time[t]:
# options = [sol.x[k, cc, t] for cc in ins.customer_charging_options[k]]
# max_idx = np.argmax(options)
# max_chg_option[k] = ins.customer_charging_options[k][max_idx]
# sort customers max x
list_x= {(k,c): sol.x[(k, c, t)] for k in ins.customers_at_time[t] for c in ins.customer_charging_options[k]}
sorteted_ev_option_pair = [k for k, v in sorted(list_x.iteritems(), key=lambda (k, v): (v, k), reverse=True) if v not in [0,1]]
# sorteted_ev_option_pair = [k for k, v in sorted(list_x.iteritems(), key=lambda (k, v): (v, k), reverse=True)]
# print 'customers at time ',t, ins.customers_at_time[t]
# print 'customers at time ',t, ins.customers_at_time[t]
# print 'sorted customers at time ',t,sorted(list_x.iteritems(), key=lambda (k, v): (v, k), reverse=True)
# print 'sorted', sorteted_ev_option_pair
for (k,c) in sorteted_ev_option_pair:
if ins.rounding_tolerance < sol.x[(k, c, t)] < 1 - ins.rounding_tolerance:
sol.frac_x_comp_count += 1
# print((k,c,t), 'enetered', sol.x[k,c,t])
other_chg_options = np.setdiff1d(ins.customer_charging_options[k], [c])
rem_option_power = np.sum([sol.x[(k, c_, t)] * ins.charging_rates[c] for c_ in
other_chg_options])
total_power_after_rounding = total_ev_power_at_time[t] + (1 - sol.x[k, c, t]) * \
ins.charging_rates[c] - rem_option_power
usage_after_rounding_down = energy_usage[k] - sol.x[k,c , t] * ins.charging_rates[c] * ins.step_length
if total_power_after_rounding <= (
ins.capacity_over_time[t] - ins.base_load_over_time[t]) and usage_after_rounding_down < \
ins.customer_usage[k] :
sol.x[k,c,t] = 1
# print(' + x[%d,%d,%d] rounded up'%(k,c,t), sol.x[k,c,t])
for c_ in other_chg_options:
sol.x[(k, c_, t)] = 0
# print(' --- x[%d,%d,%d] rounded down'%(k,c_,t), sol.x[k,c_,t])
else:
sol.x[k,c, t] = 0
# print(' + x[%d,%d,%d] rounded down'%(k,c,t), sol.x[k,c,t])
energy_usage[k] = usage_after_rounding_down
total_power_after_rounding = total_ev_power_at_time[t] - sol.x[k, c, t] * ins.charging_rates[c]
total_ev_power_at_time[t] = total_power_after_rounding
sol.count_y_due_to_rounded_x = 0
sol.count_rounded_up_y_due_to_rounded_x = 0
sol.customer_satisfy_ratio = {}
for k in customers:
energy_usage[k] = 0
for t in ins.customer_charging_time_path[k]:
for c in ins.customer_charging_options[k]:
energy_usage[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
for k in customers:
# set y variable
sol.customer_satisfy_ratio[k] = energy_usage[k]/ins.customer_usage[k]
if energy_usage[k] < ins.customer_usage[k] - ins.rounding_tolerance:
sol.y[k] = 0
sol.count_y_due_to_rounded_x += 1
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
energy_usage[k] -= sol.x[k, c, t] * ins.charging_rates[c]
sol.x[(k, c, t)] = 0
else:
sol.y[k]=1
sol.count_rounded_up_y_due_to_rounded_x += 1
sol.running_time = time.time() - t1
# calculate new obj
obj = 0
for k in np.arange(ins.n):
obj += ins.customer_utilities[k] * sol.y[k]
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
obj -= sol.x[(k, c, t)] * ins.cost_rate_matrix[c, t]
# calculate P
P = {}
for t in np.arange(ins.scheduling_horizon):
P[t] = ins.base_load_over_time[t]
for k in ins.customers_at_time[t]:
for c in ins.customer_charging_options[k]:
P[t] += sol.x[(k, c, t)] * ins.charging_rates[c] * ins.step_length
sol.frac_obj = sol.obj
sol.obj = obj
sol.customer_energy_usage = energy_usage
sol.customer_energy_usage_frac_sol = energy_usage_frac_sol
sol.P = P
sol.ar = sol.obj/sol.frac_obj
sol.running_time = time.time() - t1
return sol
def round_EV_scheduling1(ins, guess_x={}, round_x_after_y=True):
t1 = time.time()
sol = max_ev_scheduling_OPT(ins, guess_x=guess_x, fractional=True)
frac_sol = copy.deepcopy(sol)
sol.frac_sol = frac_sol
sol.frac_x_comp_count = 0
sol.frac_y_comp_count = 0
sol.rounded_up_count = 0
sol.rounded_down_count = 0
energy_usage = {}
energy_usage_frac_sol = {}
if sol.succeed:
# customers = np.setdiff1d(np.arange(ins.n), guess_x)
customers = np.arange(ins.n)
sol.total_ev_charge_at_time_frac_sol = {}
for t in np.arange(ins.scheduling_horizon):
sol.total_ev_charge_at_time_frac_sol[t] = np.sum([ins.charging_rates[c] * sol.x[(k, c, t)]
for k in ins.customers_at_time[t] for c in
ins.customer_charging_options[k]])
# round y then all its x's
# calculated energy user of each customer
for k in customers:
energy_usage[k] = 0
energy_usage_frac_sol[k] = 0
# rounding y
is_y_rounded = False
if ins.rounding_tolerance < sol.y[k] < 1 - ins.rounding_tolerance:
sol.y[k] = 0
sol.frac_y_comp_count += 1
is_y_rounded = True
for t in ins.customer_charging_time_path[k]:
for c in ins.customer_charging_options[k]:
energy_usage_frac_sol[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
if is_y_rounded:
sol.x[(k, c, t)] = 0
energy_usage[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
#### Greedy rounding
total_ev_charge_at_time = sol.total_ev_charge_at_time_frac_sol.copy()
for t in np.arange(ins.scheduling_horizon):
max_chg_option = {}
for k in ins.customers_at_time[t]:
options = [sol.x[k, cc, t] for cc in ins.customer_charging_options[k]]
max_idx = np.argmax(options)
max_chg_option[k] = ins.customer_charging_options[k][max_idx]
# sort customers max x
cust_x = {k: sol.x[(k, max_chg_option[k], t)] for k in ins.customers_at_time[t]}
sorted_customers = [k for k, v in sorted(cust_x.iteritems(), key=lambda (k, v): (v, k), reverse=True) if v not in [0,1]]
# print 'customers at time ',t, ins.customers_at_time[t]
# print 'sorted customers at time ',t,sorted(cust_x.iteritems(), key=lambda (k, v): (v, k), reverse=True)
# print 'sorted', sorted_customers
for k in sorted_customers:
if ins.rounding_tolerance < sol.x[(k, max_chg_option[k], t)] < 1 - ins.rounding_tolerance:
sol.frac_x_comp_count += 1
other_chg_options = np.setdiff1d(ins.customer_charging_options[k], [max_chg_option[k]])
rem_option_power = np.sum([sol.x[(k, c, t)] * ins.charging_rates[c] for c in
other_chg_options])
total_power_after_rounding = total_ev_charge_at_time[t] + (1 - sol.x[k, max_chg_option[k], t]) * \
ins.charging_rates[
max_chg_option[
k]] - rem_option_power
usage_after_rounding_down = energy_usage[k] - sol.x[k, max_chg_option[k], t] * ins.charging_rates[
max_chg_option[k]] * ins.step_length
if total_power_after_rounding <= (
ins.capacity_over_time[t] - ins.base_load_over_time[t]) and usage_after_rounding_down < \
ins.customer_usage[k]:
sol.x[k, max_chg_option[k], t] = 1
else:
sol.x[k, max_chg_option[k], t] = 0
energy_usage[k] = usage_after_rounding_down
total_power_after_rounding = total_ev_charge_at_time[t] - sol.x[k, max_chg_option[k], t] * \
ins.charging_rates[
max_chg_option[
k]] - rem_option_power
for c in other_chg_options:
sol.x[(k, c, t)] = 0
total_ev_charge_at_time[t] = total_power_after_rounding
sol.count_y_due_to_rounded_x = 0
sol.customer_satisfy_ratio = {}
for k in customers:
energy_usage[k] = 0
for t in ins.customer_charging_time_path[k]:
for c in ins.customer_charging_options[k]:
energy_usage[k] += sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
for k in customers:
# set y variable
sol.customer_satisfy_ratio[k] = energy_usage[k]/ins.customer_usage[k]
if energy_usage[k] < ins.customer_usage[k] - ins.rounding_tolerance:
sol.y[k] = 0
sol.count_y_due_to_rounded_x += 1
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
energy_usage[k] -= sol.x[k, c, t] * ins.charging_rates[c] * ins.step_length
sol.x[(k, c, t)] = 0
sol.running_time = time.time() - t1
# calculate new obj
obj = 0
for k in np.arange(ins.n):
obj += ins.customer_utilities[k] * sol.y[k]
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
obj -= sol.x[(k, c, t)] * ins.cost_rate_matrix[c, t]
# calculate P
P = {}
for t in np.arange(ins.scheduling_horizon):
P[t] = ins.base_load_over_time[t]
for k in ins.customers_at_time[t]:
for c in ins.customer_charging_options[k]:
P[t] += sol.x[(k, c, t)] * ins.charging_rates[c]
sol.frac_obj = sol.obj
sol.obj = obj
sol.customer_energy_usage = energy_usage
sol.customer_energy_usage_frac_sol = energy_usage_frac_sol
sol.P = P
sol.ar = sol.obj/sol.frac_obj
sol.running_time = time.time() - t1
return sol
def round_EV_scheduling_fixed_interval(ins, guess_x={}, round_x_after_y=True):
t1 = time.time()
sol = max_ev_scheduling_OPT_fixed_interval(ins, guess_x=guess_x, fractional=True)
frac_sol = copy.deepcopy(sol)
sol.frac_sol = frac_sol
sol.frac_x_comp_count = 0
if sol.succeed:
# customers = np.setdiff1d(np.arange(ins.n), guess_x)
customers = np.arange(ins.n)
sol.total_ev_charge_at_time_frac_sol = {}
obj = 0
for k in customers:
for c in ins.customer_charging_options[k]:
# rounding y
if ins.rounding_tolerance < sol.x[k,c] < 1 - ins.rounding_tolerance:
sol.x[k,c]= 0
sol.frac_x_comp_count += 1
# calculate new obj
obj += ins.customer_utilities[k,c] * sol.x[k,c]
sol.running_time = time.time() - t1
# calculate P
P = {}
for t in np.arange(ins.scheduling_horizon):
P[t] = ins.base_load_over_time[t]
for (k,c) in ins.customers_at_time[t]:
P[t] += sol.x[(k, c)] * ins.charging_rates[c]
sol.frac_obj = sol.obj
sol.obj = obj
sol.P = P
sol.ar = sol.obj/sol.frac_obj
sol.running_time = time.time() - t1
return sol
# for e-energy 2018
def max_ev_scheduling_OPT_fixed_interval(ins, guess_x={}, fractional=False, debug=False, tolerance=0.001, alg="min_OPF_OPT"):
t1 = time.time()
m = gbp.Model("max_ev_scheduling_OPT_fixed_interval")
u.gurobi_setting(m)
x = {} # key (i, c, t)
P = {}
# Q = {}
time_path = np.arange(ins.scheduling_horizon)
num_of_constraints = 0
num_of_constraints_paper_formulation = 0
for k in np.arange(ins.n):
for c in ins.customer_charging_options[k]:
if fractional:
x[(k, c)] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="x[(%d,%d)]" % (k, c))
else:
x[(k, c)] = m.addVar(vtype=gbp.GRB.BINARY, name="x[(%d,%d)]" % (k, c))
for t in time_path:
P[t] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="P_%s" % str(t))
obj = gbp.quicksum(x[k,c] * ins.customer_utilities[k,c] for k in range(ins.n) for c in ins.customer_charging_options[k])
m.setObjective(obj, gbp.GRB.MAXIMIZE)
m.update()
for t in time_path:
# capacity constraints
ev_charge_list = [x[(k, c)] * (ins.charging_rates[c]) for (k,c) in ins.customers_at_time[t] if len(ins.customers_at_time[t]) != 0]
rhs_P = ins.base_load_over_time[t] + gbp.quicksum(ev_charge_list)
m.addConstr(P[t], gbp.GRB.EQUAL, rhs_P, "P_%d" % t)
m.addConstr(P[t], gbp.GRB.LESS_EQUAL, ins.capacity_over_time[t], "C_%d" % t)
num_of_constraints += 2
num_of_constraints_paper_formulation += 1
for k in np.arange(ins.n):
# single charging option per customer contraints
X = gbp.quicksum([x[(k, c)] for c in ins.customer_charging_options[k]])
m.addConstr(X, gbp.GRB.LESS_EQUAL, 1, "sum_c X(%d) <= 1" % (k))
num_of_constraints += 1
num_of_constraints_paper_formulation += 1
# box constraints
for c in ins.customer_charging_options[k]:
m.addConstr(x[(k, c)] >= 0, "x[%s]: lb" % str((k, c)))
num_of_constraints += 1
num_of_constraints_paper_formulation += 1
# for k in guess_x.keys():
# m.addConstr(x[k], gbp.GRB.EQUAL, guess_x[k], "x[%d]: guess " % k)
m.update()
# m.write('model.lp')
m.optimize()
sol = a.OPF_EV_sol()
sol.running_time = time.time() - t1
# sol.gurobi_model = m
if u.gurobi_handle_errors(m, algname=alg):
sol.x = {(k, c): x[(k, c)].x for k in range(ins.n) for c in ins.customer_charging_options[k]}
sol.obj = obj.getValue()
sol.P = {t: P[t].x for t in np.arange(ins.scheduling_horizon)}
sol.number_of_constraints_paper_formulation = num_of_constraints_paper_formulation
sol.number_of_constraints = num_of_constraints
sol.succeed = True
else:
sol.succeed = False
return sol
# for e-energy 2018
def max_ev_scheduling_OPT(ins, guess_x={}, fractional=False, debug=False, tolerance=0.001, alg="min_OPF_OPT"):
t1 = time.time()
m = gbp.Model("max_ev_scheduling_OPT")
u.gurobi_setting(m)
x = {} # key (i, c, t)
y = {}
P = {}
# Q = {}
customer_costs = []
total_charge_per_customer = {}
time_path = np.arange(ins.scheduling_horizon)
num_of_constraints = 0
num_of_constraints_paper_formulation = 0
for k in np.arange(ins.n):
if fractional:
y[k] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="y[%d]" % k)
else:
y[k] = m.addVar(vtype=gbp.GRB.BINARY, name="y[%d]" % k)
total_charge_per_customer[k] = 0
for c in ins.customer_charging_options[k]:
for t in ins.customer_charging_time_path[k]:
if fractional:
x[(k, c, t)] = m.addVar(vtype=gbp.GRB.CONTINUOUS, name="x[(%d,%d,%d)]" % (k, c, t))
else:
x[(k, c, t)] = m.addVar(vtype=gbp.GRB.BINARY, name="x[(%d,%d,%d)]" % (k, c, t))
customer_costs.append(x[(k, c, t)] * ins.cost_rate_matrix[c, t])
total_charge_per_customer[k] += x[k, c, t] * ins.charging_rates[c] * ins.step_length