-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopf.py
2242 lines (1579 loc) · 107 KB
/
opf.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
## Copyright 2015-2017 Tom Brown (FIAS), Jonas Hoersch (FIAS), David
## Schlachtberger (FIAS)
## Copyright 2017 João Gorenstein Dedecca
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 3 of the
## License, or (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Optimal Power Flow functions.
"""
# make the code as Python 3 compatible as possible
from __future__ import division, absolute_import
from six import iteritems, string_types
__author__ = """
Tom Brown (FIAS), Jonas Hoersch (FIAS), David Schlachtberger (FIAS)
Joao Gorenstein Dedecca
"""
__copyright__ = """
Copyright 2015-2017 Tom Brown (FIAS), Jonas Hoersch (FIAS), David Schlachtberger (FIAS), GNU GPL 3
Copyright 2017 João Gorenstein Dedecca, GNU GPL 3
"""
import pandas as pd
import numpy as np
from scipy.sparse.linalg import spsolve
from pyomo.environ import (ConcreteModel, Var, Objective,
NonNegativeReals, Constraint, Reals,
Suffix, Expression, Boolean, Param, NonNegativeReals, value, Binary)
from pyomo.opt import SolverFactory
from itertools import chain
import logging
logger = logging.getLogger(__name__)
from distutils.version import StrictVersion, LooseVersion
try:
_pd_version = StrictVersion(pd.__version__)
except ValueError:
_pd_version = LooseVersion(pd.__version__)
from .pf import (calculate_dependent_values, find_slack_bus,
find_bus_controls, calculate_B_H, calculate_PTDF, find_tree,
find_cycles, _as_snapshots)
from .opt import (l_constraint, l_objective, LExpression, LConstraint,
patch_optsolver_free_model_before_solving,
patch_optsolver_record_memusage_before_solving,
empty_network)
from .descriptors import get_switchable_as_dense, allocate_series_dataframes
#Custom imports
import time, datetime, operator
from copy import deepcopy
import os,sys,psutil, gc
import networkx as nx
import pyomo
def network_opf(network,snapshots=None):
"""Optimal power flow for snapshots."""
raise NotImplementedError("Non-linear optimal power flow not supported yet")
def define_generator_variables_constraints(network,snapshots):
extendable_gens_i = network.generators.index[network.generators.p_nom_extendable]
fixed_gens_i = network.generators.index[~network.generators.p_nom_extendable & ~network.generators.committable]
fixed_committable_gens_i = network.generators.index[~network.generators.p_nom_extendable & network.generators.committable]
if (network.generators.p_nom_extendable & network.generators.committable).any():
logger.warning("The following generators have both investment optimisation and unit commitment:\n{}\nCurrently PyPSA cannot do both these functions, so PyPSA is choosing investment optimisation for these generators.".format(network.generators.index[network.generators.p_nom_extendable & network.generators.committable]))
p_min_pu = get_switchable_as_dense(network, 'Generator', 'p_min_pu')
p_max_pu = get_switchable_as_dense(network, 'Generator', 'p_max_pu')
## Define generator dispatch variables ##
gen_p_bounds = {(gen,sn) : (None,None)
for gen in extendable_gens_i | fixed_committable_gens_i
for sn in snapshots}
if len(fixed_gens_i):
var_lower = (p_min_pu.loc[:,fixed_gens_i].multiply(network.generators.loc[fixed_gens_i, 'p_nom'])).fillna(0.)
var_upper = p_max_pu.loc[:,fixed_gens_i].multiply(network.generators.loc[fixed_gens_i, 'p_nom'])
gen_p_bounds.update({(gen,sn) : (var_lower[gen][sn],var_upper[gen][sn])
for gen in fixed_gens_i
for sn in snapshots})
for bound in gen_p_bounds:
if gen_p_bounds[bound][1] == np.inf:
gen_p_bounds[bound] = (gen_p_bounds[bound][0],None)
def gen_p_bounds_f(model,gen_name,snapshot):
return gen_p_bounds[gen_name,snapshot]
network.model.generator_p = Var(list(network.generators.index), snapshots,
domain=Reals, bounds=gen_p_bounds_f)
## Define generator capacity variables if generator is extendable ##
def gen_p_nom_bounds(model, gen_name):
return (network.generators.at[gen_name,"p_nom_min"],
network.generators.at[gen_name,"p_nom_max"])
network.model.generator_p_nom = Var(list(extendable_gens_i),
domain=NonNegativeReals, bounds=gen_p_nom_bounds)
## Define generator dispatch constraints for extendable generators ##
gen_p_lower = {(gen,sn) :
[[(1,network.model.generator_p[gen,sn]),
(-p_min_pu.at[sn, gen],
network.model.generator_p_nom[gen])],">=",0.]
for gen in extendable_gens_i for sn in snapshots}
l_constraint(network.model, "generator_p_lower", gen_p_lower,
list(extendable_gens_i), snapshots)
gen_p_upper = {(gen,sn) :
[[(1,network.model.generator_p[gen,sn]),
(-p_max_pu.at[sn, gen],
network.model.generator_p_nom[gen])],"<=",0.]
for gen in extendable_gens_i for sn in snapshots}
l_constraint(network.model, "generator_p_upper", gen_p_upper,
list(extendable_gens_i), snapshots)
## Define committable generator statuses ##
network.model.generator_status = Var(list(fixed_committable_gens_i), snapshots,
within=Binary)
var_lower = p_min_pu.loc[:,fixed_committable_gens_i].multiply(network.generators.loc[fixed_committable_gens_i, 'p_nom'])
var_upper = p_max_pu.loc[:,fixed_committable_gens_i].multiply(network.generators.loc[fixed_committable_gens_i, 'p_nom'])
committable_gen_p_lower = {(gen,sn) : LConstraint(LExpression([(var_lower[gen][sn],network.model.generator_status[gen,sn]),(-1.,network.model.generator_p[gen,sn])]),"<=") for gen in fixed_committable_gens_i for sn in snapshots}
l_constraint(network.model, "committable_gen_p_lower", committable_gen_p_lower,
list(fixed_committable_gens_i), snapshots)
committable_gen_p_upper = {(gen,sn) : LConstraint(LExpression([(var_upper[gen][sn],network.model.generator_status[gen,sn]),(-1.,network.model.generator_p[gen,sn])]),">=") for gen in fixed_committable_gens_i for sn in snapshots}
l_constraint(network.model, "committable_gen_p_upper", committable_gen_p_upper,
list(fixed_committable_gens_i), snapshots)
## Deal with minimum up time ##
up_time_gens = fixed_committable_gens_i[network.generators.loc[fixed_committable_gens_i,"min_up_time"] > 0]
for gen_i, gen in enumerate(up_time_gens):
min_up_time = network.generators.loc[gen,"min_up_time"]
initial_status = network.generators.loc[gen,"initial_status"]
blocks = max(1,len(snapshots)-min_up_time+1)
gen_up_time = {}
for i in range(blocks):
lhs = LExpression([(1,network.model.generator_status[gen,snapshots[j]]) for j in range(i,i+min_up_time)])
if i == 0:
rhs = LExpression([(min_up_time,network.model.generator_status[gen,snapshots[i]])],-min_up_time*initial_status)
else:
rhs = LExpression([(min_up_time,network.model.generator_status[gen,snapshots[i]]),(-min_up_time,network.model.generator_status[gen,snapshots[i-1]])])
gen_up_time[i] = LConstraint(lhs,">=",rhs)
l_constraint(network.model, "gen_up_time_{}".format(gen_i), gen_up_time,
range(blocks))
## Deal with minimum down time ##
down_time_gens = fixed_committable_gens_i[network.generators.loc[fixed_committable_gens_i,"min_down_time"] > 0]
for gen_i, gen in enumerate(down_time_gens):
min_down_time = network.generators.loc[gen,"min_down_time"]
initial_status = network.generators.loc[gen,"initial_status"]
blocks = max(1,len(snapshots)-min_down_time+1)
gen_down_time = {}
for i in range(blocks):
#sum of 1-status
lhs = LExpression([(-1,network.model.generator_status[gen,snapshots[j]]) for j in range(i,i+min_down_time)],min_down_time)
if i == 0:
rhs = LExpression([(-min_down_time,network.model.generator_status[gen,snapshots[i]])],min_down_time*initial_status)
else:
rhs = LExpression([(-min_down_time,network.model.generator_status[gen,snapshots[i]]),(min_down_time,network.model.generator_status[gen,snapshots[i-1]])])
gen_down_time[i] = LConstraint(lhs,">=",rhs)
l_constraint(network.model, "gen_down_time_{}".format(gen_i), gen_down_time,
range(blocks))
## Deal with start up costs ##
suc_gens = fixed_committable_gens_i[network.generators.loc[fixed_committable_gens_i,"start_up_cost"] > 0]
network.model.generator_start_up_cost = Var(list(suc_gens),snapshots,
domain=NonNegativeReals)
sucs = {}
for gen in suc_gens:
suc = network.generators.loc[gen,"start_up_cost"]
initial_status = network.generators.loc[gen,"initial_status"]
for i,sn in enumerate(snapshots):
if i == 0:
rhs = LExpression([(suc, network.model.generator_status[gen,sn])],-suc*initial_status)
else:
rhs = LExpression([(suc, network.model.generator_status[gen,sn]),(-suc,network.model.generator_status[gen,snapshots[i-1]])])
lhs = LExpression([(1,network.model.generator_start_up_cost[gen,sn])])
sucs[gen,sn] = LConstraint(lhs,">=",rhs)
l_constraint(network.model, "generator_start_up", sucs, list(suc_gens), snapshots)
## Deal with shut down costs ##
sdc_gens = fixed_committable_gens_i[network.generators.loc[fixed_committable_gens_i,"shut_down_cost"] > 0]
network.model.generator_shut_down_cost = Var(list(sdc_gens),snapshots,
domain=NonNegativeReals)
sdcs = {}
for gen in sdc_gens:
sdc = network.generators.loc[gen,"shut_down_cost"]
initial_status = network.generators.loc[gen,"initial_status"]
for i,sn in enumerate(snapshots):
if i == 0:
rhs = LExpression([(-sdc, network.model.generator_status[gen,sn])],sdc*initial_status)
else:
rhs = LExpression([(-sdc, network.model.generator_status[gen,sn]),(sdc,network.model.generator_status[gen,snapshots[i-1]])])
lhs = LExpression([(1,network.model.generator_shut_down_cost[gen,sn])])
sdcs[gen,sn] = LConstraint(lhs,">=",rhs)
l_constraint(network.model, "generator_shut_down", sdcs, list(sdc_gens), snapshots)
## Deal with ramp limits without unit commitment ##
sns = snapshots[1:]
ru_gens = network.generators.index[~network.generators.ramp_limit_up.isnull()]
ru = {}
for gen in ru_gens:
for i,sn in enumerate(sns):
if network.generators.at[gen, "p_nom_extendable"]:
lhs = LExpression([(1, network.model.generator_p[gen,sn]), (-1, network.model.generator_p[gen,snapshots[i]]), (-network.generators.at[gen, "ramp_limit_up"], network.model.generator_p_nom[gen])])
elif not network.generators.at[gen, "committable"]:
lhs = LExpression([(1, network.model.generator_p[gen,sn]), (-1, network.model.generator_p[gen,snapshots[i]])], -network.generators.at[gen, "ramp_limit_up"]*network.generators.at[gen, "p_nom"])
else:
lhs = LExpression([(1, network.model.generator_p[gen,sn]), (-1, network.model.generator_p[gen,snapshots[i]]), ((network.generators.at[gen, "ramp_limit_start_up"] - network.generators.at[gen, "ramp_limit_up"])*network.generators.at[gen, "p_nom"], network.model.generator_status[gen,snapshots[i]]), (-network.generators.at[gen, "ramp_limit_start_up"]*network.generators.at[gen, "p_nom"], network.model.generator_status[gen,sn])])
ru[gen,sn] = LConstraint(lhs,"<=")
l_constraint(network.model, "ramp_up", ru, list(ru_gens), sns)
rd_gens = network.generators.index[~network.generators.ramp_limit_down.isnull()]
rd = {}
for gen in rd_gens:
for i,sn in enumerate(sns):
if network.generators.at[gen, "p_nom_extendable"]:
lhs = LExpression([(1, network.model.generator_p[gen,sn]), (-1, network.model.generator_p[gen,snapshots[i]]), (network.generators.at[gen, "ramp_limit_down"], network.model.generator_p_nom[gen])])
elif not network.generators.at[gen, "committable"]:
lhs = LExpression([(1, network.model.generator_p[gen,sn]), (-1, network.model.generator_p[gen,snapshots[i]])], network.generators.loc[gen, "ramp_limit_down"]*network.generators.at[gen, "p_nom"])
else:
lhs = LExpression([(1, network.model.generator_p[gen,sn]), (-1, network.model.generator_p[gen,snapshots[i]]), ((network.generators.at[gen, "ramp_limit_down"] - network.generators.at[gen, "ramp_limit_shut_down"])*network.generators.at[gen, "p_nom"], network.model.generator_status[gen,sn]), (network.generators.at[gen, "ramp_limit_shut_down"]*network.generators.at[gen, "p_nom"], network.model.generator_status[gen,snapshots[i]])])
rd[gen,sn] = LConstraint(lhs,">=")
l_constraint(network.model, "ramp_down", rd, list(rd_gens), sns)
def define_storage_variables_constraints(network,snapshots,OGEM_options):
sus = network.storage_units
ext_sus_i = sus.index[sus.p_nom_extendable]
fix_sus_i = sus.index[~ sus.p_nom_extendable]
model = network.model
## Define storage dispatch variables ##
p_max_pu = get_switchable_as_dense(network, 'StorageUnit', 'p_max_pu')
p_min_pu = get_switchable_as_dense(network, 'StorageUnit', 'p_min_pu')
bounds = {(su,sn) : (0,None) for su in ext_sus_i for sn in snapshots}
bounds.update({(su,sn) :
(0,sus.at[su,"p_nom"]*p_max_pu.at[sn, su])
for su in fix_sus_i for sn in snapshots})
def su_p_dispatch_bounds(model,su_name,snapshot):
return bounds[su_name,snapshot]
network.model.storage_p_dispatch = Var(list(network.storage_units.index), snapshots,
domain=NonNegativeReals, bounds=su_p_dispatch_bounds)
bounds = {(su,sn) : (0,None) for su in ext_sus_i for sn in snapshots}
bounds.update({(su,sn) :
(0,-sus.at[su,"p_nom"]*p_min_pu.at[sn, su])
for su in fix_sus_i
for sn in snapshots})
def su_p_store_bounds(model,su_name,snapshot):
return bounds[su_name,snapshot]
network.model.storage_p_store = Var(list(network.storage_units.index), snapshots,
domain=NonNegativeReals, bounds=su_p_store_bounds)
## Define spillage variables only for hours with inflow>0. ##
inflow = get_switchable_as_dense(network, 'StorageUnit', 'inflow', snapshots)
spill_sus_i = sus.index[inflow.max()>0] #skip storage units without any inflow
inflow_gt0_b = inflow>0
spill_bounds = {(su,sn) : (0,inflow.at[sn,su])
for su in spill_sus_i
for sn in snapshots
if inflow_gt0_b.at[sn,su]}
spill_index = spill_bounds.keys()
def su_p_spill_bounds(model,su_name,snapshot):
return spill_bounds[su_name,snapshot]
network.model.storage_p_spill = Var(list(spill_index),
domain=NonNegativeReals, bounds=su_p_spill_bounds)
## Define generator capacity variables if generator is extendable ##
def su_p_nom_bounds(model, su_name):
return (sus.at[su_name,"p_nom_min"],
sus.at[su_name,"p_nom_max"])
network.model.storage_p_nom = Var(list(ext_sus_i), domain=NonNegativeReals,
bounds=su_p_nom_bounds)
## Define generator dispatch constraints for extendable generators ##
def su_p_upper(model,su_name,snapshot):
return (model.storage_p_dispatch[su_name,snapshot] <=
model.storage_p_nom[su_name]*p_max_pu.at[snapshot, su_name])
network.model.storage_p_upper = Constraint(list(ext_sus_i),snapshots,rule=su_p_upper)
def su_p_lower(model,su_name,snapshot):
return (model.storage_p_store[su_name,snapshot] <=
-model.storage_p_nom[su_name]*p_min_pu.at[snapshot, su_name])
network.model.storage_p_lower = Constraint(list(ext_sus_i),snapshots,rule=su_p_lower)
## Now define state of charge constraints ##
network.model.state_of_charge = Var(list(network.storage_units.index), snapshots,
domain=NonNegativeReals, bounds=(0,None))
if OGEM_options["reference"] != "expansion":
upper = {(su,sn) : [[(1,model.state_of_charge[su,sn]),
(-sus.at[su,"max_hours"],model.storage_p_nom[su])],"<=",0.]
for su in ext_sus_i for sn in snapshots}
upper.update({(su,sn) : [[(1,model.state_of_charge[su,sn])],"<=",
sus.at[su,"max_hours"]*sus.at[su,"p_nom"]]
for su in fix_sus_i for sn in snapshots})
l_constraint(model, "state_of_charge_upper", upper,
list(network.storage_units.index), snapshots)
# Storage units dispatch and store in expansion cases is fixed, so SOC constraints are not necessary.
#this builds the constraint previous_soc + p_store - p_dispatch + inflow - spill == soc
#it is complicated by the fact that sometimes previous_soc and soc are floats, not variables
soc = {}
#store the combinations with a fixed soc
fixed_soc = {}
state_of_charge_set = get_switchable_as_dense(network, 'StorageUnit', 'state_of_charge_set', snapshots)
# TODO Resolve application of snapshot_weightings to store and dispatch
for su in sus.index:
for g,sn_group in snapshots.groupby(network.scenarios).items():
for i,sn in enumerate(sn_group):
soc[su,sn] = [[],"==",0.]
#TODO Resolve application of snapshot_weightings to store and dispatch
elapsed_hours = network.snapshot_weightings[sn] * len(network.snapshots) / network.snapshot_weightings.sum()
if i == 0 and not sus.at[su,"cyclic_state_of_charge"]:
previous_state_of_charge = sus.at[su,"state_of_charge_initial"]
soc[su,sn][2] -= ((1-sus.at[su,"standing_loss"])**elapsed_hours
* previous_state_of_charge)
else:
previous_state_of_charge = model.state_of_charge[su,sn_group[i-1]]
soc[su,sn][0].append(((1-sus.at[su,"standing_loss"])**elapsed_hours,
previous_state_of_charge))
state_of_charge = state_of_charge_set.at[sn,su]
if pd.isnull(state_of_charge):
state_of_charge = model.state_of_charge[su,sn]
soc[su,sn][0].append((-1,state_of_charge))
else:
soc[su,sn][2] += state_of_charge
#make sure the variable is also set to the fixed state of charge
fixed_soc[su,sn] = [[(1,model.state_of_charge[su,sn])],"==",state_of_charge]
soc[su,sn][0].append((sus.at[su,"efficiency_store"]
* elapsed_hours,model.storage_p_store[su,sn]))
soc[su,sn][0].append((-(1/sus.at[su,"efficiency_dispatch"]) * elapsed_hours,
model.storage_p_dispatch[su,sn]))
soc[su,sn][2] -= inflow.at[sn,su] * elapsed_hours
for su,sn in spill_index:
storage_p_spill = model.storage_p_spill[su,sn]
soc[su,sn][0].append((-1.*elapsed_hours,storage_p_spill))
l_constraint(model,"state_of_charge_constraint",
soc,list(network.storage_units.index), snapshots)
l_constraint(model, "state_of_charge_constraint_fixed",
fixed_soc, list(fixed_soc.keys()))
def define_store_variables_constraints(network,snapshots):
stores = network.stores
ext_stores = stores.index[stores.e_nom_extendable]
fix_stores = stores.index[~ stores.e_nom_extendable]
e_max_pu = get_switchable_as_dense(network, 'Store', 'e_max_pu')
e_min_pu = get_switchable_as_dense(network, 'Store', 'e_min_pu')
model = network.model
## Define store dispatch variables ##
network.model.store_p = Var(list(stores.index), snapshots, domain=Reals)
## Define store energy variables ##
bounds = {(store,sn) : (None,None) for store in ext_stores for sn in snapshots}
bounds.update({(store,sn) :
(stores.at[store,"e_nom"]*e_min_pu.at[sn,store],stores.at[store,"e_nom"]*e_max_pu.at[sn,store])
for store in fix_stores for sn in snapshots})
def store_e_bounds(model,store,snapshot):
return bounds[store,snapshot]
network.model.store_e = Var(list(stores.index), snapshots, domain=Reals,
bounds=store_e_bounds)
## Define energy capacity variables if store is extendable ##
def store_e_nom_bounds(model, store):
return (stores.at[store,"e_nom_min"],
stores.at[store,"e_nom_max"])
network.model.store_e_nom = Var(list(ext_stores), domain=Reals,
bounds=store_e_nom_bounds)
## Define energy capacity constraints for extendable generators ##
def store_e_upper(model,store,snapshot):
return (model.store_e[store,snapshot] <=
model.store_e_nom[store]*e_max_pu.at[snapshot,store])
network.model.store_e_upper = Constraint(list(ext_stores), snapshots, rule=store_e_upper)
def store_e_lower(model,store,snapshot):
return (model.store_e[store,snapshot] >=
model.store_e_nom[store]*e_min_pu.at[snapshot,store])
network.model.store_e_lower = Constraint(list(ext_stores), snapshots, rule=store_e_lower)
## Builds the constraint previous_e - p == e ##
e = {}
for store in stores.index:
for i,sn in enumerate(snapshots):
e[store,sn] = LConstraint(sense="==")
e[store,sn].lhs.variables.append((-1,model.store_e[store,sn]))
elapsed_hours = network.snapshot_weightings[sn]
if i == 0 and not stores.at[store,"e_cyclic"]:
previous_e = stores.at[store,"e_initial"]
e[store,sn].lhs.constant += ((1-stores.at[store,"standing_loss"])**elapsed_hours
* previous_e)
else:
previous_e = model.store_e[store,snapshots[i-1]]
e[store,sn].lhs.variables.append(((1-stores.at[store,"standing_loss"])**elapsed_hours,
previous_e))
e[store,sn].lhs.variables.append((-elapsed_hours, model.store_p[store,sn]))
l_constraint(model,"store_constraint", e, list(stores.index), snapshots)
def define_energy_constraints(network, snapshots):
""" Used only for base, linear case.
Limits the total generation of inflow generators.
"""
inflow_generators = network.generators[network.generators.inflow > 0]
model = network.model
#TODO Possibly keep constrain in MIP as new cut
_energy_constraint = {}
for gen in inflow_generators.index:
_energy_constraint[gen] = [[], "<=", inflow_generators.loc[gen, "inflow"]]
for sn in snapshots:
_energy_constraint[gen][0].append((1.0, model.generator_p[gen, sn]))
l_constraint(network.model, "energy_constraint", _energy_constraint, list(inflow_generators.index))
def define_branch_extension_variables(network,snapshots):
""" Creates the investment ratio and binary investment variables for branches.
e.g. the transmission capacity of a passive branch is pb_inv_ratio * s_nom_max, with pb_inv_ratio <= pb_bin_inv and pb_bin_inv a binary variable.
Converters investment uses continuous variables.
"""
passive_branches = network.passive_branches()
extendable_passive_branches_i = passive_branches.index[passive_branches.s_nom_extendable]
bounds = {b: (0, 1) for b in extendable_passive_branches_i}
def pb_inv_ratio_bounds(model, branch_type, branch_name):
return bounds[branch_type, branch_name]
network.model.pb_inv_ratio = Var(list(extendable_passive_branches_i),domain=NonNegativeReals, bounds=pb_inv_ratio_bounds)
network.model.pb_bin_inv = Var(list(extendable_passive_branches_i), domain=Boolean)
extendable_ptp_links_i = network.links.index[network.links.p_nom_extendable & (network.links.branch_type == "ptp")]
bounds = {b: (0, 1) for b in extendable_ptp_links_i}
def cb_inv_ratio_bounds(model, branch_name):
return bounds[branch_name]
network.model.cb_inv_ratio = Var(list(extendable_ptp_links_i),domain=NonNegativeReals, bounds=cb_inv_ratio_bounds)
network.model.cb_bin_inv = Var(list(extendable_ptp_links_i), domain=Boolean)
extendable_converters_i = network.links.index[network.links.p_nom_extendable & (network.links.branch_type == "converter")]
bounds = {b : (network.links.at[b,"p_nom_min"],
network.links.at[b,"p_nom_max"])
for b in extendable_converters_i}
def conv_p_nom_bounds(model, branch_name):
return bounds[branch_name]
network.model.conv_p_nom = Var(list(extendable_converters_i),
domain=NonNegativeReals, bounds=conv_p_nom_bounds)
def define_link_flows(network,snapshots):
""" Flows for extendable integer branches is limited by the investment ratio x maximum nominal capacity.
AC/DC converters are modelled as conventional continuous-investment links.
"""
extendable_links_i = network.links.index[network.links.p_nom_extendable]
fixed_links_i = network.links.index[~ network.links.p_nom_extendable]
p_max_pu = get_switchable_as_dense(network, 'Link', 'p_max_pu')
p_min_pu = get_switchable_as_dense(network, 'Link', 'p_min_pu')
fixed_lower = p_min_pu.loc[:,fixed_links_i].multiply(network.links.loc[fixed_links_i, 'p_nom'])
fixed_upper = p_max_pu.loc[:,fixed_links_i].multiply(network.links.loc[fixed_links_i, 'p_nom'])
extendable_ptp_links_i = network.links.index[network.links.p_nom_extendable & (network.links.branch_type == "ptp")]
extendable_converters_i = network.links.index[network.links.p_nom_extendable & (network.links.branch_type == "converter")]
bounds = {(cb,sn) : (fixed_lower.at[sn, cb],fixed_upper.at[sn, cb])
for cb in fixed_links_i for sn in snapshots}
bounds.update({(cb,sn) : (None,None)
for cb in extendable_links_i for sn in snapshots})
def cb_p_bounds(model,cb_name,snapshot):
return bounds[cb_name,snapshot]
network.model.link_p = Var(list(network.links.index),
snapshots, domain=Reals, bounds=cb_p_bounds)
def ext_ptp_p_upper(model,cb_name,snapshot):
return (model.link_p[cb_name,snapshot] - network.links.at[cb_name,"p_nom_max"]
* p_max_pu.at[snapshot, cb_name] * network.model.cb_inv_ratio[cb_name] <= 0)
network.model.ext_link_p_upper = Constraint(list(extendable_ptp_links_i),snapshots,rule=ext_ptp_p_upper)
def ext_ptp_p_lower(model,cb_name,snapshot):
return (model.link_p[cb_name,snapshot] - network.links.at[cb_name,"p_nom_max"]
* p_min_pu.at[snapshot, cb_name] * network.model.cb_inv_ratio[cb_name] >= 0)
network.model.ext_link_p_lower = Constraint(list(extendable_ptp_links_i),snapshots,rule=ext_ptp_p_lower)
def conv_p_upper(model,cb_name,snapshot):
return (model.link_p[cb_name,snapshot] <=
model.conv_p_nom[cb_name]
* p_max_pu.at[snapshot, cb_name])
network.model.conv_p_upper = Constraint(list(extendable_converters_i),snapshots,rule=conv_p_upper)
def conv_p_lower(model,cb_name,snapshot):
return (model.link_p[cb_name,snapshot] >=
model.conv_p_nom[cb_name]
* p_min_pu.at[snapshot, cb_name])
network.model.conv_p_lower = Constraint(list(extendable_converters_i),snapshots,rule=conv_p_lower)
def define_passive_branch_flows(network,snapshots,formulation="angles",ptdf_tolerance=0.):
if formulation == "angles":
define_passive_branch_flows_with_angles(network, snapshots)
def define_passive_branch_flows_with_angles(network, snapshots):
""" Non-extendable passive branches flow is unaltered.
Extendable passive branches uses disjunctive flow constraints with a Big M parameter.
flow + bin_inv * big_M <= delta theta / x + big_M
flow - bin_inv * big_M >= delta theta / x - big_M
The big_M is optimized as the minimum between a standard and the minimum existing path of voltage angle/value deltas between the branch nodes +5%, as in S. Binato, M.V.F. Pereira, and S. Granville A New Benders Decomposition Approach to Solve Power Transmission Network Design Problems IEEE Transactions on Power Systems 16(2): 235-240, May 2001 10.1109/59.918292
"""
from .components import passive_branch_components
network.model.voltage_angles = Var(list(network.buses.index), snapshots)
slack = {(sub,sn) :
[[(1,network.model.voltage_angles[network.sub_networks.slack_bus[sub],sn])], "==", 0.]
for sub in network.sub_networks.index for sn in snapshots}
l_constraint(network.model,"slack_angle",slack,list(network.sub_networks.index),snapshots)
passive_branches = network.passive_branches()
extendable_branches_i = passive_branches.index[passive_branches.s_nom_extendable]
fixed_branches_i = passive_branches.index[~ passive_branches.s_nom_extendable]
network.model.passive_branch_p = Var(list(passive_branches.index), snapshots)
flows = {}
for branch in fixed_branches_i:
bus0 = passive_branches.bus0[branch]
bus1 = passive_branches.bus1[branch]
bt = branch[0]
bn = branch[1]
sub = passive_branches.sub_network[branch]
attribute = "r_pu" if network.sub_networks.carrier[sub] == "DC" else "x_pu"
y = 1/passive_branches[attribute][bt,bn]
for sn in snapshots:
lhs = LExpression([(y,network.model.voltage_angles[bus0,sn]),
(-y,network.model.voltage_angles[bus1,sn]),
(-1,network.model.passive_branch_p[bt,bn,sn])])
flows[bt,bn,sn] = LConstraint(lhs,"==",LExpression())
l_constraint(network.model, "passive_fixed_branch_p_def", flows,
list(fixed_branches_i), snapshots)
lower_flows = {}
upper_flows = {}
if len(extendable_branches_i) > 0:
# Calculation of minimum path of voltage angle/value delta for connected nodes in base network.
base_network = network.copy(with_time=False)
for pb, branch in base_network.lines.iterrows():
if branch['s_nom'] == 0:
base_network.remove('Line', pb)
graph = base_network.graph(passive_branch_components) # Controllable branches do not count to calculate the minimum path.
graph.remove_nodes_from(nx.isolates(graph))
delta_theta = base_network.lines.loc[:,'s_nom_max'].multiply([branch["r_pu" if branch['branch_type'] == "DC" else "x_pu"] for b, branch in base_network.lines.iterrows()], axis=0)
theta = {edge: delta_theta.loc[edge[2][1]]
for edge in graph.edges(keys=True) if edge[2][1] in base_network.lines.index}
nx.set_edge_attributes(graph, 'theta', theta)
min_theta = nx.shortest_path_length(graph,weight = 'theta')
# Construction of disjunctive flow constraints.
for branch in extendable_branches_i:
bus0 = passive_branches.bus0[branch]
bus1 = passive_branches.bus1[branch]
bt = branch[0]
bn = branch[1]
sub = passive_branches.sub_network[branch]
attribute = "r_pu" if network.sub_networks.at[sub,"carrier"] == "DC" else "x_pu"
y = 1/(passive_branches.at[branch,attribute]*(passive_branches.at[branch,"tap_ratio"] if bt == "Transformer" else 1.))
big_M = 1e2 # Standard big_M value. Increase if the KVL duals check accuses a binding flow constraint for a not-invested branch.
# Big M optimization.
if bus0 in min_theta.keys():
if bus1 in min_theta[bus0].keys():
big_M = min(min_theta[bus0][bus1] * y * 1.05,big_M)
# TODO graph shortest path to determine big_M by bus pair
for sn in snapshots:
lhs = LExpression([(1,network.model.passive_branch_p[bt,bn,sn]),(-y,network.model.voltage_angles[bus0,sn]),
(y,network.model.voltage_angles[bus1,sn]),
(big_M,network.model.pb_bin_inv[bt,bn])])
upper_flows[bt,bn,sn] = LConstraint(lhs,"<=",LExpression(constant=big_M))
lhs = LExpression([(1,network.model.passive_branch_p[bt,bn,sn]),(-y,network.model.voltage_angles[bus0,sn]),
(y,network.model.voltage_angles[bus1,sn]),
(-big_M,network.model.pb_bin_inv[bt,bn])])
lower_flows[bt,bn,sn] = LConstraint(lhs,">=",LExpression(constant=-big_M))
l_constraint(network.model, "passive_extendable_branch_p_lower", lower_flows,
list(extendable_branches_i), snapshots)
l_constraint(network.model, "passive_extendable_branch_p_upper", upper_flows,
list(extendable_branches_i), snapshots)
def define_passive_branch_constraints(network, snapshots):
passive_branches = network.passive_branches()
extendable_branches_i = passive_branches[passive_branches.s_nom_extendable].index
fixed_branches_i = passive_branches[~ passive_branches.s_nom_extendable].index
def pb_inv_ratio_rule(model, branch_type, branch_name):
return (model.pb_inv_ratio[branch_type, branch_name] - model.pb_bin_inv[branch_type, branch_name] <= 0)
# Force the investment ratio = 0 when the binary investment = 0
network.model.pb_inv_ratio_constraint = Constraint(list(extendable_branches_i),rule=pb_inv_ratio_rule)
flow_upper = {(b[0],b[1],sn) : [[(1,network.model.passive_branch_p[b[0],b[1],sn])],
"<=", passive_branches.s_nom[b]]
for b in fixed_branches_i
for sn in snapshots}
l_constraint(network.model, "flow_upper", flow_upper,
list(fixed_branches_i), snapshots)
flow_lower = {(b[0],b[1],sn) : [[(1,network.model.passive_branch_p[b[0],b[1],sn])],
">=", -passive_branches.s_nom[b]]
for b in fixed_branches_i
for sn in snapshots}
l_constraint(network.model, "flow_lower", flow_lower,
list(fixed_branches_i), snapshots)
# For extendable branches the flow is not limited by s_nom_max anymore, but s_nom_max x investment ratio.
integer_flow_upper = ({(b[0], b[1], sn): [[(1, network.model.passive_branch_p[b[0], b[1], sn]),
(-passive_branches.at[(b[0], b[1]),"s_nom_max"], network.model.pb_inv_ratio[b[0],b[1]])], "<=", 0]
for b in extendable_branches_i
for sn in snapshots})
l_constraint(network.model, "integer_flow_upper", integer_flow_upper,
list(extendable_branches_i), snapshots)
integer_flow_lower = ({(b[0], b[1], sn): [[(1, network.model.passive_branch_p[b[0], b[1], sn]),
(passive_branches.at[(b[0], b[1]), "s_nom_max"], network.model.pb_inv_ratio[b[0],b[1]])], ">=", 0]
for b in extendable_branches_i
for sn in snapshots})
l_constraint(network.model, "integer_flow_lower", integer_flow_lower,
list(extendable_branches_i), snapshots)
def define_controllable_branch_constraints(network, snapshots):
""" Force the investment ratio = 0 when the binary investment = 0 """
extendable_ptp_links_i = network.links.index[network.links.p_nom_extendable & (network.links.branch_type == "ptp")]
def cb_inv_ratio_rule(model, branch_name):
return (model.cb_inv_ratio[branch_name] - model.cb_bin_inv[branch_name] <= 0)
network.model.cb_inv_ratio_constraint = Constraint(list(extendable_ptp_links_i),rule=cb_inv_ratio_rule)
def define_minimum_ratio(network):
""" Branches may be split into capacity ranges to better represent resistance and reactances for each range.
This defines a disjunctive lower bound for the investment ratio to respect the s_nom_min/p_nom_min applicable only to branches invested in.
"""
extendable_ptp_links = network.links[network.links.p_nom_extendable & (network.links.branch_type == "ptp")]
links_with_minimum_i = extendable_ptp_links[extendable_ptp_links.p_nom_min > 0].index
big_M = -1
def cb_minimum_ratio_rule(model, branch_name):
return (model.cb_inv_ratio[branch_name] - big_M * (1 - model.cb_bin_inv[branch_name]) >= network.links.at[branch_name,"p_nom_min"]/network.links.at[branch_name,"p_nom_max"])
network.model.cb_minimum_ratio = Constraint(list(links_with_minimum_i),rule=cb_minimum_ratio_rule)
passive_branches = network.passive_branches()
branches_with_minimum_i = passive_branches[(passive_branches.s_nom_min > 0)&(passive_branches.s_nom_extendable)].index
def pb_minimum_ratio_rule(model, branch_type, branch_name):
return (model.pb_inv_ratio[branch_type, branch_name] - big_M * (1 - model.pb_bin_inv[branch_type, branch_name]) >= passive_branches.loc[(branch_type,branch_name),"s_nom_min"]/passive_branches.loc[(branch_type,branch_name),"s_nom_max"])
network.model.pb_minimum_ratio = Constraint(list(branches_with_minimum_i),rule=pb_minimum_ratio_rule)
def define_parallelism_constraints(network,snapshots):
""" For node pairs of parallel branches of the same technology but different capacity ranges allow only one branch. """
#TODO Include as special ordered set to speed up solution
passive_branches = network.passive_branches()
extendable_branches = passive_branches[passive_branches.s_nom_extendable]
extendable_ptp_links = network.links[network.links.p_nom_extendable & (network.links.branch_type == "ptp")]
def pb_parallelism_rule(model,base):
parallel_lines = extendable_branches[extendable_branches["base_branch"] == base]
return (sum([model.pb_bin_inv[line] for line in parallel_lines.index]) <= 1)
network.model.pb_parallelism = Constraint(list(extendable_branches["base_branch"].dropna().unique()),rule=pb_parallelism_rule)
def cb_parallelism_rule(model,base):
parallel_links = extendable_ptp_links[extendable_ptp_links["base_branch"] == base]
return (sum([model.cb_bin_inv[link] for link in parallel_links.index]) <= 1)
network.model.cb_parallelism = Constraint(list(extendable_ptp_links["base_branch"].dropna().unique()),rule=cb_parallelism_rule)
def define_nodal_balances(network,snapshots):
"""Construct the nodal balance for all elements except the passive
branches.
Store the nodal balance expression in network._p_balance.
"""
#dictionary for constraints
network._p_balance = {(bus,sn) : LExpression()
for bus in network.buses.index
for sn in snapshots}
efficiency = get_switchable_as_dense(network, 'Link', 'efficiency')
for cb in network.links.index:
bus0 = network.links.at[cb,"bus0"]
bus1 = network.links.at[cb,"bus1"]
for sn in snapshots:
network._p_balance[bus0,sn].variables.append((-1,network.model.link_p[cb,sn]))
network._p_balance[bus1,sn].variables.append((efficiency.at[sn,cb],network.model.link_p[cb,sn]))
for gen in network.generators.index:
bus = network.generators.at[gen,"bus"]
sign = network.generators.at[gen,"sign"]
for sn in snapshots:
network._p_balance[bus,sn].variables.append((sign,network.model.generator_p[gen,sn]))
load_p_set = get_switchable_as_dense(network, 'Load', 'p_set')
for load in network.loads.index:
bus = network.loads.at[load,"bus"]
sign = network.loads.at[load,"sign"]
for sn in snapshots:
network._p_balance[bus,sn].constant += sign*load_p_set.at[sn,load]
for su in network.storage_units.index:
bus = network.storage_units.at[su,"bus"]
sign = network.storage_units.at[su,"sign"]
for sn in snapshots:
network._p_balance[bus,sn].variables.append((sign,network.model.storage_p_dispatch[su,sn]))
network._p_balance[bus,sn].variables.append((-sign,network.model.storage_p_store[su,sn]))
for store in network.stores.index:
bus = network.stores.at[store,"bus"]
sign = network.stores.at[store,"sign"]
for sn in snapshots:
network._p_balance[bus,sn].variables.append((sign,network.model.store_p[store,sn]))
def define_nodal_balance_constraints(network,snapshots):
passive_branches = network.passive_branches()
for branch in passive_branches.index:
bus0 = passive_branches.at[branch,"bus0"]
bus1 = passive_branches.at[branch,"bus1"]
bt = branch[0]
bn = branch[1]
for sn in snapshots:
network._p_balance[bus0,sn].variables.append((-1,network.model.passive_branch_p[bt,bn,sn]))
network._p_balance[bus1,sn].variables.append((1,network.model.passive_branch_p[bt,bn,sn]))
power_balance = {k: LConstraint(v,"==",LExpression()) for k,v in iteritems(network._p_balance)}
l_constraint(network.model, "power_balance", power_balance,
list(network.buses.index), snapshots)
def define_sub_network_balance_constraints(network,snapshots):
sn_balance = {}
for sub_network in network.sub_networks.obj:
for sn in snapshots:
sn_balance[sub_network.name,sn] = LConstraint(LExpression(),"==",LExpression())
for bus in sub_network.buses().index:
sn_balance[sub_network.name,sn].lhs.variables.extend(network._p_balance[bus,sn].variables)
sn_balance[sub_network.name,sn].lhs.constant += network._p_balance[bus,sn].constant
l_constraint(network.model,"sub_network_balance_constraint", sn_balance,
list(network.sub_networks.index), snapshots)
def define_co2_constraint(network,snapshots):
def co2_constraint(model):
#use the prime mover carrier
co2_gens = sum(network.carriers.at[network.generators.at[gen,"carrier"],"co2_emissions"]
* (1/network.generators.at[gen,"efficiency"])
* network.snapshot_weightings[sn]
* model.generator_p[gen,sn]
for gen in network.generators.index
for sn in snapshots)
#store inherits the carrier from the bus
co2_stores = sum(network.carriers.at[network.buses.at[network.stores.at[store,"bus"],"carrier"],"co2_emissions"]
* network.snapshot_weightings[sn]
* model.store_p[store,sn]
for store in network.stores.index
for sn in snapshots)
return co2_gens + co2_stores <= network.co2_limit
network.model.co2_constraint = Constraint(rule=co2_constraint)
def define_participation_variables(network, snapshots, base_welfare):
""" country_participation variables are 1 if the country builds any cooperative branch, and 0 otherwise.
Used for the Pareto welfare constraint and for cooperation analysis in general.
"""
cooperative_ptp_links = network.links[network.links.p_nom_extendable & network.links.cooperative & (network.links.branch_type == "ptp")]
passive_branches = network.passive_branches()
cooperative_passive_branches = passive_branches[passive_branches.s_nom_extendable & passive_branches.cooperative]
max_branches = len(network.model.cb_bin_inv) + len(network.model.pb_bin_inv)
countries = base_welfare[base_welfare!=0].index
_country_participation_upper = {(country) : LExpression()
for country in countries}
for cb,branch in cooperative_ptp_links.iterrows():
bus0 = network.buses.loc[branch["bus0"]]
bus1 = network.buses.loc[branch["bus1"]]
if (bus0["country"] in countries):
_country_participation_upper[bus0["country"]].variables.append((-1,network.model.cb_bin_inv[cb]))
if (bus1["country"] in countries):