|
| 1 | +"""Runs metric calculations on cloudcasting for a given input day and appends to zarr store |
| 2 | +
|
| 3 | +This app expects these environmental variables to be available: |
| 4 | + - SATELLITE_ICECHUNK_ARCHIVE (str): Path at which ground truth satellite data can be found |
| 5 | + - CLOUDCASTING_PREDICTION_DIRECTORY (str): The directory where the cloudcasting forecasts are |
| 6 | + saved |
| 7 | + - METRIC_ZARR_PATH (str): The path where the metric values will be saved |
| 8 | +
|
| 9 | + If the SATELLITE_ICECHUNK_ARCHIVE is an s3 path, then the environment variables |
| 10 | + AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_REGION must also be set. |
| 11 | +""" |
| 12 | + |
| 13 | +import os |
| 14 | +import re |
| 15 | +import fsspec |
| 16 | +import numpy as np |
| 17 | +import pandas as pd |
| 18 | +from tqdm import tqdm |
| 19 | + |
| 20 | +import xarray as xr |
| 21 | +import icechunk |
| 22 | +from loguru import logger |
| 23 | + |
| 24 | +# --------------------------------------------------------------------------- |
| 25 | + |
| 26 | +# The forecast produces these horizon steps |
| 27 | +FORECAST_STEPS = pd.timedelta_range(start="15min", end="180min", freq="15min") |
| 28 | +# The forecast is run at this frequency |
| 29 | +FORECAST_FREQ = pd.Timedelta("30min") |
| 30 | + |
| 31 | + |
| 32 | +def open_icechunk(path: str) -> xr.Dataset: |
| 33 | + """Open an icechunk store to xarray Dataset |
| 34 | + |
| 35 | + Args: |
| 36 | + path: The path to the local or s3 icechunk store |
| 37 | + """ |
| 38 | + |
| 39 | + if path.startswith("s3://"): |
| 40 | + bucket, _, path = path.removeprefix("s3://").partition("/") |
| 41 | + store = icechunk.s3_storage( |
| 42 | + bucket=bucket, |
| 43 | + prefix=path, |
| 44 | + access_key_id=os.environ["AWS_ACCESS_KEY_ID"], |
| 45 | + secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"], |
| 46 | + region=os.environ["AWS_REGION"], |
| 47 | + ) |
| 48 | + else: |
| 49 | + store = icechunk.local_filesystem_storage(path=path) |
| 50 | + |
| 51 | + repo = icechunk.Repository.open(store) |
| 52 | + session = repo.readonly_session("main") |
| 53 | + return xr.open_zarr(session.store) |
| 54 | + |
| 55 | + |
| 56 | +def app(date: pd.Timestamp | None = None) -> None: |
| 57 | + """Runs metric calculations on cloudcasting for a given input day and appends to zarr store |
| 58 | +
|
| 59 | + Args: |
| 60 | + date: The day for which the cloudcasting predictions will be scored. |
| 61 | + """ |
| 62 | + |
| 63 | + # Unpack environmental variables |
| 64 | + sat_path = os.environ["SATELLITE_ICECHUNK_ARCHIVE"] |
| 65 | + prediction_dir = os.environ["CLOUDCASTING_PREDICTION_DIRECTORY"] |
| 66 | + metric_zarr_path = os.environ["METRIC_ZARR_PATH"] |
| 67 | + |
| 68 | + |
| 69 | + now = pd.Timestamp.now(tz="UTC").replace(tzinfo=None) |
| 70 | + |
| 71 | + # Default to yesterday |
| 72 | + if date is None: |
| 73 | + date = now.floor("1D") - pd.Timedelta("1D") |
| 74 | + |
| 75 | + start_dt = date.floor("1D") |
| 76 | + end_dt = date.floor("1D") + pd.Timedelta("1D") |
| 77 | + |
| 78 | + if now <= end_dt + FORECAST_STEPS.max(): |
| 79 | + raise Exception( |
| 80 | + f"We cannot score forecast with init-time {end_dt} until after the last valid-time." |
| 81 | + ) |
| 82 | + |
| 83 | + # Open the satellite data store |
| 84 | + ds_sat = open_icechunk(path=sat_path) |
| 85 | + |
| 86 | + # Slice to only the timesteps we need for scoring |
| 87 | + ds_sat = ds_sat.sel(time=slice(start_dt, end_dt + FORECAST_STEPS.max())) |
| 88 | + |
| 89 | + # It is better to preload if we have the RAM space |
| 90 | + # - This eliminates any costs of repeatedly streaming data from the bucket |
| 91 | + # - It's also faster |
| 92 | + ds_sat = ds_sat.compute() |
| 93 | + |
| 94 | + # Find recent forecasts |
| 95 | + date_string = start_dt.strftime("%Y-%m-%d") |
| 96 | + remote_path = f"{prediction_dir}/{date_string}*.zarr" |
| 97 | + fs, path = fsspec.core.url_to_fs(remote_path) |
| 98 | + |
| 99 | + file_list = fs.glob(path) |
| 100 | + |
| 101 | + # Filter forecasts |
| 102 | + # - We only score forecasts we have the satellite data for |
| 103 | + # - If we are missing one satellite image we will skip scoring all forecasts require that |
| 104 | + forecasts_to_score = [] |
| 105 | + |
| 106 | + for file in file_list: |
| 107 | + # Find the datetime of this forecast |
| 108 | + match = re.search(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}', file) |
| 109 | + assert match |
| 110 | + |
| 111 | + # Check the satellite data required to score it is present |
| 112 | + init_time = pd.Timestamp(match.group(0)) |
| 113 | + if np.isin(init_time + FORECAST_STEPS, ds_sat.time).all(): |
| 114 | + forecasts_to_score.append(file) |
| 115 | + else: |
| 116 | + logger.warn(f"Cannot score {file} due to missing satellite data") |
| 117 | + |
| 118 | + ds_mae_list = [] |
| 119 | + |
| 120 | + for file in tqdm(forecasts_to_score): |
| 121 | + ds_forecast = xr.open_zarr(fs.get_mapper(file)).compute() |
| 122 | + |
| 123 | + valid_times = pd.Timestamp(ds_forecast.init_time.item()) + ds_forecast.step |
| 124 | + |
| 125 | + ds_forecast = ( |
| 126 | + ds_forecast |
| 127 | + .assign_coords(time=valid_times) |
| 128 | + .swap_dims({"step":"time"}) |
| 129 | + ) |
| 130 | + |
| 131 | + ds_sat_sel = ds_sat.sel( |
| 132 | + time=ds_forecast.time, |
| 133 | + x_geostationary=ds_forecast.x_geostationary, |
| 134 | + y_geostationary=ds_forecast.y_geostationary, |
| 135 | + variable=ds_forecast.variable, |
| 136 | + ) |
| 137 | + |
| 138 | + da_mae = np.abs( |
| 139 | + (ds_sat_sel.data - ds_forecast.sat_pred) |
| 140 | + .swap_dims({"time":"step"}) |
| 141 | + .drop_vars("time") |
| 142 | + ) |
| 143 | + |
| 144 | + # Create reductions of the full MAE matrix |
| 145 | + da_mae_step = da_mae.mean(dim=("x_geostationary", "y_geostationary", "variable")) |
| 146 | + da_mae_variable = da_mae.mean(dim=("x_geostationary", "y_geostationary", "step")) |
| 147 | + da_mae_spatial = da_mae.mean(dim=("step", "variable")) |
| 148 | + |
| 149 | + ds_mae_reductions = xr.Dataset( |
| 150 | + { |
| 151 | + "mae_step": da_mae_step, |
| 152 | + "mae_variable": da_mae_variable, |
| 153 | + "mae_spatial": da_mae_spatial, |
| 154 | + } |
| 155 | + ) |
| 156 | + |
| 157 | + ds_mae_list.append(ds_mae_reductions) |
| 158 | + |
| 159 | + # Concat all the MAE scores and in-fill missing init times with NaNs |
| 160 | + # - Filling with NaNs makes the chunking easier |
| 161 | + ds_all_maes = xr.concat(ds_mae_list, dim="init_time") |
| 162 | + expected_init_times = pd.date_range(start_dt, end_dt, freq=FORECAST_FREQ, inclusive="left") |
| 163 | + ds_all_maes = ds_all_maes.reindex(init_time=expected_init_times, method=None) |
| 164 | + |
| 165 | + # Chunk the data ready for saving |
| 166 | + ds_all_maes = ds_all_maes.chunk( |
| 167 | + { |
| 168 | + "x_geostationary": -1, |
| 169 | + "y_geostationary": -1, |
| 170 | + "step": -1, |
| 171 | + "variable": -1, |
| 172 | + "init_time": 48 |
| 173 | + } |
| 174 | + ) |
| 175 | + |
| 176 | + # If it exists, open the archive of MAE values and check the coordinates against them |
| 177 | + fs, stripped = fsspec.core.url_to_fs(metric_zarr_path) |
| 178 | + if fs.exists(stripped): |
| 179 | + ds_maes_archive = xr.open_zarr(metric_zarr_path) |
| 180 | + |
| 181 | + if np.isin(ds_all_maes.init_time, ds_maes_archive.init_time).any(): |
| 182 | + raise Exception("init-times in new MAEs already exist in MAE store") |
| 183 | + |
| 184 | + for coord in ["variable", "step", "x_geostationary", "y_geostationary"]: |
| 185 | + if not ds_maes_archive[coord].identical(ds_all_maes[coord]): |
| 186 | + raise Exception("Found differences in coord: {coord}") |
| 187 | + |
| 188 | + ds_all_maes.to_zarr(metric_zarr_path, mode="a-", append_dim="init_time") |
| 189 | + |
| 190 | + else: |
| 191 | + ds_all_maes.to_zarr(metric_zarr_path, mode="w") |
| 192 | + |
| 193 | + |
| 194 | + |
| 195 | +if __name__ == "__main__": |
| 196 | + app() |
0 commit comments