-
-
Notifications
You must be signed in to change notification settings - Fork 395
/
transform.py
1022 lines (873 loc) · 38.1 KB
/
transform.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
import operator
import sys
from types import BuiltinFunctionType, BuiltinMethodType, FunctionType, MethodType
import numpy as np
import pandas as pd
import param
from ..core.data import PandasInterface
from ..core.dimension import Dimension
from ..core.util import flatten, resolve_dependent_value, unique_iterator
def _maybe_map(numpy_fn):
def fn(values, *args, **kwargs):
series_like = hasattr(values, 'index') and not isinstance(values, list)
map_fn = (getattr(values, 'map_partitions', None) or
getattr(values, 'map_blocks', None))
if map_fn:
if series_like:
return map_fn(
lambda s: type(s)(numpy_fn(s, *args, **kwargs),
index=s.index))
else:
return map_fn(lambda s: numpy_fn(s, *args, **kwargs))
elif series_like:
return type(values)(
numpy_fn(values, *args, **kwargs),
index=values.index,
)
else:
return numpy_fn(values, *args, **kwargs)
return fn
def norm(values, min=None, max=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
values: Array of values to be normalized
min (float, optional): Lower bound of normalization range
max (float, optional): Upper bound of normalization range
Returns:
Array of normalized values
"""
min = np.min(values) if min is None else min
max = np.max(values) if max is None else max
return (values - min) / (max-min)
def lognorm(values, min=None, max=None):
"""Unity-based normalization on log scale.
Apply the same transformation as matplotlib.colors.LogNorm
Args:
values: Array of values to be normalized
min (float, optional): Lower bound of normalization range
max (float, optional): Upper bound of normalization range
Returns:
Array of normalized values
"""
min = np.log(np.min(values)) if min is None else np.log(min)
max = np.log(np.max(values)) if max is None else np.log(max)
return (np.log(values) - min) / (max-min)
class iloc:
"""Implements integer array indexing for dim expressions.
"""
__name__ = 'iloc'
def __init__(self, dim_expr):
self.expr = dim_expr
self.index = slice(None)
def __getitem__(self, index):
self.index = index
return dim(self.expr, self)
def __call__(self, values):
if isinstance(values, (pd.Series, pd.DataFrame)):
return values.iloc[resolve_dependent_value(self.index)]
else:
return values[resolve_dependent_value(self.index)]
class loc:
"""Implements loc for dim expressions.
"""
__name__ = 'loc'
def __init__(self, dim_expr):
self.expr = dim_expr
self.index = slice(None)
def __getitem__(self, index):
self.index = index
return dim(self.expr, self)
def __call__(self, values):
return values.loc[resolve_dependent_value(self.index)]
@_maybe_map
def bin(values, bins, labels=None):
"""Bins data into declared bins
Bins data into declared bins. By default each bin is labelled
with bin center values but an explicit list of bin labels may be
defined.
Args:
values: Array of values to be binned
bins: List or array containing the bin boundaries
labels: List of labels to assign to each bin
If the bins are length N the labels should be length N-1
Returns:
Array of binned values
"""
bins = np.asarray(bins)
if labels is None:
labels = (bins[:-1] + np.diff(bins)/2.)
else:
labels = np.asarray(labels)
dtype = 'float' if labels.dtype.kind == 'f' else 'O'
binned = np.full_like(values, (np.nan if dtype == 'f' else None), dtype=dtype)
for lower, upper, label in zip(bins[:-1], bins[1:], labels):
condition = (values > lower) & (values <= upper)
binned[np.where(condition)[0]] = label
return binned
@_maybe_map
def categorize(values, categories, default=None):
"""Maps discrete values to supplied categories.
Replaces discrete values in input array with a fixed set of
categories defined either as a list or dictionary.
Args:
values: Array of values to be categorized
categories: List or dict of categories to map inputs to
default: Default value to assign if value not in categories
Returns:
Array of categorized values
"""
uniq_cats = list(unique_iterator(values))
cats = []
for c in values:
if isinstance(categories, list):
cat_ind = uniq_cats.index(c)
if cat_ind < len(categories):
cat = categories[cat_ind]
else:
cat = default
else:
cat = categories.get(c, default)
cats.append(cat)
result = np.asarray(cats)
# Convert unicode to object type like pandas does
if result.dtype.kind in ['U', 'S']:
result = result.astype('object')
return result
if hasattr(np, 'isin'):
isin = _maybe_map(np.isin)
else:
# for 1.4 <= numpy < 1.13; in1d() available since 1.4
def _isin(element, test_elements, assume_unique=False, invert=False):
# from 1.13's numpy.lib.arraysetops
element = np.asarray(element)
return np.in1d(element, test_elements, assume_unique=assume_unique,
invert=invert).reshape(element.shape)
isin = _maybe_map(_isin)
del _isin
digitize = _maybe_map(np.digitize)
astype = _maybe_map(np.asarray)
round_ = _maybe_map(np.round)
def _python_isin(array, values):
return [v in values for v in array]
python_isin = _maybe_map(_python_isin)
# Type of numpy function like np.max changed in Numpy 1.25
# from function to a numpy._ArrayFunctionDispatcher.
function_types = (
BuiltinFunctionType, BuiltinMethodType, FunctionType,
MethodType, np.ufunc, iloc, loc, type(np.max)
)
class dim:
"""
dim transform objects are a way to express deferred transforms on
Datasets. dim transforms support all mathematical and bitwise
operators, NumPy ufuncs and methods, and provide a number of
useful methods for normalizing, binning and categorizing data.
"""
_binary_funcs = {
operator.add: '+', operator.and_: '&', operator.eq: '==',
operator.floordiv: '//', operator.ge: '>=', operator.gt: '>',
operator.le: '<=', operator.lshift: '<<', operator.lt: '<',
operator.mod: '%', operator.mul: '*', operator.ne: '!=',
operator.or_: '|', operator.pow: '**', operator.rshift: '>>',
operator.sub: '-', operator.truediv: '/'}
_builtin_funcs = {abs: 'abs', round_: 'round'}
_custom_funcs = {
norm: 'norm',
lognorm: 'lognorm',
bin: 'bin',
categorize: 'categorize',
digitize: 'digitize',
isin: 'isin',
python_isin: 'isin',
astype: 'astype',
round_: 'round',
iloc: 'iloc',
loc: 'loc',
}
_numpy_funcs = {
np.any: 'any', np.all: 'all',
np.cumprod: 'cumprod', np.cumsum: 'cumsum', np.max: 'max',
np.mean: 'mean', np.min: 'min',
np.sum: 'sum', np.std: 'std', np.var: 'var', np.log: 'log',
np.log10: 'log10'}
_unary_funcs = {operator.pos: '+', operator.neg: '-', operator.not_: '~'}
_all_funcs = [_binary_funcs, _builtin_funcs, _custom_funcs,
_numpy_funcs, _unary_funcs]
_namespaces = {'numpy': 'np'}
namespace = 'numpy'
_accessor = None
def __init__(self, obj, *args, **kwargs):
from panel.widgets import Widget
self.ops = []
self._ns = np.ndarray
self.coerce = kwargs.get('coerce', True)
if isinstance(obj, str):
self.dimension = Dimension(obj)
elif isinstance(obj, Dimension):
self.dimension = obj
elif isinstance(obj, param.Parameter):
self.dimension = obj
elif isinstance(obj, Widget):
self.dimension = obj.param.value
else:
self.dimension = obj.dimension
self.ops = obj.ops
if args:
fn = args[0]
else:
fn = None
if fn is not None:
if not (isinstance(fn, function_types+(str,)) or
any(fn in funcs for funcs in self._all_funcs)):
raise ValueError('Second argument must be a function, '
'found %s type' % type(fn))
self.ops = self.ops + [{'args': args[1:], 'fn': fn, 'kwargs': kwargs,
'reverse': kwargs.pop('reverse', False)}]
def __getstate__(self):
return self.__dict__
def __setstate__(self, state):
self.__dict__.update(state)
@property
def _current_accessor(self):
if self.ops and self.ops[-1]['kwargs'].get('accessor'):
return self.ops[-1]['fn']
def __call__(self, *args, **kwargs):
if (not self.ops or not isinstance(self.ops[-1]['fn'], str) or
'accessor' not in self.ops[-1]['kwargs']):
raise ValueError("Cannot call method on %r expression. "
"Only methods accessed via namespaces, "
"e.g. dim(...).df or dim(...).xr), "
"can be called. " % self)
op = self.ops[-1]
if op['fn'] == 'str':
new_op = dict(op, fn=astype, args=(str,), kwargs={})
else:
new_op = dict(op, args=args, kwargs=kwargs)
return self.clone(self.dimension, self.ops[:-1]+[new_op])
def __getattribute__(self, attr):
self_dict = super().__getattribute__('__dict__')
if '_ns' not in self_dict: # Not yet initialized
return super().__getattribute__(attr)
ns = self_dict['_ns']
ops = super().__getattribute__('ops')
if ops and ops[-1]['kwargs'].get('accessor'):
try:
ns = getattr(ns, ops[-1]['fn'])
except Exception:
# If the namespace doesn't know the method we are
# calling then we are using custom API of the dim
# transform itself, so set namespace to None
ns = None
extras = {ns_attr for ns_attr in dir(ns) if not ns_attr.startswith('_')}
if attr in extras and attr not in super().__dir__():
return type(self)(self, attr, accessor=True)
else:
return super().__getattribute__(attr)
def __dir__(self):
ns = self._ns
if self._current_accessor:
ns = getattr(ns, self._current_accessor)
extras = {attr for attr in dir(ns) if not attr.startswith('_')}
try:
return sorted(set(super().__dir__()) | extras)
except Exception:
return sorted(set(dir(type(self))) | set(self.__dict__) | extras)
def __hash__(self):
return hash(repr(self))
def clone(self, dimension=None, ops=None, dim_type=None):
"""
Creates a clone of the dim expression optionally overriding
the dim and ops.
"""
dim_type = dim_type or type(self)
if dimension is None:
dimension = self.dimension
new_dim = dim_type(dimension)
if ops is None:
ops = list(self.ops)
new_dim.ops = ops
return new_dim
@classmethod
def register(cls, key, function):
"""
Register a custom dim transform function which can from then
on be referenced by the key.
"""
cls._custom_funcs[key] = function
@property
def params(self):
if 'panel' in sys.modules:
from panel.widgets.base import Widget
else:
Widget = None
params = {}
for op in self.ops:
op_args = list(op['args'])+list(op['kwargs'].values())
if hasattr(op['fn'], 'index'):
# Special case for loc and iloc to check for parameters
op_args += [op['fn'].index]
op_args = flatten(op_args)
for op_arg in op_args:
if Widget and isinstance(op_arg, Widget):
op_arg = op_arg.param.value
if isinstance(op_arg, dim):
params.update(op_arg.params)
elif isinstance(op_arg, slice):
(start, stop, step) = (op_arg.start, op_arg.stop, op_arg.step)
if Widget and isinstance(start, Widget):
start = start.param.value
if Widget and isinstance(stop, Widget):
stop = stop.param.value
if Widget and isinstance(step, Widget):
step = step.param.value
if isinstance(start, param.Parameter):
params[start.name+str(id(start))] = start
if isinstance(stop, param.Parameter):
params[stop.name+str(id(stop))] = stop
if isinstance(step, param.Parameter):
params[step.name+str(id(step))] = step
if (isinstance(op_arg, param.Parameter) and
isinstance(op_arg.owner, param.Parameterized)):
params[op_arg.name+str(id(op_arg))] = op_arg
return params
# Namespace properties
@property
def df(self):
return self.clone(dim_type=df_dim)
@property
def np(self):
return self.clone(dim_type=dim)
@property
def xr(self):
return self.clone(dim_type=xr_dim)
def __getitem__(self, *index):
return type(self)(self, operator.getitem, *index)
# Builtin functions
def __abs__(self): return type(self)(self, abs)
def __round__(self, ndigits=None):
args = () if ndigits is None else (ndigits,)
return type(self)(self, round_, *args)
# Unary operators
def __neg__(self): return type(self)(self, operator.neg)
def __not__(self): return type(self)(self, operator.not_)
def __invert__(self): return type(self)(self, operator.inv)
def __pos__(self): return type(self)(self, operator.pos)
# Binary operators
def __add__(self, other): return type(self)(self, operator.add, other)
def __and__(self, other): return type(self)(self, operator.and_, other)
def __div__(self, other): return type(self)(self, operator.div, other)
def __eq__(self, other): return type(self)(self, operator.eq, other)
def __floordiv__(self, other): return type(self)(self, operator.floordiv, other)
def __ge__(self, other): return type(self)(self, operator.ge, other)
def __gt__(self, other): return type(self)(self, operator.gt, other)
def __le__(self, other): return type(self)(self, operator.le, other)
def __lt__(self, other): return type(self)(self, operator.lt, other)
def __lshift__(self, other): return type(self)(self, operator.lshift, other)
def __mod__(self, other): return type(self)(self, operator.mod, other)
def __mul__(self, other): return type(self)(self, operator.mul, other)
def __ne__(self, other): return type(self)(self, operator.ne, other)
def __or__(self, other): return type(self)(self, operator.or_, other)
def __rshift__(self, other): return type(self)(self, operator.rshift, other)
def __pow__(self, other): return type(self)(self, operator.pow, other)
def __sub__(self, other): return type(self)(self, operator.sub, other)
def __truediv__(self, other): return type(self)(self, operator.truediv, other)
# Reverse binary operators
def __radd__(self, other): return type(self)(self, operator.add, other, reverse=True)
def __rand__(self, other): return type(self)(self, operator.and_, other)
def __rdiv__(self, other): return type(self)(self, operator.div, other, reverse=True)
def __rfloordiv__(self, other): return type(self)(self, operator.floordiv, other, reverse=True)
def __rlshift__(self, other): return type(self)(self, operator.rlshift, other)
def __rmod__(self, other): return type(self)(self, operator.mod, other, reverse=True)
def __rmul__(self, other): return type(self)(self, operator.mul, other, reverse=True)
def __ror__(self, other): return type(self)(self, operator.or_, other, reverse=True)
def __rpow__(self, other): return type(self)(self, operator.pow, other, reverse=True)
def __rrshift__(self, other): return type(self)(self, operator.rrshift, other)
def __rsub__(self, other): return type(self)(self, operator.sub, other, reverse=True)
def __rtruediv__(self, other): return type(self)(self, operator.truediv, other, reverse=True)
## NumPy operations
def __array_ufunc__(self, *args, **kwargs):
ufunc = args[0]
kwargs = {k: v for k, v in kwargs.items() if v is not None}
return type(self)(self, ufunc, **kwargs)
def clip(self, min=None, max=None):
if min is None and max is None:
raise ValueError('One of max or min must be given.')
return type(self)(self, np.clip, a_min=min, a_max=max)
def any(self, *args, **kwargs): return type(self)(self, np.any, *args, **kwargs)
def all(self, *args, **kwargs): return type(self)(self, np.all, *args, **kwargs)
def cumprod(self, *args, **kwargs): return type(self)(self, np.cumprod, *args, **kwargs)
def cumsum(self, *args, **kwargs): return type(self)(self, np.cumsum, *args,
axis=kwargs.pop('axis',0),
**kwargs)
def max(self, *args, **kwargs): return type(self)(self, np.max, *args, **kwargs)
def mean(self, *args, **kwargs): return type(self)(self, np.mean, *args, **kwargs)
def min(self, *args, **kwargs): return type(self)(self, np.min, *args, **kwargs)
def sum(self, *args, **kwargs): return type(self)(self, np.sum, *args, **kwargs)
def std(self, *args, **kwargs): return type(self)(self, np.std, *args, **kwargs)
def var(self, *args, **kwargs): return type(self)(self, np.var, *args, **kwargs)
def log(self, *args, **kwargs): return type(self)(self, np.log, *args, **kwargs)
def log10(self, *args, **kwargs): return type(self)(self, np.log10, *args, **kwargs)
## Custom functions
def astype(self, dtype): return type(self)(self, astype, dtype=dtype)
def round(self, decimals=0): return type(self)(self, round_, decimals=decimals)
def digitize(self, *args, **kwargs): return type(self)(self, digitize, *args, **kwargs)
def isin(self, *args, **kwargs):
if kwargs.pop('object', None):
return type(self)(self, python_isin, *args, **kwargs)
return type(self)(self, isin, *args, **kwargs)
@property
def iloc(self):
return iloc(self)
def bin(self, bins, labels=None):
"""Bins continuous values.
Bins continuous using the provided bins and assigns labels
either computed from each bins center point or from the
supplied labels.
Args:
bins: List or array containing the bin boundaries
labels: List of labels to assign to each bin
If the bins are length N the labels should be length N-1
"""
return type(self)(self, bin, bins, labels=labels)
def categorize(self, categories, default=None):
"""Replaces discrete values with supplied categories
Replaces discrete values in input array into a fixed set of
categories defined either as a list or dictionary.
Args:
categories: List or dict of categories to map inputs to
default: Default value to assign if value not in categories
"""
return type(self)(self, categorize, categories=categories, default=default)
def lognorm(self, limits=None):
"""Unity-based normalization log scale.
Apply the same transformation as matplotlib.colors.LogNorm
Args:
limits: tuple of (min, max) defining the normalization range
"""
kwargs = {}
if limits is not None:
kwargs = {'min': limits[0], 'max': limits[1]}
return type(self)(self, lognorm, **kwargs)
def norm(self, limits=None):
"""Unity-based normalization to scale data into 0-1 range.
(values - min) / (max - min)
Args:
limits: tuple of (min, max) defining the normalization range
"""
kwargs = {}
if limits is not None:
kwargs = {'min': limits[0], 'max': limits[1]}
return type(self)(self, norm, **kwargs)
@classmethod
def pipe(cls, func, *args, **kwargs):
"""
Wrapper to give multidimensional transforms a more intuitive syntax.
For a custom function 'func' with signature (*args, **kwargs), call as
dim.pipe(func, *args, **kwargs).
"""
args = list(args) # make mutable
for k, arg in enumerate(args):
if isinstance(arg, str):
args[k] = cls(arg)
return cls(args[0], func, *args[1:], **kwargs)
@property
def str(self):
"Casts values to strings or provides str accessor."
return type(self)(self, 'str', accessor=True)
# Other methods
def applies(self, dataset, strict=False):
"""
Determines whether the dim transform can be applied to the
Dataset, i.e. whether all referenced dimensions can be
resolved.
"""
from ..element import Graph
if isinstance(self.dimension, param.Parameter):
applies = True
elif isinstance(self.dimension, dim):
applies = self.dimension.applies(dataset)
elif self.dimension.name == '*':
applies = True
else:
lookup = self.dimension if strict else self.dimension.name
applies = dataset.get_dimension(lookup) is not None
if isinstance(dataset, Graph) and not applies:
applies = dataset.nodes.get_dimension(lookup) is not None
for op in self.ops:
args = op.get('args')
if not args:
continue
for arg in args:
if isinstance(arg, dim):
applies &= arg.applies(dataset)
kwargs = op.get('kwargs')
for kwarg in kwargs.values():
if isinstance(kwarg, dim):
applies &= kwarg.applies(dataset)
return applies
def interface_applies(self, dataset, coerce):
return True
def _resolve_op(self, op, dataset, data, flat, expanded, ranges,
all_values, keep_index, compute, strict):
args = op['args']
fn = op['fn']
kwargs = dict(op['kwargs'])
fn_name = self._numpy_funcs.get(fn)
if fn_name and hasattr(data, fn_name):
if 'axis' not in kwargs and not isinstance(fn, np.ufunc):
kwargs['axis'] = None
fn = fn_name
if isinstance(fn, str):
accessor = kwargs.pop('accessor', None)
fn_args = []
else:
accessor = False
fn_args = [data]
for arg in args:
if isinstance(arg, dim):
arg = arg.apply(
dataset, flat, expanded, ranges, all_values,
keep_index, compute, strict
)
arg = resolve_dependent_value(arg)
fn_args.append(arg)
fn_kwargs = {}
for k, v in kwargs.items():
if isinstance(v, dim):
v = v.apply(
dataset, flat, expanded, ranges, all_values,
keep_index, compute, strict
)
fn_kwargs[k] = resolve_dependent_value(v)
args = tuple(fn_args[::-1] if op['reverse'] else fn_args)
kwargs = dict(fn_kwargs)
return fn, fn_name, args, kwargs, accessor
def _apply_fn(self, dataset, data, fn, fn_name, args, kwargs, accessor, drange):
if (((fn is norm) or (fn is lognorm)) and drange != {} and
not ('min' in kwargs and 'max' in kwargs)):
data = fn(data, *drange)
elif isinstance(fn, str):
method = getattr(data, fn, None)
if method is None:
mtype = 'attribute' if accessor else 'method'
raise AttributeError(
f"{self!r} could not be applied to '{dataset!r}', '{fn}' {mtype} "
f"does not exist on {type(data).__name__} type."
)
if accessor:
data = method
else:
try:
data = method(*args, **kwargs)
except Exception as e:
if 'axis' in kwargs:
kwargs.pop('axis')
data = method(*args, **kwargs)
else:
raise e
else:
data = fn(*args, **kwargs)
return data
def _compute_data(self, data, drop_index, compute):
"""
Implements conversion of data from namespace specific object,
e.g. pandas Series to NumPy array.
"""
if hasattr(data, 'compute') and compute:
data = data.compute()
return data
def _coerce(self, data):
"""
Implements coercion of data from current data format to the
namespace specific datatype.
"""
return data
def apply(self, dataset, flat=False, expanded=None, ranges=None, all_values=False,
keep_index=False, compute=True, strict=False):
"""Evaluates the transform on the supplied dataset.
Args:
dataset: Dataset object to evaluate the expression on
flat: Whether to flatten the returned array
expanded: Whether to use the expanded expand values
ranges: Dictionary for ranges for normalization
all_values: Whether to evaluate on all values
Whether to evaluate on all available values, for some
element types, such as Graphs, this may include values
not included in the referenced column
keep_index: For data types that support indexes, whether the index
should be preserved in the result.
compute: For data types that support lazy evaluation, whether
the result should be computed before it is returned.
strict: Whether to strictly check for dimension matches
(if False, counts any dimensions with matching names as the same)
Returns:
values: NumPy array computed by evaluating the expression
"""
from ..element import Graph
if ranges is None:
ranges = {}
dimension = self.dimension
if expanded is None:
expanded = not ((dataset.interface.gridded and dimension in dataset.kdims) or
(dataset.interface.multi and dataset.interface.isunique(dataset, dimension, True)))
if not self.applies(dataset) and (not isinstance(dataset, Graph) or not self.applies(dataset.nodes)):
raise KeyError(f"One or more dimensions in the expression {self!r} "
f"could not resolve on '{dataset}'. Ensure all "
"dimensions referenced by the expression are "
"present on the supplied object.")
if not self.interface_applies(dataset, coerce=self.coerce):
if self.coerce:
raise ValueError(f"The expression {self!r} assumes a {self.namespace}-like "
f"API but the dataset contains {dataset.interface.datatype} data "
"and cannot be coerced.")
else:
raise ValueError(f"The expression {self!r} assumes a {self.namespace}-like "
f"API but the dataset contains {dataset.interface.datatype} data "
"and coercion is disabled.")
if isinstance(dataset, Graph):
if dimension in dataset.kdims and all_values:
dimension = dataset.nodes.kdims[2]
dataset = dataset if dimension in dataset else dataset.nodes
dataset = self._coerce(dataset)
if self.namespace != 'numpy':
compute_for_compute = False
keep_index_for_compute = True
else:
compute_for_compute = compute
keep_index_for_compute = keep_index
if dimension.name == '*':
data = dataset.data
eldim = None
elif isinstance(dimension, param.Parameter):
data = getattr(dimension.owner, dimension.name)
eldim = None
else:
lookup = dimension if strict else dimension.name
eldim = dataset.get_dimension(lookup).name
data = dataset.interface.values(
dataset, lookup, expanded=expanded, flat=flat,
compute=compute_for_compute, keep_index=keep_index_for_compute
)
for op in self.ops:
fn, fn_name, args, kwargs, accessor = self._resolve_op(
op, dataset, data, flat, expanded, ranges, all_values,
keep_index_for_compute, compute_for_compute, strict
)
drange = ranges.get(eldim, {})
drange = drange.get('combined', drange)
data = self._apply_fn(dataset, data, fn, fn_name, args,
kwargs, accessor, drange)
drop_index = keep_index_for_compute and not keep_index
compute = not compute_for_compute and compute
if (drop_index or compute):
data = self._compute_data(data, drop_index, compute)
return data
def __repr__(self):
op_repr = f"'{self.dimension}'"
accessor = False
for i, o in enumerate(self.ops):
if i == 0:
prev = 'dim({repr}'
elif accessor:
prev = '{repr}'
else:
prev = '({repr}'
fn = o['fn']
ufunc = isinstance(fn, np.ufunc)
args = ', '.join([repr(r) for r in o['args']]) if o['args'] else ''
kwargs = o['kwargs']
prev_accessor = accessor
accessor = kwargs.pop('accessor', None)
kwargs = sorted(kwargs.items(), key=operator.itemgetter(0))
kwargs = '%s' % ', '.join(['{}={!r}'.format(*item) for item in kwargs]) if kwargs else ''
if fn in self._binary_funcs:
fn_name = self._binary_funcs[o['fn']]
if o['reverse']:
format_string = '{args}{fn}'+prev
else:
format_string = prev+'){fn}{args}'
if any(isinstance(a, dim) for a in o['args']):
format_string = format_string.replace('{args}', '({args})')
elif fn in self._unary_funcs:
fn_name = self._unary_funcs[fn]
format_string = '{fn}' + prev
else:
if isinstance(fn, str):
fn_name = fn
else:
fn_name = fn.__name__
if fn in self._builtin_funcs:
fn_name = self._builtin_funcs[fn]
format_string = '{fn}'+prev
elif isinstance(fn, str):
if accessor:
sep = '' if op_repr.endswith(')') or prev_accessor else ')'
format_string = prev+sep+'.{fn}'
else:
format_string = prev+').{fn}('
elif fn in self._numpy_funcs:
fn_name = self._numpy_funcs[fn]
format_string = prev+').{fn}('
elif isinstance(fn, iloc):
format_string = prev+f').iloc[{fn.index!r}]'
elif isinstance(fn, loc):
format_string = prev+f').loc[{fn.index!r}]'
elif fn in self._custom_funcs:
fn_name = self._custom_funcs[fn]
format_string = prev+').{fn}('
elif ufunc:
fn_name = str(fn)[8:-2]
if not (prev.startswith('dim') or prev.endswith(')')):
format_string = '{fn}' + prev
else:
format_string = '{fn}(' + prev
if fn_name in dir(np):
format_string = '.'.join([self._namespaces['numpy'], format_string])
else:
format_string = prev+', {fn}'
if accessor:
pass
elif args:
if not format_string.endswith('('):
format_string += ', '
format_string += '{args}'
if kwargs:
format_string += ', {kwargs}'
elif kwargs:
if not format_string.endswith('('):
format_string += ', '
format_string += '{kwargs}'
# Insert accessor
if i == 0 and self._accessor and ')' in format_string:
idx = format_string.index(')')
format_string = ''.join([
format_string[:idx], ').', self._accessor,
format_string[idx+1:]
])
op_repr = format_string.format(fn=fn_name, repr=op_repr,
args=args, kwargs=kwargs)
if op_repr.count('(') - op_repr.count(')') > 0:
op_repr += ')'
if not self.ops:
op_repr = f'dim({op_repr})'
if op_repr.count('(') - op_repr.count(')') > 0:
op_repr += ')'
return op_repr
class df_dim(dim):
"""
A subclass of dim which provides access to the DataFrame namespace
along with tab-completion and type coercion allowing the expression
to be applied on any columnar dataset.
"""
namespace = 'dataframe'
_accessor = 'pd'
def __init__(self, obj, *args, **kwargs):
super().__init__(obj, *args, **kwargs)
self._ns = pd.Series
def interface_applies(self, dataset, coerce):
return (not dataset.interface.gridded and
(coerce or isinstance(dataset.interface, PandasInterface)))
def _compute_data(self, data, drop_index, compute):
if hasattr(data, 'compute') and compute:
data = data.compute()
if not drop_index:
return data
if compute and hasattr(data, 'to_numpy'):
return data.to_numpy()
return data.values
def _coerce(self, dataset):
if self.interface_applies(dataset, coerce=False):
return dataset
pandas_interfaces = param.concrete_descendents(PandasInterface)
datatypes = [intfc.datatype for intfc in pandas_interfaces.values()
if dataset.interface.multi == intfc.multi]
return dataset.clone(datatype=datatypes)
@property
def loc(self):
return loc(self)
class xr_dim(dim):
"""
A subclass of dim which provides access to the xarray DataArray
namespace along with tab-completion and type coercion allowing
the expression to be applied on any gridded dataset.
"""
namespace = 'xarray'
_accessor = 'xr'
def __init__(self, obj, *args, **kwargs):
try:
import xarray as xr
except ImportError:
raise ImportError("XArray could not be imported, dim().xr "
"requires the xarray to be available.")
super().__init__(obj, *args, **kwargs)
self._ns = xr.DataArray
def interface_applies(self, dataset, coerce):
return (dataset.interface.gridded and
(coerce or dataset.interface.datatype == 'xarray'))
def _compute_data(self, data, drop_index, compute):
if drop_index:
data = data.data
if hasattr(data, 'compute') and compute:
data = data.compute()
return data
def _coerce(self, dataset):
if self.interface_applies(dataset, coerce=False):
return dataset
return dataset.clone(datatype=['xarray'])
def lon_lat_to_easting_northing(longitude, latitude):
"""
Projects the given longitude, latitude values into Web Mercator
(aka Pseudo-Mercator or EPSG:3857) coordinates.
Longitude and latitude can be provided as scalars, Pandas columns,
or Numpy arrays, and will be returned in the same form. Lists
or tuples will be converted to Numpy arrays.
Args:
longitude
latitude
Returns:
(easting, northing)
Examples:
easting, northing = lon_lat_to_easting_northing(-74,40.71)
easting, northing = lon_lat_to_easting_northing(
np.array([-74]),np.array([40.71])
)
df=pandas.DataFrame(dict(longitude=np.array([-74]),latitude=np.array([40.71])))
df.loc[:, 'longitude'], df.loc[:, 'latitude'] = lon_lat_to_easting_northing(
df.longitude,df.latitude
)
"""
if isinstance(longitude, (list, tuple)):
longitude = np.array(longitude)
if isinstance(latitude, (list, tuple)):
latitude = np.array(latitude)
origin_shift = np.pi * 6378137
easting = longitude * origin_shift / 180.0
with np.errstate(divide='ignore', invalid='ignore'):
northing = np.log(
np.tan((90 + latitude) * np.pi / 360.0)
) * origin_shift / np.pi
return easting, northing
def easting_northing_to_lon_lat(easting, northing):
"""
Projects the given easting, northing values into
longitude, latitude coordinates.