-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimizer_Weights_Genetic.py
More file actions
1218 lines (1018 loc) · 48.3 KB
/
Optimizer_Weights_Genetic.py
File metadata and controls
1218 lines (1018 loc) · 48.3 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
import warnings
warnings.filterwarnings("ignore")
import random
import csv
import pandas as pd
from tqdm import tqdm
import numpy as np
import glob
from collections import defaultdict
from Functions.Additional_Functions import *
from Functions.Orthorectification_Model_Functions import *
from deap import base, creator, tools, algorithms
from tqdm import tqdm
from multiprocessing import Pool
# ==============================
# Pre-Defined Functions
# ==============================
def calculate_angle(line1, line2):
"""
Calculate the angle between two line segments. If the lines share an endpoint,
compute the angle based on the direction vectors formed by the other endpoints.
Parameters:
line1 (list): Coordinates of the first line segment.
line2 (list): Coordinates of the second line segment.
Returns:
float: Angle between the two lines in degrees.
"""
x1, y1, x2, y2 = line1
x3, y3, x4, y4 = line2
# Determine if the lines share an endpoint
if (x2, y2) == (x4, y4):
# Shared endpoint is (x2, y2)
# Vector for line 1: (x1, y1) to (x2, y2)
v1x = x2 - x1
v1y = y2 - y1
# Vector for line 2: (x3, y3) to (x2, y2)
v2x = x2 - x3
v2y = y2 - y3
elif (x1, y1) == (x3, y3):
# Shared endpoint is (x1, y1)
# Vector for line 1: (x2, y2) to (x1, y1)
v1x = x2 - x1
v1y = y2 - y1
# Vector for line 2: (x4, y4) to (x1, y1)
v2x = x1 - x4
v2y = y1 - y4
else:
# The lines do not share an endpoint
# Vector for line 1: (x2, y2) to (x1, y1)
v1x = x2 - x1
v1y = y2 - y1
# Vector for line 2: (x4, y4) to (x3, y3)
v2x = x4 - x3
v2y = y4 - y3
# Compute dot product and magnitudes
dot_product = v1x * v2x + v1y * v2y
mag_v1 = np.sqrt(v1x ** 2 + v1y ** 2)
mag_v2 = np.sqrt(v2x ** 2 + v2y ** 2)
# Compute cosine of the angle
cos_angle = dot_product / (mag_v1 * mag_v2)
# Clip value to avoid numerical issues due to floating-point precision
cos_angle = np.clip(cos_angle, -1.0, 1.0)
angle = np.arccos(cos_angle) * (180 / np.pi) # Convert radians to degrees
return angle
def calculate_angle_between_lines(line1, line2):
"""
Calculates the angle in degrees between two lines defined by their end points.
Each line is represented as [x1, y1, x2, y2].
"""
# Vector for line1
vector1 = (line1[2] - line1[0], line1[3] - line1[1])
# Vector for line2
vector2 = (line2[2] - line2[0], line2[3] - line2[1])
# Dot product and magnitudes
dot_product = vector1[0] * vector2[0] + vector1[1] * vector2[1]
magnitude1 = math.sqrt(vector1[0]**2 + vector1[1]**2)
magnitude2 = math.sqrt(vector2[0]**2 + vector2[1]**2)
# Cosine of the angle
cos_angle = dot_product / (magnitude1 * magnitude2)
# Convert cosine to angle in degrees
angle = math.degrees(math.acos(cos_angle))
return angle
def find_node_connections(graph):
"""
Takes a graph represented as an array of lines and calculates the angles
between each pair of lines connected to the same node.
"""
# Dictionary to store which lines are connected to each node
node_connections = defaultdict(list)
# Populate the dictionary with lines connected to each node
for line in graph:
line = tuple(line.tolist())
node_connections[(line[0], line[1])].append(line)
node_connections[(line[2], line[3])].append(line)
return node_connections
def find_repeating_point(lines):
"""
Finds the point that repeats the most in the list of lines.
:param lines: List of lines, where each line is represented as [x1, y1, x2, y2].
:return: The point (x, y) that repeats the most.
"""
point_counts = defaultdict(int)
# Count occurrences of each point
for line in lines:
x1, y1, x2, y2 = line
point_counts[(x1, y1)] += 1
point_counts[(x2, y2)] += 1
# Find the point with the maximum count
repeating_point = max(point_counts, key=point_counts.get)
return repeating_point
def sort_lines_with_point(lines, point):
"""
Sorts each line in the list so that the given point is always the first point in the line.
:param lines: List of lines, where each line is represented as [x1, y1, x2, y2].
:param point: The point (x, y) that should be at the start of each line.
:return: A list of lines with the point sorted to the start.
"""
sorted_lines = []
for line in lines:
x1, y1, x2, y2 = line
if (x1, y1) != point:
# Swap points if the point is not the first one
sorted_lines.append([x2, y2, x1, y1])
else:
sorted_lines.append([x1, y1, x2, y2])
return sorted_lines
def Line_Slope(line):
"""
Calculate the slope of a line segment in degrees given its endpoints.
Each line is represented as [x1, y1, x2, y2].
"""
x1, y1, x2, y2 = line
dx = x2 - x1
dy = y2 - y1
# Calculate the angle in radians
angle_radians = math.atan2(dy, dx)
# Convert the angle to degrees
angle_degrees = math.degrees(angle_radians)
# Convert counterclockwise angle to clockwise angle
clockwise_angle = (360 - angle_degrees) % 360
return clockwise_angle
def custom_fitness_function(x, max_30, max_45, max_60, max_90, max_180, curveness):
"""
This function takes an input x in the range 0 to 180 and returns y in the range 0 to 10
according to the U-shaped behavior specified for each bin.
"""
if 0 <= x <= 30:
Start_Number = 0
End_Number = max_30
Bin_Start = 0
Bin_End = 30
if curveness == 0:
y = 3 * (x / Bin_End)
else:
y = 3 * (x / Bin_End) ** (curveness * 5)
elif 30 < x <= 45:
Start_Number = max_30
End_Number = max_45
Bin_Start = 30
Bin_End = 45
if 30 < x <= 37.5:
if curveness == 0:
y = (-(Start_Number / 7.5) * x) + (Start_Number * 5)
else:
y = Start_Number * ((np.exp(-curveness / 1.5)) ** (x - Bin_Start))
elif 37.5 < x <= 45:
if curveness == 0:
y = ((End_Number / 7.5) * x) - (End_Number * 5)
else:
y = End_Number * (np.exp((curveness / 1.5) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 1.5) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
elif 45 < x <= 60:
Start_Number = max_45
End_Number = max_60
Bin_Start = 45
Bin_End = 60
if 45 < x <= 52.5:
if curveness == 0:
y = (-(Start_Number / 7.5) * x) + (Start_Number * 7)
else:
y = Start_Number * ((np.exp(-curveness / 1.5)) ** (x - Bin_Start))
elif 52.5 < x <= 60:
if curveness == 0:
y = ((End_Number / 7.5) * x) - (End_Number * 7)
else:
y = End_Number * (np.exp((curveness / 3) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 3) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
elif 60 < x <= 90:
Start_Number = max_60
End_Number = max_90
Bin_Start = 60
Bin_End = 90
if 60 < x <= 75:
if curveness == 0:
y = (-0.2 * x) + (Start_Number * 5)
else:
y = Start_Number * ((np.exp(-curveness / 3)) ** (x - Bin_Start))
elif 75 < x <= 90:
if curveness == 0:
y = ((2 / 3) * x) - (End_Number * 5)
else:
y = End_Number * (np.exp((curveness / 3) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 3) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
elif 90 < x <= 180:
Start_Number = max_90
End_Number = max_180
Bin_Start = 90
Bin_End = 180
if 90 < x <= 135:
if curveness == 0:
y = (-(45 / 10) * x) + (607.5)
else:
y = Start_Number * ((np.exp(-curveness / 8)) ** (x - Bin_Start))
elif 135 < x <= 180:
if curveness == 0:
y = ((45 / 10) * x) - (607.5)
else:
y = End_Number * (np.exp((curveness / 8) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 8) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
else:
raise ValueError("x should be in the range 0 to 180 degrees.")
return y
def custom_fitness_function_Streight_Lines(x, max_0, max_90, max_180, max_270, max_360, curveness):
"""
This function takes an input x in the range 0 to 180 and returns y in the range 0 to 10
according to the U-shaped behavior specified for each bin.
"""
if 0 <= x <= 90:
Start_Number = max_0
End_Number = max_90
Bin_Start = 0
Bin_End = 90
if 0 <= x <= 45:
if curveness == 0:
y = (-0.2 * x) + (Start_Number * 5)
else:
y = Start_Number * ((np.exp(-curveness / 2.5)) ** (x - Bin_Start))
elif 45 < x <= 90:
if curveness == 0:
y = ((2 / 3) * x) - (End_Number * 5)
else:
y = End_Number * (np.exp((curveness / 2.5) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 2.5) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
elif 90 < x <= 180:
Start_Number = max_90
End_Number = max_180
Bin_Start = 90
Bin_End = 180
if 90 < x <= 135:
if curveness == 0:
y = (-(45 / 10) * x) + (607.5)
else:
y = Start_Number * ((np.exp(-curveness / 2.5)) ** (x - Bin_Start))
elif 135 < x <= 180:
if curveness == 0:
y = ((45 / 10) * x) - (607.5)
else:
y = End_Number * (np.exp((curveness / 2.5) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 2.5) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
elif 180 < x <= 270:
Start_Number = max_180
End_Number = max_270
Bin_Start = 180
Bin_End = 270
if 180 < x <= 225:
if curveness == 0:
y = (-(45 / 10) * x) + (607.5)
else:
y = Start_Number * ((np.exp(-curveness / 2.5)) ** (x - Bin_Start))
elif 225 < x <= 270:
if curveness == 0:
y = ((45 / 10) * x) - (607.5)
else:
y = End_Number * (np.exp((curveness / 2.5) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 2.5) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
elif 270 < x <= 360:
Start_Number = max_270
End_Number = max_360
Bin_Start = 270
Bin_End = 360
if 270 < x <= 315:
if curveness == 0:
y = (-(45 / 10) * x) + (607.5)
else:
y = Start_Number * ((np.exp(-curveness / 2.5)) ** (x - Bin_Start))
elif 315 < x <= 360:
if curveness == 0:
y = ((45 / 10) * x) - (607.5)
else:
y = End_Number * (np.exp((curveness / 2.5) * (x - ((Bin_Start + Bin_End) / 2))) - 1) / (np.exp((curveness / 2.5) * (np.abs(Bin_Start - Bin_End) / 2)) - 1)
return y
def custom_Penalty_Function(x, max_value, curveness):
if curveness == 0:
y = 50 * (x / 20)
else:
y = max_value * (x / 20) ** curveness
return y
def custom_similarity_function(x, max_value, curveness):
x = abs(x)
End_Number = max_value
y = End_Number * (x ** curveness)
return y
def custom_Line_Length_Penalty_function(x, max_value, curveness):
x = abs(x)
End_Number = max_value
y = End_Number * (x ** curveness)
return y
def custom_Point_on_Line_function(x, max_value, curveness):
x = abs(x)
End_Number = max_value
y = End_Number * (x ** (curveness * 2))
return y
def custom_fitness_function_GA(x):
"""
This function takes an input x in the range 0 to 180 and returns y in the range 0 to 10
according to the U-shaped behavior specified for each bin.
"""
x = np.abs(x)
y = np.zeros_like(x)
y[(0 == x)] = 0
y[(30 == x)] = 3
y[(45 == x)] = 5
y[(60 == x)] = 3
y[(90 == x)] = 40
y[(180 == x)] = 40
return y
def custom_Penalty_Function_GA(x):
x = np.abs(x)
y = np.zeros_like(x)
y[(0 <= x) & (x < 5)] = 0
y[(5 <= x) & (x <= 7.5)] = 40 / 3
y[(7.5 <= x) & (x <= 10)] = 40 / 2
y[(10 <= x) & (x <= 20)] = 40
return y
def custom_similarity_function_GA(x):
x = np.abs(x)
y = np.zeros_like(x)
y[(0 <= x) & (x < 1)] = 0
y[(1 == x)] = 10
return y
def custom_Line_Length_Penalty_function_GA(x):
x = np.abs(x)
y = np.zeros_like(x)
y[(0 <= x) & (x < 0.2)] = 0
y[(0.2 <= x) & (x <= 0.4)] = 40 / 3
y[(0.4 <= x) & (x <= 0.6)] = 40 / 2
y[(0.6 <= x) & (x <= 1)] = 40
return y
def custom_Point_on_Line_function_GA(x):
x = np.abs(x)
y = np.zeros_like(x)
y[(0 <= x) & (x < 1)] = 0
y[(1 == x)] = 10
return y
def Graph_Angle_Similarity(graph, max_value, curveness):
node_connections = find_node_connections(graph)
Graph_Angles = []
Num_Angles = 0
for node, lines in node_connections.items():
LNs = np.array(lines).tolist()
Node_Coordinate = find_repeating_point(LNs)
Connected_Lines = sort_lines_with_point(lines, Node_Coordinate)
NL = [list(node), Connected_Lines]
Node = NL[0]
Lines = NL[1]
Slopes = []
for Line in Lines:
Slopes.append(Line_Slope(Line))
NS = [Node, Slopes]
Node = NS[0]
angles = np.array(NS[1])
angles_diff = angles[:, None] - angles
abs_diff = np.abs(angles_diff)
upper_triangle_indices = np.triu_indices(len(angles), k=1)
differences = abs_diff[upper_triangle_indices]
for difference in differences:
Num_Angles += 1
difference = difference if difference <= 180 else 360 - difference
Graph_Angles.append(difference)
# Create a similarity matrix using broadcasting to avoid loops
angles_array = np.round(np.array(Graph_Angles), 0)
diff_matrix = np.abs(angles_array[:, np.newaxis] - angles_array)
similarity_matrix = 1 / (1 + diff_matrix)
num_elements = similarity_matrix.shape[0]
# Create a mask to ignore diagonal elements
mask = np.eye(num_elements, dtype=bool)
# Extract the off-diagonal elements
off_diagonal_elements = similarity_matrix[~mask]
off_diagonal_elements[off_diagonal_elements != 1] = 0
# Calculate the average of the off-diagonal elements
average_similarity = np.mean(off_diagonal_elements)
Similarity_Score = custom_Line_Length_Penalty_function(average_similarity, max_value, curveness)
return Similarity_Score
def Graph_Angle_Similarity_GA(graph):
node_connections = find_node_connections(graph)
Graph_Angles = []
Num_Angles = 0
for node, lines in node_connections.items():
LNs = np.array(lines).tolist()
Node_Coordinate = find_repeating_point(LNs)
Connected_Lines = sort_lines_with_point(lines, Node_Coordinate)
NL = [list(node), Connected_Lines]
Node = NL[0]
Lines = NL[1]
Slopes = []
for Line in Lines:
Slopes.append(Line_Slope(Line))
NS = [Node, Slopes]
Node = NS[0]
angles = np.array(NS[1])
angles_diff = angles[:, None] - angles
abs_diff = np.abs(angles_diff)
upper_triangle_indices = np.triu_indices(len(angles), k=1)
differences = abs_diff[upper_triangle_indices]
for difference in differences:
Num_Angles += 1
difference = difference if difference <= 180 else 360 - difference
Graph_Angles.append(difference)
# Create a similarity matrix using broadcasting to avoid loops
angles_array = np.round(np.array(Graph_Angles), 0)
diff_matrix = np.abs(angles_array[:, np.newaxis] - angles_array)
similarity_matrix = 1 / (1 + diff_matrix)
num_elements = similarity_matrix.shape[0]
# Create a mask to ignore diagonal elements
mask = np.eye(num_elements, dtype=bool)
# Extract the off-diagonal elements
off_diagonal_elements = similarity_matrix[~mask]
off_diagonal_elements[off_diagonal_elements != 1] = 0
# Calculate the average of the off-diagonal elements
average_similarity = np.mean(off_diagonal_elements)
Similarity_Score = custom_Line_Length_Penalty_function_GA(average_similarity)
return Similarity_Score
def Graph_Lines_Similarity(graph, max_value, curveness):
num_lines = len(graph)
lengths = [Line_Length(line) for line in graph]
# Initialize the similarity matrix
similarity_matrix = np.zeros((num_lines, num_lines))
# Calculate the similarity values
for i in range(num_lines):
for j in range(num_lines):
similarity_matrix[i][j] = 1 / (1 + abs(lengths[i] - lengths[j]))
# Get the number of lines
num_lines = similarity_matrix.shape[0]
# Create a mask to ignore diagonal elements (which are always 1)
mask = np.eye(num_lines, dtype=bool)
# Extract the off-diagonal elements
off_diagonal_elements = similarity_matrix[~mask]
off_diagonal_elements[off_diagonal_elements != 1] = 0
# Calculate the average of the off-diagonal elements
average_similarity = np.mean(off_diagonal_elements)
Similarity_Score = custom_Line_Length_Penalty_function(average_similarity, max_value, curveness)
return Similarity_Score
def Graph_Lines_Similarity_GA(graph):
num_lines = len(graph)
lengths = [Line_Length(line) for line in graph]
# Initialize the similarity matrix
similarity_matrix = np.zeros((num_lines, num_lines))
# Calculate the similarity values
for i in range(num_lines):
for j in range(num_lines):
similarity_matrix[i][j] = 1 / (1 + abs(lengths[i] - lengths[j]))
# Get the number of lines
num_lines = similarity_matrix.shape[0]
# Create a mask to ignore diagonal elements (which are always 1)
mask = np.eye(num_lines, dtype=bool)
# Extract the off-diagonal elements
off_diagonal_elements = similarity_matrix[~mask]
off_diagonal_elements[off_diagonal_elements != 1] = 0
# Calculate the average of the off-diagonal elements
average_similarity = np.mean(off_diagonal_elements)
Similarity_Score = custom_Line_Length_Penalty_function_GA(average_similarity)
return Similarity_Score
def Graph_Fitness(graph, max_30, max_45, max_60, max_90, max_180, curveness):
node_connections = find_node_connections(graph)
Fitness = 0
Num_Angles = 0
for node, lines in node_connections.items():
LNs = np.array(lines).tolist()
Node_Coordinate = find_repeating_point(LNs)
Connected_Lines = sort_lines_with_point(lines, Node_Coordinate)
NL = [list(node), Connected_Lines]
Node = NL[0]
Lines = NL[1]
Slopes = []
for Line in Lines:
Slopes.append(Line_Slope(Line))
NS = [Node, Slopes]
Node = NS[0]
angles = np.array(NS[1])
angles_diff = angles[:, None] - angles
abs_diff = np.abs(angles_diff)
upper_triangle_indices = np.triu_indices(len(angles), k=1)
differences = abs_diff[upper_triangle_indices]
for difference in differences:
if difference <= 180:
Num_Angles += 1
Fitness += custom_fitness_function(difference, max_30, max_45, max_60, max_90, max_180, curveness)
if difference > 180:
Num_Angles += 1
difference = 360 - difference
Fitness += custom_fitness_function(difference, max_30, max_45, max_60, max_90, max_180, curveness)
return Fitness / Num_Angles
def Graph_Fitness_Straight_Lines(graph, max_0, max_90, max_180, max_270, max_360, curveness):
Fitness = 0
for line in graph:
Slope = Line_Slope(line)
Fitness += custom_fitness_function_Streight_Lines(Slope, max_0, max_90, max_180, max_270, max_360, curveness)
return Fitness / len(graph)
def Graph_Fitness_GA(graph):
node_connections = find_node_connections(graph)
Num_Angles = 0
Angle_Tolerance = 5
Counter_30 = 0
Counter_45= 0
Counter_60 = 0
Counter_90 = 0
Counter_180 = 0
for node, lines in node_connections.items():
LNs = np.array(lines).tolist()
Node_Coordinate = find_repeating_point(LNs)
Connected_Lines = sort_lines_with_point(lines, Node_Coordinate)
NL = [list(node), Connected_Lines]
Node = NL[0]
Lines = NL[1]
Slopes = [Line_Slope(Line) for Line in Lines]
NS = [Node, Slopes]
Node = NS[0]
angles = np.array(NS[1])
angles_diff = angles[:, None] - angles
abs_diff = np.abs(angles_diff)
upper_triangle_indices = np.triu_indices(len(angles), k=1)
differences = abs_diff[upper_triangle_indices]
Num_Angles += len(differences)
for difference in differences:
if difference <= 180:
if difference == 30:
Counter_30 += 1
elif difference == 45:
Counter_45 += 1
elif difference == 60:
Counter_60 += 1
elif difference == 90:
Counter_90 += 1
elif difference == 180:
Counter_180 += 1
else:
if 360 - difference == 30:
Counter_30 += 1
elif 360 - difference == 45:
Counter_45 += 1
elif 360 - difference == 60:
Counter_60 += 1
elif 360 - difference == 90:
Counter_90 += 1
elif 360 - difference == 180:
Counter_180 += 1
Fitness = (Counter_30 * 3) + (Counter_45 * 5) + (Counter_60 * 3) + (Counter_90 * 40) + (Counter_180 * 40)
return Fitness / Num_Angles
def Graph_Fitness_Straight_Lines_GA(graph):
Angle_Tolerance = 5
Straight_Line_Counter = 0
for line in graph:
Slope = Line_Slope(line)
if 0 + Angle_Tolerance <= Slope <= 0 + Angle_Tolerance:
Straight_Line_Counter += 1
if 90 + Angle_Tolerance <= Slope <= 90 + Angle_Tolerance:
Straight_Line_Counter += 1
if 180 + Angle_Tolerance <= Slope <= 180 + Angle_Tolerance:
Straight_Line_Counter += 1
if 270 + Angle_Tolerance <= Slope <= 270 + Angle_Tolerance:
Straight_Line_Counter += 1
if 360 + Angle_Tolerance <= Slope <= 360 + Angle_Tolerance:
Straight_Line_Counter += 1
Fitness = Straight_Line_Counter * 20
return Fitness / len(graph)
def MultiLineString_From_KeyPoints_Opti(Graph_KeyPoints):
# Assuming you have a list of lines
lines = Graph_KeyPoints
X = np.hstack([np.array(Graph_KeyPoints)[:,0], np.array(Graph_KeyPoints)[:,2]])
Y = np.hstack([np.array(Graph_KeyPoints)[:,1], np.array(Graph_KeyPoints)[:,3]])
Center = [(min(X) + max(X)) / 2, (min(Y) + max(Y)) / 2]
Unrotated_Graph = []
line_strings = []
for line1 in lines:
Ln = [(line1[0], line1[1]), (line1[2], line1[3])]
rotated_line = [rotate_point(point, 0, Center) for point in Ln]
Unrotated_Graph.append([rotated_line[0][0], rotated_line[0][1], rotated_line[1][0], rotated_line[1][1]])
line_strings.append(rotated_line)
# Combine the lines into a MultiLineString
multi_line = MultiLineString(line_strings)
# Rotate the MultiLineString around its centroid by the specified angle
#if Rotation_Angle != 0:
# multi_line = scale(multi_line, 1, -1)
return multi_line, Unrotated_Graph, Center
def Graph_Segments(graph):
Graph_mls, _, _ = MultiLineString_From_KeyPoints_Opti(graph)
Graph_mls_R = rotate(Graph_mls, 90, origin='centroid')
Graph_Polys = list(polygonize(Graph_mls_R))
Graph_Polygon = MultiPolygon(Graph_Polys)
Temp_Segments = [GP.exterior.coords[:] for GP in Graph_Polys]
Graph_Poly_Coords = []
for s in Temp_Segments:
for pnt in s:
Graph_Poly_Coords.append(pnt)
Poly_Up_Left_Point = np.array([np.min(np.array(Graph_Poly_Coords)[:,0]), np.max(np.array(Graph_Poly_Coords)[:,1])], dtype = int)
Graph_Up_Left_Point = np.array([np.min(np.vstack([graph[:,0], graph[:,2]])), np.max(np.vstack([graph[:,1], graph[:,3]]))], dtype = int)
Shift_Vector = Graph_Up_Left_Point - Poly_Up_Left_Point
Shifted_Graph_Polygon = translate(Graph_Polygon, xoff=Shift_Vector[0], yoff=Shift_Vector[1])
Segments = [np.array(GP.exterior.coords[:], dtype=int).tolist() for GP in Shifted_Graph_Polygon.geoms]
Roof_Seg_Areas = [GP.area for GP in Graph_Polys]
return Segments, Roof_Seg_Areas
def Points_on_Lines_Score(graph, max_value, curveness):
GRPH = graph.reshape([graph.shape[0], 2, 2])
P1 = GRPH[:,0,:]
P2 = GRPH[:,1,:]
All_Points = np.vstack([P1, P2])
Graph_Nodes = np.array([list(x) for x in set(tuple(x) for x in All_Points)])
Line_Vectors = P2 - P1
Other_Lines_Vector = Graph_Nodes[np.newaxis, :, :] - P1[:, np.newaxis, :]
Other_Lines_lengths = np.linalg.norm(Other_Lines_Vector, axis=2)
Other_Lines_lengths = np.repeat(Other_Lines_lengths[:, :, np.newaxis], 2, axis=2)
small_value = 1e-10
Other_Lines_lengths = np.where(Other_Lines_lengths == 0, small_value, Other_Lines_lengths)
dx = graph[:, 2] - graph[:, 0]
dy = graph[:, 3] - graph[:, 1]
Lines_Length = np.sqrt(dx**2 + dy**2)
Lines_Normal_Vector = Line_Vectors / np.vstack([Lines_Length, Lines_Length]).T
Other_Lines_Normal_Vector = Other_Lines_Vector / Other_Lines_lengths
for i, OLNV in enumerate(Other_Lines_Normal_Vector):
for j, V in enumerate(OLNV):
if V.tolist() == [0, 0]:
Other_Lines_Normal_Vector[i, j] = Lines_Normal_Vector[i]
dot_products = np.clip(np.abs(np.sum(Lines_Normal_Vector[:, np.newaxis, :] * Other_Lines_Normal_Vector, axis=2)), 0, 1)
dot_products[dot_products < 0.9] = 0
Pre_Score = custom_Point_on_Line_function(dot_products, max_value, curveness)
Lines_Score = Pre_Score.mean(axis = 1)
Score = Lines_Score.mean()
return Score
def Points_on_Lines_Score_GA(graph):
GRPH = graph.reshape([graph.shape[0], 2, 2])
P1 = GRPH[:,0,:]
P2 = GRPH[:,1,:]
All_Points = np.vstack([P1, P2])
Graph_Nodes = np.array([list(x) for x in set(tuple(x) for x in All_Points)])
Line_Vectors = P2 - P1
Other_Lines_Vector = Graph_Nodes[np.newaxis, :, :] - P1[:, np.newaxis, :]
Other_Lines_lengths = np.linalg.norm(Other_Lines_Vector, axis=2)
Other_Lines_lengths = np.repeat(Other_Lines_lengths[:, :, np.newaxis], 2, axis=2)
small_value = 1e-10
Other_Lines_lengths = np.where(Other_Lines_lengths == 0, small_value, Other_Lines_lengths)
dx = graph[:, 2] - graph[:, 0]
dy = graph[:, 3] - graph[:, 1]
Lines_Length = np.sqrt(dx**2 + dy**2)
Lines_Normal_Vector = Line_Vectors / np.vstack([Lines_Length, Lines_Length]).T
Other_Lines_Normal_Vector = Other_Lines_Vector / Other_Lines_lengths
for i, OLNV in enumerate(Other_Lines_Normal_Vector):
for j, V in enumerate(OLNV):
if V.tolist() == [0, 0]:
Other_Lines_Normal_Vector[i, j] = Lines_Normal_Vector[i]
dot_products = np.clip(np.abs(np.sum(Lines_Normal_Vector[:, np.newaxis, :] * Other_Lines_Normal_Vector, axis=2)), 0, 1)
dot_products[dot_products < 0.9] = 0
Pre_Score = custom_Point_on_Line_function_GA(dot_products)
Lines_Score = Pre_Score.mean(axis = 1)
Score = Lines_Score.mean()
return Score
def calculate_normal_vector(x1, y1, x2, y2):
# Calculate the direction vector of the line
dx, dy = x2 - x1, y2 - y1
# The normal vector is perpendicular to the direction vector
Line_vector = np.array([dx, dy])
Line_Length = np.sqrt(dx**2 + dy**2)
# Normalize the vector
normal_vector = Line_vector / Line_Length
return normal_vector
def perturb_point_by_normal(x, y, normal_vector, step_size):
# Move the point along the normal vector
return x + normal_vector[0] * step_size, y + normal_vector[1] * step_size
def update_matching_points(graph, old_point, new_point):
# Update all points in the graph that match old_point to new_point
for i in range(len(graph)):
for j in range(0, 4, 2): # Iterate over start and end points
if graph[i][j] == old_point[0] and graph[i][j+1] == old_point[1]:
graph[i][j], graph[i][j+1] = new_point
def update_matching_points_Segments(Segment, old_point, new_point):
# Update all points in the graph that match old_point to new_point
for i in range(len(Segment)):
if Segment[i][0] == old_point[0] and Segment[i][1] == old_point[1]:
Segment[i][0], Segment[i][1] = new_point
def optimize_graph_With_Weights(graph, weights, max_iterations=1000, step_size=1):
# Original_Segments, Original_Segments_Area = Graph_Segments(graph)
Original_Graph = graph.copy()
current_Fitness = Graph_Fitness(graph, weights[7], weights[8], weights[9], weights[10], weights[11], weights[10])
iteration = 0
improvement = True
Graphs = []
while improvement and iteration < max_iterations:
improvement = False
for i in range(len(graph)):
# Backup the original line
original_line = graph[i]
x1, y1, x2, y2 = original_line
x1_ORG, y1_ORG, x2_ORG, y2_ORG = Original_Graph[i]
Original_Lengths = Line_Length(Original_Graph)
Original_Line_Length = Line_Length(Original_Graph[i])
# Calculate the normal vector for the line
normal_vector = calculate_normal_vector(x1, y1, x2, y2)
# four possible perturbations:
perturbations = []
# 1. Start point moves in the direction of the normal vector, end point stays
perturbations.append((
perturb_point_by_normal(x1, y1, normal_vector, step_size),
(x2, y2)
))
# 2. Start point moves in the opposite direction of the normal vector, end point stays
perturbations.append((
perturb_point_by_normal(x1, y1, -normal_vector, step_size),
(x2, y2)
))
# 3. Start point stays, end point moves in the direction of the normal vector
perturbations.append((
(x1, y1),
perturb_point_by_normal(x2, y2, normal_vector, step_size)
))
# 4. Start point stays, end point moves in the opposite direction of the normal vector
perturbations.append((
(x1, y1),
perturb_point_by_normal(x2, y2, -normal_vector, step_size)
))
# 5. Start and End points moves in the direction of the normal vector
perturbations.append((
perturb_point_by_normal(x1, y1, normal_vector, step_size),
perturb_point_by_normal(x2, y2, normal_vector, step_size)
))
# 6. Start and End points moves in the opposite direction of the normal vector
perturbations.append((
perturb_point_by_normal(x1, y1, -normal_vector, step_size),
perturb_point_by_normal(x2, y2, -normal_vector, step_size)
))
# 7. Start point moves in the opposite direction, end point moves in the direction of the normal vector
perturbations.append((
perturb_point_by_normal(x1, y1, -normal_vector, step_size),
perturb_point_by_normal(x2, y2, normal_vector, step_size)
))
# 8. Start point moves in the direction, end point moves in the opposite direction of the normal vector
perturbations.append((
perturb_point_by_normal(x1, y1, normal_vector, step_size),
perturb_point_by_normal(x2, y2, -normal_vector, step_size)
))
# Evaluate all perturbations
Fitnesses = []
graphs = []
Point_Move_Penalty = []
for start_point, end_point in perturbations:
# Create a copy of the graph to modify
new_graph = graph.copy()
# Update matching points in the copy
update_matching_points(new_graph, (x1, y1), start_point)
update_matching_points(new_graph, (x2, y2), end_point)
#Node Movement Check
Distance_start = calculate_distance(start_point, [x1_ORG, y1_ORG])
Length_Start = Line_Length([start_point[0], start_point[1], x2_ORG, y2_ORG])
Strat_Move_Ratio = min([Original_Line_Length, Length_Start]) / max([Original_Line_Length, Length_Start])
Penalty_start = custom_Penalty_Function(Distance_start, weights[19], weights[20])
Distance_end = calculate_distance(end_point, [x2_ORG, y2_ORG])
Length_end = Line_Length([x1_ORG, y1_ORG, end_point[0], end_point[1]])
end_Move_Ratio = min([Original_Line_Length, Length_end]) / max([Original_Line_Length, Length_end])
Penalty_end = custom_Penalty_Function(Distance_end, weights[19], weights[20])
Point_Move_Penalty.append(Penalty_start + Penalty_end)
graphs.append(new_graph)
Modified_Lengths = list(map(Line_Length, graphs))
Lenght_Change_Ratios = [1 - (Modified_Length / Original_Lengths) for Modified_Length in Modified_Lengths]
Lengths_W_max = (np.ones([len(Lenght_Change_Ratios)]) * weights[25]).tolist()
Lengths_W_Caurve = (np.ones([len(Lenght_Change_Ratios)]) * weights[26]).tolist()
Length_Penalties = np.array(list(map(custom_Line_Length_Penalty_function, Lenght_Change_Ratios, Lengths_W_max, Lengths_W_Caurve)))
Length_Penalty = np.mean(Length_Penalties, axis = 1)
# Calculate the fitness for this perturbation
Angle_W_30 = (np.ones([len(graphs)]) * weights[7]).tolist()
Angle_W_45 = (np.ones([len(graphs)]) * weights[8]).tolist()
Angle_W_60 = (np.ones([len(graphs)]) * weights[9]).tolist()
Angle_W_90 = (np.ones([len(graphs)]) * weights[10]).tolist()
Angle_W_180 = (np.ones([len(graphs)]) * weights[11]).tolist()
Angle_W_caurve = (np.ones([len(graphs)]) * weights[12]).tolist()
Fitness_Angle = np.array(list(map(Graph_Fitness, graphs, Angle_W_30, Angle_W_45, Angle_W_60, Angle_W_90, Angle_W_180, Angle_W_caurve))) # Angle Between Lines
Straight_W_0 = (np.ones([len(graphs)]) * weights[13]).tolist()
Straight_W_90 = (np.ones([len(graphs)]) * weights[14]).tolist()
Straight_W_180 = (np.ones([len(graphs)]) * weights[15]).tolist()
Straight_W_270 = (np.ones([len(graphs)]) * weights[16]).tolist()
Straight_W_360 = (np.ones([len(graphs)]) * weights[17]).tolist()
Straight_W_caurve = (np.ones([len(graphs)]) * weights[18]).tolist()
Fitness_Straight_Lines = np.array(list(map(Graph_Fitness_Straight_Lines, graphs, Straight_W_0, Straight_W_90, Straight_W_180, Straight_W_270, Straight_W_360, Straight_W_caurve))) # Straight Lines
PoL_W_max = (np.ones([len(graphs)]) * weights[27]).tolist()
PoL_W_caurve = (np.ones([len(graphs)]) * weights[28]).tolist()
PoL_Score = np.array(list(map(Points_on_Lines_Score, graphs, PoL_W_max, PoL_W_caurve)))
# Lines
Similarity_Lines_W_max = (np.ones([len(graphs)]) * weights[21]).tolist()
Similarity_Lines_W_caurve = (np.ones([len(graphs)]) * weights[22]).tolist()
Similarity_Lines_score = np.array(list(map(Graph_Lines_Similarity, graphs, Similarity_Lines_W_max, Similarity_Lines_W_caurve)))
# Angles
Similarity_Angles_W_max = (np.ones([len(graphs)]) * weights[23]).tolist()
Similarity_Angles_W_caurve = (np.ones([len(graphs)]) * weights[24]).tolist()
Similarity_Angles_score = np.array(list(map(Graph_Angle_Similarity, graphs, Similarity_Angles_W_max, Similarity_Angles_W_caurve)))
Point_Move_Penalty = np.array(Point_Move_Penalty)
Fitness_Angle = Fitness_Angle * weights[0]
Fitness_Straight_Lines = Fitness_Straight_Lines * weights[1]
Point_Move_Penalty = Point_Move_Penalty * weights[2]
Similarity_Lines_score = Similarity_Lines_score * weights[3]
Similarity_Angles_score = Similarity_Angles_score * weights[4]
Length_Penalty = Length_Penalty * weights[5]
PoL_Score = PoL_Score * weights[6]
Fitnesses = Fitness_Angle + Fitness_Straight_Lines - Point_Move_Penalty + Similarity_Lines_score + Similarity_Angles_score - Length_Penalty + PoL_Score
# Find the maximum fitness scenario
max_fitness_index = np.argmax(Fitnesses)
max_fitness = Fitnesses[max_fitness_index]
if max_fitness > current_Fitness:
# Apply the best perturbation to the actual graph
graph = graphs[max_fitness_index]
Graphs.append(graph)
current_Fitness = max_fitness
improvement = True
else:
graph[i] = original_line # Revert to original if no improvement
iteration += 1
return graph
def Weight_CSV_Extraction(Weights, File_Name):
"""
Function to extract 2D graph with into CSV file
Inputs:
Graph_2D_type: List of polygons with is lines and line types
Outputs:
CSV file of graph lines
"""
# field names
fields = ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'max_Move', 'max_Length', 'max_Angle', 'max_Straight', 'max_PoL', 'max_Sim_Lines', 'max_Sim_Angles']
with open(File_Name, 'w') as f:
write = csv.writer(f)
write.writerow(fields)
write.writerows(Weights)
f.close()
# Define the weight ranges for each parameter
weight_ranges = [
(50.0, 100.0), # Range for angle fitness #0
(30.0, 100.0), # Range for straight lines #1
(0.1, 2.0), # Range for move penalty #2
(1.0, 20.0), # Range for similarity lines #3
(0.1, 20.0), # Range for similarity angles #4
(0.1, 2.0), # Range for length penalty #5
(1.0, 10.0), # Range for point on line #6