Mahmudm commited on
Commit
94b76f8
·
verified ·
1 Parent(s): 571406a

Update ash_animator/basemaps.py

Browse files
Files changed (1) hide show
  1. ash_animator/basemaps.py +13 -56
ash_animator/basemaps.py CHANGED
@@ -1,36 +1,5 @@
1
- import tempfile
2
-
3
- # import contextily as ctx
4
- # from mpl_toolkits.basemap import Basemap
5
- # import cartopy.crs as ccrs
6
- # import cartopy.feature as cfeature
7
-
8
- # def draw_etopo_basemap(ax, mode="basemap", zoom=7):
9
- # try:
10
- # if mode == "stock":
11
- # ax.stock_img()
12
- # elif mode == "contextily":
13
- # extent = ax.get_extent(ccrs.PlateCarree())
14
- # ax.set_extent(extent, crs=ccrs.PlateCarree())
15
- # ctx.add_basemap(ax, crs=ccrs.PlateCarree(), source=ctx.providers.CartoDB.Voyager, zoom=zoom)
16
- # elif mode == "basemap":
17
- # extent = ax.get_extent(ccrs.PlateCarree())
18
- # m = Basemap(projection='cyl',
19
- # llcrnrlon=extent[0], urcrnrlon=extent[1],
20
- # llcrnrlat=extent[2], urcrnrlat=extent[3],
21
- # resolution='h', ax=ax)
22
- # m.shadedrelief()
23
- # m.drawcoastlines(linewidth=0.5)
24
- # m.drawcountries(linewidth=0.7)
25
- # m.drawmapboundary()
26
- # else:
27
- # raise ValueError(f"Unsupported basemap mode: {mode}")
28
- # except Exception as e:
29
- # print(f"[Relief Error - {mode} mode]:", e)
30
- # ax.add_feature(cfeature.LAND)
31
- # ax.add_feature(cfeature.OCEAN)
32
-
33
  import os
 
34
  import hashlib
35
  import contextily as ctx
36
  from mpl_toolkits.basemap import Basemap
@@ -39,15 +8,17 @@ import cartopy.feature as cfeature
39
  from PIL import Image
40
  import matplotlib.pyplot as plt
41
 
42
- # Define cache directories
43
- # Optional: Set tile cache directory (must be done before contextily downloads tiles)
44
- os.environ["XDG_CACHE_HOME"] = os.path.expanduser("~/.contextily_cache")
45
-
46
- CTX_TILE_CACHE_DIR = os.path.expanduser("~/.contextily_cache")
47
- os.path.join(tempfile.gettempdir(), 'contextily_cache') = os.path.expanduser("~/.basemap_cache")
48
 
 
49
  os.makedirs(CTX_TILE_CACHE_DIR, exist_ok=True)
50
- os.makedirs(os.path.join(tempfile.gettempdir(), 'contextily_cache'), exist_ok=True)
 
 
 
 
51
 
52
  def draw_etopo_basemap(ax, mode="basemap", zoom=11):
53
  """
@@ -67,12 +38,6 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
67
 
68
  zoom : int, optional
69
  Tile zoom level (only for "contextily"). Higher = more detail. Default is 7.
70
-
71
- Notes
72
- -----
73
- - Uses high resolution for Basemap (resolution='h') and saves figure at 300 DPI.
74
- - Cached images are reused using extent-based hashing to avoid re-rendering.
75
- - Basemap is deprecated; Cartopy with web tiles is recommended for new projects.
76
  """
77
  try:
78
  if mode == "stock":
@@ -85,22 +50,19 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
85
  ax,
86
  crs=ccrs.PlateCarree(),
87
  source=ctx.providers.CartoDB.Voyager,
88
- zoom=zoom
89
  )
90
 
91
  elif mode == "basemap":
92
  extent = ax.get_extent(crs=ccrs.PlateCarree())
93
-
94
- # Create a hash key for this extent
95
  extent_str = f"{extent[0]:.4f}_{extent[1]:.4f}_{extent[2]:.4f}_{extent[3]:.4f}"
96
  cache_key = hashlib.md5(extent_str.encode()).hexdigest()
97
- cache_file = os.path.join(os.path.join(tempfile.gettempdir(), 'contextily_cache'), f"{cache_key}_highres.png")
98
 
99
  if os.path.exists(cache_file):
100
  img = Image.open(cache_file)
101
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
102
  else:
103
- # Create a high-resolution temporary figure
104
  temp_fig, temp_ax = plt.subplots(figsize=(12, 9),
105
  subplot_kw={'projection': ccrs.PlateCarree()})
106
  temp_ax.set_extent(extent, crs=ccrs.PlateCarree())
@@ -108,18 +70,13 @@ def draw_etopo_basemap(ax, mode="basemap", zoom=11):
108
  m = Basemap(projection='cyl',
109
  llcrnrlon=extent[0], urcrnrlon=extent[1],
110
  llcrnrlat=extent[2], urcrnrlat=extent[3],
111
- resolution='f', ax=temp_ax) # 'h' = high resolution
112
 
113
  m.shadedrelief()
114
- # m.drawcoastlines(linewidth=0.1)
115
- # m.drawcountries(linewidth=0.1)
116
- # m.drawmapboundary()
117
 
118
- # Save high-DPI figure for clarity
119
  temp_fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
120
  plt.close(temp_fig)
121
 
122
- # Load and display the cached image
123
  img = Image.open(cache_file)
124
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import tempfile
3
  import hashlib
4
  import contextily as ctx
5
  from mpl_toolkits.basemap import Basemap
 
8
  from PIL import Image
9
  import matplotlib.pyplot as plt
10
 
11
+ # Use writable temporary directory for tile caching
12
+ CTX_TILE_CACHE_DIR = os.path.join(tempfile.gettempdir(), "contextily_cache")
13
+ BASEMAP_TILE_CACHE_DIR = os.path.join(tempfile.gettempdir(), "contextily_cache")
 
 
 
14
 
15
+ # Ensure directories exist
16
  os.makedirs(CTX_TILE_CACHE_DIR, exist_ok=True)
17
+ os.makedirs(BASEMAP_TILE_CACHE_DIR, exist_ok=True)
18
+
19
+ # Optionally set environment variable for contextily
20
+ os.environ["XDG_CACHE_HOME"] = CTX_TILE_CACHE_DIR
21
+
22
 
23
  def draw_etopo_basemap(ax, mode="basemap", zoom=11):
24
  """
 
38
 
39
  zoom : int, optional
40
  Tile zoom level (only for "contextily"). Higher = more detail. Default is 7.
 
 
 
 
 
 
41
  """
42
  try:
43
  if mode == "stock":
 
50
  ax,
51
  crs=ccrs.PlateCarree(),
52
  source=ctx.providers.CartoDB.Voyager,
53
+ zoom=zoom
54
  )
55
 
56
  elif mode == "basemap":
57
  extent = ax.get_extent(crs=ccrs.PlateCarree())
 
 
58
  extent_str = f"{extent[0]:.4f}_{extent[1]:.4f}_{extent[2]:.4f}_{extent[3]:.4f}"
59
  cache_key = hashlib.md5(extent_str.encode()).hexdigest()
60
+ cache_file = os.path.join(BASEMAP_TILE_CACHE_DIR, f"{cache_key}_highres.png")
61
 
62
  if os.path.exists(cache_file):
63
  img = Image.open(cache_file)
64
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
65
  else:
 
66
  temp_fig, temp_ax = plt.subplots(figsize=(12, 9),
67
  subplot_kw={'projection': ccrs.PlateCarree()})
68
  temp_ax.set_extent(extent, crs=ccrs.PlateCarree())
 
70
  m = Basemap(projection='cyl',
71
  llcrnrlon=extent[0], urcrnrlon=extent[1],
72
  llcrnrlat=extent[2], urcrnrlat=extent[3],
73
+ resolution='f', ax=temp_ax)
74
 
75
  m.shadedrelief()
 
 
 
76
 
 
77
  temp_fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
78
  plt.close(temp_fig)
79
 
 
80
  img = Image.open(cache_file)
81
  ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
82