cachai 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cachai/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from . import data
2
+ from . import tests
3
+ from cachai.tests._run_test import run_tests, get_available_tests
4
+
5
+ __all__ = ['run_tests','get_available_tests']
cachai/__main__.py ADDED
@@ -0,0 +1,45 @@
1
+ import sys
2
+ import argparse
3
+ from cachai.tests._run_test import run_tests
4
+
5
+ def main():
6
+ parser = argparse.ArgumentParser(
7
+ description='Run the tests from CACHAI',
8
+ usage='%(prog)s [OPTIONS] [TESTS...]'
9
+ )
10
+
11
+ # For specific tests
12
+ parser.add_argument(
13
+ 'tests',
14
+ nargs='*',
15
+ default=[],
16
+ help="Names of the tests to run (e.g. 'charts', 'utilities'). If not specified, all tests are run."
17
+ )
18
+
19
+ # Option to show details
20
+ parser.add_argument(
21
+ '-v', '--verbose',
22
+ action='store_true',
23
+ help='Mostrar output detallado (equivalente a pytest -v)'
24
+ )
25
+
26
+ # Option to show available tests
27
+ parser.add_argument(
28
+ '-l', '--list',
29
+ action='store_true',
30
+ help='List all available tests without running them'
31
+ )
32
+
33
+ args = parser.parse_args()
34
+
35
+ if args.list:
36
+ from cachai.tests._run_test import get_available_tests
37
+ print('Available tests:')
38
+ for test in get_available_tests():
39
+ print(f' {test}')
40
+ sys.exit(0)
41
+
42
+ sys.exit(run_tests(*args.tests))
43
+
44
+ if __name__ == '__main__':
45
+ main()
cachai/_core/chord.py ADDED
@@ -0,0 +1,592 @@
1
+ # Basic imports
2
+ import numpy as np
3
+ import pandas as pd
4
+ import seaborn as sns
5
+ from cachai import utilities as util
6
+ from cachai import gadgets
7
+ # Matplotlib imports
8
+ from matplotlib import pyplot as plt
9
+ from matplotlib.patches import Arc, Circle, PathPatch
10
+ from matplotlib.path import Path
11
+ import matplotlib.colors as mtpl_colors
12
+ from matplotlib.text import Text
13
+
14
+
15
+ class ChordDiagram():
16
+ def __init__(self, corr_matrix, **kwargs):
17
+ """
18
+ Initialize a ChordDiagram visualization.
19
+ """
20
+ # Correlation matrix error handling
21
+ self.corr_matrix = corr_matrix
22
+ self._validate_corr_matrix()
23
+
24
+ # Initialize additional parameters
25
+ self.__dict__.update(kwargs)
26
+ if isinstance(self.corr_matrix, pd.DataFrame):
27
+ if self.names is None: self.names = self.corr_matrix.columns.tolist()
28
+ self.corr_matrix = self.corr_matrix.to_numpy()
29
+ if self.names is None: self.names = [f'N{i+1}' for i in range(len(self.corr_matrix))]
30
+ if self.colors is None: self.colors = sns.hls_palette(len(self.corr_matrix))
31
+ self.nodes = dict()
32
+ self.order = [i for i in range(len(self.corr_matrix))]
33
+ self.global_indexes = []
34
+ if self.font is None: self.font = {'size':self.fontsize}
35
+
36
+ # Initialize collection lists
37
+ self.node_patches = []
38
+ self.node_labels = []
39
+ self.node_labels_params = []
40
+ self.chord_patches = [[] for i in range(len(self.corr_matrix))]
41
+ self.chord_blends = [[] for i in range(len(self.corr_matrix))]
42
+ self.bezier_curves = [[] for i in range(len(self.corr_matrix))]
43
+ self.__ports_refs = []
44
+ self.__highlighted_ports = []
45
+
46
+ # Generate the diagram
47
+ self.__generate_diagram()
48
+
49
+
50
+ # Util methods
51
+ def _validate_corr_matrix(self):
52
+ """Validate that a correlation matrix meets the required specifications:
53
+ - Input is a numpy.ndarray or pandas.DataFrame
54
+ - Matrix is 2-dimensional
55
+ - Matrix is not empty
56
+ - All values are int or float
57
+ - Matrix is symmetric
58
+ """
59
+ temp_corr_matrix = self.corr_matrix
60
+ if not isinstance(temp_corr_matrix, (np.ndarray, pd.DataFrame)):
61
+ raise TypeError('Your correlation matrix must be a numpy.ndarray or pandas.DataFrame')
62
+ # -- This block of code should not be here, but its necessary for the next validations --
63
+ if isinstance(temp_corr_matrix, pd.DataFrame):
64
+ temp_corr_matrix = self.corr_matrix.to_numpy()
65
+ # ---------------------------------------------------------------------------------------
66
+ if temp_corr_matrix.ndim != 2:
67
+ raise ValueError('Your correlation matrix must be a 2-dimensional array')
68
+ if temp_corr_matrix.shape[0] != temp_corr_matrix.shape[1]:
69
+ raise ValueError('Your correlation matrix must be a square matrix.')
70
+ if len(temp_corr_matrix) == 0:
71
+ raise ValueError('Your correlation matrix cannot be empty')
72
+ if not np.issubdtype(temp_corr_matrix.dtype, np.floating):
73
+ raise TypeError('Your correlation matrix must contain float values')
74
+ if not np.allclose(temp_corr_matrix, temp_corr_matrix.T):
75
+ raise ValueError('Your correlation matrix must be symmetric')
76
+
77
+ def _optimize_nodes(self):
78
+ """Optimize node order using Prim's algorithm."""
79
+ n_nodes = self.corr_matrix.shape[0]
80
+ # We convert the correlations to distances
81
+ # The strongest the correlation, the shorter the distance
82
+ distance_matrix = 1 - np.abs(self.corr_matrix)
83
+ # In order to ignore the diagonal, we fill it with infinity values
84
+ np.fill_diagonal(distance_matrix, np.inf)
85
+
86
+ # Prim's algorithm
87
+ visited = set()
88
+ order = []
89
+
90
+ start_node = np.argmin(np.sum(distance_matrix, axis=0))
91
+ visited.add(start_node)
92
+ order.append(start_node)
93
+
94
+ while len(visited) < n_nodes:
95
+ # Closest non-visited node to any visited node
96
+ min_dist = np.inf
97
+ next_node = -1
98
+ for node in visited:
99
+ for neighbor in range(n_nodes):
100
+ if (neighbor not in visited) and (distance_matrix[node,neighbor] < min_dist):
101
+ min_dist = distance_matrix[node, neighbor]
102
+ next_node = neighbor
103
+ if next_node == -1:
104
+ break # Just in case somehow we have disconnected nodes
105
+ visited.add(next_node)
106
+ order.append(next_node)
107
+
108
+ # Apply new order
109
+ self.order = order
110
+ self.__order_nodes()
111
+
112
+ def _radius_rule(self, dist):
113
+ """Rule to set the radius of a single chord"""
114
+ if dist <= self.min_dist:
115
+ return self.max_rho_radius
116
+ else:
117
+ return self.max_rho_radius * (1 - (dist - self.min_dist) / (np.pi - self.min_dist))
118
+
119
+ def _scale_rho(self, rho):
120
+ """Scale rho (link thickness)"""
121
+ if self.scale == 'linear':
122
+ rho_lin = np.abs(rho) * self.max_rho
123
+ return np.clip(rho_lin, 0, 1) # Clip to avoid numerical issues
124
+ elif self.scale == 'log':
125
+ rho_log = (1 - np.log10(10 - 9*np.abs(rho))) * self.max_rho
126
+ return np.clip(rho_log, 0, 1) # Clip to avoid numerical issues
127
+ else:
128
+ raise ValueError(f'Unknown scale type {self.scale}')
129
+
130
+ # Main generation methods
131
+ def __generate_diagram(self):
132
+ """Generate the complete chord diagram"""
133
+
134
+ for i,color in enumerate(self.colors):
135
+ if isinstance(color,str): self.colors[i] = mtpl_colors.to_rgb(color)
136
+
137
+ if self.filter == True: self.__filter_nodes()
138
+
139
+ if len(self.corr_matrix) == 0:
140
+ raise ValueError(f'No nodes remaining after threshold filtering: '
141
+ f'all correlations were below the threshold = {self.threshold}.')
142
+ else:
143
+ if self.optimize == True: self._optimize_nodes()
144
+ self.__generate_nodes()
145
+ self.__generate_chords()
146
+
147
+ # Add patches to axes
148
+ for node_patch, node_label in zip(self.node_patches, self.node_labels_params):
149
+ self.ax.add_patch(node_patch)
150
+ label = gadgets.PolarText(self.position,
151
+ node_label['r'],
152
+ node_label['theta'],
153
+ text=node_label['label'],
154
+ pad=self.node_labelpad,
155
+ rotation=node_label['rot'],
156
+ ha='center', va='center',
157
+ clip_on=True,
158
+ rasterized=self.rasterized)
159
+ label.set_font(self.font)
160
+ self.ax.add_artist(label)
161
+ self.node_labels.append(label)
162
+ flat_chord_patches = [p for plist in self.chord_patches for p in plist]
163
+ flat_bezier_curves = [c for clist in self.bezier_curves for c in clist]
164
+ for k,(chord_patch,bezier_curve) in enumerate(zip(flat_chord_patches,flat_bezier_curves)):
165
+ self.ax.add_patch(chord_patch)
166
+ if self.blend:
167
+ self.__add_chord_blend(chord_patch,bezier_curve,self.global_indexes[k])
168
+
169
+ self.__adjust_ax()
170
+ self.__generate_legend()
171
+ self.__generate_port_refs()
172
+
173
+ # Components generation methods
174
+ def __generate_nodes(self):
175
+ """Generate nodes"""
176
+ # Initial variables
177
+ # Minus 1 from each diagonal of A to A
178
+ relevance = np.sum(np.abs(self.corr_matrix),axis=1) - 1
179
+ relevance_norm = relevance / np.sum(relevance)
180
+ start_angles = np.cumsum([0] + list(2*np.pi*relevance_norm[:-1]))
181
+ gap_angle = (2*np.pi/len(self.corr_matrix))*self.node_gap
182
+
183
+ # Base patch
184
+ self.ax.add_patch(Circle(self.position,self.radius,
185
+ lw=0,
186
+ zorder=2,
187
+ fc='w',
188
+ ec='none',
189
+ rasterized=self.rasterized))
190
+
191
+ lw = 2*self.node_linewidth
192
+
193
+ for node in range(len(self.corr_matrix)):
194
+ node_data = dict()
195
+ theta_i = start_angles[node]
196
+ theta_f = theta_i + 2*np.pi*relevance_norm[node]
197
+ # -- Gap correction -----
198
+ theta_i = theta_i + np.min([gap_angle,theta_f])
199
+ # -----------------------
200
+ theta_m = (theta_i + theta_f)/2
201
+ theta_arc = util.angdist(theta_i,theta_f)
202
+ node_data['theta_i'] = theta_i
203
+ node_data['theta_f'] = theta_f
204
+ node_data['theta_m'] = theta_m
205
+ node_data['theta_arc'] = theta_arc
206
+
207
+ rhos = dict() # Correlations
208
+ ports = dict() # Ports of the node
209
+ states = dict() # Ports states (1 or -1)
210
+ corr = np.insert(self.corr_matrix[node],node,1)
211
+ real_corr = corr.copy()
212
+ # Control of the allowed ports using the correlation factor
213
+ # 1 = Allowed
214
+ # -1 = Forbidden
215
+ node_ports_state = [1 for p in range(len(corr))]
216
+ for p,r in enumerate(corr):
217
+ if np.abs(r) < self.threshold:
218
+ node_ports_state[p] = -1
219
+ real_corr[p] = 0
220
+ if not self.show_diag:
221
+ node_ports_state[node] = -1
222
+ real_corr[node] = 0
223
+ node_ports_state[node+1] = -1
224
+ real_corr[node+1] = 0
225
+ if np.sum(real_corr) == 0: corr_norm = real_corr
226
+ else: corr_norm = np.abs(real_corr)/np.sum(np.abs(real_corr))
227
+
228
+ for j,(rho,port_size,port_state) in enumerate(zip(corr,corr_norm,node_ports_state)):
229
+ if j == node : port_id = node
230
+ elif j == (node+1) : port_id = f'{node}*'
231
+ else:
232
+ if j < node: port_id = j
233
+ elif j > node: port_id = j-1
234
+ port_i = theta_i + theta_arc*np.sum(corr_norm[:j])
235
+ port_f = port_i + theta_arc*port_size
236
+ if port_state < 0:
237
+ port_i = 0
238
+ port_f = 0
239
+ rhos[port_id] = rho
240
+ ports[port_id] = {'i':port_i,'f':port_f}
241
+ states[port_id] = port_state
242
+
243
+ node_data['rhos'] = rhos
244
+ node_data['ports'] = ports
245
+ node_data['ports_state'] = states
246
+ self.nodes[node] = node_data
247
+
248
+ # Node
249
+ for n in self.nodes:
250
+ node = self.nodes[n]
251
+
252
+ # Patch
253
+ self.node_patches.append(
254
+ Arc(self.position,
255
+ width=2*self.radius,
256
+ height=2*self.radius,
257
+ theta1=np.rad2deg(node['theta_i']),
258
+ theta2=np.rad2deg(node['theta_f']),
259
+ lw=lw,zorder=1,
260
+ rasterized=self.rasterized,
261
+ color=self.colors[n])
262
+ )
263
+
264
+ # Label
265
+ params = dict()
266
+ params['label'] = self.names[n]
267
+ params['r'] = self.radius
268
+ params['theta'] = node['theta_m']
269
+ params['x'] = params['r'] * np.cos(params['theta']) + self.position[0]
270
+ params['y'] = params['r'] * np.sin(params['theta']) + self.position[1]
271
+ params['rot'] = np.rad2deg(node['theta_m'] - np.sign(params['y']-self.position[1])*np.pi/2)%360
272
+ self.node_labels_params.append(params)
273
+
274
+ def __generate_chords(self):
275
+ """Generate chords"""
276
+ for n in self.nodes:
277
+ node = self.nodes[n]
278
+ chord_color = self.colors[n]
279
+ chord_edge = util.mod_color(self.colors[n],light=0.5)
280
+ if self.blend:
281
+ chord_color = 'none'
282
+ chord_edge = '#3D3D3D'
283
+
284
+ # Links
285
+ if self.show_diag:
286
+ points,codes,curve = self.__compute_bezier_curves(
287
+ (node['ports'][n]['i'],node['ports'][n]['f']),
288
+ (node['ports'][f'{n}*']['i'],node['ports'][f'{n}*']['f']),
289
+ self._scale_rho(1)
290
+ )
291
+
292
+ self.chord_patches[n].append(
293
+ PathPatch(Path(points, codes),
294
+ facecolor=chord_color,
295
+ edgecolor=chord_edge,
296
+ alpha=self.chord_alpha,
297
+ hatch=self.positive_hatch,
298
+ lw=self.chord_linewidth,
299
+ rasterized=self.rasterized,
300
+ zorder=4)
301
+ )
302
+ curve['c1'] = self.colors[n]
303
+ curve['c2'] = self.colors[n]
304
+ self.bezier_curves[n].append(curve)
305
+ self.global_indexes.append(n)
306
+
307
+ for m in self.nodes:
308
+ if m > n and node['ports_state'][m] > 0:
309
+ try:
310
+ target = self.nodes[m]
311
+ this_rho = node['rhos'][m]
312
+ vis_rho = self._scale_rho(this_rho)
313
+ hatch = self.positive_hatch
314
+ if this_rho < 0: hatch = self.negative_hatch
315
+
316
+ points,codes,curve = self.__compute_bezier_curves(
317
+ (node['ports'][m]['i'],node['ports'][m]['f']),
318
+ (target['ports'][n]['i'],target['ports'][n]['f']),
319
+ vis_rho
320
+ )
321
+
322
+ self.chord_patches[n].append(
323
+ PathPatch(Path(points, codes),
324
+ facecolor=chord_color,
325
+ edgecolor=chord_edge,
326
+ alpha=self.chord_alpha,
327
+ hatch=hatch,
328
+ lw=self.chord_linewidth,
329
+ rasterized=self.rasterized,
330
+ zorder=4)
331
+ )
332
+ curve['c1'] = self.colors[n]
333
+ curve['c2'] = self.colors[m]
334
+ self.bezier_curves[n].append(curve)
335
+ self.global_indexes.append(n)
336
+
337
+ except Exception as e:
338
+ print(util.textco(rf'ChordError: Problem creating chord from {self.names[n]} to {self.names[m]}.',
339
+ c='red'))
340
+ print(util.textco(f' details: {e}',
341
+ c='red'))
342
+
343
+ def __generate_legend(self):
344
+ """Add dummie labels to show in the legend"""
345
+ if self.legend is True:
346
+ if self.positive_label is None: self.positive_label = 'Positive\ncorrelation'
347
+ if self.negative_label is None: self.negative_label = 'Negative\ncorrelation'
348
+ # Dummies
349
+ if self.positive_label is not None:
350
+ dummy = self.ax.scatter(*self.position,marker='s',s=200,
351
+ c='lightgray',ec='k',hatch=self.positive_hatch,
352
+ label=self.positive_label,zorder=0,rasterized=True)
353
+ #dummy.set_visible(False)
354
+ if self.negative_label is not None:
355
+ dummy = self.ax.scatter(*self.position,marker='s',s=200,
356
+ c='lightgray',ec='k',hatch=self.negative_hatch,
357
+ label=self.negative_label,zorder=0,rasterized=True)
358
+ #dummy.set_visible(False)
359
+
360
+ def __generate_port_refs(self):
361
+ for n in self.nodes:
362
+ self.__ports_refs.append(self.__get_node_ports_references(n))
363
+
364
+ # Helper methods
365
+ def __filter_nodes(self):
366
+ """Remove nodes with no correlation (0 chords)"""
367
+ mask = np.all((np.abs(self.corr_matrix) < self.threshold)\
368
+ | (np.eye(self.corr_matrix.shape[0], dtype=bool)), axis=1)
369
+ indexes = np.where(~mask)[0]
370
+
371
+ self.corr_matrix = self.corr_matrix[indexes][:, indexes]
372
+ self.names = [self.names[i] for i in indexes]
373
+ self.colors = [self.colors[i] for i in indexes]
374
+
375
+ def __order_nodes(self):
376
+ """Order nodes (matrix), names and colors"""
377
+ self.corr_matrix = self.corr_matrix[np.ix_(self.order, self.order)]
378
+ self.names = [self.names[i] for i in self.order]
379
+ self.colors = [self.colors[i] for i in self.order]
380
+
381
+ def __compute_bezier_curves(self,alpha,beta,rho):
382
+ """Compute bezier curves to modelate a chord"""
383
+ # Polar
384
+ alpha_i, alpha_f = alpha
385
+ alpha_m = np.mean([alpha_f,alpha_i])
386
+ alphas = util.angspace(alpha_i,alpha_f)
387
+ if len(alphas) == 0: alphas = np.array([alpha_i,alpha_f]) # Case: angdist too short
388
+
389
+ beta_i, beta_f = beta
390
+ beta_m = np.mean([beta_f,beta_i])
391
+ betas = util.angspace(beta_i,beta_f)
392
+ if len(betas) == 0: betas = np.array([beta_i,beta_f]) # Case: angdist too short
393
+
394
+ dist = util.angdist(alpha_m, beta_m)
395
+ r_rho = self._radius_rule(dist) * self.radius
396
+ dist_inex = np.min([util.angdist(alpha_i, beta_f), util.angdist(alpha_f, beta_i)])
397
+
398
+ # Convex case
399
+ if util.angdist(alpha_i, beta_f) < util.angdist(alpha_f, beta_i):
400
+ theta_rho = beta_f + dist_inex / 2
401
+ r_AB = r_rho
402
+ r_BA = r_rho + rho * self.radius
403
+ # Concave case
404
+ elif util.angdist(alpha_i, beta_f) >= util.angdist(alpha_f, beta_i):
405
+ theta_rho = alpha_f + dist_inex / 2
406
+ r_AB = r_rho + rho * self.radius
407
+ r_BA = r_rho
408
+
409
+ # Cartesian
410
+ points_A = np.column_stack([np.cos(alphas) * self.radius,
411
+ np.sin(alphas) * self.radius])
412
+ points_B = np.column_stack([np.cos(betas) * self.radius,
413
+ np.sin(betas) * self.radius])
414
+
415
+ # A to B
416
+ point_AB = [np.array([r_AB * np.cos(theta_rho),
417
+ r_AB * np.sin(theta_rho)])]
418
+ control_AB = [2 * point_AB[0] - (points_A[-1] + points_B[0]) / 2]
419
+
420
+ # B to A
421
+ point_BA = [np.array([r_BA * np.cos(theta_rho),
422
+ r_BA * np.sin(theta_rho)])]
423
+ control_BA = [2 * point_BA[0] - (points_A[0] + points_B[-1]) / 2]
424
+
425
+ # Bezier curve in the middle
426
+ mid_bezier = dict()
427
+ r_mid = (r_AB + r_BA) / 2
428
+ point_mid = [np.array([r_mid * np.cos(theta_rho),
429
+ r_mid * np.sin(theta_rho)])]
430
+ control_mid = [2 * point_mid[0] - (points_A[-1] + points_B[0]) / 2]
431
+ mid_bezier['P0'] = points_A[-1] + self.position
432
+ mid_bezier['P1'] = control_mid[0] + self.position
433
+ mid_bezier['P2'] = points_B[0] + self.position
434
+
435
+ # Points
436
+ points = np.vstack((points_A, control_AB, points_B, control_BA, points_A[0])) \
437
+ + self.position
438
+
439
+ # Codes
440
+ codes = [Path.MOVETO] + \
441
+ [Path.LINETO] * (len(points_A) - 1) + \
442
+ [Path.CURVE3] * 2 + \
443
+ [Path.LINETO] * (len(points_B) - 1) + \
444
+ [Path.CURVE3] * 2
445
+
446
+ return points,codes,mid_bezier
447
+
448
+ def __add_chord_blend(self,patch,curve,n):
449
+ """Add color mapped patches using the initial and final colors"""
450
+ # Pach vertices
451
+ vertices = patch.get_path().vertices
452
+ xmin, ymin = np.min(vertices, axis=0)
453
+ xmax, ymax = np.max(vertices, axis=0)
454
+
455
+ # Bézier curve
456
+ P0 = curve['P0']
457
+ P1 = curve['P1']
458
+ P2 = curve['P2']
459
+ bezier = util.get_bezier_curve(P0,P1,P2,n=self.bezier_n)
460
+ bezier_equidistant = util.equidistant(bezier)
461
+
462
+ # Color map
463
+ norm = mtpl_colors.Normalize(vmin=-1, vmax=1)
464
+ c1 = curve['c1'] # Color 1
465
+ c2 = curve['c2'] # Color 2
466
+ chord_cmap = sns.blend_palette([c1,c1,c2,c2],as_cmap=True)
467
+ cmap_matrix = util.map_from_curve(bezier_equidistant,xlims=(xmin,xmax),ylims=(ymin,ymax),
468
+ resolution=self.blend_resolution)
469
+ self.chord_blends[n].append(
470
+ util.colormapped_patch(
471
+ patch,
472
+ cmap_matrix,
473
+ ax=self.ax,
474
+ colormap=chord_cmap,
475
+ zorder=2,
476
+ alpha=self.chord_alpha,
477
+ rasterized=self.rasterized)
478
+ )
479
+
480
+ def __adjust_ax(self):
481
+ """Adjust scale, limits, and visibility of the axis"""
482
+ adjust_x = self.ax.get_autoscalex_on()
483
+ adjust_y = self.ax.get_autoscaley_on()
484
+ if adjust_x:
485
+ self.ax.set_xlim(self.position[0] - self.radius*1.5,self.position[0] + self.radius*1.5)
486
+ if adjust_y:
487
+ self.ax.set_ylim(self.position[1] - self.radius*1.5,self.position[1] + self.radius*1.5)
488
+ if adjust_x and adjust_y: self.ax.set_aspect('equal')
489
+ if self.show_axis == False: self.ax.axis('off')
490
+
491
+ def __get_node_ports(self,n):
492
+ """Return the occupied ports of the n-th node"""
493
+ this_items = list(self.nodes[n]['ports_state'].items())
494
+ this_items.pop(n+1)
495
+ return [p for p, s in this_items if s > 0 and p > n]
496
+
497
+ def __get_node_ports_references(self,n):
498
+ """
499
+ Return the reference of the chords of the n-th node as (n,c), where:
500
+
501
+ - n: index of the n-th node in the resulting diagram
502
+ - c: index of the c-th chord in the n-th node
503
+
504
+ Always anti-clockwise. When show_diag=True, the self-referencing chord is (n,0).
505
+ """
506
+ node = self.nodes[n]
507
+ this_ports = self.__get_node_ports(n)
508
+ refs = []
509
+ for port in node['ports_state'].keys():
510
+ if '*' not in str(port):
511
+ if node['ports_state'][port] > 0 and port > n:
512
+ refs.append((n,this_ports.index(port)))
513
+ elif node['ports_state'][port] > 0 and port < n:
514
+ target_ports = self.__get_node_ports(port)
515
+ refs.append((port,target_ports.index(n)))
516
+ if self.show_diag:
517
+ diag_ref_position = None
518
+ refs_modified = []
519
+ for i, (x, y) in enumerate(refs):
520
+ modified = (x, y + 1)
521
+ refs_modified.append(modified)
522
+ if diag_ref_position is None and x == n: diag_ref_position = i
523
+ if diag_ref_position is None: diag_ref_position = len(refs_modified)
524
+ refs_modified.insert(diag_ref_position, (n, 0))
525
+ refs = refs_modified
526
+ return refs
527
+
528
+ def __update_highlights(self):
529
+ for n in self.nodes:
530
+ for c in range(len(self.chord_patches[n])):
531
+ if (n,c) not in self.__highlighted_ports:
532
+ self.chord_patches[n][c].set_alpha(self.off_alpha)
533
+ if self.blend == True: self.chord_blends[n][c].set_alpha(self.off_alpha)
534
+
535
+ # Customization methods
536
+ def highlight_node(self,node:int,chords:list=None,alpha:float=None):
537
+ """
538
+ Targeted highlighting of the n-th node
539
+ You can also select the chords that you want to highlight using chords = [0,1,...]
540
+ """
541
+ if node >= len(self.nodes):
542
+ raise IndexError('Node is out of range. '
543
+ f'This Chord Diagram has only {len(self.nodes)} nodes.')
544
+ if node < 0 :
545
+ raise ValueError('The input node must be positive or zero.')
546
+
547
+ if chords is None: chords = [c for c in range(len(self.__ports_refs[node]))]
548
+ for chord in chords:
549
+ self.highlight_chord(node,chord,alpha)
550
+
551
+ def highlight_chord(self,node:int,chord:int,alpha:float=None):
552
+ """Targeted highlighting of the c-th chord in the n-th node"""
553
+ if node >= len(self.nodes):
554
+ raise IndexError('Node is out of range. '
555
+ f'This Chord Diagram has only {len(self.nodes)} nodes.')
556
+ if node < 0 or chord < 0:
557
+ raise ValueError('The input node and chord must be positive or zero.')
558
+
559
+ if alpha is None: alpha = self.chord_alpha
560
+ if alpha <= self.off_alpha: alpha = 0.8
561
+
562
+ self.__update_highlights()
563
+
564
+ try:
565
+ n,c = self.__ports_refs[node][chord]
566
+ self.chord_patches[n][c].set_alpha(alpha)
567
+ if self.blend == True: self.chord_blends[n][c].set_alpha(alpha)
568
+ if (n,c) not in self.__highlighted_ports: self.__highlighted_ports.append((n,c))
569
+ except IndexError:
570
+ raise IndexError(f'Chord {chord} is out of range. '
571
+ f'Node {node} has only {len(self.__ports_refs[node])} chords.')
572
+
573
+ def set_chord_alpha(self,alpha):
574
+ for n in self.nodes:
575
+ for cp in self.chord_patches[n]: cp.set_alpha(alpha)
576
+ if self.blend == True:
577
+ for cb in self.chord_blends[n]: cb.set_alpha(alpha)
578
+
579
+ # Special methods
580
+ def __str__(self):
581
+ string = ''
582
+ for n in self.nodes:
583
+ string += f'node {n} "{self.names[n]}"\n' + '-'*50
584
+ for key in self.nodes[n]:
585
+ if key == 'ports':
586
+ string += f'\n{key:<10} :'
587
+ for p in self.nodes[n][key]:
588
+ string += f'\n\t\t{p:<10} : {self.nodes[n][key][p]}'
589
+ else:
590
+ string += f'\n{key:<10} : {self.nodes[n][key]}'
591
+ string += '\n\n\n'
592
+ return string