Repository navigation
[GH-3271] Enhance GeoDataFrame and GeoSeries to handle authoritative … - #3279
Conversation
…ative "no CRS" state for locally constructed geometries
jiayuasu
left a comment
There was a problem hiding this comment.
I left a few inline questions with small reproducers and possible fixes.
| active_geometry._internal.data_fields[0] | ||
| ) | ||
| if not has_crs_metadata: | ||
| self[self._geometry_column_name] = ( |
There was a problem hiding this comment.
I think this assignment can cross pandas-on-Spark anchors. _record_no_crs_metadata() builds a projected frame, so assigning its Series back here goes through different-frame alignment.
A small reproducer is:
with ps.option_context("compute.ops_on_diff_frames", False):
sgpd.GeoDataFrame(
{"zone": ["a"], "geometry": [Point(0, 0)]}
)The Spark 3.4 CI run currently raises ValueError: Cannot combine ... different dataframe at this line. With cross-frame operations enabled, duplicate indexes may be joined and multiply rows instead. Could we attach the alias and updated InternalField through the existing internal frame, for example with with_new_spark_column, rather than assigning a derived Series?
| untouched even though the public ``.crs`` becomes authoritatively | ||
| ``None`` instead of falling back to a distributed SRID lookup. | ||
| """ | ||
| result = self._query_geometry_column( |
There was a problem hiding this comment.
Could this path preserve valid falsy names?
s = sgpd.GeoSeries([Point(0, 0)], name=0)
assert s.name == 0
s = sgpd.GeoSeries([Point(0, 0)], name="")
assert s.name == ""Both names appear to become None because _query_geometry_column(..., keep_name=True) later checks if keep_name and self.name. A metadata-only update that keeps the existing label would avoid that; alternatively, the helper could test self.name is not None.
|
|
||
| if crs is not None: | ||
| self.set_crs(crs, inplace=True, allow_override=True) | ||
| elif is_locally_owned: |
There was a problem hiding this comment.
I think a CRS carried by a local GeometryArray is lost before this branch:
arr = gpd.GeoSeries([Point(0, 0)], crs=4326).array
s = sgpd.GeoSeries(arr)
assert s.crs.to_epsg() == 4326Only a gpd.GeoSeries is checked for an inherited CRS above; a GeometryArray, or a plain pd.Series backed by one, is converted to object and then stamped as authoritative None here. Could we read data.crs / data.array.crs before conversion and use that value when setting the metadata and embedded SRID?
| # or Sedona-managed source with its own CRS state) -- record that | ||
| # explicitly so later `.crs` reads don't fall back to a distributed | ||
| # SRID lookup just to discover there isn't one. | ||
| if crs is None and is_locally_owned and self._geometry_column_name is not None: |
There was a problem hiding this comment.
Could we apply this to every locally created geometry column rather than only the active one?
gdf = sgpd.GeoDataFrame({
"geometry": [Point(0, 0)],
"secondary": [Point(1, 1)],
})
has_metadata, _ = read_crs_metadata(
gdf["secondary"]._internal.data_fields[0]
)
assert has_metadataThe secondary column still appears metadata-free, so gdf.set_geometry("secondary").crs takes the distributed SRID fallback. For pandas/GeoPandas inputs with different per-column CRSs, those inactive CRS values can also be lost during the object conversion. One option would be to capture CRS by column position before conversion, then update every geometry field with either its CRS or explicit no-CRS metadata.
| # need to record an authoritative "no CRS" state below when the user | ||
| # didn't pass one. Wrapping an existing structure just inherits | ||
| # whatever CRS state (known, known-absent, or unknown) it already had. | ||
| is_locally_owned = not isinstance( |
There was a problem hiding this comment.
Could the file-constructor path be handled explicitly? GeoSeries.from_file passes df.geometry here, so a CRS-less file is classified as distributed and remains metadata-free.
A regression check could be:
s = sgpd.GeoSeries.from_file(crsless_geojson, format="geojson")
assert read_crs_metadata(s._internal.data_fields[0]) == (True, None)At the moment from_file also reads df.crs eagerly, which can run SRID inference, and a later s.crs can repeat it. Could the reader attach the authoritative known or known-absent state directly from the file metadata instead?
| before_jobs = 0 | ||
| try: | ||
| _ = s.crs | ||
| after_jobs = len(self.session._sc._jvm.scala.concurrent.FutureCache.getPythonPlans(s)) |
There was a problem hiding this comment.
I may be missing a fixture, but TestBase exposes spark and sc, not session. That would make this line raise AttributeError, and the broad except Exception then turns the result into zero jobs, so the test still passes without measuring anything. before_jobs is also unused.
Could we use a Spark job group/status tracker around the operation instead, without swallowing instrumentation errors? For example, assign a unique job group, construct the required binary predicate from two local CRS-less operands, and assert self.sc.statusTracker().getJobIdsForGroup(group) stays empty before materialization. The companion plan test could inspect queryExecution().optimizedPlan() and check for BatchEvalPython, ArrowEvalPython, and PythonUDF.
| def check_geodataframe(df): | ||
| assert isinstance(df, GeoDataFrame) | ||
|
|
||
| def test_local_construction_no_spark_job_for_crs_discovery(self): |
There was a problem hiding this comment.
It looks like these two tests are nested inside the top-level check_geodataframe helper, so pytest does not collect them.
This should show the issue:
pytest --collect-only -q python/tests/geopandas/test_geodataframe.py |
grep local_construction_noOnly the earlier named-geometry test is collected. Could we move both methods into TestGeoDataFrame, then use the same real job-count and query-plan assertions as the GeoSeries coverage?
| return GeoSeries(ps_series, index, crs=crs) | ||
| result = GeoSeries(ps_series, index, crs=crs) | ||
| if crs is None: | ||
| # ST_GeomFromWKB/WKT always produce fresh geometries with no |
There was a problem hiding this comment.
Could we soften this rationale? ST_GeomFromWKB can preserve an SRID carried by EWKB.
For example:
geom = shapely.set_srid(Point(0, 0), 4326)
ewkb = shapely.to_wkb(geom, include_srid=True)
s = sgpd.GeoSeries.from_wkb([ewkb])
assert s._internal.spark_frame.select(
stf.ST_SRID(s.spark.column)
).first()[0] == 4326The metadata-only stamping still seems right. Suggested wording: WKT and ordinary WKB are generally SRID-less, while EWKB may carry an embedded SRID; recording public crs=None must not rewrite it.
…state for locally constructed geometries, optimizing CRS access without triggering unnecessary Spark jobs.
|
@minhpham1810 I've taken over this PR and made some updates given its complexity. Everything looks good now. Thank you for your contribution! |
Did you read the Contributor Guide?
Is this PR related to a ticket?
[GH-XXX] my subject. Closes GeoPandas: preserve authoritative no-CRS metadata for local geometry columns #3271What changes were proposed in this PR?
Addresses issue #3271: "GeoPandas: preserve authoritative no-CRS metadata for local geometry columns"
The issue reports that locally constructed
GeoSeries/GeoDataFrameobjects withcrs=Nonehave no CRS metadata, making them indistinguishable from raw distributed geometry columns of unknown provenance. This causes.crsaccess to trigger expensive distributedST_SRIDaggregation jobs to discover the CRS is absent.Changes
geoseries.py:is_locally_ownedflag to distinguish locally-constructed objects (Python list, WKT/WKB, plain pandas/geopandas objects) from wrapped distributed structures_record_no_crs_metadata()helper method that stamps empty CRS metadata (empty string in metadata dict) using_query_geometry_column()withcrs_override=None__init__whencrs=Noneandis_locally_owned=True_create_from_select()forfrom_wkt()/from_wkb()paths (freshly built geometries with no embedded SRID)geodataframe.py:is_locally_ownedflag with the same logic asGeoSeries__init__that checks if geometry column exists, is locally owned, and has no CRS metadataset_geometry()array-like branch to constructGeoSeriesdirectly from local data (avoid pre-wrapping in barepspd.Series)read_crs_metadatahelperTests:
test_geoseries.py: Added 5 new tests covering local construction paths, raw column preservation, embedded SRID preservation, and no Spark/Python plan for CRS discoverytest_geodataframe.py: Added 3 new tests covering named geometry column path and Spark/Python plan verificationHow was this patch tested?
ast.parsesyntax validationThe tests are structured to run with full Sedona build (Maven) once Spark/geopandas environment is available.
Did this PR include necessary documentation updates?
The changes are internal implementation details that preserve existing public behavior while fixing the underlying performance issue. The public
.crsproperty semantics remain unchanged: locally constructed objects now correctly reportcrs=Nonewithout triggering distributed SRID lookups.