forked from open-plan-tool/simulation-server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrid_optimizer.py
More file actions
1789 lines (1594 loc) · 72.9 KB
/
Copy pathgrid_optimizer.py
File metadata and controls
1789 lines (1594 loc) · 72.9 KB
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
"""
This module is an intricate part of a FastAPI application designed for grid optimization in energy projects, with a
focus on efficiently connecting consumers to a power house through a distribution grid. The grid comprises poles,
connection cables, and distribution cables. Here's an expanded overview highlighting the key aspects and
functionalities:
1. **Initial Data Retrieval:**
- The module begins by querying a database to retrieve node data, which includes all consumers needing power supply.
It also gathers project parameters like the Weighted Average Cost of Capital (WACC), crucial for financial
calculations in the optimization process.
2. **Grid Optimization Objective:**
- The primary goal is to connect these consumers to the power house in the most efficient manner. This involves
determining the optimal placement of poles and routing of distribution and connection cables.
3. **Core Optimization Process:**
- Utilizing the `GridOptimizer` class, it employs k-means clustering for determining the optimal locations for poles.
- The optimizer connects consumers to the nearest poles and interlinks poles using a minimum spanning tree approach,
ensuring an efficient energy distribution network.
- The grid optimization takes into account the maximum permissible length for connection cables to avoid overly long
connections that might be inefficient or impractical.
4. **Cost Calculations and Constraints Handling in Grid Optimization (Refined):**
- **Initial Setup and User Specifications:**
- The process begins with all potential grid consumers included. Users of the system have the option to manually
specify certain consumers to be either definitely connected, excluded, or equipped with solar home systems (SHS).
This user input is crucial in guiding the initial setup and subsequent optimization steps.
- **Initial Cost Distribution Among Consumers:**
- The initial phase involves distributing the cost of grid components (poles, cables) among all consumers. This
allocation is based on each consumer's specific connection details, ensuring a fair and proportionate
distribution of the grid's total cost.
- **Exclusion of Consumers Based on Cost Threshold:**
- The algorithm then evaluates each consumer, starting from the ends of the grid's branches, to check if their
individual connection cost exceeds a user-defined maximum threshold.
- Consumers whose connection costs are too high are considered for exclusion. This is a crucial step in
maintaining the financial viability of the grid.
- **Iterative Optimization Process:**
- After each exclusion, the grid's cost allocation is recalculated. This iterative process is key to understanding
the financial implications of each exclusion and adjusting the grid design accordingly.
- If a consumer's cost is within the acceptable range, all consumers upstream in the same branch are automatically
retained in the grid. This decision point helps streamline the optimization process by finalizing sections of
the grid without further analysis.
- **Determining the Direction of Grid Links:**
- A critical component of this process is establishing the directionality of each grid link. Since the Kruskal
algorithm, used for the minimum spanning tree (MST) calculation, does not provide link direction, the module
includes a specific function for this purpose.
- Determining the direction of flow for each link is essential for accurately assigning costs and for the logical
distribution of power within the grid.
- **Dynamic Grid Adjustment:**
- Based on the ongoing optimization, the grid configuration is dynamically adjusted. Consumers may be excluded
based on cost-effectiveness, and the layout of poles and cables is modified to reflect the most efficient
design under the given constraints.
- This dynamic adjustment ensures that the final grid layout is not only technically sound but also adheres to the
financial and user-defined parameters, striking a balance between efficiency, cost-effectiveness,
and user preferences.
5. **Final Output and Database Interaction:**
- Post-optimization, the `nodes` object, now containing both consumers and poles, is written back to the database.
This provides a comprehensive view of the grid layout and participant nodes.
- The `links` object is also stored in the database. It details the start and end points of all cables, categorizes
the type of cables (distribution or connection), and identifies the start and end nodes (consumers, poles,
power-house).
- The result is a database-driven representation of the optimized grid, providing a foundation for further analysis,
implementation, or modification.
6. **Error Handling and Logging:**
- Throughout the process, the module ensures robust error handling and logging, crucial for diagnosing issues and
optimizing performance.
"""
import copy
import json
import logging
import math
import time
import utm
import numpy as np
import pandas as pd
from k_means_constrained import KMeansConstrained
from pyproj import Proj
from scipy.sparse.csgraph import minimum_spanning_tree
logger = logging.getLogger(__name__)
pd.options.mode.chained_assignment = None # default='warn'
def optimize_grid(grid_opt_json):
grid_opt = GridOptimizer(grid_opt_json)
results = grid_opt.optimize()
return results
class GridOptimizer:
def __init__(self, grid_opt_json):
print("Initiating grid optimizer...")
# TODO go through the helper functions and figure out what they do / document
self.start_execution_time = time.monotonic()
self.grid_opt_json = grid_opt_json
self.nodes = pd.DataFrame(self.grid_opt_json["nodes"])
utm_zone = utm.from_latlon(
latitude=self.nodes.latitude.mean(),
longitude=self.nodes.longitude.mean(),
)
self._utm_zone = utm_zone[2]
self.grid_design_dict = self.grid_opt_json["grid_design"]
self.yearly_demand = self.grid_opt_json["yearly_demand"]
self.nodes_df, self.power_house = self._query_nodes()
self.links = pd.DataFrame(
{
"label": pd.Series([], dtype=str),
"lat_from": pd.Series([], dtype=np.dtype(float)),
"lon_from": pd.Series([], dtype=np.dtype(float)),
"lat_to": pd.Series([], dtype=np.dtype(float)),
"lon_to": pd.Series([], dtype=np.dtype(float)),
"x_from": pd.Series([], dtype=np.dtype(float)),
"y_from": pd.Series([], dtype=np.dtype(float)),
"x_to": pd.Series([], dtype=np.dtype(float)),
"y_to": pd.Series([], dtype=np.dtype(float)),
"link_type": pd.Series([], dtype=str),
"length": pd.Series([], dtype=int),
"n_consumers": pd.Series([], dtype=int),
"total_power": pd.Series([], dtype=int),
"from_node": pd.Series([], dtype=str),
"to_node": pd.Series([], dtype=str),
},
).set_index("label")
self.distribution_links = self.links[
self.links["link_type"] == "distribution"
].copy()
self.pole_max_connection = self.grid_design_dict["pole"]["max_n_connections"]
self.grid_mst = pd.DataFrame({}, dtype=np.dtype(float))
if self.grid_design_dict["shs"]["include"]:
self.max_levelized_grid_cost = self.grid_design_dict["shs"]["max_grid_cost"] / 1000 # convert to currency/Wh
else:
# If SHS are not included, set the levelized grid cost threshold to a very high number instead
self.max_levelized_grid_cost = 1e6
self.connection_cable_max_length = self.grid_design_dict["connection_cable"][
"max_length"
]
self.distribution_cable_max_length = self.grid_design_dict[
"distribution_cable"
]["max_length"]
def optimize(self):
print("Optimizing distribution grid...")
self.convert_lonlat_xy()
self._clear_poles()
n_total_consumers = len(self.nodes)
n_shs_consumers = len(self.nodes[self.nodes["is_connected"] == False]) # noqa: E712
n_grid_consumers = n_total_consumers - n_shs_consumers
self.nodes = self.nodes.sort_index(key=lambda x: x.astype("int64"))
if self.power_house is not None:
power_house_consumers = self._connect_power_house_consumer_manually(
self.connection_cable_max_length,
)
self._placeholder_consumers_for_power_house()
else:
power_house_consumers = None
print("Determining number of poles...")
n_poles = self._find_opt_number_of_poles(n_grid_consumers)
self.determine_poles(
min_n_clusters=n_poles,
power_house_consumers=power_house_consumers,
)
# Find the connection links_df in the network with lengths greater than the
# maximum allowed length for `connection` cables, specified by the user.
long_links = self.find_index_longest_distribution_link()
# Add poles to the identified long `distribution` links_df, so that the
# distance between all poles remains below the maximum allowed distance.
self._add_fixed_poles_on_long_links(long_links=long_links)
# Update the (lon,lat) coordinates based on the newly inserted poles
# which only have (x,y) coordinates.
self.convert_lonlat_xy(inverse=True)
# Connect all poles together using the minimum spanning tree algorithm.
print("Determining distribution links...")
self.connect_grid_poles(long_links=long_links)
# Calculate distances of all poles from the load centroid.
# Find the location of the power house.
self.add_number_of_distribution_and_connection_cables()
n_iter = 2 if self.power_house is None else 1
print("Determining power house location...")
for i in range(n_iter):
if self.power_house is None and i == 0:
self._select_location_of_power_house()
self._set_direction_of_links()
self.allocate_poles_to_branches()
self.allocate_subbranches_to_branches()
self.label_branch_of_consumers()
self.determine_cost_per_pole()
self._connection_cost_per_consumer()
self.determine_costs_per_branch()
consumer_idxs = self.nodes[self.nodes["node_type"] == "consumer"].index
self.nodes.loc[consumer_idxs, "yearly_consumption"] = (
self.yearly_demand / len(consumer_idxs)
)
self._determine_shs_consumers()
if self.power_house is None and len(self.links) > 0:
old_power_house = self.nodes[
self.nodes["node_type"] == "power-house"
].index[0]
self._select_location_of_power_house()
new_power_house = self.nodes[
self.nodes["node_type"] == "power-house"
].index[0]
if old_power_house == new_power_house:
break
else:
break
return self._process_results()
def _process_results(self):
"""
Returns a json object with processed nodes and links
:return json: Links and nodes calculated in optimization
"""
results = {
"nodes": self._process_nodes(),
"links": self._process_links(),
}
return results
def _process_nodes(self):
nodes_df = self.nodes.reset_index(names=["label"])
nodes_df = nodes_df.drop(
labels=[
"x",
"y",
"cluster_label",
"type_fixed",
"n_connection_links",
"n_distribution_links",
"cost_per_pole",
"branch",
"parent_branch",
"total_grid_cost_per_consumer_per_a",
"connection_cost_per_consumer",
"cost_per_branch",
"distribution_cost_per_branch",
"yearly_consumption",
],
axis=1,
)
nodes_df = nodes_df.round(decimals=6)
nodes_df = nodes_df.replace(np.nan, None)
if not nodes_df.empty:
nodes_df.latitude = nodes_df.latitude.map(lambda x: f"{x:.6f}")
nodes_df.longitude = nodes_df.longitude.map(lambda x: f"{x:.6f}")
if len(nodes_df.index) != 0:
if "parent" in nodes_df.columns:
nodes_df["parent"] = nodes_df["parent"].where(
nodes_df["parent"] != "unknown",
None,
)
return nodes_df.reset_index(drop=True).to_dict(orient="list")
def _process_links(self):
links_df = self.links.reset_index(names=["label"])
links_df = links_df.drop(
labels=[
"x_from",
"y_from",
"x_to",
"y_to",
"n_consumers",
"total_power",
],
axis=1,
)
links_df.lat_from = links_df.lat_from.map(lambda x: f"{x:.6f}")
links_df.lon_from = links_df.lon_from.map(lambda x: f"{x:.6f}")
links_df.lat_to = links_df.lat_to.map(lambda x: f"{x:.6f}")
links_df.lon_to = links_df.lon_to.map(lambda x: f"{x:.6f}")
links_df = links_df.replace(np.nan, None)
return links_df.reset_index(drop=True).to_dict(orient="list")
def _query_nodes(self):
"""
:return:
"""
nodes_df = self.nodes
nodes_df["is_connected"] = True
nodes_df.loc[nodes_df["shs_options"] == 2, "is_connected"] = False # noqa: PLR2004 -> TODO check what shs_options=2 means
nodes_df.index = nodes_df.index.astype(str)
nodes_df = nodes_df[nodes_df["node_type"].isin(["consumer", "power-house"])]
power_houses = nodes_df.loc[nodes_df["node_type"] == "power-house"]
# TODO what is happening here? is manual not the only way to add power houses?
if len(power_houses) > 0 and power_houses["how_added"].iloc[0] != "manual":
nodes_df = nodes_df.drop(index=power_houses.index)
power_houses = None
elif len(power_houses) == 0:
power_houses = None
return nodes_df, power_houses
# -------------------- NODES -------------------- #
def _get_load_centroid(self):
"""
This function obtains the ideal location for the power house, which is
at the load centroid of the village.
"""
grid_consumers = self.nodes[self.nodes["is_connected"] == True] # noqa:E712
lat = np.average(grid_consumers["latitude"])
lon = np.average(grid_consumers["longitude"])
self.load_centroid = [lat, lon]
@staticmethod
def haversine_distance(lat1, lon1, lat2, lon2):
radius = 6371.0 * 1000
# Convert degrees to radians
lat1_rad = math.radians(lat1)
lon1_rad = math.radians(lon1)
lat2_rad = math.radians(lat2)
lon2_rad = math.radians(lon2)
# Differences
dlon = lon2_rad - lon1_rad
dlat = lat2_rad - lat1_rad
# Haversine formula
a = (
math.sin(dlat / 2) ** 2
+ math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2) ** 2
)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
# Distance
distance = radius * c
return distance
def _get_poles_distances_from_load_centroid(self):
"""
This function calculates all distances between the poles and the load
centroid of the settlement.
"""
self._get_load_centroid()
lat2, lon2 = self.load_centroid
for pole_index in self._poles().index:
lat1 = self.nodes.latitude.loc[pole_index]
lon1 = self.nodes.longitude.loc[pole_index]
self.nodes.loc[pole_index, "distance_to_load_center"] = (
GridOptimizer.haversine_distance(lat1, lon1, lat2, lon2)
)
def _select_location_of_power_house(self):
"""
This function assumes the closest pole to the calculated location for
the power house, as the new location of the power house.
"""
self._get_poles_distances_from_load_centroid()
poles_with_consumers = self._poles()
poles_with_consumers = poles_with_consumers[
poles_with_consumers["n_connection_links"] > 0
]
min_distance_nearest_pole = poles_with_consumers[
"distance_to_load_center"
].min()
nearest_pole = self._poles()[
self._poles()["distance_to_load_center"] == min_distance_nearest_pole
]
self.nodes.loc[self.nodes["node_type"] == "power-house", "node_type"] = "pole"
self.nodes.loc[nearest_pole.index, "node_type"] = "power-house"
def _connect_power_house_consumer_manually(self, max_length):
power_house = self.nodes.loc[self.nodes["node_type"] == "power-house"]
self.convert_lonlat_xy()
x2 = power_house["x"].to_numpy()[0]
y2 = power_house["y"].to_numpy()[0]
consumer_nodes = self.nodes[self.nodes["node_type"] == "consumer"]
for consumer in consumer_nodes.index:
x1 = self.nodes.x.loc[consumer]
y1 = self.nodes.y.loc[consumer]
distance = np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
self.nodes.loc[consumer, "distance_to_load_center"] = distance
mask = (
(self.nodes["node_type"] == "consumer") &
(self.nodes["distance_to_load_center"] <= max_length)
)
consumers = self.nodes[mask].copy()
if len(consumers) > 0:
self.nodes = self.nodes.drop(index=consumers.index)
return consumers
def _placeholder_consumers_for_power_house(self, *, remove=False):
n_max = self.pole_max_connection
label_start = 100000
power_house = self.nodes.loc[self.nodes["node_type"] == "power-house"]
for i in range(n_max):
label = str(label_start + i)
if remove is True:
self.nodes = self.nodes.drop(index=label)
else:
self._add_node(
label,
latitude=power_house["latitude"].to_numpy()[0],
longitude=power_house["longitude"].to_numpy()[0],
x=np.nan,
y=np.nan,
cluster_label=np.nan,
n_connection_links=np.nan,
n_distribution_links=np.nan,
parent=np.nan,
)
if remove is False:
self.convert_lonlat_xy()
def _clear_nodes(self):
"""
Removes all nodes from the grid.
"""
self.nodes = self.nodes.drop(list(self.nodes.index), axis=0)
def _clear_poles(self):
"""
Removes all poles from the grid.
"""
self.nodes = self.nodes.drop(
[
label
for label in self.nodes.index
if self.nodes.node_type.loc[label] in ["pole"]
],
axis=0,
)
def get_grid_consumers(self):
df = self.nodes[
(self.nodes["is_connected"] == True) # noqa:E712
& (self.nodes["node_type"] == "consumer")
]
return df.copy()
def get_shs_consumers(self):
df = self.nodes[
(self.nodes["is_connected"] == False) # noqa:E712
& (self.nodes["node_type"] == "consumer")
]
return df.copy()
def find_index_longest_distribution_link(self):
# Find the links longer than the allowed distance
self.distribution_links = self.links[self.links["link_type"] == "distribution"]
critical_link = self.distribution_links[
self.distribution_links["length"] > self.distribution_cable_max_length
]
return list(critical_link.index)
def _add_fixed_poles_on_long_links(
self,
long_links,
):
for long_link in long_links:
# Get start and end coordinates of the long link.
x_from = self.links.x_from[long_link]
x_to = self.links.x_to[long_link]
y_from = self.links.y_from[long_link]
y_to = self.links.y_to[long_link]
# Calculate the number of additional poles required.
n_required_poles = int(
np.ceil(
self.links.length[long_link] / self.distribution_cable_max_length,
)
- 1,
)
# Get the index of the last pole in the grid. The new pole's index
# will start from this index.
last_pole = self._poles().index[-1]
# Split the pole's index using `-` as the separator, because poles
# are labeled in `p-x` format. x represents the index number, which
# must be an integer.
index_last_pole = int(last_pole.split("-")[1])
# Calculate the slope of the line, connecting the start and end
# points of the long link.
slope = (y_to - y_from) / (x_to - x_from)
# Calculate the final length of the smaller links after splitting
# the long links into smaller parts.
length_smaller_links = self.links.length[long_link] / (n_required_poles + 1)
# Add all poles between the start and end points of the long link.
for i in range(1, n_required_poles + 1):
x = x_from + np.sign(
x_to - x_from,
) * i * length_smaller_links * np.sqrt(1 / (1 + slope**2))
y = y_from + np.sign(y_to - y_from) * i * length_smaller_links * abs(
slope,
) * np.sqrt(1 / (1 + slope**2))
pole_label = f"p-{i + index_last_pole}"
# In adding the pole, the `how_added` attribute is considered
# `long-distance-init`, which means the pole is added because
# of long distance in a distribution link.
# The reason for using the `long_link` part is to distinguish
# it with the poles which are already `connected` to the grid.
# The poles in this stage are only placed on the line, and will
# be connected to the other poles using another function.
# The `cluster_label` is given as 1000, to avoid inclusion in
# other clusters.
self._add_node(
label=pole_label,
x=x,
y=y,
node_type="pole",
consumer_type="n.a.",
consumer_detail="n.a.",
is_connected=True,
how_added=long_link,
type_fixed=True,
cluster_label=1000,
custom_specification="",
shs_options=0,
)
def _add_node(self, label, **kwargs):
"""
adds a node to the grid's node dataframe.
Parameters
----------
already defined in the 'Grid' object definition
"""
default_values = {
"latitude": 0,
"longitude": 0,
"x": 0,
"y": 0,
"node_type": "consumer",
"consumer_type": "household",
"consumer_detail": "default",
"distance_to_load_center": 0,
"is_connected": True,
"how_added": "automatic",
"type_fixed": False,
"cluster_label": 0,
"n_connection_links": "0",
"n_distribution_links": 0,
"parent": "unknown",
"distribution_cost": 0,
"custom_specification": "",
"shs_options": 0,
}
node_data = {**default_values, **kwargs}
for key, value in node_data.items():
self.nodes.loc[label, key] = value
def consumers(self):
"""
Returns only the 'consumer' nodes from the grid.
Returns
------
class:`pandas.core.frame.DataFrame`
filtered pandas dataframe containing all 'consumer' nodes
"""
return self.nodes[self.nodes["node_type"] == "consumer"]
def _poles(self):
"""
Returns all poles and the power house in the grid.
Returns
------
class:`pandas.core.frame.DataFrame`
filtered pandas dataframe containing all 'pole' nodes
"""
return self.nodes[
(self.nodes["node_type"] == "pole")
| (self.nodes["node_type"] == "power-house")
]
def distance_between_nodes(self, label_node_1: str, label_node_2: str):
"""
Returns the distance between two nodes of the grid
Parameters
----------
label_node_1: str
label of the first node
label_node_2: str
label of the second node
Return
-------
distance between the two nodes in meter
"""
if (label_node_1 and label_node_2) in self.nodes.index:
# (x,y) coordinates of the points
x1 = self.nodes.x.loc[label_node_1]
y1 = self.nodes.y.loc[label_node_1]
x2 = self.nodes.x.loc[label_node_2]
y2 = self.nodes.y.loc[label_node_2]
return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
return np.inf
# -------------------- LINKS -------------------- #
def get_links(self):
"""
Returns all links of the grid.
Returns
-------
class:`pandas.core.frame.DataFrame`
a pandas dataframe containing all links of the grid
"""
return self.links
def get_nodes(self):
"""
Return all nodes of the grid.
Returns
-------
class:`pandas.core.frame.DataFrame`
a pandas dataframe containing all nodes of the grid
"""
return self.nodes
def _clear_all_links(self):
"""
Removes all links from the grid.
"""
self.links = self.get_links().drop(
list(self.get_links().index),
axis=0,
)
def _clear_links(self, link_type):
"""
Removes all link types given by the user from the grid.
"""
self.links = self.get_links().drop(
list(self.get_links()[self.get_links()["link_type"] == link_type].index),
axis=0,
)
def _add_links(self, label_node_from: str, label_node_to: str):
"""
Adds a link between two nodes of the grid and
calculates the distance of the link.
Parameters
----------
label_node_from: str
label of the first node
label_node_to: str
label of the second node
Notes
-----
The method first makes sure that the two labels belong to the grid.
Otherwise, no link will be added.
"""
# specify the type of the link which is obtained based on the start/end nodes of the link
from_type = self.nodes.node_type.loc[label_node_from]
to_type = self.nodes.node_type.loc[label_node_to]
if from_type in ["pole", "power-house"] and to_type in ["pole", "power-house"]:
(label_node_from, label_node_to) = sorted([label_node_from, label_node_to])
link_type = "distribution"
else:
link_type = "connection"
# calculate the length of the link
length = self.distance_between_nodes(
label_node_1=label_node_from,
label_node_2=label_node_to,
)
# define a label for the link and add all other characteristics to the grid object
label = f"({label_node_from}, {label_node_to})"
self.links.loc[label, "lat_from"] = self.nodes.latitude.loc[label_node_from]
self.links.loc[label, "lon_from"] = self.nodes.longitude.loc[label_node_from]
self.links.loc[label, "lat_to"] = self.nodes.latitude.loc[label_node_to]
self.links.loc[label, "lon_to"] = self.nodes.longitude.loc[label_node_to]
self.links.loc[label, "x_from"] = self.nodes.x.loc[label_node_from]
self.links.loc[label, "y_from"] = self.nodes.y.loc[label_node_from]
self.links.loc[label, "x_to"] = self.nodes.x.loc[label_node_to]
self.links.loc[label, "y_to"] = self.nodes.y.loc[label_node_to]
self.links.loc[label, "link_type"] = link_type
self.links.loc[label, "length"] = length
self.links.loc[label, "n_consumers"] = 0
self.links.loc[label, "total_power"] = 0
self.links.loc[label, "from_node"] = label_node_from
self.links.loc[label, "to_node"] = label_node_to
def total_length_distribution_cable(self):
"""
Calculates the total length of all cables connecting only poles in the grid.
Returns
------
type: float
the total length of the distribution cable in the grid
"""
return self.links.length[self.links.link_type == "distribution"].sum()
def total_length_connection_cable(self):
"""
Calculates the total length of all cables between each pole and
consumers.
Returns
------
type: float
total length of the connection cable in the grid.
"""
return self.links.length[self.links.link_type == "connection"].sum()
# -------------------- OPERATIONS -------------------- #
def convert_lonlat_xy(self, *, inverse=False):
"""
+++ ok +++
Converts (longitude, latitude) coordinates into (x, y)
plane coordinates using a python package 'pyproj'.
Parameter
---------
inverse: bool (default=false)
this parameter indicates the direction of conversion
+ false: lon,lat --> x,y
+ true: x,y --> lon/lat
"""
p = Proj(proj="utm", zone=self._utm_zone, ellps="WGS84", preserve_units=False)
# if inverse=true, this is the case when the (x,y) coordinates of the obtained
# poles (from the optimization) are converted into (lon,lat)
if inverse:
# First the possible candidates for inverse conversion are picked.
nodes_for_inverse_conversion = self.nodes[
(self.nodes["node_type"] == "pole")
| (self.nodes["node_type"] == "power-house")
]
for node_index in nodes_for_inverse_conversion.index:
lon, lat = p(
self.nodes.x.loc[node_index],
self.nodes.y.loc[node_index],
inverse=inverse,
)
self.nodes.loc[node_index, "longitude"] = lon
self.nodes.loc[node_index, "latitude"] = lat
else:
for node_index in self.nodes.index:
x, y = p(
self.nodes.longitude.loc[node_index],
self.nodes.latitude.loc[node_index],
inverse=inverse,
)
self.nodes.loc[node_index, "x"] = x
self.nodes.loc[node_index, "y"] = y
# store reference values for (x,y) to use later when converting (x,y) to (lon,lat)
# -------------------- COSTS ------------------------ #
def cost(self):
"""
Computes the cost of the grid taking into account the number
of nodes, their types (consumer or poles) and the length of
different types of cables between nodes.
Return
------
cost of the grid
"""
# get the number of poles, consumers and links from the grid
n_poles = self._poles().shape[0]
n_mg_consumers = self.consumers()[
self.consumers()["is_connected"] == True # noqa:E712
].shape[0]
n_links = self.get_links().shape[0]
# if there is no poles in the grid, or there is no link,
# the function returns an infinite value
if (n_poles == 0) or (n_links == 0):
return np.inf
# calculate the total length of the cable used between poles [m]
total_length_distribution_cable = self.total_length_distribution_cable()
# calculate the total length of the `connection` cable between poles and consumers
total_length_connection_cable = self.total_length_connection_cable()
grid_cost = (
n_poles * self.grid_design_dict["pole"]["epc"]
+ n_mg_consumers * self.grid_design_dict["mg"]["epc"]
+ total_length_connection_cable
* self.grid_design_dict["connection_cable"]["epc"]
+ total_length_distribution_cable
* self.grid_design_dict["distribution_cable"]["epc"]
)
return np.around(grid_cost, decimals=2)
def add_number_of_distribution_and_connection_cables(self):
poles = self._poles().copy()
links = self.get_links().copy()
links["from_node"] = (
links.index.str.extract(r"^\(\s*([^,]+)")[0].str.strip().tolist()
)
links["to_node"] = (
links.index.str.extract(r",\s*([^,]+)\s*\)$")[0].str.strip().tolist()
)
connection_links = links[links["link_type"] == "connection"].copy()
distribution_links = links[links["link_type"] == "distribution"].copy()
for pole_idx in poles.index:
n_distribution = len(
distribution_links[
distribution_links["from_node"] == pole_idx
].index,
)
n_distribution += len(
distribution_links[
distribution_links["to_node"] == pole_idx
].index,
)
self.nodes.loc[pole_idx, "n_distribution_links"] = n_distribution
n_connection = len(
connection_links[connection_links["from_node"] == pole_idx].index,
)
n_connection += len(
connection_links[connection_links["to_node"] == pole_idx].index,
)
self.nodes.loc[pole_idx, "n_connection_links"] = n_connection
self.nodes.loc[self.nodes["node_type"] == "consumer", "n_connection_links"] = 1
self.nodes["n_distribution_links"] = (
self.nodes["n_distribution_links"].fillna(0).astype(int)
)
self.nodes["n_connection_links"] = (
self.nodes["n_connection_links"].fillna(0).astype(int)
)
def allocate_poles_to_branches(self):
poles = self._poles().copy()
leaf_poles = pd.Series(
poles[poles["n_distribution_links"] == 1].index
).to_numpy()
split_poles = pd.Series(
poles[poles["n_distribution_links"] > 2].index # noqa: PLR2004
).to_numpy()
power_house = poles[poles["node_type"] == "power-house"].index[0]
start_poles = self.distribution_links[
(self.distribution_links["to_node"] == power_house)
]["from_node"].to_numpy()
start_set = set(start_poles)
split_set = set(split_poles)
diff_set = start_set - split_set
start_poles = np.array(list(diff_set))
for split_pole in split_poles:
for start_pole in self.distribution_links[
(self.distribution_links["to_node"] == split_pole)
]["from_node"].to_list():
start_poles = np.append(start_poles, start_pole)
start_poles = pd.Series(start_poles).drop_duplicates().to_numpy()
self.nodes["branch"] = None
tmp_idxs = self.nodes[self.nodes.index.isin(start_poles)].index
self.nodes.loc[start_poles, "branch"] = pd.Series(tmp_idxs, index=tmp_idxs)
for start_pole in start_poles:
next_pole = copy.deepcopy(start_pole)
for _ in range(len(poles.index)):
next_pole = self.distribution_links[
(self.distribution_links["to_node"] == next_pole)
]["from_node"]
if len(next_pole.index) == 1:
next_pole = next_pole.to_numpy()[0]
self.nodes.loc[next_pole, "branch"] = start_pole
if next_pole in split_poles or next_pole in leaf_poles:
break
else:
break
self.nodes.loc[
(self.nodes["branch"].isna())
& (self.nodes["node_type"].isin(["pole", "power-house"])),
"branch",
] = power_house
def label_branch_of_consumers(self):
branch_map = self.nodes.loc[
self.nodes.node_type.isin(["pole", "power-house"]),
"branch",
]
self.nodes.loc[self.nodes.node_type == "consumer", "branch"] = self.nodes.loc[
self.nodes.node_type == "consumer",
"parent",
].map(branch_map)
def determine_parent_branches(self, start_poles):
poles = self._poles().copy()
for pole in start_poles:
branch_start_pole = poles[poles.index == pole]["branch"].iloc[0]
split_pole = self.nodes[self.nodes.index == branch_start_pole][
"parent"
].iloc[0]
parent_branch = poles[poles.index == split_pole]["branch"].iloc[0]
self.nodes.loc[
self.nodes["branch"] == branch_start_pole,
"parent_branch",
] = parent_branch
def allocate_subbranches_to_branches(self):
poles = self._poles().copy()
self.nodes["parent_branch"] = None
power_house = poles[poles["node_type"] == "power-house"].index[0]
if len(poles["branch"].unique()) > 1:
leaf_poles = poles[poles["n_distribution_links"] == 1].index
self.determine_parent_branches(leaf_poles)
poles_expect_power_house = poles[poles["node_type"] != "power-house"]
split_poles = poles_expect_power_house[
poles_expect_power_house["n_distribution_links"] > 2 # noqa: PLR2004
].index
if len(split_poles) > 0:
self.determine_parent_branches(split_poles)
self.nodes.loc[
(self.nodes["parent_branch"].isna())
& (self.nodes["node_type"].isin(["pole", "power-house"])),
"parent_branch",
] = power_house
def determine_cost_per_pole(self):
poles = self._poles().copy()
links = self.get_links().copy()
self.nodes["cost_per_pole"] = None
self.nodes["cost_per_pole"] = self.nodes["cost_per_pole"].astype(float)
power_house = poles[poles["node_type"] == "power-house"].index[0]
for pole in poles.index:
if pole != power_house:
parent_pole = poles[poles.index == pole]["parent"].iloc[0]
try:
length = links[
(links["from_node"] == pole) & (links["to_node"] == parent_pole)
]["length"].iloc[0]
except IndexError:
try:
length = links[
(links["from_node"] == parent_pole)
& (links["to_node"] == pole)
]["length"].iloc[0]
except IndexError:
length = 20
self.nodes.loc[pole, "cost_per_pole"] = (
self.grid_design_dict["pole"]["epc"]
+ length * self.grid_design_dict["distribution_cable"]["epc"]
)
else:
self.nodes.loc[pole, "cost_per_pole"] = self.grid_design_dict["pole"][
"epc"
]
def determine_costs_per_branch(self, branch=None):
poles = self._poles().copy()
def _(branch):
branch_df = self.nodes[
(self.nodes["branch"] == branch) & (self.nodes["is_connected"] == True) # noqa:E712
].copy()
cost_per_branch = self.nodes[self.nodes.index.isin(branch_df.index)][
"cost_per_pole"
].sum()
cost_per_branch += self.nodes[self.nodes.index.isin(branch_df.index)][
"connection_cost_per_consumer"
].sum()
self.nodes.loc[branch_df.index, "distribution_cost_per_branch"] = (
cost_per_branch
)
self.nodes.loc[branch_df.index, "cost_per_branch"] = cost_per_branch
if branch is None:
for unique_branch in poles["branch"].unique():