Skip to content

Commit

Permalink
Deal with compatibility with both geopandas v0.x and v1.x
Browse files Browse the repository at this point in the history
  • Loading branch information
seisman committed May 14, 2024
1 parent ba9433c commit 2fb635b
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions pygmt/helpers/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from tempfile import NamedTemporaryFile

import numpy as np
from packaging.version import Version


def unique_name():
Expand Down Expand Up @@ -140,23 +141,33 @@ def tempfile_from_geojson(geojson):
# 32-bit integer overflow issue. Related issues:
# https://github.com/geopandas/geopandas/issues/967#issuecomment-842877704
# https://github.com/GenericMappingTools/pygmt/issues/2497
if geojson.index.name is None:
geojson.index.name = "index"
geojson = geojson.reset_index(drop=False)
schema = gpd.io.file.infer_schema(geojson)
for col, dtype in schema["properties"].items():
if dtype in ("int", "int64"):
overflow = geojson[col].abs().max() > 2**31 - 1
schema["properties"][col] = "float" if overflow else "int32"
ogrgmt_kwargs["schema"] = schema
if Version(gpd.__version__).major < 1: # GeoPandas v0.x
# The default engine 'fiona' supports the 'schema' parameter.
if geojson.index.name is None:
geojson.index.name = "index"
geojson = geojson.reset_index(drop=False)
schema = gpd.io.file.infer_schema(geojson)
for col, dtype in schema["properties"].items():
if dtype in ("int", "int64"):
overflow = geojson[col].abs().max() > 2**31 - 1
schema["properties"][col] = "float" if overflow else "int32"
ogrgmt_kwargs["schema"] = schema
else: # GeoPandas v1.x.
# The default engine "pyogrio" doesn't support the 'schema' parameter
# but we can change the dtype directly.
for col in geojson.columns:
if geojson[col].dtype in ("int", "int64", "Int64"):
overflow = geojson[col].abs().max() > 2**31 - 1
dtype = "float" if overflow else "int32"
geojson[col] = geojson[col].astype(dtype)

Check warning on line 162 in pygmt/helpers/tempfile.py

View check run for this annotation

Codecov / codecov/patch

pygmt/helpers/tempfile.py#L158-L162

Added lines #L158 - L162 were not covered by tests
# Using geopandas.to_file to directly export to OGR_GMT format
geojson.to_file(**ogrgmt_kwargs)
except AttributeError:
# Other 'geo' formats which implement __geo_interface__
import json

jsontext = json.dumps(geojson.__geo_interface__)
gpd.read_file(io.StringIO(jsontext)).to_file(**ogrgmt_kwargs)
gpd.read_file(filename=io.StringIO(jsontext)).to_file(**ogrgmt_kwargs)

yield tmpfile.name

Expand Down

0 comments on commit 2fb635b

Please sign in to comment.