-
Notifications
You must be signed in to change notification settings - Fork 755
Expand file tree
/
Copy pathgeoseries.py
More file actions
3199 lines (2721 loc) · 106 KB
/
geoseries.py
File metadata and controls
3199 lines (2721 loc) · 106 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import sys
import typing
from typing import Any, Union, Literal, List
import numpy as np
import geopandas as gpd
import sedona.spark.geopandas as sgpd
import pandas as pd
import pyspark.pandas as pspd
import pyspark
from pyspark.pandas import Series as PandasOnSparkSeries
from pyspark.pandas.frame import DataFrame as PandasOnSparkDataFrame
from pyspark.pandas.internal import InternalFrame
from pyspark.pandas.series import first_series
from pyspark.pandas.utils import scol_for
from pyspark.sql.types import NullType
from sedona.spark.sql.types import GeometryType
from sedona.spark.sql import st_aggregates as sta
from sedona.spark.sql import st_constructors as stc
from sedona.spark.sql import st_functions as stf
from sedona.spark.sql import st_predicates as stp
from pyspark.sql import Column as PySparkColumn
from pyspark.sql import functions as F
import shapely
from shapely.geometry.base import BaseGeometry
from sedona.spark.geopandas._typing import Label
from sedona.spark.geopandas.base import GeoFrame
from sedona.spark.geopandas.geodataframe import GeoDataFrame
from sedona.spark.geopandas.sindex import SpatialIndex
from packaging.version import parse as parse_version
from pyspark.pandas.internal import (
SPARK_DEFAULT_INDEX_NAME, # __index_level_0__
NATURAL_ORDER_COLUMN_NAME,
SPARK_DEFAULT_SERIES_NAME, # '0'
)
# ============================================================================
# IMPLEMENTATION STATUS TRACKING
# ============================================================================
IMPLEMENTATION_PRIORITY = {
"HIGH": [
"contains",
"contains_properly",
"convex_hull",
"explode",
"clip",
"clip_by_rect",
"from_shapely",
"count_coordinates",
"count_geometries",
"is_ring",
"is_closed",
"reverse",
],
"MEDIUM": [
"force_2d",
"force_3d",
"transform",
"segmentize",
"line_merge",
"unary_union",
"union_all",
"to_json",
"from_file",
"count_interior_rings",
],
"LOW": [
"delaunay_triangles",
"voronoi_polygons",
"minimum_bounding_circle",
"representative_point",
"extract_unique_points",
"from_arrow",
"to_arrow",
],
}
def _not_implemented_error(method_name: str, additional_info: str = "") -> str:
"""
Generate a standardized NotImplementedError message.
Parameters
----------
method_name : str
The name of the method that is not implemented.
additional_info : str, optional
Additional information about the method or workarounds.
Returns
-------
str
Formatted error message.
"""
base_message = (
f"GeoSeries.{method_name}() is not implemented yet.\n"
f"This method will be added in a future release."
)
if additional_info:
base_message += f"\n\n{additional_info}"
workaround = (
"\n\nTemporary workaround - use GeoPandas:\n"
" gpd_series = sedona_series.to_geopandas()\n"
f" result = gpd_series.{method_name}(...)\n"
" # Note: This will collect all data to the driver."
)
return base_message + workaround
class GeoSeries(GeoFrame, pspd.Series):
"""
A pandas-on-Spark Series for geometric/spatial operations.
GeoSeries extends pyspark.pandas.Series to provide spatial operations
using Apache Sedona's spatial functions. It maintains compatibility
with GeoPandas GeoSeries while operating on distributed datasets.
Parameters
----------
data : array-like, Iterable, dict, or scalar value
Contains the data for the GeoSeries. Can be geometries, WKB bytes,
or other GeoSeries/GeoDataFrame objects.
index : array-like or Index (1d), optional
Values must be hashable and have the same length as `data`.
crs : pyproj.CRS, optional
Coordinate Reference System for the geometries.
dtype : dtype, optional
Data type for the GeoSeries.
name : str, optional
Name of the GeoSeries.
copy : bool, default False
Whether to copy the input data.
Examples
--------
>>> from shapely.geometry import Point, Polygon
>>> from sedona.spark.geopandas import GeoSeries
>>>
>>> # Create from geometries
>>> s = GeoSeries([Point(0, 0), Point(1, 1)], crs='EPSG:4326')
>>> s
0 POINT (0 0)
1 POINT (1 1)
dtype: geometry
>>>
>>> # Spatial operations
>>> s.buffer(0.1).area
0 0.031416
1 0.031416
dtype: float64
>>>
>>> # CRS operations
>>> s_utm = s.to_crs('EPSG:32633')
>>> s_utm.crs
<Projected CRS: EPSG:32633>
Name: WGS 84 / UTM zone 33N
...
Notes
-----
This implementation differs from GeoPandas in several ways:
- Uses Spark for distributed processing
- Geometries are stored in WKB (Well-Known Binary) format internally
- Some methods may have different performance characteristics
- Not all GeoPandas methods are implemented yet (see Sedona GeoPandas docs).
Performance Considerations:
- Operations are distributed across Spark cluster
- Avoid calling .to_geopandas() on large datasets
- Use .sample() for testing with large datasets
See Also
--------
geopandas.GeoSeries : The GeoPandas equivalent
sedona.spark.geopandas.GeoDataFrame : DataFrame with geometry column
"""
def __getitem__(self, key: Any) -> Any:
return pspd.Series.__getitem__(self, key)
def __init__(
self,
data=None,
index=None,
dtype=None,
name=None,
copy=False,
fastpath=False,
crs=None,
**kwargs,
):
"""
Initialize a GeoSeries object.
Parameters
----------
data : array-like, GeoDataFrame, GeoSeries, or pandas Series
The input data for the GeoSeries.
index : array-like, optional
The index for the GeoSeries.
crs : pyproj.CRS, optional
Coordinate Reference System for the GeoSeries.
dtype : dtype, optional
Data type for the GeoSeries.
name : str, optional
Name of the GeoSeries.
copy : bool, default False
Whether to copy the input data.
fastpath : bool, default False
Internal parameter for fast initialization.
Examples
--------
>>> from shapely.geometry import Point
>>> import geopandas as gpd
>>> import pandas as pd
>>> from sedona.spark.geopandas import GeoSeries
# Example 1: Initialize with GeoDataFrame
>>> gdf = gpd.GeoDataFrame({'geometry': [Point(1, 1), Point(2, 2)]})
>>> gs = GeoSeries(data=gdf)
>>> print(gs)
0 POINT (1 1)
1 POINT (2 2)
Name: geometry, dtype: geometry
# Example 2: Initialize with GeoSeries
>>> gseries = gpd.GeoSeries([Point(1, 1), Point(2, 2)])
>>> gs = GeoSeries(data=gseries)
>>> print(gs)
0 POINT (1 1)
1 POINT (2 2)
dtype: geometry
# Example 3: Initialize with pandas Series
>>> pseries = pd.Series([Point(1, 1), Point(2, 2)])
>>> gs = GeoSeries(data=pseries)
>>> print(gs)
0 POINT (1 1)
1 POINT (2 2)
dtype: geometry
"""
assert data is not None
self._anchor: GeoDataFrame
self._col_label: Label
self._sindex: SpatialIndex = None
if isinstance(
data, (GeoDataFrame, GeoSeries, PandasOnSparkSeries, PandasOnSparkDataFrame)
):
assert dtype is None
assert name is None
assert not copy
assert not fastpath
# We don't check CRS validity to keep the operation lazy.
# Keep the original code for now.
# data_crs = None
# if hasattr(data, "crs"):
# data_crs = data.crs
# if data_crs is not None and crs is not None and data_crs != crs:
# raise ValueError(
# "CRS mismatch between CRS of the passed geometries "
# "and 'crs'. Use 'GeoSeries.set_crs(crs, "
# "allow_override=True)' to overwrite CRS or "
# "'GeoSeries.to_crs(crs)' to reproject geometries. "
# )
# PySpark Pandas' ps.Series.__init__() does not support construction from a
# ps.Series input. For now, we manually implement the logic.
index = data._col_label if index is None else index
ps_df = pspd.DataFrame(data._anchor)
super().__init__(
data=ps_df,
index=index,
dtype=dtype,
name=name,
copy=copy,
fastpath=fastpath,
)
else:
if isinstance(data, pd.Series):
assert index is None
assert dtype is None
assert name is None
assert not copy
assert not fastpath
pd_series = data
else:
pd_series = pd.Series(
data=data,
index=index,
dtype=dtype,
name=name,
copy=copy,
fastpath=fastpath,
)
pd_series = pd_series.astype(object)
# Initialize the parent class PySpark Series with the pandas Series.
super().__init__(data=pd_series)
# Ensure we're storing geometry types.
if (
self.spark.data_type != GeometryType()
and self.spark.data_type != NullType()
):
raise TypeError(
"Non geometry data passed to GeoSeries constructor, "
f"received data of dtype '{self.spark.data_type.typeName()}'"
)
if crs:
self.set_crs(crs, inplace=True)
def _is_empty(self) -> bool:
"""Check if this GeoSeries has no rows without triggering a full Spark scan."""
return not self._internal.spark_frame.take(1)
# ============================================================================
# COORDINATE REFERENCE SYSTEM (CRS) OPERATIONS
# ============================================================================
@property
def crs(self) -> Union["CRS", None]:
"""The Coordinate Reference System (CRS) as a ``pyproj.CRS`` object.
Returns None if the CRS is not set, and to set the value it
:getter: Returns a ``pyproj.CRS`` or None. When setting, the value
can be anything accepted by
:meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
Note: This assumes all records in the GeoSeries are assumed to have the same CRS.
Examples
--------
>>> from shapely.geometry import Point
>>> from sedona.spark.geopandas import GeoSeries
>>> s = GeoSeries([Point(1, 1), Point(2, 2)], crs='EPSG:4326')
>>> s.crs # doctest: +SKIP
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
See Also
--------
GeoSeries.set_crs : assign CRS
GeoSeries.to_crs : re-project to another CRS
"""
from pyproj import CRS
if self._is_empty():
return None
# F.first is non-deterministic, but it doesn't matter because all non-null values should be the same.
spark_col = stf.ST_SRID(F.first(self.spark.column, ignorenulls=True))
# Set this to avoid error complaining that we don't have a groupby column.
tmp_series = self._query_geometry_column(
spark_col,
returns_geom=False,
is_aggr=True,
)
# All geometries should have the same SRID,
# so we just take the SRID of the first non-null element.
srid = tmp_series.item()
# Turn np.nan to 0 to avoid error.
srid = 0 if np.isnan(srid) else srid
# Sedona returns 0 if SRID doesn't exist.
return CRS.from_user_input(srid) if srid != 0 else None
@crs.setter
def crs(self, value: Union["CRS", None]):
self.set_crs(value, inplace=True)
@typing.overload
def set_crs(
self,
crs: Union[Any, None] = None,
epsg: Union[int, None] = None,
inplace: Literal[True] = True,
allow_override: bool = False,
) -> None: ...
@typing.overload
def set_crs(
self,
crs: Union[Any, None] = None,
epsg: Union[int, None] = None,
inplace: Literal[False] = False,
allow_override: bool = False,
) -> "GeoSeries": ...
def set_crs(
self,
crs: Union[Any, None] = None,
epsg: Union[int, None] = None,
inplace: bool = False,
allow_override: bool = True,
) -> Union["GeoSeries", None]:
"""
Set the Coordinate Reference System (CRS) of a ``GeoSeries``.
Pass ``None`` to remove CRS from the ``GeoSeries``.
Notes
-----
The underlying geometries are not transformed to this CRS. To
transform the geometries to a new CRS, use the ``to_crs`` method.
Parameters
----------
crs : pyproj.CRS | None, optional
The value can be anything accepted
by :meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
epsg : int, optional if `crs` is specified
EPSG code specifying the projection.
inplace : bool, default False
If True, the CRS of the GeoSeries will be changed in place
(while still returning the result) instead of making a copy of
the GeoSeries.
allow_override : bool, default True
If the GeoSeries already has a CRS, allow to replace the
existing CRS, even when both are not equal. In Sedona, setting this to True
will lead to eager evaluation instead of lazy evaluation. Unlike Geopandas,
True is the default value in Sedona for performance reasons.
Returns
-------
GeoSeries
Examples
--------
>>> from sedona.spark.geopandas import GeoSeries
>>> from shapely.geometry import Point
>>> s = GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s
0 POINT (1 1)
1 POINT (2 2)
2 POINT (3 3)
dtype: geometry
Setting CRS to a GeoSeries without one:
>>> s.crs is None
True
>>> s = s.set_crs('epsg:3857')
>>> s.crs # doctest: +SKIP
<Projected CRS: EPSG:3857>
Name: WGS 84 / Pseudo-Mercator
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: World - 85°S to 85°N
- bounds: (-180.0, -85.06, 180.0, 85.06)
Coordinate Operation:
- name: Popular Visualisation Pseudo-Mercator
- method: Popular Visualisation Pseudo Mercator
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
Overriding existing CRS:
>>> s = s.set_crs(4326, allow_override=True)
Without ``allow_override=True``, ``set_crs`` returns an error if you try to
override CRS.
See Also
--------
GeoSeries.to_crs : re-project to another CRS
"""
from pyproj import CRS
if crs is not None:
crs = CRS.from_user_input(crs)
elif epsg is not None:
crs = CRS.from_epsg(epsg)
# The below block for the not allow_override case is eager due to the self.crs call.
# This hurts performance and user experience, hence the default being set to True in Sedona.
if not allow_override:
curr_crs = self.crs
if curr_crs is not None and not curr_crs == crs:
raise ValueError(
"The GeoSeries already has a CRS which is not equal to the passed "
"CRS. Specify 'allow_override=True' to allow replacing the existing "
"CRS without doing any transformation. If you actually want to "
"transform the geometries, use 'GeoSeries.to_crs' instead."
)
# 0 indicates no SRID in Sedona.
new_epsg = crs.to_epsg() if crs else 0
spark_col = stf.ST_SetSRID(self.spark.column, new_epsg)
result = self._query_geometry_column(spark_col, keep_name=True)
if inplace:
self._update_inplace(result, invalidate_sindex=False)
return None
return result
# ============================================================================
# INTERNAL HELPER METHODS
# ============================================================================
def _query_geometry_column(
self,
spark_col: PySparkColumn,
df: pyspark.sql.DataFrame = None,
returns_geom: bool = True,
is_aggr: bool = False,
keep_name: bool = False,
) -> Union["GeoSeries", pspd.Series]:
"""
Helper method to query a single geometry column with a specified operation.
Parameters
----------
spark_col : str
The query to apply to the geometry column.
df : pyspark.sql.DataFrame
The dataframe to query. If not provided, the internal dataframe will be used.
returns_geom : bool, default True
If True, the geometry column will be converted back to EWKB format.
is_aggr : bool, default False
If True, the query is an aggregation query.
Returns
-------
GeoSeries
A GeoSeries with the operation applied to the geometry column.
"""
df = self._internal.spark_frame if df is None else df
rename = SPARK_DEFAULT_SERIES_NAME
if keep_name and self.name:
rename = self.name
col_expr = spark_col.alias(rename)
exprs = [col_expr]
index_spark_columns = []
index_fields = []
if not is_aggr:
# We always select NATURAL_ORDER_COLUMN_NAME, to avoid having to regenerate it in the result.
# We always select SPARK_DEFAULT_INDEX_NAME, to retain series index info.
exprs.append(scol_for(df, SPARK_DEFAULT_INDEX_NAME))
exprs.append(scol_for(df, NATURAL_ORDER_COLUMN_NAME))
index_spark_columns = [scol_for(df, SPARK_DEFAULT_INDEX_NAME)]
index_fields = [self._internal.index_fields[0]]
sdf = df.select(
col_expr,
scol_for(df, SPARK_DEFAULT_INDEX_NAME),
scol_for(df, NATURAL_ORDER_COLUMN_NAME),
)
# Otherwise, if is_aggr, we don't select the index columns.
else:
sdf = df.select(*exprs)
internal = self._internal.copy(
spark_frame=sdf,
index_fields=index_fields,
index_spark_columns=index_spark_columns,
data_spark_columns=[scol_for(sdf, rename)],
data_fields=[self._internal.data_fields[0].copy(name=rename)],
column_label_names=[(rename,)],
)
ps_series = first_series(PandasOnSparkDataFrame(internal))
# Convert Spark series default name to pandas series default name (None) if needed.
series_name = None if rename == SPARK_DEFAULT_SERIES_NAME else rename
ps_series = ps_series.rename(series_name)
result = GeoSeries(ps_series) if returns_geom else ps_series
return result
# ============================================================================
# CONVERSION AND SERIALIZATION METHODS
# ============================================================================
def to_geopandas(self) -> gpd.GeoSeries:
"""
Convert the GeoSeries to a GeoPandas GeoSeries.
Returns
-------
geopandas.GeoSeries
A GeoPandas GeoSeries.
"""
from pyspark.pandas.utils import log_advice
log_advice(
"`to_geopandas` loads all data into the driver's memory. "
"It should only be used if the resulting GeoPandas GeoSeries is expected to be small."
)
return self._to_geopandas()
def _to_geopandas(self) -> gpd.GeoSeries:
"""
Same as `to_geopandas()`, without issuing the advice log for internal usage.
"""
pd_series = self._to_internal_pandas()
return gpd.GeoSeries(pd_series, crs=self.crs)
def to_spark_pandas(self) -> pspd.Series:
return pspd.Series(pspd.DataFrame(self._psdf._internal))
# ============================================================================
# PROPERTIES AND ATTRIBUTES
# ============================================================================
@property
def geometry(self) -> "GeoSeries":
return self
@property
def sindex(self) -> SpatialIndex:
geometry_column = _get_series_col_name(self)
if geometry_column is None:
raise ValueError("No geometry column found in GeoSeries")
if self._sindex is None:
self._sindex = SpatialIndex(self)
return self._sindex
@property
def has_sindex(self):
return self._sindex is not None
def copy(self, deep=False):
"""Make a copy of this GeoSeries object.
Parameters
----------
deep : bool, default False
If True, a deep copy of the data is made. Otherwise, a shallow
copy is made.
Returns
-------
GeoSeries
A copy of this GeoSeries object.
Examples
--------
>>> from shapely.geometry import Point
>>> from sedona.spark.geopandas import GeoSeries
>>> gs = GeoSeries([Point(1, 1), Point(2, 2)])
>>> gs_copy = gs.copy()
>>> print(gs_copy)
0 POINT (1 1)
1 POINT (2 2)
dtype: geometry
"""
if deep:
return GeoSeries(
self._anchor.copy(), dtype=self.dtype, index=self._col_label
)
else:
return self
@property
def area(self) -> pspd.Series:
spark_col = stf.ST_Area(self.spark.column)
return self._query_geometry_column(
spark_col,
returns_geom=False,
)
@property
def geom_type(self) -> pspd.Series:
spark_col = stf.ST_GeometryType(self.spark.column)
result = self._query_geometry_column(
spark_col,
returns_geom=False,
)
# ST_GeometryType returns string as 'ST_Point'
# we crop the prefix off to get 'Point'
result = result.map(lambda x: x[3:])
return result
@property
def type(self):
return self.geom_type
@property
def length(self) -> pspd.Series:
spark_expr = (
F.when(
stf.ST_GeometryType(self.spark.column).isin(
["ST_LineString", "ST_MultiLineString"]
),
stf.ST_Length(self.spark.column),
)
.when(
stf.ST_GeometryType(self.spark.column).isin(
["ST_Polygon", "ST_MultiPolygon"]
),
stf.ST_Perimeter(self.spark.column),
)
.when(
stf.ST_GeometryType(self.spark.column).isin(
["ST_Point", "ST_MultiPoint"]
),
0.0,
)
.when(
stf.ST_GeometryType(self.spark.column).isin(["ST_GeometryCollection"]),
stf.ST_Length(self.spark.column) + stf.ST_Perimeter(self.spark.column),
)
)
return self._query_geometry_column(
spark_expr,
returns_geom=False,
)
@property
def is_valid(self) -> pspd.Series:
spark_col = stf.ST_IsValid(self.spark.column)
result = self._query_geometry_column(
spark_col,
returns_geom=False,
)
return _to_bool(result)
def is_valid_reason(self) -> pspd.Series:
spark_col = stf.ST_IsValidReason(self.spark.column)
return self._query_geometry_column(
spark_col,
returns_geom=False,
)
@property
def is_empty(self) -> pspd.Series:
spark_expr = stf.ST_IsEmpty(self.spark.column)
result = self._query_geometry_column(
spark_expr,
returns_geom=False,
)
return _to_bool(result)
def count_coordinates(self):
spark_expr = stf.ST_NPoints(self.spark.column)
return self._query_geometry_column(
spark_expr,
returns_geom=False,
)
def count_geometries(self):
spark_expr = stf.ST_NumGeometries(self.spark.column)
return self._query_geometry_column(
spark_expr,
returns_geom=False,
)
def count_interior_rings(self):
# Sedona's ST_NumInteriorRings returns NULL for non-polygon geometries
# (including MultiPolygon). GeoPandas semantics require 0 for
# non-polygon and empty geometries, so we wrap with coalesce.
spark_expr = F.coalesce(stf.ST_NumInteriorRings(self.spark.column), F.lit(0))
return self._query_geometry_column(
spark_expr,
returns_geom=False,
)
def dwithin(self, other, distance, align=None):
if not isinstance(distance, (float, int)):
raise NotImplementedError(
"Array-like distance for dwithin not implemented yet."
)
other_series, extended = self._make_series_of_val(other)
align = False if extended else align
spark_expr = stp.ST_DWithin(F.col("L"), F.col("R"), F.lit(distance))
return self._row_wise_operation(
spark_expr,
other_series,
align=align,
returns_geom=False,
default_val=False,
)
def clip_by_rect(self, xmin, ymin, xmax, ymax) -> "GeoSeries":
if not all(
isinstance(val, (int, float, np.integer, np.floating))
for val in [xmin, ymin, xmax, ymax]
):
raise TypeError(
"clip_by_rect only accepts scalar numeric values for xmin/ymin/xmax/ymax"
)
rect = stc.ST_PolygonFromEnvelope(
float(xmin), float(ymin), float(xmax), float(ymax)
)
spark_expr = stf.ST_Intersection(self.spark.column, rect)
return self._query_geometry_column(
spark_expr,
returns_geom=True,
)
def difference(self, other, align=None) -> "GeoSeries":
other_series, extended = self._make_series_of_val(other)
align = False if extended else align
spark_expr = stf.ST_Difference(F.col("L"), F.col("R"))
return self._row_wise_operation(
spark_expr,
other_series,
align=align,
returns_geom=True,
)
def symmetric_difference(self, other, align=None) -> "GeoSeries":
other_series, extended = self._make_series_of_val(other)
align = False if extended else align
spark_expr = stf.ST_SymDifference(F.col("L"), F.col("R"))
return self._row_wise_operation(
spark_expr,
other_series,
align=align,
returns_geom=True,
)
def union(self, other, align=None) -> "GeoSeries":
other_series, extended = self._make_series_of_val(other)
align = False if extended else align
spark_expr = stf.ST_Union(F.col("L"), F.col("R"))
return self._row_wise_operation(
spark_expr,
other_series,
align=align,
returns_geom=True,
)
@property
def is_simple(self) -> pspd.Series:
spark_expr = stf.ST_IsSimple(self.spark.column)
result = self._query_geometry_column(
spark_expr,
returns_geom=False,
)
return _to_bool(result)
@property
def is_ring(self):
spark_expr = stf.ST_IsRing(self.spark.column)
result = self._query_geometry_column(
spark_expr,
returns_geom=False,
)
return _to_bool(result)
@property
def is_ccw(self):
# Implementation of the abstract method.
raise NotImplementedError(
_not_implemented_error(
"is_ccw",
"Tests if LinearRing geometries are oriented counter-clockwise.",
)
)
@property
def is_closed(self):
# Only check LineStrings; return False for all other geometry types
spark_expr = F.when(
stf.ST_GeometryType(self.spark.column) == "ST_LineString",
stf.ST_IsClosed(self.spark.column),
).otherwise(False)
result = self._query_geometry_column(
spark_expr,
returns_geom=False,
)
return _to_bool(result)
@property
def has_z(self) -> pspd.Series:
spark_expr = stf.ST_HasZ(self.spark.column)
return self._query_geometry_column(
spark_expr,
returns_geom=False,
)
def get_precision(self):
# Implementation of the abstract method.
raise NotImplementedError("This method is not implemented yet.")
def get_geometry(self, index) -> "GeoSeries":
# Sedona errors on negative indexes, so we use a case statement to handle it ourselves.
spark_expr = stf.ST_GeometryN(
F.col("L"),
F.when(
stf.ST_NumGeometries(F.col("L")) + F.col("R") < 0,
None,
)
.when(F.col("R") < 0, stf.ST_NumGeometries(F.col("L")) + F.col("R"))
.otherwise(F.col("R")),
)
other, _ = self._make_series_of_val(index)
# align = False either way
align = False
return self._row_wise_operation(
spark_expr,
other,
align=align,
returns_geom=True,
default_val=None,
)
@property
def boundary(self) -> "GeoSeries":
# Geopandas and shapely return NULL for GeometryCollections, so we handle it separately
# https://shapely.readthedocs.io/en/stable/reference/shapely.boundary.html
spark_expr = F.when(
stf.ST_GeometryType(self.spark.column).isin(["ST_GeometryCollection"]),
None,
).otherwise(stf.ST_Boundary(self.spark.column))
return self._query_geometry_column(
spark_expr,
)
@property
def centroid(self) -> "GeoSeries":
spark_expr = stf.ST_Centroid(self.spark.column)
return self._query_geometry_column(
spark_expr,
returns_geom=True,
)
def concave_hull(self, ratio=0.0, allow_holes=False):
spark_expr = stf.ST_ConcaveHull(self.spark.column, ratio, allow_holes)
return self._query_geometry_column(
spark_expr,
returns_geom=True,
)
@property
def convex_hull(self) -> "GeoSeries":
spark_expr = stf.ST_ConvexHull(self.spark.column)