-
Notifications
You must be signed in to change notification settings - Fork 1
/
Etapa04.py
558 lines (446 loc) · 19.6 KB
/
Etapa04.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
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 21 08:24:20 2023
@author: Usuario
"""
import numpy as np
import matplotlib.pyplot as plt
import os
import math
# Get the current script's directory
script_dir = os.path.dirname(os.path.realpath(__file__))
# Specify the folder containing the text files
folder_name = 'S16'
#------------------------------------------------------------------------------------------------------------------
# WeightedGraph class
#------------------------------------------------------------------------------------------------------------------
class WeightedGraph:
"""
Class that is used to represent a weighted graph. Internally, the class uses an adjacency list to store
the vertices and edges of the graph. This adjacency list is defined by a dictionary, whose keys
represent the vertices. For each vertex, there is a list of tuples (v,e) that indicate which vertices
are connected to the vertex and their corresponding weights.
The graph can be directed or indirected. In the class constructor, this property is set. The
behaviour of some operations depends on this property.
This graph class assumes that it is possible to have multiple links between vertices.
"""
_directed = True # This flag indicates whether the graph is directed or indirected.
_adjacency_list = {} # The adjacency list of the graph.
def __init__(self, directed:bool = False):
"""
This constructor initializes an empty graph.
param directed: A flag that indicates whether the graph is directed (True) or undirected (False).
"""
self._directed = directed
self._adjacency_list = {}
def clear(self):
"""
This method clears the graph.
"""
self._adjacency_list = {}
def number_of_vertices(self):
"""
This method returns the number of vertices of the graph.
"""
return len(self._adjacency_list)
def vertices(self):
"""
This method returns the list of vertices.
"""
v = []
for vi in self._adjacency_list:
v.append(vi)
return v
def edges(self):
"""
This method returns the list of edges.
"""
e = []
if self._directed:
for v in self._adjacency_list:
for edge in self._adjacency_list[v]:
e.append((v, edge[0], edge[1]))
else:
for v in self._adjacency_list:
for edge in self._adjacency_list[v]:
if (edge[0], v, edge[1]) not in e:
e.append((v, edge[0], edge[1]))
return e
def add_vertex(self, v):
"""
Add vertex to the graph.
param v: The new vertex to be added to the graph.
"""
if v in self._adjacency_list:
print("Warning: Vertex ", v, " already exists.")
else:
self._adjacency_list[v] = []
def remove_vertex(self, v):
"""
Remove vertex from the graph.
param v: The vertex to be removed from the graph.
"""
if v not in self._adjacency_list:
print("Warning: Vertex ", v, " is not in graph.")
else:
# Remove vertex from adjacency list.
self._adjacency_list.remove(v)
# Remove edges where the vertex is an end point.
for vertex in self._adjacency_list:
for edge in self._adjacency_list[vertex]:
if edge[0] == v:
self._adjacency_list[vertex].remove(edge)
def add_edge(self, v1, v2, e = 0):
"""
Add edge to the graph. The edge is defined by two vertices v1 and v2, and
the weigth e of the edge.
param v1: The start vertex of the new edge.
param v2: The end vertex of the new edge.
param e: The weight of the new edge.
"""
if v1 not in self._adjacency_list:
# The start vertex does not exist.
print("Warning: Vertex ", v1, " does not exist.")
elif v2 not in self._adjacency_list:
# The end vertex does not exist.
print("Warning: Vertex ", v2, " does not exist.")
elif not self._directed and v1 == v2:
# The graph is undirected, so it is no allowed to have autocycles.
print("Warning: An undirected graph cannot have autocycles.")
elif (v2, e) in self._adjacency_list[v1]:
# The edge is already in graph.
# print("Warning: The edge (", v1, "," ,v2, ",", e, ") already exists.")
pass
else:
self._adjacency_list[v1].append((v2, e))
if not self._directed:
self._adjacency_list[v2].append((v1, e))
def remove_edge(self, v1, v2, e):
"""
Remove edge from the graph.
param v1: The start vertex of the edge to be removed.
param v2: The end vertex of the edge to be removed.
param e: The weight of the edge to be removed.
"""
if v1 not in self._adjacency_list:
# v1 is not a vertex of the graph
print("Warning: Vertex ", v1, " does not exist.")
elif v2 not in self._adjacency_list:
# v2 is not a vertex of the graph
print("Warning: Vertex ", v2, " does not exist.")
else:
for edge in self._adjacency_list[v1]:
if edge == (v2, e):
self._adjacency_list[v1].remove(edge)
if not self._directed:
for edge in self._adjacency_list[v2]:
if edge == (v1, e):
self._adjacency_list[v2].remove(edge)
def adjacent_vertices(self, v):
"""
Adjacent vertices of a vertex.
param v: The vertex whose adjacent vertices are to be returned.
return: The list of adjacent vertices of v.
"""
if v not in self._adjacency_list:
# The vertex is not in the graph.
print("Warning: Vertex ", v, " does not exist.")
return []
else:
return self._adjacency_list[v]
def is_adjacent(self, v1, v2) -> bool:
"""
This method indicates whether vertex v2 is adjacent to vertex v1.
param v1: The start vertex of the relation to test.
param v2: The end vertex of the relation to test.
return: True if v2 is adjacent to v1, False otherwise.
"""
if v1 not in self._adjacency_list:
# v1 is not a vertex of the graph
print("Warning: Vertex ", v1, " does not exist.")
return False
elif v2 not in self._adjacency_list:
# v2 is not a vertex of the graph
print("Warning: Vertex ", v2, " does not exist.")
return False
else:
for edge in self._adjacency_list[v1]:
if edge[0] == v2:
return True
return False
def print_graph(self):
"""
This method shows the edges of the graph.
"""
for vertex in self._adjacency_list:
for edges in self._adjacency_list[vertex]:
print(vertex, " -> ", edges[0], " edge weight: ", edges[1])
def KruskalMST(self):
"""
This method returns the minimum spanning tree of the graph using Kruskal's algorithm.
"""
# Array that will store the resulting MST
result = []
total_weight = 0
# Sort all the edges from result[] in non-decreasing order
edges = self.edges()
self.edges = sorted(edges, key=lambda item: item[2])
# Initialize sets of disjoint sets
parent = [i for i in range(self.number_of_vertices())]
# Find the set of an element
def find(i):
if parent[i] != i:
parent[i] = find(parent[i])
return parent[i]
# Joining two subsets
def union(i, j):
parent[find(i)] = find(j)
# Include minimum weight edges one by one
edge_count = 0
while edge_count < len(self.edges):
min_edge = self.edges[edge_count]
i = self.vertices().index(min_edge[0])
j = self.vertices().index(min_edge[1])
if find(i) != find(j):
result.append(min_edge)
total_weight += min_edge[2]
union(i, j)
edge_count += 1
else:
edge_count += 1
return result
#------------------------------------------------------------------------------------------------------------------
# Class TreeNode
#------------------------------------------------------------------------------------------------------------------
class TreeNode:
"""
Class that is used to represent a node in the search algorithm. A node contains the following elements:
* A reference to its parent.
* The vertex of the graph that is represented.
* The total path cost from the root to the node.
"""
def __init__(self, parent, v, c):
"""
This constructor initializes a node.
param parent: The node parent.
param v: The graph vertex that is represented by the node.
param c: The path cost to the node from the root.
"""
self.parent = parent
self.v = v
self.c = c
def __lt__(self, node):
"""
Operator <. This definition is requiered by the PriorityQueue class.
"""
return False;
# Method that calculates the distance between 2 points
def calc_distance(p1, p2):
distance = math.sqrt((p2[0]-p1[0])**2+(p2[1]-p1[1])**2+(p2[2]-p1[2])**2)
return distance
# Method that helps convex hull by calculating the angle orientation
def orientation(p1, p2, p3):
ori = (p2[0]-p1[0])*(p3[1]-p1[1])-(p2[1]-p1[1])*(p3[0]-p1[0])
if(ori >= 0):
return False
else:
return True
# Method that calculates the convex hull of points given
def convex_hull(points_names, points, color = 'b'):
x = -math.inf
y = math.inf
index = 0
cont = 0
for i in points:
if (i[1] < y):
y = i[1]
x = i[0]
index = cont
elif (i[1] == y):
if(i[0] > x):
y = i[1]
x = i[0]
index = cont
cont+=1
pivot = (x, y)
points_angles = []
cont = 0
for i in points:
if(cont!= index):
angle = math.degrees(math.atan2(i[1]-pivot[1], i[0]-pivot[0]))
points_angles.append((i[0], i[1], angle))
cont+=1
points_angles.sort(key = lambda a: a[2])
convex_points = []
convex_points.append(points_angles[-1])
convex_points.append((x, y, 0))
convex_points.append(points_angles[0])
i = 1
while(i < len(points_angles)-1):
if(orientation(convex_points[-1],
convex_points[-2],
points_angles[i])):
convex_points.append(points_angles[i])
i+=1
else:
convex_points.pop()
convex_points.append(convex_points[0])
print("----------------------------------")
print("The points of the convex hull are:")
for i in convex_points:
print(i)
for i in range(len(convex_points)-1):
plt.plot((convex_points[i][0], convex_points[i+1][0]),
(convex_points[i][1], convex_points[i+1][1]), color = color)
print("----------------------------------")
### --------------- Matriz de Conectividad Chica ------------------- ###
# Load connectivity matrices from text files
matrix1 = np.loadtxt(os.path.join(script_dir, folder_name, 'Lectura.txt'), dtype=int)
matrix2 = np.loadtxt(os.path.join(script_dir, folder_name, 'Memoria.txt'), dtype=int)
matrix3 = np.loadtxt(os.path.join(script_dir, folder_name, 'Operaciones.txt'), dtype=int)
# Create empty weighted graph
Graph1 = WeightedGraph(directed = False)
Graph2 = WeightedGraph(directed = False)
Graph3 = WeightedGraph(directed = False)
# Assuming matrices represent connections between channels
connectivity_matrices = [matrix1, matrix2, matrix3]
channels = ['Fz', 'C3', 'Cz', 'C4', 'Pz', 'PO7', 'Oz', 'PO8']
# Add channels to graph
for i in channels:
Graph1.add_vertex(i)
Graph2.add_vertex(i)
Graph3.add_vertex(i)
points3D = [[0, 0.71934, 0.694658], [-0.71934, 0, 0.694658], [0, 0, 1], [0.71934, 0, 0.694658],
[0, -0.71934, 0.694658], [-0.587427, -0.808524, -0.0348995], [0, -0.999391, -0.0348995],
[0.587427, -0.808524, -0.0348995]]
points3D = np.array(points3D)
r = np.sqrt(points3D[:, 0] ** 2 + points3D[:, 1] ** 2 + points3D[:, 2] ** 2)
t = r / (r + points3D[:, 2])
x = r * points3D[:, 0]
y = r * points3D[:, 1]
points2D = np.column_stack((x, y))
names = ["Lectura", "Memoria", "Operaciones"]
graphs = [Graph1, Graph2, Graph3]
# Plot one subplot for each matrix
for idx, matrix in enumerate(connectivity_matrices, start=1):
plt.subplot(1, len(connectivity_matrices), idx)
circle = plt.Circle((0, 0), 1, color='r', alpha=0.25, fill=False)
plt.scatter(points2D[:, 0], points2D[:, 1])
plt.gca().add_patch(circle)
for i in range(len(points2D)):
plt.text(points2D[i, 0] - 0.02, points2D[i, 1] + 0.025, channels[i])
# Plot connections based on the connectivity matrix
for i in range(len(channels)):
for j in range(len(channels)):
if matrix[i, j] == 1:
if(idx == 1):
Graph1.add_edge(channels[i], channels[j], calc_distance(points3D[i], points3D[j]))
if(idx == 2):
Graph2.add_edge(channels[i], channels[j], calc_distance(points3D[i], points3D[j]))
if(idx == 3):
Graph3.add_edge(channels[i], channels[j], calc_distance(points3D[i], points3D[j]))
points = []
final_points = []
if(idx == 1):
for edge in Graph1.KruskalMST():
if(edge[0] not in points):
points.append(edge[0])
if(edge[1] not in points):
points.append(edge[1])
if(idx == 2):
for edge in Graph2.KruskalMST():
if(edge[0] not in points):
points.append(edge[0])
if(edge[1] not in points):
points.append(edge[1])
if(idx == 3):
for edge in Graph3.KruskalMST():
if(edge[0] not in points):
points.append(edge[0])
if(edge[1] not in points):
points.append(edge[1])
for i in range(len(points)):
for j in range(len(channels)):
if(points[i] == channels[j]):
final_points.append(tuple(points2D[j]))
convex_hull(points,final_points)
plt.axis('equal')
plt.title(f'Casco convexo de {names[idx-1]}')
# Show the plot
plt.show()
# ### --------------- Matriz de Conectividad Grande ------------------- ###
print("-----------------")
print("Matriz de conectividad de 32")
# Specify the folder containing the text files
folder_name = 'S0A'
# Load connectivity matrices from text files
matrix1 = np.loadtxt(os.path.join(script_dir, folder_name, 'Lectura.txt'), dtype=int)
matrix2 = np.loadtxt(os.path.join(script_dir, folder_name, 'Memoria.txt'), dtype=int)
matrix3 = np.loadtxt(os.path.join(script_dir, folder_name, 'Operaciones.txt'), dtype=int)
# Create empty weighted graph
Graph1 = WeightedGraph(directed = False)
Graph2 = WeightedGraph(directed = False)
Graph3 = WeightedGraph(directed = False)
# Assuming matrices represent connections between channels
connectivity_matrices = [matrix1, matrix2, matrix3]
channels = ['Fp1','Fp2', 'AF3', 'AF4', 'F7', 'F3', 'Fz', 'F4', 'F8', 'FC5', 'FC1', 'FC2', 'FC6', 'T7', 'C3', 'Cz', 'C4', 'T8', 'CP5', 'CP1', 'CP2', 'CP6', 'P7', 'P3', 'Pz', 'P4', 'P8', 'PO3', 'PO4', 'O1', 'Oz', 'O2']
for i in channels:
Graph1.add_vertex(i)
Graph2.add_vertex(i)
Graph3.add_vertex(i)
points3D = [[-0.308829,0.950477,-0.0348995], [0.308829,0.950477,-0.0348995], [-0.406247,0.871199,0.275637], [0.406247,0.871199,0.275637], [-0.808524,0.587427,-0.0348995], [-0.545007,0.673028,0.5], [0,0.71934,0.694658], [0.545007,0.673028,0.5], [0.808524,0.587427,-0.0348995], [-0.887888,0.340828,0.309017], [-0.37471,0.37471,0.848048], [0.37471,0.37471,0.848048], [0.887888,0.340828,0.309017], [-0.999391,0,-0.0348995], [-0.71934,0,0.694658], [0,0,1], [0.71934,0,0.694658], [0.999391,0,-0.0348995], [-0.887888,-0.340828,0.309017], [-0.37471,-0.37471,0.848048], [0.37471,-0.37471, 0.848048], [0.887888,-0.340828,0.309017], [-0.808524,-0.587427,-0.0348995], [-0.545007,-0.673028,0.5], [0,-0.71934,0.694658], [0.545007,-0.673028,0.5], [0.808524,-0.587427,-0.0348995], [-0.406247,-0.871199,0.275637], [0.406247,-0.871199,0.275637], [-0.308829,-0.950477,-0.0348995], [0,-0.999391,-0.0348995], [0.308829,-0.950477,-0.0348995]]
points3D = np.array(points3D)
r = np.sqrt(points3D[:, 0] ** 2 + points3D[:, 1] ** 2 + points3D[:, 2] ** 2)
t = r / (r + points3D[:, 2])
x = r * points3D[:, 0]
y = r * points3D[:, 1]
points2D = np.column_stack((x, y))
names = ["Lectura", "Memoria", "Operaciones"]
graphs = [Graph1, Graph2, Graph3]
# Plot one subplot for each matrix
for idx, matrix in enumerate(connectivity_matrices, start=1):
plt.subplot(1, len(connectivity_matrices), idx)
circle = plt.Circle((0, 0), 1, color='r', alpha=0.25, fill=False)
plt.scatter(points2D[:, 0], points2D[:, 1])
plt.gca().add_patch(circle)
for i in range(len(points2D)):
plt.text(points2D[i, 0] - 0.02, points2D[i, 1] + 0.025, channels[i])
# Plot connections based on the connectivity matrix
for i in range(len(channels)):
for j in range(len(channels)):
if matrix[i, j] == 1:
if(idx == 1):
Graph1.add_edge(channels[i], channels[j], calc_distance(points3D[i], points3D[j]))
if(idx == 2):
Graph2.add_edge(channels[i], channels[j], calc_distance(points3D[i], points3D[j]))
if(idx == 3):
Graph3.add_edge(channels[i], channels[j], calc_distance(points3D[i], points3D[j]))
points = []
final_points = []
if(idx == 1):
for edge in Graph1.KruskalMST():
if(edge[0] not in points):
points.append(edge[0])
if(edge[1] not in points):
points.append(edge[1])
if(idx == 2):
for edge in Graph2.KruskalMST():
if(edge[0] not in points):
points.append(edge[0])
if(edge[1] not in points):
points.append(edge[1])
if(idx == 3):
for edge in Graph3.KruskalMST():
if(edge[0] not in points):
points.append(edge[0])
if(edge[1] not in points):
points.append(edge[1])
for i in range(len(points)):
for j in range(len(channels)):
if(points[i] == channels[j]):
final_points.append(tuple(points2D[j]))
convex_hull(points,final_points)
plt.axis('equal')
plt.title(f'Casco convexo de {names[idx-1]}')
# Show the plot
plt.show()