-
Notifications
You must be signed in to change notification settings - Fork 1
/
viz.py
1447 lines (1343 loc) · 57.7 KB
/
viz.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
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
"""
Functions for collecting experiment results, visualizing them, etc.
"""
import itertools
import os
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import yaml
from termcolor import colored
from torch_ecg.utils import MovingAverage
try:
import ipywidgets as widgets
from IPython.display import display
except (ImportError, ModuleNotFoundError):
widgets = display = None
from ..nodes import Node
from .const import LOG_DIR
from .misc import find_longest_common_substring, is_notebook
__all__ = [
"find_log_files",
"get_config_from_log",
"get_curves_and_labels_from_log",
"plot_curves",
"plot_mean_curve_with_error_bounds",
"Panel",
]
# turn off the progress bar for loading log files
os.environ["FLSIM_VERBOSE"] = "0"
_linestyle_tuple = [ # name, linestyle (offset, on-off-seq)
("solid", (0, ())),
("densely dashed", (0, (5, 1))),
("densely dotted", (0, (1, 1))),
("densely dashdotted", (0, (3, 1, 1, 1))),
("densely dashdotdotted", (0, (3, 1, 1, 1, 1, 1))),
("dashed", (0, (5, 5))),
("dotted", (0, (1, 1))),
("dashdotdotted", (0, (3, 5, 1, 5, 1, 5))),
("dashdotted", (0, (3, 5, 1, 5))),
("loosely dashdotdotted", (0, (3, 10, 1, 10, 1, 10))),
("loosely dashdotted", (0, (3, 10, 1, 10))),
("loosely dotted", (0, (1, 10))),
("long dash with offset", (5, (10, 3))),
("loosely dashed", (0, (5, 10))),
]
# _linestyle_cycle = itertools.cycle([ls for _, ls in _linestyle_tuple])
_marker_cycle = ("o", "s", "v", "^", "<", ">", "p", "P", "*")
# fmt: off
_color_palettes = [
# seaborn color palettes
"deep", "muted", "bright", "pastel", "dark", "colorblind",
# matplotlib color palettes
"tab10", "tab20", "tab20b", "tab20c",
"Pastel1", "Pastel2", "Paired", "Accent", "Dark2",
"Set1", "Set2", "Set3",
]
# fmt: on
sns.set_palette("tab10")
DEFAULT_RC_PARAMS = {
"xtick.labelsize": 18,
"ytick.labelsize": 18,
"axes.labelsize": 22,
"legend.fontsize": 18,
"legend.title_fontsize": 20,
"figure.figsize": [16, 8],
"lines.linewidth": 2.6,
"font.family": ["sans-serif"],
}
if mpl is not None:
# NOTE: to use Windows fonts on a Linux machine (e.g. Ubuntu),
# one can execute the following commands:
# sudo apt install ttf-mscorefonts-installer
# sudo fc-cache -fv
font_files = mpl.font_manager.findSystemFonts()
for font_file in font_files:
try:
mpl.font_manager.fontManager.addfont(font_file)
except Exception:
pass
_font_names = [item.name for item in mpl.font_manager.fontManager.ttflist]
_fonts_priority = [
"Helvetica", # recommended by science (https://www.science.org/content/page/instructions-preparing-initial-manuscript)
"Arial", # alternative to Helvetica for Windows users
"TeX Gyre Heros", # alternative to Helvetica for Linux users
"Roboto", # alternative to Helvetica for Android users
"Arimo", # alternative to Helvetica, cross-platform
"Nimbus Sans", # alternative to Helvetica
"CMU Serif", # Computer Modern Roman, default for LaTeX, serif font
"JDLangZhengTi", # sans-serif font for Chinese
"Times New Roman", # less recommended, serif font
"DejaVu Sans", # default sans-serif font for matplotlib
]
_fonts_priority = [item for item in _fonts_priority if item in _font_names]
if len(_fonts_priority) == 0:
_fonts_priority = ["sans-serif"]
for font in _fonts_priority:
if font in _font_names:
DEFAULT_RC_PARAMS["font.family"] = [font]
break
print(f"FL-SIM Panel using default font {DEFAULT_RC_PARAMS['font.family']}")
mpl.rcParams.update(DEFAULT_RC_PARAMS)
plt.rcParams.update(DEFAULT_RC_PARAMS)
else:
_font_names, _fonts_priority = None, None
def find_log_files(directory: Union[str, Path] = LOG_DIR, filters: str = "", show: bool = False) -> Union[List[Path], None]:
"""Find log files in the given directory, recursively.
Parameters
----------
directory : Union[str, pathlib.Path], default fl_sim.utils.const.LOG_DIR
The directory to search for log files.
filters : str, default ""
Filters for the log files.
Only files fitting the pattern of `filters` will be returned.
show : bool, default False
Whether to print the found log files.
If True, the found log files will be printed and **NOT** returned.
Returns
-------
List[pathlib.Path]
The list of log files.
"""
log_files = [item for item in Path(directory).rglob("*.json") if item.is_file() and re.search(filters, item.name)]
if show:
for idx, fn in enumerate(log_files):
print(idx, "---", fn.stem)
else:
return sorted(log_files)
def get_config_from_log(file: Union[str, Path]) -> dict:
"""Get the config from the log file.
Parameters
----------
file : Union[str, pathlib.Path]
Path to the log file.
Returns
-------
dict
The config.
"""
file = Path(file)
if not file.exists():
print(colored("File not found", "red"))
return {}
if file.suffix == ".json":
file = file.with_suffix(".txt")
if not file.exists():
print(colored("Corresponding text log file not found", "red"))
return {}
contents = file.read_text().splitlines()
flag = False
for idx, line in enumerate(contents):
if "FLSim - INFO - Experiment config:" in line:
flag = True
break
if flag:
return eval(contents[idx + 1])
else:
print("Config not found")
return {}
def get_curves_and_labels_from_log(
files: Union[str, Path, Sequence[Union[str, Path]]],
part: str = "val",
metric: str = "acc",
) -> Tuple[List[np.ndarray], List[str]]:
"""Get the curves and labels (stems) from the given log file(s).
Parameters
----------
files : Union[str, pathlib.Path, Sequence[Union[str, pathlib.Path]]]
The log file(s).
part : str, default "val"
The part of the data, e.g., "train", "val", "test", etc.
metric : str, default "acc"
The metric to plot, e.g., "acc", "top3_acc", "loss", etc.
Returns
-------
Tuple[List[numpy.ndarray], List[str]]
The curves and labels.
"""
curves = []
stems = []
if isinstance(files, (str, Path)):
files = [files]
for file in files:
curves.append(
Node.aggregate_results_from_json_log(
file,
part=part,
metric=metric,
)
)
stems.append(Path(file).stem)
return curves, stems
def _plot_curves(
curves: Sequence[np.ndarray],
labels: Sequence[str],
fig_ax: Optional[Tuple[plt.Figure, plt.Axes]] = None,
markers: bool = True,
x_range: Optional[Tuple[int, int]] = None,
y_range: Optional[Tuple[float, float]] = None,
) -> Tuple[plt.Figure, plt.Axes]:
"""Plot the curves.
Parameters
----------
curves : Sequence[numpy.ndarray]
The curves.
labels : Sequence[str]
The labels.
fig_ax : Tuple[plt.Figure, plt.Axes]
The figure and axes to plot on.
markers : bool, default True
Whether to use markers.
"""
if fig_ax is None:
fig, ax = plt.subplots()
else:
fig, ax = fig_ax
if x_range is not None:
x_min, x_max = x_range
if x_min is None or x_min < 0:
x_min = 0
if x_max is None:
x_max = max([len(curve) for curve in curves])
# check if x_min, x_max are valid
if x_max != -1 and x_max <= x_min:
x_min, x_max = 0, max([len(curve) for curve in curves])
curves = [curve[x_min:x_max] for curve in curves]
if y_range is not None:
y_min, y_max = y_range
if y_min is None:
y_min = -np.inf
if y_max is None:
y_max = np.inf
curves = [np.where(curve < y_min, np.nan, np.where(curve > y_max, np.nan, curve)) for curve in curves]
# plot_config = dict(marker="*")
linestyle_cycle = itertools.cycle([ls for _, ls in _linestyle_tuple])
marker_cycle = itertools.cycle(_marker_cycle)
plot_config = dict()
for idx, curve in enumerate(curves):
if markers:
plot_config["marker"] = next(marker_cycle)
plot_config["linestyle"] = next(linestyle_cycle)
plot_config["label"] = labels[idx]
if x_range is not None:
plot_x = np.arange(x_min, min(x_max, len(curve) + x_min))
else:
plot_x = np.arange(len(curve))
ax.plot(plot_x, curve, **plot_config)
ax.legend(loc="best")
ax.set_xlabel("Global Iter.")
return fig, ax
def plot_curves(
files: Union[str, Path, Sequence[Union[str, Path]]],
part: str = "val",
metric: str = "acc",
fig_ax: Optional[Tuple[plt.Figure, plt.Axes]] = None,
labels: Union[str, Sequence[str]] = None,
) -> Tuple[plt.Figure, plt.Axes]:
"""Plot the curve of the given part and metric
from the given log file(s).
Parameters
----------
files : Union[str, pathlib.Path, Sequence[Union[str, pathlib.Path]]]
The log file(s).
part : str, default "val"
The part of the data, e.g., "train", "val", "test", etc.
metric : str, default "acc"
The metric to plot, e.g., "acc", "top3_acc", "loss", etc.
fig_ax : Optional[Tuple[plt.Figure, plt.Axes]], default None
The figure and axes to plot on.
If None, a new figure and axes will be created.
labels : Union[str, Sequence[str]], default None
The labels for the curves.
If None, the stem of the log file(s) will be used.
Returns
-------
Tuple[plt.Figure, plt.Axes]
The figure and axes.
"""
curves, stems = get_curves_and_labels_from_log(files, part=part, metric=metric)
if labels is None:
labels = stems
fig, ax = _plot_curves(curves, labels, fig_ax)
ax.set_ylabel(f"{part} {metric}")
return fig, ax
def plot_mean_curve_with_error_bounds(
curves: Sequence[np.ndarray],
error_type: str = "std",
fig_ax: Optional[Tuple[plt.Figure, plt.Axes]] = None,
label: Optional[str] = None,
show_error_bounds: bool = True,
error_bound_label: bool = True,
plot_config: Optional[Dict[str, Any]] = None,
fill_between_config: Dict[str, Any] = {"alpha": 0.3},
x_range: Optional[Tuple[int, int]] = None,
y_range: Optional[Tuple[float, float]] = None,
) -> Tuple[plt.Figure, plt.Axes]:
"""Plot the mean curve with error bounds.
Parameters
----------
curves : Sequence[np.ndarray]
The curves.
error_type : {"std", "sem", "quartile", "iqr"}, default "std"
The type of error bounds. Can be one of
- "std": standard deviation
- "sem": standard error of the mean
- "quartile": quartile
- "iqr": interquartile range
fig_ax : Optional[Tuple[plt.Figure, plt.Axes]], optional
The figure and axes to plot on.
If None, a new figure and axes will be created.
label : Optional[str], optional
The label for the mean curve.
Default to ``"mean"``.
show_error_bounds : bool, default True
Whether to show the error bounds.
error_bound_label : bool, default True
Whether to add the label for the error bounds.
plot_config : Optional[Dict[str, Any]], optional
The plot config for the mean curve passed to ``ax.plot``.
fill_between_config : Dict[str, Any], default {"alpha": 0.3}
The config for ``ax.fill_between``.
x_range : Optional[Tuple[int, int]], optional
The range of x-axis. Values outside the range will be discarded.
y_range : Optional[Tuple[float, float]], optional
The range of y-axis. Values outside the range will be set to NaN.
Returns
-------
Tuple[plt.Figure, plt.Axes]
The figure and axes.
"""
if fig_ax is None:
fig, ax = plt.subplots()
else:
fig, ax = fig_ax
if x_range is not None:
x_min, x_max = x_range
if x_min is None or x_min < 0:
x_min = 0
if x_max is None:
x_max = max([len(curve) for curve in curves])
# check if x_min, x_max are valid
if x_max != -1 and x_max <= x_min:
x_min, x_max = 0, max([len(curve) for curve in curves])
curves = [curve[x_min:x_max] for curve in curves]
if y_range is not None:
y_min, y_max = y_range
if y_min is None:
y_min = -np.inf
if y_max is None:
y_max = np.inf
curves = [np.where(curve < y_min, np.nan, np.where(curve > y_max, np.nan, curve)) for curve in curves]
# allow curves to have different lengths
max_len = max([len(curve) for curve in curves])
for idx, curve in enumerate(curves):
curves[idx] = np.pad(curve, (0, max_len - len(curve)), "constant", constant_values=np.nan)
curves = np.array(curves)
mean_curve = np.nanmean(curves, axis=0)
if x_range is not None:
plot_x = np.arange(x_min, x_max)
else:
plot_x = np.arange(len(mean_curve))
ax.plot(plot_x, mean_curve, label=label or "mean", **(plot_config or {}))
if show_error_bounds:
if error_type == "std":
std_curve = np.nanstd(curves, axis=0)
upper_curve = mean_curve + std_curve
lower_curve = mean_curve - std_curve
elif error_type == "sem":
std_curve = np.nanstd(curves, axis=0)
upper_curve = mean_curve + std_curve / np.sqrt(len(curves))
lower_curve = mean_curve - std_curve / np.sqrt(len(curves))
elif error_type == "quartile":
q3 = np.nanquantile(curves, 0.75, axis=0)
q1 = np.nanquantile(curves, 0.25, axis=0)
upper_curve = q3
lower_curve = q1
elif error_type == "iqr":
q3 = np.nanquantile(curves, 0.75, axis=0)
q1 = np.nanquantile(curves, 0.25, axis=0)
iqr = q3 - q1
upper_curve = q3 + 1.5 * iqr
lower_curve = q1 - 1.5 * iqr
else:
raise ValueError(f"Unknown error type: {error_type}")
if error_bound_label:
_error_type = {
"std": "STD",
"sem": "SEM",
"quartile": "Quartile",
"iqr": "IQR",
}[error_type]
fill_between_config["label"] = error_type if label is None else f"{label}±{_error_type}"
ax.fill_between(
# np.arange(len(mean_curve)),
plot_x,
lower_curve,
upper_curve,
**fill_between_config,
)
ax.legend(loc="best")
return fig, ax
class Panel:
"""Panel for visualizing experiment results.
Parameters
----------
logdir : Optional[Union[str, pathlib.Path]], optional
The directory to search for log files.
Defaults to `fl_sim.utils.const.LOG_DIR`.
TODO
----
1. ~~add sliders for matplotlib rc params~~(done)
2. ~~add a input box and a button for saving the figure~~(done)
3. ~~add a box for showing the config of the experiment~~(done)
4. ~~use `ToggleButtons` or `TagsInput` to specify indicators for merging multiple curves~~(done)
5. ~~add choices (via `Dropdown`) for color palette~~(done)
6. ~~add a dropdown selector for the sub-directories of the log directory~~(done)
7. load all the log files in background into a file-level cache buffer
8. use tabs to separate and add more configurations
"""
__name__ = "Panel"
__default_rc_params__ = DEFAULT_RC_PARAMS.copy()
def __init__(
self,
logdir: Optional[Union[str, Path]] = None,
rc_params: Optional[dict] = None,
debug: bool = False,
) -> None:
if widgets is None:
print("One or more of the required packages is not installed: " "ipywidgets, matplotlib.")
return
self._is_notebook = is_notebook()
if not self._is_notebook:
print("Panel is only supported in Jupyter Notebook (JupyterLab, Colab, SageMaker, etc.).")
return
self._logdir = Path(logdir or LOG_DIR).expanduser().resolve()
assert self._logdir.exists(), f"Log directory {self._logdir} does not exist."
self._rc_params = self.__default_rc_params__.copy()
self._rc_params.update(rc_params or {})
assert set(self._rc_params.keys()).issubset(
set(mpl.rcParams)
), f"Invalid rc_params: {set(self._rc_params) - set(mpl.rcParams)}."
self.reset_matplotlib()
sns.set()
self.reset_matplotlib(rc_params=self._rc_params)
self._debug = debug
self._debug_log_sep = "-" * 80
self._curve_cache = {}
self._log_files = find_log_files(directory=self._logdir)
self._subdir_dropdown_selector = widgets.Dropdown(
options=["./"] + [d.name for d in self._logdir.iterdir() if d.is_dir() and len(list(d.glob("*.json"))) > 0],
value="./",
description="Sub-directory:",
disabled=False,
style={"description_width": "initial"},
)
self._subdir_dropdown_selector.observe(self._on_subdir_dropdown_change, names="value")
self._subdir_refresh_button = widgets.Button(
description="Refresh",
disabled=False,
button_style="", # 'primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Refresh",
icon="refresh", # (FontAwesome names without the `fa-` prefix)
)
self._subdir_refresh_button.on_click(self._on_subdir_refresh_button_clicked)
self._files_refresh_button = widgets.Button(
description="Refresh",
disabled=False,
button_style="", # primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Refresh",
icon="refresh", # (FontAwesome names without the `fa-` prefix)
)
self._filters_input = widgets.Text(
value="",
placeholder="",
description="File filters:",
disabled=False,
layout={"width": "300px"},
)
self._log_files_mult_selector = widgets.SelectMultiple(
options=list(zip(self.log_files, self._log_files)),
description="Select log files:",
disabled=False,
layout={"width": "800px", "height": "220px"},
style={"description_width": "initial"},
)
unit = "files" if len(self._log_files) > 1 else "file"
unit_selected = "files" if len(self._log_files_mult_selector.value) > 1 else "file"
self._num_log_files_label = widgets.Label(
value=(
f"Found {len(self.log_files)} log {unit}. "
f"Selected {len(self._log_files_mult_selector.value)} log {unit_selected}."
)
)
# clear self._fig_curves, self._fig_stems if selected log files change
self._log_files_mult_selector.observe(self._log_files_mult_selector_changed, names="value")
self._files_refresh_button.on_click(self._on_files_refresh_button_clicked)
self._fig_curves, self._fig_stems = None, None
fig_setup_slider_config = dict(
step=1,
disabled=False,
continuous_update=False,
orientation="horizontal",
readout=True,
readout_format="d",
style={"description_width": "initial"},
)
init_fig_width, init_fig_height = self._rc_params["figure.figsize"]
init_x_ticks_font_size = self._rc_params["xtick.labelsize"]
init_y_ticks_font_size = self._rc_params["ytick.labelsize"]
init_axes_label_font_size = self._rc_params["axes.labelsize"]
init_legend_font_size = self._rc_params["legend.fontsize"]
init_linewidth = self._rc_params["lines.linewidth"]
self._fig_width_slider = widgets.IntSlider(
value=int(init_fig_width),
min=6,
max=20,
description="Fig. width:",
**fig_setup_slider_config,
)
self._fig_width_slider.observe(self._on_fig_width_slider_value_changed, names="value")
self._fig_height_slider = widgets.IntSlider(
value=int(init_fig_height),
min=3,
max=12,
description="Fig. height:",
**fig_setup_slider_config,
)
self._fig_height_slider.observe(self._on_fig_height_slider_value_changed, names="value")
self._x_ticks_font_size_slider = widgets.IntSlider(
value=int(init_x_ticks_font_size),
min=6,
max=32,
description="X tick font size:",
**fig_setup_slider_config,
)
self._x_ticks_font_size_slider.observe(self._on_x_ticks_font_size_slider_value_changed, names="value")
self._y_ticks_font_size_slider = widgets.IntSlider(
value=int(init_y_ticks_font_size),
min=6,
max=32,
description="Y tick font size:",
**fig_setup_slider_config,
)
self._y_ticks_font_size_slider.observe(self._on_y_ticks_font_size_slider_value_changed, names="value")
self._axes_label_font_size_slider = widgets.IntSlider(
value=int(init_axes_label_font_size),
min=6,
max=42,
description="Axes label font size:",
**fig_setup_slider_config,
)
self._axes_label_font_size_slider.observe(self._on_axes_label_font_size_slider_value_changed, names="value")
self._legend_font_size_slider = widgets.IntSlider(
value=int(init_legend_font_size),
min=6,
max=32,
description="Legend font size:",
**fig_setup_slider_config,
)
self._legend_font_size_slider.observe(self._on_legend_font_size_slider_value_changed, names="value")
self._linewidth_slider = widgets.FloatSlider(
value=init_linewidth,
min=0.6,
max=4.4,
description="Line width:",
**{**fig_setup_slider_config, **{"step": 0.1, "readout_format": ".1f"}},
)
self._linewidth_slider.observe(self._on_linewidth_slider_value_changed, names="value")
self._fill_between_alpha_slider = widgets.FloatSlider(
value=0.3,
min=0.1,
max=0.9,
description="Fill between alpha:",
**{**fig_setup_slider_config, **{"step": 0.01, "readout_format": ".2f"}},
)
self._fill_between_alpha_slider.observe(self._on_fill_between_alpha_slider_value_changed, names="value")
self._moving_averager = MovingAverage()
self._moving_average_slider = widgets.FloatSlider(
value=0.0,
min=0.0,
max=0.9,
description="Curve smoothing:",
**{**fig_setup_slider_config, **{"step": 0.01, "readout_format": ".2f"}},
)
self._moving_average_slider.observe(self._on_moving_average_slider_value_changed, names="value")
slider_box = widgets.GridBox(
[
self._fig_width_slider,
self._fig_height_slider,
self._linewidth_slider,
self._x_ticks_font_size_slider,
self._y_ticks_font_size_slider,
self._axes_label_font_size_slider,
self._legend_font_size_slider,
self._fill_between_alpha_slider,
self._moving_average_slider,
],
layout=widgets.Layout(
grid_template_columns="repeat(3, 0.5fr)",
grid_template_rows="repeat(3, 0.5fr)",
grid_gap="0px 0px",
),
)
self._part_input = widgets.Text(
value="val",
placeholder="val/train/...",
description="Part:",
disabled=False,
layout={"width": "200px"},
)
self._metric_input = widgets.Text(
value="acc",
placeholder="acc/loss/...",
description="Metric:",
disabled=False,
layout={"width": "200px"},
)
self._refresh_part_metric_button = widgets.Button(
description="Refresh part/metric/ylabel",
disabled=False,
button_style="warning", # primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Refresh part/metric",
icon="refresh", # (FontAwesome names without the `fa-` prefix)
layout={"width": "200px"},
)
self._ylabel_input = widgets.Text(
value="",
placeholder="Test/Train/Val Accuracy/Loss/...",
description="Y label:",
style={"description_width": "initial"},
)
self._refresh_part_metric_button.on_click(self._on_refresh_part_metric_button_clicked)
self._merge_curve_method_dropdown_selector = widgets.Dropdown(
options=[
("standard deviation", "std"),
("standard error of the mean", "sem"),
("quartile", "quartile"),
("interquartile range", "iqr"),
],
value="std",
description="Merge error bound type:",
style={"description_width": "initial"},
)
self._merge_curve_method_dropdown_selector.observe(
self._on_merge_curve_method_dropdown_selector_value_changed, names="value"
)
self._merge_curve_with_err_bound_label_checkbox = widgets.Checkbox(
value=True,
description="Merge with error bound label",
style={"description_width": "initial"},
)
self._merge_curve_with_err_bound_label_checkbox.observe(
self._on_merge_curve_with_err_bound_label_checkbox_value_changed,
names="value",
)
self._show_error_bounds_checkbox = widgets.Checkbox(
value=True,
description="Show error bounds",
style={"description_width": "initial"},
)
self._show_error_bounds_checkbox.observe(self._on_show_error_bounds_checkbox_value_changed, names="value")
if widgets.__version__ >= "8":
self._merge_curve_tags_input = widgets.TagsInput(
value=[],
allow_duplicates=False,
placeholder="FedAvg, FedProx:custom-label, etc.",
# description="Merge tags:",
# style={"description_width": "initial"},
)
self._merge_curve_tags_input.observe(self._on_merge_curve_tags_input_value_changed, names="value")
merge_curve_tags_box = widgets.VBox(
[
widgets.HBox(
[
self._merge_curve_method_dropdown_selector,
widgets.Label("Merge tags:"),
self._merge_curve_tags_input,
]
),
widgets.HBox(
[
self._show_error_bounds_checkbox,
self._merge_curve_with_err_bound_label_checkbox,
]
),
],
)
else: # TagsInput was added in ipywidgets 8.x
self._merge_curve_tags_input = None
merge_curve_tags_box = widgets.HTML(
"<span style='color:red'>"
f"Curve merging is not supported for ipywidgets {widgets.__version__}. "
"Please upgrade to ipywidgets 8.x or above."
"</span>"
)
self._xmin_input = widgets.Text(
value="",
# description="X range:",
# style={"description_width": "80px"},
layout={"width": "100px"},
)
self._xmax_input = widgets.Text(
value="",
# description="-",
# style={"description_width": "80px"},
layout={"width": "100px"},
)
self._ymin_input = widgets.Text(
value="",
# description="Y range:",
# style={"description_width": "80px"},
layout={"width": "100px"},
)
self._ymax_input = widgets.Text(
value="",
# description="-",
# style={"description_width": "80px"},
layout={"width": "100px"},
)
self._xy_range_refresh_button = widgets.Button(
description="Refresh XY range",
disabled=False,
button_style="warning", # primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Refresh XY range",
icon="refresh", # (FontAwesome names without the `fa-` prefix)
layout={"width": "200px"},
)
self._xy_range_refresh_button.on_click(self._on_xy_range_refresh_button_clicked)
value_range_hbox = widgets.HBox(
[
widgets.Label("X range:"),
self._xmin_input,
widgets.Label("-"),
self._xmax_input,
widgets.Label("Y range:"),
self._ymin_input,
widgets.Label("-"),
self._ymax_input,
self._xy_range_refresh_button,
],
# layout=widgets.Layout(align_items="flex-start"),
)
# canvas for displaying the curves
self._canvas = widgets.Output(layout={"border": "2px solid black"})
self._show_button = widgets.Button(
description="Plot the curves",
disabled=False,
button_style="primary", # 'primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Plot the curves",
icon="line-chart", # (FontAwesome names without the `fa-` prefix)
)
self._show_fig_flag = False
self._show_button.on_click(self._on_show_button_clicked)
self._clear_button = widgets.Button(
description="Clear",
disabled=False,
button_style="danger", # 'primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Clear",
icon="eraser", # (FontAwesome names without the `fa-` prefix)
# layout={"width": "100px",},
)
self._clear_button.on_click(self._on_clear_button_clicked)
self._style_dropdown_selector = widgets.Dropdown(
options=["darkgrid", "whitegrid", "dark", "white", "ticks"],
value="darkgrid",
description="Style:",
style={"description_width": "initial"},
layout={"width": "150px"},
)
self._style_dropdown_selector.observe(self._on_style_dropdown_selector_value_changed, names="value")
self._font_dropdown_selector = widgets.Dropdown(
options=_fonts_priority,
value=_fonts_priority[0],
description="Font family:",
style={"description_width": "initial"},
layout={"width": "200px"},
)
self._font_dropdown_selector.observe(self._on_font_dropdown_selector_value_changed, names="value")
self._palette_dropdown_selector = widgets.Dropdown(
options=_color_palettes,
value="tab10",
description="Palette:",
style={"description_width": "initial"},
layout={"width": "150px"},
)
self._palette_dropdown_selector.observe(self._on_palette_dropdown_selector_value_changed, names="value")
self._markers_checkbox = widgets.Checkbox(
value=True,
description="Show markers",
style={"description_width": "initial"},
layout={"width": "150px"},
)
self._markers_checkbox.observe(self._on_markers_checkbox_value_changed, names="value")
self._despine_checkbox = widgets.Checkbox(
value=False,
description="Despine",
style={"description_width": "initial"},
layout={"width": "100px"},
)
self._despine_checkbox.observe(self._on_despine_checkbox_value_changed, names="value")
self._savefig_dir_input = widgets.Text(
value="./images",
description="Save dir:",
style={"description_width": "initial"},
)
self._savefig_filename_input = widgets.Text(
value="",
description="Save filename:",
style={"description_width": "initial"},
placeholder="only filename, no extension",
layout={"width": "400px"},
)
self._savefig_format_dropdown_selector = widgets.Dropdown(
value="pdf",
options=["pdf", "svg", "png", "jpg", "ps"],
description="Save format:",
style={"description_width": "initial"},
layout={"width": "150px"},
)
self._savefig_dpi_slider = widgets.IntSlider(
value=600,
min=100,
max=1000,
step=20,
description="DPI:",
orientation="horizontal",
readout=True,
readout_format="d",
style={"description_width": "initial"},
layout={"width": "300px"},
)
self._savefig_button = widgets.Button(
description="Save",
disabled=False,
button_style="success", # 'primary', 'success', 'info', 'warning', 'danger' or ''
tooltip="Save",
icon="save", # (FontAwesome names without the `fa-` prefix)
)
self._savefig_message_area = widgets.Output(layout={"border": "2px solid black"})
self._savefig_button.on_click(self._on_savefig_button_clicked)
self._log_file_dropdown_selector = widgets.Dropdown(
options=list(zip(self.log_files, self._log_files)),
value=None,
description="Select log file:",
disabled=False,
layout={"width": "500px"},
style={"description_width": "initial"},
)
self._show_config_area = widgets.Output(layout={"border": "2px solid black"})
self._log_file_dropdown_selector.observe(self._on_log_file_dropdown_selector_change, names="value")
# layout, from top to bottom
subdir_selection_hbox = widgets.HBox([self._subdir_dropdown_selector, self._subdir_refresh_button])
file_filters_hbox = widgets.HBox(
[
self._filters_input,
self._files_refresh_button,
self._num_log_files_label,
]
)
# self._log_files_mult_selector
data_selection_hbox = widgets.HBox(
[
self._part_input,
self._metric_input,
self._ylabel_input,
self._refresh_part_metric_button,
]
)
viz_layout_option_hbox = widgets.HBox(
[
self._show_button,
self._clear_button,
self._style_dropdown_selector,
self._palette_dropdown_selector,
self._font_dropdown_selector,
self._markers_checkbox,
self._despine_checkbox,
],
layout=widgets.Layout(align_items="center"),
)
# self._canvas
savefig_box = widgets.VBox(
[
widgets.HBox(
[
self._savefig_dir_input,
self._savefig_filename_input,
self._savefig_format_dropdown_selector,
self._savefig_dpi_slider,
],
layout=widgets.Layout(align_items="center"),
),
widgets.HBox(
[self._savefig_button, self._savefig_message_area],
layout=widgets.Layout(align_items="center"),
),
],
)
# self._log_file_dropdown_selector
# self._show_config_area
self._layout = widgets.VBox(
[
subdir_selection_hbox,
file_filters_hbox,
self._log_files_mult_selector,
data_selection_hbox,
slider_box,
merge_curve_tags_box,
value_range_hbox,
viz_layout_option_hbox,
widgets.Box([self._canvas]),
savefig_box,
self._log_file_dropdown_selector,
self._show_config_area,
]
)
if self._debug:
self._debug_message_area = widgets.Output(
layout={"border": "5px solid red"},
)
self._layout.children = self._layout.children + (self._debug_message_area,)
display(self._layout)
with self._show_config_area:
print("Select a log file to show its config.")
def _on_subdir_dropdown_change(self, change: dict) -> None:
if widgets is None or not self._is_notebook: