-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurbs.py
2281 lines (1924 loc) · 83.5 KB
/
urbs.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
"""urbs: A linear optimisation model for distributed energy systems
urbs minimises total cost for providing energy in form of desired commodities
(usually electricity) to satisfy a given demand in form of timeseries. The
model contains commodities (electricity, fossil fuels, renewable energy
sources, greenhouse gases), processes that convert one commodity to another
(while emitting greenhouse gases as a secondary output), transmission for
transporting commodities between sites and storage for saving/retrieving
commodities.
"""
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyomo.core as pyomo
import warnings
from datetime import datetime
from operator import itemgetter
from random import random
from xlrd import XLRDError
COLORS = {
'Biomass plant': (0, 122, 55),
'Coal plant': (100, 100, 100),
'Gas plant': (237, 227, 0),
'Gud plant': (153, 153, 0),
'Hydro plant': (198, 188, 240),
'Lignite plant': (116, 66, 65),
'Photovoltaics': (243, 174, 0),
'Slack powerplant': (163, 74, 130),
'Wind park': (122, 179, 225),
'Decoration': (128, 128, 128), # plot labels
'Original Demand': (130, 130, 130), # thick demand line
'Demand': (25, 25, 25), # thick shifted demand line
'Demand delta': (130, 130, 130), # dashed demand delta
'Grid': (128, 128, 128), # background grid
'Overproduction': (190, 0, 99), # excess power
'Storage': (60, 36, 154), # storage area
'Stock': (222, 222, 222), # stock commodity power
'Purchase': (0, 153, 153),
'Feed-in': (255, 204, 153)}
def read_excel(filename):
"""Read Excel input file and prepare URBS input dict.
Reads an Excel spreadsheet that adheres to the structure shown in
mimo-example.xlsx. Two preprocessing steps happen here:
1. Column titles in 'Demand' and 'SupIm' are split, so that
'Site.Commodity' becomes the MultiIndex column ('Site', 'Commodity').
2. The attribute 'annuity-factor' is derived here from the columns 'wacc'
and 'depreciation' for 'Process', 'Transmission' and 'Storage'.
Args:
filename: filename to an Excel spreadsheet with the required sheets
'Commodity', 'Process', 'Transmission', 'Storage', 'Demand' and
'SupIm'.
Returns:
a dict of 6 DataFrames
Example:
>>> data = read_excel('mimo-example.xlsx')
>>> data['hacks'].loc['Global CO2 limit', 'Value']
150000000
"""
with pd.ExcelFile(filename) as xls:
commodity = (
xls.parse('Commodity').set_index(['Site', 'Commodity', 'Type']))
process = xls.parse('Process').set_index(['Site', 'Process'])
process_commodity = (
xls.parse('Process-Commodity')
.set_index(['Process', 'Commodity', 'Direction']))
transmission = (
xls.parse('Transmission')
.set_index(['Site In', 'Site Out', 'Transmission','Commodity']))
storage = (
xls.parse('Storage').set_index(['Site', 'Storage', 'Commodity']))
demand = xls.parse('Demand').set_index(['t'])
supim = xls.parse('SupIm').set_index(['t'])
buy_sell_price = xls.parse('Buy-Sell-Price').set_index(['t'])
dsm = xls.parse('DSM').set_index(['Site', 'Commodity']) #Demand Side Management
try:
hacks = xls.parse('Hacks').set_index(['Name'])
except XLRDError:
hacks = None
# prepare input data
# split columns by dots '.', so that 'DE.Elec' becomes the two-level
# column index ('DE', 'Elec')
demand.columns = split_columns(demand.columns, '.')
supim.columns = split_columns(supim.columns, '.')
buy_sell_price.columns = split_columns(buy_sell_price.columns, '.')
# derive annuity factor from WACC and depreciation periods
process['annuity-factor'] = annuity_factor(
process['depreciation'], process['wacc'])
transmission['annuity-factor'] = annuity_factor(
transmission['depreciation'], transmission['wacc'])
storage['annuity-factor'] = annuity_factor(
storage['depreciation'], storage['wacc'])
data = {
'commodity': commodity,
'process': process,
'process_commodity': process_commodity,
'transmission': transmission,
'storage': storage,
'demand': demand,
'supim': supim,
'buy_sell_price': buy_sell_price,
'dsm': dsm}
if hacks is not None:
data['hacks'] = hacks
# sort nested indexes to make direct assignments work, cf
# http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-need-for-sortedness-with-multiindex
for key in data:
if isinstance(data[key].index, pd.core.index.MultiIndex):
data[key].sortlevel(inplace=True)
return data
def create_model(data, timesteps=None, dt=1, dual=False):
"""Create a pyomo ConcreteModel URBS object from given input data.
Args:
data: a dict of 6 DataFrames with the keys 'commodity', 'process',
'transmission', 'storage', 'demand' and 'supim'.
timesteps: optional list of timesteps, default: demand timeseries
dt: timestep duration in hours (default: 1)
dual: set True to add dual variables to model (slower); default: False
Returns:
a pyomo ConcreteModel object
"""
m = pyomo.ConcreteModel()
m.name = 'URBS'
m.created = datetime.now().strftime('%Y%m%dT%H%M')
# Optional
if not timesteps:
timesteps = data['demand'].index.tolist()
# Preparations
# ============
# Data import. Syntax to access a value within equation definitions looks
# like this:
#
# m.storage.loc[site, storage, commodity][attribute]
#
m.commodity = data['commodity']
m.process = data['process']
m.process_commodity = data['process_commodity']
m.transmission = data['transmission']
m.storage = data['storage']
m.demand = data['demand']
m.supim = data['supim']
m.buy_sell_price = data['buy_sell_price']
m.timesteps = timesteps
m.dsm = data['dsm'] #Demand Side Management
# process input/output ratios
m.r_in = m.process_commodity.xs('In', level='Direction')['ratio']
m.r_out = m.process_commodity.xs('Out', level='Direction')['ratio']
# input ratios for partial efficiencies
# only keep those entries whose values are
# a) positive and
# b) numeric (implicitely, as NaN or NV compare false against 0)
m.r_in_min_fraction = m.process_commodity.xs('In', level='Direction')['ratio-min']
m.r_in_min_fraction = m.r_in_min_fraction[m.r_in_min_fraction > 0]
# Sets
# ====
# Syntax: m.{name} = Set({domain}, initialize={values})
# where name: set name
# domain: set domain for tuple sets, a cartesian set product
# values: set values, a list or array of element tuples
# generate ordered time step sets
m.t = pyomo.Set(
initialize=m.timesteps,
ordered=True,
doc='Set of timesteps')
# modelled (i.e. excluding init time step for storage) time steps
m.tm = pyomo.Set(
within=m.t,
initialize=m.timesteps[1:],
ordered=True,
doc='Set of modelled timesteps')
# modelled Demand Side Management time steps (downshift):
# downshift effective in tt to compensate for upshift in t
m.tt = pyomo.Set(
within=m.t,
initialize=m.timesteps[1:],
ordered=True,
doc='Set of additional DSM time steps')
# site (e.g. north, middle, south...)
m.sit = pyomo.Set(
initialize=m.commodity.index.get_level_values('Site').unique(),
doc='Set of sites')
# commodity (e.g. solar, wind, coal...)
m.com = pyomo.Set(
initialize=m.commodity.index.get_level_values('Commodity').unique(),
doc='Set of commodities')
# commodity type (i.e. SupIm, Demand, Stock, Env)
m.com_type = pyomo.Set(
initialize=m.commodity.index.get_level_values('Type').unique(),
doc='Set of commodity types')
# process (e.g. Wind turbine, Gas plant, Photovoltaics...)
m.pro = pyomo.Set(
initialize=m.process.index.get_level_values('Process').unique(),
doc='Set of conversion processes')
# tranmission (e.g. hvac, hvdc, pipeline...)
m.tra = pyomo.Set(
initialize=m.transmission.index.get_level_values('Transmission').unique(),
doc='Set of transmission technologies')
# storage (e.g. hydrogen, pump storage)
m.sto = pyomo.Set(
initialize=m.storage.index.get_level_values('Storage').unique(),
doc='Set of storage technologies')
# cost_type
m.cost_type = pyomo.Set(
initialize=['Inv', 'Fix', 'Var', 'Fuel','Revenue','Purchase','Startup'],
doc='Set of cost types (hard-coded)')
# tuple sets
m.com_tuples = pyomo.Set(
within=m.sit*m.com*m.com_type,
initialize=m.commodity.index,
doc='Combinations of defined commodities, e.g. (Mid,Elec,Demand)')
m.pro_tuples = pyomo.Set(
within=m.sit*m.pro,
initialize=m.process.index,
doc='Combinations of possible processes, e.g. (North,Coal plant)')
m.tra_tuples = pyomo.Set(
within=m.sit*m.sit*m.tra*m.com,
initialize=m.transmission.index,
doc='Combinations of possible transmission, e.g. (South,Mid,hvac,Elec)')
m.sto_tuples = pyomo.Set(
within=m.sit*m.sto*m.com,
initialize=m.storage.index,
doc='Combinations of possible storage by site, e.g. (Mid,Bat,Elec)')
m.dsm_site_tuples = pyomo.Set(
within=m.sit*m.com,
initialize=m.dsm.index,
doc='Combinations of possible dsm by site, e.g. (Mid, Elec)')
m.dsm_down_tuples = pyomo.Set(
within=m.tm*m.tm*m.sit*m.com,
initialize=[(t, tt, site, commodity)
for (t,tt, site, commodity) in dsm_down_time_tuples(m.timesteps[1:], m.dsm_site_tuples, m)],
doc='Combinations of possible dsm_down combinations, e.g. (5001,5003,Mid,Elec)')
# process input/output
m.pro_input_tuples = pyomo.Set(
within=m.sit*m.pro*m.com,
initialize=[(site, process, commodity)
for (site, process) in m.pro_tuples
for (pro, commodity) in m.r_in.index
if process == pro],
doc='Commodities consumed by process by site, e.g. (Mid,PV,Solar)')
m.pro_output_tuples = pyomo.Set(
within=m.sit*m.pro*m.com,
initialize=[(site, process, commodity)
for (site, process) in m.pro_tuples
for (pro, commodity) in m.r_out.index
if process == pro],
doc='Commodities produced by process by site, e.g. (Mid,PV,Elec)')
# process tuples for startup & partial feature
m.pro_partial_tuples = pyomo.Set(
within=m.sit*m.pro,
initialize=[(site, process)
for (site, process) in m.pro_tuples
for (pro, _) in m.r_in_min_fraction.index
if process == pro],
doc='Processes with partial input')
m.pro_partial_input_tuples = pyomo.Set(
within=m.sit*m.pro*m.com,
initialize=[(site, process, commodity)
for (site, process) in m.pro_partial_tuples
for (pro, commodity) in m.r_in_min_fraction.index
if process == pro],
doc='Commodities with partial input ratio, e.g. (Mid,Coal PP,Coal)')
# commodity type subsets
m.com_supim = pyomo.Set(
within=m.com,
initialize=commodity_subset(m.com_tuples, 'SupIm'),
doc='Commodities that have intermittent (timeseries) input')
m.com_stock = pyomo.Set(
within=m.com,
initialize=commodity_subset(m.com_tuples, 'Stock'),
doc='Commodities that can be purchased at some site(s)')
m.com_sell = pyomo.Set(
within=m.com,
initialize=commodity_subset(m.com_tuples, 'Sell'),
doc='Commodities that can be sold')
m.com_buy = pyomo.Set(
within=m.com,
initialize=commodity_subset(m.com_tuples, 'Buy'),
doc='Commodities that can be purchased')
m.com_demand = pyomo.Set(
within=m.com,
initialize=commodity_subset(m.com_tuples, 'Demand'),
doc='Commodities that have a demand (implies timeseries)')
m.com_env = pyomo.Set(
within=m.com,
initialize=commodity_subset(m.com_tuples, 'Env'),
doc='Commodities that (might) have a maximum creation limit')
# Parameters
# weight = length of year (hours) / length of simulation (hours)
# weight scales costs and emissions from length of simulation to a full
# year, making comparisons among cost types (invest is annualized, fixed
# costs are annual by default, variable costs are scaled by weight) and
# among different simulation durations meaningful.
m.weight = pyomo.Param(
initialize=float(8760) / (len(m.tm) * dt),
doc='Pre-factor for variable costs and emissions for an annual result')
# dt = spacing between timesteps. Required for storage equation that
# converts between energy (storage content, e_sto_con) and power (all other
# quantities that start with "e_")
m.dt = pyomo.Param(
initialize=dt,
doc='Time step duration (in hours), default: 1')
# Variables
# costs
m.costs = pyomo.Var(
m.cost_type,
within=pyomo.Reals,
doc='Costs by type (EUR/a)')
# commodity
m.e_co_stock = pyomo.Var(
m.tm, m.com_tuples,
within=pyomo.NonNegativeReals,
doc='Use of stock commodity source (MW) per timestep')
m.e_co_sell = pyomo.Var(
m.tm, m.com_tuples,
within=pyomo.NonNegativeReals,
doc='Use of sell commodity source (MW) per timestep')
m.e_co_buy = pyomo.Var(
m.tm, m.com_tuples,
within=pyomo.NonNegativeReals,
doc='Use of buy commodity source (MW) per timestep')
# process
m.cap_pro = pyomo.Var(
m.pro_tuples,
within=pyomo.NonNegativeReals,
doc='Total process capacity (MW)')
m.cap_pro_new = pyomo.Var(
m.pro_tuples,
within=pyomo.NonNegativeReals,
doc='New process capacity (MW)')
m.tau_pro = pyomo.Var(
m.t, m.pro_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow (MW) through process')
m.e_pro_in = pyomo.Var(
m.tm, m.pro_tuples, m.com,
within=pyomo.NonNegativeReals,
doc='Power flow of commodity into process (MW) per timestep')
m.e_pro_out = pyomo.Var(
m.tm, m.pro_tuples, m.com,
within=pyomo.NonNegativeReals,
doc='Power flow out of process (MW) per timestep')
m.cap_online = pyomo.Var(
m.t, m.pro_partial_tuples,
within=pyomo.NonNegativeReals,
doc='Online capacity (MW) of process per timestep')
m.startup_pro = pyomo.Var(
m.tm, m.pro_partial_tuples,
within=pyomo.NonNegativeReals,
doc='Started capacity (MW) of process per timestep')
# transmission
m.cap_tra = pyomo.Var(
m.tra_tuples,
within=pyomo.NonNegativeReals,
doc='Total transmission capacity (MW)')
m.cap_tra_new = pyomo.Var(
m.tra_tuples,
within=pyomo.NonNegativeReals,
doc='New transmission capacity (MW)')
m.e_tra_in = pyomo.Var(
m.tm, m.tra_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow into transmission line (MW) per timestep')
m.e_tra_out = pyomo.Var(
m.tm, m.tra_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow out of transmission line (MW) per timestep')
# storage
m.cap_sto_c = pyomo.Var(
m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='Total storage size (MWh)')
m.cap_sto_c_new = pyomo.Var(
m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='New storage size (MWh)')
m.cap_sto_p = pyomo.Var(
m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='Total storage power (MW)')
m.cap_sto_p_new = pyomo.Var(
m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='New storage power (MW)')
m.e_sto_in = pyomo.Var(
m.tm, m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow into storage (MW) per timestep')
m.e_sto_out = pyomo.Var(
m.tm, m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow out of storage (MW) per timestep')
m.e_sto_con = pyomo.Var(
m.t, m.sto_tuples,
within=pyomo.NonNegativeReals,
doc='Energy content of storage (MWh) in timestep')
# demand side management
m.dsm_up = pyomo.Var(
m.tm, m.dsm_site_tuples,
within=pyomo.NonNegativeReals,
doc='DSM upshift')
m.dsm_down = pyomo.Var(
m.dsm_down_tuples,
within=pyomo.NonNegativeReals,
doc='DSM downshift')
# Equation declarations
# equation bodies are defined in separate functions, referred to here by
# their name in the "rule" keyword.
# commodity
m.res_vertex = pyomo.Constraint(
m.tm, m.com_tuples,
rule=res_vertex_rule,
doc='storage + transmission + process + source + buy - sell == demand')
m.res_stock_step = pyomo.Constraint(
m.tm, m.com_tuples,
rule=res_stock_step_rule,
doc='stock commodity input per step <= commodity.maxperstep')
m.res_stock_total = pyomo.Constraint(
m.com_tuples,
rule=res_stock_total_rule,
doc='total stock commodity input <= commodity.max')
m.res_sell_step = pyomo.Constraint(
m.tm, m.com_tuples,
rule=res_sell_step_rule,
doc='sell commodity output per step <= commodity.maxperstep')
m.res_sell_total = pyomo.Constraint(
m.com_tuples,
rule=res_sell_total_rule,
doc='total sell commodity output <= commodity.max')
m.res_buy_step = pyomo.Constraint(
m.tm, m.com_tuples,
rule=res_buy_step_rule,
doc='buy commodity output per step <= commodity.maxperstep')
m.res_buy_total = pyomo.Constraint(
m.com_tuples,
rule=res_buy_total_rule,
doc='total buy commodity output <= commodity.max')
m.res_env_step = pyomo.Constraint(
m.tm, m.com_tuples,
rule=res_env_step_rule,
doc='environmental output per step <= commodity.maxperstep')
m.res_env_total = pyomo.Constraint(
m.com_tuples,
rule=res_env_total_rule,
doc='total environmental commodity output <= commodity.max')
# process
m.def_process_capacity = pyomo.Constraint(
m.pro_tuples,
rule=def_process_capacity_rule,
doc='total process capacity = inst-cap + new capacity')
m.def_process_input = pyomo.Constraint(
m.tm, m.pro_input_tuples - m.pro_partial_input_tuples,
rule=def_process_input_rule,
doc='process input = process throughput * input ratio')
m.def_process_output = pyomo.Constraint(
m.tm, m.pro_output_tuples,
rule=def_process_output_rule,
doc='process output = process throughput * output ratio')
m.def_intermittent_supply = pyomo.Constraint(
m.tm, m.pro_input_tuples,
rule=def_intermittent_supply_rule,
doc='process output = process capacity * supim timeseries')
m.res_process_throughput_by_capacity = pyomo.Constraint(
m.tm, m.pro_tuples,
rule=res_process_throughput_by_capacity_rule,
doc='process throughput <= total process capacity')
m.res_process_throughput_gradient = pyomo.Constraint(
m.tm, m.pro_tuples,
rule=res_process_throughput_gradient_rule,
doc='absolut process throughput gradient <= maximal gradient')
m.res_process_capacity = pyomo.Constraint(
m.pro_tuples,
rule=res_process_capacity_rule,
doc='process.cap-lo <= total process capacity <= process.cap-up')
m.res_sell_buy_symmetry = pyomo.Constraint(
m.pro_input_tuples,
rule=res_sell_buy_symmetry_rule,
doc='total power connection capacity must be symmetric in both directions')
m.res_throughput_by_online_capacity_min = pyomo.Constraint(
m.tm, m.pro_partial_tuples,
rule=res_throughput_by_online_capacity_min_rule,
doc='cap_online * min-fraction <= tau_pro')
m.res_throughput_by_online_capacity_max = pyomo.Constraint(
m.tm, m.pro_partial_tuples,
rule=res_throughput_by_online_capacity_max_rule,
doc='tau_pro <= cap_online')
m.def_partial_process_input = pyomo.Constraint(
m.tm, m.pro_partial_input_tuples,
rule=def_partial_process_input_rule,
doc='e_pro_in = cap_online * min_fraction * (r - R) / (1 - min_fraction)'
'+ tau_pro * (R - min_fraction * r) / (1 - min_fraction)')
m.res_cap_online_by_cap_pro = pyomo.Constraint(
m.tm, m.pro_partial_tuples,
rule=res_cap_online_by_cap_pro_rule,
doc='online capacity <= process capacity')
m.def_startup_capacity = pyomo.Constraint(
m.tm, m.pro_partial_tuples,
rule=def_startup_capacity_rule,
doc='startup_capacity[t] >= cap_online[t] - cap_online[t-1]')
# transmission
m.def_transmission_capacity = pyomo.Constraint(
m.tra_tuples,
rule=def_transmission_capacity_rule,
doc='total transmission capacity = inst-cap + new capacity')
m.def_transmission_output = pyomo.Constraint(
m.tm, m.tra_tuples,
rule=def_transmission_output_rule,
doc='transmission output = transmission input * efficiency')
m.res_transmission_input_by_capacity = pyomo.Constraint(
m.tm, m.tra_tuples,
rule=res_transmission_input_by_capacity_rule,
doc='transmission input <= total transmission capacity')
m.res_transmission_capacity = pyomo.Constraint(
m.tra_tuples,
rule=res_transmission_capacity_rule,
doc='transmission.cap-lo <= total transmission capacity <= '
'transmission.cap-up')
m.res_transmission_symmetry = pyomo.Constraint(
m.tra_tuples,
rule=res_transmission_symmetry_rule,
doc='total transmission capacity must be symmetric in both directions')
# storage
m.def_storage_state = pyomo.Constraint(
m.tm, m.sto_tuples,
rule=def_storage_state_rule,
doc='storage[t] = storage[t-1] + input - output')
m.def_storage_power = pyomo.Constraint(
m.sto_tuples,
rule=def_storage_power_rule,
doc='storage power = inst-cap + new power')
m.def_storage_capacity = pyomo.Constraint(
m.sto_tuples,
rule=def_storage_capacity_rule,
doc='storage capacity = inst-cap + new capacity')
m.res_storage_input_by_power = pyomo.Constraint(
m.tm, m.sto_tuples,
rule=res_storage_input_by_power_rule,
doc='storage input <= storage power')
m.res_storage_output_by_power = pyomo.Constraint(
m.tm, m.sto_tuples,
rule=res_storage_output_by_power_rule,
doc='storage output <= storage power')
m.res_storage_state_by_capacity = pyomo.Constraint(
m.t, m.sto_tuples,
rule=res_storage_state_by_capacity_rule,
doc='storage content <= storage capacity')
m.res_storage_power = pyomo.Constraint(
m.sto_tuples,
rule=res_storage_power_rule,
doc='storage.cap-lo-p <= storage power <= storage.cap-up-p')
m.res_storage_capacity = pyomo.Constraint(
m.sto_tuples,
rule=res_storage_capacity_rule,
doc='storage.cap-lo-c <= storage capacity <= storage.cap-up-c')
m.res_initial_and_final_storage_state = pyomo.Constraint(
m.t, m.sto_tuples,
rule=res_initial_and_final_storage_state_rule,
doc='storage content initial == and final >= storage.init * capacity')
# costs
m.def_costs = pyomo.Constraint(
m.cost_type,
rule=def_costs_rule,
doc='main cost function by cost type')
m.obj = pyomo.Objective(
rule=obj_rule,
sense=pyomo.minimize,
doc='minimize(cost = sum of all cost types)')
# demand side management
m.def_dsm_variables = pyomo.Constraint(
m.tm, m.dsm_site_tuples,
rule=def_dsm_variables_rule,
doc='DSMup * efficiency factor n == DSMdo')
m.res_dsm_upward = pyomo.Constraint(
m.tm, m.dsm_site_tuples,
rule=res_dsm_upward_rule,
doc='DSMup <= Cup (threshold capacity of DSMup)')
m.res_dsm_downward = pyomo.Constraint(
m.tm, m.dsm_site_tuples,
rule=res_dsm_downward_rule,
doc='DSMdo <= Cdo (threshold capacity of DSMdo)')
m.res_dsm_maximum = pyomo.Constraint(
m.tm, m.dsm_site_tuples,
rule=res_dsm_maximum_rule,
doc='DSMup + DSMdo <= max(Cup,Cdo)')
m.res_dsm_recovery = pyomo.Constraint(
m.tm, m.dsm_site_tuples,
rule=res_dsm_recovery_rule,
doc='DSMup(t, t + recovery time R) <= Cup * delay time L')
# possibly: add hack features
if 'hacks' in data:
m = add_hacks(m, data['hacks'])
if dual:
m.dual = pyomo.Suffix(direction=pyomo.Suffix.IMPORT)
return m
# Constraints
# commodity
# vertex equation: calculate balance for given commodity and site;
# contains implicit constraints for process activity, import/export and
# storage activity (calculated by function commodity_balance);
# contains implicit constraint for stock commodity source term
def res_vertex_rule(m, tm, sit, com, com_type):
# environmental or supim commodities don't have this constraint (yet)
if com in m.com_env:
return pyomo.Constraint.Skip
if com in m.com_supim:
return pyomo.Constraint.Skip
# helper function commodity_balance calculates balance from input to
# and output from processes, storage and transmission.
# if power_surplus > 0: production/storage/imports create net positive
# amount of commodity com
# if power_surplus < 0: production/storage/exports consume a net
# amount of the commodity com
power_surplus = - commodity_balance(m, tm, sit, com)
# if com is a stock commodity, the commodity source term e_co_stock
# can supply a possibly negative power_surplus
if com in m.com_stock:
power_surplus += m.e_co_stock[tm, sit, com, com_type]
# if com is a sell commodity, the commodity source term e_co_sell
# can supply a possibly positive power_surplus
if com in m.com_sell:
power_surplus -= m.e_co_sell[tm, sit, com, com_type]
# if com is a buy commodity, the commodity source term e_co_buy
# can supply a possibly negative power_surplus
if com in m.com_buy:
power_surplus += m.e_co_buy[tm, sit, com, com_type]
# if com is a demand commodity, the power_surplus is reduced by the
# demand value; no scaling by m.dt or m.weight is needed here, as this
# constraint is about power (MW), not energy (MWh)
if com in m.com_demand:
try:
power_surplus -= m.demand.loc[tm][sit,com]
except KeyError:
pass
# if sit com is a dsm tuple, the power surplus is decreased by the
# upshifted demand and increased by the downshifted demand.
if (sit, com) in m.dsm_site_tuples:
power_surplus -= m.dsm_up[tm,sit,com]
power_surplus += sum(m.dsm_down[t,tm,sit,com]
for t in dsm_time_tuples(
tm, m.timesteps[1:],
m.dsm['delay'].loc[sit,com]))
return power_surplus == 0
# demand side management constraints
# DSMup == DSMdo * efficiency factor n
def def_dsm_variables_rule(m, tm, sit, com):
dsm_down_sum = 0
for tt in dsm_time_tuples(tm, m.timesteps[1:], m.dsm['delay'].loc[sit,com]):
dsm_down_sum += m.dsm_down[tm,tt,sit,com]
return dsm_down_sum == m.dsm_up[tm,sit,com] * m.dsm.loc[sit,com]['eff']
# DSMup <= Cup (threshold capacity of DSMup)
def res_dsm_upward_rule(m, tm, sit, com):
return m.dsm_up[tm,sit,com] <= int(m.dsm.loc[sit,com]['cap-max-up'])
# DSMdo <= Cdo (threshold capacity of DSMdo)
def res_dsm_downward_rule(m, tm, sit, com):
dsm_down_sum = 0
for t in dsm_time_tuples(tm, m.timesteps[1:], m.dsm['delay'].loc[sit,com]):
dsm_down_sum += m.dsm_down[t,tm,sit,com]
return dsm_down_sum <= m.dsm.loc[sit,com]['cap-max-do']
# DSMup + DSMdo <= max(Cup,Cdo)
def res_dsm_maximum_rule(m, tm, sit, com):
dsm_down_sum = 0
for t in dsm_time_tuples(tm, m.timesteps[1:], m.dsm['delay'].loc[sit,com]):
dsm_down_sum += m.dsm_down[t,tm,sit,com]
max_dsm_limit = max(m.dsm.loc[sit,com]['cap-max-up'],
m.dsm.loc[sit,com]['cap-max-do'])
return m.dsm_up[tm,sit,com] + dsm_down_sum <= max_dsm_limit
# DSMup(t, t + recovery time R) <= Cup * delay time L
def res_dsm_recovery_rule(m, tm, sit, com):
dsm_up_sum = 0
for t in range(tm, tm+m.dsm['recov'].loc[sit,com]):
dsm_up_sum += m.dsm_up[t,sit,com]
return dsm_up_sum <= m.dsm.loc[sit,com]['cap-max-up'] * m.dsm['delay'].loc[sit,com]
# stock commodity purchase == commodity consumption, according to
# commodity_balance of current (time step, site, commodity);
# limit stock commodity use per time step
def res_stock_step_rule(m, tm, sit, com, com_type):
if com not in m.com_stock:
return pyomo.Constraint.Skip
else:
return (m.e_co_stock[tm, sit, com, com_type] <=
m.commodity.loc[sit, com, com_type]['maxperstep'])
# limit stock commodity use in total (scaled to annual consumption, thanks
# to m.weight)
def res_stock_total_rule(m, sit, com, com_type):
if com not in m.com_stock:
return pyomo.Constraint.Skip
else:
# calculate total consumption of commodity com
total_consumption = 0
for tm in m.tm:
total_consumption += (
m.e_co_stock[tm, sit, com, com_type] * m.dt)
total_consumption *= m.weight
return (total_consumption <=
m.commodity.loc[sit, com, com_type]['max'])
# limit sell commodity use per time step
def res_sell_step_rule(m, tm, sit, com, com_type):
if com not in m.com_sell:
return pyomo.Constraint.Skip
else:
return (m.e_co_sell[tm, sit, com, com_type] <=
m.commodity.loc[sit, com, com_type]['maxperstep'])
# limit sell commodity use in total (scaled to annual consumption, thanks
# to m.weight)
def res_sell_total_rule(m, sit, com, com_type):
if com not in m.com_sell:
return pyomo.Constraint.Skip
else:
# calculate total sale of commodity com
total_consumption = 0
for tm in m.tm:
total_consumption += (
m.e_co_sell[tm, sit, com, com_type] * m.dt)
total_consumption *= m.weight
return (total_consumption <=
m.commodity.loc[sit, com, com_type]['max'])
# limit buy commodity use per time step
def res_buy_step_rule(m, tm, sit, com, com_type):
if com not in m.com_buy:
return pyomo.Constraint.Skip
else:
return (m.e_co_buy[tm, sit, com, com_type] <=
m.commodity.loc[sit, com, com_type]['maxperstep'])
# limit buy commodity use in total (scaled to annual consumption, thanks
# to m.weight)
def res_buy_total_rule(m, sit, com, com_type):
if com not in m.com_buy:
return pyomo.Constraint.Skip
else:
# calculate total sale of commodity com
total_consumption = 0
for tm in m.tm:
total_consumption += (
m.e_co_buy[tm, sit, com, com_type] * m.dt)
total_consumption *= m.weight
return (total_consumption <=
m.commodity.loc[sit, com, com_type]['max'])
# environmental commodity creation == - commodity_balance of that commodity
# used for modelling emissions (e.g. CO2) or other end-of-pipe results of
# any process activity;
# limit environmental commodity output per time step
def res_env_step_rule(m, tm, sit, com, com_type):
if com not in m.com_env:
return pyomo.Constraint.Skip
else:
environmental_output = - commodity_balance(m, tm, sit, com)
return (environmental_output <=
m.commodity.loc[sit, com, com_type]['maxperstep'])
# limit environmental commodity output in total (scaled to annual
# emissions, thanks to m.weight)
def res_env_total_rule(m, sit, com, com_type):
if com not in m.com_env:
return pyomo.Constraint.Skip
else:
# calculate total creation of environmental commodity com
env_output_sum = 0
for tm in m.tm:
env_output_sum += (- commodity_balance(m, tm, sit, com) * m.dt)
env_output_sum *= m.weight
return (env_output_sum <=
m.commodity.loc[sit, com, com_type]['max'])
# process
# process capacity == new capacity + existing capacity
def def_process_capacity_rule(m, sit, pro):
return (m.cap_pro[sit, pro] ==
m.cap_pro_new[sit, pro] +
m.process.loc[sit, pro]['inst-cap'])
# process input power == process throughput * input ratio
def def_process_input_rule(m, tm, sit, pro, co):
return (m.e_pro_in[tm, sit, pro, co] ==
m.tau_pro[tm, sit, pro] * m.r_in.loc[pro, co])
# process output power = process throughput * output ratio
def def_process_output_rule(m, tm, sit, pro, co):
return (m.e_pro_out[tm, sit, pro, co] ==
m.tau_pro[tm, sit, pro] * m.r_out.loc[pro, co])
# process input (for supim commodity) = process capacity * timeseries
def def_intermittent_supply_rule(m, tm, sit, pro, coin):
if coin in m.com_supim:
return (m.e_pro_in[tm, sit, pro, coin] <=
m.cap_pro[sit, pro] * m.supim.loc[tm][sit, coin])
else:
return pyomo.Constraint.Skip
# process throughput <= process capacity
def res_process_throughput_by_capacity_rule(m, tm, sit, pro):
return (m.tau_pro[tm, sit, pro] <= m.cap_pro[sit, pro])
# absolute process throughput gradient <= maximal gradient
def res_process_throughput_gradient_rule(m, t, sit, pro):
# constraint only effectively restricting if max-grad < 1/dt
if m.process.loc[sit, pro]['max-grad'] < 1/m.dt.value:
if m.cap_pro[sit, pro].value is None:
return pyomo.Constraint.Skip
else:
return (m.tau_pro[t-1, sit, pro] - m.cap_pro[sit, pro] *
m.process.loc[sit, pro]['max-grad'] * m.dt,
m.tau_pro[t, sit, pro],
m.tau_pro[t-1, sit, pro] + m.cap_pro[sit, pro] *
m.process.loc[sit, pro]['max-grad'] * m.dt)
else:
return pyomo.Constraint.Skip
def res_throughput_by_online_capacity_min_rule(m, tm, sit, pro):
return (m.tau_pro[tm, sit, pro] >= m.cap_online[tm, sit, pro] *
m.process.loc[sit, pro]['min-fraction'])
def res_throughput_by_online_capacity_max_rule(m, tm, sit, pro):
return (m.tau_pro[tm, sit, pro] <= m.cap_online[tm, sit, pro])
def def_partial_process_input_rule(m, tm, sit, pro, coin):
R = m.r_in.loc[pro, coin] # input ratio at maximum operation point
r = m.r_in_min_fraction[pro, coin] # input ratio at lowest operation point
min_fraction = m.process.loc[sit, pro]['min-fraction']
online_factor = min_fraction * (r - R) / (1 - min_fraction)
throughput_factor = (R - min_fraction * r) / (1 - min_fraction)
return (m.e_pro_in[tm, sit, pro, coin] ==
m.cap_online[tm, sit, pro] * online_factor +
m.tau_pro[tm, sit, pro] * throughput_factor)
def res_cap_online_by_cap_pro_rule(m, tm, sit, pro):
return m.cap_online[tm, sit, pro] <= m.cap_pro[sit, pro]
def def_startup_capacity_rule(m, tm, sit, pro):
return (m.startup_pro[tm, sit, pro] >= m.cap_online[tm, sit, pro] -
m.cap_online[tm-1, sit, pro])
# lower bound <= process capacity <= upper bound
def res_process_capacity_rule(m, sit, pro):
return (m.process.loc[sit, pro]['cap-lo'],
m.cap_pro[sit, pro],
m.process.loc[sit, pro]['cap-up'])
# power connection capacity: Sell == Buy
def res_sell_buy_symmetry_rule(m, sit_in, pro_in, coin):
# constraint only for sell and buy processes
# and the processes must be in the same site
if coin in m.com_buy:
sell_pro = search_sell_buy_tuple(m, sit_in, pro_in, coin)
if sell_pro is None:
return pyomo.Constraint.Skip
else:
return (m.cap_pro[sit_in, pro_in] ==
m.cap_pro[sit_in, sell_pro])
else:
return pyomo.Constraint.Skip
# transmission
# transmission capacity == new capacity + existing capacity
def def_transmission_capacity_rule(m, sin, sout, tra, com):
return (m.cap_tra[sin, sout, tra, com] ==
m.cap_tra_new[sin, sout, tra, com] +
m.transmission.loc[sin, sout, tra, com]['inst-cap'])
# transmission output == transmission input * efficiency
def def_transmission_output_rule(m, tm, sin, sout, tra, com):
return (m.e_tra_out[tm, sin, sout, tra, com] ==
m.e_tra_in[tm, sin, sout, tra, com] *
m.transmission.loc[sin, sout, tra, com]['eff'])
# transmission input <= transmission capacity
def res_transmission_input_by_capacity_rule(m, tm, sin, sout, tra, com):
return (m.e_tra_in[tm, sin, sout, tra, com] <=
m.cap_tra[sin, sout, tra, com])
# lower bound <= transmission capacity <= upper bound
def res_transmission_capacity_rule(m, sin, sout, tra, com):
return (m.transmission.loc[sin, sout, tra, com]['cap-lo'],
m.cap_tra[sin, sout, tra, com],
m.transmission.loc[sin, sout, tra, com]['cap-up'])
# transmission capacity from A to B == transmission capacity from B to A
def res_transmission_symmetry_rule(m, sin, sout, tra, com):
return m.cap_tra[sin, sout, tra, com] == m.cap_tra[sout, sin, tra, com]
# storage
# storage content in timestep [t] == storage content[t-1]
# + newly stored energy * input efficiency
# - retrieved energy / output efficiency
def def_storage_state_rule(m, t, sit, sto, com):
return (m.e_sto_con[t, sit, sto, com] ==
m.e_sto_con[t-1, sit, sto, com] +
m.e_sto_in[t, sit, sto, com] *
m.storage.loc[sit, sto, com]['eff-in'] * m.dt -
m.e_sto_out[t, sit, sto, com] /
m.storage.loc[sit, sto, com]['eff-out'] * m.dt)
# storage power == new storage power + existing storage power
def def_storage_power_rule(m, sit, sto, com):
return (m.cap_sto_p[sit, sto, com] ==
m.cap_sto_p_new[sit, sto, com] +
m.storage.loc[sit, sto, com]['inst-cap-p'])
# storage capacity == new storage capacity + existing storage capacity
def def_storage_capacity_rule(m, sit, sto, com):
return (m.cap_sto_c[sit, sto, com] ==
m.cap_sto_c_new[sit, sto, com] +
m.storage.loc[sit, sto, com]['inst-cap-c'])
# storage input <= storage power
def res_storage_input_by_power_rule(m, t, sit, sto, com):
return m.e_sto_in[t, sit, sto, com] <= m.cap_sto_p[sit, sto, com]
# storage output <= storage power