forked from PyPSA/PyPSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinopf.py
1684 lines (1459 loc) · 58.4 KB
/
linopf.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
# -*- coding: utf-8 -*-
"""
Build optimisation problems from PyPSA networks without Pyomo.
Originally retrieved from nomopyomo ( -> 'no more Pyomo').
"""
__author__ = (
"PyPSA Developers, see https://pypsa.readthedocs.io/en/latest/developers.html"
)
__copyright__ = (
"Copyright 2015-2023 PyPSA Developers, see https://pypsa.readthedocs.io/en/latest/developers.html, "
"MIT License"
)
import numpy as np
import pandas as pd
from deprecation import deprecated
from numpy import inf
from packaging.version import Version, parse
from pypsa.descriptors import (
Dict,
additional_linkports,
expand_series,
get_active_assets,
get_activity_mask,
get_bounds_pu,
get_extendable_i,
get_non_extendable_i,
)
from pypsa.descriptors import get_switchable_as_dense as get_as_dense
from pypsa.descriptors import nominal_attrs
from pypsa.linopt import (
align_with_static_component,
define_binaries,
define_constraints,
define_variables,
get_con,
get_var,
join_exprs,
linexpr,
run_and_read_cbc,
run_and_read_cplex,
run_and_read_glpk,
run_and_read_gurobi,
run_and_read_highs,
run_and_read_xpress,
set_conref,
write_bound,
write_constraint,
write_objective,
)
from pypsa.pf import _as_snapshots
agg_group_kwargs = (
dict(numeric_only=False) if parse(pd.__version__) >= Version("1.3") else {}
)
import gc
import logging
import os
import re
import shutil
import time
from tempfile import mkstemp
logger = logging.getLogger(__name__)
lookup = pd.read_csv(
os.path.join(os.path.dirname(__file__), "variables.csv"),
index_col=["component", "variable"],
)
def define_nominal_for_extendable_variables(n, c, attr):
"""
Initializes variables for nominal capacities for a given component and a
given attribute.
Parameters
----------
n : pypsa.Network
c : str
network component of which the nominal capacity should be defined
attr : str
name of the variable, e.g. 'p_nom'
"""
ext_i = get_extendable_i(n, c)
if ext_i.empty:
return
lower = n.df(c)[attr + "_min"][ext_i]
upper = n.df(c)[attr + "_max"][ext_i]
define_variables(n, lower, upper, c, attr)
def define_dispatch_for_extendable_and_committable_variables(n, sns, c, attr):
"""
Initializes variables for power dispatch for a given component and a given
attribute.
Parameters
----------
n : pypsa.Network
c : str
name of the network component
attr : str
name of the attribute, e.g. 'p'
"""
ext_i = get_extendable_i(n, c)
if c in {"Generator", "Link"}:
ext_i = ext_i.union(
getattr(n, n.components[c]["list_name"]).query("committable").index
)
if ext_i.empty:
return
active = get_activity_mask(n, c, sns)[ext_i] if n._multi_invest else None
define_variables(n, -inf, inf, c, attr, axes=[sns, ext_i], spec="ext", mask=active)
def define_dispatch_for_non_extendable_variables(n, sns, c, attr):
"""
Initializes variables for power dispatch for a given component and a given
attribute.
Parameters
----------
n : pypsa.Network
c : str
name of the network component
attr : str
name of the attribute, e.g. 'p'
"""
fix_i = get_non_extendable_i(n, c)
if c in {"Generator", "Link"}:
fix_i = fix_i.difference(
getattr(n, n.components[c]["list_name"]).query("committable").index
)
if fix_i.empty:
return
nominal_fix = n.df(c)[nominal_attrs[c]][fix_i]
min_pu, max_pu = get_bounds_pu(n, c, sns, fix_i, attr)
lower = min_pu.mul(nominal_fix)
upper = max_pu.mul(nominal_fix)
axes = [sns, fix_i]
active = get_activity_mask(n, c, sns)[fix_i] if n._multi_invest else None
kwargs = dict(spec="non_ext", mask=active)
dispatch = define_variables(n, -inf, inf, c, attr, axes=axes, **kwargs)
dispatch = linexpr((1, dispatch))
define_constraints(n, dispatch, ">=", lower, c, "mu_lower", **kwargs)
define_constraints(n, dispatch, "<=", upper, c, "mu_upper", **kwargs)
def define_dispatch_for_extendable_constraints(n, sns, c, attr):
"""
Sets power dispatch constraints for extendable devices for a given
component and a given attribute.
Parameters
----------
n : pypsa.Network
c : str
name of the network component
attr : str
name of the attribute, e.g. 'p'
"""
ext_i = get_extendable_i(n, c)
if ext_i.empty:
return
min_pu, max_pu = get_bounds_pu(n, c, sns, ext_i, attr)
operational_ext_v = get_var(n, c, attr)[ext_i]
nominal_v = get_var(n, c, nominal_attrs[c])[ext_i]
rhs = 0
active = get_activity_mask(n, c, sns)[ext_i] if n._multi_invest else None
kwargs = dict(spec=attr, mask=active)
lhs, *axes = linexpr((max_pu, nominal_v), (-1, operational_ext_v), return_axes=True)
define_constraints(n, lhs, ">=", rhs, c, "mu_upper", axes=axes, **kwargs)
lhs, *axes = linexpr((min_pu, nominal_v), (-1, operational_ext_v), return_axes=True)
define_constraints(n, lhs, "<=", rhs, c, "mu_lower", axes=axes, **kwargs)
def define_fixed_variable_constraints(n, sns, c, attr, pnl=True):
"""
Sets constraints for fixing variables of a given component and attribute to
the corresponding values in n.df(c)[attr + '_set'] if pnl is True, or
n.pnl(c)[attr + '_set']
Parameters
----------
n : pypsa.Network
c : str
name of the network component
attr : str
name of the attribute, e.g. 'p'
pnl : bool, default True
Whether variable which should be fixed is time-dependent
"""
if pnl:
if attr + "_set" not in n.pnl(c):
return
fix = n.pnl(c)[attr + "_set"].loc[sns]
if fix.empty:
return
if n._multi_invest:
active = get_activity_mask(n, c, sns)
fix = fix.where(active)
fix = fix.stack()
lhs = linexpr((1, get_var(n, c, attr).stack()[fix.index]), as_pandas=False)
constraints = write_constraint(n, lhs, "=", fix).unstack().T
else:
if attr + "_set" not in n.df(c):
return
fix = n.df(c)[attr + "_set"].dropna()
if fix.empty:
return
lhs = linexpr((1, get_var(n, c, attr)[fix.index]), as_pandas=False)
constraints = write_constraint(n, lhs, "=", fix)
set_conref(n, constraints, c, f"mu_{attr}_set")
@deprecated(
deprecated_in="0.23",
removed_in="0.24",
details="Use define_unit_commitment_status_variables instead.",
)
def define_generator_status_variables(n, sns):
define_unit_commitment_status_variables(n, sns, "Generator")
def define_unit_commitment_status_variables(n, sns, c):
allowed_c = {"Generator", "Link"}
assert c in allowed_c, f"Component {c} must be in {allowed_c}."
com_i = n.df(c).query("committable").index
ext_i = get_extendable_i(n, c)
if not (ext_i.intersection(com_i)).empty:
logger.warning(
f"The following {c} components have both investment optimisation"
f" and unit commitment:\n\n\t{', '.join((ext_i.intersection(com_i)))}\n\nCurrently PyPSA cannot "
"do both these functions, so PyPSA is choosing investment optimisation "
f"for these {c} components."
)
com_i = com_i.difference(ext_i)
if com_i.empty:
return
active = get_activity_mask(n, c, sns)[com_i] if n._multi_invest else None
define_binaries(n, (sns, com_i), c, "status", mask=active)
@deprecated(
deprecated_in="0.23",
removed_in="0.24",
details="Use define_unit_commitment_constraints instead.",
)
def define_committable_generator_constraints(n, sns):
define_unit_commitment_constraints(n, sns, "Generator")
def define_unit_commitment_constraints(n, sns, c):
allowed_c = {"Generator", "Link"}
assert c in allowed_c, f"Component {c} must be in {allowed_c}."
com_i = n.df(c).query("committable and not p_nom_extendable").index
if com_i.empty:
return
nominal = n.df(c)[nominal_attrs[c]][com_i]
min_pu, max_pu = get_bounds_pu(n, c, sns, com_i, "p")
lower = min_pu.mul(nominal)
upper = max_pu.mul(nominal)
status = get_var(n, c, "status")
p = get_var(n, c, "p")[com_i]
lhs = linexpr((lower, status), (-1, p))
active = get_activity_mask(n, c, sns)[com_i] if n._multi_invest else None
define_constraints(n, lhs, "<=", 0, c, "committable_lb", mask=active)
lhs = linexpr((upper, status), (-1, p))
define_constraints(n, lhs, ">=", 0, c, "committable_ub", mask=active)
def define_ramp_limit_constraints(n, sns, c):
"""
Defines ramp limits for a given component with valid ramplimit.
"""
rup_i = n.df(c).query("ramp_limit_up == ramp_limit_up").index
rdown_i = n.df(c).query("ramp_limit_down == ramp_limit_down").index
if rup_i.empty & rdown_i.empty:
return
fix_i = get_non_extendable_i(n, c)
ext_i = get_extendable_i(n, c)
if "committable" in n.df(c):
com_i = n.df(c).query("committable").index.difference(ext_i)
else:
com_i = []
# Check if ramping is not at start of n.snapshots
start_i = n.snapshots.get_loc(sns[0]) - 1
pnl = n.pnl(c)
# get dispatch for either one or two ports
attr = ({"p", "p0"} & set(pnl)).pop()
p_prev_fix = pnl[attr].iloc[start_i]
is_rolling_horizon = (sns[0] != n.snapshots[0]) and not p_prev_fix.empty
if is_rolling_horizon:
active = get_activity_mask(n, c, sns)
p = get_var(n, c, "p")
p_prev = get_var(n, c, "p").shift(1, fill_value=-1)
rhs_prev = pd.DataFrame(0, *p.axes)
rhs_prev.loc[sns[0]] = p_prev_fix
else:
active = get_activity_mask(n, c, sns[1:])
p = get_var(n, c, "p").loc[sns[1:]]
p_prev = get_var(n, c, "p").shift(1, fill_value=-1).loc[sns[1:]]
rhs_prev = pd.DataFrame(0, *p.axes)
# fix up
gens_i = rup_i.intersection(fix_i)
if not gens_i.empty:
lhs = linexpr((1, p[gens_i]), (-1, p_prev[gens_i]))
rhs = rhs_prev[gens_i] + n.df(c).loc[gens_i].eval("ramp_limit_up * p_nom")
kwargs = dict(spec="nonext.", mask=active[gens_i])
define_constraints(n, lhs, "<=", rhs, c, "mu_ramp_limit_up", **kwargs)
# ext up
gens_i = rup_i.intersection(ext_i)
if not gens_i.empty:
limit_pu = n.df(c)["ramp_limit_up"][gens_i]
p_nom = get_var(n, c, "p_nom")[gens_i]
lhs = linexpr((1, p[gens_i]), (-1, p_prev[gens_i]), (-limit_pu, p_nom))
rhs = rhs_prev[gens_i]
kwargs = dict(spec="ext.", mask=active[gens_i])
define_constraints(n, lhs, "<=", rhs, c, "mu_ramp_limit_up", **kwargs)
# com up
gens_i = rup_i.intersection(com_i)
if not gens_i.empty:
limit_start = n.df(c).loc[gens_i].eval("ramp_limit_start_up * p_nom")
limit_up = n.df(c).loc[gens_i].eval("ramp_limit_up * p_nom")
status = get_var(n, c, "status").loc[p.index, gens_i]
status_prev = (
get_var(n, c, "status").shift(1, fill_value=-1).loc[p.index, gens_i]
)
lhs = linexpr(
(1, p[gens_i]),
(-1, p_prev[gens_i]),
(limit_start - limit_up, status_prev),
(-limit_start, status),
)
rhs = rhs_prev[gens_i]
if is_rolling_horizon:
status_prev_fix = n.pnl(c)["status"][com_i].iloc[start_i]
rhs.loc[sns[0]] += (limit_up - limit_start) * status_prev_fix
kwargs = dict(spec="com.", mask=active[gens_i])
define_constraints(n, lhs, "<=", rhs, c, "mu_ramp_limit_up", **kwargs)
# fix down
gens_i = rdown_i.intersection(fix_i)
if not gens_i.empty:
lhs = linexpr((1, p[gens_i]), (-1, p_prev[gens_i]))
rhs = rhs_prev[gens_i] + n.df(c).loc[gens_i].eval(
"-1 * ramp_limit_down * p_nom"
)
kwargs = dict(spec="nonext.", mask=active[gens_i])
define_constraints(n, lhs, ">=", rhs, c, "mu_ramp_limit_down", **kwargs)
# ext down
gens_i = rdown_i.intersection(ext_i)
if not gens_i.empty:
limit_pu = n.df(c)["ramp_limit_down"][gens_i]
p_nom = get_var(n, c, "p_nom")[gens_i]
lhs = linexpr((1, p[gens_i]), (-1, p_prev[gens_i]), (limit_pu, p_nom))
rhs = rhs_prev[gens_i]
kwargs = dict(spec="ext.", mask=active[gens_i])
define_constraints(n, lhs, ">=", rhs, c, "mu_ramp_limit_down", **kwargs)
# com down
gens_i = rdown_i.intersection(com_i)
if not gens_i.empty:
limit_shut = n.df(c).loc[gens_i].eval("ramp_limit_shut_down * p_nom")
limit_down = n.df(c).loc[gens_i].eval("ramp_limit_down * p_nom")
status = get_var(n, c, "status").loc[p.index, gens_i]
status_prev = (
get_var(n, c, "status").shift(1, fill_value=-1).loc[p.index, gens_i]
)
lhs = linexpr(
(1, p[gens_i]),
(-1, p_prev[gens_i]),
(limit_down - limit_shut, status),
(limit_shut, status_prev),
)
rhs = rhs_prev[gens_i]
if is_rolling_horizon:
status_prev_fix = n.pnl(c)["status"][com_i].iloc[start_i]
rhs.loc[sns[0]] += -limit_shut * status_prev_fix
kwargs = dict(spec="com.", mask=active[gens_i])
define_constraints(n, lhs, ">=", rhs, c, "mu_ramp_limit_down", **kwargs)
def define_nominal_constraints_per_bus_carrier(n, sns):
for carrier in n.carriers.index:
for bound, sense in [("max", "<="), ("min", ">=")]:
col = f"nom_{bound}_{carrier}"
if col not in n.buses.columns:
continue
rhs = n.buses[col].dropna()
lhs = pd.Series("", rhs.index)
for c, attr in nominal_attrs.items():
if c not in n.one_port_components:
continue
attr = nominal_attrs[c]
if (c, attr) not in n.variables.index:
continue
nominals = get_var(n, c, attr)[n.df(c).carrier == carrier]
if nominals.empty:
continue
per_bus = (
linexpr((1, nominals)).groupby(n.df(c).bus).sum(**agg_group_kwargs)
)
lhs += per_bus.reindex(lhs.index, fill_value="")
if bound == "max":
lhs = lhs[lhs != ""]
rhs = rhs.reindex(lhs.index)
else:
assert (lhs != "").all(), (
f"No extendable components of carrier {carrier} on bus "
f'{list(lhs[lhs == ""].index)}'
)
define_constraints(n, lhs, sense, rhs, "Bus", "mu_" + col)
def define_nodal_balance_constraints(n, sns):
"""
Defines nodal balance constraint.
"""
#
def bus_injection(c, attr, groupcol="bus", sign=1):
# additional sign only necessary for branches in reverse direction
if "sign" in n.df(c):
sign = sign * n.df(c).sign
expr = linexpr((sign, get_var(n, c, attr))).rename(columns=n.df(c)[groupcol])
# drop empty bus2, bus3 if multiline link
if c == "Link":
expr.drop(columns="", errors="ignore", inplace=True)
return expr
# one might reduce this a bit by using n.branches and lookup
args = [
["Generator", "p"],
["Store", "p"],
["StorageUnit", "p_dispatch"],
["StorageUnit", "p_store", "bus", -1],
["Line", "s", "bus0", -1],
["Line", "s", "bus1", 1],
["Transformer", "s", "bus0", -1],
["Transformer", "s", "bus1", 1],
["Link", "p", "bus0", -1],
["Link", "p", "bus1", get_as_dense(n, "Link", "efficiency", sns)],
]
args = [arg for arg in args if not n.df(arg[0]).empty]
if not n.links.empty:
for i in additional_linkports(n):
eff = get_as_dense(n, "Link", f"efficiency{i}", sns)
args.append(["Link", "p", f"bus{i}", eff])
lhs = (
pd.concat([bus_injection(*arg) for arg in args], axis=1)
.groupby(axis=1, level=0)
.sum(**agg_group_kwargs)
.reindex(columns=n.buses.index, fill_value="")
)
sense = "="
rhs = (
(-get_as_dense(n, "Load", "p_set", sns) * n.loads.sign)
.groupby(n.loads.bus, axis=1)
.sum()
.reindex(columns=n.buses.index, fill_value=0)
)
if (lhs == "").any(axis=None):
if ((lhs == "") & (rhs != 0)).any(axis=None):
raise ValueError("Empty LHS in nodal balance constraint for non-zero RHS.")
mask = lhs != ""
else:
mask = None
define_constraints(n, lhs, sense, rhs, "Bus", "marginal_price", mask=mask)
def define_kirchhoff_constraints(n, sns):
"""
Defines Kirchhoff voltage constraints.
"""
comps = n.passive_branch_components & set(n.variables.index.levels[0])
if len(comps) == 0:
return
branch_vars = pd.concat({c: get_var(n, c, "s") for c in comps}, axis=1)
def cycle_flow(ds, sns):
if sns is None:
sns = slice(None)
ds = ds[lambda ds: ds != 0.0].dropna()
vals = linexpr((ds, branch_vars.loc[sns, ds.index]), as_pandas=False)
return vals.sum(1)
constraints = []
periods = sns.unique("period") if n._multi_invest else [None]
for period in periods:
n.determine_network_topology(investment_period=period)
subconstraints = []
for sub in n.sub_networks.obj:
branches = sub.branches()
C = pd.DataFrame(sub.C.todense(), index=branches.index)
if C.empty:
continue
carrier = n.sub_networks.carrier[sub.name]
weightings = branches.x_pu_eff if carrier == "AC" else branches.r_pu_eff
C_weighted = 1e5 * C.mul(weightings, axis=0)
cycle_sum = C_weighted.apply(cycle_flow, sns=period)
snapshots = sns if period is None else sns[sns.get_loc(period)]
cycle_sum.set_index(snapshots, inplace=True)
con = write_constraint(n, cycle_sum, "=", 0)
subconstraints.append(con)
if len(subconstraints) == 0:
continue
constraints.append(pd.concat(subconstraints, axis=1, ignore_index=True))
if constraints:
constraints = pd.concat(constraints).rename_axis(columns="cycle")
set_conref(n, constraints, "SubNetwork", "mu_kirchhoff_voltage_law")
def define_storage_unit_constraints(n, sns):
"""
Defines state of charge (soc) constraints for storage units. In principal
the constraints states:
previous_soc + p_store - p_dispatch + inflow - spill == soc
"""
sus_i = n.storage_units.index
if sus_i.empty:
return
c = "StorageUnit"
# spillage
has_periods = isinstance(sns, pd.MultiIndex)
active = get_activity_mask(n, c, sns)
upper = get_as_dense(n, c, "inflow", sns).loc[:, lambda df: df.max() > 0]
spill = define_variables(
n, 0, upper, "StorageUnit", "spill", mask=active[upper.columns]
)
# elapsed hours
eh = expand_series(n.snapshot_weightings.stores[sns], sus_i)
# efficiencies
eff_stand = (1 - get_as_dense(n, c, "standing_loss", sns)).pow(eh)
eff_dispatch = get_as_dense(n, c, "efficiency_dispatch", sns)
eff_store = get_as_dense(n, c, "efficiency_store", sns)
soc = get_var(n, c, "state_of_charge")
if has_periods:
cyclic_i = (
n.df(c)
.query("cyclic_state_of_charge & " "~cyclic_state_of_charge_per_period")
.index
)
cyclic_pp_i = (
n.df(c)
.query("cyclic_state_of_charge & " "cyclic_state_of_charge_per_period")
.index
)
noncyclic_i = (
n.df(c)
.query("~cyclic_state_of_charge & " "~state_of_charge_initial_per_period")
.index
)
noncyclic_pp_i = (
n.df(c)
.query("~cyclic_state_of_charge & " "state_of_charge_initial_per_period")
.index
)
else:
cyclic_i = n.df(c).query("cyclic_state_of_charge").index
noncyclic_i = n.df(c).query("~cyclic_state_of_charge ").index
# cyclic constraint for whole optimization horizon
previous_soc_cyclic = (
soc.where(active).ffill().apply(lambda ds: np.roll(ds, 1)).ffill()
)
# non cyclic constraint: determine the first active snapshot
first_active_snapshot = active.cumsum()[noncyclic_i] == 1
coeff_var = [
(-1, soc),
(-1 / eff_dispatch * eh, get_var(n, c, "p_dispatch")),
(eff_store * eh, get_var(n, c, "p_store")),
]
lhs, *axes = linexpr(*coeff_var, return_axes=True)
def masked_term(coeff, var, cols):
return (
linexpr((coeff[cols], var[cols]))
.reindex(index=axes[0], columns=axes[1], fill_value="")
.values
)
if (c, "spill") in n.variables.index:
lhs += masked_term(-eh, get_var(n, c, "spill"), spill.columns)
lhs += masked_term(eff_stand, previous_soc_cyclic, cyclic_i)
lhs += masked_term(
eff_stand[~first_active_snapshot],
soc.shift()[~first_active_snapshot],
noncyclic_i,
)
# rhs set e at beginning of optimization horizon for noncyclic
rhs = -get_as_dense(n, c, "inflow", sns).mul(eh).astype(float)
rhs[noncyclic_i] = rhs[noncyclic_i].where(
~first_active_snapshot, rhs - n.df(c).state_of_charge_initial, axis=1
)
if has_periods:
# cyclic constraint for soc per period - cyclic soc within each period
previous_soc_cyclic_pp = soc.groupby(level=0).transform(
lambda ds: np.roll(ds, 1)
)
lhs += masked_term(eff_stand, previous_soc_cyclic_pp, cyclic_pp_i)
# set the initial enery at the beginning of each period
first_active_snapshot_pp = active[noncyclic_pp_i].groupby(level=0).cumsum() == 1
lhs += masked_term(
eff_stand[~first_active_snapshot_pp],
soc.shift()[~first_active_snapshot_pp],
noncyclic_pp_i,
)
rhs[noncyclic_pp_i] = rhs[noncyclic_pp_i].where(
~first_active_snapshot_pp, rhs - n.df(c).state_of_charge_initial, axis=1
)
define_constraints(n, lhs, "==", rhs, c, "mu_state_of_charge", mask=active)
def define_store_constraints(n, sns):
"""
Defines energy balance constraints for stores. In principal this states:
previous_e - p == e
"""
stores_i = n.stores.index
if stores_i.empty:
return
c = "Store"
has_periods = isinstance(sns, pd.MultiIndex)
active = get_activity_mask(n, c, sns)
define_variables(n, -inf, inf, axes=[sns, stores_i], name=c, attr="p", mask=active)
# elapsed hours
eh = expand_series(n.snapshot_weightings.stores[sns], stores_i) # elapsed hours
eff_stand = (1 - get_as_dense(n, c, "standing_loss", sns)).pow(eh)
e = get_var(n, c, "e")
if has_periods:
cyclic_i = n.df(c).query("e_cyclic & ~e_cyclic_per_period").index
cyclic_pp_i = n.df(c).query("e_cyclic & e_cyclic_per_period").index
noncyclic_i = n.df(c).query("~e_cyclic & ~e_initial_per_period").index
noncyclic_pp_i = n.df(c).query("~e_cyclic & e_initial_per_period").index
else:
cyclic_i = n.df(c).query("e_cyclic").index
noncyclic_i = n.df(c).query("~e_cyclic").index
# cyclic constraint for whole optimization horizon
previous_e_cyclic = e.where(active).ffill().apply(lambda ds: np.roll(ds, 1)).ffill()
# non cyclic constraint: determine the first active snapshot
first_active_snapshot = active.cumsum()[noncyclic_i] == 1
coeff_var = [(-eh, get_var(n, c, "p")), (-1, e)]
lhs, *axes = linexpr(*coeff_var, return_axes=True)
def masked_term(coeff, var, cols):
return (
linexpr((coeff[cols], var[cols]))
.reindex(index=sns, columns=stores_i, fill_value="")
.values
)
lhs += masked_term(eff_stand, previous_e_cyclic, cyclic_i)
lhs += masked_term(
eff_stand[~first_active_snapshot],
e.shift()[~first_active_snapshot],
noncyclic_i,
)
# rhs set e at beginning of optimization horizon for noncyclic
rhs = pd.DataFrame(0.0, sns, stores_i)
rhs[noncyclic_i] = rhs[noncyclic_i].where(
~first_active_snapshot, -n.df(c).e_initial, axis=1
)
if has_periods:
# cyclic constraint for soc per period - cyclic soc within each period
previous_e_cyclic_pp = e.groupby(level=0).transform(lambda ds: np.roll(ds, 1))
lhs += masked_term(eff_stand, previous_e_cyclic_pp, cyclic_pp_i)
# set the initial enery at the beginning of each period
first_active_snapshot_pp = active[noncyclic_pp_i].groupby(level=0).cumsum() == 1
lhs += masked_term(
eff_stand[~first_active_snapshot_pp],
e.shift()[~first_active_snapshot_pp],
noncyclic_pp_i,
)
rhs[noncyclic_pp_i] = rhs[noncyclic_pp_i].where(
~first_active_snapshot_pp, -n.df(c).e_initial, axis=1
)
define_constraints(n, lhs, "==", rhs, c, "mu_state_of_charge", mask=active)
def define_growth_limit(n, sns, c, attr):
"""
Constraint new installed capacity per investment period.
Parameters
----------
n : pypsa.Network
c : str
network component of which the nominal capacity should be defined
attr : str
name of the variable, e.g. 'p_nom'
"""
if not n._multi_invest:
return
ext_i = get_extendable_i(n, c)
if "carrier" not in n.df(c) or n.df(c).empty:
return
if (n.carriers.max_relative_growth > 0).any():
logger.warning(
"Max relative growth is not implemented for the native pypsa optimization framework. "
"Use the linopy framework with `n.optimize` instead."
)
with_limit = n.carriers.query("max_growth != inf").index
limit_i = n.df(c).query("carrier in @with_limit").index.intersection(ext_i)
if limit_i.empty:
return
periods = sns.unique("period")
v = get_var(n, c, attr)
carriers = n.df(c).loc[limit_i, "carrier"]
caps = pd.concat(
{
period: linexpr((1, v)).where(n.get_active_assets(c, period), "")
for period in periods
},
axis=1,
).T[limit_i]
lhs = caps.groupby(carriers, axis=1).sum(**agg_group_kwargs)
rhs = n.carriers.max_growth[with_limit]
define_constraints(n, lhs, "<=", rhs, "Carrier", "growth_limit_{}".format(c))
def define_global_constraints(n, sns):
"""
Defines global constraints for the optimization. Possible types are.
1. primary_energy
Use this to constraint the byproducts of primary energy sources as
CO2
2. transmission_volume_expansion_limit
Use this to set a limit for line volume expansion. Possible carriers
are 'AC' and 'DC'
3. transmission_expansion_cost_limit
Use this to set a limit for line expansion costs. Possible carriers
are 'AC' and 'DC'
4. tech_capacity_expansion_limit
Use this to se a limit for the summed capacitiy of a carrier (e.g.
'onwind') for each investment period at choosen nodes. This limit
could e.g. represent land resource/ building restrictions for a
technology in a certain region. Currently, only the
capacities of extendable generators have to be below the set limit.
"""
if n._multi_invest:
period_weighting = n.investment_period_weightings["years"]
weightings = n.snapshot_weightings.mul(period_weighting, level=0, axis=0).loc[
sns
]
else:
weightings = n.snapshot_weightings.loc[sns]
def get_period(n, glc, sns):
period = slice(None)
if n._multi_invest and not np.isnan(glc["investment_period"]):
period = int(glc["investment_period"])
if period not in sns.unique("period"):
logger.warning(
"Optimized snapshots do not contain the investment "
f"period required for global constraint `{glc.name}`."
)
return period
# (1) primary_energy
glcs = n.global_constraints.query('type == "primary_energy"')
for name, glc in glcs.iterrows():
rhs = glc.constant
lhs = ""
carattr = glc.carrier_attribute
emissions = n.carriers.query(f"{carattr} != 0")[carattr]
period = get_period(n, glc, sns)
if emissions.empty:
continue
# generators
gens = n.generators.query("carrier in @emissions.index")
if not gens.empty:
efficiency = get_as_dense(n, "Generator", "efficiency", inds=gens.index)
em_pu = gens.carrier.map(emissions) / efficiency
em_pu = em_pu.multiply(weightings.generators, axis=0).loc[period]
p = get_var(n, "Generator", "p").loc[sns, gens.index].loc[period]
vals = linexpr((em_pu, p), as_pandas=False)
lhs += join_exprs(vals)
# storage units
sus = n.storage_units.query(
"carrier in @emissions.index and " "not cyclic_state_of_charge"
)
sus_i = sus.index
if not sus.empty:
em_pu = sus.carrier.map(emissions)
soc = (
get_var(n, "StorageUnit", "state_of_charge").loc[sns, sus_i].loc[period]
)
soc = soc.where(soc != -1).ffill().iloc[-1]
vals = linexpr((-em_pu, soc), as_pandas=False)
lhs = lhs + "\n" + join_exprs(vals)
rhs -= em_pu @ sus.state_of_charge_initial
# stores
n.stores["carrier"] = n.stores.bus.map(n.buses.carrier)
stores = n.stores.query("carrier in @emissions.index and not e_cyclic")
if not stores.empty:
em_pu = stores.carrier.map(emissions)
e = get_var(n, "Store", "e").loc[sns, stores.index].loc[period]
e = e.where(e != -1).ffill().iloc[-1]
vals = linexpr((-em_pu, e), as_pandas=False)
lhs = lhs + "\n" + join_exprs(vals)
rhs -= stores.carrier.map(emissions) @ stores.e_initial
define_constraints(
n,
lhs,
glc.sense,
rhs,
"GlobalConstraint",
"mu",
axes=pd.Index([name]),
spec=name,
)
# (2) transmission_volume_expansion_limit
glcs = n.global_constraints.query(
"type == " '"transmission_volume_expansion_limit"'
)
def substr(s):
return re.sub("[\\[\\]\\(\\)]", "", s)
for name, glc in glcs.iterrows():
car = [substr(c.strip()) for c in glc.carrier_attribute.split(",")]
lhs = ""
period = get_period(n, glc, sns)
for c, attr in (("Line", "s_nom"), ("Link", "p_nom")):
if n.df(c).empty:
continue
ext_i = n.df(c).query(f"carrier in @car and {attr}_extendable").index
ext_i = ext_i[get_activity_mask(n, c, sns)[ext_i].loc[period].any()]
if ext_i.empty:
continue
v = linexpr(
(n.df(c).length[ext_i], get_var(n, c, attr)[ext_i]), as_pandas=False
)
lhs += "\n" + join_exprs(v)
if lhs == "":
continue
sense = glc.sense
rhs = glc.constant
define_constraints(
n,
lhs,
sense,
rhs,
"GlobalConstraint",
"mu",
axes=pd.Index([name]),
spec=name,
)
# (3) transmission_expansion_cost_limit
glcs = n.global_constraints.query("type == " '"transmission_expansion_cost_limit"')
for name, glc in glcs.iterrows():
car = [substr(c.strip()) for c in glc.carrier_attribute.split(",")]
lhs = ""
period = get_period(n, glc, sns)
for c, attr in (("Line", "s_nom"), ("Link", "p_nom")):
ext_i = n.df(c).query(f"carrier in @car and {attr}_extendable").index
ext_i = ext_i[get_activity_mask(n, c, sns)[ext_i].loc[period].any()]
if ext_i.empty:
continue
v = linexpr(
(n.df(c).capital_cost[ext_i], get_var(n, c, attr)[ext_i]),
as_pandas=False,
)
lhs += "\n" + join_exprs(v)
if lhs == "":
continue
sense = glc.sense
rhs = glc.constant
define_constraints(
n,
lhs,
sense,
rhs,
"GlobalConstraint",
"mu",
axes=pd.Index([name]),
spec=name,
)
# (4) tech_capacity_expansion_limit
# TODO: Generalize to carrier capacity expansion limit (i.e. also for stores etc.)
def substr(s):
return re.sub("[\\[\\]\\(\\)]", "", s)
glcs = n.global_constraints.query("type == " '"tech_capacity_expansion_limit"')
c, attr = "Generator", "p_nom"
for name, glc in glcs.iterrows():
period = get_period(n, glc, sns)
car = glc["carrier_attribute"]
bus = str(glc.get("bus", "")) # in pypsa buses are always strings
ext_i = n.df(c).query("carrier == @car and p_nom_extendable").index
if bus:
ext_i = n.df(c).loc[ext_i].query("bus == @bus").index
ext_i = ext_i[get_activity_mask(n, c, sns)[ext_i].loc[period].any()]
if ext_i.empty:
continue
cap_vars = get_var(n, c, attr)[ext_i]
lhs = join_exprs(linexpr((1, cap_vars)))
rhs = glc.constant
sense = glc.sense
define_constraints(
n,
lhs,
sense,
rhs,
"GlobalConstraint",
"mu",
axes=pd.Index([name]),