-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmicrogrid_system.py
1796 lines (1368 loc) · 66.9 KB
/
microgrid_system.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Class structure for microgrid system and its components.
File contents:
Classes:
Component
PV (inherits from Component)
MRE (inherits from Component)
Tidal (inherits from MRE)
Wave (inherits from MRE)
Battery (inherits from Component)
SimpleLiIonBattery (inherits from Battery)
Generator (inherits from Component)
GeneratorGroup (inherits from Component)
FuelTank (inherits from Component)
MicrogridSystem
SimpleMicrogridSystem (inherits from MicrogridSystem)
"""
from copy import deepcopy
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
import warnings
from validation import validate_all_parameters, log_error
# Microgrid components
class Component:
"""
Component class: solar module, battery, generator, fuel_tank
Parameters
----------
category: type of equipment, choices are:
['pv', 'battery', 'generator', 'fuel_tank']
existing: whether or not the component already exists on site
Methods
----------
get_category: returns the category
calc_capital_cost(): calculate capital costs
calc_om_cost(): calculate om costs
"""
category = None
existing = False
capital_cost = None
om_cost = None
def __repr__(self):
pass
def get_category(self):
return self.category
def calc_capital_cost(self, *args):
pass
def calc_om_cost(self, *args):
pass
def copy_and_mod(self, param_name, param_value):
self_copy = deepcopy(self)
self_copy.__setattr__(param_name, param_value)
return self_copy
class PV(Component):
"""
PV system
Parameters
----------
category: equipment type, set to 'pv'
existing: whether or not the component already exists on site
capacity: total_capacity in kW
tilt: panel tilt in degrees
azimuth: panel azimuth in degrees
module_area: individual module_area in in^2
module_capacity: individual module_capacity in kW
spacing_buffer: buffer to account for panel spacing in area calculation
pv_racking: mount type of panels
(options: [roof, ground, carport])
pv_tracking: type of tracking
(options: [fixed, single_axis])
advanced_inputs: panel advanced inputs (currently does nothing)
Methods
----------
calc_area: calculates the total area of the array in ft^2
get_capacity: returns the total array capacity in kW
calc_capital_cost: calculate capital costs
calc_om_cost: calculate om costs
"""
def __init__(self, existing, pv_capacity, tilt, azimuth, module_capacity, module_area,
spacing_buffer, pv_tracking, pv_racking, advanced_inputs={}, validate=True):
# Assign parameters
self.category = 'pv'
self.existing = existing
self.capacity = pv_capacity # in kW
self.tilt = tilt
self.azimuth = azimuth
self.module_area = module_area # in in^2
self.module_capacity = module_capacity # in kW
self.spacing_buffer = spacing_buffer
self.pv_tracking = pv_tracking
self.pv_racking = pv_racking
self.advanced_inputs = advanced_inputs
if validate:
# List of initialized parameters to validate
args_dict = {'existing': existing, 'pv_capacity': pv_capacity,
'tilt': tilt, 'azimuth': azimuth,
'module_capacity': module_capacity,
'module_area_in2': module_area,
'spacing_buffer': spacing_buffer,
'pv_tracking': pv_tracking, 'pv_racking': pv_racking}
# Validate input parameters
validate_all_parameters(args_dict)
def __repr__(self):
return 'PV: Capacity: {:.1f}kW'.format(self.capacity)
def calc_area(self):
""" Calculates the area of the array """
# Calculate total array area in ft^2
return self.capacity / self.module_capacity * \
self.module_area / 144 * self.spacing_buffer
def get_capacity(self):
return self.capacity
def calc_capital_cost(self, cost_df, existing_components):
""" Calculates cost of PV array """
# Adjust total pv_capacity to consider existing pv
if 'pv' in existing_components.keys():
adjusted_pv_capacity = max(
self.capacity - existing_components['pv'].capacity, 0)
else:
adjusted_pv_capacity = self.capacity
# Set cost to largest size in case pv exceeds max size on cost doc
pv_cost_per_w = cost_df.loc[(self.pv_racking + ';' + self.pv_tracking)].iloc[-1]
for col in cost_df:
if adjusted_pv_capacity <= col:
pv_cost_per_w = cost_df.loc[(self.pv_racking + ';' + self.pv_tracking), col]
break
# If utility-scale roof or carport-mount, print user warning
if self.capacity > 5000 and self.pv_racking in ['roof', 'carport']:
print(f'WARNING: A pv capacity of {self.capacity}kW does not make sense with '
f'{self.pv_racking} racking. It is recommended that you select '
f'ground-mounted racking.')
return adjusted_pv_capacity * 1000 * pv_cost_per_w
def calc_om_cost(self, cost_df, existing_components):
""" Calculates O&M costs of a PV array """
# Adjust total pv_capacity to consider existing pv
if 'pv' in existing_components.keys():
adjusted_pv_capacity = max(
self.capacity - existing_components['pv'].capacity, 0)
else:
adjusted_pv_capacity = self.capacity
pv_om_cost_per_kw = cost_df['PV_{};{}'.format(
self.pv_racking, self.pv_tracking)].values[1]
return adjusted_pv_capacity * pv_om_cost_per_kw
class MRE(Component):
"""
Marine Renewable Energy system
Parameters
----------
category: equipment type, set to 'mre'
existing: whether or not the component already exists on site
num_generators: the number of marine energy generators/turbines
mre_capacity: total_capacity in kW
generator_type: type of marine energy generator: 'tidal' or 'wave'
generator_capacity: the capacity per generator/turbine, in kW
Methods
----------
get_capacity: returns the total array capacity in kW
"""
def __init__(self, existing, mre_capacity, generator_type,
generator_capacity):
# Assign parameters
self.category = 'mre'
self.existing = existing
self.capacity = mre_capacity # in kW
self.generator_type = generator_type
self.generator_capacity = generator_capacity # in kW
self.num_generators = int(mre_capacity / generator_capacity)
def get_capacity(self):
return self.capacity
class Tidal(MRE):
"""
Tidal Generator Array
Parameters
----------
all parameters from parent class MRE
generator_type: type of marine energy generator: 'tidal'
Methods
----------
all methods from parent class MRE
"""
def __init__(self, existing, mre_capacity, generator_capacity, device_name, validate=True):
super().__init__(existing, mre_capacity, 'tidal', generator_capacity)
if validate:
# List of initialized parameters to validate
args_dict = {'existing': existing, 'mre_capacity': mre_capacity,
'tidal_turbine_rated_power': generator_capacity}
# Validate input parameters
validate_all_parameters(args_dict)
self.device_name = device_name
def __repr__(self):
return 'Tidal: Capacity: {:.1f}kW'.format(self.capacity)
def calc_capital_cost(self, cost_df, existing_components):
""" Calculates cost of Tidal array """
# Adjust total mre_capacity to consider existing mre
# TODO - update this to consider # of turbines instead of capacity
if 'mre' in existing_components.keys() and \
existing_components['mre'].generator_type == 'tidal':
adjusted_mre_num = max(
self.num_generators - existing_components['mre'].num_generators, 0)
else:
adjusted_mre_num = self.num_generators
# Set costs using loc to find the correct device
tidal_cost_per_turbine = cost_df.loc[self.device_name, 'Cost (USD)']
# Set costs
# tidal_cost_per_turbine = cost_df.reset_index().iloc[0]['Cost (USD)']
return adjusted_mre_num * tidal_cost_per_turbine
def calc_om_cost(self, cost_df, existing_components):
""" Calculates O&M costs of a Tidal array """
# Adjust total mre_capacity to consider existing mre
if 'mre' in existing_components.keys() and \
existing_components['mre'].generator_type == 'tidal':
adjusted_mre_cap = max(
self.capacity - existing_components['mre'].capacity, 0)
else:
adjusted_mre_cap = self.capacity
# Set O&M cost
tidal_om_cost_per_kw = cost_df['Tidal'].values[1]
return adjusted_mre_cap * tidal_om_cost_per_kw
class Wave(MRE):
"""
Wave Generator Array
Parameters
----------
all parameters from parent class MRE
generator_type: type of marine energy generator: 'wave'
generator_capacity: the capacity per generator, in kW
wave_inputs: TBD
Methods
----------
all methods from parent class MRE
"""
def __init__(self, existing, mre_capacity, generator_capacity,
wave_inputs, validate=True):
super().__init__(existing, mre_capacity, 'wave',
generator_capacity)
# Assign parameters
self.wave_inputs = wave_inputs
# TODO
if validate:
# List of initialized parameters to validate
args_dict = {'existing': existing, 'mre_capacity': mre_capacity,
'generator_capacity': generator_capacity,
'wave_inputs': wave_inputs}
# Validate input parameters
validate_all_parameters(args_dict)
def __repr__(self):
return 'Wave: Capacity: {:.1f}kW'.format(self.capacity)
def calc_capital_cost(self, cost_df, existing_components):
""" Calculates cost of Wave array """
# Adjust total mre_capacity to consider existing mre
if 'mre' in existing_components.keys() and \
existing_components['mre'].generator_type == 'wave':
adjusted_mre_capacity = max(
self.capacity - existing_components['mre'].capacity, 0)
else:
adjusted_mre_capacity = self.capacity
# Set costs
# TODO
return adjusted_mre_capacity
def calc_om_cost(self, cost_df, existing_components):
""" Calculates O&M costs of a Wave array """
# Adjust total mre_capacity to consider existing pv
if 'mre' in existing_components.keys() and \
existing_components['mre'].generator_type == 'wave':
adjusted_mre_capacity = max(
self.capacity - existing_components['mre'].capacity, 0)
else:
adjusted_mre_capacity = self.capacity
# Set O&M cost
# TODO
return adjusted_mre_capacity
class Battery(Component):
"""
General battery class
Parameters
----------
category: equipment type, set to 'battery'
existing: whether or not the component already exists on site
power: battery power in kW
batt_capacity: battery capacity in kW
initial_soc: initial state of charge
default = 1
one_way_battery_efficiency: one way battery efficiency
default = 0.9
one_way_inverter_efficiency: one way inverter efficiency
default = 0.95
soc_upper_limit: state of charge upper limit
default = 1
soc_lower_limit: state of charge lower limit
default = 0.1
Methods
----------
reset_state: resets the state of the battery to initial conditions
update_state: only defined in child classes
get_state: returns current state of charge, voltage, number of cycles, and time since
last used
get_capacity_power: returns the battery capacity and power
calc_capital_cost: calculate capital costs
calc_om_cost: calculate om costs
Calculated Attributes
----------
soc: battery state of charge, initially set as initial_soc
cycles: number of used cycles, initially set at 0, currently unused
voltage: battery voltage, currently unused
time_since_last_used: amount of time elapsed since the battery was last charged or
discharged, currently unused
"""
def __init__(self, existing, power, batt_capacity, initial_soc=1,
one_way_battery_efficiency=0.9,
one_way_inverter_efficiency=0.95, soc_upper_limit=1,
soc_lower_limit=0.1, validate=True):
# Battery parameters
self.category = 'battery'
self.existing = existing
self.power = power # kW
self.batt_capacity = batt_capacity # kWh
self.initial_soc = initial_soc
self.one_way_battery_efficiency = one_way_battery_efficiency
self.one_way_inverter_efficiency = one_way_inverter_efficiency
self.soc_upper_limit = soc_upper_limit
self.soc_lower_limit = soc_lower_limit
# Initialize battery state
self.soc = deepcopy(self.initial_soc)
self.cycles = 0
self.voltage = 0
self.time_since_last_used = 0
if validate:
# List of initialized parameters to validate
args_dict = {
'existing': existing, 'power': power,
'batt_capacity': batt_capacity, 'initial_soc': initial_soc,
'one_way_battery_efficiency': one_way_battery_efficiency,
'one_way_inverter_efficiency': one_way_inverter_efficiency,
'soc_upper_limit': soc_upper_limit,
'soc_lower_limit': soc_lower_limit
}
# Validate input parameters
validate_all_parameters(args_dict)
def __repr__(self):
return 'Battery: Capacity: {:.1f}kWh, Power: {:.1f}kW'.format(
self.batt_capacity, self.power)
def reset_state(self):
""" Resets the state to initial conditions. This is useful since many simulations
share one system (and therefore battery) object.
"""
# Initialize battery state
self.soc = deepcopy(self.initial_soc)
self.cycles = 0
self.voltage = 0
self.time_since_last_used = 0
def update_state(self, *args):
pass
def get_state(self):
return self.soc, self.voltage, self.cycles, self.time_since_last_used
def get_capacity_power(self):
return self.batt_capacity, self.power
def calc_capital_cost(self, cost_df, existing_components):
""" Calculate battery system capital costs """
# Adjust total capacity and power to consider existing batteries
if 'batt' in existing_components.keys():
adjusted_batt_capacity = max(
self.batt_capacity - existing_components['batt'].batt_capacity, 0)
adjusted_batt_power = max(
self.power - existing_components['batt'].power, 0)
else:
adjusted_batt_capacity = self.batt_capacity
adjusted_batt_power = self.power
# Parse battery and inverter capital costs from costs dataframe
batt_cost_per_wh = cost_df['Battery System'].values[1]
inverter_cost_per_w = cost_df['Inverter'].values[1]
return adjusted_batt_capacity * 1000 * batt_cost_per_wh \
+ adjusted_batt_power * 1000 * inverter_cost_per_w
def calc_om_cost(self, cost_df, existing_components):
""" Calculate battery system O&M costs """
# Adjust total capacity and power to consider existing batteries
if 'batt' in existing_components.keys():
adjusted_batt_capacity = max(
self.batt_capacity - existing_components['batt'].batt_capacity, 0)
else:
adjusted_batt_capacity = self.batt_capacity
# Parse battery and inverter o&m costs from costs dataframe
batt_om_cost_per_kwh = cost_df['Battery'].values[1]
return adjusted_batt_capacity * batt_om_cost_per_kwh
class SimpleLiIonBattery(Battery):
"""
Models a simple lithium ion battery, where the battery discharges according to three
possible methods:
(1) at a constant rate every night, based on the available capacity
(2) at a dynamic rate every night based on remaining available
capacity
(3) up to the available capacity at all hours, day or night
Parameters
----------
all parameters from parent class Battery
Methods
----------
all methods from parent class Battery
update_state: charges or discharges the battery for a single time step based on net
load
Calculated Attributes
----------
charge_eff: battery charging efficiency
discharge_eff: battery discharging efficiency
"""
def __init__(self, existing, power, batt_capacity, initial_soc=1,
one_way_battery_efficiency=0.9,
one_way_inverter_efficiency=0.95, soc_upper_limit=1,
soc_lower_limit=0.1, validate=True):
super().__init__(existing, power, batt_capacity, initial_soc,
one_way_battery_efficiency,
one_way_inverter_efficiency, soc_upper_limit,
soc_lower_limit, validate)
# Set efficiencies
self.charge_eff = self.one_way_battery_efficiency \
* self.one_way_inverter_efficiency
self.discharge_eff = self.one_way_battery_efficiency \
* self.one_way_inverter_efficiency
def update_state(self, net_load, duration, dispatch_strategy, night_params=None):
"""
Charge or discharge the battery for a single time step.
Parameters
----------
net_load: Net load to be charged into battery (negative values) or discharged from
battery (positive values) (in kW)
duration: duration of timestep in seconds
dispatch_strategy: determines the battery dispatch strategy.
Options include:
night_const_batt (constant discharge at night)
night_dynamic_batt (updates the discharge rate based on remaining available
capacity)
available_capacity (discharged up to the available capacity)
night_params: dictionary of night params only used if dispatch_strategy is not
set to available_capacity with the following keys:
is_night: if it is currently nighttime, boolean
night_duration: length of current night in number of timesteps, if is_night is
false, it is 0
night_hours_left: remaining hours in night
soc_at_initial_hour_of_night: the initial state of charge during the first hour of
the night
"""
# Initialize delta power
delta_power = 0
# Spare capacity available for charging
spare_capacity = (self.soc_upper_limit - self.soc) * self.batt_capacity
# Available capacity for discharging
available_capacity = (self.soc - self.soc_lower_limit) \
* self.batt_capacity
# Determine if the battery is charged: if there's extra power and room in the battery
if net_load < 0 < spare_capacity:
# Amount of energy applied at terminals to fill battery
external_energy = spare_capacity/self.charge_eff
# Charging power is minimum of net load, battery power rating and available
# capacity divided by # hours per timestep
delta_power = -min([abs(net_load), self.power, external_energy/(duration/3600)])
# Update SOC
self.soc -= delta_power*duration/3600*self.charge_eff / self.batt_capacity
# Determine if the battery is discharged
elif net_load > 0 and available_capacity > 0:
# Amount of energy available to meet the load
external_energy = available_capacity*self.discharge_eff
# Discharging power is minimum of net load, battery power rating and available
# capacity divided by # hours per timestep
delta_power = min([abs(net_load), self.power, external_energy/(duration/3600)])
# If nighttime and using a night-based dispatch strategy, limit the discharge rate
if night_params and night_params['is_night']:
# Calculate the maximum nighttime discharge power for the whole night
if dispatch_strategy == 'night_const_batt':
max_nighttime_power = \
(night_params['soc_at_initial_hour_of_night'] - self.soc_lower_limit) \
* self.batt_capacity * self.discharge_eff / night_params['night_duration']
elif dispatch_strategy == 'night_dynamic_batt':
max_nighttime_power = \
(self.soc - self.soc_lower_limit) \
* self.batt_capacity * self.discharge_eff \
/ night_params['night_hours_left']
delta_power = min([delta_power, max_nighttime_power])
# Update SOC
self.soc -= delta_power * duration / 3600 / self.discharge_eff \
/ self.batt_capacity
# Check that the SOC is above or below limit, with a slight buffer to allow for
# rounding errors
if self.soc > self.soc_upper_limit+1E-5 or self.soc < self.soc_lower_limit-1E-5:
message = 'Battery SOC is above or below allowable limit.'
log_error(message)
raise Exception(message)
# Return power used to charge or discharge battery
return delta_power
class Generator(Component):
"""
Generator class
Parameters
----------
category: equipment type, set to 'generator'
existing: whether or not the component already exists on site
rated_power: generator rated power in kW
num_units: number of generator units
fuel_curve_model: gallons/hr at 1/4, 1/2, 3/4, and full load.
Expects a Pandas series with indices of ['1/4 Load (gal/hr)', '1/2 Load (gal/hr)',
'3/4 Load (gal/hr)', 'Full Load (gal/hr)']
ideal_minimum_load: fractional load level below which a warning is issued.
Currently unused.
Default = 0.3
loading_level_to_add_unit: fractional load level above which another generator unit is
added. Currently unused.
Default = 0.9
loading_level_to_remove_unit: fractional load level below which a generator unit is
removed (if possible). Currently unused.
Default = 0.3
capital_cost: cost for both parts and labor in USD
prime_generator: (boolean) indicates order of dispatch for multiple generators
Methods
----------
get_rated_power: returns the generator rated power in kW
get_fuel_curve_model: returns the fuel curve model coefficients
calculate_fuel_consumption: calculates dispatch and fuel consumed by generators
calc_capital_cost: calculate capital costs
calc_om_cost: calculate om costs
"""
def __init__(self, existing, rated_power, num_units, fuel_curve_model, capital_cost,
prime_generator=True, ideal_minimum_load=0.3, loading_level_to_add_unit=0.9,
loading_level_to_remove_unit=0.3, validate=True):
self.category = 'generator'
self.existing = existing
self.rated_power = rated_power # kW
self.num_units = num_units
self.prime_generator = prime_generator
self.fuel_curve_model = fuel_curve_model
self.capital_cost = capital_cost
self.ideal_minimum_load = ideal_minimum_load
self.loading_level_to_add_unit = loading_level_to_add_unit
self.loading_level_to_remove_unit = loading_level_to_remove_unit
if validate:
# List of initialized parameters to validate
args_dict = {
'existing': existing, 'rated_power': rated_power,
'num_units': num_units,
'fuel_curve_model': fuel_curve_model,
'capital_cost': capital_cost,
'prime_generator': prime_generator,
'ideal_minimum_load': ideal_minimum_load,
'loading_level_to_add_unit': loading_level_to_add_unit,
'loading_level_to_remove_unit': loading_level_to_remove_unit
}
# Validate input parameters
validate_all_parameters(args_dict)
def __repr__(self):
return 'Generator: Rated Power: {:.1f}kW, Number: {}'.format(
self.rated_power, self.num_units)
def get_rated_power(self):
return self.rated_power
def get_fuel_curve_model(self):
return self.get_fuel_curve_model
def calculate_fuel_consumption(self, gen_power, duration, validate=True):
"""
Calculates fuel consumed by generator, and also return number of hours at each load
bin which is used for the load duration calculation.
Note: the current implementation assumes that all generators are dispatched together
at the same loading level. This will have to be updated in the future.
Inputs:
gen_power: dataframe with one column: 'gen_power'
duration: time step length in seconds
Outputs:
load_duration_df: dataframe with columns [binned_load, num_hours]
total_fuel: total fuel consumed in L
"""
# Validate input parameters
if validate:
args_dict = {'gen_power': gen_power, 'duration': duration}
validate_all_parameters(args_dict)
# Create load bins
gen_power.columns = ['gen_power']
gen_power['binned_load'] = gen_power['gen_power'].apply(round)
grouped_load = gen_power.groupby('binned_load')['gen_power'].\
count().to_frame(name='num_timesteps').reset_index()
# Calculate the number of hours at each load bin
grouped_load['num_hours'] = grouped_load['num_timesteps'] * duration \
/ 3600
# Determine fuel consumption function
with warnings.catch_warnings():
warnings.simplefilter('ignore', np.RankWarning)
fuel_func = np.poly1d(np.polyfit([0, 0.25, 0.5, 0.75, 1],
[0,
self.fuel_curve_model['1/4 Load (gal/hr)'],
self.fuel_curve_model['1/2 Load (gal/hr)'],
self.fuel_curve_model['3/4 Load (gal/hr)'],
self.fuel_curve_model['Full Load (gal/hr)']],
10))
# Calculate fuel consumption for each bin in Gallons
grouped_load['fuel_used'] = grouped_load['binned_load'].apply(
lambda x: fuel_func(x/(self.rated_power*self.num_units)))
# Calculate total fuel consumption
total_fuel = (grouped_load['fuel_used']
* grouped_load['num_hours']).sum()
total_fuel = np.max([total_fuel, 0.])
return grouped_load, total_fuel
def calc_capital_cost(self, cost_df, existing_components):
""" Calculate generator capital costs """
if 'generator' in existing_components.keys():
return 0
else:
return self.capital_cost * self.num_units
def calc_om_cost(self, cost_df, existing_components):
""" Calculate generator O&M costs """
if 'generator' in existing_components.keys():
return 0
else:
# Parse generator o&m costs from costs dataframe
gen_om_per_kW_scalar = cost_df['Generator_scalar'].values[1]
gen_om_exp = cost_df['Generator_exp'].values[1]
return gen_om_per_kW_scalar * (self.rated_power * self.num_units)**gen_om_exp
class GeneratorGroup(Component):
"""
Generator Group class
Parameters
----------
category: equipment type, set to 'generator'
generator_list: a list of Generator objects
Methods
----------
calc_capital_cost: calculate capital costs
calc_om_cost: calculate om costs
"""
def __init__(self, generator_list, validate=True):
self.category = 'generator'
self.generator_list = generator_list
self.rated_power = np.sum([gen.rated_power * gen.num_units for gen in self.generator_list])
self.num_units = 1 # Used for results parsing to be consistent with Generator object
if validate:
# List of initialized parameters to validate
args_dict = {
'generator_list': generator_list
}
# Validate input parameters
validate_all_parameters(args_dict)
def __repr__(self):
return f'GeneratorGroup: {", ".join([gen.__repr__() for gen in self.generator_list])}'
def calc_capital_cost(self, cost_df, *args):
""" Calculate generator group capital costs """
return np.sum([gen.calc_capital_cost(cost_df, {}) for gen in self.generator_list])
def calc_om_cost(self, cost_df, *args):
""" Calculate generator O&M costs """
return np.sum([gen.calc_om_cost(cost_df, {}) for gen in self.generator_list])
class FuelTank(Component):
"""
Fuel Tank class
Parameters
----------
category: equipment type, set to 'fuel_tank'
existing: whether or not the component already exists on site
tank_size: size of fuel tank (gal)
num_units: number of fuel tanks
tank_cost: cost of an individual tank in USD
Methods
----------
calc_capital_cost: calculate capital costs
calc_om_cost: calculate the o&m costs
"""
def __init__(self, existing, tank_size, num_units, tank_cost,
validate=True):
self.category = 'fuel_tank'
self.existing = existing
self.tank_size = tank_size
self.num_units = num_units
self.tank_cost = tank_cost
if validate:
# List of initialized parameters to validate
args_dict = {'existing': existing, 'fuel_tank_size': tank_size,
'num_units': num_units, 'fuel_tank_cost': tank_cost}
# Validate input parameters
validate_all_parameters(args_dict)
def __repr__(self):
return 'Fuel Tank: Size: {:.1f}Gal, Number: {}'.format(
self.tank_size, self.num_units)
def calc_capital_cost(self, *args):
""" Calculate capital cost of fuel tank(s) """
return self.num_units * self.tank_cost
def calc_om_cost(self, *args):
return 0
# System class, contains components
class MicrogridSystem:
"""
Microgrid system containing multiple components.
Parameters
----------
name: unique system name
components: collection of Component objects
costs_usd: dictionary containing different costs in USD
capital_cost_usd: total captial costs in USD
annual_benefits_usd: dictionary of total annual benefits from the system in USD by re_type
pv_area_ft2: total pv array area in ft^2
fuel_used_gal: aggregated (mean, std, and worst-case) fuel used by system from
simulations in gallons
simple_payback_yr: system payback based on capital costs and annual benefits in years
pv_percent: aggregated (mean, std, and worst-case) percent of load met by pv across
all simulations
batt_percent: aggregated (mean, std, and worst-case) percent of load met by batteries
across all simulations
gen_percent: aggregated (mean, std, and worst-case) percent of load met by generators
across all simulations
generator_power_kW: aggregated (mean, std, and worst-case) required generator size
across all simulations
load_duration: Pandas dataframe containing load duration curve aggregated across all
simulations. Contains columns:
[load_bin, num_hours, num_hours_at_or_below]
simulations: dictionary to hold simulator objects
outputs: dictionary of outputs from all simulations
Methods
----------
add_component: adds a component to the system
get_components: returns the system components