-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewload.py
638 lines (581 loc) · 27.7 KB
/
newload.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
import copy
from helper_functions import *
import math
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt
import numpy as np
from operator import itemgetter
import pandas as pd
from template import Template
from themeclasses import *
class Newload(Template):
"""
This class will hold the page responsible for calculating and displaying the new load generated by zero-emissions
equipment.
"""
def __init__(self, parent, controller, bd):
Template.__init__(self, parent, controller, bd)
title = pagetitle(self.titleframe, 'New Load with Simulated ZE Equipment')
title.grid(row=0, column=0, sticky='nsew')
with open('UI_Text/Newload_Instructions.txt', 'r') as _f:
instructions = _f.read()
self.instructionslabel = instruction_label(self.instructionsframe, instructions)
self.instructionslabel.grid(row=0, column=0)
self.durabilitywarning = tk.StringVar()
self.durabilitywarning.set('')
self.calculated = False
self.durabilitywarninglabel = tk.Label(self.controlsframe, textvariable=self.durabilitywarning)
self.durabilitywarninglabel.grid(row=8, column=0, sticky='nsew ')
self.chargingmode = tk.StringVar()
self.chargingmode.set('Uncontrolled')
self.chargemodedropdown = tk.OptionMenu(self.controlsframe, self.chargingmode, 'Uncontrolled', 'Managed',
command=lambda _: self.showhidemanagedcharging())
self.chargemodedropdown.grid(row=0, column=0)
self.charglimitlabel = tk.Label(self.controlsframe,
text="When managing charging,\nEV charging can increase monthly\npeak load by this amount:")
self.charglimitlabel.grid(row=1, column=0)
self.charglimitlabel.grid_remove()
nonly = (self.register(numonly), '%S')
self.charginglimit = tk.DoubleVar()
self.charginglimit.set(0) # zero indicates that no limit will be applied
self.charginglimitinput = tk.Entry(self.controlsframe,
textvariable=self.charginglimit,
validate='key',
validatecommand=nonly)
self.charginglimitinput.grid(row=2, column=0)
self.charginglimitinput.grid_remove()
self.recalcbutton = tk.Button(self.controlsframe,
text='Re-calculate EV Charging',
command=lambda: self.calc_battery_charging(controller))
self.recalcbutton.grid(row=3, column=0, sticky='nsew')
self.allowbreakcharge = tk.BooleanVar()
self.allowbreakcharge.set(True)
self.allowbreakchargecheck = tk.Checkbutton(self.controlsframe, text='Allow charging during mid-shift breaks?',
variable=self.allowbreakcharge, onvalue=True, offvalue=False)
self.allowbreakchargecheck.grid(row=4, column=0)
self.plotselectorlabel = tk.Label(self.controlsframe, text='Select which new load profile to plot:')
self.plotselectorlabel.grid(row=5, column=0, sticky='nsew')
self.plottype = tk.StringVar()
self.plottype.set('Average')
self.plotselector = tk.OptionMenu(self.controlsframe, self.plottype, 'Average', 'Busy',
command=lambda _: self.plot_newload())
self.plotselector.grid(row=6, column=0, sticky='nsew')
self.plotpeakdaybutton = tk.Button(self.controlsframe,
text='Plot Peak Day Results',
command=lambda : self.plot_newload_peakday())
self.plotpeakdaybutton.grid(row=7, column=0, sticky='nsew')
self.ntt = 0
self.avgzeload = pd.DataFrame()
self.busyzeload = pd.DataFrame()
self.newload = pd.DataFrame()
self.newloadwarningstate = False
self.busyshiftphase = {}
self.avgshiftphase = {}
self.busyyear = pd.DataFrame()
self.avgyear = pd.DataFrame()
self.selectedspecs = {}
self.avgtechdict = {}
self.assignment = {}
self.baselinemonthmaxs = pd.DataFrame()
self.avgassignment = {}
self.busyassignment = {}
# Set up plotting canvas
self.plotwindow = tk.Frame(self.rightframe)
self.plotwindow.grid(row=0, column=1)
self.figure = plt.figure(num=3, figsize=(10, 5), dpi=100)
self.axes = self.figure.add_subplot(111)
self.chart_type = FigureCanvasTkAgg(self.figure, self.plotwindow)
self.toolbar = NavigationToolbar2Tk(self.chart_type, self.plotwindow)
self.toolbar.update()
self.chart_type._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
self.selected = {}
self.fuelandemissions = {}
def showhidemanagedcharging(self):
if self.chargingmode.get() == 'Managed':
self.charglimitlabel.grid()
self.charginglimitinput.grid()
elif self.chargingmode.get() == "Uncontrolled":
self.charglimitlabel.grid_remove()
self.charginglimitinput.grid_remove()
else:
print('Something went wrong showing/hiding managed charging options.')
def calc_battery_charging(self, controller):
# clear out previous model
self.newload = pd.DataFrame()
self.avgzeload = pd.DataFrame()
self.busyzeload = pd.DataFrame()
self.newload = pd.DataFrame()
self.newloadwarningstate = False
self.durabilitywarning.set('')
# Create schedule data frames
# transpose raw data and convert to dataframe
avgsched = pd.DataFrame(list(map(list, zip(*self.controller.frames['Schedule'].avgsheet.get_sheet_data())))[1:], )
avgsched.columns = list(map(list, zip(*self.controller.frames['Schedule'].avgsheet.get_sheet_data())))[0]
avgsched = avgsched.astype(int)
busysched = pd.DataFrame(list(map(list, zip(*self.controller.frames['Schedule'].busysheet.get_sheet_data())))[1:], )
busysched.columns = list(map(list, zip(*self.controller.frames['Schedule'].busysheet.get_sheet_data())))[0]
busysched = busysched.astype(int)
# Get selected technologies from ZE Equip page
self.selected = {key: value for key, value in self.controller.frames['Zeequip'].selected.items()
if value is not None} # TODO: handle the case where tech is selected but none are used
self.selectedspecs = {}
for tech in self.controller.frames['Zeequip'].tech:
if tech['Name'] in self.selected.values():
self.selectedspecs[tech['Name']] = tech
# build data frame to hold timeseries data base on baseline load input
if self.chargingmode.get() == "Managed":
self.avgzeload['Datetime'] = copy.deepcopy(controller.frames['Load'].data['Datetime'])
self.busyzeload['Datetime'] = copy.deepcopy(controller.frames['Load'].data['Datetime'])
elif self.chargingmode.get() == "Uncontrolled":
self.avgzeload['Datetime'] = copy.deepcopy(
controller.frames['Load'].data.loc[
[x for x in range(int(self.controller.parameters["UNMANAGED_DAYS_TO_SIMULATE"] /
self.controller.frames['Load'].dt.get() * 24))], 'Datetime'])
self.busyzeload['Datetime'] = copy.deepcopy(
controller.frames['Load'].data.loc[
[x for x in range(int(self.controller.parameters["UNMANAGED_DAYS_TO_SIMULATE"] /
self.controller.frames['Load'].dt.get() * 24))], 'Datetime'])
# Get monthly baseline load peaks to use for managed charging
self.baselinemonthmaxs = self.controller.frames['Load'].data.groupby(
self.controller.frames['Load'].data['Datetime'].dt.month).apply(max)
# fill in data frame with schedule info
ndays = int(self.avgzeload.shape[0]/(4*24))
# calculate grid charging power vs time
for key, value in self.selected.items():
if self.selectedspecs[value]['Power Supply'] == 'Grid':
avgload = [np.repeat(
x*(1-self.controller.parameters['SCHEDULE_FRAC_ON_BREAK']) *
self.selectedspecs[value]['Grid Specs']['Constant_Power'], 4)
for i, x in avgsched[key].items()]*ndays
self.avgzeload.loc[:, key] = [item for sublist in avgload for item in sublist]
busyload = [np.repeat(
x*(1-self.controller.parameters['SCHEDULE_FRAC_ON_BREAK']) *
self.selectedspecs[value]['Grid Specs']['Constant_Power'], 4)
for i, x in busysched[key].items()]*ndays
self.busyzeload.loc[:, key] = [item for sublist in busyload for item in sublist]
# Calculate aggregate load from grid-connected tech
if self.avgzeload.shape[1] == 0:
avggridload = np.zeros(self.avgzeload.shape[0])
else:
avggridload = [sum(
[self.avgzeload.loc[ts, col].sum()
for col in self.avgzeload
if col != 'Datetime'])
for ts in range(self.avgzeload.shape[0])]
if self.busyzeload.shape[1] == 0:
busygridload = np.zeros(self.busyzeload.shape[0])
else:
busygridload = [sum([self.busyzeload.loc[ts, col].sum() for col in self.busyzeload if col != 'Datetime'])
for ts in range(self.busyzeload.shape[0])]
# Repeat input schedule every day for a year
self.busyyear = pd.concat([busysched.loc[busysched.index.repeat(4)]] * ndays, ignore_index=True)
self.avgyear = pd.concat([avgsched.loc[avgsched.index.repeat(4)]] * ndays, ignore_index=True)
# Calculate shift phases
self.busyshiftphase = {key: [0 for _ in range(self.busyyear.shape[0])] for key, value in self.selected.items()}
self.avgshiftphase = {key: [0 for _ in range(self.avgyear.shape[0])] for key, value in self.selected.items()}
counter = 0
for key, value in self.selected.items():
for ts in range(self.busyyear.shape[0]): # iterate the shift phase every time two hours on-shift have passed
if self.busyyear[key][ts] != 0:
self.busyshiftphase[key][ts] = math.floor(
counter / (self.controller.parameters['SCHEDULE_SHIFT_LENGTH'] /
self.controller.frames['Load'].dt.get() *
self.controller.parameters['SCHEDULE_FRAC_ON_BREAK'])) + 1
counter = (counter + 1) % \
(self.controller.parameters['SCHEDULE_SHIFT_LENGTH'] /
self.controller.frames['Load'].dt.get())
else:
self.busyshiftphase[key][ts] = 0
for key, value in self.selected.items():
for ts in range(self.avgyear.shape[0]): # iterate the shift phase every time two hours on-shift have passed
if self.avgyear[key][ts] != 0:
self.avgshiftphase[key][ts] = math.floor(
counter / (self.controller.parameters['SCHEDULE_SHIFT_LENGTH'] /
self.controller.frames['Load'].dt.get() *
self.controller.parameters['SCHEDULE_FRAC_ON_BREAK'])) + 1
counter = (counter + 1) % \
(self.controller.parameters['SCHEDULE_SHIFT_LENGTH'] /
self.controller.frames['Load'].dt.get())
else:
self.avgshiftphase[key][ts] = 0
# Produce dict of all battery equipment(individual pieces)
self.avgtechdict = {}
counter = 0
for key, value in self.selectedspecs.items():
if value['Power Supply'] == 'Battery':
for n in range(max(
max(self.avgyear[value['Equipment Type']]),
max(self.busyyear[value['Equipment Type']]))):
self.avgtechdict[key + ' ' + str(n+1)] = \
{'shift': (counter % int(1/self.controller.parameters['SCHEDULE_FRAC_ON_BREAK']))+1,
'type': key,
'tech': value,
'number': n}
counter += 1
# Calculate when assignment occurs - unique to equipment types and avg vs busy schedules
self.avgassignment = {}
for key, value in self.selected.items():
self.avgassignment[key] = []
for ts in range(self.avgzeload.shape[0]):
if ts == 0:
self.avgassignment[key].append(True) # always trigger assignment in the first time step
# Also trigger assignment when number in operation changes
elif self.avgyear[key][ts-1] != self.avgyear[key][ts]:
self.avgassignment[key].append(True)
else:
self.avgassignment[key].append(False)
self.busyassignment = {}
for key, value in self.selected.items():
self.busyassignment[key] = []
for ts in range(self.avgzeload.shape[0]):
if ts == 0:
self.busyassignment[key].append(True) # always trigger assignment in the first time step
elif self.avgyear[key][ts - 1] != self.avgyear[key][
ts]: # Also trigger assignment when number in operation changes
self.busyassignment[key].append(True)
else:
self.busyassignment[key].append(False)
# Initialize all storage variables
for equip_type, value in self.selected.items():
if self.selectedspecs[value]['Power Supply'] == 'Battery':
self.avgzeload[equip_type] = 0
self.busyzeload[equip_type] = 0
# Calculate Battery Charging
for ts in range(self.avgzeload.shape[0]):
if ts == 0:
# Get starting durability
avgdurability = {}
for key, value in self.avgtechdict.items():
avgdurability[key] = copy.deepcopy(
self.selectedspecs[value['type']]['Battery Specs']['Durability (hrs)'])
avgassignment = self.assignevs(ts, avgdurability, self.avgassignment, 'no previous assignment', 'avg')
# Get whether the tech is charging, in use, or inactive
avgstatus = self.evstatus(avgdurability, avgassignment)
# Generate a request for power
avgrequest = self.chargingrequest(avgstatus, avgdurability, ts, self.avgshiftphase)
avgtimestepcharging = self.scheduletimestep(ts, avgrequest, avggridload)
avgendingdurability = self.incrementdurability(avgdurability, avgtimestepcharging, avgstatus)
self.avg_save_charging_power(avgtimestepcharging, ts)
busydurability = {}
for key, value in self.avgtechdict.items():
busydurability[key] = copy.deepcopy(
self.selectedspecs[value['type']]['Battery Specs']['Durability (hrs)'])
busyassignment = self.assignevs(ts, busydurability, self.busyassignment,
'no previous assignment', 'busy')
busystatus = self.evstatus(busydurability,
busyassignment) # Get whether the tech is charging, in use, or inactive
# Generate a request for power
busyrequest = self.chargingrequest(busystatus, busydurability, ts, self.busyshiftphase)
busytimestepcharging = self.scheduletimestep(ts, busyrequest, busygridload)
busyendingdurability = self.incrementdurability(busydurability, busytimestepcharging, busystatus)
self.busy_save_charging_power(busytimestepcharging, ts)
else:
avgdurability = avgendingdurability
avgassignment = self.assignevs(ts, avgdurability, self.avgassignment, avgassignment, 'avg')
avgstatus = self.evstatus(avgdurability, avgassignment) # Get whether the tech is charging, in use, or inactive
avgrequest = self.chargingrequest(avgstatus, avgdurability, ts, self.avgshiftphase) # Generate a request for power
avgtimestepcharging = self.scheduletimestep(ts, avgrequest, avggridload)
avgendingdurability = self.incrementdurability(avgdurability, avgtimestepcharging, avgstatus)
self.avg_save_charging_power(avgtimestepcharging, ts)
busydurability = busyendingdurability
busyassignment = self.assignevs(ts, busydurability, self.busyassignment, busyassignment, 'busy')
# Get whether the tech is charging, in use, or inactive
busystatus = self.evstatus(busydurability, busyassignment)
# Generate a request for power
busyrequest = self.chargingrequest(busystatus, busydurability, ts, self.busyshiftphase)
busytimestepcharging = self.scheduletimestep(ts, busyrequest, busygridload)
busyendingdurability = self.incrementdurability(busydurability, busytimestepcharging, busystatus)
self.busy_save_charging_power(busytimestepcharging, ts)
# Store results
self.newload['Datetime'] = copy.deepcopy(self.controller.frames['Load'].data['Datetime'])
self.newload['Baseline Electric Load (kW)'] = copy.deepcopy(
controller.frames['Load'].data['Baseline Electric Load (kW)'])
self.newload['Average Day New Load'] = copy.deepcopy(
controller.frames['Load'].data['Baseline Electric Load (kW)'])
self.newload['Busy Day New Load'] = copy.deepcopy(
controller.frames['Load'].data['Baseline Electric Load (kW)'])
if self.chargingmode.get() == "Uncontrolled":
# tile results in to fill in full year
self.avgzeload = pd.concat(
[self.avgzeload]*int(366/self.controller.parameters["UNMANAGED_DAYS_TO_SIMULATE"]))
self.avgzeload = self.avgzeload.set_index(np.arange(0, (self.avgzeload.shape[0]), 1))
self.avgzeload = self.avgzeload.drop(
np.arange(self.controller.frames['Load'].data.shape[0], self.avgzeload.shape[0], 1))
self.avgzeload['Datetime'] = copy.deepcopy(self.controller.frames['Load'].data['Datetime'])
self.busyzeload = pd.concat([self.busyzeload] *
int(366 / self.controller.parameters["UNMANAGED_DAYS_TO_SIMULATE"]))
self.busyzeload = self.busyzeload.set_index(np.arange(0, (self.busyzeload.shape[0]), 1))
self.busyzeload = self.busyzeload.drop(
np.arange(self.controller.frames['Load'].data.shape[0], self.busyzeload.shape[0], 1))
self.busyzeload['Datetime'] = copy.deepcopy(self.controller.frames['Load'].data['Datetime'])
# put avg and busy ze loads into newload
for ze in self.avgzeload:
if ze != 'Datetime':
self.newload['Average Day New Load'] = self.newload['Average Day New Load'] + self.avgzeload[ze]
for ze in self.busyzeload:
if ze != 'Datetime':
self.newload['Busy Day New Load'] = self.newload['Busy Day New Load'] + self.busyzeload[ze]
self.plot_newload()
self.update_warning()
self.calculated = True
self.calcfuelandemissions()
def avg_save_charging_power(self, avgtimestepcharging, ts):
for equip_type in self.selected.keys():
for key, value in self.avgtechdict.items():
if value['tech']['Equipment Type'] == equip_type:
self.avgzeload.loc[ts, equip_type] += avgtimestepcharging[key]
def busy_save_charging_power(self, busytimestepcharging, ts):
for equip_type in self.selected.keys():
for key, value in self.avgtechdict.items():
if value['tech']['Equipment Type'] == equip_type:
self.busyzeload.loc[ts, equip_type] += busytimestepcharging[key]
def assignevs(self, ts, durability, assignmenttrigger, previous_assignment, busyvavg):
"""
When an assignment is triggered, select which EVs will be needed in use and which are available for charging
"""
assignments = {}
for equiptype in self.selected.keys():
if not assignmenttrigger[equiptype][ts]: # only reassign when prompted
for key, value in self.avgtechdict.items():
if value['tech']['Equipment Type'] == equiptype:
assignments[key] = previous_assignment[key]
else:
# Get number of equipment requested
if busyvavg == 'avg':
n_needed = self.avgyear[equiptype][ts]
else:
n_needed = self.busyyear[equiptype][ts]
# pick the n_needed with the highest durability
for selected_key in dict(sorted(durability.items(), key=itemgetter(1), reverse=True)[:n_needed]).keys():
assignments[selected_key] = True
for unselected_key in dict(sorted(durability.items(), key=itemgetter(1), reverse=True)[n_needed:]).keys():
assignments[unselected_key] = False
return assignments
def incrementdurability(self, durability, timestepcharging, status):
"""
Return a dictionary mapping the equipment type/shift to its timestep-ending durability
including changes due to being in operation and charging
"""
endingdurability = {}
for key, value in self.avgtechdict.items():
if status[key] == 'charging':
endingdurability[key] = durability[key] + (timestepcharging[key] * self.controller.frames['Load'].dt.get() *
value['tech']['Battery Specs']['Durability (hrs)'] /
(value['tech']['Battery Specs']['Charging Time'] *
value['tech']['Battery Specs']['Charging Power (kW)']))
endingdurability[key] = min(value['tech']['Battery Specs']['Durability (hrs)'], endingdurability[key])
elif status[key] == 'inuse':
endingdurability[key] = durability[key] - self.controller.frames['Load'].dt.get()
if endingdurability[key] < 0:
self.durabilitywarning.set(
'WARNING: Some battery equipment\nare shown to run out of\nstored energy during\noperation')
endingdurability[key] = max(0, endingdurability[key])
else:
endingdurability[key] = durability[key]
return endingdurability
def scheduletimestep(self, ts, request, gridload):
"""
Accepts a power request from each Battery equipment type/shift
Allocates available power proportional to request
Returns charging power for each Battery equipment type/shift
"""
if self.chargingmode.get() == 'Uncontrolled': # handle the case where no limit is set
return request
power = {}
# Will request violate maximum?
nonchargingload = self.controller.frames['Load'].data['Baseline Electric Load (kW)'][ts] + gridload[ts]
requestedchargingload = 0
for key, value in request.items():
requestedchargingload += value
monthlymaxsiteload = self.baselinemonthmaxs.loc[
self.controller.frames['Load'].data['Datetime'][ts].month,
'Baseline Electric Load (kW)'] + self.charginglimit.get()
if requestedchargingload == 0:
return request
if nonchargingload > monthlymaxsiteload: # If grid-connected equipment already consumes all power
for key, value in request.items():
power[key] = 0
return power
# Allocate available power to each EV proportionally
elif (nonchargingload + requestedchargingload) > monthlymaxsiteload:
feasiblefraction = 1 - ((nonchargingload + requestedchargingload) -
monthlymaxsiteload)/requestedchargingload
feasiblefraction = max(0, feasiblefraction)
for key, value in request.items():
power[key] = request[key]*feasiblefraction
return power
else: # Power is not limited
return request
def chargingrequest(self, statusdict, durability, ts, shiftphasedict):
"""
For each battery technology present, returns a dictionary mapping the equipment type/shift to its charging
power request
"""
requestdict = {}
for key, value in self.avgtechdict.items(): # for all individual pieces of equipment
if statusdict[key] == 'charging' or (value['shift'] ==
shiftphasedict[value['tech']['Equipment Type']][ts] and
self.allowbreakcharge.get()):
techmax = self.selectedspecs[value['type']]['Battery Specs']['Charging Power (kW)'] # Max charging power
# If the battery were to be filled in one time step from its current SOC, how much power would that take?
durmax = ((self.selectedspecs[value['type']]['Battery Specs']['Durability (hrs)'] - durability[key]) *
self.selectedspecs[value['type']]['Battery Specs']['Charging Time'] *
self.selectedspecs[value['type']]['Battery Specs']['Charging Power (kW)'] /
self.selectedspecs[value['type']]['Battery Specs']['Durability (hrs)']) / \
self.controller.frames['Load'].dt.get()
requestdict[key] = min(techmax, durmax)
else:
requestdict[key] = 0
return requestdict
def evstatus(self, durability, assignment):
"""
For each technology present, returns a dictionary mapping the equipment type/shift to its status
either "charging", "inuse" or "inactive"
"""
statusdict = {}
for key, value in self.avgtechdict.items(): # for all individual pieces of equipment
if assignment[key]:
statusdict[key] = 'inuse'
else:
if durability[key] == self.selectedspecs[value['type']]['Battery Specs']['Durability (hrs)']:
statusdict[key] = 'inactive'
else:
statusdict[key] = 'charging'
return statusdict
def plot_newload(self):
plt.figure(3)
plt.cla() # Clear the plotting window to allow for re-plotting.
if self.plottype.get() == "Average":
plt.step(x=self.controller.frames['Load'].data['Datetime'],
y=self.controller.frames['Load'].data['Baseline Electric Load (kW)'],
where='post',
color=theme['loadcolor'],
zorder=1)
bottom = copy.deepcopy(self.controller.frames['Load'].data['Baseline Electric Load (kW)'])
for column in self.avgzeload:
if column == 'Datetime':
pass
else:
try:
plt.fill_between(x=self.avgzeload['Datetime'],
y1=bottom,
y2=bottom + self.avgzeload[column],
step='post',
facecolor=theme['checolors'][column],
zorder=1,
label=column)
except KeyError:
plt.fill_between(x=self.avgzeload['Datetime'],
y1=bottom,
y2=bottom + self.avgzeload[column],
step='post',
zorder=1,
label=column)
bottom += self.avgzeload[column]
plt.title('Battery Charging and Grid Use Stacked on Baseline Load\n(Average Schedule)')
else:
plt.step(x=self.controller.frames['Load'].data['Datetime'],
y=self.controller.frames['Load'].data['Baseline Electric Load (kW)'],
where='post',
color=theme['loadcolor'],
zorder=1)
bottom = copy.deepcopy(self.controller.frames['Load'].data['Baseline Electric Load (kW)'])
for column in self.busyzeload:
if column == 'Datetime':
pass
else:
try:
plt.fill_between(x=self.busyzeload['Datetime'],
y1=bottom,
y2=bottom + self.busyzeload[column],
step='post',
facecolor=theme['checolors'][column],
zorder=1,
label=column)
except KeyError:
plt.fill_between(x=self.busyzeload['Datetime'],
y1=bottom,
y2=bottom + self.busyzeload[column],
step='post',
zorder=1,
label=column)
bottom += self.busyzeload[column]
plt.title('Battery Charging and Grid Use Stacked on Baseline Load\n(Busy Schedule)')
if self.controller.frames['Load'].loadlimit.get() > 0:
plt.hlines(self.controller.frames['Load'].loadlimit.get(),
xmin=min(self.controller.frames['Load'].data['Datetime']),
xmax=max(self.controller.frames['Load'].data['Datetime']), colors='r', zorder=2)
plt.ylabel('Electric Load (kW)')
plt.legend()
self.chart_type.draw()
def plot_newload_peakday(self):
plt.figure(3)
plt.cla() # Clear the plotting window to allow for re-plotting.
# Find new load peak days and plot only those
dailybusypeaks = self.newload['Busy Day New Load'].groupby(
self.newload['Datetime'].dt.date).apply(max)
peakdate = dailybusypeaks.index[dailybusypeaks == dailybusypeaks.max()].tolist()[0]
#get indexes for the peak date
peakdaymask = self.newload['Datetime'].dt.date == peakdate
plt.step(x=self.controller.frames['Load'].data.loc[peakdaymask, 'Datetime'],
y=self.controller.frames['Load'].data.loc[peakdaymask, 'Baseline Electric Load (kW)'],
where='post',
color=theme['loadcolor'],
zorder=1,
label='Baseline')
plt.step(x=self.newload.loc[peakdaymask, 'Datetime'], y=self.newload.loc[peakdaymask, 'Average Day New Load'],
where='post',
zorder=1,
label='Average Schedule')
plt.step(x=self.newload.loc[peakdaymask, 'Datetime'], y=self.newload.loc[peakdaymask, 'Busy Day New Load'],
where='post',
zorder=1,
label='Busy Schedule')
# bottom = copy.deepcopy(self.controller.frames['Load'].data['Baseline Electric Load (kW)'])
# for column in self.avgzeload:
# if column == 'Datetime':
# pass
# else:
# plt.fill_between(x=self.avgzeload['Datetime'],
# y1=bottom,
# y2=bottom + self.avgzeload[column],
# step='post',
# facecolor=theme['checolors'][column],
# zorder=1,
# label=column)
# bottom += self.avgzeload[column]
plt.title('Peak Load Day')
if self.controller.frames['Load'].loadlimit.get() > 0:
plt.hlines(self.controller.frames['Load'].loadlimit.get(),
xmin=min(self.controller.frames['Load'].data.loc[peakdaymask, 'Datetime']),
xmax=max(self.controller.frames['Load'].data.loc[peakdaymask, 'Datetime']), colors='r', zorder=2)
plt.ylabel('Electric Load (kW)')
plt.legend()
self.chart_type.draw()
def update_warning(self):
"""
Update the warning depending on whether or not the load limit is exceeded by the new load
"""
pass
def calcfuelandemissions(self):
"""Fuel and Emissions savings based on avg day"""
pass
self.fuelandemissions['Fuel (Gallons)'] = 0
self.fuelandemissions['NOx (g)'] = 0
self.fuelandemissions['PM2.5 (g)'] = 0
self.fuelandemissions['CO2 (kg)'] = 0
for column in self.avgzeload:
if column == "Datetime":
pass
else:
self.fuelandemissions['Fuel (Gallons)'] += \
sum(self.avgzeload[column]) / self.controller.parameters['DIESEL_KWH_PER_GALLON_EQ']
self.fuelandemissions['NOx (g)'] += \
self.controller.parameters["DIESEL_NOX_g_PER_GALLON"] * \
sum(self.avgzeload[column]) / self.controller.parameters['DIESEL_KWH_PER_GALLON_EQ']
self.fuelandemissions['PM2.5 (g)'] += \
self.controller.parameters["DIESEL_PM2.5_g_PER_GALLON"] * \
sum(self.avgzeload[column]) / self.controller.parameters['DIESEL_KWH_PER_GALLON_EQ']
self.fuelandemissions['CO2 (kg)'] += \
self.controller.parameters["DIESEL_CO2_kge_PER_GALLON"] * \
sum(self.avgzeload[column]) / self.controller.parameters['DIESEL_KWH_PER_GALLON_EQ']