Mahmudm commited on
Commit
c71d790
·
verified ·
1 Parent(s): c4d34aa

Update ash_animator/basemaps.py

Browse files
Files changed (1) hide show
  1. ash_animator/basemaps.py +29 -31
ash_animator/basemaps.py CHANGED
@@ -1,40 +1,23 @@
 
1
  import os
2
  import hashlib
3
- import tempfile
4
  import contextily as ctx
5
  from mpl_toolkits.basemap import Basemap
6
-
7
-
8
- import os
9
- import tempfile
10
-
11
- def get_cache_dir(app_name):
12
- return os.path.join(tempfile.gettempdir(), f"{app_name}_cache")
13
-
14
-
15
- # Define and create cache directories
16
- CTX_TILE_CACHE_DIR = get_cache_dir("contextily")
17
- BASEMAP_TILE_CACHE_DIR = get_cache_dir("basemap")
18
- CARTOPY_CACHE_DIR = get_cache_dir("cartopy")
19
-
20
- os.environ["XDG_CACHE_HOME"] = CTX_TILE_CACHE_DIR
21
- os.environ["CARTOPY_USER_BACKGROUNDS"] = CARTOPY_CACHE_DIR
22
- os.environ["CARTOPY_CACHE_DIR"] = CARTOPY_CACHE_DIR
23
-
24
- if not os.path.exists(CTX_TILE_CACHE_DIR):
25
- os.makedirs(CTX_TILE_CACHE_DIR, exist_ok=True)
26
- if not os.path.exists(BASEMAP_TILE_CACHE_DIR):
27
- os.makedirs(BASEMAP_TILE_CACHE_DIR, exist_ok=True)
28
- if not os.path.exists(CARTOPY_CACHE_DIR):
29
- os.makedirs(CARTOPY_CACHE_DIR, exist_ok=True)
30
-
31
-
32
  import cartopy.crs as ccrs
33
  import cartopy.feature as cfeature
34
- import cartopy.io.shapereader as shpreader
35
  from PIL import Image
36
  import matplotlib.pyplot as plt
37
 
 
 
 
 
 
 
 
 
 
 
38
  def draw_etopo_basemap(ax, mode="basemap", zoom=11):
39
  """
40
  Draws a high-resolution basemap background on the provided Cartopy GeoAxes.
@@ -52,7 +35,13 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
52
  Default is "basemap".
53
 
54
  zoom : int, optional
55
- Tile zoom level (only for "contextily"). Higher = more detail. Default is 11.
 
 
 
 
 
 
56
  """
57
  try:
58
  if mode == "stock":
@@ -65,11 +54,13 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
65
  ax,
66
  crs=ccrs.PlateCarree(),
67
  source=ctx.providers.CartoDB.Voyager,
68
- zoom=zoom
69
  )
70
 
71
  elif mode == "basemap":
72
  extent = ax.get_extent(crs=ccrs.PlateCarree())
 
 
73
  extent_str = f"{extent[0]:.4f}_{extent[1]:.4f}_{extent[2]:.4f}_{extent[3]:.4f}"
74
  cache_key = hashlib.md5(extent_str.encode()).hexdigest()
75
  cache_file = os.path.join(BASEMAP_TILE_CACHE_DIR, f"{cache_key}_highres.png")
@@ -78,6 +69,7 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
78
  img = Image.open(cache_file)
79
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
80
  else:
 
81
  temp_fig, temp_ax = plt.subplots(figsize=(12, 9),
82
  subplot_kw={'projection': ccrs.PlateCarree()})
83
  temp_ax.set_extent(extent, crs=ccrs.PlateCarree())
@@ -85,12 +77,18 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
85
  m = Basemap(projection='cyl',
86
  llcrnrlon=extent[0], urcrnrlon=extent[1],
87
  llcrnrlat=extent[2], urcrnrlat=extent[3],
88
- resolution='f', ax=temp_ax)
 
89
  m.shadedrelief()
 
 
 
90
 
 
91
  temp_fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
92
  plt.close(temp_fig)
93
 
 
94
  img = Image.open(cache_file)
95
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
96
 
 
1
+
2
  import os
3
  import hashlib
 
4
  import contextily as ctx
5
  from mpl_toolkits.basemap import Basemap
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  import cartopy.crs as ccrs
7
  import cartopy.feature as cfeature
 
8
  from PIL import Image
9
  import matplotlib.pyplot as plt
10
 
11
+ # Define cache directories
12
+ # Optional: Set tile cache directory (must be done before contextily downloads tiles)
13
+ os.environ["XDG_CACHE_HOME"] = os.path.expanduser("~/.contextily_cache")
14
+
15
+ CTX_TILE_CACHE_DIR = os.path.expanduser("~/.contextily_cache")
16
+ BASEMAP_TILE_CACHE_DIR = os.path.expanduser("~/.basemap_cache")
17
+
18
+ os.makedirs(CTX_TILE_CACHE_DIR, exist_ok=True)
19
+ os.makedirs(BASEMAP_TILE_CACHE_DIR, exist_ok=True)
20
+
21
  def draw_etopo_basemap(ax, mode="basemap", zoom=11):
22
  """
23
  Draws a high-resolution basemap background on the provided Cartopy GeoAxes.
 
35
  Default is "basemap".
36
 
37
  zoom : int, optional
38
+ Tile zoom level (only for "contextily"). Higher = more detail. Default is 7.
39
+
40
+ Notes
41
+ -----
42
+ - Uses high resolution for Basemap (resolution='h') and saves figure at 300 DPI.
43
+ - Cached images are reused using extent-based hashing to avoid re-rendering.
44
+ - Basemap is deprecated; Cartopy with web tiles is recommended for new projects.
45
  """
46
  try:
47
  if mode == "stock":
 
54
  ax,
55
  crs=ccrs.PlateCarree(),
56
  source=ctx.providers.CartoDB.Voyager,
57
+ zoom=zoom
58
  )
59
 
60
  elif mode == "basemap":
61
  extent = ax.get_extent(crs=ccrs.PlateCarree())
62
+
63
+ # Create a hash key for this extent
64
  extent_str = f"{extent[0]:.4f}_{extent[1]:.4f}_{extent[2]:.4f}_{extent[3]:.4f}"
65
  cache_key = hashlib.md5(extent_str.encode()).hexdigest()
66
  cache_file = os.path.join(BASEMAP_TILE_CACHE_DIR, f"{cache_key}_highres.png")
 
69
  img = Image.open(cache_file)
70
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
71
  else:
72
+ # Create a high-resolution temporary figure
73
  temp_fig, temp_ax = plt.subplots(figsize=(12, 9),
74
  subplot_kw={'projection': ccrs.PlateCarree()})
75
  temp_ax.set_extent(extent, crs=ccrs.PlateCarree())
 
77
  m = Basemap(projection='cyl',
78
  llcrnrlon=extent[0], urcrnrlon=extent[1],
79
  llcrnrlat=extent[2], urcrnrlat=extent[3],
80
+ resolution='f', ax=temp_ax) # 'h' = high resolution
81
+
82
  m.shadedrelief()
83
+ # m.drawcoastlines(linewidth=0.1)
84
+ # m.drawcountries(linewidth=0.1)
85
+ # m.drawmapboundary()
86
 
87
+ # Save high-DPI figure for clarity
88
  temp_fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
89
  plt.close(temp_fig)
90
 
91
+ # Load and display the cached image
92
  img = Image.open(cache_file)
93
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
94