-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharrayadapter.py
More file actions
4179 lines (3498 loc) · 161 KB
/
arrayadapter.py
File metadata and controls
4179 lines (3498 loc) · 161 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
# FIXME: * drag and drop axes uses set_data while changing filters do not
# TODO:
# redesign (again) the adapter <> arraymodel boundary:
# - the adapter may return buffers of any size (the most efficient size
# which includes the requested area). It must include the requested area if
# it exists. The buffer must be reasonably small (must fit in RAM
# comfortably). In that case, the adapter must also return actual hstart
# and vstart.
# >>> on second thoughts, I am unsure this is a good idea. It might be
# better to store the entire buffer on the adapter and have a
# BufferedAdapter base class (or maybe do this in AbstractAdapter
# directly -- but doing this for in-memory containers is wasteful).
# - the buffers MUST be 2D
# - what about type? numpy or any sequence?
# * we should always have 2 buffers worth in memory
# - asking for a new buffer/chunk should be done in a Thread
# - when there are less than X lines unseen, ask for more. X should depend on
# size of buffer and time to fetch a new buffer
# TODO (long term): add support for streaming data source. In that case,
# the behavior should be mostly what we had before (when we scroll, it
# requests more data and the total length of the scrollbar is updated)
#
# TODO (even longer term): add support for streaming data source with a limit
# (ie keep last N entries)
#
# TODO: add support for "progressive" data sources, e.g. pandas SAS reader
# (from pandas.io.sas.sas7bdat import SAS7BDATReader), which can read by
# chunks but cannot read a particular offset. It would be crazy to
# re-read the whole thing up to the requested data each time, but caching
# the whole file in memory probably isn't desirable/feasible either, so
# I guess the best we can do is to cache as many chunks as we can without
# filling up the memory (the first chunk + the last few we just read
# are probably the most likely to be re-visited) and read from the file
# if the user requests some data outside of those chunks
import collections.abc
import warnings
import logging
import sys
import os
import math
import importlib
import itertools
import time
# import types
from datetime import datetime
from typing import Optional
from pathlib import Path
import numpy as np
import larray as la
from larray.util.misc import Product
from larray_editor.utils import (get_sample, scale_to_01range,
is_number_value_vectorized, logger,
timed)
from larray_editor.commands import CellValueChange
MAX_FILTER_OPTIONS = 1001
def indirect_sort(seq, ascending):
return sorted(range(len(seq)), key=seq.__getitem__, reverse=not ascending)
REGISTERED_ADAPTERS = {}
REGISTERED_ADAPTERS_USING_STRINGS = {}
REGISTERED_ADAPTER_TYPES = None
KB = 2 ** 10
MB = 2 ** 20
def register_adapter_using_string(target_type: str, adapter_creator):
"""Register an adapter to display a type
Parameters
----------
target_type : str
Type for which the adapter should be used, given as a string.
adapter_creator : callable
Callable which will return an Adapter instance
"""
assert '.' in target_type
top_module_name, type_name = target_type.split('.', maxsplit=1)
module_adapters = REGISTERED_ADAPTERS_USING_STRINGS.setdefault(top_module_name, {})
if type_name in module_adapters:
logger.warning(f"Replacing adapter for {target_type}")
module_adapters[type_name] = adapter_creator
# container = REGISTERED_ADAPTERS_USING_STRINGS
# parts = target_type.split('.')
# for i, p in enumerate(parts):
# if i == len(parts) - 1:
# if p in container:
# print(f"Warning: replacing adapter for {target_type}")
# container[p] = adapter_creator
# else:
# container = container.setdefault(p, {})
# TODO: sadly we cannot use functools.singledispatch because it does not support string types,
# but the MRO stuff is a lot better than my own code so I could inspire myself with that.
# Ideally, I could add support for string types in singledispatch and propose the addition
# to Python
def register_adapter(target_type, adapter_creator):
"""Register an adapter to display a type
Parameters
----------
target_type : str | type
Type for which the adapter should be used.
adapter_creator : callable
Callable which will return an Adapter instance
"""
if isinstance(target_type, str):
register_adapter_using_string(target_type, adapter_creator)
return
if target_type in REGISTERED_ADAPTERS:
logger.warning(f"Warning: replacing adapter for {target_type}")
REGISTERED_ADAPTERS[target_type] = adapter_creator
# normally, the list is created only once when a first adapter is
# asked for, but if an adapter is registered after that point we need
# to update the list
if REGISTERED_ADAPTER_TYPES is not None:
update_registered_adapter_types()
def adapter_for(target_type):
"""Class decorator to register new adapters
Parameters
----------
target_type : str | type
Type handled by adapter class.
"""
def decorate_callable(adapter_creator):
register_adapter(target_type, adapter_creator)
return adapter_creator
return decorate_callable
PATH_SUFFIX_ADAPTERS = {}
def register_path_adapter(suffixes, adapter_creator, required_module=None):
"""Register an adapter to display a file type (extension)
Parameters
----------
suffixes : str | list[str]
File extension(s) for which the adapter should be used.
adapter_creator : callable
Callable which will return an Adapter instance.
required_module : str
Name of module required to handle this file type.
"""
if isinstance(suffixes, str):
suffixes = [suffixes]
for suffix in suffixes:
if suffix in PATH_SUFFIX_ADAPTERS:
logger.warning(f"Replacing path adapter for {suffix}")
PATH_SUFFIX_ADAPTERS[suffix] = (adapter_creator, required_module)
def path_adapter_for(suffixes, required_module=None):
"""Class/function decorator to register new file-type adapters
Parameters
----------
suffixes : str | list[str]
File extension(s) associated with adapter class.
required_module : str, optional
Name of module required to handle this file type.
"""
def decorate_callable(adapter_creator):
register_path_adapter(suffixes, adapter_creator, required_module)
return adapter_creator
return decorate_callable
def get_adapter_creator_for_type(data_type): # -> AbstractAdapter | func | None:
# first check precise type
if data_type in REGISTERED_ADAPTERS:
return REGISTERED_ADAPTERS[data_type]
data_type_full_module_name = data_type.__module__
if '.' in data_type_full_module_name:
data_type_top_module_name, _ = data_type_full_module_name.split('.', maxsplit=1)
else:
data_type_top_module_name = data_type_full_module_name
# handle string types
if data_type_top_module_name in REGISTERED_ADAPTERS_USING_STRINGS:
assert data_type_top_module_name in sys.modules
module = sys.modules[data_type_top_module_name]
module_adapters = REGISTERED_ADAPTERS_USING_STRINGS[data_type_top_module_name]
# register all adapters for that module using concrete types (instead
# of string types)
for str_adapter_type, adapter in list(module_adapters.items()):
# submodule
type_name = str_adapter_type
while '.' in type_name and module is not None:
submodule_name, type_name = type_name.split('.', maxsplit=1)
module = getattr(module, submodule_name, None)
# submodule not found (probably not loaded yet)
if module is None:
continue
adapter_type = getattr(module, type_name, None)
if adapter_type is None:
continue
# cache real adapter type if we have (more) objects of that kind to
# display later
REGISTERED_ADAPTERS[adapter_type] = adapter
update_registered_adapter_types()
# remove string form from adapters mapping
del module_adapters[str_adapter_type]
if not module_adapters:
del REGISTERED_ADAPTERS_USING_STRINGS[data_type_top_module_name]
# then check subclasses
if REGISTERED_ADAPTER_TYPES is None:
update_registered_adapter_types()
for adapter_type in REGISTERED_ADAPTER_TYPES:
if issubclass(data_type, adapter_type):
return REGISTERED_ADAPTERS[adapter_type]
return None
def get_adapter_creator(data): # -> AbstractAdapter | str:
obj_type = type(data)
creator = get_adapter_creator_for_type(obj_type)
# 3 options:
# - the type is not handled
if creator is None:
return f"Cannot display objects of type {obj_type.__name__}"
# - all instances of the type are handled by the same adapter
elif isinstance(creator, type) and issubclass(creator, AbstractAdapter):
return creator
# - different adapters handle that type and/or not all instance are handled
else:
return creator(data)
def update_registered_adapter_types():
global REGISTERED_ADAPTER_TYPES
REGISTERED_ADAPTER_TYPES = list(REGISTERED_ADAPTERS.keys())
# sort classes with longer MRO first, so that subclasses come before
# their parent class
def class_mro_length(cls):
return len(cls.mro())
REGISTERED_ADAPTER_TYPES.sort(key=class_mro_length, reverse=True)
def get_adapter(data, attributes=None):
if data is None:
return None
adapter_creator = get_adapter_creator(data)
assert adapter_creator is not None
if isinstance(adapter_creator, str):
raise TypeError(adapter_creator)
resource_handle = adapter_creator.open(data)
return adapter_creator(resource_handle, attributes)
def nd_shape_to_2d(shape, num_h_axes=1):
"""
Parameters
----------
shape : tuple
num_h_axes : int, optional
Defaults to 1.
Examples
--------
>>> nd_shape_to_2d(())
(1, 1)
>>> nd_shape_to_2d((2,))
(1, 2)
>>> nd_shape_to_2d((0,))
(1, 0)
>>> nd_shape_to_2d((2, 3))
(2, 3)
>>> nd_shape_to_2d((2, 0))
(2, 0)
>>> nd_shape_to_2d((2, 3, 4))
(6, 4)
>>> nd_shape_to_2d((2, 3, 0))
(6, 0)
>>> nd_shape_to_2d((2, 0, 4))
(0, 4)
>>> nd_shape_to_2d((), num_h_axes=2)
(1, 1)
>>> nd_shape_to_2d((2,), num_h_axes=2)
(1, 2)
>>> nd_shape_to_2d((2, 3), num_h_axes=2)
(1, 6)
>>> nd_shape_to_2d((2, 3, 4), num_h_axes=2)
(2, 12)
>>> nd_shape_to_2d((), num_h_axes=0)
(1, 1)
>>> nd_shape_to_2d((2,), num_h_axes=0)
(2, 1)
>>> nd_shape_to_2d((2, 3), num_h_axes=0)
(6, 1)
>>> nd_shape_to_2d((2, 3, 4), num_h_axes=0)
(24, 1)
Returns
-------
shape: tuple of integers
2d shape
"""
shape_v = shape[:-num_h_axes] if num_h_axes else shape
shape_h = shape[-num_h_axes:] if num_h_axes else ()
return np.prod(shape_v, dtype=int), np.prod(shape_h, dtype=int)
# CHECK: maybe implement decorator to mark any method as a context menu action. But what we need is not a method
# which does the action, but a method which adds a command part to the current command.
# @context_menu('Transpose')
# def transpose(self):
# pass
class AbstractAdapter:
# TODO: we should have a way to provide other attributes: format, readonly, font (problematic for colwidth),
# align, tooltips, flags?, min_value, max_value (for the delegate), ...
# I guess data itself will need to be a dict: {'values': ...}
def __init__(self, data, attributes=None):
self.data = data
self.attributes = attributes
# CHECK: filters will probably not make it as-is after quickbar is implemented: they will need to move
# to the axes area
# AND possibly h/vlabels and
# must update the current command
self.current_filter = {}
self._current_sort = []
# FIXME: this is an ugly/quick&dirty workaround
# AFAICT, this is only used in ArrayDelegate
self.dtype = np.dtype(object)
# self.dtype = None
self.vmin = None
self.vmax = None
self._number_format = "%s"
self.sort_key = None # (kind='axis'|'column'|'row', idx_of_kind, direction (1, -1))
# caching support
self._cached_fragment = None
self._cached_fragment_v_start = None
self._cached_fragment_h_start = None
# ================================ #
# methods which MUST be overridden #
# ================================ #
# def get_values(self, h_start, v_start, h_stop, v_stop):
# raise NotImplementedError()
# TODO: split this into:
# - extract_chunk_from_data (result is in native/cheapest
# format to produce)
# and
# - native_chunk_to_2D_sequence
# the goal is to cache chunks
def get_chunk_from_data(self, data, h_start, v_start, h_stop, v_stop):
"""
Extract a subset of a data object of the type the adapter handles.
Must return a 2D sequence, preferably a numpy array.
"""
raise NotImplementedError()
def shape2d(self):
raise NotImplementedError()
# =============================== #
# methods which CAN be overridden #
# =============================== #
def cell_activated(self, row_idx, column_idx):
"""
If this method returns a (not None) value, it will be used as the new
value for the array_editor_widget. Later this should add an operand on
the quickbar but we are not there yet.
"""
return None
def get_values(self, h_start, v_start, h_stop, v_stop):
return self.get_chunk_from_data(self.data, h_start, v_start, h_stop, v_stop)
@classmethod
def open(cls, data):
"""Open the ressources used by the adapter
The result of this method will be stored in the .data
attribute and passed as argument to the adapter class"""
return data
def close(self):
"""Close the ressources used by the adapter"""
pass
def _is_chunk_cached(self, h_start, v_start, h_stop, v_stop):
cached_fragment = self._cached_fragment
if cached_fragment is None:
return False
cached_h_start = self._cached_fragment_h_start
cached_v_start = self._cached_fragment_v_start
cached_width = cached_fragment.shape[1]
cached_height = cached_fragment.shape[0]
return (h_start >= cached_h_start and
h_stop <= cached_h_start + cached_width and
v_start >= cached_v_start and
v_stop <= cached_v_start + cached_height)
def _get_fragment_via_cache(self, h_start, v_start, h_stop, v_stop):
clsname = self.__class__.__name__
logger.debug(f"{clsname}._get_fragment_via_cache({h_start, v_start, h_stop, v_stop})")
if self._is_chunk_cached(h_start, v_start, h_stop, v_stop):
fragment = self._cached_fragment
fragment_h_start = self._cached_fragment_h_start
fragment_v_start = self._cached_fragment_v_start
logger.debug(" -> cache hit ! "
f"({fragment_h_start=} {fragment_v_start=})")
else:
fragment, fragment_h_start, fragment_v_start = (
self._get_fragment_from_source(h_start, v_start,
h_stop, v_stop))
logger.debug(" -> cache miss ! "
f"({fragment_h_start=} {fragment_v_start=})")
self._cached_fragment = fragment
self._cached_fragment_h_start = fragment_h_start
self._cached_fragment_v_start = fragment_v_start
return fragment, fragment_h_start, fragment_v_start
# TODO: factorize with LArrayArrayAdapter (so that we get the attributes
# handling of LArrayArrayAdapter for all types and the larray adapter
# can benefit from the generic code here
@timed(logger)
def get_data_values_and_attributes(self, h_start, v_start, h_stop, v_stop):
"""h_stop and v_stop should *not* be included"""
# TODO: implement region caching
logger.debug(
f"{self.__class__.__name__}.get_data_values_and_attributes("
f"{h_start=}, {v_start=}, {h_stop=}, {v_stop=})"
)
height, width = self.shape2d()
assert v_start >= 0, f"v_start ({v_start}) is out of bounds (should be >= 0)"
assert h_start >= 0, f"h_start ({h_start}) is out of bounds (should be >= 0)"
assert v_stop >= 0, f"v_stop ({v_stop}) is out of bounds (should be >= 0)"
assert h_stop >= 0, f"h_stop ({h_stop}) is out of bounds (should be >= 0)"
if height > 0:
assert v_start < height, f"v_start ({v_start}) is out of bounds (should be < {height})"
if width > 0:
assert h_start < width, f"h_start ({h_start}) is out of bounds (should be < {width})"
assert v_stop <= height, f"v_stop ({v_stop}) is out of bounds (should be <= {height})"
assert h_stop <= width, f"h_stop ({h_stop}) is out of bounds (should be <= {width})"
chunk_values = self.get_values(h_start, v_start, h_stop, v_stop)
if isinstance(chunk_values, np.ndarray):
assert chunk_values.ndim == 2
logger.debug(f" {chunk_values.shape=}")
elif isinstance(chunk_values, list) and len(chunk_values) == 0:
chunk_values = [[]]
# Without specifying dtype=object, asarray converts sequences
# containing both strings and numbers to all strings which then
# fail in get_color_value, but we do not want to convert
# existing numpy arrays to object dtype. This is a bit silly and
# inefficient for numeric-only sequences, but I do not see
# a better way.
if not isinstance(chunk_values, np.ndarray):
chunk_values = np.asarray(chunk_values, dtype=object)
finite_values = get_finite_numeric_values(chunk_values)
vmin, vmax = self.update_finite_min_max_values(finite_values,
h_start, v_start,
h_stop, v_stop)
color_value = scale_to_01range(finite_values, vmin, vmax)
chunk_format = self.get_format(chunk_values, h_start, v_start, h_stop, v_stop)
return {'data_format': chunk_format,
'values': chunk_values,
'bg_value': color_value}
def get_format(self, chunk_values, h_start, v_start, h_stop, v_stop):
return [[self._number_format]]
def set_format(self, fmt):
"""Change display format"""
# print(f"setting adapter format: {fmt}")
self._number_format = fmt
def from_clipboard_data_to_model_data(self, list_data):
return list_data
def get_axes_labels_and_data_values(self, row_min, row_max, col_min, col_max):
axes_names = self.get_axes_area()
axes_names = axes_names['values'] if isinstance(axes_names, dict) else axes_names
hlabels = self.get_hlabels_values(col_min, col_max)
vlabels = self.get_vlabels_values(row_min, row_max)
raw_data = self.get_values(col_min, row_min, col_max, row_max)
if isinstance(raw_data, list) and len(raw_data) == 0:
raw_data = [[]]
return axes_names, vlabels, hlabels, raw_data
def move_axis(self, data, attributes, old_index, new_index):
"""Move an axis of the data array and associated attribute arrays.
Parameters
----------
data : array
Array to transpose
attributes : dict or None
Dict of associated arrays.
old_index: int
Current index of axis to move.
new_index: int
New index of axis after transpose.
Returns
-------
data : array
Transposed input array
attributes: dict
Transposed associated arrays
"""
raise NotImplementedError()
def can_filter_axis(self, axis_idx) -> bool:
return False
def get_filter_names(self):
"""return [combo_label, ...]"""
return []
# TODO: change to get_filter_options(filter_idx, start, stop)
# ... in the end, filters will move to axes names
# AND possibly h/vlabels and
# must update the current command
def get_filter_options(self, filter_idx) -> Optional[list]:
"""return [combo_values]"""
return None
def update_filter(self, filter_idx, indices):
"""Update current filter for a given axis if labels selection from the array widget has changed
Parameters
----------
filter_idx: int
Index of filter for which selection has changed.
indices: list of int
Indices of selected labels.
"""
raise NotImplementedError()
def get_current_filter_indices(self, filter_idx):
"""Returns indices currently selected for a given filter.
Must return None if that filter is not applied.
Parameters
----------
filter_idx : int
Index of filter.
"""
return self.current_filter.get(filter_idx)
def map_filtered_to_global(self, filtered_shape, filter, local2dkey):
"""
map local (filtered data) 2D key to global (unfiltered) ND key.
Parameters
----------
filtered_shape : tuple
Shape of filtered data.
filter : dict
Current filter: {axis_idx: index_or_indices}
local2dkey: tuple
Positional index (row, column) of the modified data cell.
Returns
-------
tuple
ND indices associated with the modified element of the non-filtered array.
"""
raise NotImplementedError()
def translate_changes(self, data_model_changes):
to_global = self.map_filtered_to_global
# FIXME: filtered_data is specific to LArray. Either make it part of the API, or do not pass it as argument
# and get it in the implementation of map_filtered_to_global
global_changes = [
CellValueChange(to_global(self.filtered_data.shape, self.current_filter, key),
old_value, new_value)
for key, (old_value, new_value) in data_model_changes.items()
]
return global_changes
def get_sample(self):
"""Return a sample of the internal data"""
# TODO: use default_buffer sizes instead, or, better yet, a new get_preferred_buffer_size() method
height, width = self.shape2d()
# TODO: use this instead (but it currently does not work because get_values does not always
# return a numpy array while the current code does
# return self.get_values(0, 0, min(width, 20), min(height, 20))
return self.get_data_values_and_attributes(0, 0, min(width, 20), min(height, 20))['values']
@timed(logger)
def update_finite_min_max_values(self, finite_values: np.ndarray,
h_start: int, v_start: int,
h_stop: int, v_stop: int):
"""can return either two floats or two arrays"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
# we need initial to support empty arrays
vmin = np.nanmin(finite_values, initial=np.nan)
vmax = np.nanmax(finite_values, initial=np.nan)
self.vmin = (
np.nanmin([self.vmin, vmin]) if self.vmin is not None else vmin)
self.vmax = (
np.nanmax([self.vmax, vmax]) if self.vmax is not None else vmax)
return self.vmin, self.vmax
def get_axes_area(self):
# axes = self.filtered_data.axes
# test axes.size == 0 is required in case an instance built as Array([]) is passed
# test len(axes) == 0 is required when a user filters until getting a scalar (because in that case size is 1)
# TODO: store this in the adapter
# if axes.size == 0 or len(axes) == 0:
# return [[]]
# else:
shape = self.shape2d()
row_idx_names = [name if name is not None else ''
for name in self.get_vnames()]
num_v_axes = len(row_idx_names)
col_idx_names = [name if name is not None else ''
for name in self.get_hnames()]
num_h_axes = len(col_idx_names)
if (not len(row_idx_names) and not len(col_idx_names)) or any(d == 0 for d in shape):
return [[]]
names = np.full((max(num_h_axes, 1), max(num_v_axes, 1)), '', dtype=object)
if len(row_idx_names) > 1:
names[-1, :-1] = row_idx_names[:-1]
if len(col_idx_names) > 1:
names[:-1, -1] = col_idx_names[:-1]
part1 = row_idx_names[-1] if row_idx_names else ''
part2 = col_idx_names[-1] if col_idx_names else ''
sep = '\\' if part1 and part2 else ''
names[-1, -1] = f'{part1}{sep}{part2}'
current_sort = self.get_current_sort()
sorted_axes = {axis_idx: ascending for axis_idx, label_idx, ascending in current_sort
if label_idx == -1}
decoration = np.full_like(names, '', dtype=object)
ascending_to_decoration = {
True: 'arrow_up',
False: 'arrow_down',
}
decoration[-1, :-1] = [ascending_to_decoration[sorted_axes[i]] if i in sorted_axes else ''
for i in range(len(row_idx_names) - 1)]
return {'values': names.tolist(), 'decoration': decoration.tolist()}
def get_current_sort(self) -> list[tuple]:
"""Return current sort
Must be a list of tuples of the form
(axis_idx, label_idx, ascending) where
* axis_idx: is the index of the axis (of the label)
being sorted
* label_idx: is the index of the label being sorted,
or -1 if the sort is by the axis labels themselves
* ascending: bool
Note that unsorted axes are not mentioned.
"""
return self._current_sort
# Adapter classes *may* implement this if can_sort_axis returns True for any axis
# (otherwise they will rely on this default implementation)
def axis_sort_direction(self, axis_idx):
"""must return 'ascending', 'descending' or 'unsorted'"""
for cur_sort_axis_idx, label_idx, ascending in self._current_sort:
if cur_sort_axis_idx == axis_idx:
return 'ascending' if ascending else 'descending'
return 'unsorted'
def hlabel_sort_direction(self, row_idx, col_idx):
"""must return 'ascending', 'descending' or 'unsorted'"""
cell_axis_idx = self.hlabel_row_to_axis_num(row_idx)
for axis_idx, label_idx, ascending in self._current_sort:
if axis_idx == cell_axis_idx and label_idx == col_idx:
return 'ascending' if ascending else 'descending'
return 'unsorted'
def can_filter_hlabel(self, row_idx, col_idx) -> bool:
return False
def can_sort_axis_labels(self, axis_idx) -> bool:
return False
def sort_axis_labels(self, axis_idx, ascending):
pass
# TODO: unsure a different result per label is useful. Per axis would probably be enough
def can_sort_hlabel(self, row_idx, col_idx) -> bool:
return False
def sort_hlabel(self, row_idx, col_idx, ascending):
pass
@timed(logger)
def get_vlabels(self, start, stop) -> dict:
chunk_values = self.get_vlabels_values(start, stop)
if isinstance(chunk_values, list) and len(chunk_values) == 0:
chunk_values = [[]]
return {'values': chunk_values}
def get_vlabels_values(self, start, stop):
# Note that using some kind of lazy object here is pointless given that
# we will use most of it (the buffer should not be much larger than the
# viewport). It would make sense to define one big lazy object as
# self._vlabels = Product([range(len(data))]) and use return
# self._vlabels[start:stop] here but I am unsure it is worth it because
# that would be slower than what we have now.
return [[i] for i in range(start, stop)]
@timed(logger)
def get_hlabels(self, start, stop):
values = self.get_hlabels_values(start, stop)
return {'values': values, 'decoration': self.get_hlabels_decorations(start, stop, values)}
def get_hlabels_values(self, start, stop):
return [list(range(start, stop))]
def hlabel_row_to_axis_num(self, row_idx):
return row_idx + self.num_v_axes()
def num_v_axes(self):
return 1
def get_hlabels_decorations(self, start, stop, labels):
current_sort = self.get_current_sort()
sorted_labels_by_axis = {}
for axis_idx, label_idx, ascending in current_sort:
sorted_labels_by_axis.setdefault(axis_idx, {})[label_idx] = ascending
ascending_to_decoration = {
True: 'arrow_up',
False: 'arrow_down',
}
decorations = []
for row_idx in range(len(labels)):
row_axis_idx = self.hlabel_row_to_axis_num(row_idx)
axis_sorted_labels = sorted_labels_by_axis.get(row_axis_idx, {})
decoration_row = [
ascending_to_decoration[axis_sorted_labels[col_idx]] if col_idx in axis_sorted_labels else ''
for col_idx in range(start, stop)
]
decorations.append(decoration_row)
return decorations
def get_vnames(self):
return ['']
def get_hnames(self):
return ['']
def get_vname(self):
return ' '.join(str(name) for name in self.get_vnames())
def get_hname(self):
return ' '.join(str(name) for name in self.get_hnames())
def combine_labels_and_data(self, raw_data, axes_names, vlabels, hlabels):
"""Return list
Parameters
----------
raw_data : sequence of sequence of built-in scalar types
Array of selected data. Supports numpy arrays, tuple, list etc.
axes_names : list of string
List of axis names
vlabels : nested list
Selected vertical labels
hlabels: nested list
Selected horizontal labels
Returns
-------
list of list of built-in Python scalars (None, bool, int, float, str)
"""
# we use itertools.chain so that we can combine any iterables, not just lists
chain = itertools.chain
topheaders = [list(chain(axis_row, hlabels_row))
for axis_row, hlabels_row in zip(axes_names, hlabels)]
datarows = [list(chain(row_labels, row_data))
for row_labels, row_data in zip(vlabels, raw_data)]
return topheaders + datarows
# FIXME (unsure this is still the case): this function does not support None axes_names, vlabels and hlabels
# which _selection_data() produces in some cases (notably when working
# on a scalar array). Unsure if we should fix _selection_data or this
# method though.
def get_combined_values(self, row_min, row_max, col_min, col_max):
"""Return ...
Parameters
----------
Returns
-------
list of list of built-in Python scalars (None, bool, int, float, str)
"""
axes_names, vlabels, hlabels, raw_data = (
self.get_axes_labels_and_data_values(row_min, row_max,
col_min, col_max)
)
return self.combine_labels_and_data(raw_data, axes_names,
vlabels, hlabels)
def to_string(self, row_min, row_max, col_min, col_max, sep='\t'):
"""Copy selection as tab-separated (clipboard) text
Returns
-------
str
"""
data = self.get_combined_values(row_min, row_max, col_min, col_max)
# np.savetxt make things more complicated, especially on py3
# We do not use repr for everything to avoid having extra quotes for strings.
# XXX: but is it really a problem? Wouldn't it allow us to copy-paste values with sep (tabs) in them?
# I need to test what Excel does for strings
def vrepr(v):
if isinstance(v, float):
return repr(v)
else:
return str(v)
return '\n'.join(sep.join(vrepr(v) for v in line) for line in data)
def to_excel(self, row_min, row_max, col_min, col_max):
"""Export data to an Excel Sheet
"""
import xlwings as xw
data = self.get_combined_values(row_min, row_max, col_min, col_max)
# convert (row) generators to lists then array
# TODO: the conversion to array is currently necessary even though xlwings will translate it back to a list
# anyway. The problem is that our lists contains numpy types and especially np.str_ crashes xlwings.
# unsure how we should fix this properly: in xlwings, or change get_combined_data() to return only
# standard Python types.
array = np.array([list(r) for r in data])
# Create a new Excel instance. We cannot simply use xw.view(array)
# because it reuses the active Excel instance if any, and if that one
# is hidden, the user will not see anything
app = xw.App(visible=True)
# Activate XLA(M) addins. By default, they are not activated when an
# Excel Workbook is opened via COM
xl_app = app.api
for i in range(1, xl_app.AddIns.Count + 1):
addin = xl_app.AddIns(i)
addin_path = addin.FullName
if addin.Installed and '.xll' not in addin_path.lower():
xl_app.Workbooks.Open(addin_path)
# Dump array to first sheet
book = app.books[0]
sheet = book.sheets[0]
with app.properties(screen_updating=False):
sheet["A1"].value = array
# Unsure whether we should do this or not
# sheet.tables.add(sheet["A1"].expand())
sheet.autofit()
# Move Excel Window at the front. Without steal_focus it does not seem
# to do anything
app.activate(steal_focus=True)
def plot(self, row_min, row_max, col_min, col_max):
"""Return a matplotlib.Figure object for selected subset.
Returns
-------
A matplotlib.Figure object.
"""
from matplotlib.figure import Figure
# we do not use the axes_names part because the position of axes names is up to the adapter
_, vlabels, hlabels, raw_data = self.get_axes_labels_and_data_values(row_min, row_max, col_min, col_max)
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f"AbstractAdapter.plot {vlabels=} {hlabels=}")
logger.debug(f"{raw_data=}")
if not isinstance(raw_data, np.ndarray):
# Without dtype=object, in the presence of a string, raw_data will
# be entirely converted to strings which is not what we want.
raw_data = np.asarray(raw_data, dtype=object)
raw_data = raw_data.reshape((raw_data.shape[0], -1))
assert isinstance(raw_data, np.ndarray), f"got data of type {type(raw_data)}"
assert raw_data.ndim == 2, f"ndim is {raw_data.ndim}"
finite_values = get_finite_numeric_values(raw_data)
figure = Figure()
# create an axis
ax = figure.add_subplot()
# we have a list of rows but we want a list of columns
xlabels = list(zip(*hlabels))
ylabels = vlabels
xlabel = self.get_hname()
ylabel = self.get_vname()
height, width = finite_values.shape
if width == 1:
# plot one column
xlabels, ylabels = ylabels, xlabels
xlabel, ylabel = ylabel, xlabel
height, width = width, height
finite_values = finite_values.T
# plot each row as a line
xticklabels = ['\n'.join(str(label) for label in label_col)
for label_col in xlabels]
xdata = np.arange(width)
for data_row, ylabels_row in zip(finite_values, ylabels):
row_label = ' '.join(str(label) for label in ylabels_row)
ax.plot(xdata, data_row, label=row_label)
# set x axis
if xlabel:
ax.set_xlabel(xlabel)
ax.set_xlim((0, width - 1))
# we need to do that because matplotlib is smart enough to
# not show all ticks but a selection. However, that selection
# may include ticks outside the range of x axis
xticks = [t for t in ax.get_xticks().astype(int) if t < len(xticklabels)]
xticklabels = [xticklabels[t] for t in xticks]
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)
# add legend
all_empty_labels = all(not label for yrow in ylabels for label in yrow)
if width != 1 and not all_empty_labels:
kwargs = {'title': ylabel} if ylabel else {}
ax.legend(**kwargs)
return figure
class AbstractColumnarAdapter(AbstractAdapter):
"""For adapters where color is per column"""
def __init__(self, data, attributes=None):
super().__init__(data, attributes)
self.vmin = {}
self.vmax = {}
@timed(logger)
def update_finite_min_max_values(self, finite_values: np.ndarray,
h_start: int, v_start: int,
h_stop: int, v_stop: int):
assert isinstance(self.vmin, dict) and isinstance(self.vmax, dict)
assert h_stop >= h_start
num_cols = h_stop - h_start
# vmin or self.vmin can both be nan (if the whole section data
# is/was nan)
global_vmin = self.vmin
global_vmax = self.vmax
vmin_slice = np.empty(num_cols, dtype=np.float64)
vmax_slice = np.empty(num_cols, dtype=np.float64)
# per column => axis=0
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
local_vmin = np.nanmin(finite_values, axis=0, initial=np.nan)
local_vmax = np.nanmax(finite_values, axis=0, initial=np.nan)
assert local_vmin.shape == (num_cols,), \
(f"unexpected shape: {local_vmin.shape} ({finite_values.shape=}) vs "
f"{(num_cols,)} ({h_start=} {h_stop=})")
for global_col_idx in range(h_start, h_stop):
local_col_idx = global_col_idx - h_start
col_min = np.nanmin([global_vmin.get(global_col_idx, np.nan),
local_vmin[local_col_idx]])
# update the global vmin dict inplace
global_vmin[global_col_idx] = col_min