Repository navigation
Expand file tree
/
Copy pathline.py
More file actions
2075 lines (1712 loc) · 76.2 KB
/
Copy pathline.py
File metadata and controls
2075 lines (1712 loc) · 76.2 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
from __future__ import annotations
import math
import numpy as np
from toolz import memoize
from datashader.antialias import two_stage_agg
from datashader.glyphs.points import _PointLike, _GeometryLike
from datashader.utils import isnull, isreal, ngjit
from numba import cuda
import numba.types as nb_types
try:
import cudf
import cupy as cp
from ..transfer_functions._cuda_utils import cuda_args
except ImportError:
cudf = None
cp = None
cuda_args = None
try:
import spatialpandas
except Exception:
spatialpandas = None
class _AntiAliasedLine:
""" Methods common to all lines. """
_line_width = 0 # Use antialiasing if > 0.
def set_line_width(self, line_width):
self._line_width = line_width
if hasattr(self, "antialiased"):
self.antialiased = (line_width > 0)
def _build_extend(self, x_mapper, y_mapper, info, append, antialias_stage_2,
antialias_stage_2_funcs):
return self._internal_build_extend(
x_mapper, y_mapper, info, append, self._line_width, antialias_stage_2,
antialias_stage_2_funcs)
def _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
):
antialias = line_width > 0
map_onto_pixel = _build_map_onto_pixel_for_line(x_mapper, y_mapper, antialias)
overwrite, use_2_stage_agg = two_stage_agg(antialias_stage_2)
if not use_2_stage_agg:
antialias_stage_2_funcs = None
draw_segment = _build_draw_segment(
append, map_onto_pixel, expand_aggs_and_cols, line_width, overwrite,
)
return draw_segment, antialias_stage_2_funcs
class LineAxis0(_PointLike, _AntiAliasedLine):
"""A line, with vertices defined by ``x`` and ``y``.
Parameters
----------
x, y : str
Column names for the x and y coordinates of each vertex.
"""
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
extend_cpu, extend_cuda = _build_extend_line_axis0(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
x_name = self.x
y_name = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
if cudf and isinstance(df, cudf.DataFrame):
xs = self.to_cupy_array(df, x_name)
ys = self.to_cupy_array(df, y_name)
do_extend = extend_cuda[cuda_args(xs.shape)]
else:
xs = df.loc[:, x_name].to_numpy()
ys = df.loc[:, y_name].to_numpy()
do_extend = extend_cpu
# line may be clipped, then mapped to pixels
do_extend(
sx, tx, sy, ty, xmin, xmax, ymin, ymax,
xs, ys, plot_start, antialias_stage_2, *aggs_and_cols
)
return extend
class LineAxis0Multi(_PointLike, _AntiAliasedLine):
"""
"""
def validate(self, in_dshape):
if not all([isreal(in_dshape.measure[str(xcol)]) for xcol in self.x]):
raise ValueError('x columns must be real')
elif not all([isreal(in_dshape.measure[str(ycol)]) for ycol in self.y]):
raise ValueError('y columns must be real')
if len(self.x) != len(self.y):
raise ValueError(
f'x and y coordinate lengths do not match: {len(self.x)} != {len(self.y)}')
@property
def x_label(self):
return 'x'
@property
def y_label(self):
return 'y'
def required_columns(self):
return self.x + self.y
def compute_x_bounds(self, df):
bounds_list = [self._compute_bounds(df[x])
for x in self.x]
mins, maxes = zip(*bounds_list)
return self.maybe_expand_bounds((min(mins), max(maxes)))
def compute_y_bounds(self, df):
bounds_list = [self._compute_bounds(df[y])
for y in self.y]
mins, maxes = zip(*bounds_list)
return self.maybe_expand_bounds((min(mins), max(maxes)))
@memoize
def compute_bounds_dask(self, ddf):
r = ddf.map_partitions(lambda df: np.array([[
np.nanmin([np.nanmin(df[c].values).item() for c in self.x]),
np.nanmax([np.nanmax(df[c].values).item() for c in self.x]),
np.nanmin([np.nanmin(df[c].values).item() for c in self.y]),
np.nanmax([np.nanmax(df[c].values).item() for c in self.y])]]
)).compute()
x_extents = np.nanmin(r[:, 0]), np.nanmax(r[:, 1])
y_extents = np.nanmin(r[:, 2]), np.nanmax(r[:, 3])
return (self.maybe_expand_bounds(x_extents),
self.maybe_expand_bounds(y_extents))
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
extend_cpu, extend_cuda = _build_extend_line_axis0_multi(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
x_names = self.x
y_names = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
if cudf and isinstance(df, cudf.DataFrame):
xs = self.to_cupy_array(df, x_names)
ys = self.to_cupy_array(df, y_names)
do_extend = extend_cuda[cuda_args(xs.shape)]
else:
xs = df.loc[:, list(x_names)].to_numpy()
ys = df.loc[:, list(y_names)].to_numpy()
do_extend = extend_cpu
# line may be clipped, then mapped to pixels
do_extend(
sx, tx, sy, ty, xmin, xmax, ymin, ymax,
xs, ys, plot_start, antialias_stage_2, *aggs_and_cols,
)
return extend
class LinesAxis1(_PointLike, _AntiAliasedLine):
"""A collection of lines (on line per row) with vertices defined
by the lists of columns in ``x`` and ``y``
Parameters
----------
x, y : list
Lists of column names for the x and y coordinates
"""
def validate(self, in_dshape):
if not all([isreal(in_dshape.measure[str(xcol)])
for xcol in self.x]):
raise ValueError('x columns must be real')
elif not all([isreal(in_dshape.measure[str(ycol)])
for ycol in self.y]):
raise ValueError('y columns must be real')
unique_x_measures = set(in_dshape.measure[str(xcol)]
for xcol in self.x)
if len(unique_x_measures) > 1:
raise ValueError('x columns must have the same data type')
unique_y_measures = set(in_dshape.measure[str(ycol)]
for ycol in self.y)
if len(unique_y_measures) > 1:
raise ValueError('y columns must have the same data type')
if len(self.x) != len(self.y):
raise ValueError(
f'x and y coordinate lengths do not match: {len(self.x)} != {len(self.y)}')
def required_columns(self):
return self.x + self.y
@property
def x_label(self):
return 'x'
@property
def y_label(self):
return 'y'
def compute_x_bounds(self, df):
xs = tuple(df[xlabel] for xlabel in self.x)
bounds_list = [self._compute_bounds(xcol) for xcol in xs]
mins, maxes = zip(*bounds_list)
return self.maybe_expand_bounds((min(mins), max(maxes)))
def compute_y_bounds(self, df):
ys = tuple(df[ylabel] for ylabel in self.y)
bounds_list = [self._compute_bounds(ycol) for ycol in ys]
mins, maxes = zip(*bounds_list)
return self.maybe_expand_bounds((min(mins), max(maxes)))
@memoize
def compute_bounds_dask(self, ddf):
r = ddf.map_partitions(lambda df: np.array([[
np.nanmin([np.nanmin(df[c].values).item() for c in self.x]),
np.nanmax([np.nanmax(df[c].values).item() for c in self.x]),
np.nanmin([np.nanmin(df[c].values).item() for c in self.y]),
np.nanmax([np.nanmax(df[c].values).item() for c in self.y])]]
)).compute()
x_extents = np.nanmin(r[:, 0]), np.nanmax(r[:, 1])
y_extents = np.nanmin(r[:, 2]), np.nanmax(r[:, 3])
return (self.maybe_expand_bounds(x_extents),
self.maybe_expand_bounds(y_extents))
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
extend_cpu, extend_cuda = _build_extend_line_axis1_none_constant(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
x_names = self.x
y_names = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
if cudf and isinstance(df, cudf.DataFrame):
xs = self.to_cupy_array(df, x_names)
ys = self.to_cupy_array(df, y_names)
do_extend = extend_cuda[cuda_args(xs.shape)]
else:
xs = df.loc[:, list(x_names)].to_numpy()
ys = df.loc[:, list(y_names)].to_numpy()
do_extend = extend_cpu
do_extend(
sx, tx, sy, ty, xmin, xmax, ymin, ymax, xs, ys, antialias_stage_2, *aggs_and_cols
)
return extend
class LinesAxis1XConstant(LinesAxis1):
"""
"""
def validate(self, in_dshape):
if not all([isreal(in_dshape.measure[str(ycol)]) for ycol in self.y]):
raise ValueError('y columns must be real')
unique_y_measures = set(in_dshape.measure[str(ycol)]
for ycol in self.y)
if len(unique_y_measures) > 1:
raise ValueError('y columns must have the same data type')
if len(self.x) != len(self.y):
raise ValueError(
f'x and y coordinate lengths do not match: {len(self.x)} != {len(self.y)}')
def required_columns(self):
return self.y
def compute_x_bounds(self, *args):
x_min = np.nanmin(self.x)
x_max = np.nanmax(self.x)
return self.maybe_expand_bounds((x_min, x_max))
@memoize
def compute_bounds_dask(self, ddf):
r = ddf.map_partitions(lambda df: np.array([[
np.nanmin([np.nanmin(df[c].values).item() for c in self.y]),
np.nanmax([np.nanmax(df[c].values).item() for c in self.y])]]
)).compute()
y_extents = np.nanmin(r[:, 0]), np.nanmax(r[:, 1])
return (self.compute_x_bounds(),
self.maybe_expand_bounds(y_extents))
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
extend_cpu, extend_cuda = _build_extend_line_axis1_x_constant(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
x_values = self.x
y_names = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
if cudf and isinstance(df, cudf.DataFrame):
xs = cp.asarray(x_values)
ys = self.to_cupy_array(df, y_names)
do_extend = extend_cuda[cuda_args(ys.shape)]
else:
xs = x_values
ys = df.loc[:, list(y_names)].to_numpy()
do_extend = extend_cpu
do_extend(
sx, tx, sy, ty, xmin, xmax, ymin, ymax, xs, ys, antialias_stage_2, *aggs_and_cols
)
return extend
class LinesAxis1YConstant(LinesAxis1):
"""
"""
def validate(self, in_dshape):
if not all([isreal(in_dshape.measure[str(xcol)]) for xcol in self.x]):
raise ValueError('x columns must be real')
unique_x_measures = set(in_dshape.measure[str(xcol)]
for xcol in self.x)
if len(unique_x_measures) > 1:
raise ValueError('x columns must have the same data type')
if len(self.x) != len(self.y):
raise ValueError(
f'x and y coordinate lengths do not match: {len(self.x)} != {len(self.y)}')
def required_columns(self):
return self.x
def compute_y_bounds(self, *args):
y_min = np.nanmin(self.y)
y_max = np.nanmax(self.y)
return self.maybe_expand_bounds((y_min, y_max))
@memoize
def compute_bounds_dask(self, ddf):
r = ddf.map_partitions(lambda df: np.array([[
np.nanmin([np.nanmin(df[c].values).item() for c in self.x]),
np.nanmax([np.nanmax(df[c].values).item() for c in self.x])]]
)).compute()
x_extents = np.nanmin(r[:, 0]), np.nanmax(r[:, 1])
return (self.maybe_expand_bounds(x_extents),
self.compute_y_bounds())
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
extend_cpu, extend_cuda = _build_extend_line_axis1_y_constant(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
x_names = self.x
y_values = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
if cudf and isinstance(df, cudf.DataFrame):
xs = self.to_cupy_array(df, x_names)
ys = cp.asarray(y_values)
do_extend = extend_cuda[cuda_args(xs.shape)]
else:
xs = df.loc[:, list(x_names)].to_numpy()
ys = y_values
do_extend = extend_cpu
do_extend(
sx, tx, sy, ty, xmin, xmax, ymin, ymax, xs, ys, antialias_stage_2, *aggs_and_cols
)
return extend
class LinesAxis1Ragged(_PointLike, _AntiAliasedLine):
def validate(self, in_dshape):
try:
from datashader.datatypes import RaggedDtype
except ImportError:
RaggedDtype = type(None)
if not isinstance(in_dshape[str(self.x)], RaggedDtype):
raise ValueError('x must be a RaggedArray')
elif not isinstance(in_dshape[str(self.y)], RaggedDtype):
raise ValueError('y must be a RaggedArray')
def required_columns(self):
return (self.x,) + (self.y,)
def compute_x_bounds(self, df):
bounds = self._compute_bounds(df[self.x].array.flat_array)
return self.maybe_expand_bounds(bounds)
def compute_y_bounds(self, df):
bounds = self._compute_bounds(df[self.y].array.flat_array)
return self.maybe_expand_bounds(bounds)
@memoize
def compute_bounds_dask(self, ddf):
r = ddf.map_partitions(lambda df: np.array([[
np.nanmin(df[self.x].array.flat_array).item(),
np.nanmax(df[self.x].array.flat_array).item(),
np.nanmin(df[self.y].array.flat_array).item(),
np.nanmax(df[self.y].array.flat_array).item()]]
)).compute()
x_extents = np.nanmin(r[:, 0]), np.nanmax(r[:, 1])
y_extents = np.nanmin(r[:, 2]), np.nanmax(r[:, 3])
return (self.maybe_expand_bounds(x_extents),
self.maybe_expand_bounds(y_extents))
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
extend_cpu = _build_extend_line_axis1_ragged(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
x_name = self.x
y_name = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
xs = df[x_name].array
ys = df[y_name].array
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
# line may be clipped, then mapped to pixels
extend_cpu(
sx, tx, sy, ty, xmin, xmax, ymin, ymax, xs, ys, antialias_stage_2, *aggs_and_cols
)
return extend
class LineAxis1Geometry(_GeometryLike, _AntiAliasedLine):
# spatialpandas must be available if a LineAxis1Geometry object is created.
@property
def geom_dtypes(self):
from spatialpandas.geometry import (
LineDtype, MultiLineDtype, RingDtype, PolygonDtype,
MultiPolygonDtype
)
return (LineDtype, MultiLineDtype, RingDtype,
PolygonDtype, MultiPolygonDtype)
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs):
from spatialpandas.geometry import (
PolygonArray, MultiPolygonArray, RingArray
)
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
perform_extend_cpu = _build_extend_line_axis1_geometry(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
geometry_name = self.geometry
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
geom_array = df[geometry_name].array
# Use type to decide whether geometry represents a closed .
# We skip for closed geometries so as not to double count the first/last
# pixel
if isinstance(geom_array, (PolygonArray, MultiPolygonArray)):
# Convert polygon array to multi line of boundary
geom_array = geom_array.boundary
closed_rings = True
elif isinstance(geom_array, RingArray):
closed_rings = True
else:
closed_rings = False
perform_extend_cpu(
sx, tx, sy, ty, xmin, xmax, ymin, ymax,
geom_array, closed_rings, antialias_stage_2, *aggs_and_cols
)
return extend
class LineAxis1GeoPandas(_GeometryLike, _AntiAliasedLine):
# geopandas must be available for a GeoPandasLine to be created.
@property
def geom_dtypes(self):
from geopandas.array import GeometryDtype
return (GeometryDtype,)
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs,
):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
perform_extend_cpu = _build_extend_line_axis1_geopandas(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs,
)
geometry_name = self.geometry
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
geom_array = df[geometry_name].array
perform_extend_cpu(
sx, tx, sy, ty, xmin, xmax, ymin, ymax,
geom_array, antialias_stage_2, *aggs_and_cols,
)
return extend
class LinesXarrayCommonX(LinesAxis1):
def __init__(self, x, y, x_dim_index: int):
super().__init__(x, y)
self.x_dim_index = x_dim_index
def __hash__(self):
# This ensures that @memoize below caches different functions for different x_dim_index.
return hash((type(self), self.x_dim_index))
def compute_x_bounds(self, dataset):
bounds = self._compute_bounds(dataset[self.x])
return self.maybe_expand_bounds(bounds)
def compute_y_bounds(self, dataset):
bounds = self._compute_bounds(dataset[self.y])
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 validate(self, in_dshape):
if not isreal(in_dshape.measure[str(self.x)]):
raise ValueError('x column must be real')
if not isreal(in_dshape.measure[str(self.y)]):
raise ValueError('y column must be real')
@memoize
def _internal_build_extend(
self, x_mapper, y_mapper, info, append, line_width, antialias_stage_2,
antialias_stage_2_funcs,
):
expand_aggs_and_cols = self.expand_aggs_and_cols(append)
draw_segment, antialias_stage_2_funcs = _line_internal_build_extend(
x_mapper, y_mapper, append, line_width, antialias_stage_2, antialias_stage_2_funcs,
expand_aggs_and_cols,
)
swap_dims = self.x_dim_index == 0
extend_cpu, extend_cuda = _build_extend_line_axis1_x_constant(
draw_segment, expand_aggs_and_cols, antialias_stage_2_funcs, swap_dims,
)
x_name = self.x
y_name = self.y
def extend(aggs, df, vt, bounds, plot_start=True):
sx, tx, sy, ty = vt
xmin, xmax, ymin, ymax = bounds
aggs_and_cols = aggs + info(df, aggs[0].shape[:2])
if cudf and isinstance(df, cudf.DataFrame):
xs = cp.asarray(df[x_name])
ys = cp.asarray(df[y_name])
do_extend = extend_cuda[cuda_args(ys.shape)]
elif cp and isinstance(df[y_name].data, cp.ndarray):
xs = cp.asarray(df[x_name])
ys = df[y_name].data
shape = ys.shape[::-1] if swap_dims else ys.shape
do_extend = extend_cuda[cuda_args(shape)]
else:
xs = df[x_name].to_numpy()
ys = df[y_name].to_numpy()
do_extend = extend_cpu
do_extend(
sx, tx, sy, ty, xmin, xmax, ymin, ymax, xs, ys, antialias_stage_2, *aggs_and_cols
)
return extend
def _build_map_onto_pixel_for_line(x_mapper, y_mapper, want_antialias=False):
@ngjit
def map_onto_pixel_snap(sx, tx, sy, ty, xmin, xmax, ymin, ymax, x, y):
"""Map points onto pixel grid.
Points falling on upper bound are mapped into previous bin.
If the line has been clipped, x and y will have been
computed to lie on the bounds; we compare point and bounds
in integer space to avoid fp error. In contrast, with
auto-ranging, a point on the bounds will be the same
floating point number as the bound, so comparison in fp
representation of continuous space or in integer space
doesn't change anything.
"""
xx = int(x_mapper(x) * sx + tx)
yy = int(y_mapper(y) * sy + ty)
# Note that sx and tx were designed so that
# x_mapper(xmax) * sx + tx equals the width of the canvas in pixels
#
# Likewise, sy and ty were designed so that
# y_mapper(ymax) * sy + ty equals the height of the canvas in pixels
#
# We round these results to integers (rather than casting to integers
# with the int constructor) to handle cases where floating-point
# precision errors results in a value just under the integer number
# of pixels.
xxmax = round(x_mapper(xmax) * sx + tx)
yymax = round(y_mapper(ymax) * sy + ty)
return (xx - 1 if xx == xxmax else xx,
yy - 1 if yy == yymax else yy)
@ngjit
def map_onto_pixel_no_snap(sx, tx, sy, ty, xmin, xmax, ymin, ymax, x, y):
xx = x_mapper(x)*sx + tx - 0.5
yy = y_mapper(y)*sy + ty - 0.5
return xx, yy
if want_antialias:
return map_onto_pixel_no_snap
else:
return map_onto_pixel_snap
@ngjit
def _liang_barsky(xmin, xmax, ymin, ymax, x0, x1, y0, y1, skip):
""" An implementation of the Liang-Barsky line clipping algorithm.
https://en.wikipedia.org/wiki/Liang%E2%80%93Barsky_algorithm
"""
# Check if line is fully outside viewport
if x0 < xmin and x1 < xmin:
skip = True
elif x0 > xmax and x1 > xmax:
skip = True
elif y0 < ymin and y1 < ymin:
skip = True
elif y0 > ymax and y1 > ymax:
skip = True
t0, t1 = 0, 1
dx1 = x1 - x0
t0, t1, accept = _clipt(-dx1, x0 - xmin, t0, t1)
if not accept:
skip = True
t0, t1, accept = _clipt(dx1, xmax - x0, t0, t1)
if not accept:
skip = True
dy1 = y1 - y0
t0, t1, accept = _clipt(-dy1, y0 - ymin, t0, t1)
if not accept:
skip = True
t0, t1, accept = _clipt(dy1, ymax - y0, t0, t1)
if not accept:
skip = True
if t1 < 1:
clipped_end = True
x1 = x0 + t1 * dx1
y1 = y0 + t1 * dy1
else:
clipped_end = False
if t0 > 0:
# If x0 is clipped, we need to plot the new start
clipped_start = True
x0 = x0 + t0 * dx1
y0 = y0 + t0 * dy1
else:
clipped_start = False
return x0, x1, y0, y1, skip, clipped_start, clipped_end
@ngjit
def _clipt(p, q, t0, t1):
accept = True
if p < 0 and q < 0:
r = q / p
if r > t1:
accept = False
elif r > t0:
t0 = r
elif p > 0 and q < p:
r = q / p
if r < t0:
accept = False
elif r < t1:
t1 = r
elif q < 0:
accept = False
return t0, t1, accept
@ngjit
def _clamp(x, low, high):
# Clamp ``x`` in the range ``low`` to ``high``.
return max(low, min(x, high))
@ngjit
def _linearstep(edge0, edge1, x):
t = _clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0)
return t
@ngjit
def _x_intercept(y, cx0, cy0, cx1, cy1):
# Return x value of intercept between line at constant y and line
# between corner points.
if cy0 == cy1:
# Line is horizontal, return the "upper", i.e. right-hand, end of it.
return cx1
frac = (y - cy0) / (cy1 - cy0) # In range 0..1
return cx0 + frac*(cx1 - cx0)
def _build_full_antialias(expand_aggs_and_cols):
"""Specialize antialiased line drawing algorithm for a given append/axis combination"""
@ngjit
@expand_aggs_and_cols
def _full_antialias(line_width, overwrite, i, x0, x1, y0, y1,
segment_start, segment_end, xm, ym, append,
nx, ny, buffer, *aggs_and_cols):
"""Draw an antialiased line segment.
If overwrite=True can overwrite each pixel multiple times because
using max for the overwriting. If False can only write each pixel
once per segment and its previous segment.
Argument xm, ym are only valid if overwrite and segment_start are False.
"""
if x0 == x1 and y0 == y1:
return
# Scan occurs in y-direction. But wish to scan in the shortest direction,
# so if |x0-x1| < |y0-y1| then flip (x,y) coords for maths and flip back
# again before setting pixels.
flip_xy = abs(x0-x1) < abs(y0-y1)
if flip_xy:
x0, y0 = y0, x0
x1, y1 = y1, x1
xm, ym = ym, xm
scale = 1.0
# line_width less than 1 is rendered as 1 but with lower intensity.
if line_width < 1.0:
scale *= line_width
line_width = 1.0
aa = 1.0
halfwidth = 0.5*(line_width + aa)
# Want y0 <= y1, so switch vertical direction if this is not so.
flip_order = y1 < y0 or (y1 == y0 and x1 < x0)
# Start (x0, y0), end (y0, y1)
# c1 +-------------+ c2 along | right
# (x0, y0) | o o | (x1, y1) vector | vector
# c0 +-------------+ c3 ----> v
alongx = float(x1 - x0)
alongy = float(y1 - y0) # Always +ve
length = math.sqrt(alongx**2 + alongy**2)
alongx /= length
alongy /= length
rightx = alongy
righty = -alongx
# 4 corners, x and y. Uses buffer, which must have length 8. Order of coords is
# (x0, x1, x2, x3, y0, y1, y2, y3). Each CPU/GPU thread has its own local buffer
# so there is no cross-talk. Contents of buffer are written and read within the
# lifetime of this function, so it doesn't matter what they are before this
# function is called or after it returns.
if flip_order:
buffer[0] = x1 - halfwidth*( rightx - alongx)
buffer[1] = x1 - halfwidth*(-rightx - alongx)
buffer[2] = x0 - halfwidth*(-rightx + alongx)
buffer[3] = x0 - halfwidth*( rightx + alongx)
buffer[4] = y1 - halfwidth*( righty - alongy)
buffer[5] = y1 - halfwidth*(-righty - alongy)
buffer[6] = y0 - halfwidth*(-righty + alongy)
buffer[7] = y0 - halfwidth*( righty + alongy)
else:
buffer[0] = x0 + halfwidth*( rightx - alongx)
buffer[1] = x0 + halfwidth*(-rightx - alongx)
buffer[2] = x1 + halfwidth*(-rightx + alongx)
buffer[3] = x1 + halfwidth*( rightx + alongx)
buffer[4] = y0 + halfwidth*( righty - alongy)
buffer[5] = y0 + halfwidth*(-righty - alongy)
buffer[6] = y1 + halfwidth*(-righty + alongy)
buffer[7] = y1 + halfwidth*( righty + alongy)
xmax = nx-1
ymax = ny-1
if flip_xy:
xmax, ymax = ymax, xmax
# Index of lowest-y point.
if flip_order:
lowindex = 0 if x0 > x1 else 1
else:
lowindex = 0 if x1 > x0 else 1
if not overwrite and not segment_start:
prev_alongx = x0 - xm
prev_alongy = y0 - ym
prev_length = math.sqrt(prev_alongx**2 + prev_alongy**2)
if prev_length > 0.0:
prev_alongx /= prev_length
prev_alongy /= prev_length
prev_rightx = prev_alongy
prev_righty = -prev_alongx
else:
overwrite = True
# y limits of scan.
ystart = _clamp(math.ceil(buffer[4 + lowindex]), 0, ymax)
yend = _clamp(math.floor(buffer[4 + (lowindex+2) % 4]), 0, ymax)
# Need to know which edges are to left and right; both will change.
ll = lowindex # Index of lower point of left edge.
lu = (ll + 1) % 4 # Index of upper point of left edge.
rl = lowindex # Index of lower point of right edge.
ru = (rl + 3) % 4 # Index of upper point of right edge.
for y in range(ystart, yend+1):
if ll == lowindex and y > buffer[4 + lu]:
ll = lu
lu = (ll + 1) % 4
if rl == lowindex and y > buffer[4 + ru]:
rl = ru
ru = (rl + 3) % 4
# Find x limits of scan at this y.
xleft = _clamp(math.ceil(_x_intercept(
y, buffer[ll], buffer[4+ll], buffer[lu], buffer[4+lu])), 0, xmax)
xright = _clamp(math.floor(_x_intercept(
y, buffer[rl], buffer[4+rl], buffer[ru], buffer[4+ru])), 0, xmax)
for x in range(xleft, xright+1):
along = (x-x0)*alongx + (y-y0)*alongy # dot product
prev_correction = False
if along < 0.0:
# Before start of segment
if overwrite or segment_start or (x-x0)*prev_alongx + (y-y0)*prev_alongy > 0.0:
distance = math.sqrt((x-x0)**2 + (y-y0)**2) # round join/end cap
else:
continue
elif along > length:
# After end of segment
if overwrite or segment_end:
distance = math.sqrt((x-x1)**2 + (y-y1)**2) # round join/end cap
else:
continue
else:
# Within segment
distance = abs((x-x0)*rightx + (y-y0)*righty)
if not overwrite and not segment_start and \
-prev_length <= (x-x0)*prev_alongx + (y-y0)*prev_alongy <= 0.0 and \
abs((x-x0)*prev_rightx + (y-y0)*prev_righty) <= halfwidth:
prev_correction = True
value = 1.0 - _linearstep(0.5*(line_width - aa), halfwidth, distance)
value *= scale
prev_value = 0.0
if prev_correction:
# Already set pixel from previous segment, need to correct it
prev_distance = abs((x-x0)*prev_rightx + (y-y0)*prev_righty)
prev_value = 1.0 - _linearstep(0.5*(line_width - aa), halfwidth, prev_distance)
prev_value *= scale
if value <= prev_value:
# Have already used a larger value (alpha) for this pixel.
value = 0.0
if value > 0.0:
xx, yy = (y, x) if flip_xy else (x, y)
append(i, xx, yy, value, prev_value, *aggs_and_cols)
return _full_antialias
def _build_bresenham(expand_aggs_and_cols):
"""Specialize a bresenham kernel for a given append/axis combination"""
@ngjit
@expand_aggs_and_cols
def _bresenham(i, sx, tx, sy, ty, xmin, xmax, ymin, ymax, segment_start,
x0, x1, y0, y1, clipped, append, *aggs_and_cols):
"""Draw a line segment using Bresenham's algorithm
This method plots a line segment with integer coordinates onto a pixel
grid.
"""
dx = x1 - x0
ix = (dx > 0) - (dx < 0)
dx = abs(dx) * 2
dy = y1 - y0