Repository navigation
Expand file tree
/
Copy pathquadmesh.py
More file actions
972 lines (815 loc) · 36.9 KB
/
Copy pathquadmesh.py
File metadata and controls
972 lines (815 loc) · 36.9 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
import math
from toolz import memoize
import numpy as np
from datashader.glyphs.glyph import Glyph
from datashader.resampling import infer_interval_breaks, infer_interval_breaks_2d
from datashader.utils import isreal, ngjit, ngjit_parallel
import numba
from numba import cuda, prange
try:
import dask.array as dask_array
except ImportError:
dask_array = None
try:
import cupy
from datashader.transfer_functions._cuda_utils import cuda_args
except Exception:
cupy = None
cuda_args = None
def _inner_make_3d_func_from_2d(*, n_arrays, func, prefix_idx):
# Generate the 3D function source
prefix_str = ', '.join([f"pre{i}" for i in range(prefix_idx)])
arrays_str = ', '.join([f"arr{i}" for i in range(n_arrays)])
array_idx_str = ', '.join([f"arr{i}[z]" for i in range(n_arrays)])
func_source = f"""\
def func_3d({prefix_str}, nz, {arrays_str}):
for z in prange(nz):
func({prefix_str}, {array_idx_str})"""
# Compile the function
local_vars = {'prange': prange, 'func': func}
exec(func_source, local_vars)
return local_vars["func_3d"]
def _make_3d_from_2d(func, prefix_idx, parallel=True):
"""
Factory function that generates cached 3D wrappers from 2D quadmesh functions.
This helper eliminates boilerplate by automatically generating 3D wrapper functions
that loop over the z-dimension (bands) and call a 2D function for each slice. It
replaces ~10 lines of repetitive code per factory with a single function call.
For example, if func is extend_cpu(xs, ys, shape, *aggs_and_cols) then prefix_idx is 3:
@ngjit_parallel
def func_3d(arg0, arg1, arg2, nz, arr0, arr1, arr2):
for z in prange(nz):
func(arg0, arg1, arg2, arr0[z], arr1[z], arr2[z])
Parameters
----------
func : callable
The 2D function to wrap. Should accept (prefix_params..., *aggs_and_cols).
May be decorated by @ngjit and @expand_aggs_and_cols.
prefix_idx : int
These are the parameters that come before *aggs_and_cols.
Example:
- extend_cpu(xs, ys, shape, *aggs_and_cols) -> prefix_idx=3
parallel : bool, optional
Whether to use parallel execution over z-dimension (default True).
Returns
-------
callable
A factory function factory_3d(n_arrays) that returns cached compiled 3D wrappers.
The factory maintains an internal cache keyed by n_arrays.
"""
cache = {}
decorator = ngjit_parallel if parallel else ngjit
def factory_3d(n_arrays):
if n_arrays not in cache:
func_3d = _inner_make_3d_func_from_2d(
n_arrays=n_arrays,
func=func,
prefix_idx=prefix_idx
)
cache[n_arrays] = decorator(func_3d)
return cache[n_arrays]
return factory_3d
class _CUDAStreamPool:
def __init__(self, max_streams=5):
# max_streams chosen based on https://forums.developer.nvidia.com/t/how-many-streams-maximum-number-of-streams/6571/4
self.streams = [cuda.stream() for _ in range(max_streams)]
def get_streams(self, n_required):
"""Get streams for n_required parallel executions."""
return self.streams[:min(n_required, len(self.streams))]
_cuda_stream_pool = None
def _make_3d_from_2d_cuda(kernel_2d, prefix_idx):
"""
Factory function that creates 3D CUDA wrappers using parallel streams.
This is the GPU equivalent of _make_3d_from_2d, creating wrappers that launch
2D CUDA kernels in parallel streams for each z-slice. This achieves true
parallelism on GPU, similar to how prange provides parallelism on CPU.
Parameters
----------
kernel_2d : cuda kernel
The 2D CUDA kernel to wrap (e.g., upsample_cuda, extend_cuda).
Must be a @cuda.jit decorated function.
prefix_idx : int
Number of arguments before nz and arrays.
Example: For raster (src_w, src_h, ..., out_h, nz, agg, col) -> prefix_idx=10
Returns
-------
callable
A factory function factory_3d(grid_shape) that returns a wrapper function
for launching kernels in parallel streams.
"""
def factory_3d(grid_shape):
"""
Factory that takes grid_shape and returns the 3D wrapper.
Parameters
----------
grid_shape : tuple
(width, height) tuple for cuda_args grid computation.
Returns
-------
callable
Wrapper function that launches 2D kernel in parallel streams for each z-slice.
"""
# Global stream pool for parallel 3D CUDA kernel launches
global _cuda_stream_pool
if _cuda_stream_pool is None:
_cuda_stream_pool = _CUDAStreamPool()
def wrapper(*args):
# Split args: prefix, nz, arrays
prefix_args = args[:prefix_idx]
nz = args[prefix_idx]
arrays = args[prefix_idx + 1:]
# Get grid configuration (blocks, threads_per_block)
grid_config = cuda_args(grid_shape)
# Get streams for parallelization
streams = _cuda_stream_pool.get_streams(nz)
# Launch in parallel streams
for z in range(nz):
stream_idx = z % len(streams)
z_arrays = tuple(arr[z] if arr.ndim == 3 else arr for arr in arrays)
# In Numba CUDA, pass stream as third element in kernel launcher config
kernel = kernel_2d[(*grid_config, streams[stream_idx])]
kernel(*prefix_args, *z_arrays)
# Synchronize all used streams
cuda.synchronize()
return wrapper
return factory_3d
def _cuda_mapper(mapper):
@cuda.jit
def kernel(in_array, out_array):
i, j = cuda.grid(2)
if i < out_array.shape[0] and j < out_array.shape[1]:
out_array[i, j] = mapper(in_array[i, j])
def cuda_map(in_array):
out_array = cupy.zeros(in_array.shape, dtype='float64')
in_array = cuda.to_device(in_array)
kernel[cuda_args(in_array.shape)](in_array, out_array)
return out_array
return cuda_map
class _QuadMeshLike(Glyph):
def __init__(self, x, y, name):
self.x = x
self.y = y
self.name = name
@property
def ndims(self):
return 2
@property
def inputs(self):
return (self.x, self.y, self.name)
def validate(self, in_dshape):
if not isreal(in_dshape.measure[str(self.x)]):
raise ValueError('x must be real')
elif not isreal(in_dshape.measure[str(self.y)]):
raise ValueError('y must be real')
elif not isreal(in_dshape.measure[str(self.name)]):
raise ValueError('aggregate value must be real')
@property
def x_label(self):
return self.x
@property
def y_label(self):
return self.y
@staticmethod
def _get_shape_info(aggs):
"""
Get shape info, handling both 2D and 3D cases.
Returns
-------
tuple
(is_3d, nz, plot_height, plot_width)
For 2D: (False, None, height, width)
For 3D: (True, nz, height, width)
"""
if aggs[0].ndim == 3:
nz, plot_height, plot_width = aggs[0].shape
return True, nz, plot_height, plot_width
else:
plot_height, plot_width = aggs[0].shape
return False, None, plot_height, plot_width
class QuadMeshRectilinear(_QuadMeshLike):
def _compute_bounds_from_1d_centers(
self, xr_ds, dim, maybe_expand=False, orient=True
):
vals = xr_ds[dim].values
# Assume dimension is sorted in ascending or descending order
v0, v1, v_nm1, v_n = [
vals[i] for i in [0, 1, -2, -1]
]
# Check if we should swap order
if v_n < v0:
descending = True
v0, v1, v_nm1, v_n = v_n, v_nm1, v1, v0
else:
descending = False
bounds = (v0 - 0.5 * (v1 - v0), v_n + 0.5 * (v_n - v_nm1))
if not orient and descending:
# swap back to descending order
bounds = bounds[1], bounds[0]
if maybe_expand:
bounds = self.maybe_expand_bounds(bounds)
return bounds
def compute_x_bounds(self, xr_ds):
return self._compute_bounds_from_1d_centers(xr_ds, self.x, maybe_expand=True)
def compute_y_bounds(self, xr_ds):
return self._compute_bounds_from_1d_centers(xr_ds, self.y, maybe_expand=True)
def compute_bounds_dask(self, xr_ds):
return self.compute_x_bounds(xr_ds), self.compute_y_bounds(xr_ds)
def infer_interval_breaks(self, centers):
# Infer breaks for 1D array of centers
return infer_interval_breaks(centers)
@memoize
def _build_extend(self, x_mapper, y_mapper, info, append, _antialias_stage_2,
_antialias_stage_2_funcs):
x_name = self.x
y_name = self.y
name = self.name
@ngjit
@self.expand_aggs_and_cols(append)
def perform_extend(i, j, xs, ys, shape, *aggs_and_cols):
x0i, x1i = xs[i], xs[i + 1]
# Make sure x0 <= x1
if x0i > x1i:
x0i, x1i = x1i, x0i
# Make sure single pixel quads are represented
if x0i == x1i and shape[1] != x1i:
x1i += 1
y0i, y1i = ys[j], ys[j + 1]
# Make sure y0 <= y1
if y0i > y1i:
y0i, y1i = y1i, y0i
# Make sure single pixel quads are represented
if y0i == y1i and shape[0] != y1i:
y1i += 1
# x1i and y1i are not included in the iteration. this
# serves to avoid overlapping quads and it avoids the need
# for special handling of quads that end on exactly on the
# upper bound.
for xi in range(x0i, x1i):
for yi in range(y0i, y1i):
append(j, i, xi, yi, *aggs_and_cols)
@cuda.jit
@self.expand_aggs_and_cols(append)
def extend_cuda(xs, ys, shape, *aggs_and_cols):
i, j = cuda.grid(2)
if i < (xs.shape[0] - 1) and j < (ys.shape[0] - 1):
perform_extend(i, j, xs, ys, shape, *aggs_and_cols)
@ngjit
@self.expand_aggs_and_cols(append)
def extend_cpu(xs, ys, shape, *aggs_and_cols):
for i in range(len(xs) - 1):
for j in range(len(ys) - 1):
perform_extend(i, j, xs, ys, shape, *aggs_and_cols)
extend_cpu_3d = _make_3d_from_2d(extend_cpu, 3)
extend_cuda_3d = _make_3d_from_2d_cuda(extend_cuda, 3)
def extend(aggs, xr_ds, vt, bounds, x_breaks=None, y_breaks=None):
from datashader.core import LinearAxis
use_cuda = cupy and isinstance(xr_ds[name].data, cupy.ndarray)
# Build axis transform (mapper) functions
if use_cuda:
x_mapper2 = _cuda_mapper(x_mapper)
y_mapper2 = _cuda_mapper(y_mapper)
else:
x_mapper2 = x_mapper
y_mapper2 = y_mapper
# Convert from bin centers to interval edges
if x_breaks is None:
if use_cuda:
x_centers = cupy.array(xr_ds[x_name].data)
else:
x_centers = xr_ds[x_name].values
x_breaks = self.infer_interval_breaks(x_centers)
else:
# The copy is necessary given that dask_xarray calculates x_breaks once
# for the whole array, and then passes slices of that
# array in for each chunk. We use in-place ops below,
# so make a copy here first.
x_breaks = x_breaks.copy()
if y_breaks is None:
if use_cuda:
y_centers = cupy.array(xr_ds[y_name].data)
else:
y_centers = xr_ds[y_name].values
y_breaks = self.infer_interval_breaks(y_centers)
else:
# The copy is necessary given that dask_xarray calculates y_breaks once
# for the whole array, and then passes slices of that
# array in for each chunk. We use in-place ops below,
# so make a copy here first.
y_breaks = y_breaks.copy()
x0, x1, y0, y1 = bounds
xspan = x1 - x0
yspan = y1 - y0
if x_mapper is LinearAxis.mapper:
xscaled = x_breaks
else:
xscaled = x_mapper2(x_breaks)
xscaled -= x0
xscaled /= xspan
if y_mapper is LinearAxis.mapper:
yscaled = y_breaks
else:
yscaled = y_mapper2(y_breaks)
yscaled -= y0
yscaled /= yspan
# Find intervals that overlap the canvas bounds [0,1]
# This handles both ascending and descending coordinate orders
if xscaled[0] > xscaled[1]:
xscaled = xscaled[::-1]
xr_ds = xr_ds.isel({x_name: slice(None, None, -1)})
if yscaled[0] > yscaled[1]:
yscaled = yscaled[::-1]
xr_ds = xr_ds.isel({y_name: slice(None, None, -1)})
_0 = cupy.array(0) if use_cuda else 0
_1 = cupy.array(1) if use_cuda else 1
xm0 = max(np.searchsorted(xscaled, _0, "right") - 1, 0)
xm1 = np.searchsorted(xscaled, _1, "left")
ym0 = max(np.searchsorted(yscaled, _0, "right") - 1, 0)
ym1 = np.searchsorted(yscaled, _1, "left")
if xm0 == xm1 or ym0 == ym1:
return
# Get shape info for 3D or 2D case
is_3d, nz, plot_height, plot_width = self._get_shape_info(aggs)
xp = cupy if use_cuda else np
# Downselect xs and ys and convert to int
xs = xscaled[xm0:xm1 + 1]
xs *= plot_width
xs = xs.astype(int)
xp.clip(xs, 0, plot_width, out=xs)
ys = yscaled[ym0:ym1 + 1]
ys *= plot_height
ys = ys.astype(int)
xp.clip(ys, 0, plot_height, out=ys)
if is_3d:
cols_full = info(xr_ds.transpose(..., y_name, x_name), aggs[0].shape)
cols = tuple([c[:, ym0:ym1, xm0:xm1] for c in cols_full])
aggs_and_cols = aggs + cols
if use_cuda:
do_extend = extend_cuda_3d(grid_shape=(xs.shape[0] - 1, ys.shape[0] - 1))
else:
do_extend = extend_cpu_3d(n_arrays=len(aggs_and_cols))
do_extend(xs, ys, (plot_height, plot_width), nz, *aggs_and_cols)
else:
cols_full = info(xr_ds.transpose(y_name, x_name), aggs[0].shape)
cols = tuple([c[ym0:ym1, xm0:xm1] for c in cols_full])
aggs_and_cols = aggs + cols
if use_cuda:
do_extend = extend_cuda[cuda_args(xr_ds[name].shape)]
else:
do_extend = extend_cpu
do_extend(xs, ys, (plot_height, plot_width), *aggs_and_cols)
return extend
@ngjit
def build_scale_translate(out_size, out0, out1, src_size, src0, src1):
translate_y = src_size * (out0 - src0) / (src1 - src0)
scale_y = (src_size * (out1 - out0)) / (out_size * (src1 - src0))
return scale_y, translate_y
class QuadMeshRaster(QuadMeshRectilinear):
def is_upsample(self, source, x, y, name, x_range, y_range, out_w, out_h):
# Check upsampling in x
src_w = len(source[x])
if x_range is None:
upsample_width = out_w >= src_w
else:
out_x0, out_x1 = x_range
src_x0, src_x1 = self._compute_bounds_from_1d_centers(
source, x, maybe_expand=False, orient=False
)
src_xbinsize = math.fabs((src_x1 - src_x0) / src_w)
out_xbinsize = math.fabs((out_x1 - out_x0) / out_w)
upsample_width = src_xbinsize >= out_xbinsize
# Check upsampling in y
src_h = len(source[y])
if y_range is None:
upsample_height = out_h >= src_h
else:
out_y0, out_y1 = y_range
src_y0, src_y1 = self._compute_bounds_from_1d_centers(
source, y, maybe_expand=False, orient=False
)
src_ybinsize = math.fabs((src_y1 - src_y0) / src_h)
out_ybinsize = math.fabs((out_y1 - out_y0) / out_h)
upsample_height = src_ybinsize >= out_ybinsize
return upsample_width, upsample_height
@memoize
def _build_extend(self, x_mapper, y_mapper, info, append, _antialias_stage_2,
_antialias_stage_2_funcs):
x_name = self.x
y_name = self.y
name = self.name
@ngjit_parallel
def upsample_cpu(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, agg, col
):
for out_j in prange(out_h):
src_j = int(math.floor(scale_y * (out_j + 0.5) + translate_y - offset_y))
for out_i in range(out_w):
src_i = int(math.floor(scale_x * (out_i + 0.5) + translate_x - offset_x))
if src_j < 0 or src_j >= src_h or src_i < 0 or src_i >= src_w:
agg[out_j, out_i] = np.nan
else:
agg[out_j, out_i] = col[src_j, src_i]
@cuda.jit
def upsample_cuda(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, agg, col
):
out_i, out_j = cuda.grid(2)
if out_i < out_w and out_j < out_h:
src_j = int(math.floor(scale_y * (out_j + 0.5) + translate_y - offset_y))
src_i = int(math.floor(scale_x * (out_i + 0.5) + translate_x - offset_x))
if src_j < 0 or src_j >= src_h or src_i < 0 or src_i >= src_w:
agg[out_j, out_i] = np.nan
else:
agg[out_j, out_i] = col[src_j, src_i]
@ngjit_parallel
@self.expand_aggs_and_cols(append)
def downsample_cpu(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, *aggs_and_cols
):
for out_j in prange(out_h):
# Calculate raw indices first
raw_j0 = math.floor(scale_y * (out_j + 0.0) + translate_y - offset_y)
raw_j1 = math.floor(scale_y * (out_j + 1.0) + translate_y - offset_y)
# Handle negative scale_y (descending coordinates) - swap before clamping
if scale_y < 0 and raw_j0 > raw_j1:
raw_j0, raw_j1 = raw_j1, raw_j0
# Now clamp to valid range
src_j0 = int(max(raw_j0, 0))
src_j1 = int(min(raw_j1, src_h))
for out_i in range(out_w):
src_i0 = int(max(
math.floor(scale_x * (out_i + 0.0) + translate_x - offset_x), 0
))
src_i1 = int(min(
math.floor(scale_x * (out_i + 1.0) + translate_x - offset_x), src_w
))
for src_j in range(src_j0, src_j1):
for src_i in range(src_i0, src_i1):
append(src_j, src_i, out_i, out_j, *aggs_and_cols)
@cuda.jit
@self.expand_aggs_and_cols(append)
def downsample_cuda(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, *aggs_and_cols
):
out_i, out_j = cuda.grid(2)
if out_i < out_w and out_j < out_h:
# Calculate raw indices first
raw_j0 = math.floor(scale_y * (out_j + 0.0) + translate_y - offset_y)
raw_j1 = math.floor(scale_y * (out_j + 1.0) + translate_y - offset_y)
# Handle negative scale_y (descending coordinates) - swap before clamping
if scale_y < 0 and raw_j0 > raw_j1:
raw_j0, raw_j1 = raw_j1, raw_j0
# Now clamp to valid range
src_j0 = max(raw_j0, 0)
src_j1 = min(raw_j1, src_h)
src_i0 = max(
math.floor(scale_x * (out_i + 0.0) + translate_x - offset_x), 0
)
src_i1 = min(
math.floor(scale_x * (out_i + 1.0) + translate_x - offset_x), src_w
)
for src_j in range(src_j0, src_j1):
for src_i in range(src_i0, src_i1):
append(src_j, src_i, out_i, out_j, *aggs_and_cols)
# We don't parallelize cpu since 2d funcs are already parallelized
# and expect out_h >> z-dimension
upsample_cpu_3d = _make_3d_from_2d(upsample_cpu, 10, parallel=False)
downsample_cpu_3d = _make_3d_from_2d(downsample_cpu, 10, parallel=False)
upsample_cuda_3d = _make_3d_from_2d_cuda(upsample_cuda, 10)
downsample_cuda_3d = _make_3d_from_2d_cuda(downsample_cuda, 10)
def extend(aggs, xr_ds, vt, bounds,
scale_x=None, scale_y=None, translate_x=None, translate_y=None,
offset_x=None, offset_y=None, src_xbinsize=None, src_ybinsize=None):
use_cuda = cupy and isinstance(xr_ds[name].data, cupy.ndarray)
# Get shape info for 3D or 2D case
is_3d, nz, out_h, out_w = self._get_shape_info(aggs)
# Compute output constants
out_x0, out_x1, out_y0, out_y1 = bounds
out_xbinsize = math.fabs((out_x1 - out_x0) / out_w)
out_ybinsize = math.fabs((out_y1 - out_y0) / out_h)
# Compute source constants
# For 3D, need to transpose with the third dimension first
if is_3d:
# Get the third dimension name (e.g., 'band')
third_dim = [d for d in xr_ds[name].dims if d not in (x_name, y_name)][0]
xr_ds = xr_ds.transpose(third_dim, y_name, x_name)
nz_src, src_h, src_w = xr_ds[name].shape
else:
xr_ds = xr_ds.transpose(y_name, x_name)
src_h, src_w = xr_ds[name].shape
if (scale_x is None or scale_y is None or
translate_x is None or translate_y is None or
offset_x is None or offset_y is None or
src_xbinsize is None or src_ybinsize is None ):
# Compute bin sizes from bounds
src_x0, src_x1 = self._compute_bounds_from_1d_centers(
xr_ds, x_name, maybe_expand=False, orient=False
)
src_y0, src_y1 = self._compute_bounds_from_1d_centers(
xr_ds, y_name, maybe_expand=False, orient=False
)
src_xbinsize = math.fabs((src_x1 - src_x0) / src_w)
src_ybinsize = math.fabs((src_y1 - src_y0) / src_h)
# Compute scale/translate
scale_y, translate_y = build_scale_translate(
out_h, out_y0, out_y1, src_h, src_y0, src_y1
)
scale_x, translate_x = build_scale_translate(
out_w, out_x0, out_x1, src_w, src_x0, src_x1
)
offset_x = offset_y = 0
# Build aggs_and_cols tuple
cols = info(xr_ds, aggs[0].shape[-2:])
aggs_and_cols = tuple(aggs) + tuple(cols)
if src_h == 0 or src_w == 0 or out_h == 0 or out_w == 0:
# Nothing to do
return
elif src_xbinsize >= out_xbinsize and src_ybinsize >= out_ybinsize:
# Upsample
if is_3d:
if use_cuda:
do_sampling = upsample_cuda_3d(grid_shape=(out_w, out_h))
else:
do_sampling = upsample_cpu_3d(n_arrays=len(aggs_and_cols))
do_sampling(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, nz, aggs[0], cols[0]
)
else:
if use_cuda:
do_sampling = upsample_cuda[cuda_args((out_w, out_h))]
else:
do_sampling = upsample_cpu
return do_sampling(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, aggs[0], cols[0]
)
else:
# Downsample. Note that caller is responsible for making sure to not
# mix upsampling and downsampling.
if is_3d:
if use_cuda:
do_sampling = downsample_cuda_3d(grid_shape=(out_w, out_h))
else:
do_sampling = downsample_cpu_3d(n_arrays=len(aggs_and_cols))
do_sampling(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, nz, *aggs_and_cols
)
else:
# 2D downsample
if use_cuda:
do_sampling = downsample_cuda[cuda_args((out_w, out_h))]
else:
do_sampling = downsample_cpu
return do_sampling(
src_w, src_h, translate_x, translate_y, scale_x, scale_y,
offset_x, offset_y, out_w, out_h, *aggs_and_cols
)
return extend
class QuadMeshCurvilinear(_QuadMeshLike):
def compute_x_bounds(self, xr_ds):
x_breaks = self.infer_interval_breaks(xr_ds[self.x].values)
bounds = Glyph._compute_bounds_2d(x_breaks)
return self.maybe_expand_bounds(bounds)
def compute_y_bounds(self, xr_ds):
y_breaks = self.infer_interval_breaks(xr_ds[self.y].values)
bounds = Glyph._compute_bounds_2d(y_breaks)
return self.maybe_expand_bounds(bounds)
def compute_bounds_dask(self, xr_ds):
return self.compute_x_bounds(xr_ds), self.compute_y_bounds(xr_ds)
def infer_interval_breaks(self, centers):
if (
(bool(cupy) and isinstance(centers, cupy.ndarray))
or (bool(dask_array) and isinstance(centers, dask_array.Array))
):
breaks = infer_interval_breaks(centers, axis=1)
breaks = infer_interval_breaks(breaks, axis=0)
return breaks
if centers.dtype.kind in "iu":
centers = centers.astype(float)
return infer_interval_breaks_2d(centers)
@memoize
def _build_extend(self, x_mapper, y_mapper, info, append, _antialias_stage_2,
_antialias_stage_2_funcs):
x_name = self.x
y_name = self.y
name = self.name
@ngjit
@self.expand_aggs_and_cols(append)
def perform_extend(
i, j,
plot_height, plot_width, xs, ys, xverts, yverts,
yincreasing, eligible, intersect, *aggs_and_cols
):
# make array of quad x any vertices
xverts[0] = xs[j, i]
xverts[1] = xs[j, i + 1]
xverts[2] = xs[j + 1, i + 1]
xverts[3] = xs[j + 1, i]
xverts[4] = xverts[0]
yverts[0] = ys[j, i]
yverts[1] = ys[j, i + 1]
yverts[2] = ys[j + 1, i + 1]
yverts[3] = ys[j + 1, i]
yverts[4] = yverts[0]
# Compute the rectilinear bounding box around the quad and
# skip quad if there is no chance for it to intersect
# viewport
xmin = min(min(xverts[0], xverts[1]), min(xverts[2], xverts[3]))
if xmin >= plot_width:
return
xmin = max(xmin, 0)
xmax = max(max(xverts[0], xverts[1]), max(xverts[2], xverts[3]))
if xmax < 0:
return
xmax = min(xmax, plot_width)
ymin = min(min(yverts[0], yverts[1]), min(yverts[2], yverts[3]))
if ymin >= plot_height:
return
ymin = max(ymin, 0)
ymax = max(max(yverts[0], yverts[1]), max(yverts[2], yverts[3]))
if ymax < 0:
return
ymax = min(ymax, plot_height)
# Handle subpixel quads
if xmin == xmax or ymin == ymax:
# If either dimension is a single pixel, then render it
if xmin == xmax and xmax < plot_width:
xmax += 1
if ymin == ymax and ymax < plot_height:
ymax += 1
for yi in range(ymin, ymax):
for xi in range(xmin, xmax):
append(j, i, xi, yi, *aggs_and_cols)
return
# make yincreasing an array holding whether each edge is
# increasing vertically (+1), decreasing vertically (-1),
# or horizontal (0).
yincreasing[:] = 0
for k in range(4):
if yverts[k + 1] > yverts[k]:
yincreasing[k] = 1
elif yverts[k + 1] < yverts[k]:
yincreasing[k] = -1
for yi in range(ymin, ymax):
eligible[:] = 1
for xi in range(xmin, xmax):
intersect[:] = 0
# Test edges
for edge_i in range(4):
# Skip if we already know edge is ineligible
if not eligible[edge_i]:
continue
# Check if edge is fully to left of point. If
# so, we don't need to consider it again for
# this row.
if ((xverts[edge_i] < xi) and
(xverts[edge_i + 1] < xi)):
eligible[edge_i] = 0
continue
# Check if edge is fully above or below point.
# If so, we don't need to consider it again
# for this row.
if ((yverts[edge_i] > yi) ==
(yverts[edge_i + 1] > yi)):
eligible[edge_i] = 0
continue
# Now check if edge is to the right of point.
# A is vector from point to first vertex
ax = xverts[edge_i] - xi
ay = yverts[edge_i] - yi
# B is vector from point to second vertex
bx = xverts[edge_i + 1] - xi
by = yverts[edge_i + 1] - yi
# Compute cross product of B and A
bxa = (bx * ay - by * ax)
# If cross product has same sign as yincreasing
# then edge intersects to the right
intersect[edge_i] = (
bxa * yincreasing[edge_i] < 0
)
intersections = (
intersect[0] + intersect[1] + intersect[2] + intersect[3]
)
if intersections % 2 == 1:
# If odd number of intersections, point
# is inside quad
append(j, i, xi, yi, *aggs_and_cols)
@cuda.jit
@self.expand_aggs_and_cols(append)
def extend_cuda(plot_height, plot_width, xs, ys, *aggs_and_cols):
# # For consistency with CPU path, we initialize all arrays here
# # xverts/yverts arrays
xverts = cuda.local.array(5, dtype=numba.types.int32)
yverts = cuda.local.array(5, dtype=numba.types.int32)
#
# # Array holding whether each edge is increasing
# # vertically (+1), decreasing vertically (-1),
# # or horizontal (0).
yincreasing = cuda.local.array(4, dtype=numba.types.int8)
# # Array that will hold mask of whether edges are
# # eligible for intersection tests
eligible = cuda.local.array(4, dtype=numba.types.int8)
# # Array that will hold a mask of whether edges
# # intersect the ray to the right of test point
intersect = cuda.local.array(4, dtype=numba.types.int8)
i, j = cuda.grid(2)
if i < (xs.shape[0] - 1) and j < (ys.shape[0] - 1):
perform_extend(
i, j, plot_height, plot_width, xs, ys,
xverts, yverts, yincreasing, eligible, intersect,
*aggs_and_cols
)
@ngjit
@self.expand_aggs_and_cols(append)
def extend_cpu(plot_height, plot_width, xs, ys, *aggs_and_cols):
# For performance, we initialize all arrays once before the loop
# xverts/yverts arrays
xverts = np.zeros(5, dtype=np.int32)
yverts = np.zeros(5, dtype=np.int32)
# Array holding whether each edge is increasing
# vertically (+1), decreasing vertically (-1),
# or horizontal (0).
yincreasing = np.zeros(4, dtype=np.int8)
# Array that will hold mask of whether edges are
# eligible for intersection tests
eligible = np.ones(4, dtype=np.int8)
# Array that will hold a mask of whether edges
# intersect the ray to the right of test point
intersect = np.zeros(4, dtype=np.int8)
y_len, x_len, = xs.shape
for j in range(y_len - 1):
for i in range(x_len - 1):
perform_extend(
i, j, plot_height, plot_width, xs, ys,
xverts, yverts, yincreasing, eligible, intersect, *aggs_and_cols
)
extend_cpu_3d = _make_3d_from_2d(extend_cpu, 4)
extend_cuda_3d = _make_3d_from_2d_cuda(extend_cuda, 4)
def extend(aggs, xr_ds, vt, bounds, x_breaks=None, y_breaks=None):
from datashader.core import LinearAxis
use_cuda = cupy and isinstance(xr_ds[name].data, cupy.ndarray)
# Build axis transform (mapper) functions
if use_cuda:
x_mapper2 = _cuda_mapper(x_mapper)
y_mapper2 = _cuda_mapper(y_mapper)
else:
x_mapper2 = x_mapper
y_mapper2 = y_mapper
# Convert from bin centers to interval edges
if x_breaks is None:
if use_cuda:
x_centers = cupy.array(xr_ds[x_name].data)
else:
x_centers = xr_ds[x_name].values
x_breaks = self.infer_interval_breaks(x_centers)
if y_breaks is None:
if use_cuda:
y_centers = cupy.array(xr_ds[y_name].data)
else:
y_centers = xr_ds[y_name].values
y_breaks = self.infer_interval_breaks(y_centers)
# Scale x and y vertices into integer canvas coordinates
x0, x1, y0, y1 = bounds
xspan = x1 - x0
yspan = y1 - y0
if x_mapper is LinearAxis.mapper:
xscaled = x_breaks
else:
xscaled = x_mapper2(x_breaks)
xscaled -= x0
if y_mapper is LinearAxis.mapper:
yscaled = y_breaks
else:
yscaled = y_mapper2(y_breaks)
yscaled -= y0
# Get shape info for 3D or 2D case
is_3d, nz, plot_height, plot_width = self._get_shape_info(aggs)
# dtype here matches that in perform_extend
xp = cupy if use_cuda else np
xs = xp.empty(xscaled.shape, dtype=xp.int32)
ys = xp.empty(yscaled.shape, dtype=xp.int32)
xp.multiply(xscaled, plot_width/xspan, casting="unsafe", out=xs)
xp.multiply(yscaled, plot_height/yspan, casting="unsafe", out=ys)
coord_dims = xr_ds.coords[x_name].dims
if is_3d:
aggs_and_cols = aggs + info(xr_ds.transpose(..., *coord_dims), aggs[0].shape)
if use_cuda:
do_extend = extend_cuda_3d(grid_shape=(xs.shape[1] - 1, xs.shape[0] - 1))
else:
do_extend = extend_cpu_3d(n_arrays=len(aggs_and_cols))
do_extend(plot_height, plot_width, xs, ys, nz, *aggs_and_cols)
else:
aggs_and_cols = aggs + info(xr_ds.transpose(*coord_dims), aggs[0].shape[:2])
if use_cuda:
do_extend = extend_cuda[cuda_args(xr_ds[name].shape)]
else:
do_extend = extend_cpu
do_extend(
plot_height, plot_width, xs, ys, *aggs_and_cols
)
return extend