-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy path_layer.py
2109 lines (1666 loc) · 68.7 KB
/
_layer.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
"""Notes:
- When we pass a value of `None` as a default value to a trait, that value will be
serialized to JS as `null` and will not be passed into the GeoArrow model (see the
lengthy assignments of type `..(isDefined(this.param) && { param: this.param })`).
Then the default value in the JS GeoArrow layer (defined in
`@geoarrow/deck.gl-layers`) will be used.
"""
from __future__ import annotations
import sys
import warnings
from textwrap import dedent
from typing import (
TYPE_CHECKING,
List,
Optional,
Sequence,
Tuple,
Union,
)
import ipywidgets
import traitlets
import traitlets as t
from arro3.core import Table
from arro3.core.types import ArrowStreamExportable
from lonboard._base import BaseExtension, BaseWidget
from lonboard._constants import EXTENSION_NAME, OGC_84
from lonboard._geoarrow._duckdb import from_duckdb as _from_duckdb
from lonboard._geoarrow.geopandas_interop import geopandas_to_geoarrow
from lonboard._geoarrow.ops import reproject_table
from lonboard._geoarrow.ops.bbox import Bbox, total_bounds
from lonboard._geoarrow.ops.centroid import WeightedCentroid, weighted_centroid
from lonboard._geoarrow.ops.coord_layout import make_geometry_interleaved
from lonboard._geoarrow.parse_wkb import parse_serialized_table
from lonboard._serialization import infer_rows_per_chunk
from lonboard._utils import auto_downcast as _auto_downcast
from lonboard._utils import get_geometry_column_index, remove_extension_kwargs
from lonboard.traits import (
ArrowTableTrait,
ColorAccessor,
FloatAccessor,
NormalAccessor,
VariableLengthTuple,
)
if TYPE_CHECKING:
import geopandas as gpd
from lonboard.types.layer import (
BaseLayerKwargs,
BitmapLayerKwargs,
BitmapTileLayerKwargs,
ColumnLayerKwargs,
HeatmapLayerKwargs,
PathLayerKwargs,
PointCloudLayerKwargs,
PolygonLayerKwargs,
ScatterplotLayerKwargs,
SolidPolygonLayerKwargs,
)
if TYPE_CHECKING:
import duckdb
import pyproj
if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
if sys.version_info >= (3, 12):
from typing import Unpack
else:
from typing_extensions import Unpack
class BaseLayer(BaseWidget):
# Note: these class attributes are **not** serialized to JS
_bbox = Bbox()
_weighted_centroid = WeightedCentroid()
# The following traitlets **are** serialized to JS
def __init__(self, *, extensions: Sequence[BaseExtension] = (), **kwargs):
# We allow layer extensions to dynamically inject properties onto the layer
# widgets where the layer is defined. We wish to allow extensions and their
# properties to be passed in the layer constructor. _However_, if
extension_kwargs = remove_extension_kwargs(extensions, kwargs)
super().__init__(extensions=extensions, **kwargs)
# Dynamically set layer traits from extensions after calling __init__
self._add_extension_traits(extensions)
# Assign any extension properties that we took out before calling __init__
added_names: List[str] = []
for prop_name, prop_value in extension_kwargs.items():
self.set_trait(prop_name, prop_value)
added_names.append(prop_name)
self.send_state(added_names)
# TODO: validate that only one extension per type is included. E.g. you can't have
# two data filter extensions.
extensions = VariableLengthTuple(t.Instance(BaseExtension)).tag(
sync=True, **ipywidgets.widget_serialization
)
"""
A list of [layer extension](https://developmentseed.org/lonboard/latest/api/layer-extensions/)
objects to add additional features to a layer.
"""
def _add_extension_traits(self, extensions: Sequence[BaseExtension]):
"""Assign selected traits from the extension onto this Layer."""
for extension in extensions:
# NOTE: here it's important that we call `traitlets.HasTraits.add_traits`
# and not `self.add_traits`. This is because `add_traits` is originally
# defined on `HasTraits` but `ipywidgets.Widget` overrides that method to
# additionally call `send_state` for any trait that has `"sync"` tagged in
# its metadata. But this is incompatible with traits that don't have default
# values.
#
# For example, with the DataFilterExtension, we want to dynamically add the
# `get_filter_value` trait, but require that the user pass in a value. With
# the `Widget` implementation, `send_state` will fail, even if the user
# passes in a value, because `send_state` is called before we call
# `super().__init__()`
traitlets.HasTraits.add_traits(self, **extension._layer_traits)
# Note: This is part of `Widget.add_traits` (in the direct superclass) that
# we skip by calling `traitlets.HasTraits.add_traits`
for name, trait in extension._layer_traits.items():
if trait.get_metadata("sync"):
self.keys.append(name)
# This doesn't currently work due to I think some race conditions around syncing
# traits vs the other parameters.
# def add_extension(self, extension: BaseExtension, **props):
# """Add a new layer extension to an existing layer instance.
# Any properties for the added extension should also be passed as keyword
# arguments to this function.
# Examples:
# ```py
# from lonboard import ScatterplotLayer
# from lonboard.layer_extension import DataFilterExtension
# gdf = geopandas.GeoDataFrame(...)
# layer = ScatterplotLayer.from_geopandas(gdf)
# extension = DataFilterExtension(filter_size=1)
# filter_values = gdf["filter_column"]
# layer.add_extension(
# extension,
# get_filter_value=filter_values,
# filter_range=[0, 1]
# )
# ```
# Args:
# extension: The new extension to add.
# Raises:
# ValueError: if another extension of the same type already exists on the
# layer.
# """
# if any(isinstance(extension, type(ext)) for ext in self.extensions):
# raise ValueError("Only one extension of each type permitted")
# with self.hold_trait_notifications():
# self._add_extension_traits([extension])
# self.extensions += (extension,)
# # Assign any extension properties
# added_names: List[str] = []
# for prop_name, prop_value in props.items():
# self.set_trait(prop_name, prop_value)
# added_names.append(prop_name)
# self.send_state(added_names + ["extensions"])
pickable = t.Bool(True).tag(sync=True)
"""
Whether the layer responds to mouse pointer picking events.
This must be set to `True` for tooltips and other interactive elements to be
available. This can also be used to only allow picking on specific layers within a
map instance.
Note that picking has some performance overhead in rendering. To get the absolute
best rendering performance with large data (at the cost of removing interactivity),
set this to `False`.
- Type: `bool`
- Default: `True`
"""
visible = t.Bool(True).tag(sync=True)
"""
Whether the layer is visible.
Under most circumstances, using the `visible` attribute to control the visibility of
layers is recommended over removing/adding the layer from the `Map.layers` list.
In particular, toggling the `visible` attribute will persist the layer on the
JavaScript side, while removing/adding the layer from the `Map.layers` list will
re-download and re-render from scratch.
- Type: `bool`
- Default: `True`
"""
opacity = t.Float(1, min=0, max=1).tag(sync=True)
"""
The opacity of the layer.
- Type: `float`. Must range between 0 and 1.
- Default: `1`
"""
auto_highlight = t.Bool(False).tag(sync=True)
"""
When true, the current object pointed to by the mouse pointer (when hovered over) is
highlighted with `highlightColor`.
Requires `pickable` to be `True`.
- Type: `bool`
- Default: `False`
"""
highlight_color = VariableLengthTuple(
t.Int(), default_value=None, minlen=3, maxlen=4
)
"""
RGBA color to blend with the highlighted object (the hovered over object if
`auto_highlight=true`). When the value is a 3 component (RGB) array, a default alpha
of 255 is applied.
- Type: List or Tuple of integers
- Default: `[0, 0, 128, 128]`
"""
selected_index = t.Int(None, allow_none=True).tag(sync=True)
"""
The positional index of the most-recently clicked on row of data.
You can use this to access the full row of data from a GeoDataFrame
```py
gdf.iloc[layer.selected_index]
```
Setting a value here from Python will do nothing. This attribute only exists to be
updated from JavaScript on a map click. Note that `pickable` must be `True` (the
default) on this layer for the JavaScript `onClick` handler to work; if `pickable`
is set to `False`, `selected_index` will never update.
Note that you can use `observe` to call a function whenever a new value is received
from JavaScript. Refer
[here](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Events.html#signatures)
for an example.
"""
title = t.CUnicode("Layer", allow_none=False).tag(sync=True)
"""
The title of the layer. The title of the layer is visible in the table of
contents produced by the lonboard.controls.make_TOC() function.
"""
def default_geoarrow_viewport(
table: Table,
) -> Optional[Tuple[Bbox, WeightedCentroid]]:
# Note: in the ArcLayer we won't necessarily have a column with a geoarrow
# extension type/metadata
geom_col_idx = get_geometry_column_index(table.schema)
if geom_col_idx is None:
return None
geom_field = table.schema.field(geom_col_idx)
geom_col = table.column(geom_col_idx)
table_bbox = total_bounds(geom_field, geom_col)
table_centroid = weighted_centroid(geom_field, geom_col)
# Check each layer's data _individually_ to ensure that no layer is outside of
# epsg:4326 bounds
if table_centroid.num_items > 0:
if table_centroid.x is not None and (
table_centroid.x < -180 or table_centroid.x > 180
):
msg = "Longitude of data's center is outside of WGS84 bounds.\n"
msg += "Is data in WGS84 projection?"
raise ValueError(msg)
if table_centroid.y is not None and (
table_centroid.y < -90 or table_centroid.y > 90
):
msg = "Latitude of data's center is outside of WGS84 bounds.\n"
msg += "Is data in WGS84 projection?"
raise ValueError(msg)
return table_bbox, table_centroid
class BaseArrowLayer(BaseLayer):
"""Any Arrow-based layer should subclass from BaseArrowLayer"""
# Note: these class attributes are **not** serialized to JS
# Number of rows per chunk for serializing table and accessor columns.
#
# This is a _layer-level_ construct because we need to ensure the main table and all
# accessors have exactly the same chunking, because each chunk is rendered
# independently as a separate deck.gl layer
_rows_per_chunk: int
# The following traitlets **are** serialized to JS
table: ArrowTableTrait
def __init__(
self,
*,
table: ArrowStreamExportable,
_rows_per_chunk: Optional[int] = None,
**kwargs: Unpack[BaseLayerKwargs],
):
table_o3 = Table.from_arrow(table)
parsed_tables = parse_serialized_table(table_o3)
assert len(parsed_tables) == 1, (
"Mixed geometry type input not supported here. Use the top "
"level viz() function or separate your geometry types in advance."
)
table_o3 = parsed_tables[0]
table_o3 = make_geometry_interleaved(table_o3)
# Reproject table to WGS84 if needed
# Note this must happen before calculating the default viewport
table_o3 = reproject_table(table_o3, to_crs=OGC_84)
default_viewport = default_geoarrow_viewport(table_o3)
if default_viewport is not None:
self._bbox = default_viewport[0]
self._weighted_centroid = default_viewport[1]
rows_per_chunk = _rows_per_chunk or infer_rows_per_chunk(table_o3)
if rows_per_chunk <= 0:
raise ValueError("Cannot serialize table with 0 rows per chunk.")
self._rows_per_chunk = rows_per_chunk
table_o3 = table_o3.rechunk(max_chunksize=rows_per_chunk)
super().__init__(table=table_o3, **kwargs)
@classmethod
def from_geopandas(
cls,
gdf: gpd.GeoDataFrame,
*,
auto_downcast: bool = True,
**kwargs: Unpack[BaseLayerKwargs],
) -> Self:
"""Construct a Layer from a geopandas GeoDataFrame.
The GeoDataFrame will be reprojected to EPSG:4326 if it is not already in that
coordinate system.
Args:
gdf: The GeoDataFrame to set on the layer.
Keyword Args:
auto_downcast: If `True`, automatically downcast to smaller-size data types
if possible without loss of precision. This calls
[pandas.DataFrame.convert_dtypes][pandas.DataFrame.convert_dtypes] and
[pandas.to_numeric][pandas.to_numeric] under the hood.
Returns:
A Layer with the initialized data.
"""
if auto_downcast:
# Note: we don't deep copy because we don't need to clone geometries
gdf = _auto_downcast(gdf.copy()) # type: ignore
table = geopandas_to_geoarrow(gdf)
return cls(table=table, **kwargs)
@classmethod
def from_duckdb(
cls,
sql: Union[str, duckdb.DuckDBPyRelation],
con: Optional[duckdb.DuckDBPyConnection] = None,
*,
crs: Optional[Union[str, pyproj.CRS]] = None,
**kwargs: Unpack[BaseLayerKwargs],
) -> Self:
"""Construct a Layer from a duckdb-spatial query.
DuckDB Spatial does not currently expose coordinate reference system
information, so **the user must ensure that data has been reprojected to
EPSG:4326** or pass in the existing CRS of the data in the `crs` keyword
parameter.
Args:
sql: The SQL input to visualize. This can either be a string containing a
SQL query or the output of the duckdb `sql` function.
con: The current DuckDB connection. This is required when passing a `str` to
the `sql` parameter or when using a non-global DuckDB connection.
Defaults to None.
Keyword Args:
crs: The CRS of the input data. This can either be a string passed to
`pyproj.CRS.from_user_input` or a `pyproj.CRS` object. Defaults to None.
Returns:
A Layer with the initialized data.
"""
if isinstance(sql, str):
assert con is not None, "con must be provided when sql is a str"
rel = con.sql(sql)
table = _from_duckdb(rel, con=con, crs=crs)
else:
table = _from_duckdb(sql, con=con, crs=crs)
return cls(table=table, **kwargs)
class BitmapLayer(BaseLayer):
"""
The `BitmapLayer` renders a bitmap (e.g. PNG, JPEG, or WebP) at specified
boundaries.
**Example:**
```py
from lonboard import Map, BitmapLayer
layer = BitmapLayer(
image='https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-districts.png',
bounds=[-122.5190, 37.7045, -122.355, 37.829]
)
m = Map(layer)
m
```
"""
def __init__(self, **kwargs: BitmapLayerKwargs):
super().__init__(**kwargs) # type: ignore
_layer_type = t.Unicode("bitmap").tag(sync=True)
image = t.Unicode().tag(sync=True)
"""The URL to an image to display.
- Type: `str`
"""
bounds = t.Union(
[
VariableLengthTuple(t.Float(), minlen=4, maxlen=4),
VariableLengthTuple(
VariableLengthTuple(t.Float(), minlen=2, maxlen=2),
minlen=4,
maxlen=4,
),
]
).tag(sync=True)
"""The bounds of the image.
Supported formats:
- Coordinates of the bounding box of the bitmap `[left, bottom, right, top]`
- Coordinates of four corners of the bitmap, should follow the sequence of
`[[left, bottom], [left, top], [right, top], [right, bottom]]`.
"""
desaturate = t.Float(0, min=0, max=1).tag(sync=True)
"""The desaturation of the bitmap. Between `[0, 1]`.
- Type: `float`, optional
- Default: `0`
"""
transparent_color = VariableLengthTuple(
t.Float(), default_value=None, allow_none=True, minlen=3, maxlen=4
)
"""The color to use for transparent pixels, in `[r, g, b, a]`.
- Type: `List[float]`, optional
- Default: `[0, 0, 0, 0]`
"""
tint_color = VariableLengthTuple(
t.Float(), default_value=None, allow_none=True, minlen=3, maxlen=4
)
"""The color to tint the bitmap by, in `[r, g, b]`.
- Type: `List[float]`, optional
- Default: `[255, 255, 255]`
"""
@property
def _bbox(self) -> Bbox:
a, b, c, d = self.bounds
# Four corners
if isinstance(a, tuple):
bbox = Bbox()
bbox.update(Bbox(a[0], a[1], a[0], a[1]))
bbox.update(Bbox(b[0], b[1], b[0], b[1]))
bbox.update(Bbox(c[0], c[1], c[0], c[1]))
bbox.update(Bbox(d[0], d[1], d[0], d[1]))
return bbox
return Bbox(a, b, c, d)
@property
def _weighted_centroid(self) -> WeightedCentroid:
bbox = self._bbox
center_x = (bbox.minx + bbox.maxx) / 2
center_y = (bbox.miny + bbox.maxy) / 2
# no idea what weight to put on this; we don't know how many "objects" this
# image should represent.
return WeightedCentroid(x=center_x, y=center_y, num_items=100)
class BitmapTileLayer(BaseLayer):
"""
The BitmapTileLayer renders image tiles (e.g. PNG, JPEG, or WebP) in the web
mercator tiling system. Only the tiles visible in the current viewport are loaded
and rendered.
**Example:**
```py
from lonboard import Map, BitmapTileLayer
# We set `max_requests < 0` because `tile.openstreetmap.org` supports HTTP/2.
layer = BitmapTileLayer(
data="https://tile.openstreetmap.org/{z}/{x}/{y}.png",
tile_size=256,
max_requests=-1,
min_zoom=0,
max_zoom=19,
)
m = Map(layer)
```
"""
def __init__(self, **kwargs: BitmapTileLayerKwargs):
super().__init__(**kwargs) # type: ignore
_layer_type = t.Unicode("bitmap-tile").tag(sync=True)
data = t.Union([t.Unicode(), VariableLengthTuple(t.Unicode(), minlen=1)]).tag(
sync=True
)
"""
Either a URL template or an array of URL templates from which the tile data should
be loaded.
If the value is a string: a URL template. Substrings {x} {y} and {z}, if present,
will be replaced with a tile's actual index when it is requested.
If the value is an array: multiple URL templates. Each endpoint must return the same
content for the same tile index. This can be used to work around domain sharding,
allowing browsers to download more resources simultaneously. Requests made are
balanced among the endpoints, based on the tile index.
"""
tile_size = t.Int(None, allow_none=True).tag(sync=True)
"""
The pixel dimension of the tiles, usually a power of 2.
Tile size represents the target pixel width and height of each tile when rendered.
Smaller tile sizes display the content at higher resolution, while the layer needs
to load more tiles to fill the same viewport.
- Type: `int`, optional
- Default: `512`
"""
zoom_offset = t.Int(None, allow_none=True).tag(sync=True)
"""
This offset changes the zoom level at which the tiles are fetched. Needs to be an
integer.
- Type: `int`, optional
- Default: `0`
"""
max_zoom = t.Int(None, allow_none=True).tag(sync=True)
"""
The max zoom level of the layer's data. When overzoomed (i.e. `zoom > max_zoom`),
tiles from this level will be displayed.
- Type: `int`, optional
- Default: `None`
"""
min_zoom = t.Int(None, allow_none=True).tag(sync=True)
"""
The min zoom level of the layer's data. When underzoomed (i.e. `zoom < min_zoom`),
the layer will not display any tiles unless `extent` is defined, to avoid issuing
too many tile requests.
- Type: `int`, optional
- Default: `None`
"""
extent = VariableLengthTuple(
t.Float(), minlen=4, maxlen=4, allow_none=True, default_value=None
).tag(sync=True)
"""
The bounding box of the layer's data, in the form of `[min_x, min_y, max_x, max_y]`.
If provided, the layer will only load and render the tiles that are needed to fill
this box.
- Type: `List[float]`, optional
- Default: `None`
"""
max_cache_size = t.Int(None, allow_none=True).tag(sync=True)
"""
The maximum number of tiles that can be cached. The tile cache keeps loaded tiles in
memory even if they are no longer visible. It reduces the need to re-download the
same data over and over again when the user pan/zooms around the map, providing a
smoother experience.
If not supplied, the `max_cache_size` is calculated as 5 times the number of tiles
in the current viewport.
- Type: `int`, optional
- Default: `None`
"""
# TODO: Not sure if `getTileData` returns a `byteLength`?
# max_cache_byte_size = t.Int(None, allow_none=True).tag(sync=True)
# """
# """
refinement_strategy = t.Unicode(None, allow_none=True).tag(sync=True)
"""How the tile layer refines the visibility of tiles.
When zooming in and out, if the layer only shows tiles from the current zoom level,
then the user may observe undesirable flashing while new data is loading. By setting
`refinement_strategy` the layer can attempt to maintain visual continuity by
displaying cached data from a different zoom level before data is available.
This prop accepts one of the following:
- `"best-available"`: If a tile in the current viewport is waiting for its data to
load, use cached content from the closest zoom level to fill the empty space. This
approach minimizes the visual flashing due to missing content.
- `"no-overlap"`: Avoid showing overlapping tiles when backfilling with cached
content. This is usually favorable when tiles do not have opaque backgrounds.
- `"never"`: Do not display any tile that is not selected.
- Type: `str`, optional
- Default: `"best-available"`
"""
max_requests = t.Int(None, allow_none=True).tag(sync=True)
"""The maximum number of concurrent data fetches.
If <= 0, no throttling will occur, and `get_tile_data` may be called an unlimited
number of times concurrently regardless of how long that tile is or was visible.
If > 0, a maximum of `max_requests` instances of `get_tile_data` will be called
concurrently. Requests may never be called if the tile wasn't visible long enough to
be scheduled and started. Requests may also be aborted (through the signal passed to
`get_tile_data`) if there are more than `max_requests` ongoing requests and some of
those are for tiles that are no longer visible.
If `get_tile_data` makes fetch requests against an HTTP 1 web server, then
max_requests should correlate to the browser's maximum number of concurrent fetch
requests. For Chrome, the max is 6 per domain. If you use the data prop and specify
multiple domains, you can increase this limit. For example, with Chrome and 3
domains specified, you can set max_requests=18.
If the web server supports HTTP/2 (Open Chrome dev tools and look for "h2" in the
Protocol column), then you can make an unlimited number of concurrent requests (and
can set max_requests=-1). Note that this will request data for every tile, no matter
how long the tile was visible, and may increase server load.
"""
desaturate = t.Float(0, min=0, max=1).tag(sync=True)
"""The desaturation of the bitmap. Between `[0, 1]`.
- Type: `float`, optional
- Default: `0`
"""
transparent_color = VariableLengthTuple(
t.Float(), default_value=None, allow_none=True, minlen=3, maxlen=4
)
"""The color to use for transparent pixels, in `[r, g, b, a]`.
- Type: `List[float]`, optional
- Default: `[0, 0, 0, 0]`
"""
tint_color = VariableLengthTuple(
t.Float(), default_value=None, allow_none=True, minlen=3, maxlen=4
)
"""The color to tint the bitmap by, in `[r, g, b]`.
- Type: `List[float]`, optional
- Default: `[255, 255, 255]`
"""
class ColumnLayer(BaseArrowLayer):
"""
The ColumnLayer renders extruded cylinders (tessellated regular polygons) at given
coordinates.
"""
def __init__(
self,
*,
table: ArrowStreamExportable,
_rows_per_chunk: Optional[int] = None,
**kwargs: Unpack[ColumnLayerKwargs],
):
super().__init__(table=table, _rows_per_chunk=_rows_per_chunk, **kwargs)
@classmethod
def from_geopandas(
cls,
gdf: gpd.GeoDataFrame,
*,
auto_downcast: bool = True,
**kwargs: Unpack[ColumnLayerKwargs],
) -> Self:
return super().from_geopandas(gdf=gdf, auto_downcast=auto_downcast, **kwargs)
@classmethod
def from_duckdb(
cls,
sql: Union[str, duckdb.DuckDBPyRelation],
con: Optional[duckdb.DuckDBPyConnection] = None,
*,
crs: Optional[Union[str, pyproj.CRS]] = None,
**kwargs: Unpack[ColumnLayerKwargs],
) -> Self:
return super().from_duckdb(sql=sql, con=con, crs=crs, **kwargs)
_layer_type = t.Unicode("column").tag(sync=True)
table = ArrowTableTrait(allowed_geometry_types={EXTENSION_NAME.POINT})
"""A GeoArrow table with a Point or MultiPoint column.
This is the fastest way to plot data from an existing GeoArrow source, such as
[geoarrow-rust](https://geoarrow.github.io/geoarrow-rs/python/latest) or
[geoarrow-pyarrow](https://geoarrow.github.io/geoarrow-python/main/index.html).
If you have a GeoPandas `GeoDataFrame`, use
[`from_geopandas`][lonboard.ScatterplotLayer.from_geopandas] instead.
"""
disk_resolution = t.Int(None, allow_none=True).tag(sync=True)
"""
The number of sides to render the disk as. The disk is a regular polygon that fits
inside the given radius. A higher resolution will yield a smoother look close-up,
but also need more resources to render.
- Type: `int`, optional
- Default: `20`
"""
radius = t.Float(None, allow_none=True).tag(sync=True)
"""
Disk size in units specified by `radius_units` (default meters).
- Type: `float`, optional
- Default: `1000`
"""
angle = t.Float(None, allow_none=True).tag(sync=True)
"""
Disk rotation, counter-clockwise in degrees.
- Type: `float`, optional
- Default: `0`
"""
offset = t.Tuple(t.Float(), t.Float(), default_value=None, allow_none=True).tag(
sync=True
)
"""
Disk offset from the position, relative to the radius. By default, the disk is
centered at each position.
- Type: `tuple[float, float]`, optional
- Default: `(0, 0)`
"""
coverage = t.Float(None, allow_none=True).tag(sync=True)
"""
Radius multiplier, between 0 - 1. The radius of the disk is calculated by
`coverage * radius`
- Type: `float`, optional
- Default: `1`
"""
elevation_scale = t.Float(None, allow_none=True).tag(sync=True)
"""
Column elevation multiplier. The elevation of column is calculated by
`elevation_scale * get_elevation(d)`. `elevation_scale` is a handy property
to scale all column elevations without updating the data.
- Type: `float`, optional
- Default: `1`
"""
filled = t.Bool(None, allow_none=True).tag(sync=True)
"""
Whether to draw a filled column (solid fill).
- Type: `bool`, optional
- Default: `True`
"""
stroked = t.Bool(None, allow_none=True).tag(sync=True)
"""
Whether to draw an outline around the disks. Only applies if `extruded=False`.
- Type: `bool`, optional
- Default: `False`
"""
extruded = t.Bool(None, allow_none=True).tag(sync=True)
"""
Whether to extrude the columns. If set to `false`, all columns will be rendered as
flat polygons.
- Type: `bool`, optional
- Default: `True`
"""
wireframe = t.Bool(None, allow_none=True).tag(sync=True)
"""
Whether to generate a line wireframe of the column. The outline will have
"horizontal" lines closing the top and bottom polygons and a vertical line
(a "strut") for each vertex around the disk. Only applies if `extruded=True`.
- Type: `bool`, optional
- Default: `False`
"""
flat_shading = t.Bool(None, allow_none=True).tag(sync=True)
"""
If `True`, the vertical surfaces of the columns use [flat
shading](https://en.wikipedia.org/wiki/Shading#Flat_vs._smooth_shading). If `false`,
use smooth shading. Only effective if `extruded` is `True`.
- Type: `bool`, optional
- Default: `False`
"""
radius_units = t.Unicode(None, allow_none=True).tag(sync=True)
"""
The units of the radius, one of `'meters'`, `'common'`, and `'pixels'`. See [unit
system](https://deck.gl/docs/developer-guide/coordinate-systems#supported-units).
- Type: `str`, optional
- Default: `'meters'`
"""
line_width_units = t.Unicode(None, allow_none=True).tag(sync=True)
"""
The units of the line width, one of `'meters'`, `'common'`, and `'pixels'`. See
[unit
system](https://deck.gl/docs/developer-guide/coordinate-systems#supported-units).
- Type: `str`, optional
- Default: `'meters'`
"""
line_width_scale = t.Float(None, allow_none=True, min=0).tag(sync=True)
"""
The line width multiplier that multiplied to all outlines if the `stroked` attribute
is `True`.
- Type: `float`, optional
- Default: `1`
"""
line_width_min_pixels = t.Float(None, allow_none=True, min=0).tag(sync=True)
"""
The minimum outline width in pixels. This can be used to prevent the line from
getting too small when zoomed out.
- Type: `float`, optional
- Default: `0`
"""
line_width_max_pixels = t.Float(None, allow_none=True, min=0).tag(sync=True)
"""
The maximum outline width in pixels. This can be used to prevent the line from
getting too big when zoomed in.
- Type: `float`, optional
- Default: `None`
"""
get_fill_color = ColorAccessor(None, allow_none=True)
"""
The filled color of each object in the format of `[r, g, b, [a]]`. Each channel is a
number between 0-255 and `a` is 255 if not supplied.
- Type: [ColorAccessor][lonboard.traits.ColorAccessor], optional
- If a single `list` or `tuple` is provided, it is used as the filled color for
all objects.
- If a numpy or pyarrow array is provided, each value in the array will be used
as the filled color for the object at the same row index.
- Default: `[0, 0, 0, 255]`.
"""
get_line_color = ColorAccessor(None, allow_none=True)
"""
The outline color of each object in the format of `[r, g, b, [a]]`. Each channel is
a number between 0-255 and `a` is 255 if not supplied.
- Type: [ColorAccessor][lonboard.traits.ColorAccessor], optional
- If a single `list` or `tuple` is provided, it is used as the outline color for
all objects.
- If a numpy or pyarrow array is provided, each value in the array will be used
as the outline color for the object at the same row index.
- Default: `[0, 0, 0, 255]`.
"""
get_elevation = FloatAccessor(None, allow_none=True)
"""
The elevation of each cell in meters.
Only applies if `extruded=True`.
- Type: [FloatAccessor][lonboard.traits.FloatAccessor], optional
- If a number is provided, it is used as the width for all polygons.
- If an array is provided, each value in the array will be used as the width for
the polygon at the same row index.
- Default: `1000`.
"""
get_line_width = FloatAccessor(None, allow_none=True)
"""
The width of the outline of each column, in units specified by `line_width_units`
(default `'meters'`). Only applies if `extruded: false` and `stroked: true`.
- Type: [FloatAccessor][lonboard.traits.FloatAccessor], optional
- If a number is provided, it is used as the outline width for all columns.
- If an array is provided, each value in the array will be used as the outline
width for the column at the same row index.
- Default: `1`.
"""
class PolygonLayer(BaseArrowLayer):
"""The `PolygonLayer` renders filled, stroked and/or extruded polygons.
!!! note
This layer is essentially a combination of a [`PathLayer`][lonboard.PathLayer]
and a [`SolidPolygonLayer`][lonboard.SolidPolygonLayer]. This has some overhead
beyond a `SolidPolygonLayer`, so if you're looking for the maximum performance
with large data, you may want to use a `SolidPolygonLayer` directly.
**Example:**
From GeoPandas:
```py
import geopandas as gpd
from lonboard import Map, PolygonLayer
# A GeoDataFrame with Polygon or MultiPolygon geometries
gdf = gpd.GeoDataFrame()
layer = PolygonLayer.from_geopandas(
gdf,
get_fill_color=[255, 0, 0],
get_line_color=[0, 100, 100, 150],
)
m = Map(layer)
```