Spaces:
Configuration error
Configuration error
Upload 183 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +25 -0
- ash_animator/__init__.py +12 -0
- ash_animator/__pycache__/__init__.cpython-312.pyc +0 -0
- ash_animator/__pycache__/animation_all.cpython-312.pyc +0 -0
- ash_animator/__pycache__/animation_single.cpython-312.pyc +0 -0
- ash_animator/__pycache__/animation_vertical.cpython-312.pyc +0 -0
- ash_animator/__pycache__/basemaps.cpython-312.pyc +0 -0
- ash_animator/__pycache__/converter.cpython-312.pyc +0 -0
- ash_animator/__pycache__/export.cpython-312.pyc +0 -0
- ash_animator/__pycache__/interpolation.cpython-312.pyc +0 -0
- ash_animator/__pycache__/plot_3dfield_data.cpython-312.pyc +0 -0
- ash_animator/__pycache__/plot_horizontal_data.cpython-312.pyc +0 -0
- ash_animator/__pycache__/utils.cpython-312.pyc +0 -0
- ash_animator/animation_all.py +516 -0
- ash_animator/animation_single.py +147 -0
- ash_animator/animation_vertical.py +360 -0
- ash_animator/basemaps.py +131 -0
- ash_animator/converter.py +414 -0
- ash_animator/export.py +119 -0
- ash_animator/interpolation.py +14 -0
- ash_animator/plot_3dfield_data.py +465 -0
- ash_animator/plot_horizontal_data.py +564 -0
- ash_animator/utils.py +23 -0
- ash_output/3D/T1.nc +3 -0
- ash_output/3D/T10.nc +3 -0
- ash_output/3D/T2.nc +3 -0
- ash_output/3D/T3.nc +3 -0
- ash_output/3D/T4.nc +3 -0
- ash_output/3D/T5.nc +3 -0
- ash_output/3D/T6.nc +3 -0
- ash_output/3D/T7.nc +3 -0
- ash_output/3D/T8.nc +3 -0
- ash_output/3D/T9.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T10_202001121400.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T1_202001120500.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T2_202001120600.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T3_202001120700.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T4_202001120800.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T5_202001120900.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T6_202001121000.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T7_202001121100.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T8_202001121200.nc +3 -0
- ash_output/horizontal/AQOutput_HorizontalField_C1_T9_202001121300.nc +3 -0
- media/2D/2d_fields/air_concentration/air_concentration.gif +3 -0
- media/2D/frames/air_concentration/frame_0001.jpg +3 -0
- media/2D/frames/air_concentration/frame_0008.jpg +3 -0
- media/2D/frames/air_concentration/frame_0009.jpg +3 -0
- media/2D/frames/air_concentration/frame_0010.jpg +3 -0
- media/Taal_273070_20200112_scenario_yizhou.zip +3 -0
- media/default_model.zip +3 -0
.gitattributes
CHANGED
|
@@ -32,3 +32,28 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
ash_output/3D/T1.nc filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
ash_output/3D/T10.nc filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
ash_output/3D/T2.nc filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
ash_output/3D/T3.nc filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
ash_output/3D/T4.nc filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
ash_output/3D/T5.nc filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
ash_output/3D/T6.nc filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
ash_output/3D/T7.nc filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
ash_output/3D/T8.nc filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
ash_output/3D/T9.nc filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T1_202001120500.nc filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T10_202001121400.nc filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T2_202001120600.nc filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T3_202001120700.nc filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T4_202001120800.nc filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T5_202001120900.nc filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T6_202001121000.nc filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T7_202001121100.nc filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T8_202001121200.nc filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
ash_output/horizontal/AQOutput_HorizontalField_C1_T9_202001121300.nc filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
media/2D/2d_fields/air_concentration/air_concentration.gif filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
media/2D/frames/air_concentration/frame_0001.jpg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
media/2D/frames/air_concentration/frame_0008.jpg filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
media/2D/frames/air_concentration/frame_0009.jpg filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
media/2D/frames/air_concentration/frame_0010.jpg filter=lfs diff=lfs merge=lfs -text
|
ash_animator/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Auto-generated __init__.py to import all modules
|
| 3 |
+
from .basemaps import *
|
| 4 |
+
from .converter import *
|
| 5 |
+
from .interpolation import *
|
| 6 |
+
from .plot_3dfield_data import *
|
| 7 |
+
from .plot_horizontal_data import *
|
| 8 |
+
from .utils import *
|
| 9 |
+
from .animation_all import *
|
| 10 |
+
from .animation_single import *
|
| 11 |
+
from .animation_vertical import *
|
| 12 |
+
from .export import *
|
ash_animator/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (522 Bytes). View file
|
|
|
ash_animator/__pycache__/animation_all.cpython-312.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
ash_animator/__pycache__/animation_single.cpython-312.pyc
ADDED
|
Binary file (11.5 kB). View file
|
|
|
ash_animator/__pycache__/animation_vertical.cpython-312.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
ash_animator/__pycache__/basemaps.cpython-312.pyc
ADDED
|
Binary file (5.01 kB). View file
|
|
|
ash_animator/__pycache__/converter.cpython-312.pyc
ADDED
|
Binary file (14.2 kB). View file
|
|
|
ash_animator/__pycache__/export.cpython-312.pyc
ADDED
|
Binary file (9.3 kB). View file
|
|
|
ash_animator/__pycache__/interpolation.cpython-312.pyc
ADDED
|
Binary file (1.03 kB). View file
|
|
|
ash_animator/__pycache__/plot_3dfield_data.cpython-312.pyc
ADDED
|
Binary file (33.5 kB). View file
|
|
|
ash_animator/__pycache__/plot_horizontal_data.cpython-312.pyc
ADDED
|
Binary file (30.8 kB). View file
|
|
|
ash_animator/__pycache__/utils.cpython-312.pyc
ADDED
|
Binary file (1.61 kB). View file
|
|
|
ash_animator/animation_all.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# import os
|
| 3 |
+
# import numpy as np
|
| 4 |
+
# import matplotlib.pyplot as plt
|
| 5 |
+
# import matplotlib.animation as animation
|
| 6 |
+
# import matplotlib.ticker as mticker
|
| 7 |
+
# import cartopy.crs as ccrs
|
| 8 |
+
# import cartopy.feature as cfeature
|
| 9 |
+
# from adjustText import adjust_text
|
| 10 |
+
# import cartopy.io.shapereader as shpreader
|
| 11 |
+
# from .interpolation import interpolate_grid
|
| 12 |
+
# from .basemaps import draw_etopo_basemap
|
| 13 |
+
|
| 14 |
+
# def animate_all_z_levels(animator, output_folder: str, fps: int = 2, threshold: float = 0.1):
|
| 15 |
+
# os.makedirs(output_folder, exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 18 |
+
# reader = shpreader.Reader(countries_shp)
|
| 19 |
+
# country_geoms = list(reader.records())
|
| 20 |
+
|
| 21 |
+
# for z_index, z_val in enumerate(animator.levels):
|
| 22 |
+
# fig = plt.figure(figsize=(16, 7))
|
| 23 |
+
# proj = ccrs.PlateCarree()
|
| 24 |
+
# ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 25 |
+
# ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 26 |
+
|
| 27 |
+
# valid_mask = np.stack([
|
| 28 |
+
# ds['ash_concentration'].values[z_index] for ds in animator.datasets
|
| 29 |
+
# ]).max(axis=0) > 0
|
| 30 |
+
# y_idx, x_idx = np.where(valid_mask)
|
| 31 |
+
|
| 32 |
+
# if y_idx.size == 0 or x_idx.size == 0:
|
| 33 |
+
# print(f"Z level {z_val} km has no valid data. Skipping...")
|
| 34 |
+
# plt.close()
|
| 35 |
+
# continue
|
| 36 |
+
|
| 37 |
+
# y_min, y_max = y_idx.min(), y_idx.max()
|
| 38 |
+
# x_min, x_max = x_idx.min(), x_idx.max()
|
| 39 |
+
|
| 40 |
+
# buffer_y = int((y_max - y_min) * 0.5)
|
| 41 |
+
# buffer_x = int((x_max - x_min) * 0.5)
|
| 42 |
+
|
| 43 |
+
# y_start = max(0, y_min - buffer_y)
|
| 44 |
+
# y_end = min(animator.lat_grid.shape[0], y_max + buffer_y + 1)
|
| 45 |
+
# x_start = max(0, x_min - buffer_x)
|
| 46 |
+
# x_end = min(animator.lon_grid.shape[1], x_max + buffer_x + 1)
|
| 47 |
+
|
| 48 |
+
# lat_zoom = animator.lats[y_start:y_end]
|
| 49 |
+
# lon_zoom = animator.lons[x_start:x_end]
|
| 50 |
+
# lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 51 |
+
|
| 52 |
+
# valid_frames = []
|
| 53 |
+
# for t in range(len(animator.datasets)):
|
| 54 |
+
# data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 55 |
+
# interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 56 |
+
# interp = np.where(interp < 0, np.nan, interp)
|
| 57 |
+
# if np.isfinite(interp).sum() > 0:
|
| 58 |
+
# valid_frames.append(t)
|
| 59 |
+
|
| 60 |
+
# if not valid_frames:
|
| 61 |
+
# print(f"No valid frames for Z={z_val} km. Skipping animation.")
|
| 62 |
+
# plt.close()
|
| 63 |
+
# continue
|
| 64 |
+
|
| 65 |
+
# def update(t):
|
| 66 |
+
# ax1.clear()
|
| 67 |
+
# ax2.clear()
|
| 68 |
+
|
| 69 |
+
# data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 70 |
+
# interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 71 |
+
# interp = np.where(interp < 0, np.nan, interp)
|
| 72 |
+
# zoom_plot = interp[y_start:y_end, x_start:x_end]
|
| 73 |
+
|
| 74 |
+
# valid_vals = interp[np.isfinite(interp)]
|
| 75 |
+
# if valid_vals.size == 0:
|
| 76 |
+
# return []
|
| 77 |
+
|
| 78 |
+
# min_val = np.nanmin(valid_vals)
|
| 79 |
+
# max_val = np.nanmax(valid_vals)
|
| 80 |
+
# log_cutoff = 1e-3
|
| 81 |
+
# log_ratio = max_val / (min_val + 1e-6)
|
| 82 |
+
# use_log = min_val > log_cutoff and log_ratio > 100
|
| 83 |
+
|
| 84 |
+
# if use_log:
|
| 85 |
+
# data_for_plot = np.where(interp > log_cutoff, interp, np.nan)
|
| 86 |
+
# levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20)
|
| 87 |
+
# scale_label = "Hybrid Log"
|
| 88 |
+
# else:
|
| 89 |
+
# data_for_plot = interp
|
| 90 |
+
# levels = np.linspace(0, max_val, 20)
|
| 91 |
+
# scale_label = "Linear"
|
| 92 |
+
|
| 93 |
+
# draw_etopo_basemap(ax1, mode='stock')
|
| 94 |
+
# draw_etopo_basemap(ax2, mode='stock')
|
| 95 |
+
|
| 96 |
+
# c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 97 |
+
# cmap="rainbow", alpha=0.6, transform=proj)
|
| 98 |
+
# ax1.contour(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 99 |
+
# colors='black', linewidths=0.5, transform=proj)
|
| 100 |
+
# ax1.set_title(f"T{t+1} | Alt: {z_val} km (Full - {scale_label})")
|
| 101 |
+
# ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 102 |
+
# ax1.coastlines()
|
| 103 |
+
# ax1.add_feature(cfeature.BORDERS, linestyle=':')
|
| 104 |
+
# ax1.add_feature(cfeature.LAND)
|
| 105 |
+
# ax1.add_feature(cfeature.OCEAN)
|
| 106 |
+
|
| 107 |
+
# c2 = ax2.contourf(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 108 |
+
# cmap="rainbow", alpha=0.4, transform=proj)
|
| 109 |
+
# ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 110 |
+
# colors='black', linewidths=0.5, transform=proj)
|
| 111 |
+
# ax2.set_title(f"T{t+1} | Alt: {z_val} km (Zoom - {scale_label})")
|
| 112 |
+
# ax2.set_extent([lon_zoom.min(), lon_zoom.max(), lat_zoom.min(), lat_zoom.max()])
|
| 113 |
+
# ax2.coastlines()
|
| 114 |
+
# ax2.add_feature(cfeature.BORDERS, linestyle=':')
|
| 115 |
+
# ax2.add_feature(cfeature.LAND)
|
| 116 |
+
# ax2.add_feature(cfeature.OCEAN)
|
| 117 |
+
|
| 118 |
+
# ax2.text(animator.lons[0], animator.lats[0], animator.country_label, fontsize=9, color='white',
|
| 119 |
+
# transform=proj, bbox=dict(facecolor='black', alpha=0.5))
|
| 120 |
+
|
| 121 |
+
# texts_ax1, texts_ax2 = [], []
|
| 122 |
+
# for country in country_geoms:
|
| 123 |
+
# name = country.attributes['NAME_LONG']
|
| 124 |
+
# geom = country.geometry
|
| 125 |
+
# try:
|
| 126 |
+
# lon, lat = geom.centroid.x, geom.centroid.y
|
| 127 |
+
# if (lon_zoom.min() <= lon <= lon_zoom.max()) and (lat_zoom.min() <= lat <= lat_zoom.max()):
|
| 128 |
+
# text = ax2.text(lon, lat, name, fontsize=6, transform=proj,
|
| 129 |
+
# ha='center', va='center', color='white',
|
| 130 |
+
# bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 131 |
+
# texts_ax2.append(text)
|
| 132 |
+
|
| 133 |
+
# if (animator.lons.min() <= lon <= animator.lons.max()) and (animator.lats.min() <= lat <= animator.lats.max()):
|
| 134 |
+
# text = ax1.text(lon, lat, name, fontsize=6, transform=proj,
|
| 135 |
+
# ha='center', va='center', color='white',
|
| 136 |
+
# bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 137 |
+
# texts_ax1.append(text)
|
| 138 |
+
# except:
|
| 139 |
+
# continue
|
| 140 |
+
|
| 141 |
+
# adjust_text(texts_ax1, ax=ax1, only_move={'points': 'y', 'text': 'y'},
|
| 142 |
+
# arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 143 |
+
# adjust_text(texts_ax2, ax=ax2, only_move={'points': 'y', 'text': 'y'},
|
| 144 |
+
# arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 145 |
+
|
| 146 |
+
# if np.nanmax(valid_vals) > threshold:
|
| 147 |
+
# alert_text = f"⚠ Exceeds {threshold} g/m³!"
|
| 148 |
+
# for ax in [ax1, ax2]:
|
| 149 |
+
# ax.text(0.99, 0.01, alert_text, transform=ax.transAxes,
|
| 150 |
+
# ha='right', va='bottom', fontsize=10, color='red',
|
| 151 |
+
# bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 152 |
+
# ax1.contour(animator.lons, animator.lats, interp, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 153 |
+
# ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 154 |
+
|
| 155 |
+
# if not hasattr(update, "colorbar"):
|
| 156 |
+
# update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 157 |
+
# label="Ash concentration (g/m³)")
|
| 158 |
+
# formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 159 |
+
# update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 160 |
+
# if use_log:
|
| 161 |
+
# update.colorbar.ax.text(1.05, 1.02, "log scale", transform=update.colorbar.ax.transAxes,
|
| 162 |
+
# fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 163 |
+
|
| 164 |
+
# return []
|
| 165 |
+
|
| 166 |
+
# ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False)
|
| 167 |
+
# gif_path = os.path.join(output_folder, f"ash_T1-Tn_Z{z_index+1}.gif")
|
| 168 |
+
# ani.save(gif_path, writer='pillow', fps=fps)
|
| 169 |
+
# plt.close()
|
| 170 |
+
# print(f"✅ Saved animation for Z={z_val} km to {gif_path}")
|
| 171 |
+
###################################################################################################################
|
| 172 |
+
# import os
|
| 173 |
+
# import numpy as np
|
| 174 |
+
# import matplotlib.pyplot as plt
|
| 175 |
+
# import matplotlib.animation as animation
|
| 176 |
+
# import matplotlib.ticker as mticker
|
| 177 |
+
# import cartopy.crs as ccrs
|
| 178 |
+
# import cartopy.feature as cfeature
|
| 179 |
+
# from adjustText import adjust_text
|
| 180 |
+
# import cartopy.io.shapereader as shpreader
|
| 181 |
+
# from .interpolation import interpolate_grid
|
| 182 |
+
# from .basemaps import draw_etopo_basemap
|
| 183 |
+
|
| 184 |
+
# def animate_all_z_levels(animator, output_folder: str, fps: int = 2, threshold: float = 0.1):
|
| 185 |
+
# os.makedirs(output_folder, exist_ok=True)
|
| 186 |
+
|
| 187 |
+
# countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 188 |
+
# reader = shpreader.Reader(countries_shp)
|
| 189 |
+
# country_geoms = list(reader.records())
|
| 190 |
+
|
| 191 |
+
# # Compute consistent zoom window across all z-levels and time frames
|
| 192 |
+
# valid_mask_all = np.zeros_like(animator.datasets[0]['ash_concentration'].values[0], dtype=bool)
|
| 193 |
+
# for ds in animator.datasets:
|
| 194 |
+
# for z in range(len(animator.levels)):
|
| 195 |
+
# valid_mask_all |= ds['ash_concentration'].values[z] > 0
|
| 196 |
+
|
| 197 |
+
# y_idx_all, x_idx_all = np.where(valid_mask_all)
|
| 198 |
+
# if y_idx_all.size == 0 or x_idx_all.size == 0:
|
| 199 |
+
# raise ValueError("No valid data found across any Z level or frame.")
|
| 200 |
+
|
| 201 |
+
# y_min, y_max = y_idx_all.min(), y_idx_all.max()
|
| 202 |
+
# x_min, x_max = x_idx_all.min(), x_idx_all.max()
|
| 203 |
+
# buffer_y = int((y_max - y_min) * 0.5)
|
| 204 |
+
# buffer_x = int((x_max - x_min) * 0.5)
|
| 205 |
+
|
| 206 |
+
# y_start = max(0, y_min - buffer_y)
|
| 207 |
+
# y_end = min(animator.lat_grid.shape[0], y_max + buffer_y + 1)
|
| 208 |
+
# x_start = max(0, x_min - buffer_x)
|
| 209 |
+
# x_end = min(animator.lon_grid.shape[1], x_max + buffer_x + 1)
|
| 210 |
+
|
| 211 |
+
# lat_zoom = animator.lats[y_start:y_end]
|
| 212 |
+
# lon_zoom = animator.lons[x_start:x_end]
|
| 213 |
+
# lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 214 |
+
|
| 215 |
+
# for z_index, z_val in enumerate(animator.levels):
|
| 216 |
+
# fig = plt.figure(figsize=(16, 7))
|
| 217 |
+
# proj = ccrs.PlateCarree()
|
| 218 |
+
# ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 219 |
+
# ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 220 |
+
|
| 221 |
+
# valid_frames = []
|
| 222 |
+
# for t in range(len(animator.datasets)):
|
| 223 |
+
# data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 224 |
+
# interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 225 |
+
# interp = np.where(interp < 0, np.nan, interp)
|
| 226 |
+
# if np.isfinite(interp).sum() > 0:
|
| 227 |
+
# valid_frames.append(t)
|
| 228 |
+
|
| 229 |
+
# if not valid_frames:
|
| 230 |
+
# print(f"No valid frames for Z={z_val} km. Skipping animation.")
|
| 231 |
+
# plt.close()
|
| 232 |
+
# continue
|
| 233 |
+
|
| 234 |
+
# def update(t):
|
| 235 |
+
# ax1.clear()
|
| 236 |
+
# ax2.clear()
|
| 237 |
+
|
| 238 |
+
# data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 239 |
+
# interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 240 |
+
# interp = np.where(interp < 0, np.nan, interp)
|
| 241 |
+
# zoom_plot = interp[y_start:y_end, x_start:x_end]
|
| 242 |
+
|
| 243 |
+
# valid_vals = interp[np.isfinite(interp)]
|
| 244 |
+
# if valid_vals.size == 0:
|
| 245 |
+
# return []
|
| 246 |
+
|
| 247 |
+
# min_val = np.nanmin(valid_vals)
|
| 248 |
+
# max_val = np.nanmax(valid_vals)
|
| 249 |
+
# log_cutoff = 1e-3
|
| 250 |
+
# log_ratio = max_val / (min_val + 1e-6)
|
| 251 |
+
# use_log = min_val > log_cutoff and log_ratio > 100
|
| 252 |
+
|
| 253 |
+
# if use_log:
|
| 254 |
+
# data_for_plot = np.where(interp > log_cutoff, interp, np.nan)
|
| 255 |
+
# levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20)
|
| 256 |
+
# scale_label = "Hybrid Log"
|
| 257 |
+
# else:
|
| 258 |
+
# data_for_plot = interp
|
| 259 |
+
# levels = np.linspace(0, max_val, 20)
|
| 260 |
+
# scale_label = "Linear"
|
| 261 |
+
|
| 262 |
+
# draw_etopo_basemap(ax1, mode='stock')
|
| 263 |
+
# draw_etopo_basemap(ax2, mode='stock')
|
| 264 |
+
|
| 265 |
+
# c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 266 |
+
# cmap="rainbow", alpha=0.6, transform=proj)
|
| 267 |
+
# ax1.contour(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 268 |
+
# colors='black', linewidths=0.5, transform=proj)
|
| 269 |
+
# ax1.set_title(f"T{t+1} | Alt: {z_val} km (Full - {scale_label})")
|
| 270 |
+
# ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 271 |
+
# ax1.coastlines()
|
| 272 |
+
# ax1.add_feature(cfeature.BORDERS, linestyle=':')
|
| 273 |
+
# ax1.add_feature(cfeature.LAND)
|
| 274 |
+
# ax1.add_feature(cfeature.OCEAN)
|
| 275 |
+
|
| 276 |
+
# c2 = ax2.contourf(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 277 |
+
# cmap="rainbow", alpha=0.4, transform=proj)
|
| 278 |
+
# ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 279 |
+
# colors='black', linewidths=0.5, transform=proj)
|
| 280 |
+
# ax2.set_title(f"T{t+1} | Alt: {z_val} km (Zoom - {scale_label})")
|
| 281 |
+
# ax2.set_extent([lon_zoom.min(), lon_zoom.max(), lat_zoom.min(), lat_zoom.max()])
|
| 282 |
+
# ax2.coastlines()
|
| 283 |
+
# ax2.add_feature(cfeature.BORDERS, linestyle=':')
|
| 284 |
+
# ax2.add_feature(cfeature.LAND)
|
| 285 |
+
# ax2.add_feature(cfeature.OCEAN)
|
| 286 |
+
|
| 287 |
+
# ax2.text(animator.lons[0], animator.lats[0], animator.country_label, fontsize=9, color='white',
|
| 288 |
+
# transform=proj, bbox=dict(facecolor='black', alpha=0.5))
|
| 289 |
+
|
| 290 |
+
# texts_ax1, texts_ax2 = [], []
|
| 291 |
+
# for country in country_geoms:
|
| 292 |
+
# name = country.attributes['NAME_LONG']
|
| 293 |
+
# geom = country.geometry
|
| 294 |
+
# try:
|
| 295 |
+
# lon, lat = geom.centroid.x, geom.centroid.y
|
| 296 |
+
# if (lon_zoom.min() <= lon <= lon_zoom.max()) and (lat_zoom.min() <= lat <= lat_zoom.max()):
|
| 297 |
+
# text = ax2.text(lon, lat, name, fontsize=6, transform=proj,
|
| 298 |
+
# ha='center', va='center', color='white',
|
| 299 |
+
# bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 300 |
+
# texts_ax2.append(text)
|
| 301 |
+
|
| 302 |
+
# if (animator.lons.min() <= lon <= animator.lons.max()) and (animator.lats.min() <= lat <= animator.lats.max()):
|
| 303 |
+
# text = ax1.text(lon, lat, name, fontsize=6, transform=proj,
|
| 304 |
+
# ha='center', va='center', color='white',
|
| 305 |
+
# bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 306 |
+
# texts_ax1.append(text)
|
| 307 |
+
# except:
|
| 308 |
+
# continue
|
| 309 |
+
|
| 310 |
+
# adjust_text(texts_ax1, ax=ax1, only_move={'points': 'y', 'text': 'y'},
|
| 311 |
+
# arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 312 |
+
# adjust_text(texts_ax2, ax=ax2, only_move={'points': 'y', 'text': 'y'},
|
| 313 |
+
# arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 314 |
+
|
| 315 |
+
# if np.nanmax(valid_vals) > threshold:
|
| 316 |
+
# alert_text = f"⚠ Exceeds {threshold} g/m³!"
|
| 317 |
+
# for ax in [ax1, ax2]:
|
| 318 |
+
# ax.text(0.99, 0.01, alert_text, transform=ax.transAxes,
|
| 319 |
+
# ha='right', va='bottom', fontsize=10, color='red',
|
| 320 |
+
# bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 321 |
+
# ax1.contour(animator.lons, animator.lats, interp, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 322 |
+
# ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 323 |
+
|
| 324 |
+
# if not hasattr(update, "colorbar"):
|
| 325 |
+
# update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 326 |
+
# label="Ash concentration (g/m³)")
|
| 327 |
+
# formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 328 |
+
# update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 329 |
+
# if use_log:
|
| 330 |
+
# update.colorbar.ax.text(1.05, 1.02, "log scale", transform=update.colorbar.ax.transAxes,
|
| 331 |
+
# fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 332 |
+
|
| 333 |
+
# return []
|
| 334 |
+
|
| 335 |
+
# ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False)
|
| 336 |
+
# gif_path = os.path.join(output_folder, f"ash_T1-Tn_Z{z_index+1}.gif")
|
| 337 |
+
# ani.save(gif_path, writer='pillow', fps=fps)
|
| 338 |
+
# plt.close()
|
| 339 |
+
# print(f"✅ Saved animation for Z={z_val} km to {gif_path}")
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
import os
|
| 343 |
+
import numpy as np
|
| 344 |
+
import matplotlib.pyplot as plt
|
| 345 |
+
import matplotlib.animation as animation
|
| 346 |
+
import matplotlib.ticker as mticker
|
| 347 |
+
import cartopy.crs as ccrs
|
| 348 |
+
import cartopy.feature as cfeature
|
| 349 |
+
from adjustText import adjust_text
|
| 350 |
+
import cartopy.io.shapereader as shpreader
|
| 351 |
+
from .interpolation import interpolate_grid
|
| 352 |
+
from .basemaps import draw_etopo_basemap
|
| 353 |
+
|
| 354 |
+
def animate_all_z_levels(animator, output_folder: str, fps: int = 2, threshold: float = 0.1,
|
| 355 |
+
zoom_width_deg: float = 6.0, zoom_height_deg: float = 6.0):
|
| 356 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 357 |
+
|
| 358 |
+
countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 359 |
+
reader = shpreader.Reader(countries_shp)
|
| 360 |
+
country_geoms = list(reader.records())
|
| 361 |
+
|
| 362 |
+
# Find the most active region (max concentration point)
|
| 363 |
+
max_conc = -np.inf
|
| 364 |
+
center_lat = center_lon = None
|
| 365 |
+
for ds in animator.datasets:
|
| 366 |
+
for z in range(len(animator.levels)):
|
| 367 |
+
data = ds['ash_concentration'].values[z]
|
| 368 |
+
if np.max(data) > max_conc:
|
| 369 |
+
max_conc = np.max(data)
|
| 370 |
+
max_idx = np.unravel_index(np.argmax(data), data.shape)
|
| 371 |
+
center_lat = animator.lat_grid[max_idx]
|
| 372 |
+
center_lon = animator.lon_grid[max_idx]
|
| 373 |
+
|
| 374 |
+
if center_lat is None or center_lon is None:
|
| 375 |
+
raise ValueError("No valid concentration found to determine zoom center.")
|
| 376 |
+
|
| 377 |
+
# Compute fixed zoom extents in lat/lon degrees
|
| 378 |
+
lon_zoom_min = center_lon - zoom_width_deg / 2
|
| 379 |
+
lon_zoom_max = center_lon + zoom_width_deg / 2
|
| 380 |
+
lat_zoom_min = center_lat - zoom_height_deg / 2
|
| 381 |
+
lat_zoom_max = center_lat + zoom_height_deg / 2
|
| 382 |
+
|
| 383 |
+
# Create zoom grids for plotting
|
| 384 |
+
lat_zoom = animator.lats[(animator.lats >= lat_zoom_min) & (animator.lats <= lat_zoom_max)]
|
| 385 |
+
lon_zoom = animator.lons[(animator.lons >= lon_zoom_min) & (animator.lons <= lon_zoom_max)]
|
| 386 |
+
lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 387 |
+
|
| 388 |
+
for z_index, z_val in enumerate(animator.levels):
|
| 389 |
+
fig = plt.figure(figsize=(16, 7))
|
| 390 |
+
proj = ccrs.PlateCarree()
|
| 391 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 392 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 393 |
+
|
| 394 |
+
valid_frames = []
|
| 395 |
+
for t in range(len(animator.datasets)):
|
| 396 |
+
data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 397 |
+
interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 398 |
+
interp = np.where(interp < 0, np.nan, interp)
|
| 399 |
+
if np.isfinite(interp).sum() > 0:
|
| 400 |
+
valid_frames.append(t)
|
| 401 |
+
|
| 402 |
+
if not valid_frames:
|
| 403 |
+
print(f"No valid frames for Z={z_val} km. Skipping animation.")
|
| 404 |
+
plt.close()
|
| 405 |
+
continue
|
| 406 |
+
|
| 407 |
+
def update(t):
|
| 408 |
+
ax1.clear()
|
| 409 |
+
ax2.clear()
|
| 410 |
+
|
| 411 |
+
data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 412 |
+
interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 413 |
+
interp = np.where(interp < 0, np.nan, interp)
|
| 414 |
+
|
| 415 |
+
# Extract zoom window from interpolated data
|
| 416 |
+
lat_idx = np.where((animator.lats >= lat_zoom_min) & (animator.lats <= lat_zoom_max))[0]
|
| 417 |
+
lon_idx = np.where((animator.lons >= lon_zoom_min) & (animator.lons <= lon_zoom_max))[0]
|
| 418 |
+
zoom_plot = interp[np.ix_(lat_idx, lon_idx)]
|
| 419 |
+
|
| 420 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 421 |
+
if valid_vals.size == 0:
|
| 422 |
+
return []
|
| 423 |
+
|
| 424 |
+
min_val = np.nanmin(valid_vals)
|
| 425 |
+
max_val = np.nanmax(valid_vals)
|
| 426 |
+
log_cutoff = 1e-3
|
| 427 |
+
log_ratio = max_val / (min_val + 1e-6)
|
| 428 |
+
use_log = min_val > log_cutoff and log_ratio > 100
|
| 429 |
+
|
| 430 |
+
if use_log:
|
| 431 |
+
data_for_plot = np.where(interp > log_cutoff, interp, np.nan)
|
| 432 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20)
|
| 433 |
+
scale_label = "Hybrid Log"
|
| 434 |
+
else:
|
| 435 |
+
data_for_plot = interp
|
| 436 |
+
levels = np.linspace(0, max_val, 20)
|
| 437 |
+
scale_label = "Linear"
|
| 438 |
+
|
| 439 |
+
draw_etopo_basemap(ax1, mode='stock')
|
| 440 |
+
draw_etopo_basemap(ax2, mode='stock')
|
| 441 |
+
|
| 442 |
+
c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 443 |
+
cmap="rainbow", alpha=0.6, transform=proj)
|
| 444 |
+
ax1.contour(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 445 |
+
colors='black', linewidths=0.5, transform=proj)
|
| 446 |
+
ax1.set_title(f"T{t+1} | Alt: {z_val} km (Full - {scale_label})")
|
| 447 |
+
ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 448 |
+
ax1.coastlines()
|
| 449 |
+
ax1.add_feature(cfeature.BORDERS, linestyle=':')
|
| 450 |
+
ax1.add_feature(cfeature.LAND)
|
| 451 |
+
ax1.add_feature(cfeature.OCEAN)
|
| 452 |
+
|
| 453 |
+
c2 = ax2.contourf(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 454 |
+
cmap="rainbow", alpha=0.4, transform=proj)
|
| 455 |
+
ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 456 |
+
colors='black', linewidths=0.5, transform=proj)
|
| 457 |
+
ax2.set_title(f"T{t+1} | Alt: {z_val} km (Zoom - {scale_label})")
|
| 458 |
+
ax2.set_extent([lon_zoom_min, lon_zoom_max, lat_zoom_min, lat_zoom_max])
|
| 459 |
+
ax2.coastlines()
|
| 460 |
+
ax2.add_feature(cfeature.BORDERS, linestyle=':')
|
| 461 |
+
ax2.add_feature(cfeature.LAND)
|
| 462 |
+
ax2.add_feature(cfeature.OCEAN)
|
| 463 |
+
|
| 464 |
+
ax2.text(animator.lons[0], animator.lats[0], animator.country_label, fontsize=9, color='white',
|
| 465 |
+
transform=proj, bbox=dict(facecolor='black', alpha=0.5))
|
| 466 |
+
|
| 467 |
+
texts_ax1, texts_ax2 = [], []
|
| 468 |
+
for country in country_geoms:
|
| 469 |
+
name = country.attributes['NAME_LONG']
|
| 470 |
+
geom = country.geometry
|
| 471 |
+
try:
|
| 472 |
+
lon, lat = geom.centroid.x, geom.centroid.y
|
| 473 |
+
if (lon_zoom_min <= lon <= lon_zoom_max) and (lat_zoom_min <= lat <= lat_zoom_max):
|
| 474 |
+
text = ax2.text(lon, lat, name, fontsize=6, transform=proj,
|
| 475 |
+
ha='center', va='center', color='white',
|
| 476 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 477 |
+
texts_ax2.append(text)
|
| 478 |
+
|
| 479 |
+
if (animator.lons.min() <= lon <= animator.lons.max()) and (animator.lats.min() <= lat <= animator.lats.max()):
|
| 480 |
+
text = ax1.text(lon, lat, name, fontsize=6, transform=proj,
|
| 481 |
+
ha='center', va='center', color='white',
|
| 482 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 483 |
+
texts_ax1.append(text)
|
| 484 |
+
except:
|
| 485 |
+
continue
|
| 486 |
+
|
| 487 |
+
adjust_text(texts_ax1, ax=ax1, only_move={'points': 'y', 'text': 'y'},
|
| 488 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 489 |
+
adjust_text(texts_ax2, ax=ax2, only_move={'points': 'y', 'text': 'y'},
|
| 490 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 491 |
+
|
| 492 |
+
if np.nanmax(valid_vals) > threshold:
|
| 493 |
+
alert_text = f"⚠ Exceeds {threshold} g/m³!"
|
| 494 |
+
for ax in [ax1, ax2]:
|
| 495 |
+
ax.text(0.99, 0.01, alert_text, transform=ax.transAxes,
|
| 496 |
+
ha='right', va='bottom', fontsize=10, color='red',
|
| 497 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 498 |
+
ax1.contour(animator.lons, animator.lats, interp, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 499 |
+
ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 500 |
+
|
| 501 |
+
if not hasattr(update, "colorbar"):
|
| 502 |
+
update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 503 |
+
label="Ash concentration (g/m³)")
|
| 504 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 505 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 506 |
+
if use_log:
|
| 507 |
+
update.colorbar.ax.text(1.05, 1.02, "log scale", transform=update.colorbar.ax.transAxes,
|
| 508 |
+
fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 509 |
+
|
| 510 |
+
return []
|
| 511 |
+
|
| 512 |
+
ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False)
|
| 513 |
+
gif_path = os.path.join(output_folder, f"ash_T1-Tn_Z{z_index+1}.gif")
|
| 514 |
+
ani.save(gif_path, writer='pillow', fps=fps)
|
| 515 |
+
plt.close()
|
| 516 |
+
print(f"✅ Saved animation for Z={z_val} km to {gif_path}")
|
ash_animator/animation_single.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import matplotlib.animation as animation
|
| 6 |
+
import matplotlib.ticker as mticker
|
| 7 |
+
import cartopy.crs as ccrs
|
| 8 |
+
import cartopy.feature as cfeature
|
| 9 |
+
from .interpolation import interpolate_grid
|
| 10 |
+
from .basemaps import draw_etopo_basemap
|
| 11 |
+
|
| 12 |
+
def animate_single_z_level(animator, z_km: float, output_path: str, fps: int = 2, include_metadata: bool = True, threshold: float = 0.1):
|
| 13 |
+
if z_km not in animator.levels:
|
| 14 |
+
print(f"Z level {z_km} km not found in dataset.")
|
| 15 |
+
return
|
| 16 |
+
|
| 17 |
+
z_index = np.where(animator.levels == z_km)[0][0]
|
| 18 |
+
fig = plt.figure(figsize=(16, 7))
|
| 19 |
+
proj = ccrs.PlateCarree()
|
| 20 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 21 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 22 |
+
|
| 23 |
+
meta = animator.datasets[0].attrs
|
| 24 |
+
legend_text = (
|
| 25 |
+
f"Run name: {meta.get('run_name', 'N/A')}\n"
|
| 26 |
+
f"Run time: {meta.get('run_time', 'N/A')}\n"
|
| 27 |
+
f"Met data: {meta.get('met_data', 'N/A')}\n"
|
| 28 |
+
f"Start release: {meta.get('start_of_release', 'N/A')}\n"
|
| 29 |
+
f"End release: {meta.get('end_of_release', 'N/A')}\n"
|
| 30 |
+
f"Source strength: {meta.get('source_strength', 'N/A')} g/s\n"
|
| 31 |
+
f"Release loc: {meta.get('release_location', 'N/A')}\n"
|
| 32 |
+
f"Release height: {meta.get('release_height', 'N/A')} m asl\n"
|
| 33 |
+
f"Run duration: {meta.get('run_duration', 'N/A')}"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
valid_mask = np.stack([
|
| 37 |
+
ds['ash_concentration'].values[z_index] for ds in animator.datasets
|
| 38 |
+
]).max(axis=0) > 0
|
| 39 |
+
y_idx, x_idx = np.where(valid_mask)
|
| 40 |
+
|
| 41 |
+
if y_idx.size == 0 or x_idx.size == 0:
|
| 42 |
+
print(f"Z level {z_km} km has no valid data. Skipping...")
|
| 43 |
+
plt.close()
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
y_min, y_max = y_idx.min(), y_idx.max()
|
| 47 |
+
x_min, x_max = x_idx.min(), x_idx.max()
|
| 48 |
+
buffer_y = int((y_max - y_min) * 0.5)
|
| 49 |
+
buffer_x = int((x_max - x_min) * 0.5)
|
| 50 |
+
y_start = max(0, y_min - buffer_y)
|
| 51 |
+
y_end = min(animator.lat_grid.shape[0], y_max + buffer_y + 1)
|
| 52 |
+
x_start = max(0, x_min - buffer_x)
|
| 53 |
+
x_end = min(animator.lon_grid.shape[1], x_max + buffer_x + 1)
|
| 54 |
+
|
| 55 |
+
lat_zoom = animator.lats[y_start:y_end]
|
| 56 |
+
lon_zoom = animator.lons[x_start:x_end]
|
| 57 |
+
lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 58 |
+
|
| 59 |
+
valid_frames = []
|
| 60 |
+
for t in range(len(animator.datasets)):
|
| 61 |
+
interp = interpolate_grid(animator.datasets[t]['ash_concentration'].values[z_index],
|
| 62 |
+
animator.lon_grid, animator.lat_grid)
|
| 63 |
+
if np.isfinite(interp).sum() > 0:
|
| 64 |
+
valid_frames.append(t)
|
| 65 |
+
|
| 66 |
+
if not valid_frames:
|
| 67 |
+
print(f"No valid frames for Z={z_km} km. Skipping animation.")
|
| 68 |
+
plt.close()
|
| 69 |
+
return
|
| 70 |
+
|
| 71 |
+
def update(t):
|
| 72 |
+
ax1.clear()
|
| 73 |
+
ax2.clear()
|
| 74 |
+
|
| 75 |
+
data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 76 |
+
interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 77 |
+
interp = np.where(interp < 0, np.nan, interp)
|
| 78 |
+
zoom_plot = interp[y_start:y_end, x_start:x_end]
|
| 79 |
+
|
| 80 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 81 |
+
if valid_vals.size == 0:
|
| 82 |
+
return []
|
| 83 |
+
|
| 84 |
+
min_val = np.nanmin(valid_vals)
|
| 85 |
+
max_val = np.nanmax(valid_vals)
|
| 86 |
+
log_cutoff = 1e-3
|
| 87 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 88 |
+
|
| 89 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 90 |
+
data_for_plot = np.where(interp > log_cutoff, interp, 0) if use_log else interp
|
| 91 |
+
scale_label = "Log" if use_log else "Linear"
|
| 92 |
+
|
| 93 |
+
draw_etopo_basemap(ax1, mode='stock')
|
| 94 |
+
draw_etopo_basemap(ax2, mode='stock')
|
| 95 |
+
|
| 96 |
+
c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 97 |
+
cmap="rainbow", alpha=0.6, transform=proj)
|
| 98 |
+
ax1.set_title(f"T{t+1} | Alt: {z_km} km (Full - {scale_label})")
|
| 99 |
+
ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 100 |
+
ax1.coastlines(); ax1.add_feature(cfeature.BORDERS); ax1.add_feature(cfeature.LAND); ax1.add_feature(cfeature.OCEAN)
|
| 101 |
+
|
| 102 |
+
c2 = ax2.contourf(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 103 |
+
cmap="rainbow", alpha=0.6, transform=proj)
|
| 104 |
+
ax2.set_title(f"T{t+1} | Alt: {z_km} km (Zoom - {scale_label})")
|
| 105 |
+
ax2.set_extent([lon_zoom.min(), lon_zoom.max(), lat_zoom.min(), lat_zoom.max()])
|
| 106 |
+
ax2.coastlines(); ax2.add_feature(cfeature.BORDERS); ax2.add_feature(cfeature.LAND); ax2.add_feature(cfeature.OCEAN)
|
| 107 |
+
|
| 108 |
+
if not hasattr(update, "colorbar"):
|
| 109 |
+
update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 110 |
+
label="Ash concentration (g/m³)")
|
| 111 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 112 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 113 |
+
if use_log:
|
| 114 |
+
update.colorbar.ax.text(1.05, 1.02, "log scale", transform=update.colorbar.ax.transAxes,
|
| 115 |
+
fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 116 |
+
|
| 117 |
+
if include_metadata:
|
| 118 |
+
ax1.annotate(legend_text, xy=(0.75, 0.99), xycoords='axes fraction',
|
| 119 |
+
fontsize=8, ha='left', va='top',
|
| 120 |
+
bbox=dict(boxstyle="round", facecolor="white", edgecolor="gray"))
|
| 121 |
+
for ax in [ax1, ax2]:
|
| 122 |
+
ax.text(0.01, 0.01,
|
| 123 |
+
f"Source: NAME\nRes: {animator.x_res:.2f}°\n{meta.get('run_name', 'N/A')}",
|
| 124 |
+
transform=ax.transAxes, fontsize=8, color='white',
|
| 125 |
+
bbox=dict(facecolor='black', alpha=0.5))
|
| 126 |
+
|
| 127 |
+
for ax in [ax1, ax2]:
|
| 128 |
+
ax.text(0.01, 0.98, f"Time step T{t+1}", transform=ax.transAxes,
|
| 129 |
+
fontsize=9, color='white', va='top', ha='left',
|
| 130 |
+
bbox=dict(facecolor='black', alpha=0.4, boxstyle='round'))
|
| 131 |
+
|
| 132 |
+
if np.nanmax(valid_vals) > threshold:
|
| 133 |
+
alert_text = f"⚠ Exceeds {threshold} g/m³!"
|
| 134 |
+
for ax in [ax1, ax2]:
|
| 135 |
+
ax.text(0.99, 0.01, alert_text, transform=ax.transAxes,
|
| 136 |
+
ha='right', va='bottom', fontsize=10, color='red',
|
| 137 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 138 |
+
ax1.contour(animator.lons, animator.lats, interp, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 139 |
+
ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 140 |
+
|
| 141 |
+
return []
|
| 142 |
+
|
| 143 |
+
ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False)
|
| 144 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 145 |
+
ani.save(output_path, writer='pillow', fps=fps)
|
| 146 |
+
plt.close()
|
| 147 |
+
print(f"✅ Saved animation for Z={z_km} km to {output_path}")
|
ash_animator/animation_vertical.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import matplotlib.animation as animation
|
| 6 |
+
import matplotlib.ticker as mticker
|
| 7 |
+
import cartopy.crs as ccrs
|
| 8 |
+
import cartopy.feature as cfeature
|
| 9 |
+
import cartopy.io.shapereader as shpreader
|
| 10 |
+
from .interpolation import interpolate_grid
|
| 11 |
+
from .basemaps import draw_etopo_basemap
|
| 12 |
+
|
| 13 |
+
# def animate_vertical_profile(animator, t_index: int, output_path: str, fps: int = 2, include_metadata: bool = True, threshold: float = 0.1):
|
| 14 |
+
# if not (0 <= t_index < len(animator.datasets)):
|
| 15 |
+
# print(f"Invalid time index {t_index}. Must be between 0 and {len(animator.datasets) - 1}.")
|
| 16 |
+
# return
|
| 17 |
+
|
| 18 |
+
# ds = animator.datasets[t_index]
|
| 19 |
+
# fig = plt.figure(figsize=(16, 7))
|
| 20 |
+
# proj = ccrs.PlateCarree()
|
| 21 |
+
# ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 22 |
+
# ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 23 |
+
|
| 24 |
+
# meta = ds.attrs
|
| 25 |
+
# legend_text = (
|
| 26 |
+
# f"Run name: {meta.get('run_name', 'N/A')}\n"
|
| 27 |
+
# f"Run time: {meta.get('run_time', 'N/A')}\n"
|
| 28 |
+
# f"Met data: {meta.get('met_data', 'N/A')}\n"
|
| 29 |
+
# f"Start release: {meta.get('start_of_release', 'N/A')}\n"
|
| 30 |
+
# f"End release: {meta.get('end_of_release', 'N/A')}\n"
|
| 31 |
+
# f"Source strength: {meta.get('source_strength', 'N/A')} g/s\n"
|
| 32 |
+
# f"Release loc: {meta.get('release_location', 'N/A')}\n"
|
| 33 |
+
# f"Release height: {meta.get('release_height', 'N/A')} m asl\n"
|
| 34 |
+
# f"Run duration: {meta.get('run_duration', 'N/A')}"
|
| 35 |
+
# )
|
| 36 |
+
|
| 37 |
+
# valid_mask = np.stack([ds['ash_concentration'].values[z] for z in range(len(animator.levels))]).max(axis=0) > 0
|
| 38 |
+
# y_idx, x_idx = np.where(valid_mask)
|
| 39 |
+
|
| 40 |
+
# if y_idx.size == 0 or x_idx.size == 0:
|
| 41 |
+
# print(f"No valid data found for time T{t_index+1}. Skipping...")
|
| 42 |
+
# plt.close()
|
| 43 |
+
# return
|
| 44 |
+
|
| 45 |
+
# y_min, y_max = y_idx.min(), y_idx.max()
|
| 46 |
+
# x_min, x_max = x_idx.min(), x_idx.max()
|
| 47 |
+
# buffer_y = int((y_max - y_min) * 0.1)
|
| 48 |
+
# buffer_x = int((x_max - x_min) * 0.1)
|
| 49 |
+
# y_start = max(0, y_min - buffer_y)
|
| 50 |
+
# y_end = min(animator.lat_grid.shape[0], y_max + buffer_y + 1)
|
| 51 |
+
# x_start = max(0, x_min - buffer_x)
|
| 52 |
+
# x_end = min(animator.lon_grid.shape[1], x_max + buffer_x + 1)
|
| 53 |
+
|
| 54 |
+
# lat_zoom = animator.lats[y_start:y_end]
|
| 55 |
+
# lon_zoom = animator.lons[x_start:x_end]
|
| 56 |
+
# lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 57 |
+
|
| 58 |
+
# z_indices_with_data = []
|
| 59 |
+
# for z_index in range(len(animator.levels)):
|
| 60 |
+
# data = ds['ash_concentration'].values[z_index]
|
| 61 |
+
# interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 62 |
+
# if np.isfinite(interp).sum() > 0:
|
| 63 |
+
# z_indices_with_data.append(z_index)
|
| 64 |
+
|
| 65 |
+
# if not z_indices_with_data:
|
| 66 |
+
# print(f"No valid Z-levels at time T{t_index+1}.")
|
| 67 |
+
# plt.close()
|
| 68 |
+
# return
|
| 69 |
+
|
| 70 |
+
# def update(z_index):
|
| 71 |
+
# ax1.clear()
|
| 72 |
+
# ax2.clear()
|
| 73 |
+
|
| 74 |
+
# data = ds['ash_concentration'].values[z_index]
|
| 75 |
+
# interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 76 |
+
# interp = np.where(interp < 0, np.nan, interp)
|
| 77 |
+
# zoom_plot = interp[y_start:y_end, x_start:x_end]
|
| 78 |
+
|
| 79 |
+
# valid_vals = interp[np.isfinite(interp)]
|
| 80 |
+
# if valid_vals.size == 0:
|
| 81 |
+
# return []
|
| 82 |
+
|
| 83 |
+
# min_val = np.nanmin(valid_vals)
|
| 84 |
+
# max_val = np.nanmax(valid_vals)
|
| 85 |
+
# log_cutoff = 1e-3
|
| 86 |
+
# use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 87 |
+
|
| 88 |
+
# levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 89 |
+
# data_for_plot = np.where(interp > log_cutoff, interp, 0) if use_log else interp
|
| 90 |
+
# scale_label = "Log" if use_log else "Linear"
|
| 91 |
+
|
| 92 |
+
# draw_etopo_basemap(ax1, mode='stock')
|
| 93 |
+
# draw_etopo_basemap(ax2, mode='stock')
|
| 94 |
+
|
| 95 |
+
# c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 96 |
+
# cmap="rainbow", alpha=0.6, transform=proj)
|
| 97 |
+
# ax1.set_title(f"T{t_index+1} | Alt: {animator.levels[z_index]} km (Full - {scale_label})")
|
| 98 |
+
# ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 99 |
+
# ax1.coastlines(); ax1.add_feature(cfeature.BORDERS, linestyle=':')
|
| 100 |
+
# ax1.add_feature(cfeature.LAND); ax1.add_feature(cfeature.OCEAN)
|
| 101 |
+
|
| 102 |
+
# c2 = ax2.contourf(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 103 |
+
# cmap="rainbow", alpha=0.6, transform=proj)
|
| 104 |
+
# ax2.set_title(f"T{t_index+1} | Alt: {animator.levels[z_index]} km (Zoom - {scale_label})")
|
| 105 |
+
# ax2.set_extent([lon_zoom.min(), lon_zoom.max(), lat_zoom.min(), lat_zoom.max()])
|
| 106 |
+
# ax2.coastlines(); ax2.add_feature(cfeature.BORDERS, linestyle=':')
|
| 107 |
+
# ax2.add_feature(cfeature.LAND); ax2.add_feature(cfeature.OCEAN)
|
| 108 |
+
|
| 109 |
+
# for ax in [ax1, ax2]:
|
| 110 |
+
# ax.text(0.01, 0.98, f"Altitude: {animator.levels[z_index]:.2f} km", transform=ax.transAxes,
|
| 111 |
+
# fontsize=9, color='white', va='top', ha='left',
|
| 112 |
+
# bbox=dict(facecolor='black', alpha=0.4, boxstyle='round'))
|
| 113 |
+
|
| 114 |
+
# if include_metadata:
|
| 115 |
+
# ax.text(0.01, 0.01,
|
| 116 |
+
# f"Source: NAME\nRes: {animator.x_res:.2f}°\n{meta.get('run_name', 'N/A')}",
|
| 117 |
+
# transform=ax.transAxes, fontsize=8, color='white',
|
| 118 |
+
# bbox=dict(facecolor='black', alpha=0.5))
|
| 119 |
+
|
| 120 |
+
# if np.nanmax(valid_vals) > threshold:
|
| 121 |
+
# for ax in [ax1, ax2]:
|
| 122 |
+
# ax.text(0.99, 0.01, f"⚠ Exceeds {threshold} g/m³!", transform=ax.transAxes,
|
| 123 |
+
# ha='right', va='bottom', fontsize=10, color='red',
|
| 124 |
+
# bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 125 |
+
# ax1.contour(animator.lons, animator.lats, interp, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 126 |
+
# ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 127 |
+
|
| 128 |
+
# if include_metadata and not hasattr(update, "legend_text"):
|
| 129 |
+
# ax1.annotate(legend_text, xy=(0.75, 0.99), xycoords='axes fraction',
|
| 130 |
+
# fontsize=8, ha='left', va='top',
|
| 131 |
+
# bbox=dict(boxstyle="round", facecolor="white", edgecolor="gray"))
|
| 132 |
+
|
| 133 |
+
# if not hasattr(update, "colorbar"):
|
| 134 |
+
# update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 135 |
+
# label="Ash concentration (g/m³)")
|
| 136 |
+
# formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 137 |
+
# update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 138 |
+
|
| 139 |
+
# if use_log:
|
| 140 |
+
# update.colorbar.ax.text(1.05, 1.02, "log scale", transform=update.colorbar.ax.transAxes,
|
| 141 |
+
# fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 142 |
+
|
| 143 |
+
# return []
|
| 144 |
+
|
| 145 |
+
# os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 146 |
+
# ani = animation.FuncAnimation(fig, update, frames=z_indices_with_data, blit=False)
|
| 147 |
+
# ani.save(output_path, writer='pillow', fps=fps)
|
| 148 |
+
# plt.close()
|
| 149 |
+
# print(f"✅ Saved vertical profile animation for T{t_index+1} to {output_path}")
|
| 150 |
+
|
| 151 |
+
# def animate_all_vertical_profiles(animator, output_folder: str, fps: int = 2, include_metadata: bool = True, threshold: float = 0.1):
|
| 152 |
+
# os.makedirs(output_folder, exist_ok=True)
|
| 153 |
+
# for t_index in range(len(animator.datasets)):
|
| 154 |
+
# output_path = os.path.join(output_folder, f"vertical_T{t_index+1:02d}.gif")
|
| 155 |
+
# print(f"🔄 Generating vertical profile animation for T{t_index+1}...")
|
| 156 |
+
# animate_vertical_profile(animator, t_index, output_path, fps, include_metadata, threshold)
|
| 157 |
+
|
| 158 |
+
import os
|
| 159 |
+
import numpy as np
|
| 160 |
+
import matplotlib.pyplot as plt
|
| 161 |
+
import matplotlib.animation as animation
|
| 162 |
+
import matplotlib.ticker as mticker
|
| 163 |
+
import cartopy.crs as ccrs
|
| 164 |
+
import cartopy.feature as cfeature
|
| 165 |
+
import cartopy.io.shapereader as shpreader
|
| 166 |
+
from .interpolation import interpolate_grid
|
| 167 |
+
from .basemaps import draw_etopo_basemap
|
| 168 |
+
from adjustText import adjust_text
|
| 169 |
+
|
| 170 |
+
def animate_vertical_profile(animator, t_index: int, output_path: str, fps: int = 2,
|
| 171 |
+
include_metadata: bool = True, threshold: float = 0.1,
|
| 172 |
+
zoom_width_deg: float = 6.0, zoom_height_deg: float = 6.0):
|
| 173 |
+
if not (0 <= t_index < len(animator.datasets)):
|
| 174 |
+
print(f"Invalid time index {t_index}. Must be between 0 and {len(animator.datasets) - 1}.")
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 178 |
+
reader = shpreader.Reader(countries_shp)
|
| 179 |
+
country_geoms = list(reader.records())
|
| 180 |
+
|
| 181 |
+
ds = animator.datasets[t_index]
|
| 182 |
+
fig = plt.figure(figsize=(18, 7)) # Wider for metadata outside
|
| 183 |
+
proj = ccrs.PlateCarree()
|
| 184 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 185 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 186 |
+
|
| 187 |
+
meta = ds.attrs
|
| 188 |
+
legend_text = (
|
| 189 |
+
f"Run name: {meta.get('run_name', 'N/A')}\n"
|
| 190 |
+
f"Run time: {meta.get('run_time', 'N/A')}\n"
|
| 191 |
+
f"Met data: {meta.get('met_data', 'N/A')}\n"
|
| 192 |
+
f"Start release: {meta.get('start_of_release', 'N/A')}\n"
|
| 193 |
+
f"End release: {meta.get('end_of_release', 'N/A')}\n"
|
| 194 |
+
f"Source strength: {meta.get('source_strength', 'N/A')} g/s\n"
|
| 195 |
+
f"Release loc: {meta.get('release_location', 'N/A')}\n"
|
| 196 |
+
f"Release height: {meta.get('release_height', 'N/A')} m asl\n"
|
| 197 |
+
f"Run duration: {meta.get('run_duration', 'N/A')}"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# 🔍 Find most active point at this time step
|
| 201 |
+
max_conc = -np.inf
|
| 202 |
+
center_lat = center_lon = None
|
| 203 |
+
for z in range(len(animator.levels)):
|
| 204 |
+
data = ds['ash_concentration'].values[z]
|
| 205 |
+
if np.max(data) > max_conc:
|
| 206 |
+
max_conc = np.max(data)
|
| 207 |
+
max_idx = np.unravel_index(np.argmax(data), data.shape)
|
| 208 |
+
center_lat = animator.lat_grid[max_idx]
|
| 209 |
+
center_lon = animator.lon_grid[max_idx]
|
| 210 |
+
|
| 211 |
+
if center_lat is None or center_lon is None:
|
| 212 |
+
print(f"No valid data found for time T{t_index+1}. Skipping...")
|
| 213 |
+
plt.close()
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
# 🌍 Define fixed zoom extents
|
| 217 |
+
lon_zoom_min = center_lon - zoom_width_deg / 2
|
| 218 |
+
lon_zoom_max = center_lon + zoom_width_deg / 2
|
| 219 |
+
lat_zoom_min = center_lat - zoom_height_deg / 2
|
| 220 |
+
lat_zoom_max = center_lat + zoom_height_deg / 2
|
| 221 |
+
|
| 222 |
+
lat_zoom = animator.lats[(animator.lats >= lat_zoom_min) & (animator.lats <= lat_zoom_max)]
|
| 223 |
+
lon_zoom = animator.lons[(animator.lons >= lon_zoom_min) & (animator.lons <= lon_zoom_max)]
|
| 224 |
+
lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 225 |
+
|
| 226 |
+
z_indices_with_data = []
|
| 227 |
+
for z_index in range(len(animator.levels)):
|
| 228 |
+
data = ds['ash_concentration'].values[z_index]
|
| 229 |
+
interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 230 |
+
if np.isfinite(interp).sum() > 0:
|
| 231 |
+
z_indices_with_data.append(z_index)
|
| 232 |
+
|
| 233 |
+
if not z_indices_with_data:
|
| 234 |
+
print(f"No valid Z-levels at time T{t_index+1}.")
|
| 235 |
+
plt.close()
|
| 236 |
+
return
|
| 237 |
+
|
| 238 |
+
def update(z_index):
|
| 239 |
+
ax1.clear()
|
| 240 |
+
ax2.clear()
|
| 241 |
+
|
| 242 |
+
data = ds['ash_concentration'].values[z_index]
|
| 243 |
+
interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 244 |
+
interp = np.where(interp < 0, np.nan, interp)
|
| 245 |
+
|
| 246 |
+
lat_idx = np.where((animator.lats >= lat_zoom_min) & (animator.lats <= lat_zoom_max))[0]
|
| 247 |
+
lon_idx = np.where((animator.lons >= lon_zoom_min) & (animator.lons <= lon_zoom_max))[0]
|
| 248 |
+
zoom_plot = interp[np.ix_(lat_idx, lon_idx)]
|
| 249 |
+
|
| 250 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 251 |
+
if valid_vals.size == 0:
|
| 252 |
+
return []
|
| 253 |
+
|
| 254 |
+
min_val = np.nanmin(valid_vals)
|
| 255 |
+
max_val = np.nanmax(valid_vals)
|
| 256 |
+
log_cutoff = 1e-3
|
| 257 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 258 |
+
|
| 259 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 260 |
+
data_for_plot = np.where(interp > log_cutoff, interp, 0) if use_log else interp
|
| 261 |
+
scale_label = "Log" if use_log else "Linear"
|
| 262 |
+
|
| 263 |
+
draw_etopo_basemap(ax1, mode='stock')
|
| 264 |
+
draw_etopo_basemap(ax2, mode='stock')
|
| 265 |
+
|
| 266 |
+
c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 267 |
+
cmap="rainbow", alpha=0.6, transform=proj)
|
| 268 |
+
ax1.set_title(f"T{t_index+1} | Alt: {animator.levels[z_index]} km (Full - {scale_label})")
|
| 269 |
+
ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 270 |
+
ax1.coastlines(); ax1.add_feature(cfeature.BORDERS, linestyle=':')
|
| 271 |
+
ax1.add_feature(cfeature.LAND); ax1.add_feature(cfeature.OCEAN)
|
| 272 |
+
|
| 273 |
+
c2 = ax2.contourf(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=levels,
|
| 274 |
+
cmap="rainbow", alpha=0.6, transform=proj)
|
| 275 |
+
ax2.set_title(f"T{t_index+1} | Alt: {animator.levels[z_index]} km (Zoom - {scale_label})")
|
| 276 |
+
ax2.set_extent([lon_zoom_min, lon_zoom_max, lat_zoom_min, lat_zoom_max])
|
| 277 |
+
ax2.coastlines(); ax2.add_feature(cfeature.BORDERS, linestyle=':')
|
| 278 |
+
ax2.add_feature(cfeature.LAND); ax2.add_feature(cfeature.OCEAN)
|
| 279 |
+
|
| 280 |
+
for ax in [ax1, ax2]:
|
| 281 |
+
ax.text(0.01, 0.98, f"Altitude: {animator.levels[z_index]:.2f} km", transform=ax.transAxes,
|
| 282 |
+
fontsize=9, color='white', va='top', ha='left',
|
| 283 |
+
bbox=dict(facecolor='black', alpha=0.4, boxstyle='round'))
|
| 284 |
+
|
| 285 |
+
if include_metadata:
|
| 286 |
+
fig.text(0.50, 0.1, legend_text, va='center', ha='left', fontsize=8,
|
| 287 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'),
|
| 288 |
+
transform=fig.transFigure)
|
| 289 |
+
|
| 290 |
+
if np.nanmax(valid_vals) > threshold:
|
| 291 |
+
for ax in [ax1, ax2]:
|
| 292 |
+
ax.text(0.99, 0.01, f"⚠ Exceeds {threshold} g/m³!", transform=ax.transAxes,
|
| 293 |
+
ha='right', va='bottom', fontsize=10, color='red',
|
| 294 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 295 |
+
ax1.contour(animator.lons, animator.lats, interp, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 296 |
+
ax2.contour(lon_zoom_grid, lat_zoom_grid, zoom_plot, levels=[threshold], colors='red', linewidths=2, transform=proj)
|
| 297 |
+
|
| 298 |
+
if not hasattr(update, "colorbar"):
|
| 299 |
+
update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 300 |
+
label="Ash concentration (g/m³)", shrink=0.75)
|
| 301 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 302 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 303 |
+
|
| 304 |
+
if use_log:
|
| 305 |
+
update.colorbar.ax.text(1.05, 1.02, "log scale", transform=update.colorbar.ax.transAxes,
|
| 306 |
+
fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 307 |
+
|
| 308 |
+
######################3
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
texts_ax1, texts_ax2 = [], []
|
| 312 |
+
for country in country_geoms:
|
| 313 |
+
name = country.attributes['NAME_LONG']
|
| 314 |
+
geom = country.geometry
|
| 315 |
+
try:
|
| 316 |
+
lon, lat = geom.centroid.x, geom.centroid.y
|
| 317 |
+
if (lon_zoom_min <= lon <= lon_zoom_max) and (lat_zoom_min <= lat <= lat_zoom_max):
|
| 318 |
+
text = ax2.text(lon, lat, name, fontsize=6, transform=proj,
|
| 319 |
+
ha='center', va='center', color='white',
|
| 320 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 321 |
+
texts_ax2.append(text)
|
| 322 |
+
|
| 323 |
+
if (animator.lons.min() <= lon <= animator.lons.max()) and (animator.lats.min() <= lat <= animator.lats.max()):
|
| 324 |
+
text = ax1.text(lon, lat, name, fontsize=6, transform=proj,
|
| 325 |
+
ha='center', va='center', color='white',
|
| 326 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 327 |
+
texts_ax1.append(text)
|
| 328 |
+
except:
|
| 329 |
+
continue
|
| 330 |
+
|
| 331 |
+
adjust_text(texts_ax1, ax=ax1, only_move={'points': 'y', 'text': 'y'},
|
| 332 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 333 |
+
adjust_text(texts_ax2, ax=ax2, only_move={'points': 'y', 'text': 'y'},
|
| 334 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
############################################
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
return []
|
| 343 |
+
|
| 344 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 345 |
+
ani = animation.FuncAnimation(fig, update, frames=z_indices_with_data, blit=False)
|
| 346 |
+
ani.save(output_path, writer='pillow', fps=fps)
|
| 347 |
+
plt.close()
|
| 348 |
+
print(f"✅ Saved vertical profile animation for T{t_index+1} to {output_path}")
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def animate_all_vertical_profiles(animator, output_folder: str, fps: int = 2,
|
| 352 |
+
include_metadata: bool = True, threshold: float = 0.1,
|
| 353 |
+
zoom_width_deg: float = 10.0, zoom_height_deg: float = 6.0):
|
| 354 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 355 |
+
for t_index in range(len(animator.datasets)):
|
| 356 |
+
output_path = os.path.join(output_folder, f"vertical_T{t_index+1:02d}.gif")
|
| 357 |
+
print(f"🔄 Generating vertical profile animation for T{t_index+1}...")
|
| 358 |
+
animate_vertical_profile(animator, t_index, output_path, fps,
|
| 359 |
+
include_metadata, threshold,
|
| 360 |
+
zoom_width_deg, zoom_height_deg)
|
ash_animator/basemaps.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# import contextily as ctx
|
| 3 |
+
# from mpl_toolkits.basemap import Basemap
|
| 4 |
+
# import cartopy.crs as ccrs
|
| 5 |
+
# import cartopy.feature as cfeature
|
| 6 |
+
|
| 7 |
+
# def draw_etopo_basemap(ax, mode="basemap", zoom=7):
|
| 8 |
+
# try:
|
| 9 |
+
# if mode == "stock":
|
| 10 |
+
# ax.stock_img()
|
| 11 |
+
# elif mode == "contextily":
|
| 12 |
+
# extent = ax.get_extent(ccrs.PlateCarree())
|
| 13 |
+
# ax.set_extent(extent, crs=ccrs.PlateCarree())
|
| 14 |
+
# ctx.add_basemap(ax, crs=ccrs.PlateCarree(), source=ctx.providers.CartoDB.Voyager, zoom=zoom)
|
| 15 |
+
# elif mode == "basemap":
|
| 16 |
+
# extent = ax.get_extent(ccrs.PlateCarree())
|
| 17 |
+
# m = Basemap(projection='cyl',
|
| 18 |
+
# llcrnrlon=extent[0], urcrnrlon=extent[1],
|
| 19 |
+
# llcrnrlat=extent[2], urcrnrlat=extent[3],
|
| 20 |
+
# resolution='h', ax=ax)
|
| 21 |
+
# m.shadedrelief()
|
| 22 |
+
# m.drawcoastlines(linewidth=0.5)
|
| 23 |
+
# m.drawcountries(linewidth=0.7)
|
| 24 |
+
# m.drawmapboundary()
|
| 25 |
+
# else:
|
| 26 |
+
# raise ValueError(f"Unsupported basemap mode: {mode}")
|
| 27 |
+
# except Exception as e:
|
| 28 |
+
# print(f"[Relief Error - {mode} mode]:", e)
|
| 29 |
+
# ax.add_feature(cfeature.LAND)
|
| 30 |
+
# ax.add_feature(cfeature.OCEAN)
|
| 31 |
+
|
| 32 |
+
import os
|
| 33 |
+
import hashlib
|
| 34 |
+
import contextily as ctx
|
| 35 |
+
from mpl_toolkits.basemap import Basemap
|
| 36 |
+
import cartopy.crs as ccrs
|
| 37 |
+
import cartopy.feature as cfeature
|
| 38 |
+
from PIL import Image
|
| 39 |
+
import matplotlib.pyplot as plt
|
| 40 |
+
|
| 41 |
+
# Define cache directories
|
| 42 |
+
# Optional: Set tile cache directory (must be done before contextily downloads tiles)
|
| 43 |
+
os.environ["XDG_CACHE_HOME"] = os.path.expanduser("~/.contextily_cache")
|
| 44 |
+
|
| 45 |
+
CTX_TILE_CACHE_DIR = os.path.expanduser("~/.contextily_cache")
|
| 46 |
+
BASEMAP_TILE_CACHE_DIR = os.path.expanduser("~/.basemap_cache")
|
| 47 |
+
|
| 48 |
+
os.makedirs(CTX_TILE_CACHE_DIR, exist_ok=True)
|
| 49 |
+
os.makedirs(BASEMAP_TILE_CACHE_DIR, exist_ok=True)
|
| 50 |
+
|
| 51 |
+
def draw_etopo_basemap(ax, mode="basemap", zoom=11):
|
| 52 |
+
"""
|
| 53 |
+
Draws a high-resolution basemap background on the provided Cartopy GeoAxes.
|
| 54 |
+
|
| 55 |
+
Parameters
|
| 56 |
+
----------
|
| 57 |
+
ax : matplotlib.axes._subplots.AxesSubplot
|
| 58 |
+
The matplotlib Axes object (with Cartopy projection) to draw the map background on.
|
| 59 |
+
|
| 60 |
+
mode : str, optional
|
| 61 |
+
The basemap mode to use:
|
| 62 |
+
- "stock": Default stock image from Cartopy.
|
| 63 |
+
- "contextily": Web tile background (CartoDB Voyager), with caching.
|
| 64 |
+
- "basemap": High-resolution shaded relief using Basemap, with caching.
|
| 65 |
+
Default is "basemap".
|
| 66 |
+
|
| 67 |
+
zoom : int, optional
|
| 68 |
+
Tile zoom level (only for "contextily"). Higher = more detail. Default is 7.
|
| 69 |
+
|
| 70 |
+
Notes
|
| 71 |
+
-----
|
| 72 |
+
- Uses high resolution for Basemap (resolution='h') and saves figure at 300 DPI.
|
| 73 |
+
- Cached images are reused using extent-based hashing to avoid re-rendering.
|
| 74 |
+
- Basemap is deprecated; Cartopy with web tiles is recommended for new projects.
|
| 75 |
+
"""
|
| 76 |
+
try:
|
| 77 |
+
if mode == "stock":
|
| 78 |
+
ax.stock_img()
|
| 79 |
+
|
| 80 |
+
elif mode == "contextily":
|
| 81 |
+
extent = ax.get_extent(crs=ccrs.PlateCarree())
|
| 82 |
+
ax.set_extent(extent, crs=ccrs.PlateCarree())
|
| 83 |
+
ctx.add_basemap(
|
| 84 |
+
ax,
|
| 85 |
+
crs=ccrs.PlateCarree(),
|
| 86 |
+
source=ctx.providers.CartoDB.Voyager,
|
| 87 |
+
zoom=zoom
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
elif mode == "basemap":
|
| 91 |
+
extent = ax.get_extent(crs=ccrs.PlateCarree())
|
| 92 |
+
|
| 93 |
+
# Create a hash key for this extent
|
| 94 |
+
extent_str = f"{extent[0]:.4f}_{extent[1]:.4f}_{extent[2]:.4f}_{extent[3]:.4f}"
|
| 95 |
+
cache_key = hashlib.md5(extent_str.encode()).hexdigest()
|
| 96 |
+
cache_file = os.path.join(BASEMAP_TILE_CACHE_DIR, f"{cache_key}_highres.png")
|
| 97 |
+
|
| 98 |
+
if os.path.exists(cache_file):
|
| 99 |
+
img = Image.open(cache_file)
|
| 100 |
+
ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
|
| 101 |
+
else:
|
| 102 |
+
# Create a high-resolution temporary figure
|
| 103 |
+
temp_fig, temp_ax = plt.subplots(figsize=(12, 9),
|
| 104 |
+
subplot_kw={'projection': ccrs.PlateCarree()})
|
| 105 |
+
temp_ax.set_extent(extent, crs=ccrs.PlateCarree())
|
| 106 |
+
|
| 107 |
+
m = Basemap(projection='cyl',
|
| 108 |
+
llcrnrlon=extent[0], urcrnrlon=extent[1],
|
| 109 |
+
llcrnrlat=extent[2], urcrnrlat=extent[3],
|
| 110 |
+
resolution='f', ax=temp_ax) # 'h' = high resolution
|
| 111 |
+
|
| 112 |
+
m.shadedrelief()
|
| 113 |
+
# m.drawcoastlines(linewidth=0.1)
|
| 114 |
+
# m.drawcountries(linewidth=0.1)
|
| 115 |
+
# m.drawmapboundary()
|
| 116 |
+
|
| 117 |
+
# Save high-DPI figure for clarity
|
| 118 |
+
temp_fig.savefig(cache_file, dpi=300, bbox_inches='tight', pad_inches=0)
|
| 119 |
+
plt.close(temp_fig)
|
| 120 |
+
|
| 121 |
+
# Load and display the cached image
|
| 122 |
+
img = Image.open(cache_file)
|
| 123 |
+
ax.imshow(img, extent=extent, transform=ccrs.PlateCarree())
|
| 124 |
+
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(f"Unsupported basemap mode: {mode}")
|
| 127 |
+
|
| 128 |
+
except Exception as e:
|
| 129 |
+
print(f"[Relief Error - {mode} mode]:", e)
|
| 130 |
+
ax.add_feature(cfeature.LAND)
|
| 131 |
+
ax.add_feature(cfeature.OCEAN)
|
ash_animator/converter.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# # Full updated and corrected version of NAMEDataConverter with sanitized metadata keys
|
| 2 |
+
|
| 3 |
+
# import os
|
| 4 |
+
# import re
|
| 5 |
+
# import zipfile
|
| 6 |
+
# import shutil
|
| 7 |
+
# import numpy as np
|
| 8 |
+
# import xarray as xr
|
| 9 |
+
# import matplotlib.pyplot as plt
|
| 10 |
+
# import matplotlib.animation as animation
|
| 11 |
+
# from typing import List, Tuple
|
| 12 |
+
|
| 13 |
+
# class NAMEDataConverter:
|
| 14 |
+
# def __init__(self, output_dir: str):
|
| 15 |
+
# self.output_dir = output_dir
|
| 16 |
+
# os.makedirs(self.output_dir, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
# def _sanitize_key(self, key: str) -> str:
|
| 19 |
+
# # Replace non-alphanumeric characters with underscores, and ensure it starts with a letter
|
| 20 |
+
# key = re.sub(r'\W+', '_', key)
|
| 21 |
+
# if not key[0].isalpha():
|
| 22 |
+
# key = f"attr_{key}"
|
| 23 |
+
# return key
|
| 24 |
+
|
| 25 |
+
# def _parse_metadata(self, lines: List[str]) -> dict:
|
| 26 |
+
# metadata = {}
|
| 27 |
+
# for line in lines:
|
| 28 |
+
# if ":" in line:
|
| 29 |
+
# key, value = line.split(":", 1)
|
| 30 |
+
# clean_key = self._sanitize_key(key.strip().lower())
|
| 31 |
+
# metadata[clean_key] = value.strip()
|
| 32 |
+
|
| 33 |
+
# try:
|
| 34 |
+
# metadata.update({
|
| 35 |
+
# "x_origin": float(metadata["x_grid_origin"]),
|
| 36 |
+
# "y_origin": float(metadata["y_grid_origin"]),
|
| 37 |
+
# "x_size": int(metadata["x_grid_size"]),
|
| 38 |
+
# "y_size": int(metadata["y_grid_size"]),
|
| 39 |
+
# "x_res": float(metadata["x_grid_resolution"]),
|
| 40 |
+
# "y_res": float(metadata["y_grid_resolution"]),
|
| 41 |
+
# "prelim_cols": int(metadata["number_of_preliminary_cols"]),
|
| 42 |
+
# "n_fields": int(metadata["number_of_field_cols"]),
|
| 43 |
+
# })
|
| 44 |
+
# except KeyError as e:
|
| 45 |
+
# raise ValueError(f"Missing required metadata field: {e}")
|
| 46 |
+
# except ValueError as e:
|
| 47 |
+
# raise ValueError(f"Invalid value in metadata: {e}")
|
| 48 |
+
|
| 49 |
+
# if metadata["x_res"] == 0 or metadata["y_res"] == 0:
|
| 50 |
+
# raise ZeroDivisionError("Grid resolution cannot be zero.")
|
| 51 |
+
|
| 52 |
+
# return metadata
|
| 53 |
+
|
| 54 |
+
# def _get_data_lines(self, lines: List[str]) -> List[str]:
|
| 55 |
+
# idx = next(i for i, l in enumerate(lines) if l.strip() == "Fields:")
|
| 56 |
+
# return lines[idx + 1:]
|
| 57 |
+
|
| 58 |
+
# def convert_3d_group(self, group: List[Tuple[int, str]], output_filename: str) -> str:
|
| 59 |
+
# first_file_path = group[0][1]
|
| 60 |
+
# with open(first_file_path, 'r') as f:
|
| 61 |
+
# lines = f.readlines()
|
| 62 |
+
# meta = self._parse_metadata(lines)
|
| 63 |
+
|
| 64 |
+
# lons = np.round(np.arange(meta["x_origin"], meta["x_origin"] + meta["x_size"] * meta["x_res"], meta["x_res"]), 6)
|
| 65 |
+
# lats = np.round(np.arange(meta["y_origin"], meta["y_origin"] + meta["y_size"] * meta["y_res"], meta["y_res"]), 6)
|
| 66 |
+
|
| 67 |
+
# z_levels = []
|
| 68 |
+
# z_coords = []
|
| 69 |
+
|
| 70 |
+
# for z_idx, filepath in group:
|
| 71 |
+
# with open(filepath, 'r') as f:
|
| 72 |
+
# lines = f.readlines()
|
| 73 |
+
# data_lines = self._get_data_lines(lines)
|
| 74 |
+
# grid = np.zeros((meta["y_size"], meta["x_size"]), dtype=np.float32)
|
| 75 |
+
|
| 76 |
+
# for line in data_lines:
|
| 77 |
+
# parts = [p.strip().strip(',') for p in line.strip().split(',') if p.strip()]
|
| 78 |
+
# if len(parts) >= 5 and parts[0].isdigit() and parts[1].isdigit():
|
| 79 |
+
# try:
|
| 80 |
+
# x = int(parts[0]) - 1
|
| 81 |
+
# y = int(parts[1]) - 1
|
| 82 |
+
# val = float(parts[4])
|
| 83 |
+
# if 0 <= x < meta["x_size"] and 0 <= y < meta["y_size"]:
|
| 84 |
+
# grid[y, x] = val
|
| 85 |
+
# except Exception:
|
| 86 |
+
# continue
|
| 87 |
+
# z_levels.append(grid)
|
| 88 |
+
# z_coords.append(z_idx)
|
| 89 |
+
|
| 90 |
+
# z_cube = np.stack(z_levels, axis=0)
|
| 91 |
+
# ds = xr.Dataset(
|
| 92 |
+
# {
|
| 93 |
+
# "ash_concentration": (['altitude', 'latitude', 'longitude'], z_cube)
|
| 94 |
+
# },
|
| 95 |
+
# coords={
|
| 96 |
+
# "altitude": np.array(z_coords, dtype=np.float32),
|
| 97 |
+
# "latitude": lats,
|
| 98 |
+
# "longitude": lons
|
| 99 |
+
# },
|
| 100 |
+
# attrs={
|
| 101 |
+
# "title": "Volcanic Ash Concentration",
|
| 102 |
+
# "source": "NAME model output processed to NetCDF",
|
| 103 |
+
# **{k: str(v) for k, v in meta.items()} # Ensure all attrs are strings
|
| 104 |
+
# }
|
| 105 |
+
# )
|
| 106 |
+
# ds["ash_concentration"].attrs.update({
|
| 107 |
+
# "units": "g/m^3",
|
| 108 |
+
# "long_name": "Volcanic ash concentration"
|
| 109 |
+
# })
|
| 110 |
+
# ds["altitude"].attrs["units"] = "kilometers above sea level"
|
| 111 |
+
# ds["latitude"].attrs["units"] = "degrees_north"
|
| 112 |
+
# ds["longitude"].attrs["units"] = "degrees_east"
|
| 113 |
+
|
| 114 |
+
# out_path = os.path.join(self.output_dir, output_filename)
|
| 115 |
+
# ds.to_netcdf(out_path)
|
| 116 |
+
# return out_path
|
| 117 |
+
|
| 118 |
+
# def batch_process_zip(self, zip_path: str) -> List[str]:
|
| 119 |
+
# extract_dir = os.path.join(self.output_dir, "unzipped")
|
| 120 |
+
# os.makedirs(extract_dir, exist_ok=True)
|
| 121 |
+
|
| 122 |
+
# with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
| 123 |
+
# zip_ref.extractall(extract_dir)
|
| 124 |
+
|
| 125 |
+
# txt_files = []
|
| 126 |
+
# for root, _, files in os.walk(extract_dir):
|
| 127 |
+
# for file in files:
|
| 128 |
+
# if file.endswith(".txt"):
|
| 129 |
+
# txt_files.append(os.path.join(root, file))
|
| 130 |
+
|
| 131 |
+
# pattern = re.compile(r"_T(\d+)_.*_Z(\d+)\.txt$")
|
| 132 |
+
# grouped = {}
|
| 133 |
+
# for f in txt_files:
|
| 134 |
+
# match = pattern.search(f)
|
| 135 |
+
# if match:
|
| 136 |
+
# t = int(match.group(1))
|
| 137 |
+
# z = int(match.group(2))
|
| 138 |
+
# grouped.setdefault(t, []).append((z, f))
|
| 139 |
+
|
| 140 |
+
# nc_files = []
|
| 141 |
+
# for t_key in sorted(grouped):
|
| 142 |
+
# group = sorted(grouped[t_key])
|
| 143 |
+
# out_nc = self.convert_3d_group(group, f"T{t_key}.nc")
|
| 144 |
+
# nc_files.append(out_nc)
|
| 145 |
+
# return nc_files
|
| 146 |
+
|
| 147 |
+
# Re-defining the integrated class first
|
| 148 |
+
import os
|
| 149 |
+
import re
|
| 150 |
+
import zipfile
|
| 151 |
+
import numpy as np
|
| 152 |
+
import xarray as xr
|
| 153 |
+
from typing import List, Tuple
|
| 154 |
+
import shutil
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class NAMEDataProcessor:
|
| 158 |
+
def __init__(self, output_root: str):
|
| 159 |
+
self.output_root = output_root
|
| 160 |
+
self.output_3d = os.path.join(self.output_root, "3D")
|
| 161 |
+
self.output_horizontal = os.path.join(self.output_root, "horizontal")
|
| 162 |
+
os.makedirs(self.output_3d, exist_ok=True)
|
| 163 |
+
os.makedirs(self.output_horizontal, exist_ok=True)
|
| 164 |
+
|
| 165 |
+
def _sanitize_key(self, key: str) -> str:
|
| 166 |
+
key = re.sub(r'\W+', '_', key)
|
| 167 |
+
if not key[0].isalpha():
|
| 168 |
+
key = f"attr_{key}"
|
| 169 |
+
return key
|
| 170 |
+
|
| 171 |
+
def _parse_metadata(self, lines: List[str]) -> dict:
|
| 172 |
+
metadata = {}
|
| 173 |
+
for line in lines:
|
| 174 |
+
if ":" in line:
|
| 175 |
+
key, value = line.split(":", 1)
|
| 176 |
+
clean_key = self._sanitize_key(key.strip().lower())
|
| 177 |
+
metadata[clean_key] = value.strip()
|
| 178 |
+
|
| 179 |
+
try:
|
| 180 |
+
metadata.update({
|
| 181 |
+
"x_origin": float(metadata["x_grid_origin"]),
|
| 182 |
+
"y_origin": float(metadata["y_grid_origin"]),
|
| 183 |
+
"x_size": int(metadata["x_grid_size"]),
|
| 184 |
+
"y_size": int(metadata["y_grid_size"]),
|
| 185 |
+
"x_res": float(metadata["x_grid_resolution"]),
|
| 186 |
+
"y_res": float(metadata["y_grid_resolution"]),
|
| 187 |
+
})
|
| 188 |
+
except KeyError as e:
|
| 189 |
+
raise ValueError(f"Missing required metadata field: {e}")
|
| 190 |
+
except ValueError as e:
|
| 191 |
+
raise ValueError(f"Invalid value in metadata: {e}")
|
| 192 |
+
|
| 193 |
+
if metadata["x_res"] == 0 or metadata["y_res"] == 0:
|
| 194 |
+
raise ZeroDivisionError("Grid resolution cannot be zero.")
|
| 195 |
+
|
| 196 |
+
return metadata
|
| 197 |
+
|
| 198 |
+
def _get_data_lines(self, lines: List[str]) -> List[str]:
|
| 199 |
+
idx = next(i for i, l in enumerate(lines) if l.strip() == "Fields:")
|
| 200 |
+
return lines[idx + 1:]
|
| 201 |
+
|
| 202 |
+
def _is_horizontal_file(self, filename: str) -> bool:
|
| 203 |
+
return "HorizontalField" in filename
|
| 204 |
+
|
| 205 |
+
def _convert_horizontal(self, filepath: str, output_filename: str) -> str:
|
| 206 |
+
with open(filepath, 'r') as f:
|
| 207 |
+
lines = f.readlines()
|
| 208 |
+
|
| 209 |
+
meta = self._parse_metadata(lines)
|
| 210 |
+
data_lines = self._get_data_lines(lines)
|
| 211 |
+
|
| 212 |
+
lons = np.round(np.arange(meta["x_origin"], meta["x_origin"] + meta["x_size"] * meta["x_res"], meta["x_res"]), 6)
|
| 213 |
+
lats = np.round(np.arange(meta["y_origin"], meta["y_origin"] + meta["y_size"] * meta["y_res"], meta["y_res"]), 6)
|
| 214 |
+
|
| 215 |
+
air_conc = np.zeros((meta["y_size"], meta["x_size"]), dtype=np.float32)
|
| 216 |
+
dry_depo = np.zeros((meta["y_size"], meta["x_size"]), dtype=np.float32)
|
| 217 |
+
wet_depo = np.zeros((meta["y_size"], meta["x_size"]), dtype=np.float32)
|
| 218 |
+
|
| 219 |
+
for line in data_lines:
|
| 220 |
+
parts = [p.strip().strip(',') for p in line.strip().split(',') if p.strip()]
|
| 221 |
+
if len(parts) >= 7 and parts[0].isdigit() and parts[1].isdigit():
|
| 222 |
+
try:
|
| 223 |
+
x = int(parts[0]) - 1
|
| 224 |
+
y = int(parts[1]) - 1
|
| 225 |
+
air_val = float(parts[4])
|
| 226 |
+
dry_val = float(parts[5])
|
| 227 |
+
wet_val = float(parts[6])
|
| 228 |
+
if 0 <= x < meta["x_size"] and 0 <= y < meta["y_size"]:
|
| 229 |
+
air_conc[y, x] = air_val
|
| 230 |
+
dry_depo[y, x] = dry_val
|
| 231 |
+
wet_depo[y, x] = wet_val
|
| 232 |
+
except Exception:
|
| 233 |
+
continue
|
| 234 |
+
|
| 235 |
+
ds = xr.Dataset(
|
| 236 |
+
{
|
| 237 |
+
"air_concentration": (['latitude', 'longitude'], air_conc),
|
| 238 |
+
"dry_deposition_rate": (['latitude', 'longitude'], dry_depo),
|
| 239 |
+
"wet_deposition_rate": (['latitude', 'longitude'], wet_depo)
|
| 240 |
+
},
|
| 241 |
+
coords={
|
| 242 |
+
"latitude": lats,
|
| 243 |
+
"longitude": lons
|
| 244 |
+
},
|
| 245 |
+
attrs={
|
| 246 |
+
"title": "Volcanic Ash Horizontal Output (Multiple Fields)",
|
| 247 |
+
"source": "NAME model output processed to NetCDF (horizontal multi-field)",
|
| 248 |
+
**{k: str(v) for k, v in meta.items()}
|
| 249 |
+
}
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
ds["air_concentration"].attrs.update({
|
| 253 |
+
"units": "g/m^3",
|
| 254 |
+
"long_name": "Boundary Layer Average Air Concentration"
|
| 255 |
+
})
|
| 256 |
+
ds["dry_deposition_rate"].attrs.update({
|
| 257 |
+
"units": "g/m^2/s",
|
| 258 |
+
"long_name": "Dry Deposition Rate"
|
| 259 |
+
})
|
| 260 |
+
ds["wet_deposition_rate"].attrs.update({
|
| 261 |
+
"units": "g/m^2/s",
|
| 262 |
+
"long_name": "Wet Deposition Rate"
|
| 263 |
+
})
|
| 264 |
+
ds["latitude"].attrs["units"] = "degrees_north"
|
| 265 |
+
ds["longitude"].attrs["units"] = "degrees_east"
|
| 266 |
+
|
| 267 |
+
out_path = os.path.join(self.output_horizontal, output_filename)
|
| 268 |
+
ds.to_netcdf(out_path, engine="netcdf4")
|
| 269 |
+
|
| 270 |
+
return out_path
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _convert_3d_group(self, group: List[Tuple[int, str]], output_filename: str) -> str:
|
| 274 |
+
first_file_path = group[0][1]
|
| 275 |
+
with open(first_file_path, 'r') as f:
|
| 276 |
+
lines = f.readlines()
|
| 277 |
+
meta = self._parse_metadata(lines)
|
| 278 |
+
|
| 279 |
+
lons = np.round(np.arange(meta["x_origin"], meta["x_origin"] + meta["x_size"] * meta["x_res"], meta["x_res"]), 6)
|
| 280 |
+
lats = np.round(np.arange(meta["y_origin"], meta["y_origin"] + meta["y_size"] * meta["y_res"], meta["y_res"]), 6)
|
| 281 |
+
|
| 282 |
+
z_levels = []
|
| 283 |
+
z_coords = []
|
| 284 |
+
|
| 285 |
+
for z_idx, filepath in group:
|
| 286 |
+
with open(filepath, 'r') as f:
|
| 287 |
+
lines = f.readlines()
|
| 288 |
+
data_lines = self._get_data_lines(lines)
|
| 289 |
+
grid = np.zeros((meta["y_size"], meta["x_size"]), dtype=np.float32)
|
| 290 |
+
|
| 291 |
+
for line in data_lines:
|
| 292 |
+
parts = [p.strip().strip(',') for p in line.strip().split(',') if p.strip()]
|
| 293 |
+
if len(parts) >= 5 and parts[0].isdigit() and parts[1].isdigit():
|
| 294 |
+
try:
|
| 295 |
+
x = int(parts[0]) - 1
|
| 296 |
+
y = int(parts[1]) - 1
|
| 297 |
+
val = float(parts[4])
|
| 298 |
+
if 0 <= x < meta["x_size"] and 0 <= y < meta["y_size"]:
|
| 299 |
+
grid[y, x] = val
|
| 300 |
+
except Exception:
|
| 301 |
+
continue
|
| 302 |
+
z_levels.append(grid)
|
| 303 |
+
z_coords.append(z_idx)
|
| 304 |
+
|
| 305 |
+
z_cube = np.stack(z_levels, axis=0)
|
| 306 |
+
ds = xr.Dataset(
|
| 307 |
+
{
|
| 308 |
+
"ash_concentration": (['altitude', 'latitude', 'longitude'], z_cube)
|
| 309 |
+
},
|
| 310 |
+
coords={
|
| 311 |
+
"altitude": np.array(z_coords, dtype=np.float32),
|
| 312 |
+
"latitude": lats,
|
| 313 |
+
"longitude": lons
|
| 314 |
+
},
|
| 315 |
+
attrs={
|
| 316 |
+
"title": "Volcanic Ash Concentration (3D)",
|
| 317 |
+
"source": "NAME model output processed to NetCDF (3D fields)",
|
| 318 |
+
**{k: str(v) for k, v in meta.items()}
|
| 319 |
+
}
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
out_path = os.path.join(self.output_3d, output_filename)
|
| 323 |
+
|
| 324 |
+
# 🔥 Check if file exists, delete it first
|
| 325 |
+
# if os.path.exists(out_path):
|
| 326 |
+
# os.remove(out_path)
|
| 327 |
+
|
| 328 |
+
# 🔥 Save NetCDF safely using netCDF4
|
| 329 |
+
ds.to_netcdf(out_path, engine="netcdf4")
|
| 330 |
+
|
| 331 |
+
return out_path
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def batch_process_zip(self, zip_path: str) -> List[str]:
|
| 335 |
+
extract_dir = os.path.abspath("unzipped")
|
| 336 |
+
|
| 337 |
+
os.makedirs(extract_dir, exist_ok=True)
|
| 338 |
+
|
| 339 |
+
###
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# Function to empty folder contents
|
| 343 |
+
def empty_folder(folder_path):
|
| 344 |
+
import os
|
| 345 |
+
import glob
|
| 346 |
+
files = glob.glob(os.path.join(folder_path, '*'))
|
| 347 |
+
for f in files:
|
| 348 |
+
try:
|
| 349 |
+
os.remove(f)
|
| 350 |
+
except IsADirectoryError:
|
| 351 |
+
shutil.rmtree(f)
|
| 352 |
+
|
| 353 |
+
# 🛠 Clear cached open files and garbage collect before deleting
|
| 354 |
+
|
| 355 |
+
# 🔥 Empty previous outputs, do not delete folders
|
| 356 |
+
if os.path.exists(self.output_3d):
|
| 357 |
+
empty_folder(self.output_3d)
|
| 358 |
+
else:
|
| 359 |
+
os.makedirs(self.output_3d, exist_ok=True)
|
| 360 |
+
|
| 361 |
+
# if os.path.exists(self.output_horizontal):
|
| 362 |
+
# empty_folder(self.output_horizontal)
|
| 363 |
+
# else:
|
| 364 |
+
# os.makedirs(self.output_horizontal, exist_ok=True)
|
| 365 |
+
|
| 366 |
+
# if os.path.exists(extract_dir):
|
| 367 |
+
# shutil.rmtree(extract_dir)
|
| 368 |
+
# os.makedirs(extract_dir, exist_ok=True)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
#####
|
| 375 |
+
|
| 376 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
| 377 |
+
zip_ref.extractall(extract_dir)
|
| 378 |
+
|
| 379 |
+
txt_files = []
|
| 380 |
+
for root, _, files in os.walk(extract_dir):
|
| 381 |
+
for file in files:
|
| 382 |
+
if file.endswith(".txt"):
|
| 383 |
+
txt_files.append(os.path.join(root, file))
|
| 384 |
+
|
| 385 |
+
horizontal_files = []
|
| 386 |
+
grouped_3d = {}
|
| 387 |
+
|
| 388 |
+
pattern = re.compile(r"_T(\d+)_.*_Z(\d+)\.txt$")
|
| 389 |
+
|
| 390 |
+
for f in txt_files:
|
| 391 |
+
if self._is_horizontal_file(f):
|
| 392 |
+
horizontal_files.append(f)
|
| 393 |
+
else:
|
| 394 |
+
match = pattern.search(f)
|
| 395 |
+
if match:
|
| 396 |
+
t = int(match.group(1))
|
| 397 |
+
z = int(match.group(2))
|
| 398 |
+
grouped_3d.setdefault(t, []).append((z, f))
|
| 399 |
+
|
| 400 |
+
nc_files = []
|
| 401 |
+
|
| 402 |
+
# Process horizontal
|
| 403 |
+
for f in sorted(horizontal_files):
|
| 404 |
+
base_name = os.path.splitext(os.path.basename(f))[0]
|
| 405 |
+
out_nc = self._convert_horizontal(f, f"{base_name}.nc")
|
| 406 |
+
nc_files.append(out_nc)
|
| 407 |
+
|
| 408 |
+
# Process 3D
|
| 409 |
+
for t_key in sorted(grouped_3d):
|
| 410 |
+
group = sorted(grouped_3d[t_key])
|
| 411 |
+
out_nc = self._convert_3d_group(group, f"T{t_key}.nc")
|
| 412 |
+
nc_files.append(out_nc)
|
| 413 |
+
|
| 414 |
+
return nc_files
|
ash_animator/export.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import matplotlib.ticker as mticker
|
| 6 |
+
import cartopy.crs as ccrs
|
| 7 |
+
import cartopy.feature as cfeature
|
| 8 |
+
from .interpolation import interpolate_grid
|
| 9 |
+
from .basemaps import draw_etopo_basemap
|
| 10 |
+
|
| 11 |
+
def export_frames_as_jpgs(animator, output_folder: str, include_metadata: bool = True):
|
| 12 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 13 |
+
|
| 14 |
+
meta = animator.datasets[0].attrs
|
| 15 |
+
legend_text = (
|
| 16 |
+
f"Run name: {meta.get('run_name', 'N/A')}\n"
|
| 17 |
+
f"Run time: {meta.get('run_time', 'N/A')}\n"
|
| 18 |
+
f"Met data: {meta.get('met_data', 'N/A')}\n"
|
| 19 |
+
f"Start of release: {meta.get('start_of_release', 'N/A')}\n"
|
| 20 |
+
f"End of release: {meta.get('end_of_release', 'N/A')}\n"
|
| 21 |
+
f"Source strength: {meta.get('source_strength', 'N/A')} g / s\n"
|
| 22 |
+
f"Release location: {meta.get('release_location', 'N/A')}\n"
|
| 23 |
+
f"Release height: {meta.get('release_height', 'N/A')} m asl\n"
|
| 24 |
+
f"Run duration: {meta.get('run_duration', 'N/A')}"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
for z_index, z_val in enumerate(animator.levels):
|
| 28 |
+
z_dir = os.path.join(output_folder, f"ash_T1-Tn_Z{z_index+1}")
|
| 29 |
+
os.makedirs(z_dir, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
valid_mask = np.stack([
|
| 32 |
+
ds['ash_concentration'].values[z_index] for ds in animator.datasets
|
| 33 |
+
]).max(axis=0) > 0
|
| 34 |
+
y_idx, x_idx = np.where(valid_mask)
|
| 35 |
+
|
| 36 |
+
if y_idx.size == 0 or x_idx.size == 0:
|
| 37 |
+
print(f"Z level {z_val} km has no valid data. Skipping...")
|
| 38 |
+
continue
|
| 39 |
+
|
| 40 |
+
y_min, y_max = y_idx.min(), y_idx.max()
|
| 41 |
+
x_min, x_max = x_idx.min(), x_idx.max()
|
| 42 |
+
|
| 43 |
+
for t in range(len(animator.datasets)):
|
| 44 |
+
data = animator.datasets[t]['ash_concentration'].values[z_index]
|
| 45 |
+
interp = interpolate_grid(data, animator.lon_grid, animator.lat_grid)
|
| 46 |
+
if np.isfinite(interp).sum() == 0:
|
| 47 |
+
continue
|
| 48 |
+
|
| 49 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 8), subplot_kw={'projection': ccrs.PlateCarree()})
|
| 50 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 51 |
+
min_val = np.nanmin(valid_vals)
|
| 52 |
+
max_val = np.nanmax(valid_vals)
|
| 53 |
+
log_cutoff = 1e-3
|
| 54 |
+
log_ratio = max_val / (min_val + 1e-6)
|
| 55 |
+
use_log = min_val > log_cutoff and log_ratio > 100
|
| 56 |
+
|
| 57 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 58 |
+
data_for_plot = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 59 |
+
scale_label = "Hybrid Log" if use_log else "Linear"
|
| 60 |
+
|
| 61 |
+
# Plot full
|
| 62 |
+
c1 = ax1.contourf(animator.lons, animator.lats, data_for_plot, levels=levels,
|
| 63 |
+
cmap="rainbow", alpha=0.6, transform=ccrs.PlateCarree())
|
| 64 |
+
draw_etopo_basemap(ax1, mode='stock')
|
| 65 |
+
ax1.set_extent([animator.lons.min(), animator.lons.max(), animator.lats.min(), animator.lats.max()])
|
| 66 |
+
ax1.set_title(f"T{t+1} | Alt: {z_val} km (Full - {scale_label})")
|
| 67 |
+
ax1.coastlines(); ax1.add_feature(cfeature.BORDERS)
|
| 68 |
+
ax1.add_feature(cfeature.LAND); ax1.add_feature(cfeature.OCEAN)
|
| 69 |
+
|
| 70 |
+
# Zoom region
|
| 71 |
+
buffer_y = int((y_max - y_min) * 0.5)
|
| 72 |
+
buffer_x = int((x_max - x_min) * 0.5)
|
| 73 |
+
|
| 74 |
+
y_start = max(0, y_min - buffer_y)
|
| 75 |
+
y_end = min(data_for_plot.shape[0], y_max + buffer_y + 1)
|
| 76 |
+
x_start = max(0, x_min - buffer_x)
|
| 77 |
+
x_end = min(data_for_plot.shape[1], x_max + buffer_x + 1)
|
| 78 |
+
|
| 79 |
+
zoom = data_for_plot[y_start:y_end, x_start:x_end]
|
| 80 |
+
lon_zoom = animator.lons[x_start:x_end]
|
| 81 |
+
lat_zoom = animator.lats[y_start:y_end]
|
| 82 |
+
|
| 83 |
+
c2 = ax2.contourf(lon_zoom, lat_zoom, zoom, levels=levels,
|
| 84 |
+
cmap="rainbow", alpha=0.6, transform=ccrs.PlateCarree())
|
| 85 |
+
draw_etopo_basemap(ax2, mode='stock')
|
| 86 |
+
ax2.set_extent([lon_zoom.min(), lon_zoom.max(), lat_zoom.min(), lat_zoom.max()])
|
| 87 |
+
ax2.set_title(f"T{t+1} | Alt: {z_val} km (Zoom - {scale_label})")
|
| 88 |
+
ax2.coastlines(); ax2.add_feature(cfeature.BORDERS)
|
| 89 |
+
ax2.add_feature(cfeature.LAND); ax2.add_feature(cfeature.OCEAN)
|
| 90 |
+
|
| 91 |
+
for ax in [ax1, ax2]:
|
| 92 |
+
ax.text(0.01, 0.98, f"Time step T{t+1}", transform=ax.transAxes,
|
| 93 |
+
fontsize=9, color='white', va='top', ha='left',
|
| 94 |
+
bbox=dict(facecolor='black', alpha=0.4, boxstyle='round'))
|
| 95 |
+
|
| 96 |
+
if include_metadata:
|
| 97 |
+
for ax in [ax1, ax2]:
|
| 98 |
+
ax.text(0.01, 0.01,
|
| 99 |
+
f"Source: NAME model\nRes: {animator.x_res:.2f}°\n{meta.get('run_name', 'N/A')}",
|
| 100 |
+
transform=ax.transAxes, fontsize=8, color='white',
|
| 101 |
+
bbox=dict(facecolor='black', alpha=0.5))
|
| 102 |
+
ax1.annotate(legend_text, xy=(0.75, 0.99), xycoords='axes fraction',
|
| 103 |
+
fontsize=8, ha='left', va='top',
|
| 104 |
+
bbox=dict(boxstyle="round", facecolor="white", edgecolor="gray"),
|
| 105 |
+
annotation_clip=False)
|
| 106 |
+
|
| 107 |
+
cbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical', shrink=0.75, pad=0.03)
|
| 108 |
+
cbar.set_label("Ash concentration (g/m³)")
|
| 109 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 110 |
+
cbar.ax.yaxis.set_major_formatter(formatter)
|
| 111 |
+
|
| 112 |
+
if use_log:
|
| 113 |
+
cbar.ax.text(1.1, 1.02, "log scale", transform=cbar.ax.transAxes,
|
| 114 |
+
fontsize=9, color='gray', rotation=90, ha='left', va='bottom')
|
| 115 |
+
|
| 116 |
+
frame_path = os.path.join(z_dir, f"frame_{t+1:04d}.jpg")
|
| 117 |
+
plt.savefig(frame_path, dpi=150, bbox_inches='tight')
|
| 118 |
+
plt.close(fig)
|
| 119 |
+
print(f"Saved {frame_path}")
|
ash_animator/interpolation.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.interpolate import griddata
|
| 4 |
+
|
| 5 |
+
def interpolate_grid(data, lon_grid, lat_grid):
|
| 6 |
+
data = np.where(data < 0, np.nan, data)
|
| 7 |
+
mask = data > 0
|
| 8 |
+
if np.count_nonzero(mask) < 10:
|
| 9 |
+
return np.full_like(data, np.nan)
|
| 10 |
+
|
| 11 |
+
points = np.column_stack((lon_grid[mask], lat_grid[mask]))
|
| 12 |
+
values = data[mask]
|
| 13 |
+
grid_z = griddata(points, values, (lon_grid, lat_grid), method='cubic')
|
| 14 |
+
return np.where(grid_z < 0, 0, grid_z)
|
ash_animator/plot_3dfield_data.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import matplotlib.animation as animation
|
| 5 |
+
import matplotlib.ticker as mticker
|
| 6 |
+
import cartopy.crs as ccrs
|
| 7 |
+
import cartopy.feature as cfeature
|
| 8 |
+
import cartopy.io.shapereader as shpreader
|
| 9 |
+
from adjustText import adjust_text
|
| 10 |
+
from .interpolation import interpolate_grid
|
| 11 |
+
from .basemaps import draw_etopo_basemap
|
| 12 |
+
import imageio.v2 as imageio
|
| 13 |
+
import shutil
|
| 14 |
+
|
| 15 |
+
class Plot_3DField_Data:
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
A class for visualizing 3D spatiotemporal field data (e.g., ash concentration) across time and altitude levels.
|
| 19 |
+
|
| 20 |
+
This class uses matplotlib and cartopy to create:
|
| 21 |
+
- Animated GIFs of spatial fields at given altitudes
|
| 22 |
+
- Vertical profile animations over time
|
| 23 |
+
- Exported static frames with metadata annotations and zoomed views
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
animator : object
|
| 28 |
+
A container holding the dataset, including:
|
| 29 |
+
- datasets: list of xarray-like DataArrays with 'ash_concentration'
|
| 30 |
+
- lons, lats: 1D longitude and latitude arrays
|
| 31 |
+
- lat_grid, lon_grid: 2D grid arrays for spatial mapping
|
| 32 |
+
- levels: 1D array of vertical altitude levels (e.g., in km)
|
| 33 |
+
output_dir : str
|
| 34 |
+
Base directory for saving all outputs. Defaults to "plots".
|
| 35 |
+
cmap : str
|
| 36 |
+
Matplotlib colormap name. Defaults to "rainbow".
|
| 37 |
+
fps : int
|
| 38 |
+
Frames per second for GIFs. Defaults to 2.
|
| 39 |
+
include_metadata : bool
|
| 40 |
+
Whether to annotate each figure with simulation metadata. Defaults to True.
|
| 41 |
+
threshold : float
|
| 42 |
+
Value threshold (e.g., in g/m³) to highlight exceedances. Defaults to 0.1.
|
| 43 |
+
zoom_width_deg : float
|
| 44 |
+
Width of the zoomed-in region in degrees. Defaults to 6.0.
|
| 45 |
+
zoom_height_deg : float
|
| 46 |
+
Height of the zoomed-in region in degrees. Defaults to 6.0.
|
| 47 |
+
zoom_level : int
|
| 48 |
+
Zoom level passed to basemap drawing. Defaults to 7.
|
| 49 |
+
basemap_type : str
|
| 50 |
+
Type of basemap to draw (passed to draw_etopo_basemap). Defaults to "basemap".
|
| 51 |
+
|
| 52 |
+
Methods
|
| 53 |
+
-------
|
| 54 |
+
plot_single_z_level(z_km, filename)
|
| 55 |
+
Generate animation over time at a specific altitude level.
|
| 56 |
+
|
| 57 |
+
plot_vertical_profile_at_time(t_index, filename=None)
|
| 58 |
+
Generate vertical profile GIF for a single timestep.
|
| 59 |
+
|
| 60 |
+
animate_altitude(t_index, output_path)
|
| 61 |
+
Animate altitude slices for one timestep.
|
| 62 |
+
|
| 63 |
+
animate_all_altitude_profiles(output_folder='altitude_profiles')
|
| 64 |
+
Generate vertical animations for all time steps.
|
| 65 |
+
|
| 66 |
+
export_frames_as_jpgs(include_metadata=True)
|
| 67 |
+
Export individual frames as static `.jpg` images with annotations.
|
| 68 |
+
"""
|
| 69 |
+
def __init__(self, animator, output_dir="plots", cmap="rainbow", fps=2,
|
| 70 |
+
include_metadata=True, threshold=0.1,
|
| 71 |
+
zoom_width_deg=6.0, zoom_height_deg=6.0, zoom_level=7, basemap_type="basemap"):
|
| 72 |
+
self.animator = animator
|
| 73 |
+
self.output_dir = os.path.abspath(os.path.join(os.getcwd(), output_dir))
|
| 74 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
| 75 |
+
self.cmap = cmap
|
| 76 |
+
self.fps = fps
|
| 77 |
+
self.include_metadata = include_metadata
|
| 78 |
+
self.threshold = threshold
|
| 79 |
+
self.zoom_width = zoom_width_deg
|
| 80 |
+
self.zoom_height = zoom_height_deg
|
| 81 |
+
shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 82 |
+
self.country_geoms = list(shpreader.Reader(shp).records())
|
| 83 |
+
self.zoom_level=zoom_level
|
| 84 |
+
self.basemap_type=basemap_type
|
| 85 |
+
|
| 86 |
+
#############3
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Load shapefile once
|
| 90 |
+
countries_shp = shpreader.natural_earth(
|
| 91 |
+
resolution='110m',
|
| 92 |
+
category='cultural',
|
| 93 |
+
name='admin_0_countries'
|
| 94 |
+
)
|
| 95 |
+
self.country_geoms = list(shpreader.Reader(countries_shp).records())
|
| 96 |
+
|
| 97 |
+
# Cache extent bounds
|
| 98 |
+
self.lon_min = np.min(self.animator.lons)
|
| 99 |
+
self.lon_max = np.max(self.animator.lons)
|
| 100 |
+
self.lat_min = np.min(self.animator.lats)
|
| 101 |
+
self.lat_max = np.max(self.animator.lats)
|
| 102 |
+
|
| 103 |
+
#####################3
|
| 104 |
+
|
| 105 |
+
def _make_dirs(self, path):
|
| 106 |
+
path = os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(path)))
|
| 107 |
+
os.makedirs(path, exist_ok=True)
|
| 108 |
+
|
| 109 |
+
def _get_zoom_indices(self, center_lat, center_lon):
|
| 110 |
+
lon_min = center_lon - self.zoom_width / 2
|
| 111 |
+
lon_max = center_lon + self.zoom_width / 2
|
| 112 |
+
lat_min = center_lat - self.zoom_height / 2
|
| 113 |
+
lat_max = center_lat + self.zoom_height / 2
|
| 114 |
+
lat_idx = np.where((self.animator.lats >= lat_min) & (self.animator.lats <= lat_max))[0]
|
| 115 |
+
lon_idx = np.where((self.animator.lons >= lon_min) & (self.animator.lons <= lon_max))[0]
|
| 116 |
+
return lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max
|
| 117 |
+
|
| 118 |
+
def _get_max_concentration_location(self):
|
| 119 |
+
max_conc = -np.inf
|
| 120 |
+
center_lat = center_lon = None
|
| 121 |
+
for ds in self.animator.datasets:
|
| 122 |
+
for z in range(len(self.animator.levels)):
|
| 123 |
+
data = ds['ash_concentration'].values[z]
|
| 124 |
+
if np.max(data) > max_conc:
|
| 125 |
+
max_conc = np.max(data)
|
| 126 |
+
max_idx = np.unravel_index(np.argmax(data), data.shape)
|
| 127 |
+
center_lat = self.animator.lat_grid[max_idx]
|
| 128 |
+
center_lon = self.animator.lon_grid[max_idx]
|
| 129 |
+
return center_lat, center_lon
|
| 130 |
+
|
| 131 |
+
def _add_country_labels(self, ax, extent):
|
| 132 |
+
proj = ccrs.PlateCarree()
|
| 133 |
+
texts = []
|
| 134 |
+
for country in self.country_geoms:
|
| 135 |
+
name = country.attributes['NAME_LONG']
|
| 136 |
+
geom = country.geometry
|
| 137 |
+
try:
|
| 138 |
+
lon, lat = geom.centroid.x, geom.centroid.y
|
| 139 |
+
if extent[0] <= lon <= extent[1] and extent[2] <= lat <= extent[3]:
|
| 140 |
+
text = ax.text(lon, lat, name, fontsize=6, transform=proj,
|
| 141 |
+
ha='center', va='center', color='white',
|
| 142 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 143 |
+
texts.append(text)
|
| 144 |
+
except:
|
| 145 |
+
continue
|
| 146 |
+
adjust_text(texts, ax=ax, only_move={'points': 'y', 'text': 'y'},
|
| 147 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 148 |
+
|
| 149 |
+
def _plot_frame(self, ax, data, lons, lats, title, levels, scale_label, proj):
|
| 150 |
+
draw_etopo_basemap(ax, mode=self.basemap_type, zoom=self.zoom_level)
|
| 151 |
+
c = ax.contourf(lons, lats, data, levels=levels, cmap=self.cmap, alpha=0.6, transform=proj)
|
| 152 |
+
ax.contour(lons, lats, data, levels=levels, colors='black', linewidths=0.5, transform=proj)
|
| 153 |
+
ax.set_title(title)
|
| 154 |
+
ax.set_extent([lons.min(), lons.max(), lats.min(), lats.max()])
|
| 155 |
+
ax.coastlines()
|
| 156 |
+
ax.add_feature(cfeature.BORDERS, linestyle=':')
|
| 157 |
+
ax.add_feature(cfeature.LAND)
|
| 158 |
+
ax.add_feature(cfeature.OCEAN)
|
| 159 |
+
return c
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# metadata placement function and usage
|
| 164 |
+
|
| 165 |
+
def _draw_metadata_sidebar(self, fig, meta_dict):
|
| 166 |
+
lines = [
|
| 167 |
+
f"Run name: {meta_dict.get('run_name', 'N/A')}",
|
| 168 |
+
f"Run time: {meta_dict.get('run_time', 'N/A')}",
|
| 169 |
+
f"Met data: {meta_dict.get('met_data', 'N/A')}",
|
| 170 |
+
f"Start release: {meta_dict.get('start_of_release', 'N/A')}",
|
| 171 |
+
f"End release: {meta_dict.get('end_of_release', 'N/A')}",
|
| 172 |
+
f"Source strength: {meta_dict.get('source_strength', 'N/A')} g/s",
|
| 173 |
+
f"Release loc: {meta_dict.get('release_location', 'N/A')}",
|
| 174 |
+
f"Release height: {meta_dict.get('release_height', 'N/A')} m asl",
|
| 175 |
+
f"Run duration: {meta_dict.get('run_duration', 'N/A')}"
|
| 176 |
+
]
|
| 177 |
+
full_text = "\n".join(lines) # ✅ actual newlines
|
| 178 |
+
fig.text(0.1, 0.095, full_text, va='center', ha='left',
|
| 179 |
+
fontsize=9, family='monospace', color='black',
|
| 180 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def plot_single_z_level(self, z_km, filename="z_level.gif"):
|
| 185 |
+
|
| 186 |
+
if z_km not in self.animator.levels:
|
| 187 |
+
print(f"Z level {z_km} km not found.")
|
| 188 |
+
return
|
| 189 |
+
z_index = np.where(self.animator.levels == z_km)[0][0]
|
| 190 |
+
output_path = os.path.join(self.output_dir, "z_levels", filename)
|
| 191 |
+
fig = plt.figure(figsize=(16, 8))
|
| 192 |
+
proj = ccrs.PlateCarree()
|
| 193 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 194 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 195 |
+
|
| 196 |
+
center_lat, center_lon = self._get_max_concentration_location()
|
| 197 |
+
lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 198 |
+
lat_zoom = self.animator.lats[lat_idx]
|
| 199 |
+
lon_zoom = self.animator.lons[lon_idx]
|
| 200 |
+
lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
meta = self.animator.datasets[0].attrs
|
| 205 |
+
valid_frames = []
|
| 206 |
+
for t in range(len(self.animator.datasets)):
|
| 207 |
+
interp = interpolate_grid(self.animator.datasets[t]['ash_concentration'].values[z_index],
|
| 208 |
+
self.animator.lon_grid, self.animator.lat_grid)
|
| 209 |
+
if np.isfinite(interp).sum() > 0:
|
| 210 |
+
valid_frames.append(t)
|
| 211 |
+
if not valid_frames:
|
| 212 |
+
print(f"No valid frames for Z={z_km} km.")
|
| 213 |
+
plt.close()
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
def update(t):
|
| 217 |
+
ax1.clear()
|
| 218 |
+
ax2.clear()
|
| 219 |
+
|
| 220 |
+
data = self.animator.datasets[t]['ash_concentration'].values[z_index]
|
| 221 |
+
interp = interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 222 |
+
interp = np.where(interp < 0, np.nan, interp)
|
| 223 |
+
zoom_plot = interp[np.ix_(lat_idx, lon_idx)]
|
| 224 |
+
|
| 225 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 226 |
+
if valid_vals.size == 0:
|
| 227 |
+
return []
|
| 228 |
+
|
| 229 |
+
min_val, max_val = np.nanmin(valid_vals), np.nanmax(valid_vals)
|
| 230 |
+
log_cutoff = 1e-3
|
| 231 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 232 |
+
|
| 233 |
+
levels = (
|
| 234 |
+
np.logspace(np.log10(log_cutoff), np.log10(max_val), 20)
|
| 235 |
+
if use_log else
|
| 236 |
+
np.linspace(0, max_val, 20)
|
| 237 |
+
)
|
| 238 |
+
data_for_plot = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 239 |
+
scale_label = "Log" if use_log else "Linear"
|
| 240 |
+
|
| 241 |
+
c = self._plot_frame(ax1, data_for_plot, self.animator.lons, self.animator.lats,
|
| 242 |
+
f"T{t+1} | Alt: {z_km} km (Full - {scale_label})", levels, scale_label, proj)
|
| 243 |
+
self._plot_frame(ax2, zoom_plot, lon_zoom, lat_zoom,
|
| 244 |
+
f"T{t} | Alt: {z_km} km (Zoom - {scale_label})", levels, scale_label, proj)
|
| 245 |
+
|
| 246 |
+
self._add_country_labels(ax1, [self.animator.lons.min(), self.animator.lons.max(),
|
| 247 |
+
self.animator.lats.min(), self.animator.lats.max()])
|
| 248 |
+
self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 249 |
+
|
| 250 |
+
if not hasattr(update, "colorbar"):
|
| 251 |
+
update.colorbar = fig.colorbar(c, ax=[ax1, ax2], orientation='vertical',
|
| 252 |
+
label="Ash concentration (g/m³)")
|
| 253 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 254 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 255 |
+
|
| 256 |
+
# ✅ Draw threshold outline and label only if exceeded
|
| 257 |
+
if np.nanmax(valid_vals) > self.threshold:
|
| 258 |
+
ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 259 |
+
colors='red', linewidths=2, transform=proj)
|
| 260 |
+
ax2.contour(lon_zoom, lat_zoom, zoom_plot, levels=[self.threshold],
|
| 261 |
+
colors='red', linewidths=2, transform=proj)
|
| 262 |
+
ax2.text(0.99, 0.01, f"⚠ Max Thresold Exceed: {np.nanmax(valid_vals):.2f} > {self.threshold} g/m³",
|
| 263 |
+
transform=ax2.transAxes, ha='right', va='bottom',
|
| 264 |
+
fontsize=9, color='red',
|
| 265 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 266 |
+
|
| 267 |
+
return []
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
self._draw_metadata_sidebar(fig, meta)
|
| 273 |
+
self._make_dirs(output_path)
|
| 274 |
+
fig.tight_layout()
|
| 275 |
+
ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False, cache_frame_data =False)
|
| 276 |
+
ani.save(output_path, writer='pillow', fps=self.fps, dpi=300)
|
| 277 |
+
plt.close()
|
| 278 |
+
print(f"✅ Saved Z-level animation to {output_path}")
|
| 279 |
+
|
| 280 |
+
def plot_vertical_profile_at_time(self, t_index, filename=None):
|
| 281 |
+
time_label = f"T{t_index+1}"
|
| 282 |
+
for z_index, z_val in enumerate(self.animator.levels):
|
| 283 |
+
filename = f"TimeSlices_Z{z_val:.1f}km.gif"
|
| 284 |
+
self.plot_single_z_level(z_val, filename=os.path.join("vertical_profiles_timeSlice", filename))
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
################################################
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def animate_altitude(self, t_index: int, output_path: str):
|
| 292 |
+
if not (0 <= t_index < len(self.animator.datasets)):
|
| 293 |
+
print(f"Invalid time index {t_index}. Must be between 0 and {len(self.animator.datasets) - 1}.")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
ds = self.animator.datasets[t_index]
|
| 297 |
+
fig = plt.figure(figsize=(18, 7))
|
| 298 |
+
proj = ccrs.PlateCarree()
|
| 299 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 300 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 301 |
+
|
| 302 |
+
meta = ds.attrs
|
| 303 |
+
center_lat, center_lon = self._get_max_concentration_location()
|
| 304 |
+
if center_lat is None or center_lon is None:
|
| 305 |
+
print(f"No valid data found for time T{t_index + 1}. Skipping...")
|
| 306 |
+
plt.close()
|
| 307 |
+
return
|
| 308 |
+
|
| 309 |
+
lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 310 |
+
lat_zoom = self.animator.lats[lat_idx]
|
| 311 |
+
lon_zoom = self.animator.lons[lon_idx]
|
| 312 |
+
lon_zoom_grid, lat_zoom_grid = np.meshgrid(lon_zoom, lat_zoom)
|
| 313 |
+
|
| 314 |
+
z_indices_with_data = []
|
| 315 |
+
for z_index in range(len(self.animator.levels)):
|
| 316 |
+
data = ds['ash_concentration'].values[z_index]
|
| 317 |
+
interp = interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 318 |
+
if np.isfinite(interp).sum() > 0:
|
| 319 |
+
z_indices_with_data.append(z_index)
|
| 320 |
+
|
| 321 |
+
if not z_indices_with_data:
|
| 322 |
+
print(f"No valid Z-levels at time T{t_index + 1}.")
|
| 323 |
+
plt.close()
|
| 324 |
+
return
|
| 325 |
+
|
| 326 |
+
def update(z_index):
|
| 327 |
+
ax1.clear()
|
| 328 |
+
ax2.clear()
|
| 329 |
+
|
| 330 |
+
data = ds['ash_concentration'].values[z_index]
|
| 331 |
+
interp = interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 332 |
+
interp = np.where(interp < 0, np.nan, interp)
|
| 333 |
+
zoom_plot = interp[np.ix_(lat_idx, lon_idx)]
|
| 334 |
+
|
| 335 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 336 |
+
if valid_vals.size == 0:
|
| 337 |
+
return []
|
| 338 |
+
|
| 339 |
+
min_val, max_val = np.nanmin(valid_vals), np.nanmax(valid_vals)
|
| 340 |
+
log_cutoff = 1e-3
|
| 341 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 342 |
+
|
| 343 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 344 |
+
data_for_plot = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 345 |
+
scale_label = "Log" if use_log else "Linear"
|
| 346 |
+
|
| 347 |
+
title1 = f"T{t_index + 1} | Alt: {self.animator.levels[z_index]} km (Full - {scale_label})"
|
| 348 |
+
title2 = f"T{t_index + 1} | Alt: {self.animator.levels[z_index]} km (Zoom - {scale_label})"
|
| 349 |
+
|
| 350 |
+
c1 = self._plot_frame(ax1, data_for_plot, self.animator.lons, self.animator.lats, title1, levels, scale_label, proj)
|
| 351 |
+
self._plot_frame(ax2, zoom_plot, lon_zoom, lat_zoom, title2, levels, scale_label, proj)
|
| 352 |
+
|
| 353 |
+
self._add_country_labels(ax1, [self.lon_min, self.lon_max, self.lat_min, self.lat_max])
|
| 354 |
+
self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 355 |
+
|
| 356 |
+
if self.include_metadata:
|
| 357 |
+
self._draw_metadata_sidebar(fig, meta)
|
| 358 |
+
|
| 359 |
+
if not hasattr(update, "colorbar"):
|
| 360 |
+
update.colorbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical',
|
| 361 |
+
label="Ash concentration (g/m³)", shrink=0.75)
|
| 362 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 363 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 364 |
+
|
| 365 |
+
if np.nanmax(valid_vals) > self.threshold:
|
| 366 |
+
ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 367 |
+
colors='red', linewidths=2, transform=proj)
|
| 368 |
+
ax2.contour(lon_zoom, lat_zoom, zoom_plot, levels=[self.threshold],
|
| 369 |
+
colors='red', linewidths=2, transform=proj)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
ax2.text(0.99, 0.01, f"⚠ Max Thresold Exceed: {np.nanmax(valid_vals):.2f} > {self.threshold} g/m³",
|
| 373 |
+
transform=ax2.transAxes, ha='right', va='bottom',
|
| 374 |
+
fontsize=9, color='red',
|
| 375 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 376 |
+
return []
|
| 377 |
+
|
| 378 |
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
| 379 |
+
#fig.set_size_inches(18, 7)
|
| 380 |
+
fig.tight_layout(rect=[0.02, 0.02, 0.98, 0.98])
|
| 381 |
+
ani = animation.FuncAnimation(fig, update, frames=z_indices_with_data, blit=False, cache_frame_data =False)
|
| 382 |
+
ani.save(output_path, writer='pillow', fps=self.fps, dpi=300)
|
| 383 |
+
plt.close()
|
| 384 |
+
print(f"✅ Saved vertical profile animation for T{t_index + 1} to {output_path}")
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def animate_all_altitude_profiles(self, output_folder='altitude_profiles'):
|
| 389 |
+
output_folder = os.path.join(self.output_dir, "altitude_profiles")
|
| 390 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 391 |
+
for t_index in range(len(self.animator.datasets)):
|
| 392 |
+
output_path = os.path.join(output_folder, f"vertical_T{t_index + 1:02d}.gif")
|
| 393 |
+
print(f"🔄 Generating vertical profile animation for T{t_index + 1}...")
|
| 394 |
+
self.animate_altitude(t_index, output_path)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def export_frames_as_jpgs(self, include_metadata: bool = True):
|
| 402 |
+
output_folder = os.path.join(self.output_dir, "frames")
|
| 403 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 404 |
+
meta = self.animator.datasets[0].attrs
|
| 405 |
+
legend_text = "\\n".join([
|
| 406 |
+
f"Run name: {meta.get('run_name', 'N/A')}",
|
| 407 |
+
f"Run time: {meta.get('run_time', 'N/A')}",
|
| 408 |
+
f"Met data: {meta.get('met_data', 'N/A')}",
|
| 409 |
+
f"Start release: {meta.get('start_of_release', 'N/A')}",
|
| 410 |
+
f"End release: {meta.get('end_of_release', 'N/A')}",
|
| 411 |
+
f"Strength: {meta.get('source_strength', 'N/A')} g/s",
|
| 412 |
+
f"Location: {meta.get('release_location', 'N/A')}",
|
| 413 |
+
f"Height: {meta.get('release_height', 'N/A')} m asl",
|
| 414 |
+
f"Duration: {meta.get('run_duration', 'N/A')}"
|
| 415 |
+
])
|
| 416 |
+
for z_index, z_val in enumerate(self.animator.levels):
|
| 417 |
+
z_dir = os.path.join(output_folder, f"Z{z_val:.1f}km")
|
| 418 |
+
os.makedirs(z_dir, exist_ok=True)
|
| 419 |
+
for t in range(len(self.animator.datasets)):
|
| 420 |
+
data = self.animator.datasets[t]['ash_concentration'].values[z_index]
|
| 421 |
+
interp = interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 422 |
+
if not np.isfinite(interp).any():
|
| 423 |
+
continue
|
| 424 |
+
fig = plt.figure(figsize=(16, 8))
|
| 425 |
+
proj = ccrs.PlateCarree()
|
| 426 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 427 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 428 |
+
valid_vals = interp[np.isfinite(interp)]
|
| 429 |
+
min_val, max_val = np.nanmin(valid_vals), np.nanmax(valid_vals)
|
| 430 |
+
log_cutoff = 1e-3
|
| 431 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 432 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 433 |
+
data_for_plot = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 434 |
+
scale_label = "Log" if use_log else "Linear"
|
| 435 |
+
center_lat, center_lon = self._get_max_concentration_location()
|
| 436 |
+
lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 437 |
+
zoom_plot = interp[np.ix_(lat_idx, lon_idx)]
|
| 438 |
+
lon_zoom = self.animator.lons[lon_idx]
|
| 439 |
+
lat_zoom = self.animator.lats[lat_idx]
|
| 440 |
+
c1 = self._plot_frame(ax1, data_for_plot, self.animator.lons, self.animator.lats,
|
| 441 |
+
f"T{t+1} | Alt: {z_val} km (Full - {scale_label})", levels, scale_label, proj)
|
| 442 |
+
self._plot_frame(ax2, zoom_plot, lon_zoom, lat_zoom,
|
| 443 |
+
f"T{t+1} | Alt: {z_val} km (Zoom - {scale_label})", levels, scale_label, proj)
|
| 444 |
+
self._add_country_labels(ax1, [self.animator.lons.min(), self.animator.lons.max(),
|
| 445 |
+
self.animator.lats.min(), self.animator.lats.max()])
|
| 446 |
+
self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 447 |
+
if np.nanmax(valid_vals) > self.threshold:
|
| 448 |
+
ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 449 |
+
colors='red', linewidths=2, transform=proj)
|
| 450 |
+
ax2.contour(lon_zoom, lat_zoom, zoom_plot, levels=[self.threshold],
|
| 451 |
+
colors='red', linewidths=2, transform=proj)
|
| 452 |
+
ax2.text(0.99, 0.01, f"⚠ Max: {np.nanmax(valid_vals):.2f} > {self.threshold} g/m³",
|
| 453 |
+
transform=ax2.transAxes, ha='right', va='bottom',
|
| 454 |
+
fontsize=9, color='red',
|
| 455 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 456 |
+
if include_metadata:
|
| 457 |
+
self._draw_metadata_sidebar(fig, meta)
|
| 458 |
+
cbar = fig.colorbar(c1, ax=[ax1, ax2], orientation='vertical', shrink=0.75, pad=0.03)
|
| 459 |
+
cbar.set_label("Ash concentration (g/m³)")
|
| 460 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 461 |
+
cbar.ax.yaxis.set_major_formatter(formatter)
|
| 462 |
+
frame_path = os.path.join(z_dir, f"frame_{t+1:04d}.jpg")
|
| 463 |
+
plt.savefig(frame_path, dpi=150, bbox_inches='tight')
|
| 464 |
+
plt.close(fig)
|
| 465 |
+
print(f"📸 Saved {frame_path}")
|
ash_animator/plot_horizontal_data.py
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
''' import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import matplotlib.animation as animation
|
| 5 |
+
import matplotlib.ticker as mticker
|
| 6 |
+
import cartopy.crs as ccrs
|
| 7 |
+
import cartopy.feature as cfeature
|
| 8 |
+
import cartopy.io.shapereader as shpreader
|
| 9 |
+
from adjustText import adjust_text
|
| 10 |
+
from ash_animator.interpolation import interpolate_grid
|
| 11 |
+
from ash_animator.basemaps import draw_etopo_basemap
|
| 12 |
+
|
| 13 |
+
class Plot_Horizontal_Data:
|
| 14 |
+
def __init__(self, animator, output_dir="plots", cmap="rainbow", fps=2,
|
| 15 |
+
include_metadata=True, threshold=0.1,
|
| 16 |
+
zoom_width_deg=6.0, zoom_height_deg=6.0, zoom_level=7, static_frame_export=False):
|
| 17 |
+
self.animator = animator
|
| 18 |
+
self.output_dir = os.path.abspath(os.path.join(os.getcwd(), output_dir))
|
| 19 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
| 20 |
+
self.cmap = cmap
|
| 21 |
+
self.fps = fps
|
| 22 |
+
self.include_metadata = include_metadata
|
| 23 |
+
self.threshold = threshold
|
| 24 |
+
self.zoom_width = zoom_width_deg
|
| 25 |
+
self.zoom_height = zoom_height_deg
|
| 26 |
+
shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 27 |
+
self.country_geoms = list(shpreader.Reader(shp).records())
|
| 28 |
+
self.interpolate_grid= interpolate_grid
|
| 29 |
+
self._draw_etopo_basemap=draw_etopo_basemap
|
| 30 |
+
self.zoom_level=zoom_level
|
| 31 |
+
self.static_frame_export=static_frame_export
|
| 32 |
+
|
| 33 |
+
def _make_dirs(self, path):
|
| 34 |
+
os.makedirs(os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(path))), exist_ok=True)
|
| 35 |
+
|
| 36 |
+
def _get_max_concentration_location(self, field):
|
| 37 |
+
max_val = -np.inf
|
| 38 |
+
lat = lon = None
|
| 39 |
+
for ds in self.animator.datasets:
|
| 40 |
+
data = ds[field].values
|
| 41 |
+
if np.max(data) > max_val:
|
| 42 |
+
max_val = np.max(data)
|
| 43 |
+
idx = np.unravel_index(np.argmax(data), data.shape)
|
| 44 |
+
lat = self.animator.lat_grid[idx]
|
| 45 |
+
lon = self.animator.lon_grid[idx]
|
| 46 |
+
return lat, lon
|
| 47 |
+
|
| 48 |
+
def _get_zoom_indices(self, center_lat, center_lon):
|
| 49 |
+
lon_min = center_lon - self.zoom_width / 2
|
| 50 |
+
lon_max = center_lon + self.zoom_width / 2
|
| 51 |
+
lat_min = center_lat - self.zoom_height / 2
|
| 52 |
+
lat_max = center_lat + self.zoom_height / 2
|
| 53 |
+
lat_idx = np.where((self.animator.lats >= lat_min) & (self.animator.lats <= lat_max))[0]
|
| 54 |
+
lon_idx = np.where((self.animator.lons >= lon_min) & (self.animator.lons <= lon_max))[0]
|
| 55 |
+
return lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max
|
| 56 |
+
|
| 57 |
+
def _add_country_labels(self, ax, extent):
|
| 58 |
+
proj = ccrs.PlateCarree()
|
| 59 |
+
texts = []
|
| 60 |
+
for country in self.country_geoms:
|
| 61 |
+
name = country.attributes['NAME_LONG']
|
| 62 |
+
geom = country.geometry
|
| 63 |
+
try:
|
| 64 |
+
lon, lat = geom.centroid.x, geom.centroid.y
|
| 65 |
+
if extent[0] <= lon <= extent[1] and extent[2] <= lat <= extent[3]:
|
| 66 |
+
text = ax.text(lon, lat, name, fontsize=6, transform=proj,
|
| 67 |
+
ha='center', va='center', color='white',
|
| 68 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 69 |
+
texts.append(text)
|
| 70 |
+
except:
|
| 71 |
+
continue
|
| 72 |
+
adjust_text(texts, ax=ax, only_move={'points': 'y', 'text': 'y'},
|
| 73 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 74 |
+
|
| 75 |
+
def _draw_metadata_sidebar(self, fig, meta_dict):
|
| 76 |
+
lines = [
|
| 77 |
+
f"Run name: {meta_dict.get('run_name', 'N/A')}",
|
| 78 |
+
f"Run time: {meta_dict.get('run_time', 'N/A')}",
|
| 79 |
+
f"Met data: {meta_dict.get('met_data', 'N/A')}",
|
| 80 |
+
f"Start release: {meta_dict.get('start_of_release', 'N/A')}",
|
| 81 |
+
f"End release: {meta_dict.get('end_of_release', 'N/A')}",
|
| 82 |
+
f"Source strength: {meta_dict.get('source_strength', 'N/A')} g/s",
|
| 83 |
+
f"Release loc: {meta_dict.get('release_location', 'N/A')}",
|
| 84 |
+
f"Release height: {meta_dict.get('release_height', 'N/A')} m asl",
|
| 85 |
+
f"Run duration: {meta_dict.get('run_duration', 'N/A')}"
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
# Split into two columns
|
| 89 |
+
mid = len(lines) // 2 + len(lines) % 2
|
| 90 |
+
left_lines = lines[:mid]
|
| 91 |
+
right_lines = lines[mid:]
|
| 92 |
+
|
| 93 |
+
left_text = "\n".join(left_lines)
|
| 94 |
+
right_text = "\n".join(right_lines)
|
| 95 |
+
|
| 96 |
+
# right column
|
| 97 |
+
fig.text(0.05, 0.05, left_text, va='bottom', ha='left',
|
| 98 |
+
fontsize=9, family='monospace', color='black',
|
| 99 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
|
| 100 |
+
|
| 101 |
+
# left column
|
| 102 |
+
fig.text(0.3, 0.05, right_text, va='bottom', ha='left',
|
| 103 |
+
fontsize=9, family='monospace', color='black',
|
| 104 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _plot_frame(self, ax, data, lons, lats, title, levels, scale_label, proj):
|
| 111 |
+
self._draw_etopo_basemap(ax, mode='basemap', zoom=self.zoom_level)
|
| 112 |
+
c = ax.contourf(lons, lats, data, levels=levels, cmap=self.cmap, alpha=0.6, transform=proj)
|
| 113 |
+
ax.set_title(title)
|
| 114 |
+
ax.set_extent([lons.min(), lons.max(), lats.min(), lats.max()])
|
| 115 |
+
ax.coastlines()
|
| 116 |
+
ax.add_feature(cfeature.BORDERS, linestyle=':')
|
| 117 |
+
ax.add_feature(cfeature.LAND)
|
| 118 |
+
ax.add_feature(cfeature.OCEAN)
|
| 119 |
+
return c
|
| 120 |
+
|
| 121 |
+
def get_available_2d_fields(self):
|
| 122 |
+
ds = self.animator.datasets[0]
|
| 123 |
+
return [v for v in ds.data_vars if ds[v].ndim == 2]
|
| 124 |
+
|
| 125 |
+
def plot_single_field_over_time(self, field, filename="field.gif"):
|
| 126 |
+
output_path = os.path.join(self.output_dir, "2d_fields", field, filename)
|
| 127 |
+
meta = self.animator.datasets[0].attrs
|
| 128 |
+
center_lat, center_lon = self._get_max_concentration_location(field)
|
| 129 |
+
lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 130 |
+
lat_zoom = self.animator.lats[lat_idx]
|
| 131 |
+
lon_zoom = self.animator.lons[lon_idx]
|
| 132 |
+
|
| 133 |
+
valid_frames = []
|
| 134 |
+
for t in range(len(self.animator.datasets)):
|
| 135 |
+
data = self.animator.datasets[t][field].values
|
| 136 |
+
interp = self.interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 137 |
+
if np.isfinite(interp).sum() > 0:
|
| 138 |
+
valid_frames.append(t)
|
| 139 |
+
|
| 140 |
+
if not valid_frames:
|
| 141 |
+
print(f"No valid frames to plot for field '{field}'.")
|
| 142 |
+
return
|
| 143 |
+
|
| 144 |
+
fig = plt.figure(figsize=(16, 8))
|
| 145 |
+
proj = ccrs.PlateCarree()
|
| 146 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 147 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 148 |
+
|
| 149 |
+
def update(t):
|
| 150 |
+
ax1.clear()
|
| 151 |
+
ax2.clear()
|
| 152 |
+
data = self.animator.datasets[t][field].values
|
| 153 |
+
interp = self.interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 154 |
+
zoom = interp[np.ix_(lat_idx, lon_idx)]
|
| 155 |
+
valid = interp[np.isfinite(interp)]
|
| 156 |
+
if valid.size == 0:
|
| 157 |
+
return []
|
| 158 |
+
|
| 159 |
+
min_val, max_val = np.nanmin(valid), np.nanmax(valid)
|
| 160 |
+
log_cutoff = 1e-3
|
| 161 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 162 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 163 |
+
plot_data = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 164 |
+
scale_label = "Log" if use_log else "Linear"
|
| 165 |
+
|
| 166 |
+
c = self._plot_frame(ax1, plot_data, self.animator.lons, self.animator.lats,
|
| 167 |
+
f"T{t+1} | {field} (Full - {scale_label})", levels, scale_label, proj)
|
| 168 |
+
self._plot_frame(ax2, zoom, lon_zoom, lat_zoom,
|
| 169 |
+
f"T{t+1} | {field} (Zoom - {scale_label})", levels, scale_label, proj)
|
| 170 |
+
|
| 171 |
+
self._add_country_labels(ax1, [self.animator.lons.min(), self.animator.lons.max(),
|
| 172 |
+
self.animator.lats.min(), self.animator.lats.max()])
|
| 173 |
+
self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 174 |
+
|
| 175 |
+
# Inside update() function:
|
| 176 |
+
if not hasattr(update, "colorbar"):
|
| 177 |
+
unit_label = f"{field}:({self.animator.datasets[0][field].attrs.get("units", field)})" #self.animator.datasets[0][field].attrs.get("units", field)
|
| 178 |
+
update.colorbar = fig.colorbar(c, ax=[ax1, ax2], orientation='vertical', label=unit_label)
|
| 179 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 180 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if np.nanmax(valid) > self.threshold:
|
| 184 |
+
ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 185 |
+
colors='red', linewidths=2, transform=proj)
|
| 186 |
+
ax2.contour(lon_zoom, lat_zoom, zoom, levels=[self.threshold],
|
| 187 |
+
colors='red', linewidths=2, transform=proj)
|
| 188 |
+
ax2.text(0.99, 0.01, f"⚠ Max Thresold Exceed: {np.nanmax(valid):.2f} > {self.threshold}",
|
| 189 |
+
transform=ax2.transAxes, ha='right', va='bottom',
|
| 190 |
+
fontsize=9, color='red',
|
| 191 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 192 |
+
|
| 193 |
+
if self.static_frame_export:
|
| 194 |
+
frame_folder = os.path.join(self.output_dir, "frames", field)
|
| 195 |
+
os.makedirs(frame_folder, exist_ok=True)
|
| 196 |
+
frame_path = os.path.join(frame_folder, f"frame_{t+1:04d}.jpg")
|
| 197 |
+
plt.savefig(frame_path, dpi=300, bbox_inches='tight')
|
| 198 |
+
print(f"🖼️ Saved static frame: {frame_path}")
|
| 199 |
+
|
| 200 |
+
return []
|
| 201 |
+
|
| 202 |
+
if self.include_metadata:
|
| 203 |
+
self._draw_metadata_sidebar(fig, meta)
|
| 204 |
+
|
| 205 |
+
self._make_dirs(output_path)
|
| 206 |
+
fig.tight_layout()
|
| 207 |
+
ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False, cache_frame_data =False)
|
| 208 |
+
ani.save(output_path, writer='pillow', fps=self.fps)
|
| 209 |
+
plt.close()
|
| 210 |
+
print(f"✅ Saved enhanced 2D animation for {field} to {output_path}")
|
| 211 |
+
|
| 212 |
+
# def export_frames_as_jpgs(self, fields=None, include_metadata=True):
|
| 213 |
+
# all_fields = self.get_available_2d_fields()
|
| 214 |
+
# if fields:
|
| 215 |
+
# fields = [f for f in fields if f in all_fields]
|
| 216 |
+
# else:
|
| 217 |
+
# fields = all_fields
|
| 218 |
+
|
| 219 |
+
# meta = self.animator.datasets[0].attrs
|
| 220 |
+
|
| 221 |
+
# for field in fields:
|
| 222 |
+
# print(f"📤 Exporting frames for field: {field}")
|
| 223 |
+
# output_folder = os.path.join(self.output_dir, "frames", field)
|
| 224 |
+
# os.makedirs(output_folder, exist_ok=True)
|
| 225 |
+
|
| 226 |
+
# center_lat, center_lon = self._get_max_concentration_location(field)
|
| 227 |
+
# lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 228 |
+
# lat_zoom = self.animator.lats[lat_idx]
|
| 229 |
+
# lon_zoom = self.animator.lons[lon_idx]
|
| 230 |
+
|
| 231 |
+
# for t, ds in enumerate(self.animator.datasets):
|
| 232 |
+
# data = ds[field].values
|
| 233 |
+
# interp = self.interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 234 |
+
# if not np.isfinite(interp).any():
|
| 235 |
+
# continue
|
| 236 |
+
|
| 237 |
+
# fig = plt.figure(figsize=(16, 8))
|
| 238 |
+
# proj = ccrs.PlateCarree()
|
| 239 |
+
# ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 240 |
+
# ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 241 |
+
# zoom = interp[np.ix_(lat_idx, lon_idx)]
|
| 242 |
+
# valid = interp[np.isfinite(interp)]
|
| 243 |
+
# min_val, max_val = np.nanmin(valid), np.nanmax(valid)
|
| 244 |
+
# log_cutoff = 1e-3
|
| 245 |
+
# use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 246 |
+
# levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 247 |
+
# plot_data = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 248 |
+
# scale_label = "Log" if use_log else "Linear"
|
| 249 |
+
|
| 250 |
+
# c = self._plot_frame(ax1, plot_data, self.animator.lons, self.animator.lats,
|
| 251 |
+
# f"T{t+1} | {field} (Full - {scale_label})", levels, scale_label, proj)
|
| 252 |
+
# self._plot_frame(ax2, zoom, lon_zoom, lat_zoom,
|
| 253 |
+
# f"T{t+1} | {field} (Zoom - {scale_label})", levels, scale_label, proj)
|
| 254 |
+
|
| 255 |
+
# self._add_country_labels(ax1, [self.animator.lons.min(), self.animator.lons.max(),
|
| 256 |
+
# self.animator.lats.min(), self.animator.lats.max()])
|
| 257 |
+
# self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 258 |
+
|
| 259 |
+
# if include_metadata:
|
| 260 |
+
# self._draw_metadata_sidebar(fig, meta)
|
| 261 |
+
|
| 262 |
+
# cbar = fig.colorbar(c, ax=[ax1, ax2], orientation='vertical', shrink=0.75, pad=0.03)
|
| 263 |
+
# unit_label = f"{field}:({self.animator.datasets[0][field].attrs.get('units', field)})"
|
| 264 |
+
# cbar.set_label(unit_label)
|
| 265 |
+
# formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 266 |
+
# cbar.ax.yaxis.set_major_formatter(formatter)
|
| 267 |
+
|
| 268 |
+
# if np.nanmax(valid) > self.threshold:
|
| 269 |
+
# ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 270 |
+
# colors='red', linewidths=2, transform=proj)
|
| 271 |
+
# ax2.contour(lon_zoom, lat_zoom, zoom, levels=[self.threshold],
|
| 272 |
+
# colors='red', linewidths=2, transform=proj)
|
| 273 |
+
# ax2.text(0.99, 0.01, f"⚠ Max: {np.nanmax(valid):.2f} > {self.threshold}",
|
| 274 |
+
# transform=ax2.transAxes, ha='right', va='bottom',
|
| 275 |
+
# fontsize=9, color='red',
|
| 276 |
+
# bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 277 |
+
|
| 278 |
+
# frame_path = os.path.join(output_folder, f"frame_{t+1:04d}.jpg")
|
| 279 |
+
# plt.savefig(frame_path, dpi=150, bbox_inches='tight')
|
| 280 |
+
# plt.close(fig)
|
| 281 |
+
# print(f"📸 Saved {frame_path}")
|
| 282 |
+
'''
|
| 283 |
+
|
| 284 |
+
import os
|
| 285 |
+
import numpy as np
|
| 286 |
+
import matplotlib.pyplot as plt
|
| 287 |
+
import matplotlib.animation as animation
|
| 288 |
+
import matplotlib.ticker as mticker
|
| 289 |
+
import cartopy.crs as ccrs
|
| 290 |
+
import cartopy.feature as cfeature
|
| 291 |
+
import cartopy.io.shapereader as shpreader
|
| 292 |
+
from adjustText import adjust_text
|
| 293 |
+
from ash_animator.interpolation import interpolate_grid
|
| 294 |
+
from ash_animator.basemaps import draw_etopo_basemap
|
| 295 |
+
|
| 296 |
+
class Plot_Horizontal_Data:
|
| 297 |
+
def __init__(self, animator, output_dir="plots", cmap="rainbow", fps=2,
|
| 298 |
+
include_metadata=True, threshold=0.1,
|
| 299 |
+
zoom_width_deg=6.0, zoom_height_deg=6.0, zoom_level=7, static_frame_export=False):
|
| 300 |
+
self.animator = animator
|
| 301 |
+
self.output_dir = os.path.abspath(os.path.join(os.getcwd(), output_dir))
|
| 302 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
| 303 |
+
self.cmap = cmap
|
| 304 |
+
self.fps = fps
|
| 305 |
+
self.include_metadata = include_metadata
|
| 306 |
+
self.threshold = threshold
|
| 307 |
+
self.zoom_width = zoom_width_deg
|
| 308 |
+
self.zoom_height = zoom_height_deg
|
| 309 |
+
shp = shpreader.natural_earth(resolution='110m', category='cultural', name='admin_0_countries')
|
| 310 |
+
self.country_geoms = list(shpreader.Reader(shp).records())
|
| 311 |
+
self.interpolate_grid= interpolate_grid
|
| 312 |
+
self._draw_etopo_basemap=draw_etopo_basemap
|
| 313 |
+
self.zoom_level=zoom_level
|
| 314 |
+
self.static_frame_export=static_frame_export
|
| 315 |
+
|
| 316 |
+
def _make_dirs(self, path):
|
| 317 |
+
os.makedirs(os.path.abspath(os.path.join(os.getcwd(), os.path.dirname(path))), exist_ok=True)
|
| 318 |
+
|
| 319 |
+
def _get_max_concentration_location(self, field):
|
| 320 |
+
max_val = -np.inf
|
| 321 |
+
lat = lon = None
|
| 322 |
+
for ds in self.animator.datasets:
|
| 323 |
+
data = ds[field].values
|
| 324 |
+
if np.max(data) > max_val:
|
| 325 |
+
max_val = np.max(data)
|
| 326 |
+
idx = np.unravel_index(np.argmax(data), data.shape)
|
| 327 |
+
lat = self.animator.lat_grid[idx]
|
| 328 |
+
lon = self.animator.lon_grid[idx]
|
| 329 |
+
return lat, lon
|
| 330 |
+
|
| 331 |
+
def _get_zoom_indices(self, center_lat, center_lon):
|
| 332 |
+
lon_min = center_lon - self.zoom_width / 2
|
| 333 |
+
lon_max = center_lon + self.zoom_width / 2
|
| 334 |
+
lat_min = center_lat - self.zoom_height / 2
|
| 335 |
+
lat_max = center_lat + self.zoom_height / 2
|
| 336 |
+
lat_idx = np.where((self.animator.lats >= lat_min) & (self.animator.lats <= lat_max))[0]
|
| 337 |
+
lon_idx = np.where((self.animator.lons >= lon_min) & (self.animator.lons <= lon_max))[0]
|
| 338 |
+
return lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max
|
| 339 |
+
|
| 340 |
+
def _add_country_labels(self, ax, extent):
|
| 341 |
+
proj = ccrs.PlateCarree()
|
| 342 |
+
texts = []
|
| 343 |
+
for country in self.country_geoms:
|
| 344 |
+
name = country.attributes['NAME_LONG']
|
| 345 |
+
geom = country.geometry
|
| 346 |
+
try:
|
| 347 |
+
lon, lat = geom.centroid.x, geom.centroid.y
|
| 348 |
+
if extent[0] <= lon <= extent[1] and extent[2] <= lat <= extent[3]:
|
| 349 |
+
text = ax.text(lon, lat, name, fontsize=6, transform=proj,
|
| 350 |
+
ha='center', va='center', color='white',
|
| 351 |
+
bbox=dict(facecolor='black', alpha=0.5, linewidth=0))
|
| 352 |
+
texts.append(text)
|
| 353 |
+
except:
|
| 354 |
+
continue
|
| 355 |
+
adjust_text(texts, ax=ax, only_move={'points': 'y', 'text': 'y'},
|
| 356 |
+
arrowprops=dict(arrowstyle="->", color='white', lw=0.5))
|
| 357 |
+
|
| 358 |
+
def _draw_metadata_sidebar(self, fig, meta_dict):
|
| 359 |
+
lines = [
|
| 360 |
+
f"Run name: {meta_dict.get('run_name', 'N/A')}",
|
| 361 |
+
f"Run time: {meta_dict.get('run_time', 'N/A')}",
|
| 362 |
+
f"Met data: {meta_dict.get('met_data', 'N/A')}",
|
| 363 |
+
f"Start release: {meta_dict.get('start_of_release', 'N/A')}",
|
| 364 |
+
f"End release: {meta_dict.get('end_of_release', 'N/A')}",
|
| 365 |
+
f"Source strength: {meta_dict.get('source_strength', 'N/A')} g/s",
|
| 366 |
+
f"Release loc: {meta_dict.get('release_location', 'N/A')}",
|
| 367 |
+
f"Release height: {meta_dict.get('release_height', 'N/A')} m asl",
|
| 368 |
+
f"Run duration: {meta_dict.get('run_duration', 'N/A')}"
|
| 369 |
+
]
|
| 370 |
+
|
| 371 |
+
# Split into two columns
|
| 372 |
+
mid = len(lines) // 2 + len(lines) % 2
|
| 373 |
+
left_lines = lines[:mid]
|
| 374 |
+
right_lines = lines[mid:]
|
| 375 |
+
|
| 376 |
+
left_text = "\n".join(left_lines)
|
| 377 |
+
right_text = "\n".join(right_lines)
|
| 378 |
+
|
| 379 |
+
# right column
|
| 380 |
+
fig.text(0.05, 0.05, left_text, va='bottom', ha='left',
|
| 381 |
+
fontsize=9, family='monospace', color='black',
|
| 382 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
|
| 383 |
+
|
| 384 |
+
# left column
|
| 385 |
+
fig.text(0.3, 0.05, right_text, va='bottom', ha='left',
|
| 386 |
+
fontsize=9, family='monospace', color='black',
|
| 387 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='gray'))
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _plot_frame(self, ax, data, lons, lats, title, levels, scale_label, proj):
|
| 394 |
+
self._draw_etopo_basemap(ax, mode='basemap', zoom=self.zoom_level)
|
| 395 |
+
c = ax.contourf(lons, lats, data, levels=levels, cmap=self.cmap, alpha=0.6, transform=proj)
|
| 396 |
+
ax.set_title(title)
|
| 397 |
+
ax.set_extent([lons.min(), lons.max(), lats.min(), lats.max()])
|
| 398 |
+
ax.coastlines()
|
| 399 |
+
ax.add_feature(cfeature.BORDERS, linestyle=':')
|
| 400 |
+
ax.add_feature(cfeature.LAND)
|
| 401 |
+
ax.add_feature(cfeature.OCEAN)
|
| 402 |
+
return c
|
| 403 |
+
|
| 404 |
+
def get_available_2d_fields(self):
|
| 405 |
+
ds = self.animator.datasets[0]
|
| 406 |
+
return [v for v in ds.data_vars if ds[v].ndim == 2]
|
| 407 |
+
|
| 408 |
+
def plot_single_field_over_time(self, field, filename="field.gif"):
|
| 409 |
+
output_path = os.path.join(self.output_dir, "2d_fields", field, filename)
|
| 410 |
+
meta = self.animator.datasets[0].attrs
|
| 411 |
+
center_lat, center_lon = self._get_max_concentration_location(field)
|
| 412 |
+
lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 413 |
+
lat_zoom = self.animator.lats[lat_idx]
|
| 414 |
+
lon_zoom = self.animator.lons[lon_idx]
|
| 415 |
+
|
| 416 |
+
valid_frames = []
|
| 417 |
+
for t in range(len(self.animator.datasets)):
|
| 418 |
+
data = self.animator.datasets[t][field].values
|
| 419 |
+
interp = self.interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 420 |
+
if np.isfinite(interp).sum() > 0:
|
| 421 |
+
valid_frames.append(t)
|
| 422 |
+
|
| 423 |
+
if not valid_frames:
|
| 424 |
+
print(f"No valid frames to plot for field '{field}'.")
|
| 425 |
+
return
|
| 426 |
+
|
| 427 |
+
fig = plt.figure(figsize=(16, 8))
|
| 428 |
+
proj = ccrs.PlateCarree()
|
| 429 |
+
ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 430 |
+
ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 431 |
+
|
| 432 |
+
def update(t):
|
| 433 |
+
ax1.clear()
|
| 434 |
+
ax2.clear()
|
| 435 |
+
data = self.animator.datasets[t][field].values
|
| 436 |
+
interp = self.interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 437 |
+
zoom = interp[np.ix_(lat_idx, lon_idx)]
|
| 438 |
+
valid = interp[np.isfinite(interp)]
|
| 439 |
+
if valid.size == 0:
|
| 440 |
+
return []
|
| 441 |
+
|
| 442 |
+
min_val, max_val = np.nanmin(valid), np.nanmax(valid)
|
| 443 |
+
log_cutoff = 1e-3
|
| 444 |
+
use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 445 |
+
levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 446 |
+
plot_data = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 447 |
+
scale_label = "Log" if use_log else "Linear"
|
| 448 |
+
|
| 449 |
+
c = self._plot_frame(ax1, plot_data, self.animator.lons, self.animator.lats,
|
| 450 |
+
f"T{t+1} | {field} (Full - {scale_label})", levels, scale_label, proj)
|
| 451 |
+
self._plot_frame(ax2, zoom, lon_zoom, lat_zoom,
|
| 452 |
+
f"T{t+1} | {field} (Zoom - {scale_label})", levels, scale_label, proj)
|
| 453 |
+
|
| 454 |
+
self._add_country_labels(ax1, [self.animator.lons.min(), self.animator.lons.max(),
|
| 455 |
+
self.animator.lats.min(), self.animator.lats.max()])
|
| 456 |
+
self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 457 |
+
|
| 458 |
+
# Inside update() function:
|
| 459 |
+
if not hasattr(update, "colorbar"):
|
| 460 |
+
unit_label = f"{field}:({self.animator.datasets[0][field].attrs.get('units', field)})" #self.animator.datasets[0][field].attrs.get("units", field)
|
| 461 |
+
update.colorbar = fig.colorbar(c, ax=[ax1, ax2], orientation='vertical', label=unit_label)
|
| 462 |
+
formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 463 |
+
update.colorbar.ax.yaxis.set_major_formatter(formatter)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
if np.nanmax(valid) > self.threshold:
|
| 467 |
+
ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 468 |
+
colors='red', linewidths=2, transform=proj)
|
| 469 |
+
ax2.contour(lon_zoom, lat_zoom, zoom, levels=[self.threshold],
|
| 470 |
+
colors='red', linewidths=2, transform=proj)
|
| 471 |
+
ax2.text(0.99, 0.01, f"⚠ Max Thresold Exceed: {np.nanmax(valid):.2f} > {self.threshold}",
|
| 472 |
+
transform=ax2.transAxes, ha='right', va='bottom',
|
| 473 |
+
fontsize=9, color='red',
|
| 474 |
+
bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 475 |
+
|
| 476 |
+
if self.static_frame_export:
|
| 477 |
+
frame_folder = os.path.join(self.output_dir, "frames", field)
|
| 478 |
+
os.makedirs(frame_folder, exist_ok=True)
|
| 479 |
+
frame_path = os.path.join(frame_folder, f"frame_{t+1:04d}.jpg")
|
| 480 |
+
plt.savefig(frame_path, dpi=300, bbox_inches='tight')
|
| 481 |
+
print(f"🖼️ Saved static frame: {frame_path}")
|
| 482 |
+
|
| 483 |
+
return []
|
| 484 |
+
|
| 485 |
+
if self.include_metadata:
|
| 486 |
+
self._draw_metadata_sidebar(fig, meta)
|
| 487 |
+
|
| 488 |
+
self._make_dirs(output_path)
|
| 489 |
+
fig.tight_layout()
|
| 490 |
+
ani = animation.FuncAnimation(fig, update, frames=valid_frames, blit=False, cache_frame_data =False)
|
| 491 |
+
ani.save(output_path, writer='pillow', fps=self.fps)
|
| 492 |
+
plt.close()
|
| 493 |
+
print(f"✅ Saved enhanced 2D animation for {field} to {output_path}")
|
| 494 |
+
|
| 495 |
+
# def export_frames_as_jpgs(self, fields=None, include_metadata=True):
|
| 496 |
+
# all_fields = self.get_available_2d_fields()
|
| 497 |
+
# if fields:
|
| 498 |
+
# fields = [f for f in fields if f in all_fields]
|
| 499 |
+
# else:
|
| 500 |
+
# fields = all_fields
|
| 501 |
+
|
| 502 |
+
# meta = self.animator.datasets[0].attrs
|
| 503 |
+
|
| 504 |
+
# for field in fields:
|
| 505 |
+
# print(f"📤 Exporting frames for field: {field}")
|
| 506 |
+
# output_folder = os.path.join(self.output_dir, "frames", field)
|
| 507 |
+
# os.makedirs(output_folder, exist_ok=True)
|
| 508 |
+
|
| 509 |
+
# center_lat, center_lon = self._get_max_concentration_location(field)
|
| 510 |
+
# lat_idx, lon_idx, lon_min, lon_max, lat_min, lat_max = self._get_zoom_indices(center_lat, center_lon)
|
| 511 |
+
# lat_zoom = self.animator.lats[lat_idx]
|
| 512 |
+
# lon_zoom = self.animator.lons[lon_idx]
|
| 513 |
+
|
| 514 |
+
# for t, ds in enumerate(self.animator.datasets):
|
| 515 |
+
# data = ds[field].values
|
| 516 |
+
# interp = self.interpolate_grid(data, self.animator.lon_grid, self.animator.lat_grid)
|
| 517 |
+
# if not np.isfinite(interp).any():
|
| 518 |
+
# continue
|
| 519 |
+
|
| 520 |
+
# fig = plt.figure(figsize=(16, 8))
|
| 521 |
+
# proj = ccrs.PlateCarree()
|
| 522 |
+
# ax1 = fig.add_subplot(1, 2, 1, projection=proj)
|
| 523 |
+
# ax2 = fig.add_subplot(1, 2, 2, projection=proj)
|
| 524 |
+
# zoom = interp[np.ix_(lat_idx, lon_idx)]
|
| 525 |
+
# valid = interp[np.isfinite(interp)]
|
| 526 |
+
# min_val, max_val = np.nanmin(valid), np.nanmax(valid)
|
| 527 |
+
# log_cutoff = 1e-3
|
| 528 |
+
# use_log = min_val > log_cutoff and (max_val / (min_val + 1e-6)) > 100
|
| 529 |
+
# levels = np.logspace(np.log10(log_cutoff), np.log10(max_val), 20) if use_log else np.linspace(0, max_val, 20)
|
| 530 |
+
# plot_data = np.where(interp > log_cutoff, interp, np.nan) if use_log else interp
|
| 531 |
+
# scale_label = "Log" if use_log else "Linear"
|
| 532 |
+
|
| 533 |
+
# c = self._plot_frame(ax1, plot_data, self.animator.lons, self.animator.lats,
|
| 534 |
+
# f"T{t+1} | {field} (Full - {scale_label})", levels, scale_label, proj)
|
| 535 |
+
# self._plot_frame(ax2, zoom, lon_zoom, lat_zoom,
|
| 536 |
+
# f"T{t+1} | {field} (Zoom - {scale_label})", levels, scale_label, proj)
|
| 537 |
+
|
| 538 |
+
# self._add_country_labels(ax1, [self.animator.lons.min(), self.animator.lons.max(),
|
| 539 |
+
# self.animator.lats.min(), self.animator.lats.max()])
|
| 540 |
+
# self._add_country_labels(ax2, [lon_min, lon_max, lat_min, lat_max])
|
| 541 |
+
|
| 542 |
+
# if include_metadata:
|
| 543 |
+
# self._draw_metadata_sidebar(fig, meta)
|
| 544 |
+
|
| 545 |
+
# cbar = fig.colorbar(c, ax=[ax1, ax2], orientation='vertical', shrink=0.75, pad=0.03)
|
| 546 |
+
# unit_label = f"{field}:({self.animator.datasets[0][field].attrs.get('units', field)})"
|
| 547 |
+
# cbar.set_label(unit_label)
|
| 548 |
+
# formatter = mticker.FuncFormatter(lambda x, _: f'{x:.2g}')
|
| 549 |
+
# cbar.ax.yaxis.set_major_formatter(formatter)
|
| 550 |
+
|
| 551 |
+
# if np.nanmax(valid) > self.threshold:
|
| 552 |
+
# ax1.contour(self.animator.lons, self.animator.lats, interp, levels=[self.threshold],
|
| 553 |
+
# colors='red', linewidths=2, transform=proj)
|
| 554 |
+
# ax2.contour(lon_zoom, lat_zoom, zoom, levels=[self.threshold],
|
| 555 |
+
# colors='red', linewidths=2, transform=proj)
|
| 556 |
+
# ax2.text(0.99, 0.01, f"⚠ Max: {np.nanmax(valid):.2f} > {self.threshold}",
|
| 557 |
+
# transform=ax2.transAxes, ha='right', va='bottom',
|
| 558 |
+
# fontsize=9, color='red',
|
| 559 |
+
# bbox=dict(facecolor='white', alpha=0.8, edgecolor='red'))
|
| 560 |
+
|
| 561 |
+
# frame_path = os.path.join(output_folder, f"frame_{t+1:04d}.jpg")
|
| 562 |
+
# plt.savefig(frame_path, dpi=150, bbox_inches='tight')
|
| 563 |
+
# plt.close(fig)
|
| 564 |
+
# print(f"📸 Saved {frame_path}")
|
ash_animator/utils.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from geopy.geocoders import Nominatim
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
def create_grid(attrs):
|
| 6 |
+
x_origin = float(attrs["x_origin"])
|
| 7 |
+
y_origin = float(attrs["y_origin"])
|
| 8 |
+
x_res = float(attrs["x_res"])
|
| 9 |
+
y_res = float(attrs["y_res"])
|
| 10 |
+
x_grid_size = int(attrs["x_grid_size"])
|
| 11 |
+
y_grid_size = int(attrs["y_grid_size"])
|
| 12 |
+
|
| 13 |
+
lons = np.round(np.linspace(x_origin, x_origin + (x_grid_size - 1) * x_res, x_grid_size), 6)
|
| 14 |
+
lats = np.round(np.linspace(y_origin, y_origin + (y_grid_size - 1) * y_res, y_grid_size), 6)
|
| 15 |
+
return lons, lats, np.meshgrid(lons, lats)
|
| 16 |
+
|
| 17 |
+
def get_country_label(lat, lon):
|
| 18 |
+
geolocator = Nominatim(user_agent="ash_animator")
|
| 19 |
+
try:
|
| 20 |
+
location = geolocator.reverse((lat, lon), language='en')
|
| 21 |
+
return location.raw['address'].get('country', 'Unknown')
|
| 22 |
+
except:
|
| 23 |
+
return "Unknown"
|
ash_output/3D/T1.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f04bb4ebcd78d22d304f989a1db3798ba8973c3605d409cf5d8c214e10640ae
|
| 3 |
+
size 2995772
|
ash_output/3D/T10.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fe2756a79311d5a93cef00a673e3f7bdc13a569527177a3a1d8bb98a2e2aec4b
|
| 3 |
+
size 2995772
|
ash_output/3D/T2.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:417fd7f9876bc5cd90aa9b337d4643a2f60c4c16bcb02d387cac0d4e14865bdb
|
| 3 |
+
size 2995772
|
ash_output/3D/T3.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2ec9f03b1d56ef60f53c7d896b314391ef43aad5d8a483429f1225019a3cd9ba
|
| 3 |
+
size 2995772
|
ash_output/3D/T4.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f5588d08a7e435beff468d8395104cc9e6e74e096669e2ffd626a6bcd4ce029
|
| 3 |
+
size 2995772
|
ash_output/3D/T5.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6ab72f23b1002e1282a249ca69a1b86edb931434d4061da53623a35259099e70
|
| 3 |
+
size 2995772
|
ash_output/3D/T6.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:59e5b28106a70437df8acbe5f3a09bae1cb02452c64c81829ca024e45748ae01
|
| 3 |
+
size 2995772
|
ash_output/3D/T7.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ff112cf7b8c3fe57eebbb137d347689161cc294f08c5594f03f511531513e6ae
|
| 3 |
+
size 2995772
|
ash_output/3D/T8.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b3147e15ec2c41fc248cd547633ecdb19282e5b4f99c72cbe3fe0685defd7d4
|
| 3 |
+
size 2995772
|
ash_output/3D/T9.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:779e66b51cced7ff2fcdb898497bd9239cc63dd1f98c3ea1e47ea227e033a469
|
| 3 |
+
size 2995772
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T10_202001121400.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:30423a57456aac09b692d4626113cfad7354c10ebfe2a6b8dc2bfc67660a087f
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T1_202001120500.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e8d702759a96a17a9ee42f048e495634071edf3134d3e44498b1a4400c3e09fc
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T2_202001120600.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ecee00afe0a4d182d1ef81fb693e55a1b692e2be6e3652e935de486c7bb7512
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T3_202001120700.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:be479227b11adf3b7dc893379eb237ccb977dec090b8fd61d4d124bbbedf9818
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T4_202001120800.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4486fd0527002f561c922a5a6281f3398a3813d857a5095cb20bb6ffd8646c97
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T5_202001120900.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7677dd47e53ff9d1f6529c64c3447b3a17dc49edc740bedbc275798169eabf8f
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T6_202001121000.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2c098cbd98dc31e6401fe90491324c068c9b9eb35e2d6893f74d18ca9c4161c4
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T7_202001121100.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f50cadb7ab79147d443212d94778666a97c844aa2ac775a7053b978878135937
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T8_202001121200.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b21e0a229a6831c8a1a394f3dc6650a0e045058cac23fe4d908024db387e2874
|
| 3 |
+
size 760991
|
ash_output/horizontal/AQOutput_HorizontalField_C1_T9_202001121300.nc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d55b4912c21a4b2b43d7fabc608c0095c72afa337fe7dead76cd100921e6bf7f
|
| 3 |
+
size 760991
|
media/2D/2d_fields/air_concentration/air_concentration.gif
ADDED
|
Git LFS Details
|
media/2D/frames/air_concentration/frame_0001.jpg
ADDED
|
Git LFS Details
|
media/2D/frames/air_concentration/frame_0008.jpg
ADDED
|
Git LFS Details
|
media/2D/frames/air_concentration/frame_0009.jpg
ADDED
|
Git LFS Details
|
media/2D/frames/air_concentration/frame_0010.jpg
ADDED
|
Git LFS Details
|
media/Taal_273070_20200112_scenario_yizhou.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9bb340a75132c3008a149557ff85f8bc05b4a46e70eee027503e30b9573fdd39
|
| 3 |
+
size 181349
|
media/default_model.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9bb340a75132c3008a149557ff85f8bc05b4a46e70eee027503e30b9573fdd39
|
| 3 |
+
size 181349
|