-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdreamram_explorer.py
More file actions
2932 lines (2636 loc) · 122 KB
/
Copy pathdreamram_explorer.py
File metadata and controls
2932 lines (2636 loc) · 122 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
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import csv
import gc
import json
import sys
import time
import webbrowser
from collections import Counter, OrderedDict
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
import numpy as np
from bokeh.layouts import column, row
from bokeh.models import (
BasicTickFormatter,
BasicTicker,
Button,
CheckboxGroup,
ColorBar,
ColumnDataSource,
CustomJS,
CustomJSTickFormatter,
DataTable,
Div,
FixedTicker,
LinearColorMapper,
Range1d,
NumericInput,
Select,
TableColumn,
TextAreaInput,
)
from bokeh.palettes import Cividis256, Greys256, Inferno256, Magma256, Plasma256, Viridis256
from bokeh.plotting import figure
from bokeh.server.server import Server
DEFAULT_MIN_ALPHA = 255
DEFAULT_MARGIN_FRAC = 0.07
DEFAULT_PALETTE = Viridis256
PALETTE_OPTIONS = {
"viridis": Viridis256,
"cividis": Cividis256,
"plasma": Plasma256,
"inferno": Inferno256,
"magma": Magma256,
}
DEFAULT_POINT_RADIUS = 1
DEFAULT_UNGROUPED_NAME = "Ungrouped"
DEFAULT_ALL_COLUMNS_GROUP_NAME = "All columns"
DEFAULT_ALWAYS_VISIBLE_GROUP_NAME = "Always visible"
DEFAULT_NONE_GROUP_NAME = "Selection"
NONE_SORT_COLUMN_LABEL = "(none)"
LOG_CHECK_X = 0
LOG_CHECK_Y = 1
LOG_CHECK_COLOR = 2
BEST_MATCH_POINT_SIZE = 30
PARETO_POINT_SIZE = 8
BASELINE_POINT_SIZE = 16
AXIS_LABEL_FONT_SIZE = "24pt"
TICK_LABEL_FONT_SIZE = "14pt"
COLOR_BAR_TITLE_FONT_SIZE = "24pt"
COLOR_BAR_TICK_FONT_SIZE = "14pt"
JSON_PANEL_WIDTH = 360
MAX_BACKGROUND_CACHE_ENTRIES = 1
RENDER_CHUNK_SIZE = 1_000_000
BACKGROUND_GRAY_RGB = (188, 188, 188)
BACKGROUND_ALPHA_MIN = 255
BACKGROUND_ALPHA_MAX = 255
USER_PARETO_COLUMN = "user"
USER_PARETO_LINE_COLORS = {
2: (68, 1, 84),
4: (59, 82, 139),
8: (33, 145, 140),
16: (94, 201, 98),
32: (253, 231, 37),
}
USER_PARETO_LINE_WIDTH = 3.6
USER_PARETO_POINT_LINE_WIDTH = 2.2
USER_PARETO_GREYS_LOW_FRACTION = 0.15
LOG2_TICK_JS = r"""
const rounded_tick = Math.round(tick)
if (Math.abs(tick - rounded_tick) > 1e-6) {
return ""
}
const value = Math.pow(2, rounded_tick)
if (!isFinite(value)) {
return ""
}
const absval = Math.abs(value)
let text = ""
if (absval === 0) {
text = "0"
} else if (absval >= 1e6 || absval < 1e-4) {
text = value.toExponential(3)
} else if (absval >= 1000) {
text = value.toFixed(0)
} else if (absval >= 1) {
text = value.toFixed(3)
} else {
text = value.toPrecision(4)
}
return text.replace(/(\.\d*?[1-9])0+$/, "$1").replace(/\.0+$/, "").replace(/e\+/, "e")
"""
def _hex_palette_to_rgb(palette: list[str]) -> np.ndarray:
rgb = np.empty((len(palette), 3), dtype=np.uint8)
for i, color in enumerate(palette):
color = color.lstrip("#")
rgb[i, 0] = int(color[0:2], 16)
rgb[i, 1] = int(color[2:4], 16)
rgb[i, 2] = int(color[4:6], 16)
return rgb
def _rgb_to_hex(rgb: tuple[int, int, int]) -> str:
return f"#{int(rgb[0]):02x}{int(rgb[1]):02x}{int(rgb[2]):02x}"
def _resample_palette_segment(
palette: list[str],
low_fraction: float = 0.0,
high_fraction: float = 1.0,
n_samples: int = 256,
) -> list[str]:
if not palette:
return []
low_fraction = float(np.clip(low_fraction, 0.0, 1.0))
high_fraction = float(np.clip(high_fraction, low_fraction, 1.0))
max_index = len(palette) - 1
start = low_fraction * max_index
stop = high_fraction * max_index
sample_positions = np.linspace(start, stop, int(max(1, n_samples)))
sample_indices = np.clip(np.round(sample_positions).astype(np.int64), 0, max_index)
return [palette[int(idx)] for idx in sample_indices]
def user_pareto_line_color(user_value: float) -> str:
rounded = int(round(float(user_value)))
if np.isfinite(user_value) and abs(float(user_value) - rounded) <= 1e-9:
rgb = USER_PARETO_LINE_COLORS.get(rounded)
if rgb is not None:
return _rgb_to_hex(rgb)
return "black"
@dataclass(frozen=True)
class DataStore:
columns: list[str]
arrays: dict[str, np.ndarray]
matrix: np.ndarray
row_count: int
n_columns: int
dtype_name: str
load_seconds: float
engine_used: str
bytes_in_memory: int
@dataclass(frozen=True)
class LabelManager:
columns: list[str]
raw_to_friendly: dict[str, str]
raw_to_display: dict[str, str]
display_to_raw: dict[str, str]
unique_friendly_to_raw: dict[str, str]
@classmethod
def build(cls, columns: list[str], label_csv: Path | None) -> "LabelManager":
raw_to_friendly = {column: column for column in columns}
if label_csv is not None:
if not label_csv.exists():
raise FileNotFoundError(f"Label CSV not found: {label_csv}")
with label_csv.open("r", newline="") as handle:
reader = csv.reader(handle)
for row_idx, row in enumerate(reader, start=1):
if not row or all(str(cell).strip() == "" for cell in row):
continue
if len(row) < 2:
raise ValueError(
f"Label CSV row {row_idx} must have at least two columns: raw_header,friendly_label"
)
raw = str(row[0]).strip()
friendly = str(row[1]).strip()
if raw not in raw_to_friendly:
raise ValueError(f"Label CSV row {row_idx} refers to unknown data column: {raw}")
if friendly:
raw_to_friendly[raw] = friendly
friendly_counts = Counter(raw_to_friendly.values())
raw_to_display: dict[str, str] = {}
display_to_raw: dict[str, str] = {}
unique_friendly_to_raw: dict[str, str] = {}
for raw in columns:
friendly = raw_to_friendly[raw]
if friendly_counts[friendly] == 1:
display = friendly
unique_friendly_to_raw[friendly] = raw
else:
display = f"{friendly} [{raw}]"
raw_to_display[raw] = display
display_to_raw[display] = raw
return cls(
columns=list(columns),
raw_to_friendly=raw_to_friendly,
raw_to_display=raw_to_display,
display_to_raw=display_to_raw,
unique_friendly_to_raw=unique_friendly_to_raw,
)
def options(self, subset: list[str] | None = None, include_none: bool = False) -> list[tuple[str, str]]:
raw_columns = subset if subset is not None else self.columns
values: list[tuple[str, str]] = []
if include_none:
values.append(("", NONE_SORT_COLUMN_LABEL))
values.extend((raw, self.raw_to_display[raw]) for raw in raw_columns)
return values
def label(self, raw_column: str) -> str:
return self.raw_to_display[raw_column]
def resolve(self, ref: str) -> str:
key = str(ref).strip()
if key in self.raw_to_display:
return key
if key in self.display_to_raw:
return self.display_to_raw[key]
if key in self.unique_friendly_to_raw:
return self.unique_friendly_to_raw[key]
raise KeyError(
f"Unknown column reference: {ref!r}. Use a raw header, a unique friendly label, or an exact dropdown label."
)
@dataclass(frozen=True)
class ColumnGroupManager:
columns: list[str]
subgroup_order: list[str]
subgroup_to_columns: dict[str, list[str]]
column_to_subgroup: dict[str, str]
always_visible_columns: list[str]
always_visible_group_name: str
ungrouped_name: str
@classmethod
def build(cls, columns: list[str], subgroup_json: Path | None) -> "ColumnGroupManager":
payload: dict[str, object]
if subgroup_json is None:
payload = {}
ungrouped_default = DEFAULT_ALL_COLUMNS_GROUP_NAME
else:
if not subgroup_json.exists():
raise FileNotFoundError(f"Subgroups JSON not found: {subgroup_json}")
with subgroup_json.open("r", encoding="utf-8") as handle:
loaded = json.load(handle)
if not isinstance(loaded, dict):
raise ValueError("Subgroups JSON must be a JSON object.")
payload = loaded
ungrouped_default = DEFAULT_UNGROUPED_NAME
ungrouped_name = str(payload.get("ungrouped_name", ungrouped_default)).strip() or ungrouped_default
has_explicit_always_visible = "always_visible" in payload
raw_always_visible = payload.get("always_visible", [])
if raw_always_visible is None:
raw_always_visible = []
if not isinstance(raw_always_visible, list):
raise ValueError("Subgroups JSON field 'always_visible' must be a list of raw column names.")
always_visible_group_name = (
str(payload.get("always_visible_group_name", DEFAULT_ALWAYS_VISIBLE_GROUP_NAME)).strip()
or DEFAULT_ALWAYS_VISIBLE_GROUP_NAME
)
always_visible_columns: list[str] = []
always_visible_set: set[str] = set()
for entry in raw_always_visible:
raw = str(entry).strip()
if raw == "":
continue
if raw not in columns:
raise ValueError(f"Subgroups JSON 'always_visible' refers to unknown data column: {raw}")
if raw in always_visible_set:
raise ValueError(f"Subgroups JSON 'always_visible' contains the same column more than once: {raw}")
always_visible_set.add(raw)
always_visible_columns.append(raw)
if not has_explicit_always_visible and "id" in columns and "id" not in always_visible_set:
always_visible_columns.append("id")
always_visible_set.add("id")
raw_subgroups = payload.get("subgroups", [])
if raw_subgroups is None:
raw_subgroups = []
if not isinstance(raw_subgroups, list):
raise ValueError("Subgroups JSON field 'subgroups' must be a list.")
subgroup_order: list[str] = []
subgroup_to_columns: dict[str, list[str]] = {}
column_to_subgroup: dict[str, str] = {}
seen_group_names: set[str] = set()
assigned_columns: set[str] = set()
for group_idx, group_item in enumerate(raw_subgroups, start=1):
if not isinstance(group_item, dict):
raise ValueError(f"Subgroup entry {group_idx} must be an object.")
name = str(group_item.get("name", "")).strip()
if not name:
raise ValueError(f"Subgroup entry {group_idx} is missing a non-empty 'name'.")
if name in seen_group_names:
raise ValueError(f"Subgroups JSON contains duplicate subgroup name: {name}")
seen_group_names.add(name)
raw_columns = group_item.get("columns")
if not isinstance(raw_columns, list):
raise ValueError(f"Subgroup '{name}' must have a 'columns' list.")
parsed_columns: list[str] = []
seen_within_group: set[str] = set()
for entry in raw_columns:
raw = str(entry).strip()
if raw == "":
continue
if raw not in columns:
raise ValueError(f"Subgroup '{name}' refers to unknown data column: {raw}")
if raw in seen_within_group:
raise ValueError(f"Subgroup '{name}' contains the same column more than once: {raw}")
if raw in assigned_columns:
raise ValueError(f"Data column '{raw}' appears in more than one subgroup.")
seen_within_group.add(raw)
assigned_columns.add(raw)
parsed_columns.append(raw)
column_to_subgroup[raw] = name
subgroup_order.append(name)
subgroup_to_columns[name] = parsed_columns
ungrouped_columns = [column for column in columns if column not in assigned_columns]
if ungrouped_columns:
subgroup_order.append(ungrouped_name)
subgroup_to_columns[ungrouped_name] = ungrouped_columns
for column in ungrouped_columns:
column_to_subgroup[column] = ungrouped_name
return cls(
columns=list(columns),
subgroup_order=subgroup_order,
subgroup_to_columns=subgroup_to_columns,
column_to_subgroup=column_to_subgroup,
always_visible_columns=always_visible_columns,
always_visible_group_name=always_visible_group_name,
ungrouped_name=ungrouped_name,
)
def grouped_options(
self,
labels: LabelManager,
include_none: bool = False,
none_group_name: str = DEFAULT_NONE_GROUP_NAME,
) -> dict[str, list[tuple[str, str]]]:
grouped: dict[str, list[tuple[str, str]]] = {}
if include_none:
grouped[none_group_name] = [("", NONE_SORT_COLUMN_LABEL)]
if self.always_visible_columns:
grouped[self.always_visible_group_name] = [
(column, labels.label(column)) for column in self.always_visible_columns
]
always_visible = set(self.always_visible_columns)
for group_name in self.subgroup_order:
columns = [
column for column in self.subgroup_to_columns.get(group_name, []) if column not in always_visible
]
if not columns:
continue
grouped[group_name] = [(column, labels.label(column)) for column in columns]
return grouped
def toggleable_groups(self) -> list[str]:
toggleable: list[str] = []
always_visible = set(self.always_visible_columns)
for group_name in self.subgroup_order:
if any(column not in always_visible for column in self.subgroup_to_columns.get(group_name, [])):
toggleable.append(group_name)
return toggleable
@dataclass(frozen=True)
class BaselineInfo:
index: int
column_title: str
summary_label: str
@dataclass(frozen=True)
class SortSpec:
column: str
direction: str
@dataclass
class FilterRow:
column_select: Select
min_input: NumericInput
max_input: NumericInput
remove_button: Button
info: Div
container: object
@dataclass
class SortControl:
column_select: Select
direction_select: Select
@dataclass(frozen=True)
class ParetoResult:
enabled: bool
relative_indices: np.ndarray
display_relative_indices: np.ndarray
@dataclass(frozen=True)
class ParetoSubsetResult:
group_value: float
frontier_plot_positions: np.ndarray
display_plot_positions: np.ndarray
frontier_row_indices: np.ndarray
@dataclass(frozen=True)
class BestRowDescriptor:
row_index: int
color_value: float
group_column: str | None = None
group_value: float | None = None
class StatsCache:
def __init__(self, arrays: dict[str, np.ndarray]):
self.arrays = arrays
self._cache: dict[str, tuple[float, float]] = {}
def get(self, column: str) -> tuple[float, float]:
if column not in self._cache:
arr = self.arrays[column]
finite = arr[np.isfinite(arr)]
if finite.size == 0:
self._cache[column] = (0.0, 1.0)
else:
self._cache[column] = (float(finite.min()), float(finite.max()))
return self._cache[column]
class FilterMaskCache:
def __init__(self, arrays: dict[str, np.ndarray], row_count: int):
self.arrays = arrays
self.row_count = int(row_count)
self._signature: tuple[tuple[str, float | None, float | None], ...] | None = None
self._mask: np.ndarray | None = None
self._all_true = np.ones(self.row_count, dtype=bool)
def get(self, filters: list[tuple[str, float | None, float | None]]) -> np.ndarray:
signature = tuple((column, lo, hi) for column, lo, hi in filters)
if self._signature == signature and self._mask is not None:
return self._mask
if not filters:
self._signature = signature
self._mask = self._all_true
return self._mask
mask = np.ones(self.row_count, dtype=bool)
for column, lo, hi in filters:
arr = self.arrays[column]
mask &= np.isfinite(arr)
if lo is not None:
mask &= arr >= lo
if hi is not None:
mask &= arr <= hi
self._signature = signature
self._mask = mask
return mask
class EmptySelectionError(RuntimeError):
pass
@dataclass(frozen=True)
class PlotBounds:
x_img_min: float
x_img_max: float
y_img_min: float
y_img_max: float
x_range: tuple[float, float]
y_range: tuple[float, float]
@dataclass(frozen=True)
class BackgroundCacheEntry:
image: np.ndarray
bounds: PlotBounds
n_rows: int
n_nonzero_pixels: int
max_count_per_pixel: int
class PlotComputer:
def __init__(
self,
arrays: dict[str, np.ndarray],
width: int,
height: int,
palette_rgb: np.ndarray,
min_alpha: int = DEFAULT_MIN_ALPHA,
point_radius: int = DEFAULT_POINT_RADIUS,
chunk_size: int = RENDER_CHUNK_SIZE,
):
self.arrays = arrays
self.width = int(width)
self.height = int(height)
self.min_alpha = int(min_alpha)
self.point_radius = int(point_radius)
self.palette_rgb = np.ascontiguousarray(palette_rgb, dtype=np.uint8)
self.chunk_size = max(1, int(chunk_size))
self.n_pixels = self.width * self.height
self.empty_image = np.zeros((self.height, self.width), dtype=np.uint32)
def build_xy_mask(
self,
filter_mask: np.ndarray,
x_col: str,
y_col: str,
x_log: bool,
y_log: bool,
) -> np.ndarray:
x = self.arrays[x_col]
y = self.arrays[y_col]
mask = filter_mask.copy()
mask &= np.isfinite(x)
mask &= np.isfinite(y)
if x_log:
mask &= x > 0
if y_log:
mask &= y > 0
return mask
def build_plot_mask(
self,
filter_mask: np.ndarray,
x_col: str,
y_col: str,
color_col: str,
x_log: bool,
y_log: bool,
color_log: bool,
) -> np.ndarray:
mask = self.build_xy_mask(filter_mask, x_col, y_col, x_log, y_log)
c = self.arrays[color_col]
mask &= np.isfinite(c)
if color_log:
mask &= c > 0
return mask
def _iter_mask_slices(self, mask: np.ndarray):
idx = np.flatnonzero(mask).astype(np.int64, copy=False)
if idx.size == 0:
return
step = self.chunk_size
for start in range(0, idx.size, step):
yield idx[start : start + step]
def compute_bounds_from_mask(
self,
x_values: np.ndarray,
y_values: np.ndarray,
mask: np.ndarray,
x_log: bool,
y_log: bool,
) -> PlotBounds:
found = False
x_min = x_max = y_min = y_max = 0.0
for idx in self._iter_mask_slices(mask):
x_chunk = transform_values_inplace(x_values[idx], x_log)
y_chunk = transform_values_inplace(y_values[idx], y_log)
chunk_x_min = float(np.min(x_chunk))
chunk_x_max = float(np.max(x_chunk))
chunk_y_min = float(np.min(y_chunk))
chunk_y_max = float(np.max(y_chunk))
if not found:
x_min, x_max = chunk_x_min, chunk_x_max
y_min, y_max = chunk_y_min, chunk_y_max
found = True
else:
x_min = min(x_min, chunk_x_min)
x_max = max(x_max, chunk_x_max)
y_min = min(y_min, chunk_y_min)
y_max = max(y_max, chunk_y_max)
if not found:
raise EmptySelectionError("No plottable rows remain after filters and log-scale requirements.")
x_img_min, x_img_max, y_img_min, y_img_max = _match_extent_aspect(
x_min,
x_max,
y_min,
y_max,
self.width,
self.height,
)
return PlotBounds(
x_img_min=x_img_min,
x_img_max=x_img_max,
y_img_min=y_img_min,
y_img_max=y_img_max,
x_range=_padded_range(x_min, x_max, frac=DEFAULT_MARGIN_FRAC),
y_range=_padded_range(y_min, y_max, frac=DEFAULT_MARGIN_FRAC),
)
def render_background_from_mask(
self,
x_values: np.ndarray,
y_values: np.ndarray,
mask: np.ndarray,
x_log: bool,
y_log: bool,
) -> BackgroundCacheEntry:
bounds = self.compute_bounds_from_mask(x_values, y_values, mask, x_log, y_log)
counts = np.zeros(self.n_pixels, dtype=np.uint32)
n_rows = 0
for idx in self._iter_mask_slices(mask):
x_chunk = transform_values_inplace(x_values[idx], x_log)
y_chunk = transform_values_inplace(y_values[idx], y_log)
flat = self._coords_to_flat_pixels(
x_chunk,
y_chunk,
bounds.x_img_min,
bounds.x_img_max,
bounds.y_img_min,
bounds.y_img_max,
)
counts += np.bincount(flat, minlength=self.n_pixels).astype(np.uint32, copy=False)
n_rows += int(idx.size)
counts_vis = self._expand_counts(counts)
image = self._counts_to_gray_rgba(counts_vis.ravel())
return BackgroundCacheEntry(
image=image,
bounds=bounds,
n_rows=n_rows,
n_nonzero_pixels=int(np.count_nonzero(counts)),
max_count_per_pixel=int(np.max(counts)) if counts.size else 0,
)
def render_color_overlay_from_indices(
self,
x_values: np.ndarray,
y_values: np.ndarray,
c_values: np.ndarray,
indices: np.ndarray,
x_log: bool,
y_log: bool,
color_log: bool,
z_order: str,
bounds: PlotBounds,
color_low: float,
color_high: float,
) -> dict[str, object]:
if indices.size == 0:
return {
"image": self.empty_image,
"n_rows": 0,
"n_nonzero_pixels": 0,
"max_count_per_pixel": 0,
}
counts = np.zeros(self.n_pixels, dtype=np.uint32)
fill_value = -np.inf if z_order == "highest" else np.inf
color_top = np.full(self.n_pixels, fill_value, dtype=np.float32)
n_rows = 0
step = self.chunk_size
for start in range(0, indices.size, step):
idx = indices[start : start + step]
x_chunk = transform_values_inplace(x_values[idx], x_log)
y_chunk = transform_values_inplace(y_values[idx], y_log)
c_chunk = transform_values_inplace(c_values[idx], color_log)
flat = self._coords_to_flat_pixels(
x_chunk,
y_chunk,
bounds.x_img_min,
bounds.x_img_max,
bounds.y_img_min,
bounds.y_img_max,
)
counts += np.bincount(flat, minlength=self.n_pixels).astype(np.uint32, copy=False)
if z_order == "highest":
np.maximum.at(color_top, flat, c_chunk)
else:
np.minimum.at(color_top, flat, c_chunk)
n_rows += int(idx.size)
counts_vis, color_vis = self._expand_points(counts, color_top, z_order)
image = self._colors_to_rgba(counts_vis.ravel(), color_vis.ravel(), color_low, color_high)
return {
"image": image,
"n_rows": n_rows,
"n_nonzero_pixels": int(np.count_nonzero(counts)),
"max_count_per_pixel": int(np.max(counts)) if counts.size else 0,
}
def compute_bounds(self, x_plot: np.ndarray, y_plot: np.ndarray) -> PlotBounds:
if x_plot.size == 0:
raise EmptySelectionError("No plottable rows remain after filters and log-scale requirements.")
x_min = float(x_plot.min())
x_max = float(x_plot.max())
y_min = float(y_plot.min())
y_max = float(y_plot.max())
x_img_min, x_img_max, y_img_min, y_img_max = _match_extent_aspect(
x_min,
x_max,
y_min,
y_max,
self.width,
self.height,
)
return PlotBounds(
x_img_min=x_img_min,
x_img_max=x_img_max,
y_img_min=y_img_min,
y_img_max=y_img_max,
x_range=_padded_range(x_min, x_max, frac=DEFAULT_MARGIN_FRAC),
y_range=_padded_range(y_min, y_max, frac=DEFAULT_MARGIN_FRAC),
)
def render_background(self, x_plot: np.ndarray, y_plot: np.ndarray) -> BackgroundCacheEntry:
bounds = self.compute_bounds(x_plot, y_plot)
counts = self._accumulate_counts(x_plot, y_plot, bounds)
counts_vis = self._expand_counts(counts)
image = self._counts_to_gray_rgba(counts_vis.ravel())
return BackgroundCacheEntry(
image=image,
bounds=bounds,
n_rows=int(x_plot.size),
n_nonzero_pixels=int(np.count_nonzero(counts)),
max_count_per_pixel=int(np.max(counts)) if counts.size else 0,
)
def render_color_overlay(
self,
x_plot: np.ndarray,
y_plot: np.ndarray,
c_plot: np.ndarray,
z_order: str,
bounds: PlotBounds,
color_low: float,
color_high: float,
) -> dict[str, object]:
if x_plot.size == 0:
return {
"image": self.empty_image,
"n_rows": 0,
"n_nonzero_pixels": 0,
"max_count_per_pixel": 0,
}
flat = self._coords_to_flat_pixels(
x_plot,
y_plot,
bounds.x_img_min,
bounds.x_img_max,
bounds.y_img_min,
bounds.y_img_max,
)
counts = np.bincount(flat, minlength=self.n_pixels).astype(np.uint32, copy=False)
fill_value = -np.inf if z_order == "highest" else np.inf
color_top = np.full(self.n_pixels, fill_value, dtype=np.float32)
colors = c_plot.astype(np.float32, copy=False)
if z_order == "highest":
np.maximum.at(color_top, flat, colors)
else:
np.minimum.at(color_top, flat, colors)
counts_vis, color_vis = self._expand_points(counts, color_top, z_order)
image = self._colors_to_rgba(counts_vis.ravel(), color_vis.ravel(), color_low, color_high)
return {
"image": image,
"n_rows": int(x_plot.size),
"n_nonzero_pixels": int(np.count_nonzero(counts)),
"max_count_per_pixel": int(np.max(counts)) if counts.size else 0,
}
def _coords_to_flat_pixels(
self,
x_plot: np.ndarray,
y_plot: np.ndarray,
x_img_min: float,
x_img_max: float,
y_img_min: float,
y_img_max: float,
) -> np.ndarray:
x_scale = (self.width - 1) / (x_img_max - x_img_min)
y_scale = (self.height - 1) / (y_img_max - y_img_min)
px = ((x_plot - x_img_min) * x_scale).astype(np.int32)
py = ((y_plot - y_img_min) * y_scale).astype(np.int32)
np.clip(px, 0, self.width - 1, out=px)
np.clip(py, 0, self.height - 1, out=py)
return py.astype(np.int32, copy=False) * np.int32(self.width) + px.astype(np.int32, copy=False)
def coords_to_pixels(
self,
x_plot: np.ndarray,
y_plot: np.ndarray,
x_img_min: float,
x_img_max: float,
y_img_min: float,
y_img_max: float,
) -> tuple[np.ndarray, np.ndarray]:
flat = self._coords_to_flat_pixels(x_plot, y_plot, x_img_min, x_img_max, y_img_min, y_img_max)
py = (flat // self.width).astype(np.int32, copy=False)
px = (flat - py * self.width).astype(np.int32, copy=False)
return px, py
def _accumulate_counts(self, x_plot: np.ndarray, y_plot: np.ndarray, bounds: PlotBounds) -> np.ndarray:
flat = self._coords_to_flat_pixels(
x_plot,
y_plot,
bounds.x_img_min,
bounds.x_img_max,
bounds.y_img_min,
bounds.y_img_max,
)
counts = np.bincount(flat, minlength=self.n_pixels).astype(np.uint32, copy=False)
return counts
def _expand_counts(self, counts_flat: np.ndarray) -> np.ndarray:
counts_2d = counts_flat.reshape(self.height, self.width)
if self.point_radius <= 0:
return counts_2d
return self._square_filter(counts_2d, mode="max", fill_value=0)
def _expand_points(
self,
counts_flat: np.ndarray,
color_flat: np.ndarray,
z_order: str,
) -> tuple[np.ndarray, np.ndarray]:
counts_2d = counts_flat.reshape(self.height, self.width)
color_2d = color_flat.reshape(self.height, self.width)
if self.point_radius <= 0:
return counts_2d, color_2d
counts_vis = self._square_filter(counts_2d, mode="max", fill_value=0)
color_fill = -np.inf if z_order == "highest" else np.inf
color_mode = "max" if z_order == "highest" else "min"
color_vis = self._square_filter(color_2d, mode=color_mode, fill_value=color_fill)
return counts_vis, color_vis
def _square_filter(
self,
arr: np.ndarray,
mode: str,
fill_value: int | float,
radius: int | None = None,
) -> np.ndarray:
radius = self.point_radius if radius is None else int(radius)
if radius <= 0:
return arr
height, width = arr.shape
out = np.full(arr.shape, fill_value, dtype=arr.dtype)
for dy in range(-radius, radius + 1):
src_y0 = max(0, -dy)
src_y1 = min(height, height - dy)
dst_y0 = max(0, dy)
dst_y1 = min(height, height + dy)
for dx in range(-radius, radius + 1):
src_x0 = max(0, -dx)
src_x1 = min(width, width - dx)
dst_x0 = max(0, dx)
dst_x1 = min(width, width + dx)
src = arr[src_y0:src_y1, src_x0:src_x1]
dst = out[dst_y0:dst_y1, dst_x0:dst_x1]
if mode == "max":
np.maximum(dst, src, out=dst)
elif mode == "min":
np.minimum(dst, src, out=dst)
else:
raise ValueError(f"Unsupported filter mode: {mode}")
return out
def _counts_to_gray_rgba(self, counts: np.ndarray) -> np.ndarray:
img = np.zeros(self.n_pixels, dtype=np.uint32)
nonzero = counts > 0
if not np.any(nonzero):
return img.reshape(self.height, self.width)
alpha = np.full(int(np.count_nonzero(nonzero)), BACKGROUND_ALPHA_MAX, dtype=np.uint8)
view = img.view(np.uint8).reshape(-1, 4)
view[nonzero, 0] = BACKGROUND_GRAY_RGB[0]
view[nonzero, 1] = BACKGROUND_GRAY_RGB[1]
view[nonzero, 2] = BACKGROUND_GRAY_RGB[2]
view[nonzero, 3] = alpha
return img.reshape(self.height, self.width)
def _colors_to_rgba(
self,
counts: np.ndarray,
color_top: np.ndarray,
color_low: float,
color_high: float,
) -> np.ndarray:
img = np.zeros(self.n_pixels, dtype=np.uint32)
nonzero = counts > 0
if not np.any(nonzero):
return img.reshape(self.height, self.width)
low = float(color_low)
high = float(color_high)
if not np.isfinite(low) or not np.isfinite(high):
low, high = 0.0, 1.0
if low == high:
low -= 0.5
high += 0.5
selected_colors = color_top[nonzero]
norm = (selected_colors - low) / (high - low)
palette_idx = np.clip((norm * (len(self.palette_rgb) - 1)).astype(np.int32), 0, len(self.palette_rgb) - 1)
alpha = np.full(int(np.count_nonzero(nonzero)), 255, dtype=np.uint8)
view = img.view(np.uint8).reshape(-1, 4)
view[nonzero, 0] = self.palette_rgb[palette_idx, 0]
view[nonzero, 1] = self.palette_rgb[palette_idx, 1]
view[nonzero, 2] = self.palette_rgb[palette_idx, 2]
view[nonzero, 3] = alpha
return img.reshape(self.height, self.width)
def _ensure_nonzero_extent(vmin: float, vmax: float) -> tuple[float, float]:
if vmin == vmax:
pad = 0.5 if vmin == 0 else max(abs(vmin) * 0.01, 1e-12)
return vmin - pad, vmax + pad
return vmin, vmax
def _padded_range(vmin: float, vmax: float, frac: float) -> tuple[float, float]:
span = vmax - vmin
if span <= 0:
span = 1.0 if vmin == 0 else max(abs(vmin) * 0.1, 1e-12)
pad = span * frac
return vmin - pad, vmax + pad
def _match_extent_aspect(
x_min: float,
x_max: float,
y_min: float,
y_max: float,
width: int,
height: int,
) -> tuple[float, float, float, float]:
x_min, x_max = _ensure_nonzero_extent(x_min, x_max)
y_min, y_max = _ensure_nonzero_extent(y_min, y_max)
x_span = x_max - x_min
y_span = y_max - y_min
target_ratio = float(width) / float(height)
current_ratio = x_span / y_span
if np.isclose(current_ratio, target_ratio, rtol=1e-9, atol=1e-12):
return x_min, x_max, y_min, y_max
x_center = 0.5 * (x_min + x_max)
y_center = 0.5 * (y_min + y_max)
if current_ratio < target_ratio:
x_span = y_span * target_ratio
else:
y_span = x_span / target_ratio
return (
x_center - 0.5 * x_span,
x_center + 0.5 * x_span,
y_center - 0.5 * y_span,
y_center + 0.5 * y_span,
)
def load_float_csv(csv_path: Path, dtype: str = "float32") -> DataStore:
if dtype not in {"float32", "float64"}:
raise ValueError("dtype must be 'float32' or 'float64'")
np_dtype = np.float32 if dtype == "float32" else np.float64
t0 = time.perf_counter()
with csv_path.open("r", newline="") as handle:
reader = csv.reader(handle)
try:
header = next(reader)
except StopIteration as exc: