forked from tum-ens/urbs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurbs.py
1381 lines (1163 loc) · 49.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.
Model entities
==============
Commodity: (site, commodity, type)
e.g. (Norway, wind, SupIm) or (Iceland, electricity, Demand)
Process: (site, process, input, output)
e.g. (Iceland, turbine, geothermal, electricity)
Transmission: (site in, site out, transmission, commodity)
e.g. (Iceland, Norway, undersea cable, electricity)
Storage: (site, storage, stored commodity)
e.g. (Norway, pump storage, electricity)
Commodity
---------
Commodities are goods that can be generated, stored, transmitted and consumed.
By convention, they are represented by their energy content (in MWh), but can
be changed (to J, kW, t, kg) by simply using different (consistent) units for
all input data. Each commodity must be exactly one of following four types:
- Demand: The
- Stock: Can be introduced (bought, mined, taken out of "stock") in arbitrary
quantities at any time for a given, fixed price per unit. Its maximum
supply can be limited per timestep or for a whole year. Typical examples of
stock commodities are coal, gas, uranium or biomass.
- SupIm: Fluctuating resources like
solar radiation and wind energy, which are available according to
a timeseries of values. Can also be used to model "must-run" plants like
uncontrollable, distributed generation units.
- Env: The special commodity CO2 is of this type and represents the
amount (in tons) of greenhouse gas emissions from processes. Its
total amount can be limited, to investigate the effect of policies
on the.
Stock commodities have three numeric attributes that represent their price,
total annual and per timestep supply. Environmental commodities (i.e. CO2) have
a maximum allowed quantity that may be created.
Process
-------
Processes describe conversion technologies from one commodity to another. They
can be visualised like a black box with one input (commodity) and one output
(commodity). A fixed conversion efficiency
Transmission
------------
Storage
-------
Timeseries
==========
Demand
------
Each combination of site and demand commodity may have one timeseries,
describing the (average) power demand (MWh/h) per timestep. They are a crucial
input parameter, as the whole optimisation aims to satisfy these demands with
minimal costs from the given technologies (process, storage, transmission).
Intermittent Supply
-------------------
Each combination (site, supim commodity) must be supplied with one timeseries,
normalised to a maximum value of 1 relative to the installed capacity of a
process using this commodity as input. For eample, a wind power timeseries
should reach value 1, when the wind speed exceeds the modelled wind turbine's
design wind speed is exceeded. This implies that any non-linear behaviour of
intermittent processes can already be incorporated while preparing this
timeseries.
"""
import coopr.pyomo as pyomo
import pandas as pd
from datetime import datetime
from operator import itemgetter
from random import random
COLORS = {
'Biomass': (0, 122, 55),
'Coal': (100, 100, 100),
'Demand': (25, 25, 25),
'Diesel': (116, 66, 65),
'Gas': (237, 227, 0),
'Elec': (0, 101, 189),
'Heat': (230, 112, 36),
'Hydro': (198, 188, 240),
'Import': (128, 128, 200),
'Lignite': (116, 66, 65),
'Oil': (116, 66, 65),
'Overproduction': (190, 0, 99),
'Slack': (163, 74, 130),
'Solar': (243, 174, 0),
'Storage': (60, 36, 154),
'Wind': (122, 179, 225),
'Stock': (222, 222, 222),
'Decoration': (128, 128, 128),
'Grid': (128, 128, 128)}
def read_excel(filename):
"""Read Excel input file and prepare URBS input dict.
Reads an Excel spreadsheet that adheres to the structure shown in
data-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('data-example.xlsx')
>>> data['commodity'].loc[('Global', 'CO2', 'Env'), 'max']
150000000.0
"""
with pd.ExcelFile(filename) as xls:
commodity = xls.parse(
'Commodity',
index_col=['Sit', 'Com', 'Type'])
process = xls.parse(
'Process',
index_col=['Sit', 'Pro', 'CoIn', 'CoOut'])
transmission = xls.parse(
'Transmission',
index_col=['SitIn', 'SitOut', 'Tra', 'Com'])
storage = xls.parse(
'Storage',
index_col=['Sit', 'Sto', 'Com'])
demand = xls.parse(
'Demand',
index_col=['t'])
supim = xls.parse(
'SupIm',
index_col=['t'])
# 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, '.')
# 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,
'transmission': transmission,
'storage': storage,
'demand': demand,
'supim': supim}
# 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):
"""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'.
Returns:
a pyomo ConcreteModel object
"""
m = pyomo.ConcreteModel()
m.name = 'URBS'
m.settings = {
'dateformat': '%Y%m%dT%H%M%S',
'timesteps': timesteps,
}
m.created = datetime.now().strftime(m.settings['dateformat'])
# Preparations
# ============
# Data import. Syntax to access a value within equation definitions looks
# like this:
#
# m.process.loc[sit, pro, coin, cout][attribute]
#
get_inputs = itemgetter(
"commodity", "process", "transmission", "storage",
"demand", "supim")
(m.commodity, m.process, m.transmission, m.storage,
m.demand, m.supim) = get_inputs(data)
# 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
m.t = pyomo.Set(
initialize=m.settings['timesteps'],
ordered=True,
doc='Set of timesteps')
m.tm = pyomo.Set(
within=m.t,
initialize=m.settings['timesteps'][1:],
ordered=True,
doc='Set of modelled timesteps')
m.sit = pyomo.Set(
initialize=m.commodity.index.get_level_values('Sit').unique(),
doc='Set of sites')
m.com = pyomo.Set(
initialize=m.commodity.index.get_level_values('Com').unique(),
doc='Set of commodities')
m.com_type = pyomo.Set(
initialize=m.commodity.index.get_level_values('Type').unique(),
doc='Set of commodity types')
m.pro = pyomo.Set(
initialize=m.process.index.get_level_values('Pro').unique(),
doc='Set of conversion processes')
m.tra = pyomo.Set(
initialize=m.transmission.index.get_level_values('Tra').unique(),
doc='Set of tranmission technologies')
m.sto = pyomo.Set(
initialize=m.storage.index.get_level_values('Sto').unique(),
doc='Set of storage technologies')
m.cost_type = pyomo.Set(
initialize=['Inv', 'Fix', 'Var', 'Fuel'],
doc='Set of cost types (hard-coded)')
# sets of existing tuples:
# com_tuples = [('DE', 'Coal', 'Stock'), ('MA', 'Wind', 'SupIm'), ...]
# pro_tuples = [('DE', 'pp', 'Coal', 'Elec'), ('NO', 'wt', 'Wind', 'Elec')]
# sto_tuples = [('DE', 'bat', 'Elec'), ('NO', 'pst', 'Elec')...]
m.com_tuples = pyomo.Set(within=m.sit*m.com*m.com_type,
initialize=m.commodity.index)
m.pro_tuples = pyomo.Set(within=m.sit*m.pro*m.com*m.com,
initialize=m.process.index)
m.tra_tuples = pyomo.Set(within=m.sit*m.sit*m.tra*m.com,
initialize=m.transmission.index)
m.sto_tuples = pyomo.Set(within=m.sit*m.sto*m.com,
initialize=m.storage.index)
# subsets of commodities by type
# for equations that apply to only one commodity type
m.com_supim = pyomo.Set(
within=m.com,
initialize=set(c[1] for c in m.com_tuples if c[2] == 'SupIm'))
m.com_stock = pyomo.Set(
within=m.com,
initialize=set(c[1] for c in m.com_tuples if c[2] == 'Stock'))
m.com_demand = pyomo.Set(
within=m.com,
initialize=set(c[1] for c in m.com_tuples if c[2] == 'Demand'))
# Parameters
# ==========
# for model entities (commodity, process, transmission, storage) no
# parames are needed, just use the DataFrames m.commodity, m.process,
# m.storage and m.transmission directly.
# Syntax: m.{name} = Param({domain}, initialize={values})
# where name: param name
# domain: one or multiple model sets; empty for scalar parameters
# values: dict of parameter values, addressed by elements of domains
# if domain is skipped, defines a scalar parameter with a single value
m.weight = pyomo.Param(initialize=float(8760) / len(m.t))
# Variables
# =========
# listed alphabetically
# Syntax: m.{name} = Var({domain}, within={range}, doc={docstring})
# where name: variable name
# domain: variable domain, consisting of one or multiple sets
# range: variable values, like Binary, Integer, NonNegativeReals
# docstring: a documentation string/short description
# capacities
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.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.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)')
# emissions
m.co2_pro_out = pyomo.Var(
m.tm, m.pro_tuples,
within=pyomo.NonNegativeReals,
doc='CO2 emissions from process (t) per timestep')
# costs
m.costs = pyomo.Var(
m.cost_type,
within=pyomo.NonNegativeReals,
doc='Costs by type (EUR/a)')
# timeseries
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_pro_in = pyomo.Var(
m.tm, m.pro_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow into process (MW) per timestep')
m.e_pro_out = pyomo.Var(
m.tm, m.pro_tuples,
within=pyomo.NonNegativeReals,
doc='Power flow out of process (MW) per timestep')
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')
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')
# Equation definition
# ===================
# listed by topic. All equations except the Objective function are
# of type Constraint, although there are two semantics for those,
# indicated by the name prefix (def, res).
# - def: definition, usually equations, defining variable values
# - res: restriction, usually inequalities, limiting variable values
# topics
# - commodity
# - process
# - transmission
# - storage
# - emissions
# - costs
# commodity
def res_demand_rule(m, tm, sit, com, com_type):
if com not in m.com_demand:
return pyomo.Constraint.Skip
else:
provided_energy = - commodity_balance(m, tm, sit, com)
return (provided_energy >=
m.demand.loc[tm][sit, com])
def def_e_co_stock_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] ==
commodity_balance(m, tm, sit, com))
def res_stock_hour_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]['maxperhour'])
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]
total_consumption *= m.weight
return (total_consumption <=
m.commodity.loc[sit, com, com_type]['max'])
# process
def def_process_capacity_rule(m, sit, pro, coin, cout):
return (m.cap_pro[sit, pro, coin, cout] ==
m.cap_pro_new[sit, pro, coin, cout] +
m.process.loc[sit, pro, coin, cout]['inst-cap'])
def def_process_output_rule(m, tm, sit, pro, coin, cout):
return (m.e_pro_out[tm, sit, pro, coin, cout] ==
m.e_pro_in[tm, sit, pro, coin, cout] *
m.process.loc[sit, pro, coin, cout]['eff'])
def def_intermittent_supply_rule(m, tm, sit, pro, coin, cout):
if coin in m.com_supim:
return (m.e_pro_in[tm, sit, pro, coin, cout] ==
m.cap_pro[sit, pro, coin, cout] *
m.supim.loc[tm][sit, coin])
else:
return pyomo.Constraint.Skip
def def_co2_emissions_rule(m, tm, sit, pro, coin, cout):
return (m.co2_pro_out[tm, sit, pro, coin, cout] ==
m.e_pro_in[tm, sit, pro, coin, cout] *
m.process.loc[sit, pro, coin, cout]['co2'] *
m.weight)
def res_process_output_by_capacity_rule(m, tm, sit, pro, coin, cout):
return (m.e_pro_out[tm, sit, pro, coin, cout] <=
m.cap_pro[sit, pro, coin, cout])
def res_process_capacity_rule(m, sit, pro, coin, cout):
return (m.process.loc[sit, pro, coin, cout]['cap-lo'],
m.cap_pro[sit, pro, coin, cout],
m.process.loc[sit, pro, coin, cout]['cap-up'])
# transmission
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'])
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'])
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])
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'])
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
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.e_sto_out[t, sit, sto, com] /
m.storage.loc[sit, sto, com]['eff-out'])
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'])
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'])
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]
def res_storage_output_by_power_rule(m, t, sit, sto, co):
return m.e_sto_out[t, sit, sto, co] <= m.cap_sto_p[sit, sto, co]
def res_storage_state_by_capacity_rule(m, t, sit, sto, com):
return m.e_sto_con[t, sit, sto, com] <= m.cap_sto_c[sit, sto, com]
def res_storage_power_rule(m, sit, sto, com):
return (m.storage.loc[sit, sto, com]['cap-lo-p'],
m.cap_sto_p[sit, sto, com],
m.storage.loc[sit, sto, com]['cap-up-p'])
def res_storage_capacity_rule(m, sit, sto, com):
return (m.storage.loc[sit, sto, com]['cap-lo-c'],
m.cap_sto_c[sit, sto, com],
m.storage.loc[sit, sto, com]['cap-up-c'])
def res_initial_and_final_storage_state_rule(m, t, sit, sto, com):
if t == m.t[1]: # first timestep (Pyomo uses 1-based indexing)
return (m.e_sto_con[t, sit, sto, com] ==
m.cap_sto_c[sit, sto, com] *
m.storage.loc[sit, sto, com]['init'])
elif t == m.t[len(m.t)]: # last timestep
return (m.e_sto_con[t, sit, sto, com] >=
m.cap_sto_c[sit, sto, com] *
m.storage.loc[sit, sto, com]['init'])
else:
return pyomo.Constraint.Skip
# emissions
def res_co2_emission_rule(m):
return (pyomo.summation(m.co2_pro_out) <=
m.commodity.loc['Global', 'CO2', 'Env']['max'])
# costs
def def_costs_rule(m, cost_type):
"""Calculate total costs by cost type.
Sums up process activity and capacity expansions
and sums them in the cost types that are specified in the set
m.cost_type. To change or add cost types, add/change entries
there and modify the if/elif cases in this function accordingly.
Cost types are
- Investment costs for process power, storage power and
storage capacity. They are multiplied by the annuity
factors.
- Fixed costs for process power, storage power and storage
capacity.
- Variables costs for usage of processes, storage and transmission.
"""
if cost_type == 'Inv':
return m.costs['Inv'] == \
sum(m.cap_pro_new[p] *
m.process.loc[p]['inv-cost'] *
m.process.loc[p]['annuity-factor']
for p in m.pro_tuples) + \
sum(m.cap_tra_new[t] *
m.transmission.loc[t]['inv-cost'] *
m.transmission.loc[t]['annuity-factor']
for t in m.tra_tuples) + \
sum(m.cap_sto_p_new[s] *
m.storage.loc[s]['inv-cost-p'] *
m.storage.loc[s]['annuity-factor'] +
m.cap_sto_c_new[s] *
m.storage.loc[s]['inv-cost-c'] *
m.storage.loc[s]['annuity-factor']
for s in m.sto_tuples)
elif cost_type == 'Fix':
return m.costs['Fix'] == \
sum(m.cap_pro[p] * m.process.loc[p]['fix-cost']
for p in m.pro_tuples) + \
sum(m.cap_tra[t] * m.transmission.loc[t]['fix-cost']
for t in m.tra_tuples) + \
sum(m.cap_sto_p[s] * m.storage.loc[s]['fix-cost-p'] +
m.cap_sto_c[s] * m.storage.loc[s]['fix-cost-c']
for s in m.sto_tuples)
elif cost_type == 'Var':
return m.costs['Var'] == \
sum(m.e_pro_out[(tm,) + p] *
m.process.loc[p]['var-cost'] *
m.weight
for tm in m.tm for p in m.pro_tuples) + \
sum(m.e_tra_in[(tm,) + t] *
m.transmission.loc[t]['var-cost'] *
m.weight
for tm in m.tm for t in m.tra_tuples) + \
sum(m.e_sto_con[(tm,) + s] *
m.storage.loc[s]['var-cost-c'] * m.weight +
(m.e_sto_in[(tm,) + s] + m.e_sto_out[(tm,) + s]) *
m.storage.loc[s]['var-cost-p'] * m.weight
for tm in m.tm for s in m.sto_tuples)
elif cost_type == 'Fuel':
return m.costs['Fuel'] == sum(
m.e_co_stock[(tm,) + c] *
m.commodity.loc[c]['price'] *
m.weight
for tm in m.tm for c in m.com_tuples
if c[1] in m.com_stock)
else:
raise NotImplementedError("Unknown cost type.")
def obj_rule(m):
return pyomo.summation(m.costs)
# Equation declaration
# ====================
# declarations connect rule functions to the model, specifying
# the model sets for which the constraints are enforced
# a constraint with m.{name} automagically binds to the function
# {name}_rule. If the names don't match, one can link Constraint to
# function by using the rule keyword. Example:
# m.every_step = pyomo.Constraint(m.tm, rule=any_function_name)
# commodity
m.res_demand = pyomo.Constraint(
m.tm, m.com_tuples,
doc='storage + transmission + process + source >= demand')
m.def_e_co_stock = pyomo.Constraint(
m.tm, m.com_tuples,
doc='commodity source term = hourly commodity consumption')
m.res_stock_hour = pyomo.Constraint(
m.tm, m.com_tuples,
doc='hourly commodity source term <= commodity.maxperhour')
m.res_stock_total = pyomo.Constraint(
m.com_tuples,
doc='total commodity source term <= commodity.max')
# process
m.def_process_capacity = pyomo.Constraint(
m.pro_tuples,
doc='total process capacity = inst-cap + new capacity')
m.def_process_output = pyomo.Constraint(
m.tm, m.pro_tuples,
doc='process output = process input * efficiency')
m.def_intermittent_supply = pyomo.Constraint(
m.tm, m.pro_tuples,
doc='process output = process capacity * supim timeseries')
m.def_co2_emissions = pyomo.Constraint(
m.tm, m.pro_tuples,
doc='process co2 output = process input * process.co2 * weight')
m.res_process_output_by_capacity = pyomo.Constraint(
m.tm, m.pro_tuples,
doc='process output <= total process capacity')
m.res_process_capacity = pyomo.Constraint(
m.pro_tuples,
doc='process.cap-lo <= total process capacity <= process.cap-up')
# transmission
m.def_transmission_capacity = pyomo.Constraint(
m.tra_tuples,
doc='total transmission capacity = inst-cap + new capacity')
m.def_transmission_output = pyomo.Constraint(
m.tm, m.tra_tuples,
doc='transmission output = transmission input * efficiency')
m.res_transmission_input_by_capacity = pyomo.Constraint(
m.tm, m.tra_tuples,
doc='transmission input <= total transmission capacity')
m.res_transmission_capacity = pyomo.Constraint(
m.tra_tuples,
doc='transmission.cap-lo <= total transmission capacity <= '
'transmission.cap-up')
m.res_transmission_symmetry = pyomo.Constraint(
m.tra_tuples,
doc='total transmission capacity must be symmetric in both directions')
# storage
m.def_storage_state = pyomo.Constraint(
m.tm, m.sto_tuples,
doc='storage[t] = storage[t-1] + input - output')
m.def_storage_power = pyomo.Constraint(
m.sto_tuples,
doc='storage power = inst-cap + new power')
m.def_storage_capacity = pyomo.Constraint(
m.sto_tuples,
doc='storage capacity = inst-cap + new capacity')
m.res_storage_input_by_power = pyomo.Constraint(
m.tm, m.sto_tuples,
doc='storage input <= storage power')
m.res_storage_output_by_power = pyomo.Constraint(
m.tm, m.sto_tuples,
doc='storage output <= storage power')
m.res_storage_state_by_capacity = pyomo.Constraint(
m.t, m.sto_tuples,
doc='storage content <= storage capacity')
m.res_storage_power = pyomo.Constraint(
m.sto_tuples,
doc='storage.cap-lo-p <= storage power <= storage.cap-up-p')
m.res_storage_capacity = pyomo.Constraint(
m.sto_tuples,
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,
doc='storage content initial == and final >= storage.init * capacity')
# emissions
m.res_co2_emission = pyomo.Constraint(
doc='total CO2 emissions <= commodity.global.co2.max')
# costs
m.def_costs = pyomo.Constraint(
m.cost_type,
doc='main cost function by cost type')
m.obj = pyomo.Objective(
sense=pyomo.minimize,
doc='minimize(cost = sum of all cost types)')
return m
def annuity_factor(n, i):
"""Annuity factor formula.
Evaluates the annuity factor formula for depreciation duration
and interest rate. Works also well for equally sized numpy arrays
of values for n and i.
Args:
n: depreciation period (years)
i: interest rate (percent, e.g. 0.06 means 6 %)
Returns:
Value of the expression (1+i)**n * i / ((1+i)**n - 1)
Example:
>>> round(annuity_factor(20, 0.07), 5)
0.09439
"""
return (1+i)**n * i / ((1+i)**n - 1)
def commodity_balance(m, tm, sit, com):
"""Calculate commodity balance at given timestep.
For a given commodity co and timestep tm, calculate the balance of
consumed (to process/storage/transmission, counts positive) and provided
(from process/storage/transmission, counts negative) energy. Used as helper
function in create_model for constraints on demand and stock commodities.
Args:
m: the model object
tm: the timestep
co: the commodity
Returns
balance: net value of consumed (+) or provided (-) energy
"""
balance = 0
for p in m.pro_tuples:
if p[0] == sit and p[2] == com:
# usage as input for process increases balance
balance += m.e_pro_in[(tm,)+p]
if p[0] == sit and p[3] == com:
# output from processes decreases balance
balance -= m.e_pro_out[(tm,)+p]
for t in m.tra_tuples:
# exports increase balance
if t[0] == sit and t[3] == com:
balance += m.e_tra_in[(tm,)+t]
# imports decrease balance
if t[1] == sit and t[3] == com:
balance -= m.e_tra_out[(tm,)+t]
for s in m.sto_tuples:
# usage as input for storage increases consumption
# output from storage decreases consumption
if s[0] == sit and s[2] == com:
balance += m.e_sto_in[(tm,)+s]
balance -= m.e_sto_out[(tm,)+s]
return balance
def split_columns(columns, sep='.'):
"""Split columns by separator into MultiIndex.
Given a list of column labels containing a separator string (default: '.'),
derive a MulitIndex that is split at the separator string.
Args:
columns: list of column labels, containing the separator string
sep: the separator string (default: '.')
Example:
>>> split_columns(['DE.Elec', 'MA.Elec', 'NO.Wind'])
MultiIndex(levels=[[u'DE', u'MA', u'NO'], [u'Elec', u'Wind']],
labels=[[0, 1, 2], [0, 0, 1]])
"""
column_tuples = [tuple(col.split('.')) for col in columns]
return pd.MultiIndex.from_tuples(column_tuples)
def get_entity(instance, name):
""" Return a DataFrame for an entity in model instance.
Args:
instance: a Pyomo ConcreteModel instance
name: name of a Set, Param, Var, Constraint or Objective
Returns:
a single-columned Pandas DataFrame with domain as index
"""
# retrieve entity, its type and its onset names
entity = instance.__getattribute__(name)
labels = get_onset_names(entity)
# extract values
if isinstance(entity, pyomo.Set):
# Pyomo sets don't have values, only elements
results = pd.DataFrame([(v, 1) for v in entity.value])
# for unconstrained sets, the column label is identical to their index
# hence, make index equal to entity name and append underscore to name
# (=the later column title) to preserve identical index names for both
# unconstrained supersets
if not labels:
labels = [name]
name = name+'_'
elif isinstance(entity, pyomo.Param):
if entity.dim() > 1:
results = pd.DataFrame([v[0]+(v[1],) for v in entity.iteritems()])
else:
results = pd.DataFrame(entity.iteritems())
else:
# create DataFrame
if entity.dim() > 1:
# concatenate index tuples with value if entity has
# multidimensional indices v[0]
results = pd.DataFrame(
[v[0]+(v[1].value,) for v in entity.iteritems()])
else:
# otherwise, create tuple from scalar index v[0]
results = pd.DataFrame(
[(v[0], v[1].value) for v in entity.iteritems()])
# check for duplicate onset names and append one to several "_" to make
# them unique, e.g. ['sit', 'sit', 'com'] becomes ['sit', 'sit_', 'com']
for k, label in enumerate(labels):
if label in labels[:k]:
labels[k] = labels[k] + "_"
# name columns according to labels + entity name
results.columns = labels + [name]
results.set_index(labels, inplace=True)
return results
def get_entities(instance, names):
""" Return one DataFrame with entities in columns and a common index.
Works only on entities that share a common domain (set or set_tuple), which
is used as index of the returned DataFrame.
Args:
instance: a Pyomo ConcreteModel instance
names: list of entity names (as returned by list_entities)
Returns:
a Pandas DataFrame with entities as columns and domains as index
"""
df = pd.DataFrame()
for name in names:
other = get_entity(instance, name)
if df.empty:
df = other
else:
index_names_before = df.index.names
df = df.join(other, how='outer')
if index_names_before != df.index.names:
df.index.names = index_names_before
return df
def list_entities(instance, entity_type):
""" Return list of sets, params, variables, constraints or objectives
Args:
instance: a Pyomo ConcreteModel object
entity_type: "set", "par", "var", "con" or "obj"
Returns:
DataFrame of entities
Example:
>>> data = read_excel('data-example.xlsx')
>>> model = create_model(data, range(1,25))
>>> list_entities(model, 'obj') #doctest: +NORMALIZE_WHITESPACE
Description Domain
Name
obj minimize(cost = sum of all cost types) []
[1 rows x 2 columns]
"""
# helper function to discern entities by type
def filter_by_type(entity, entity_type):
if entity_type == 'set':
return isinstance(entity, pyomo.Set) and not entity.virtual
elif entity_type == 'par':
return isinstance(entity, pyomo.Param)
elif entity_type == 'var':
return isinstance(entity, pyomo.Var)
elif entity_type == 'con':
return isinstance(entity, pyomo.Constraint)
elif entity_type == 'obj':
return isinstance(entity, pyomo.Objective)
else:
raise ValueError("Unknown entity_type '{}'".format(entity_type))
# iterate through all model components and keep only
iter_entities = instance.__dict__.iteritems()
entities = sorted(
(name, entity.doc, get_onset_names(entity))
for (name, entity) in iter_entities
if filter_by_type(entity, entity_type))
# if something was found, wrap tuples in DataFrame, otherwise return empty
if entities:
entities = pd.DataFrame(entities,
columns=['Name', 'Description', 'Domain'])
entities.set_index('Name', inplace=True)
else:
entities = pd.DataFrame()
return entities
def get_onset_names(entity):
"""
Example:
>>> data = read_excel('data-example.xlsx')
>>> model = create_model(data, range(1,25))
>>> get_onset_names(model.e_co_stock)
['t', 'sit', 'com', 'com_type']
"""
# get column titles for entities from domain set names
labels = []
if isinstance(entity, pyomo.Set):
if entity.dimen > 1:
# N-dimensional set tuples, possibly with nested set tuples within
if entity.domain:
domains = entity.domain.set_tuple
else:
domains = entity.set_tuple
for domain_set in domains:
labels.extend(get_onset_names(domain_set))
elif entity.dimen == 1:
if entity.domain:
# 1D subset; add domain name
labels.append(entity.domain.name)
else:
# unrestricted set; add entity name
labels.append(entity.name)
else:
# no domain, so no labels needed
pass
elif isinstance(entity, (pyomo.Param, pyomo.Var, pyomo.Constraint,
pyomo.Objective)):
if entity.dim() > 0 and entity._index:
labels = get_onset_names(entity._index)
else:
# zero dimensions, so no onset labels
pass
else:
raise ValueError("Unknown entity type!")
return labels
def get_constants(instance):
"""Return summary DataFrames for important variables
Usage: