forked from yabata/ficus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ficus.py
2586 lines (2183 loc) · 85.2 KB
/
ficus.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
"""ficus: A (mixed integer) linear optimisation model for local energy systems
ficus minimises total cost for providing energy in form of desired commodities
to satisfy a given demand in form of timeseries. The
model contains commodities (e.g. electricity, heat, gas...),
processes that convert one commodity to another
and storage for saving/retrieving commodities.
https://github.com/yabata/ficus
"""
import pyomo.core as pyen
import pyomo.environ
from pyomo.opt import SolverFactory
from pyomo.opt import SolverManagerFactory
import pandas as pd
import numpy as np
import time
import os
############################################################################################
#RUN FUNCTIONS
############################################################################################
def run_ficus (input_file, opt = 'glpk', Threads = 2,neos=False):
"""Read input data, create a model and solve it
Args:
opt: Solver to be used
Threads: number of simultaneous CPU threads (only for gurobi and cplex)
neos: set to TRUE, if solver from neos server should be used
Returns:
prob: model instance containing results
"""
# Optimizer
# ============
optimizer = SolverFactory(opt) #set optimizer
if optimizer.name == 'gurobi' and not neos:
# reference with list of option names
# http://www.gurobi.com/documentation/5.6/reference-manual/parameters
optimizer.set_options("Threads="+str(Threads)) # number of simultaneous CPU threads
elif optimizer.name == 'cplex' and not neos:
optimizer.options["threads"] = Threads # number of simultaneous CPU threads
else:
print('\n Setting number of simultaneous CPU threads only available for locally installed "gurobi" and "cplex"\n')
# RUN MODEL
# ============
#read model data
print('Read Data ...\n')
t0 = time.time()
xls_data = read_xlsdata(input_file)
print('Data Read. time: '+"{:.1f}".format(time.time()-t0)+' s\n')
#prepare data for model from xls_data
print('Prepare Data ...\n')
t = time.time()
data = prepare_modeldata(xls_data)
print('Data Prepared. time: '+"{:.1f}".format(time.time()-t)+' s\n')
#define optimisation problem
print('Define Model ...\n')
t = time.time()
prob = create_model(data)
print('Model Defined. time: '+"{:.1f}".format(time.time()-t)+' s\n')
# solve the problem
print('Solve Model ...\n')
t = time.time()
if neos:
solver_manager = SolverManagerFactory('neos')
result = solver_manager.solve(prob,opt=optimizer,tee=True)
else:
result = optimizer.solve(prob,tee=True)
print('Model Solved. time: '+"{:.1f}".format(time.time()-t)+' s\n')
print('Load Results ...\n')
t = time.time()
prob.solutions.load_from(result) # load result back to model instance
print('Results Loaded. time: '+"{:.1f}".format(time.time()-t)+' s\n')
print('Total Time: '+"{:.1f}".format(time.time()-t0)+' s\n')
return prob
def run_from_excel(input_file,opt):
"""Run Model directly from excel with makro
Args:
input_file: path of input file
opt: solver
"""
import sys
#create new time stamp folder in subfolder "result" with name of inputfile
result_name = os.path.splitext(os.path.split(input_file)[1])[0]
result_folder = os.path.join(os.path.split(input_file)[0],'result')
result_dir = prepare_result_directory(result_folder,result_name)
#Use "cbc" or "mosek" solver from Neos server, if selected
if 'neos' in opt:
neos = True
if 'cbc' in opt:
opt = 'cbc'
elif 'mosek' in opt:
opt = 'mosek'
else:
neos = False
#create and solve model from inputfile
prob = run_ficus(input_file, opt = opt,neos=neos)
#save results
report(prob, result_dir)
#save figures
result_figures(result_dir,prob=prob, show=True)
raw_input("Press Enter to close figures and cmd window...\n")
return
############################################################################################
#Model
############################################################################################
def create_model(data):
# Preparations
# ============
#Model Data
time_settings = data['time-settings']
mip_equations = data['mip-equations']
ext_co = data['ext-co']
ext_import = data['ext_import']
ext_export = data['ext_export']
demandrate_factor = data['demandrate_factor']
process = data['process']
process_commodity = data['process_commodity']
process_class = data['process_class']
storage = data['storage']
demand = data['demand']
supim = data['supim']
#TIME PARAMETERS
timesteps = np.arange (int(time_settings.loc['Time']['start']) - 1 , \
int(time_settings.loc['Time']['end']) + 1)
tb=int(time_settings.loc['Time']['timebase']) #timebase of time dependent data
year_factor = float(timesteps.size-1) * tb / (365 * 24 * 60 * 60) # multiple of a year: opt_time[s] / year [s]
p2e = float(tb) / 3600 # factor for converting power [kW] to energy [kWh] for one timestep
# Flags
# ============
#Partload
if process['partload-min'].any() == 0:
mip_equations.loc['Partload']['Active']='no' #partload equations are irrelevant if "partload-min" = 0 for all processes
if mip_equations.loc['Partload']['Active']=='no':
#if "Partload" is deactivated, adjust process parameters
process['partload-min']=0
process['start-up-energy']=0
process_commodity['ratio-partload']=process_commodity['ratio']
elif mip_equations.loc['Partload']['Active']=='yes':
if process_commodity['ratio-partload'].isnull().any():
raise NotImplementedError("'ratio-partload' in sheet 'Process-Commodity' contains invalid values")
#Min-Cap
if (process['cap-new-min'].any() or storage['cap-new-min-p'].any() or storage['cap-new-min-e'].any()) == 0:
mip_equations.loc['Min-Cap']['Active']='no' #partload equations are irrelevant if "partload-min" = 0 for all processes
if mip_equations.loc['Min-Cap']['Active']=='no':
#if "Min-Cap" is deactivated, adjust minimum capacity parameters
process['cap-new-min']=0
storage['cap-new-min-p']=0
storage['cap-new-min-e']=0
#=========
#MODEL
#=========
m = pyen.ConcreteModel()
m.name = 'ficus'
m.inputfile = data['input_file']
##Sets##
########
#commodity
m.commodity = pyen.Set(
initialize=demand.columns | pd.Index(set(process_commodity.index.get_level_values(2))) | ext_import.columns,
doc='Commodities')
m.co_consumed = pyen.Set(
within=m.commodity,
initialize=demand.columns | get_pro_inputs(process_commodity),
doc='Commodities that are consumed by processes or demand')
m.co_produced = pyen.Set(
within=m.commodity,
initialize = get_pro_outputs(process_commodity),
doc='Commodities that are produced by processes')
m.co_ext_in = pyen.Set(
within=m.commodity,
initialize=ext_import.columns,
doc='Commodities in External-Supply-Price')
m.co_ext_out = pyen.Set(
within=m.commodity,
initialize=ext_export.columns,
doc='Commodities in Feed-In-Price')
m.co_ext = pyen.Set(
within=m.commodity,
initialize=ext_export.columns | ext_import.columns,
doc='Commodities in External Supply or Feed-In-Price')
m.co_demand = pyen.Set(
within=m.commodity,
initialize=demand.columns,
doc='Commodities in Demand')
m.co_storage = pyen.Set(
within=m.commodity,
initialize=pd.Index(set(storage.index.get_level_values(1))),
doc='Commodities stored in Storage')
m.co_supim = pyen.Set(
initialize=supim.columns,
doc='Commodities in supim')
m.co_proclass = pyen.Set(
within=m.commodity,
initialize=pd.Index(set(process_class.index.get_level_values(1))),
doc='Commodities in Process Class')
#process
m.pro_name = pyen.Set(
initialize=pd.Index(set(process.index.get_level_values(0))),
doc='Name of Process')
m.pro_num = pyen.Set(
initialize=pd.Index(set(process.index.get_level_values(1))),
doc='Num of Process')
m.pro_tuples = pyen.Set(
within=m.pro_name*m.pro_num,
initialize=process.index.get_values(),
doc='Processes, converting commodities')
if process.index.get_values().size>0:
m.pro_input_tuples = pyen.Set(
within=m.pro_name*m.pro_num*m.commodity,
initialize = process_commodity.xs('In',level='Direction').index.get_values(),
doc='Commodities consumed by processes')
m.pro_output_tuples = pyen.Set(
within=m.pro_name*m.pro_num*m.commodity,
initialize=process_commodity.xs('Out',level='Direction').index.get_values(),
doc='Commodities emitted by processes')
else:
m.pro_input_tuples = pyen.Set(
within=m.pro_name*m.pro_num*m.commodity,
initialize = [],
doc='Commodities consumed by processes')
m.pro_output_tuples = pyen.Set(
within=m.pro_name*m.pro_num*m.commodity,
initialize=[],
doc='Commodities emitted by processes')
#Process Class
m.proclass_name = pyen.Set(
initialize=pd.Index(set(process_class.index.get_level_values(0))),
doc='Process Classes')
m.proclass_tuples = pyen.Set(
within=m.proclass_name*m.commodity,
initialize=process_class.index.get_values(),
doc='Process Class tuples')
#Storage
m.storage_name = pyen.Set(
initialize=pd.Index(set(storage.index.get_level_values(0))),
doc='Name of Storage')
m.storage_num = pyen.Set(
initialize=pd.Index(set(storage.index.get_level_values(2))),
doc='Num of Storage')
m.sto_tuples = pyen.Set(
within=m.storage_name*m.co_storage*m.storage_num,
initialize=storage.index.get_values(),
doc='storage name with stored commodity and num')
# time
m.t0 = pyen.Set(
ordered=True,
initialize=timesteps,
doc='Timesteps with zero')
m.t = pyen.Set(
within=m.t0,
ordered=True,
initialize=timesteps[1:],
doc='Timesteps for model')
# costs
m.cost_type = pyen.Set(
initialize=['Import', 'Export','Demand charges','Invest','Fix costs', 'Var costs','Process fee','Pro subsidy'],
doc='Types of costs')
##Parameters##
##############
if process.index.get_values().size>0:
# process input/output ratios
m.r_in = process_commodity.xs('In', level='Direction')['ratio']
m.r_in_partl = process_commodity.xs('In', level='Direction')['ratio-partload']
m.r_out = process_commodity.xs('Out', level='Direction')['ratio']
m.r_out_partl = process_commodity.xs('Out', level='Direction')['ratio-partload']
#Calculate slope and offset for process input and output equations
#For calculating power input/output p for each commodity dependent on power throughput "flow"
# p = slope * flow + offset
m.pro_p_in_slope = pd.Series(index=m.r_in.index)
m.pro_p_in_offset_spec = pd.Series(index=m.r_in.index)
for idx in m.pro_p_in_slope.index:
m.pro_p_in_slope.loc[idx] = (m.r_in.loc[idx] - m.r_in_partl.loc[idx]*process.loc[idx[0:2]]['partload-min'])/(1-process.loc[idx[0:2]]['partload-min'])
m.pro_p_in_offset_spec[idx] = m.r_in.loc[idx]-m.pro_p_in_slope.loc[idx]
m.pro_p_out_slope = pd.Series(index=m.r_out.index)
m.pro_p_out_offset_spec = pd.Series(index=m.r_out.index)
for idx in m.pro_p_out_slope.index:
m.pro_p_out_slope.loc[idx] = (m.r_out.loc[idx] - m.r_out_partl.loc[idx]*process.loc[idx[0:2]]['partload-min'])/(1-process.loc[idx[0:2]]['partload-min'])
m.pro_p_out_offset_spec[idx] = m.r_out.loc[idx]-m.pro_p_out_slope.loc[idx]
m.demand = demand
m.supim = supim
m.tb = tb
##Variables##
##############
#Commodity Energy Balance
m.co_e_consumed = pyen.Var(
m.co_consumed, within=pyen.NonNegativeReals,
doc='total energy consumed of commodity')
m.co_e_produced = pyen.Var(
m.co_produced, within=pyen.NonNegativeReals,
doc='total energy produced of commodity')
#Commodity Power flow
m.pro_p_flow= pyen.Var(
m.pro_tuples,m.t0, within=pyen.NonNegativeReals,
doc='power flow (kW) through process')
m.pro_p_in = pyen.Var(
m.pro_input_tuples,m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) of commodity into process')
m.pro_p_out = pyen.Var(
m.pro_output_tuples,m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) of commodity out of process')
m.ext_p_in= pyen.Var(
m.co_ext_in,m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) of commodity from extern source')
m.ext_p_out= pyen.Var(
m.co_ext_out,m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) of commodity to extern (export)')
m.ext_demandrate_in= pyen.Var(
m.co_ext_in,m.t, within=pyen.NonNegativeReals,
doc=' power flow (kW) of imported commodity in one timestep based in demand rate time interval')
m.ext_demandrate_out= pyen.Var(
m.co_ext_out,m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) of exported commodity in one timestep based in demand rate time interval')
m.ext_demandrate_max= pyen.Var(
m.co_ext_in, within=pyen.NonNegativeReals,
doc='max power flow (kW) of imported or exported commodity in one timestep based in demand rate time interval')
m.sto_p_in= pyen.Var(
m.sto_tuples, m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) in storage')
m.sto_p_out= pyen.Var(
m.sto_tuples, m.t, within=pyen.NonNegativeReals,
doc='power flow (kW) out of storage')
#Process
m.pro_cap = pyen.Var(
m.pro_tuples, within=pyen.NonNegativeReals,
doc='Capacity (kW) of process')
m.pro_cap_new = pyen.Var(
m.pro_tuples, within=pyen.NonNegativeReals,
doc='New additional Capacity (kW) of process')
if mip_equations.loc['Min-Cap']['Active']=='yes':
m.pro_cap_build = pyen.Var(
m.pro_tuples, within=pyen.Boolean,
doc='Boolean: True if new capacity is build. Needed for minimum new capacity')
elif mip_equations.loc['Min-Cap']['Active']=='no':
m.pro_cap_build = pyen.Param(
m.pro_tuples, initialize=1,
doc='No Min-Cap: Build = 1')
else:
raise NotImplementedError("For mip_equations only 'yes' or 'no' are valid inputs")
if mip_equations.loc['Partload']['Active']=='yes':
m.pro_p_in_offset= pyen.Var(
m.pro_input_tuples,m.t, within=pyen.Reals,
doc='offset for calculating process input (kW)')
m.pro_p_out_offset= pyen.Var(
m.pro_output_tuples,m.t, within=pyen.Reals,
doc='offset for calculating process output (kW)')
m.pro_mode_run= pyen.Var(
m.pro_tuples,m.t0, within=pyen.Boolean,
doc='booelan : true if process in run mode')
m.pro_mode_startup= pyen.Var(
m.pro_tuples,m.t, within=pyen.NonNegativeReals,
doc='1 if process is "switched" on, 0 else')
m.pro_p_startup = pyen.Var(
m.pro_input_tuples,m.t, within=pyen.NonNegativeReals,
doc='switch on power losses (kW)')
elif mip_equations.loc['Partload']['Active']=='no':
m.pro_p_in_offset= pyen.Param(
m.pro_input_tuples,m.t, initialize=0,
doc='No Partload: offset is zero')
m.pro_p_out_offset= pyen.Param(
m.pro_output_tuples,m.t, initialize=0,
doc='No Partload: offset is zero')
m.pro_mode_run= pyen.Param(
m.pro_tuples,m.t0, initialize=1,
doc='No Partload: run=1')
m.pro_mode_startup= pyen.Param(
m.pro_tuples,m.t, initialize=0,
doc='No Partload: startup=0')
m.pro_p_startup= pyen.Param(
m.pro_input_tuples,m.t, initialize=0,
doc='No Partload: startup_loss=0')
else:
raise NotImplementedError("For mip_equations only 'yes' or 'no' are valid inputs")
#PROCESS CLASS
m.proclass_cap = pyen.Var(
m.proclass_tuples, within=pyen.NonNegativeReals,
doc='Capacity (kW) of all processes in class and commodity')
m.proclass_e_out = pyen.Var(
m.proclass_tuples, within=pyen.NonNegativeReals,
doc='Energy output (kWh) of all processes in class and commodity')
m.proclass_e_in = pyen.Var(
m.proclass_tuples, within=pyen.NonNegativeReals,
doc='Energy input (kWh) of all processes in class and commodity')
#STORAGE
m.sto_cap_e = pyen.Var(
m.sto_tuples, within=pyen.NonNegativeReals,
doc='Energy Capacity (kWh) ofstorage')
m.sto_cap_e_new = pyen.Var(
m.sto_tuples, within=pyen.NonNegativeReals,
doc='New additional Energy Capacity (kW) of storage')
m.sto_cap_p = pyen.Var(
m.sto_tuples, within=pyen.NonNegativeReals,
doc='Power Capacity (kW) of storage')
m.sto_cap_p_new = pyen.Var(
m.sto_tuples, within=pyen.NonNegativeReals,
doc='New additional Power Capacity (kW) of storage')
m.sto_e_cont = pyen.Var(
m.sto_tuples, m.t0, within=pyen.NonNegativeReals,
doc='Energy content in storage')
if mip_equations.loc['Min-Cap']['Active']=='yes':
m.sto_cap_build = pyen.Var(
m.sto_tuples, within=pyen.Boolean,
doc='Boolean: True if new capacity is build. Needed for minimum new capacity')
elif mip_equations.loc['Min-Cap']['Active']=='no':
m.sto_cap_build = pyen.Param(
m.sto_tuples, initialize=1,
doc='Boolean: True if new capacity is build. Needed for minimum new capacity')
else:
raise NotImplementedError("For mip_equations only 'yes' or 'no' are valid inputs")
if mip_equations.loc['Storage In-Out']['Active'] == 'yes':
m.sto_charge = pyen.Var(
m.co_storage, m.t, within=pyen.Boolean,
doc='Bool Variable, 1 if charging')
elif mip_equations.loc['Storage In-Out']['Active'] == 'no':
pass
else:
raise NotImplementedError("For mip_equations only 'yes' or 'no' are valid inputs")
#COSTS
m.costs = pyen.Var(
m.cost_type, within=pyen.Reals,
doc='cost by cost types')
##Equations##
##############
"""COMMODITY"""
def co_energy_consumption_rule(m, co):
return m.co_e_consumed[co] == energy_consumption(m, co) * p2e
m.co_energy_consumption = pyen.Constraint(
m.co_consumed,
rule = co_energy_consumption_rule,
doc='commodity: total energy consumed ')
def co_energy_production_rule(m, co):
return m.co_e_produced[co] == energy_production(m, co) * p2e
m.co_energy_production = pyen.Constraint(
m.co_produced,
rule = co_energy_production_rule,
doc='commodity: total energy produced ')
def co_power_balance_rule(m, co, t):
co_balance = commodity_balance(m, co, t)
return co_balance == 0
m.co_power_balance = pyen.Constraint(
m.commodity, m.t,
rule=co_power_balance_rule,
doc='power balance must be zero for every timestep')
""" PROCESS """
#initial
def pro_p_flow_init_rule(m,pro,num,t):
if t == m.t0[1]:
return m.pro_p_flow[pro,num,t] == process.loc[pro,num]['initial-power']
else:
return pyen.Constraint.Skip
m.pro_p_flow_init = pyen.Constraint(
m.pro_tuples,m.t0,
rule = pro_p_flow_init_rule,
doc='initial p_flow')
if mip_equations.loc['Partload']['Active']=='yes':
def pro_mode_run_init_rule(m,pro,num,t):
if t == m.t0[1]:
return m.pro_mode_run[pro,num,t] == process.loc[pro,num]['initial-run']
else:
return pyen.Constraint.Skip
m.pro_mode_run_init = pyen.Constraint(
m.pro_tuples,m.t0,
rule = pro_mode_run_init_rule,
doc='initial run mode')
# capacity
def pro_cap_abs_rule(m,pro,num):
return m.pro_cap[pro,num] == m.pro_cap_new[pro,num] + process.loc[pro,num]['cap-installed']
m.pro_cap_abs = pyen.Constraint(
m.pro_tuples,
rule = pro_cap_abs_rule,
doc='capacity = cap_new + cap_installed')
def pro_cap_new_max_rule(m,pro,num):
return m.pro_cap_new[pro,num] <= m.pro_cap_build[pro,num] * process.loc[pro,num]['cap-new-max']
m.pro_cap_new_max = pyen.Constraint(
m.pro_tuples,
rule = pro_cap_new_max_rule,
doc='limit max new capacity of process')
def pro_cap_new_min_rule(m,pro,num):
return m.pro_cap_new[pro,num] >= m.pro_cap_build[pro,num] * process.loc[pro,num]['cap-new-min']
m.pro_cap_new_min = pyen.Constraint(
m.pro_tuples,
rule=pro_cap_new_min_rule,
doc='limit min new capacity of process, if it is built')
#flow
def pro_p_flow_max_rule(m,pro,num,t):
return m.pro_p_flow[pro,num,t] <= \
m.pro_cap[pro,num]
m.pro_p_flow_max = pyen.Constraint(
m.pro_tuples,m.t,
rule = pro_p_flow_max_rule,
doc='p_flow <= capacity of process')
#Supim
def pro_p_supim_input_rule(m,pro,num,co,t):
if co in m.co_supim:
return m.pro_p_in[pro,num,co,t] <= \
m.pro_cap[pro,num] * supim.loc[t][co]*m.r_in[pro,num,co]
else:
return pyen.Constraint.Skip
m.pro_p_supim_input = pyen.Constraint(
m.pro_input_tuples,m.t,
rule=pro_p_supim_input_rule,
doc='Limit power input from "supim" to installed capacity')
# in
def pro_p_input_rule(m,pro,num,co,t):
return m.pro_p_in[pro,num,co,t] == \
m.pro_p_flow[pro,num,t] * m.pro_p_in_slope[pro,num,co]\
+ m.pro_p_in_offset[pro,num,co,t]\
+ m.pro_p_startup[pro,num,co,t]
m.pro_p_input = pyen.Constraint(
m.pro_input_tuples,m.t,
rule=pro_p_input_rule,
doc='Calculate input power for every commodity dependent on ratios\
p_in = p_flow * p_slope_in + p_offset_in + startup * E_startup/t*r_in;')
#out
def pro_p_output_rule(m,pro,num,co,t):
return m.pro_p_out[pro,num,co,t] == m.pro_p_flow[pro,num,t] * m.pro_p_out_slope[pro,num,co]\
+ m.pro_p_out_offset[pro,num,co,t]
m.pro_p_output = pyen.Constraint(
m.pro_output_tuples, m.t,
rule=pro_p_output_rule,
doc='Calculate output power for every commodity dependent on ratios\
p_out = p_flow * p_slope_out + p_offset_out')
if mip_equations.loc['Partload']['Active']=='yes':
#offset in
def pro_p_in_offset_lt_rule(m,pro,num,co,t):
return m.pro_p_in_offset[pro,num,co,t] \
- (m.pro_p_in_offset_spec[pro,num,co] * m.pro_cap[pro,num]) \
<= (1 - m.pro_mode_run[pro,num,t]) * process.loc[pro,num]['cap-abs-max']*m.r_in[pro,num,co]
m.pro_p_in_offset_lt = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_in_offset_lt_rule,
doc='offset must be (lower) equal to offset_spec*cap , when run = 1\
p_offset - (offset_spec*cap) <= (1-run) * cap-max -> p_offset <= (offset_spec*cap) if run=1. ')
def pro_p_in_offset_gt_rule(m,pro,num,co,t):
return m.pro_p_in_offset[pro,num,co,t] - (m.pro_p_in_offset_spec[pro,num,co] * m.pro_cap[pro,num])\
>= -(1 - m.pro_mode_run[pro,num,t]) * process.loc[pro,num]['cap-abs-max']*m.r_in[pro,num,co]
m.pro_p_in_offset_gt = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_in_offset_gt_rule,
doc='offset must be (greater) equal to offset_spec*cap , when run = 1\
p_offset - (offset_spec*cap) >= -(1-run) * cap-max -> p_offset >= (offset_spec*cap) if run=1')
def pro_p_offset_in_ltzero_when_off_rule(m,pro,num,co,t):
return m.pro_p_in_offset[pro,num,co,t] <= \
(m.pro_mode_run[pro,num,t]) * \
process.loc[pro,num]['cap-abs-max']*m.r_in[pro,num,co]
m.pro_p_offset_in_ltzero_when_off = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_offset_in_ltzero_when_off_rule,
doc='p_offset must be (lower) equal to zero when run=0\
p_offset <= run * cap_max')
def pro_p_offset_in_gtzero_when_off_rule(m,pro,num,co,t):
return m.pro_p_in_offset[pro,num,co,t] >= \
-(m.pro_mode_run[pro,num,t]) * \
process.loc[pro,num]['cap-abs-max']*m.r_in[pro,num,co]
m.pro_p_offset_in_gtzero_when_off = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_offset_in_gtzero_when_off_rule,
doc='p_offset must be (greater) equal to zero when run=0\
p_offset >= run * cap_max')
#offset out
def pro_p_out_offset_lt_rule(m,pro,num,co,t):
return m.pro_p_out_offset[pro,num,co,t] - (m.pro_p_out_offset_spec[pro,num,co] * m.pro_cap[pro,num])\
<= (1 - m.pro_mode_run[pro,num,t]) * process.loc[pro,num]['cap-abs-max']*m.r_out[pro,num,co]
m.pro_p_out_offset_lt = pyen.Constraint(
m.pro_output_tuples,m.t,
rule = pro_p_out_offset_lt_rule,
doc='offset must be (lower) equal to offset_spec*cap , when run = 1\
p_offset - (offset_spec*cap) <= (1-run) * cap-max -> p_offset <= (offset_spec*cap) if run=1. ')
def pro_p_out_offset_gt_rule(m,pro,num,co,t):
return m.pro_p_out_offset[pro,num,co,t] - (m.pro_p_out_offset_spec[pro,num,co] * m.pro_cap[pro,num])\
>= -(1 - m.pro_mode_run[pro,num,t]) * process.loc[pro,num]['cap-abs-max']*m.r_out[pro,num,co]
m.pro_p_out_offset_gt = pyen.Constraint(
m.pro_output_tuples,m.t,
rule = pro_p_out_offset_gt_rule,
doc='offset must be (greater) equal to offset_spec*cap , when run = 1\
p_offset - (offset_spec*cap) >= -(1-run) * cap-max -> p_offset >= (offset_spec*cap) if run=1')
def pro_p_offset_out_ltzero_when_off_rule(m,pro,num,co,t):
return m.pro_p_out_offset[pro,num,co,t] <= \
(m.pro_mode_run[pro,num,t]) * \
process.loc[pro,num]['cap-abs-max']*m.r_out[pro,num,co]
m.pro_p_offset_out_ltzero_when_off = pyen.Constraint(
m.pro_output_tuples,m.t,
rule = pro_p_offset_out_ltzero_when_off_rule,
doc='p_offset is zero when mode not "run"')
def pro_p_offset_out_gtzero_when_off_rule(m,pro,num,co,t):
return m.pro_p_out_offset[pro,num,co,t] >= \
-(m.pro_mode_run[pro,num,t]) * \
process.loc[pro,num]['cap-abs-max']*m.r_out[pro,num,co]
m.pro_p_offset_out_gtzero_when_off = pyen.Constraint(
m.pro_output_tuples,m.t,
rule = pro_p_offset_out_gtzero_when_off_rule,
doc='p_offset is zero when mode not "run"')
# mode
def pro_p_flow_zero_when_off_rule(m,pro,num,t):
return m.pro_p_flow[pro,num,t] <= \
(m.pro_mode_run[pro,num,t]) * \
process.loc[pro,num]['cap-abs-max']
m.pro_p_flow_zero_when_off = pyen.Constraint(
m.pro_tuples,m.t,
rule=pro_p_flow_zero_when_off_rule,
doc='p_flow is zero when run = 0')
def pro_p_gt_partload_rule(m,pro,num,t):
return (m.pro_p_flow[pro,num,t] - m.pro_cap[pro,num] * process.loc[pro,num]['partload-min']) >= -(1 - m.pro_mode_run[pro,num,t]) * process.loc[pro,num]['cap-abs-max']
m.pro_p_gt_partload = pyen.Constraint(
m.pro_tuples,m.t,
rule = pro_p_gt_partload_rule,
doc='p_flow >= capacity * partload if run =1 ')
#switch on losses
def pro_mode_start_up1_rule(m,pro,num,t):
return m.pro_mode_startup[pro,num,t] >= \
m.pro_mode_run[pro,num,t] - \
(m.pro_mode_run[pro,num,t-1])
m.pro_mode_start_up1 = pyen.Constraint(
m.pro_tuples,m.t,
rule=pro_mode_start_up1_rule,
doc='switch on >= run[t] - run[t-1]')
def pro_mode_start_up2_rule(m,pro,num,t):
return m.pro_mode_startup[pro,num,t] <= \
m.pro_mode_run[pro,num,t]
m.pro_mode_start_up2 = pyen.Constraint(
m.pro_tuples,m.t,
rule=pro_mode_start_up2_rule,
doc='switch on <= run[t]')
def pro_mode_start_up3_rule(m,pro,num,t):
return m.pro_mode_startup[pro,num,t] <= \
1 - m.pro_mode_run[pro,num,t-1]
m.pro_mode_start_up3 = pyen.Constraint(
m.pro_tuples,m.t,
rule=pro_mode_start_up3_rule,
doc='switch on <= run[t-1]')
def pro_p_startup_lt_rule(m,pro,num,co,t):
return (m.pro_p_startup[pro,num,co,t]\
- (process.loc[pro,num]['start-up-energy'] / p2e \
* m.r_in[pro,num,co]*m.pro_cap[pro,num]))\
<= ((1 - m.pro_mode_startup[pro,num,t]) \
* (process.loc[pro,num]['start-up-energy'] / p2e\
* m.r_in[pro,num,co]*process.loc[pro,num]['cap-abs-max']))
m.pro_p_startup_lt = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_startup_lt_rule,
doc='switch on loss must be (lower) equal to p_startup_spec*cap , when startup = 1\
p_startup - (startup_spec*cap) <= (1-startup) * cap-max -> p_startup <= (p_startup_spec*cap) if startup=1. ')
def pro_p_startup_gt_rule(m,pro,num,co,t):
return (m.pro_p_startup[pro,num,co,t]\
- (process.loc[pro,num]['start-up-energy'] / p2e\
* m.r_in[pro,num,co]*m.pro_cap[pro,num]))\
>= -((1 - m.pro_mode_startup[pro,num,t]) \
* (process.loc[pro,num]['start-up-energy'] / p2e\
* m.r_in[pro,num,co]*process.loc[pro,num]['cap-abs-max']))
m.pro_p_startup_gt = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_startup_gt_rule,
doc='switch on loss must be (greater) equal to p_startup_spec*cap , when startup = 1\
p_startup - (startup_spec*cap) >= -(1-startup) * cap-max -> p_startup >= (p_startup_spec*cap) if startup=1. ')
def pro_p_startup_zerowhenoff_rule(m,pro,num,co,t):
return m.pro_p_startup[pro,num,co,t]\
<= m.pro_mode_startup[pro,num,t] \
* (process.loc[pro,num]['start-up-energy'] / p2e\
* m.r_in[pro,num,co]*process.loc[pro,num]['cap-abs-max'])
m.pro_p_startup_zerowhenoff = pyen.Constraint(
m.pro_input_tuples,m.t,
rule = pro_p_startup_zerowhenoff_rule,
doc='switch on loss must be zerowhen startup = 0')
"""PROCESS CLASS"""
# CALCULATIONS
def proclass_cap_sum_rule(m,cl,co):
return m.proclass_cap[cl,co] == \
sum(m.pro_cap[p[0:2]] * m.r_out[p]\
for p in m.pro_output_tuples
if co in p
if cl == process.loc[p[0:2]]['class'])\
+ sum(m.pro_cap[p[0:2]] * m.r_in[p]\
for p in m.pro_input_tuples
if co in p
if cl == process.loc[p[0:2]]['class'])
m.proclass_cap_sum = pyen.Constraint(
m.proclass_tuples,
rule=proclass_cap_sum_rule,
doc='Calculate total capacity of class and commodity')
def proclass_e_out_sum_rule(m,cl,co):
return m.proclass_e_out[cl,co] == \
sum(m.pro_p_out[p,t] * p2e\
for t in m.t
for p in m.pro_output_tuples\
if co in p
if cl == process.loc[p[0:2]]['class'])
m.proclass_e_out_sum = pyen.Constraint(
m.proclass_tuples,
rule=proclass_e_out_sum_rule,
doc='Calculate total energy outpout of class and commodity')
def proclass_e_in_sum_rule(m,cl,co):
return m.proclass_e_in[cl,co] == \
sum(m.pro_p_in[p,t] * p2e\
for t in m.t
for p in m.pro_input_tuples\
if co in p
if cl == process.loc[p[0:2]]['class'])
m.proclass_e_in_sum = pyen.Constraint(
m.proclass_tuples,
rule=proclass_e_in_sum_rule,
doc='Calculate total energy outpout of class and commodity')
# CONSTRAINTS
def proclass_cap_max_rule(m, cl, co):
return m.proclass_cap[cl,co] <= \
process_class.loc[cl,co]['cap-max']
m.proclass_cap_max = pyen.Constraint(
m.proclass_tuples,
rule=proclass_cap_max_rule,
doc='limitmax capacity of class and commodity')
def proclass_e_max_rule(m, cl, co):
if process_class.loc[cl,co]['Direction'] == 'In':
return m.proclass_e_in[cl,co] <= \
process_class.loc[cl,co]['energy-max'] * year_factor
if process_class.loc[cl,co]['Direction'] == 'Out':
return m.proclass_e_out[cl,co] <= \
process_class.loc[cl,co]['energy-max'] * year_factor
m.proclass_e_max = pyen.Constraint(
m.proclass_tuples,
rule=proclass_e_max_rule,
doc='limitmax energy output of class and commodity')
"""STORAGE"""
#initial
def sto_e_cont_init_rule(m,sto,co,num,t):
if t == m.t0[1]:
return m.sto_e_cont[sto,co,num,t] == \
storage.loc[sto,co,num]['initial-soc'] * m.sto_cap_e[sto,co,num]
elif t == m.t0[-1]:
return m.sto_e_cont[sto,co,num,t] == \
storage.loc[sto,co,num]['initial-soc'] * m.sto_cap_e[sto,co,num]
else:
return pyen.Constraint.Skip
m.sto_e_cont_init = pyen.Constraint(
m.sto_tuples,m.t0,
rule=sto_e_cont_init_rule,
doc='initial and minimum final content of energy storage')
# capacity
def sto_cap_e_abs_rule(m,sto,co,num):
return m.sto_cap_e[sto,co,num] == \
m.sto_cap_e_new[sto,co,num] + storage.loc[sto,co,num]['cap-installed-e']
m.sto_cap_e_abs = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_e_abs_rule,
doc='Energy Capacity: capacity = cap_new + cap_installed')
def sto_cap_e_new_max_rule(m,sto,co,num):
return m.sto_cap_e_new[sto,co,num] <= \
m.sto_cap_build[sto,co,num] * storage.loc[sto,co,num]['cap-new-max-e']
m.sto_cap_e_new_max = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_e_new_max_rule,
doc='Energy Capacity:: limit max new capacity of storage')
def sto_cap_e_new_min_rule(m,sto,co,num):
return m.sto_cap_e_new[sto,co,num] >= \
m.sto_cap_build[sto,co,num] * storage.loc[sto,co,num]['cap-new-min-e']
m.sto_cap_e_new_min = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_e_new_min_rule,
doc='Energy Capacity:: limit min new capacity of storage')
def sto_cap_p_abs_rule(m,sto,co,num):
return m.sto_cap_p[sto,co,num] == \
m.sto_cap_p_new[sto,co,num] + storage.loc[sto,co,num]['cap-installed-p']
m.sto_cap_p_abs = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_p_abs_rule,
doc='Power Capacity: capacity = cap_new + cap_installed')
def sto_cap_p_new_max_rule(m,sto,co,num):
return m.sto_cap_p_new[sto,co,num] <= \
m.sto_cap_build[sto,co,num] * storage.loc[sto,co,num]['cap-new-max-p']
m.sto_cap_p_new_max = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_p_new_max_rule,
doc='Power Capacity:: limit max new capacity of storage')
def sto_cap_p_new_min_rule(m,sto,co,num):
return m.sto_cap_p_new[sto,co,num] >= \
m.sto_cap_build[sto,co,num] * storage.loc[sto,co,num]['cap-new-min-p']
m.sto_cap_p_new_min = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_p_new_min_rule,
doc='Power Capacity:: limit min new capacity of storage')
def sto_cap_p_c_relation_rule(m,sto,co,num):
return m.sto_cap_p[sto,co,num] <= \
m.sto_cap_e[sto,co,num] * storage.loc[sto,co,num]['max-p-e-ratio']
m.sto_cap_p_c_relation = pyen.Constraint(
m.sto_tuples,
rule=sto_cap_p_c_relation_rule,
doc='max ratio between power and energy capacity of storage, if not independent')
#in-out
def sto_p_in_max_rule(m,sto,co,num,t):
return m.sto_p_in[sto,co,num,t] <= \
m.sto_cap_p[sto,co,num]
m.sto_p_in_max = pyen.Constraint(
m.sto_tuples, m.t,
rule=sto_p_in_max_rule,
doc='max charge power')
def sto_p_out_max_rule(m,sto,co,num,t):
return m.sto_p_out[sto,co,num,t] <= \
m.sto_cap_p[sto,co,num]
m.sto_p_out_max = pyen.Constraint(
m.sto_tuples, m.t,
rule=sto_p_out_max_rule,
doc='max discharge power')
if mip_equations.loc['Storage In-Out']['Active'] == 'yes':
def sto_p_in_not_out_rule(m,sto,co,num,t):
return m.sto_p_in[sto,co,num,t] <= \
m.sto_charge[co,t]*\
(storage.loc[sto,co,num]['cap-new-max-p']+storage.loc[sto,co,num]['cap-installed-p'])
m.sto_p_in_not_out = pyen.Constraint(
m.sto_tuples, m.t,
rule = sto_p_in_not_out_rule,
doc='only charge, when not discharging')
def sto_p_out_not_in_rule(m,sto,co,num,t):
return m.sto_p_out[sto,co,num,t] <= \
(1-m.sto_charge[co,t])*\
(storage.loc[sto,co,num]['cap-new-max-p']+storage.loc[sto,co,num]['cap-installed-p'])
m.sto_p_out_not_in = pyen.Constraint(
m.sto_tuples, m.t,
rule = sto_p_out_not_in_rule,
doc='only discharge, when not charging')
#Energy Content
def sto_e_cont_def_rule(m,sto,co,num,t):
return m.sto_e_cont[sto,co,num,t] == \
m.sto_e_cont[sto,co,num,t-1] \
* (1 - storage.loc[sto,co,num]['self-discharge'] * p2e)\
+ m.sto_p_in[sto,co,num,t] * storage.loc[sto,co,num]['eff-in'] *p2e\
- m.sto_p_out[sto,co,num,t] / storage.loc[sto,co,num]['eff-out'] * p2e
m.sto_e_cont_def = pyen.Constraint(
m.sto_tuples, m.t,
rule=sto_e_cont_def_rule,
doc='Energy Content of Storage: E(t) = E(t-1)*(1 - self_disch) + P_in*eff_in - P_out/eff_out')
def sto_e_cont_max_rule(m,sto,co,num,t):
return m.sto_e_cont[sto,co,num,t] <= m.sto_cap_e[sto,co,num] * storage.loc[sto,co,num]['DOD']
m.sto_e_cont_max = pyen.Constraint(
m.sto_tuples, m.t,
rule=sto_e_cont_max_rule,
doc='Energy Content of Storage lower than energy capacity of storage')
# CHARGE CYCLES
def sto_max_cycle_rule(m,sto,co,num):
return sum( m.sto_p_in[sto,co,num,t] * p2e for t in m.t) <=\
m.sto_cap_e[sto,co,num] \
* storage.loc[sto,co,num]['DOD'] * storage.loc[sto,co,num]['cycles-max']\
* year_factor/storage.loc[sto,co,num]['lifetime']
m.sto_max_cycle= pyen.Constraint(
m.sto_tuples,
rule=sto_max_cycle_rule,
doc='sum(P_in*tb) <= cap_E *DOD* Z_max (similar to Z*cap<=Z_max*cap)')
"""GRID"""
def ext_p_in_max_rule(m, co, t):
return m.ext_p_in[co,t] <= ext_co.loc[co]['import-max']