Skip to content

Commit

Permalink
Merge branch 'fmaussion:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
benatouba authored Jul 9, 2024
2 parents fabbed7 + 6c1ac55 commit 1873ab9
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 30 deletions.
1 change: 1 addition & 0 deletions .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ jobs:
env:
MPLBACKEND: agg
COVERAGE_RCFILE: ${{ github.workspace }}/.coveragerc
STATIC_MAP_API_KEY: ${{ secrets.STATIC_MAP_API_KEY }}
- name: Upload Coverage
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ savefig
.eggs
dist/
sg_execution_times.rst
.env

# PyCharm stuffs
.idea/
Expand Down
1 change: 1 addition & 0 deletions docs/examples/plot_googlestatic.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
shp = salem.read_shapefile(get_demo_file('rgi_kesselwand.shp'))
# I you need to do a lot of maps you might want
# to use an API key and set it here with key='YOUR_API_KEY'
# or set it in your environment as STATIC_MAP_API_KEY
g = GoogleVisibleMap(x=[shp.min_x, shp.max_x], y=[shp.min_y, shp.max_y],
scale=2, # scale is for more details
maptype='satellite') # try out also: 'terrain'
Expand Down
2 changes: 1 addition & 1 deletion salem/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def _lazy_property(self):
if not path.exists(download_dir):
makedirs(download_dir)

sample_data_gh_commit = '57e6d694aa470b967336f5ca2d4fc743c5c8efd6'
sample_data_gh_commit = '454bf696324000d198f574a1bf5bc56e3e489051'
sample_data_dir = path.join(cache_dir, 'salem-sample-data-' +
sample_data_gh_commit)

Expand Down
54 changes: 33 additions & 21 deletions salem/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@
from salem import wgs84
from salem import utils, gis, wrftools, sio, check_crs

API_KEY = None


class GeoDataset(object):
"""Interface for georeferenced datasets.
Expand Down Expand Up @@ -482,11 +480,14 @@ class GoogleCenterMap(GeoDataset):
"""Google static map centered on a point.
Needs motionless.
See https://developers.google.com/maps/documentation/maps-static/usage-and-billing
for pricing.
"""

def __init__(self, center_ll=(11.38, 47.26), size_x=640, size_y=640,
scale=1, zoom=12, maptype='satellite', use_cache=True,
**kwargs):
key=None, **kwargs):
"""Initialize
Parameters
Expand All @@ -507,28 +508,32 @@ def __init__(self, center_ll=(11.38, 47.26), size_x=640, size_y=640,
'roadmap', 'satellite', 'hybrid', 'terrain'
use_cache : bool, default: True
store the downloaded image in the cache to avoid future downloads
key : str, default: None
Google API key. If None, it will try to read it from
the environment variable STATIC_MAP_API_KEY
kwargs : **
any keyword accepted by motionless.CenterMap (e.g. `key` for the API)
any keyword accepted by motionless.CenterMap
"""

global API_KEY

# Google grid
grid = gis.googlestatic_mercator_grid(center_ll=center_ll,
nx=size_x, ny=size_y,
zoom=zoom, scale=scale)

if 'key' not in kwargs:
if API_KEY is None:
with open(utils.get_demo_file('.api_key'), 'r') as f:
API_KEY = f.read().replace('\n', '')
kwargs['key'] = API_KEY
if key is None:
try:
key = os.environ['STATIC_MAP_API_KEY']
except KeyError:
raise ValueError('You need to provide a Google API key'
' or set the STATIC_MAP_API_KEY environment'
' variable.')

# Motionless
import motionless
googleurl = motionless.CenterMap(lon=center_ll[0], lat=center_ll[1],
size_x=size_x, size_y=size_y,
maptype=maptype, zoom=zoom, scale=scale,
maptype=maptype, zoom=zoom,
scale=scale, key=key,
**kwargs)

# done
Expand Down Expand Up @@ -556,10 +561,13 @@ class GoogleVisibleMap(GoogleCenterMap):
"""Google static map automatically sized and zoomed to a selected region.
It's usually more practical to use than GoogleCenterMap.
See https://developers.google.com/maps/documentation/maps-static/usage-and-billing
for pricing.
"""

def __init__(self, x, y, crs=wgs84, size_x=640, size_y=640, scale=1,
maptype='satellite', use_cache=True, **kwargs):
maptype='satellite', use_cache=True, key=None, **kwargs):
"""Initialize
Parameters
Expand All @@ -581,6 +589,9 @@ def __init__(self, x, y, crs=wgs84, size_x=640, size_y=640, scale=1,
'roadmap', 'satellite', 'hybrid', 'terrain'
use_cache : bool, default: True
store the downloaded image in the cache to avoid future downloads
key : str, default: None
Google API key. If None, it will try to read it from
the environment variable STATIC_MAP_API_KEY
kwargs : **
any keyword accepted by motionless.CenterMap (e.g. `key` for the API)
Expand All @@ -590,7 +601,13 @@ def __init__(self, x, y, crs=wgs84, size_x=640, size_y=640, scale=1,
play with the `size_x` and `size_y` kwargs.
"""

global API_KEY
if key is None:
try:
key = os.environ['STATIC_MAP_API_KEY']
except KeyError:
raise ValueError('You need to provide a Google API key'
' or set the STATIC_MAP_API_KEY environment'
' variable.')

if 'zoom' in kwargs or 'center_ll' in kwargs:
raise ValueError('incompatible kwargs.')
Expand All @@ -617,12 +634,7 @@ def __init__(self, x, y, crs=wgs84, size_x=640, size_y=640, scale=1,
else:
break

if 'key' not in kwargs:
if API_KEY is None:
with open(utils.get_demo_file('.api_key'), 'r') as f:
API_KEY = f.read().replace('\n', '')
kwargs['key'] = API_KEY

GoogleCenterMap.__init__(self, center_ll=mc, size_x=size_x,
size_y=size_y, zoom=zoom, scale=scale,
maptype=maptype, use_cache=use_cache, **kwargs)
maptype=maptype, use_cache=use_cache,
key=key, **kwargs)
13 changes: 8 additions & 5 deletions salem/gis.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

try:
from osgeo import osr
osr.UseExceptions()
has_gdal = True
except ImportError:
has_gdal = False
Expand Down Expand Up @@ -1259,7 +1260,6 @@ def proj_is_same(p1, p2):
"""
if has_gdal:
# this is more robust, but gdal is a pain
osr.UseExceptions()
s1 = osr.SpatialReference()
s1.ImportFromProj4(p1.srs)
s2 = osr.SpatialReference()
Expand All @@ -1275,7 +1275,11 @@ def proj_is_same(p1, p2):
def _transform_internal(p1, p2, x, y, **kwargs):
if hasattr(pyproj, 'Transformer'):
trf = pyproj.Transformer.from_proj(p1, p2, **kwargs)
return trf.transform(x, y)
with warnings.catch_warnings():
# https://github.com/pyproj4/pyproj/issues/1415
warnings.filterwarnings("ignore", category=DeprecationWarning,
message=".*ndim > 0 to a scalar.*")
return trf.transform(x, y)
else:
return pyproj.transform(p1, p2, x, y, **kwargs)

Expand Down Expand Up @@ -1397,9 +1401,9 @@ def transform_geopandas(gdf, from_crs=None, to_crs=wgs84, inplace=False):
to_crs = to_crs.srs
elif isinstance(to_crs, Grid):
to_crs = None
result.crs = to_crs
result.set_crs(to_crs, allow_override=True, inplace=True)
out.geometry = result
out.crs = to_crs
out.set_crs(to_crs, allow_override=True, inplace=True)
out['min_x'] = [g.bounds[0] for g in out.geometry]
out['max_x'] = [g.bounds[2] for g in out.geometry]
out['min_y'] = [g.bounds[1] for g in out.geometry]
Expand Down Expand Up @@ -1441,7 +1445,6 @@ def proj_to_cartopy(proj):
srs = proj.srs
if has_gdal:
# this is more robust, as srs could be anything (espg, etc.)
from osgeo import osr
s1 = osr.SpatialReference()
s1.ImportFromProj4(proj.srs)
if s1.ExportToProj4():
Expand Down
5 changes: 2 additions & 3 deletions salem/tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ def create_dummy_shp(fname):
i_line = shpg.LinearRing([(1.4, 1.4), (1.6, 1.4), (1.6, 1.6), (1.4, 1.6)])
p1 = shpg.Polygon(e_line, [i_line])
p2 = shpg.Polygon([(2.5, 1.3), (3., 1.8), (2.5, 2.3), (2, 1.8)])
df = gpd.GeoDataFrame()
df = gpd.GeoDataFrame(crs='EPSG:4326', geometry=gpd.GeoSeries([p1, p2]))
df['name'] = ['Polygon', 'Line']
df.set_geometry(gpd.GeoSeries([p1, p2]), inplace=True)
of = os.path.join(testdir, fname)
df.to_file(of)
return of
Expand Down Expand Up @@ -843,7 +842,7 @@ def test_mf_datasets(self):
dsm.to_netcdf(fo)
dsm.close()
dsm = sio.open_wrf_dataset(fo)
assert_allclose(ds['PRCP'], dsm['PRCP'])
assert_allclose(ds['PRCP'], dsm['PRCP'], rtol=1e-6)
assert_allclose(prcp_nc, dsm['PRCP_NC'].isel(time=slice(1, 4)),
rtol=1e-6)

Expand Down

0 comments on commit 1873ab9

Please sign in to comment.