-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplot.py
More file actions
1967 lines (1593 loc) · 85 KB
/
plot.py
File metadata and controls
1967 lines (1593 loc) · 85 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
from __future__ import annotations
from abc import ABC
from typing import Any, Optional, Sequence
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.colors import ListedColormap
from .cluster import Clustering, ParameterBasedClustering
from .color_scheme import ColorScheme
from .interface import Interface
from .parameters import (BoolParameter, NoneRangeParameter, Parameter,
ListParameter)
from .plotter import Plotter
class Plot(ABC):
def __init__(self):
self.interface: Interface
self.color_scheme: ColorScheme
self.parameters: tuple[str]
self.scale: tuple[str]
self.show_x_label: bool
self.show_y_label: bool
self._x_lim: Sequence[float] | None
self._y_lim: Sequence[float] | None
@staticmethod
def settings(interface: Interface):
return []
@classmethod
def from_qt(cls, qt_settings: dict):
return cls(**qt_settings)
def _parse_axis_limit_reference(self, reference_str):
"""
Parse the axis limit reference string.
Args:
reference_str (str): The reference string (e.g., 'x@1,0').
Returns:
tuple: A tuple containing the axis ('x' or 'y'), row index, and column index.
"""
ref_axis, ref_indices = reference_str.split('@')
ref_row, ref_col = map(int, ref_indices.split(','))
return ref_axis, ref_row, ref_col
def plot_dependencies(self):
dependencies = {'before': [], 'after': []}
for value in [self._x_lim, self._y_lim]:
if isinstance(value, str):
# Assuming format is 'x(y)@row,col'
ref_plot = tuple(map(int, value[2:].split(',')))
# Add edge with (row, col) only
dependencies['after'].append(ref_plot)
return dependencies
def get_limits(self, axis_limits: dict) -> list[tuple[float | None]]:
final_limits = []
parameters = list(self.parameters) + [None] * \
max(2 - len(self.parameters), 0)
for i_lim, scale, parameter in zip((self._x_lim, self._y_lim), self.scale, parameters):
if parameter == 'Time':
final_limits.append((None, None))
elif scale == 'Tanh':
final_limits.append((-1., 1.))
elif i_lim is None:
final_limits.append((None, None))
elif isinstance(i_lim, str):
ref_axis, ref_row, ref_col = self._parse_axis_limit_reference(
i_lim)
if (ref_row, ref_col) in axis_limits:
final_limits.append(
axis_limits[(ref_row, ref_col)][0 if ref_axis == 'x' else 1])
else:
raise ValueError('Render order failure')
else:
final_limits.append(i_lim)
return final_limits
@staticmethod
def transform_data(data_list, transform_parameter: str = 'Nodes'):
# Extract unique transform_parameter's and sort them
transform_parameter_values = {
transform_parameter_value for data in data_list for transform_parameter_value in data[transform_parameter]}
transform_parameter_values = {
elem for elem in transform_parameter_values if elem is not None}
transform_parameter_values = sorted(transform_parameter_values)
transform_parameter_value_index = {transform_parameter_value: i for i,
transform_parameter_value in enumerate(transform_parameter_values)}
# Extract time steps
time_steps = [data['Time'] for data in data_list]
# Initialize parameters dictionary
params = {key: np.full((len(transform_parameter_values), len(time_steps)), np.nan)
for key in data_list[0] if key not in [transform_parameter, 'Time', 'Nodes', 'Type']}
if 'Type' in data_list[0]:
params['Type'] = np.full(
(len(transform_parameter_values), len(time_steps)), '')
# Fill in the parameter values
for t, data in enumerate(data_list):
for param in params:
if param in data and param != 'Nodes':
# Map each transform_parameter_value's value to the corresponding row in the parameter's array
for transform_parameter_value, value in zip(data[transform_parameter], data[param]):
if transform_parameter_value is not None:
idx = transform_parameter_value_index[transform_parameter_value]
params[param][idx, t] = value
return {
'Time': np.array(time_steps),
transform_parameter: transform_parameter_values,
**params
}
def get_static_plot_requests(self):
return []
def get_dynamic_plot_requests(self):
return []
def get_track_clusterings_requests(self) -> list[dict[str, Any]]:
return []
@staticmethod
def is_available(interface: Interface) -> tuple[bool, str]:
''' Returns True if available for this interface and comment why'''
return True, ''
def settings_to_code(self) -> str:
return ''
def is_single_color(color: str | float | np.ndarray) -> bool:
return isinstance(color, (str, float)) or color.shape == (4,) or color.shape == (3,)
@staticmethod
def tanh_axis_labels(ax: plt.Axes, scale: list[str]):
"""
Adjust axis labels for tanh scaling.
Parameters:
-----------
ax : plt.Axes
The Axes object to which the label adjustments should be applied.
scale : list[str]
Which axis to adjust. Choices: 'x', 'y', or 'both'.
"""
tickslabels = [-np.inf] + list(np.arange(-2.5, 2.6, 0.5)) + [np.inf]
ticks = np.tanh(tickslabels)
tickslabels = [r'-$\infty$' if label == -np.inf else r'$\infty$' if label == np.inf else label if abs(
label) <= 1.5 else None for label in tickslabels]
minor_tickslabels = np.arange(-2.5, 2.6, 0.1)
minor_ticks = np.tanh(minor_tickslabels)
if scale[0] == 'Tanh':
ax.set_xticks(ticks)
ax.set_xticklabels(tickslabels)
ax.set_xticks(minor_ticks, minor=True)
ax.set_xticklabels([], minor=True)
ax.set_xlim([-1, 1])
if scale[1] == 'Tanh':
ax.set_yticks(ticks)
ax.set_yticklabels(tickslabels)
ax.set_yticks(minor_ticks, minor=True)
ax.set_yticklabels([], minor=True)
ax.set_ylim([-1, 1])
@Plotter.plot_type("Histogram")
class plot_histogram(Plot):
def __init__(self, interface: Interface, color_scheme: ColorScheme, parameter: str,
scale: Optional[tuple[str] | None] = None,
rotated: Optional[bool] = False,
show_x_label: bool = True, show_y_label: bool = True,
exclude_types: tuple[str] = (),
x_lim: Optional[Sequence[float] | None] = None, y_lim: Optional[Sequence[float] | None] = None,
histogram_color: str | dict | float | None = None):
self.interface: Interface = interface
self.color_scheme: ColorScheme = color_scheme
self.parameter: str = parameter
self.parameters: tuple[str] = (parameter,)
self.scale: tuple[str] = tuple(scale or ('Linear', 'Linear'))
self.exclude_types: tuple[str] = exclude_types
self.rotated: bool = rotated
self.show_x_label: bool = show_x_label
self.show_y_label: bool = show_y_label
self._x_lim: Sequence[float] | None = x_lim
self._y_lim: Sequence[float] | None = y_lim
def histogram_color_to_histogram_color_settings(histogram_color) -> dict:
if isinstance(histogram_color, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in histogram_color.keys()):
raise ValueError(
'Histogram color is incorrectly formatted')
return histogram_color
if isinstance(histogram_color, (str, float)):
return {'mode': 'Constant Color', 'settings': {'color': histogram_color}}
else:
return {'mode': 'Constant Color'}
self.histogram_color_settings: dict = histogram_color_to_histogram_color_settings(
histogram_color)
if self.histogram_color_settings['mode'] not in self.color_scheme.method_logger['Distribution Color']['modes']:
raise ValueError('Histogram color is incorrectly formatted')
def get_track_clusterings_requests(self):
return [self.color_scheme.requires_tracking(self.histogram_color_settings)]
def settings_to_code(self) -> str:
return ('\'parameter\':'+self.parameter +
',\'scale\':'+str(self.scale) +
',\'rotated\':'+str(self.rotated) +
',\'show_x_label\':'+str(self.show_x_label) +
',\'show_y_label\':'+str(self.show_y_label) +
',\'x_lim\':'+str(self._x_lim) +
',\'y_lim\':'+str(self._y_lim) +
',\'histogram_color\':'+str(self.histogram_color_settings))
@staticmethod
def settings(interface: Interface) -> list[Parameter]:
return [ListParameter(name='Parameter', parameter_name='parameter', arguments=interface.node_parameters, comment='Parameter of the histogram'),
ListParameter(name='Scale', parameter_name='scale', arguments=[
'Linear', 'Tanh'], comment='Scale of the parameter'),
BoolParameter(name='Rotate', parameter_name='rotated', default_value=False,
comment='Should the histogram be rotated?'),
BoolParameter(
name='Show X Label', parameter_name='show_x_label', default_value=True, comment=''),
BoolParameter(
name='Show Y Label', parameter_name='show_y_label', default_value=True, comment=''),
NoneRangeParameter(name='X Limit', parameter_name='x_lim',
default_min_value=None, default_max_value=None, limits=(None, None), comment=''),
NoneRangeParameter(name='Y Limit', parameter_name='y_lim',
default_min_value=None, default_max_value=None, limits=(None, None), comment=''),
]
@staticmethod
def qt_to_settings(qt_settings: dict) -> dict:
'''
Transforms dict of settings from PyQT GUI to the dict that will be used for class init.
'''
settings = qt_settings.copy()
# Extract the value of 'parameter' and remove it from settings
parameter_value = settings.pop('parameter', None)
settings['parameter'] = parameter_value
settings['scale'] = (settings['scale'], 'Linear')
return settings
def get_dynamic_plot_requests(self) -> list[dict]:
return [{'method': 'calculate_node_values', 'settings': {'parameters': (self.parameter, 'Type'), 'scale': self.scale}}]
def plot(self, ax: plt.Axes, group_number: int, axis_limits: dict):
"""
Plot a histogram on the given ax with the provided data data.
Parameters:
-----------
ax : plt.Axes
Axes object where the histogram will be plotted.
data : list[float]
list containing parameter values.
scale : str, optional
The scale for the x-axis. Options: 'Linear' or 'Tanh'.
rotated : bool, optional
If True, the histogram is rotated to be horizontal.
x_lim : Optional[Sequence[float] | None]
Limits of the x-axis.
y_lim : Optional[Sequence[float] | None]
Limits of the y-axis.
"""
if len(self.parameters) != 1:
raise ValueError('Histogram expects only one parameter')
x_lim, y_lim = self.get_limits(axis_limits)
data = self.interface.dynamic_data_cache[group_number][self.get_dynamic_plot_requests()[
0]]
nodes = data['Nodes']
types = data['Type']
acceptable_types = np.array(
[t not in self.exclude_types for t in types])
self.parameter = self.parameters[0]
values = np.array(data[self.parameter])
valid_indices = (~np.isnan(values)) & acceptable_types
values = values[valid_indices]
histogram_color = self.color_scheme.distribution_color(
nodes=nodes, group_number=group_number, **self.histogram_color_settings)
if self.rotated:
if self.scale[1] == 'Tanh':
values = np.tanh(values)
y_lim = [np.nanmin(values) if y_lim[0] is None else y_lim[0], np.nanmax(
values) if y_lim[1] is None else y_lim[1]]
values = values[(values >= y_lim[0]) & (values <= y_lim[1])]
sns.kdeplot(y=values, ax=ax, fill=True, color=histogram_color)
sns.histplot(y=values, kde=False, ax=ax,
binrange=y_lim, element="step", fill=False, stat="density", color=histogram_color)
if self.show_y_label:
ax.set_ylabel(Plotter._parameter_dict.get(
self.parameter, self.parameter))
if self.show_x_label:
ax.set_xlabel('Density')
else:
if self.scale[0] == 'Tanh':
values = np.tanh(values)
x_lim = [np.nanmin(values) if x_lim[0] is None else x_lim[0], np.nanmax(
values) if x_lim[1] is None else x_lim[1]]
values = values[(values >= x_lim[0]) & (values <= x_lim[1])]
sns.kdeplot(data=values, ax=ax, fill=True, color=histogram_color)
sns.histplot(data=values, kde=False, ax=ax,
binrange=x_lim, element="step", fill=False, stat="density", color=histogram_color)
if self.show_x_label:
ax.set_xlabel(Plotter._parameter_dict.get(
self.parameter, self.parameter))
if self.show_y_label:
ax.set_ylabel('Density')
Plot.tanh_axis_labels(ax=ax, scale=self.scale)
if x_lim is not None:
ax.set_xlim(*x_lim)
if y_lim is not None:
ax.set_ylim(*y_lim)
@Plotter.plot_type("Hexbin")
class plot_hexbin(Plot):
def __init__(self, interface: Interface, color_scheme: ColorScheme, parameters: tuple[str],
scale: Optional[tuple[str] | None] = None,
rotated: Optional[bool] = False,
show_x_label: bool = True, show_y_label: bool = True,
x_lim: Optional[Sequence[float] | None] = None, y_lim: Optional[Sequence[float] | None] = None, colormap: str | None = None, show_colorbar: bool = False):
self.interface: Interface = interface
self.color_scheme = color_scheme
self.parameters = tuple(parameters)
self.scale = tuple(scale or ('Linear', 'Linear'))
self.rotated = rotated
self.show_x_label = show_x_label
self.show_y_label = show_y_label
self._x_lim = x_lim
self._y_lim = y_lim
self.show_colorbar = show_colorbar
def colormap_to_colormap_settings(colormap) -> dict:
if isinstance(colormap, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in colormap.keys()):
raise ValueError(
'Colormap is incorrectly formatted')
return colormap
if isinstance(colormap, (str, float)):
return {'mode': 'Independent Colormap', 'settings': {'colormap': colormap}}
else:
return {'mode': 'Independent Colormap'}
self.colormap_settings = colormap_to_colormap_settings(colormap)
if self.colormap_settings['mode'] not in self.color_scheme.method_logger['Color Map']['modes']:
raise ValueError(
f"Colormap is incorrectly formatted: Mode {self.colormap_settings['mode']} not in known modes {self.color_scheme.method_logger['Color Map']['modes']}")
def get_track_clusterings_requests(self):
return [self.color_scheme.requires_tracking(self.colormap_settings)]
def settings_to_code(self) -> str:
return ('\'parameters\':'+str(self.parameters) +
',\'scale\':'+str(self.scale) +
',\'rotated\':'+str(self.rotated) +
',\'show_x_label\':'+str(self.show_x_label) +
',\'show_y_label\':'+str(self.show_y_label) +
',\'x_lim\':'+str(self._x_lim) +
',\'y_lim\':'+str(self._y_lim) +
',\'show_colorbar\':'+str(self.show_colorbar))
@staticmethod
def settings(interface: Interface) -> list[Parameter]:
return [ListParameter(name='X parameter', parameter_name='x_parameter', arguments=interface.node_parameters, comment=''),
ListParameter(name='X scale', parameter_name='x_scale', arguments=[
'Linear', 'Tanh'], comment=''),
ListParameter(name='Y parameter', parameter_name='y_parameter',
arguments=interface.node_parameters, comment=''),
ListParameter(name='Y scale', parameter_name='y_scale', arguments=[
'Linear', 'Tanh'], comment=''),
BoolParameter(name='Rotate', parameter_name='rotated', default_value=False,
comment='Should the plot be rotated?'),
BoolParameter(
name='Show X Label', parameter_name='show_x_label', default_value=True, comment=''),
BoolParameter(
name='Show Y Label', parameter_name='show_y_label', default_value=True, comment=''),
NoneRangeParameter(name='X Limit', parameter_name='x_lim',
default_min_value=None, default_max_value=None, limits=(None, None), comment=''),
NoneRangeParameter(name='Y Limit', parameter_name='y_lim',
default_min_value=None, default_max_value=None, limits=(None, None), comment=''),
BoolParameter(
name='Show Colorbar', parameter_name='show_colorbar', default_value=False, comment=''),
]
@staticmethod
def qt_to_settings(qt_settings: dict) -> dict:
# Copy qt_settings to avoid modifying the original dictionary
settings = qt_settings.copy()
# Extract the value of 'parameter' and remove it from settings
x_parameter_value = settings.pop('x_parameter', None)
y_parameter_value = settings.pop('y_parameter', None)
x_scale = settings.pop('x_scale', None)
y_scale = settings.pop('y_scale', None)
settings['parameters'] = (x_parameter_value, y_parameter_value)
settings['scale'] = (x_scale, y_scale)
return settings
def get_dynamic_plot_requests(self):
return [{'method': 'calculate_node_values', 'settings': {'parameters': self.parameters, 'scale': self.scale}}]
def plot(self, ax: plt.Axes, group_number: int, axis_limits: dict):
"""
Plot a hexbin on the given ax with the provided x and y values.
Parameters:
-----------
ax : plt.Axes
Axes object where the hexbin will be plotted.
x_values, y_values : list[float]
lists containing x-values and y-values
extent : list[float], optional
The bounding box in data coordinates that the hexbin should fill.
colormap : str, optional
The colormap to be used for hexbin coloring.
cmax : float, optional
The maximum number of counts in a hexbin for colormap scaling.
scale : list, optional
Scale for the plot values (x and y). Options: 'Linear' or 'Tanh'. Default is 'Linear' for both.
show_colorbar : bool, optional
"""
x_lim, y_lim = self.get_limits(axis_limits)
data = self.interface.dynamic_data_cache[group_number][self.get_dynamic_plot_requests()[
0]]
x_parameter = self.parameters[0]
y_parameter = self.parameters[1]
x_values = np.array(data[x_parameter])
y_values = np.array(data[y_parameter])
nodes = data['Nodes']
colormap = self.color_scheme.colorbar(
nodes=nodes, group_number=group_number, **self.colormap_settings)
# Find indices where neither x_values nor y_values are NaN
valid_indices = ~np.isnan(x_values) & ~np.isnan(y_values)
# Filter the values using these indices
x_values = x_values[valid_indices]
y_values = y_values[valid_indices]
if self.scale[0] == 'Tanh':
x_values = np.tanh(x_values)
if self.scale[1] == 'Tanh':
y_values = np.tanh(y_values)
if x_lim == (None, None):
x_lim = [-1, 1] if self.scale[0] == 'Tanh' else [
np.nanmin(x_values), np.nanmax(x_values)]
if y_lim == (None, None):
y_lim = [-1, 1] if self.scale[1] == 'Tanh' else [
np.nanmin(y_values), np.nanmax(y_values)]
extent = x_lim+y_lim
delta_x = 0.1*(extent[1]-extent[0])
x_field_extent = [extent[0]-delta_x, extent[1]+delta_x]
delta_y = 0.1*(extent[3]-extent[2])
y_field_extent = [extent[2]-delta_y, extent[3]+delta_y]
field_extent = x_field_extent + y_field_extent
ax.imshow([[0, 0], [0, 0]], cmap=colormap,
interpolation='nearest', aspect='auto', extent=field_extent)
hb = ax.hexbin(x_values, y_values, gridsize=50,
bins='log', extent=extent, cmap=colormap)
# Create a background filled with the `0` value of the colormap
ax.imshow([[0, 0], [0, 0]], cmap=colormap,
interpolation='nearest', aspect='auto', extent=extent)
# Create the hexbin plot
hb = ax.hexbin(x_values, y_values, gridsize=50, cmap=colormap,
bins='log', extent=extent)
Plot.tanh_axis_labels(ax=ax, scale=self.scale)
if x_lim is not None:
ax.set_xlim(*x_lim)
if y_lim is not None:
ax.set_ylim(*y_lim)
if self.show_colorbar:
plt.colorbar(hb, ax=ax)
if self.show_x_label:
ax.set_xlabel(Plotter._parameter_dict.get(
self.parameters[0], self.parameters[0]))
if self.show_y_label:
ax.set_ylabel(Plotter._parameter_dict.get(
self.parameters[1], self.parameters[1]))
@Plotter.plot_type("Scatter")
class plot_scatter(Plot):
def __init__(self, interface: Interface, color_scheme: ColorScheme, parameters: tuple[str],
scale: Optional[tuple[str] | None] = None,
rotated: Optional[bool] = False,
show_x_label: bool = True, show_y_label: bool = True,
x_lim: Optional[Sequence[float] | None] = None, y_lim: Optional[Sequence[float] | None] = None,
color: Optional[str | None] = None, marker: Optional[str | None] = None):
self.interface: Interface = interface
self.parameters = tuple(parameters)
self.scale = tuple(scale or ('Linear', 'Linear'))
self.rotated = rotated
self.show_x_label = show_x_label
self.show_y_label = show_y_label
self._x_lim = x_lim
self._y_lim = y_lim
self.color_scheme = color_scheme
def scatter_color_to_scatter_color_settings(scatter_color) -> dict:
if isinstance(scatter_color, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in scatter_color.keys()):
raise ValueError(
'Scatter color is incorrectly formatted')
return scatter_color
if isinstance(scatter_color, (str, float)):
return {'mode': 'Constant Color', 'settings': {'color': scatter_color}}
else:
return {'mode': 'Constant Color'}
self.scatter_color_settings: dict = scatter_color_to_scatter_color_settings(
color)
if self.scatter_color_settings['mode'] not in self.color_scheme.method_logger['Scatter Color']['modes']:
raise ValueError(
f"Scatter color is incorrectly formatted: Mode {self.scatter_color_settings['mode']} not in known modes {self.color_scheme.method_logger['Scatter Color']['modes']}")
def scatter_marker_to_scatter_marker_settings(scatter_marker) -> dict:
if isinstance(scatter_marker, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in scatter_marker.keys()):
raise ValueError(
'Scatter marker is incorrectly formatted')
return scatter_marker
if isinstance(scatter_marker, (str, float)):
return {'mode': 'Constant Marker', 'settings': {'marker': scatter_marker}}
else:
return {'mode': 'Constant Marker'}
self.scatter_marker_settings: dict = scatter_marker_to_scatter_marker_settings(
marker)
def get_track_clusterings_requests(self):
return [self.color_scheme.requires_tracking(self.scatter_color_settings), self.color_scheme.requires_tracking(self.scatter_marker_settings)]
def get_dynamic_plot_requests(self):
return [{'method': 'calculate_node_values', 'settings': {'parameters': self.parameters, 'scale': self.scale}}]
def plot(self, ax: plt.Axes, group_number: int, axis_limits: dict):
"""
Plot a scatter plot on the given ax with the provided x and y values.
Parameters:
-----------
ax : plt.Axes
Axes object where the scatter plot will be plotted.
data : defaultdict[list[float]]
A dictionary containing lists of x and y values.
parameters : tuple[str]
A tuple containing the names of the parameters to be plotted.
x_lim, y_lim : Optional[Sequence[float]]
The limits for the x and y axes.
color : Optional[str]
The color of the markers.
marker : str
The shape of the marker.
show_x_label, show_y_label : bool
Flags to show or hide the x and y labels.
"""
x_lim, y_lim = self.get_limits(axis_limits)
data = self.interface.dynamic_data_cache[group_number][self.get_dynamic_plot_requests()[
0]]
x_parameter, y_parameter = self.parameters
x_values = np.array(data[x_parameter])
y_values = np.array(data[y_parameter])
nodes = data['Nodes']
# Remove NaN values
valid_indices = ~np.isnan(x_values) & ~np.isnan(y_values)
x_values = x_values[valid_indices]
y_values = y_values[valid_indices]
valid_nodes = [nodes[i] for i in np.where(valid_indices)[0]]
if self.scale[0] == 'Tanh':
x_values = np.tanh(x_values)
if self.scale[1] == 'Tanh':
y_values = np.tanh(y_values)
colors = self.color_scheme.scatter_colors_nodes(
nodes=valid_nodes, group_number=group_number, **self.scatter_color_settings)
markers = self.color_scheme.scatter_markers_nodes(
nodes=valid_nodes, group_number=group_number, **self.scatter_marker_settings)
if isinstance(markers, (str, type(None))):
ax.scatter(x_values, y_values, color=colors, marker=markers)
else:
# Convert markers to a NumPy array for efficient processing
markers = np.array(markers)
unique_markers = np.unique(markers)
colors = np.array(colors)
colors_is_array = not (Plot.is_single_color(colors))
if colors_is_array:
# Ensure colors is a NumPy array of individual colors for each point
colors = np.array(colors)
else:
# Single color definition, use it directly for all points
c = colors
# Plot each group of points with the same marker individually
for marker in unique_markers:
# Find indices of points with the current marker
indices = np.where(markers == marker)[0]
if colors_is_array:
# Extract the colors for the selected indices for individual colors per point
c = colors[indices, :]
# Plot these points as a separate scatter plot
ax.scatter(x_values[indices],
y_values[indices], color=c, marker=marker)
# Setting the plot limits
if x_lim is not None:
ax.set_xlim(*x_lim)
if y_lim is not None:
ax.set_ylim(*y_lim)
Plot.tanh_axis_labels(ax=ax, scale=self.scale)
if self.show_x_label:
ax.set_xlabel(Plotter._parameter_dict.get(
x_parameter, x_parameter))
if self.show_y_label:
ax.set_ylabel(Plotter._parameter_dict.get(
y_parameter, y_parameter))
@Plotter.plot_type("Clustering: Centroids")
class plot_clustering_centroids(Plot):
def __init__(self, interface: Interface, color_scheme: ColorScheme, parameters: tuple[str], clustering_settings: dict,
scale: Optional[tuple[str] | None] = None,
rotated: Optional[bool] = False,
show_x_label: bool = True, show_y_label: bool = True,
x_lim: Optional[Sequence[float] | None] = None, y_lim: Optional[Sequence[float] | None] = None,
color: Optional[str | None] = None, marker: Optional[str | None] = None):
self.interface: Interface = interface
self.parameters = tuple(parameters)
self.clustering_settings = clustering_settings
self.scale = tuple(scale or ('Linear', 'Linear'))
self.rotated = rotated
self.show_x_label = show_x_label
self.show_y_label = show_y_label
self._x_lim = x_lim
self._y_lim = y_lim
self.color_scheme = color_scheme
def centroid_color_to_centroid_color_settings(centroid_color) -> dict:
if isinstance(centroid_color, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in centroid_color.keys()):
raise ValueError(
'Centroid color is incorrectly formatted')
return centroid_color
if isinstance(centroid_color, (str, float)):
return {'mode': 'Constant Color', 'settings': {'color': centroid_color}}
else:
return {'mode': 'Constant Color'}
self.centroid_color_settings: dict = centroid_color_to_centroid_color_settings(
color)
if self.centroid_color_settings['mode'] not in self.color_scheme.method_logger['Scatter Color']['modes']:
raise ValueError(
f"Centroid color is incorrectly formatted: Mode {self.centroid_color_settings['mode']} not in known modes {self.color_scheme.method_logger['Centroid Color']['modes']}")
def centroid_marker_to_centroid_marker_settings(centroid_marker) -> dict:
if isinstance(centroid_marker, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in centroid_marker.keys()):
raise ValueError(
'Centroid marker is incorrectly formatted')
return centroid_marker
if isinstance(centroid_marker, (str, float)):
return {'mode': 'Constant Marker', 'settings': {'marker': centroid_marker}}
else:
return {'mode': 'Constant Marker'}
self.centroid_marker_settings: dict = centroid_marker_to_centroid_marker_settings(
marker)
if self.centroid_marker_settings['mode'] not in self.color_scheme.method_logger['Centroid Marker']['modes']:
raise ValueError(
f"Centroid marker is incorrectly formatted: Mode {self.centroid_marker_settings['mode']} not in known modes {self.color_scheme.method_logger['Centroid Marker']['modes']}")
def get_track_clusterings_requests(self):
return [self.color_scheme.requires_tracking(self.centroid_color_settings), self.color_scheme.requires_tracking(self.centroid_marker_settings)]
def get_dynamic_plot_requests(self):
return [{'method': 'get_clustering', 'settings': {'parameters': self.parameters, 'scale': self.scale, 'clustering_settings': self.clustering_settings}}]
def plot(self, ax: plt.Axes, group_number: int, axis_limits: dict):
"""
Plots the decision boundaries for a 2D slice of the clustering object's data.
Args:
- x_feature_index (int): The index of the feature to be plotted on the x-axis.
- y_feature_index (int): The index of the feature to be plotted on the y-axis.
- plot_limits (tuple): A tuple containing the limits of the plot: (x_min, x_max, y_min, y_max).
- resolution (int): The number of points to generate in the mesh for the plot.
Returns:
None
"""
x_lim, y_lim = self.get_limits(axis_limits)
clustering: ParameterBasedClustering = self.interface.dynamic_data_cache[group_number][self.get_dynamic_plot_requests()[
0]]
x_feature_name, y_feature_name = self.parameters
x_feature_index, y_feature_index = clustering.get_indices_from_parameters(
[x_feature_name, y_feature_name])
# Plot centroids if they are 2D
centroids = clustering.centroids()
labels = clustering.cluster_labels
markers = self.color_scheme.centroid_markers(
clusters=labels, group_number=group_number, **self.centroid_marker_settings)
colors = self.color_scheme.centroid_colors(
clusters=labels, group_number=group_number, **self.centroid_color_settings)
if centroids.shape[1] != 2:
raise ValueError(f"Centroids ({centroids}) shape is incorrect")
x_values = centroids[:, x_feature_index]
y_values = centroids[:, y_feature_index]
if self.scale[0] == 'Tanh':
x_values = np.tanh(x_values)
if self.scale[1] == 'Tanh':
y_values = np.tanh(y_values)
if isinstance(markers, (str, type(None))):
ax.scatter(x_values, y_values, color=colors, marker=markers)
else:
# Convert markers to a NumPy array for efficient processing
markers = np.array(markers)
unique_markers = np.unique(markers)
# Check the type of colors to handle single color definitions
colors = np.array(colors)
colors_is_array = not (Plot.is_single_color(colors))
if colors_is_array:
# Ensure colors is a NumPy array of individual colors for each point
colors = np.array(colors)
else:
# Single color definition, use it directly for all points
c = colors
# Plot each group of points with the same marker individually
for marker in unique_markers:
# Find indices of points with the current marker
indices = np.where(markers == marker)[0]
if colors_is_array:
# Extract the colors for the selected indices for individual colors per point
c = colors[indices, :]
# Plot these points as a separate scatter plot
ax.scatter(x_values[indices],
y_values[indices], color=c, marker=marker)
# Setting the plot limits
if x_lim is not None:
ax.set_xlim(*x_lim)
if y_lim is not None:
ax.set_ylim(*y_lim)
Plot.tanh_axis_labels(ax=ax, scale=self.scale)
if self.show_x_label:
ax.set_xlabel(Plotter._parameter_dict.get(
self.parameters[0], self.parameters[0]))
if self.show_y_label:
ax.set_ylabel(Plotter._parameter_dict.get(
self.parameters[1], self.parameters[1]))
@Plotter.plot_type("Clustering: Fill")
class plot_clustering_fill(Plot):
def __init__(self, interface: Interface, color_scheme: ColorScheme, parameters: tuple[str], clustering_settings: dict = {},
scale: Optional[tuple[str] | None] = None,
show_x_label: bool = True, show_y_label: bool = True,
x_lim: Optional[Sequence[float] | None] = None, y_lim: Optional[Sequence[float] | None] = None,
fill_color: dict = None, alpha: float = 0.2, resolution: int = 100):
self.interface: Interface = interface
self.parameters = tuple(parameters)
self.color_scheme = color_scheme
self.clustering_settings = clustering_settings
self.scale = tuple(scale or ('Linear', 'Linear'))
self.show_x_label = show_x_label
self.show_y_label = show_y_label
self._x_lim = x_lim
self._y_lim = y_lim
self.resolution = resolution
self.alpha = alpha
def fill_color_to_fill_color_settings(fill_color) -> dict:
if isinstance(fill_color, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in fill_color.keys()):
raise ValueError(
'Histogram color is incorrectly formatted')
return fill_color
else:
return {'mode': 'Cluster Color', 'settings': {'clustering_settings': self.clustering_settings}}
self.fill_color_settings: dict = fill_color_to_fill_color_settings(
fill_color)
def get_track_clusterings_requests(self):
return [self.color_scheme.requires_tracking(self.fill_color_settings)]
def get_dynamic_plot_requests(self):
return [{'method': 'get_clustering', 'settings': {'parameters': self.parameters, 'scale': self.scale, 'clustering_settings': self.clustering_settings}}]
def plot(self, ax: plt.Axes, group_number: int, axis_limits: dict):
x_lim, y_lim = self.get_limits(axis_limits)
clustering: Clustering = self.interface.dynamic_data_cache[group_number][self.get_dynamic_plot_requests()[
0]]
labels = clustering.cluster_labels
colors = self.color_scheme.fill_colors(
clusters=labels, group_number=group_number, **self.fill_color_settings)
x_feature_name, y_feature_name = self.parameters
x_feature_index, y_feature_index = clustering.get_indices_from_parameters(
[x_feature_name, y_feature_name])
if np.any(x_lim) == None:
x_lim = [np.nanmin(clustering.data[:, x_feature_index]), np.nanmax(
clustering.data[:, x_feature_index])]
if np.any(y_lim) == None:
y_lim = [np.nanmin(clustering.data[:, y_feature_index]), np.nanmax(
clustering.data[:, y_feature_index])]
xx, yy = np.meshgrid(
np.linspace(x_lim[0], x_lim[1], self.resolution), np.linspace(
y_lim[0], y_lim[1], self.resolution)
)
mesh_points = np.c_[xx.ravel(), yy.ravel()]
mesh_points_scaled = np.array(mesh_points)
if self.scale[0] == 'Tanh':
mesh_points_scaled[:, 0] = np.arctanh(mesh_points_scaled[:, 0])
if self.scale[1] == 'Tanh':
mesh_points_scaled[:, 1] = np.arctanh(mesh_points_scaled[:, 1])
Z = clustering.predict_cluster(
mesh_points_scaled, parameters=self.parameters)
Z = Z.reshape(xx.shape)
# Create a ListedColormap with your colors
cmap = ListedColormap(colors)
# Custom function to check if a value is None or NaN
def is_nan_or_none(value):
return value is None or (isinstance(value, float) and np.isnan(value))
# Replace None with np.nan
Z = np.where(Z == None, np.nan, Z)
# Convert the array to float
Z = Z.astype(float)
im = ax.imshow(Z, extent=[x_lim[0], x_lim[1], y_lim[0], y_lim[1]],
origin='lower', aspect='auto', alpha=self.alpha, interpolation='nearest',
cmap=cmap)
Plot.tanh_axis_labels(ax=ax, scale=self.scale)
if self.show_x_label:
ax.set_xlabel(Plotter._parameter_dict.get(
self.parameters[0], self.parameters[0]))
if self.show_y_label:
ax.set_ylabel(Plotter._parameter_dict.get(
self.parameters[1], self.parameters[1]))
@Plotter.plot_type("Clustering: Degree of Membership")
class plot_clustering_degree_of_membership(Plot):
def __init__(self, interface: Interface, color_scheme: ColorScheme, parameters: tuple[str], clustering_settings: dict = {},
scale: Optional[tuple[str] | None] = None,
show_x_label: bool = True, show_y_label: bool = True,
x_lim: Optional[Sequence[float] | None] = None, y_lim: Optional[Sequence[float] | None] = None,
colormap=None, alpha: float = 0.2, resolution: int = 100):
self.interface: Interface = interface
self.parameters = tuple(parameters)
self.color_scheme = color_scheme
self.clustering_settings = clustering_settings
if 'clustering_parameters' not in self.clustering_settings:
self.clustering_settings['clustering_parameters'] = self.parameters
self.scale = tuple(scale or ('Linear', 'Linear'))
self.show_x_label = show_x_label
self.show_y_label = show_y_label
self._x_lim = x_lim
self._y_lim = y_lim
self.resolution = resolution
self.alpha = alpha
def colormap_to_colormap_settings(colormap) -> dict:
if isinstance(colormap, dict):
# check if only 'mode' and 'settings' in dict
if not all(key in {'mode', 'settings'} for key in colormap.keys()):
raise ValueError(
'Colormap is incorrectly formatted')
return colormap
if isinstance(colormap, (str, float)):
return {'mode': 'Independent Colormap', 'settings': {'colormap': colormap}}
else:
return {'mode': 'Independent Colormap'}
self.colormap_settings = colormap_to_colormap_settings(colormap)
if self.colormap_settings['mode'] not in self.color_scheme.method_logger['Color Map']['modes']:
raise ValueError(
f"Colormap is incorrectly formatted: Mode {self.colormap_settings['mode']} not in known modes {self.color_scheme.method_logger['Color Map']['modes']}")
def get_track_clusterings_requests(self):
return [self.color_scheme.requires_tracking(self.colormap_settings)]
def get_dynamic_plot_requests(self):
return [{'method': 'get_clustering', 'settings': {'parameters': self.parameters, 'scale': self.scale, 'clustering_settings': self.clustering_settings}}]
def plot(self, ax: plt.Axes, group_number: int, axis_limits: dict):
x_lim, y_lim = self.get_limits(axis_limits)
clustering: Clustering = self.interface.dynamic_data_cache[group_number][
self.get_dynamic_plot_requests()[0]]
colormap = self.color_scheme.colorbar(