-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrid.py
670 lines (513 loc) · 24.5 KB
/
grid.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
import datetime, sys
from math import inf
class GridComponent:
def __init__(self, id_: str, coordX: int, coordY: int):
self.id_: str = id_
self.coordX: int = coordX
self.coordY: int = coordY
self.currentKWH: int = 0
self.desiredKWH: int = 0
class Provider(GridComponent):
def __init__(self, id_: str, coordX: int, coordY: int, maxKWH: int):
super().__init__(id_, coordX, coordY)
self.maxKWH = maxKWH
def getSatisfaction(self) -> float:
"""Returns the satisfaction of this component in percent
Returns:
float: satisfaction of component in percent
"""
percent = 0
if self.maxKWH == 0:
percent = 100
else:
percent = (1 - self.currentKWH/self.maxKWH) * 100
return percent
class User(GridComponent):
def __init__(self, id_: str, coordX: int, coordY: int):
super().__init__(id_, coordX, coordY)
def getSatisfaction(self) -> float:
"""Returns the satisfaction of this component in percent
Returns:
float: satisfaction of component in percent
"""
percent = 0
if self.desiredKWH == 0:
percent = 100
else:
percent = self.currentKWH/self.desiredKWH * 100
return percent
class Storage(GridComponent):
def __init__(self, id_: str, coordX: int, coordY: int, maxKWH: int):
super().__init__(id_, coordX, coordY)
self.maxKWH = maxKWH
def getSatisfaction(self) -> float:
"""Returns the satisfaction of this component in percent
Returns:
float: satisfaction of component in percent
"""
percent = 0
if self.maxKWH == 0:
percent = 100
else:
percent = self.currentKWH/self.maxKWH * 100
return percent
class P2x(GridComponent):
def __init__(self, id_: str, coordX: int, coordY: int):
super().__init__(id_, coordX, coordY)
def getSatisfaction(self) -> float:
"""Returns the satisfaction of this component in percent
Returns:
float: satisfaction of component in percent
"""
percent = 0
if self.desiredKWH == 0:
percent = 100
else:
percent = self.currentKWH/self.desiredKWH * 100
return percent
class Grid:
def __init__(self, gridData: dict, scenario: dict, gridSize: int = 20, timestepSize: float = 1):
# mock simulation data of each component in the grid
self.scenario = scenario
# size (in px) of each cell in the grid
self.cellSize = 100
# size of the square grid
self.gridSize = gridSize
# TODO the farther two cells are apart from each other, the less energy will arive on consumption since energy
# is lost on the way in the form of heat
self.energyLossPerCell = 0.98
# timestepSize in seconds corresponds to 15 elapsed simulation minutes
self.timestepSize = timestepSize
# keep track of simulation day time
self.simulationDayTime = datetime.datetime(year=1, month=1, day=2, hour=0)
# if the equilibrium (in percent) is 100, it means that every component in the grid is perfectly satisfied.
# we keep accumulate the equilibrium with each step and average it over the number of steps in order to get
# a metric that tells us how good the energy distribution works at all times
self.accumulatedEquilibrium = 0
# keep track of how many steps have been made. use this counter to compute a running average equilibrium
self.stepCounter = 1
# cells that are set to true exist, the other ones don't
self.cells = []
for i in range(self.gridSize):
self.cells.append([False for j in range(self.gridSize)])
# keep track of which cells are occupied by a component in order to prevent overlaps
self.occupiedCells = []
for i in range(self.gridSize):
self.occupiedCells.append([False for j in range(self.gridSize)])
# grid components
self.providers = []
self.users = []
self.storages = []
self.p2xs = []
# distribution keeps track of which component ID consumes which other component ID
self.dependencyMap = {}
# verify and load gridData
for key in gridData:
if key == 'cellSize':
self.cellSize = gridData[key]
if key == 'gridCells':
gcs = gridData[key]
for gc in gcs:
for x in range(round(gc[0][0]), round(gc[1][0])+1):
for y in range(round(gc[0][1]), round(gc[1][1])+1):
if x >= self.gridSize or y >= self.gridSize:
print('could not add cell (%d, %d) as cell overflows the grid' % (x, y))
continue
self.cells[x][y] = True
if key == 'providers':
ps = gridData[key]
for p in ps:
if p['coordX'] >= self.gridSize or p['coordY'] >= self.gridSize:
print('could not add provider "%s" as cell coordinates overflow the grid' % p['displayName'])
continue
if self.occupiedCells[p['coordX']][p['coordY']]:
print('could not add provider "%s" as cell was already occupied' % p['displayName'])
continue
self.providers.append(
Provider(
id_=p['id'],
coordX=p['coordX'],
coordY=p['coordY'],
maxKWH=p['maxKWH']
)
)
self.occupiedCells[p['coordX']][p['coordY']] = True
if key == 'users':
us = gridData[key]
for u in us:
if u['coordX'] >= self.gridSize or u['coordY'] >= self.gridSize:
print('could not add user "%s" as cell coordinates overflow the grid' % u['displayName'])
continue
if self.occupiedCells[u['coordX']][u['coordY']]:
print('could not add user %s as cell was already occupied' % u['displayName'])
continue
self.users.append(
User(
id_=u['id'],
coordX=u['coordX'],
coordY=u['coordY']
)
)
self.occupiedCells[u['coordX']][u['coordY']] = True
if key == 'storages':
ss = gridData[key]
for s in ss:
if s['coordX'] >= self.gridSize or s['coordY'] >= self.gridSize:
print('could not add storage "%s" as cell coordinates overflow the grid' % s['displayName'])
continue
if self.occupiedCells[s['coordX']][s['coordY']]:
print('could not add storage %s as cell was already occupied' % s['displayName'])
continue
self.storages.append(
Storage(
id_=s['id'],
coordX=s['coordX'],
coordY=s['coordY'],
maxKWH=s['maxKWH']
)
)
self.occupiedCells[s['coordX']][s['coordY']] = True
if key == 'p2xs':
ps = gridData[key]
for p in ps:
if p['coordX'] >= self.gridSize or p['coordY'] >= self.gridSize:
print('could not add p2x "%s" as cell coordinates overflow the grid' % p['displayName'])
continue
if self.occupiedCells[p['coordX']][p['coordY']]:
print('could not add p2x %s as cell was already occupied' % p['displayName'])
continue
self.p2xs.append(
P2x(
id_=p['id'],
coordX=p['coordX'],
coordY=p['coordY']
)
)
self.occupiedCells[p['coordX']][p['coordY']] = True
# load scenario data
self.updateScenario()
self.resetDepencencyMap()
def resetDepencencyMap(self) -> None:
"""Resets the dependency map (purple lines in the simulation) of each component."""
self.dependencyMap = {}
for p in self.providers:
self.dependencyMap[p.id_] = []
for u in self.users:
self.dependencyMap[u.id_] = []
for s in self.storages:
self.dependencyMap[s.id_] = []
for p in self.p2xs:
self.dependencyMap[p.id_] = []
def updateScenario(self) -> None:
"""Updates currentKWH/desiredKWHs for each component in the grid."""
# interpolate between two scenario timestamps for each timestepsize that fits between those two timestamps
currentMinute = self.simulationDayTime.strftime("%M")
currentHour = self.simulationDayTime.strftime("%H:00")
previousHour = (self.simulationDayTime - datetime.timedelta(hours=1)).strftime("%H:00")
factorB = (int(currentMinute)/60)
factorA = (1-factorB)
if currentHour in self.scenario:
for key in self.scenario[currentHour]:
if key == 'providerKWHs':
for componentID in self.scenario[currentHour][key]:
for p in self.providers:
if p.id_ == componentID:
# the scenario dictates how much kWh the provider generates at which timestep.
# there is, however, a maximum that a provider can generate, so if the current kWh
# is not consumed, then the provider won't be able to generate more even if the
# scenario would have dictated that to be the case. in the real world, such a
# generator would be put to stop
energyState = factorA*self.scenario[previousHour][key][componentID] + \
factorB*self.scenario[currentHour][key][componentID]
if p.currentKWH + energyState < p.maxKWH:
p.currentKWH += energyState
else:
p.currentKWH = p.maxKWH
if key == 'userKWHs':
for componentID in self.scenario[currentHour][key]:
for u in self.users:
if u.id_ == componentID:
# the users energy needs are strictly timespecific
energyState = factorA*self.scenario[previousHour][key][componentID] + \
factorB*self.scenario[currentHour][key][componentID]
u.desiredKWH = energyState
u.currentKWH = 0
if key == 'p2xKWHs':
for componentID in self.scenario[currentHour][key]:
for p in self.p2xs:
if p.id_ == componentID:
# the p2x energy needs are strictly timespecific
energyState = factorA*self.scenario[previousHour][key][componentID] + \
factorB*self.scenario[currentHour][key][componentID]
p.desiredKWH = energyState
p.currentKWH = 0
def updateEquilibrium(self) -> None:
"""Updates the running average equilibrium of the grid"""
compontentCount = 0
currentAccumulatedEquilibrium = 0
for p in self.providers:
if self.cells[p.coordX][p.coordY]:
currentAccumulatedEquilibrium += p.getSatisfaction()
compontentCount += 1
for u in self.users:
if self.cells[u.coordX][u.coordY]:
currentAccumulatedEquilibrium += u.getSatisfaction()
compontentCount += 1
for s in self.storages:
if self.cells[s.coordX][s.coordY]:
currentAccumulatedEquilibrium += s.getSatisfaction()
compontentCount += 1
for p in self.p2xs:
if self.cells[p.coordX][p.coordY]:
currentAccumulatedEquilibrium += p.getSatisfaction()
compontentCount += 1
currentAverageEquilibrium = currentAccumulatedEquilibrium/compontentCount
self.accumulatedEquilibrium += currentAverageEquilibrium
def resetEquilibrium(self) -> None:
self.accumulatedEquilibrium = 0
self.stepCounter = 1
def getRunningEquilibrium(self) -> float:
"""Returns the running equilibrium. It is a metric that can explain whether the grid distributes its energy optimally among all of its components."""
return self.accumulatedEquilibrium/self.stepCounter
def getCellSubgroup(self, x: int, y: int, visited=[]) -> list:
"""Given an active cells position, get all the other surrounding active cells that belong to the same group."""
group = []
if (x,y) in visited:
return group
if self.cells[x][y]:
group.append((x, y))
# check above
if y > 0:
for pos in self.getCellSubgroup(x, y-1, visited+group):
group.append(pos)
# check below
if y < len(self.cells[x]):
for pos in self.getCellSubgroup(x, y+1, visited+group):
group.append(pos)
# check left
if x > 0:
for pos in self.getCellSubgroup(x-1, y, visited+group):
group.append(pos)
# check right
if x < len(self.cells):
for pos in self.getCellSubgroup(x+1, y, visited+group):
group.append(pos)
return group
def getCellGroups(self) -> list:
"""Get all cell groups on the grid."""
groups = []
for y in range(len(self.cells)):
for x in range(len(self.cells[y])):
subGroup = self.getCellSubgroup(x, y)
if subGroup != []:
discardSubGroup = False
for pos in subGroup:
for group in groups:
for visitedPos in group:
if pos == visitedPos:
discardSubGroup = True
break
if discardSubGroup:
break
if discardSubGroup:
break
if not discardSubGroup:
groups.append(subGroup)
return groups
def getDirectNeighbours(self, x: int, y: int) -> list:
"""Get the direct active neighbour cells (up, down, left, right) of a given cell position."""
if not self.cells[x][y]:
return []
neighbours = []
# check above
if y > 0:
if self.cells[x][y-1]:
neighbours.append((x, y-1))
# check below
if y < self.gridSize:
if self.cells[x][y+1]:
neighbours.append((x, y+1))
# check left
if x > 0:
if self.cells[x-1][y]:
neighbours.append((x-1, y))
# check right
if x < self.gridSize:
if self.cells[x+1][y]:
neighbours.append((x+1, y))
return neighbours
def getCellDistance(self, srcX: int, srcY: int, trgX: int, trgY: int) -> int:
"""Returns the amount of active cells between the two given active cell's positions.
Args:
srcX(int): x position of source cell
srcY(int): y position of source cell
trgX(int): x position of target cell
trgY(int): y position of target cell
Returns:
int: grid distance (not euclidean) between source and target cell
"""
# dijkstra algortihm
# https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Algorithm
# step 1
unvisited = self.getCellSubgroup(srcX, srcY)
# step 2
d = {pos: inf for pos in unvisited}
d[(srcX, srcY)] = 0
currentNode = (srcX, srcY)
# step 3
while True:
neighbours = self.getDirectNeighbours(currentNode[0], currentNode[1])
for n in neighbours:
if n in unvisited:
if d[currentNode] + 1 < d[n]:
d[n] = d[currentNode] + 1
# step 4
unvisited.remove(currentNode)
# step 5
minTentativeDistance = inf
minPos = None
for pos in unvisited:
if d[pos] < minTentativeDistance:
minTentativeDistance = d[pos]
minPos = pos
if (trgX, trgY) not in unvisited or minTentativeDistance == inf:
return d[(trgX, trgY)]
# step 6
currentNode = minPos
def sortComponentsByDistanceTo(self, components: list, src: GridComponent) -> list:
"""Returns a sorted list of components by the distance to a given source component.
Args:
components(list): list of grid components
src(GridComponent): the source grid component
Returns:
list: the given components list sorted (ascending) by distance to the source component
"""
componentCopy = []
subGroup = self.getCellSubgroup(src.coordX, src.coordY)
for c in components:
if (c.coordX, c.coordY) not in subGroup:
continue
componentCopy.append(c)
componentCopy.sort(
key=lambda c: self.getCellDistance(src.coordX, src.coordY, c.coordX, c.coordY)
)
return componentCopy
def getPositionOf(self, componentID: str) -> tuple:
"""Get the position of the given component.
Args:
componentID(str): ID of the component
Returns:
tuple: position tuple (x, y) in grid space
"""
for p in self.providers:
if p.id_ == componentID:
return (p.coordX, p.coordY)
for u in self.users:
if u.id_ == componentID:
return (u.coordX, u.coordY)
for s in self.storages:
if s.id_ == componentID:
return (s.coordX, s.coordY)
for p in self.p2xs:
if p.id_ == componentID:
return (p.coordX, p.coordY)
print('could not find component with id (%s)' % componentID)
sys.exit(1)
def step(self) -> None:
"""Computes the energy flow for the next timestep."""
# map each component to the component it is going to consume in the next timestep
# prioritize: providers -> users -> storages -> p2x
self.resetDepencencyMap()
self.updateScenario()
# components can only consume components from the same subgroup
subGroups = self.getCellGroups()
for group in subGroups:
# step 1, users get to consume from providers, then storages
for u in self.users:
if (u.coordX, u.coordY) not in group:
continue
if not self.cells[u.coordX][u.coordY]:
continue
for p in self.sortComponentsByDistanceTo(self.providers, u):
if (p.coordX, p.coordY) not in group:
continue
if not self.cells[p.coordX][p.coordY]:
continue
# compute energy consumption
if p.currentKWH > 0 and u.currentKWH < u.desiredKWH:
neededKWH = u.desiredKWH - u.currentKWH
p.currentKWH -= neededKWH
if p.currentKWH < 0:
u.currentKWH -= p.currentKWH
p.currentKWH = 0
else:
u.currentKWH += neededKWH
# keep track of component dependency
if p.id_ not in self.dependencyMap[u.id_]:
self.dependencyMap[u.id_].append(p.id_)
for s in self.sortComponentsByDistanceTo(self.storages, u):
if (s.coordX, s.coordY) not in group:
continue
if not self.cells[s.coordX][s.coordY]:
continue
# compute energy consumption
if s.currentKWH > 0 and u.currentKWH < u.desiredKWH:
neededKWH = u.desiredKWH - u.currentKWH
s.currentKWH -= neededKWH
if s.currentKWH < 0:
u.currentKWH -= s.currentKWH
s.currentKWH = 0
else:
u.currentKWH += neededKWH
# keep track of component dependency
if s.id_ not in self.dependencyMap[u.id_]:
self.dependencyMap[u.id_].append(s.id_)
# step 2, storages can now consume from providers
for s in self.storages:
if (s.coordX, s.coordY) not in group:
continue
if not self.cells[s.coordX][s.coordY]:
continue
for p in self.sortComponentsByDistanceTo(self.providers, s):
if (p.coordX, p.coordY) not in group:
continue
if not self.cells[p.coordX][p.coordY]:
continue
# compute energy consumption
if p.currentKWH > 0 and s.currentKWH < s.maxKWH:
neededKWH = s.maxKWH - s.currentKWH
p.currentKWH -= neededKWH
if p.currentKWH < 0:
s.currentKWH -= p.currentKWH
p.currentKWH = 0
else:
s.currentKWH += neededKWH
# keep track of component dependency
if p.id_ not in self.dependencyMap[s.id_]:
self.dependencyMap[s.id_].append(p.id_)
# step three, p2x's can now consume from the provider's leftovers
for p2x in self.p2xs:
if (p2x.coordX, p2x.coordY) not in group:
continue
if not self.cells[p2x.coordX][p2x.coordY]:
continue
for p in self.sortComponentsByDistanceTo(self.providers, p2x):
if (p.coordX, p.coordY) not in group:
continue
if not self.cells[p.coordX][p.coordY]:
continue
# compute energy consumption
if p.currentKWH > 0 and p2x.currentKWH < p2x.desiredKWH:
neededKWH = p2x.desiredKWH - p2x.currentKWH
p.currentKWH -= neededKWH
if p.currentKWH < 0:
p2x.currentKWH -= p.currentKWH
p.currentKWH = 0
else:
p2x.currentKWH += neededKWH
# keep track of component dependency
if p.id_ not in self.dependencyMap[p2x.id_]:
self.dependencyMap[p2x.id_].append(p.id_)
self.simulationDayTime += datetime.timedelta(minutes=15)
self.stepCounter += 1
self.updateEquilibrium()