### Install Project Dependencies Source: https://github.com/chia-tung/dlamp/blob/master/README.md Installs the necessary Python packages for the project using pip, including requirements from a 'requirements.txt' file and an upgrade for hydra-core. Ensure Python 3.11 is active in your environment. ```bash pip3 install -r requirements.txt pip3 install hydra-core --upgrade ``` -------------------------------- ### YAML: Example Inference Configuration for predict.yaml Source: https://context7.com/chia-tung/dlamp/llms.txt Provides an example configuration for the 'predict.yaml' file, specifying data, lightning, model, inference, and plot settings. This configuration is crucial for running the prediction script with specific parameters. It defines data sources, batch size, model variants, and inference types. ```yaml data: use_Kth_hour_pred: null lightning: sampling_rate: 1 batch_size: 1 # Must be 1 for inference workers: 4 defaults: - data: rwrf_202502 - lightning: pangu_rwrf_202502 - model: pangu_rwrf_202502 - inference: pangu_rwrf_onnx - plot: pangu_rwrf ``` -------------------------------- ### Install ONNX Runtime with GPU Support Source: https://github.com/chia-tung/dlamp/blob/master/README.md Installs the 'onnxruntime-gpu' package, version 1.18.0. This library is crucial for running ONNX models efficiently on NVIDIA GPUs, requiring a compatible CUDA version. Refer to ONNX Runtime documentation for specific CUDA version matching. ```bash pip install onnxruntime-gpu==1.18.0 ``` -------------------------------- ### Example Usage of CustomDataset and DataManager (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Demonstrates how to initialize and use the CustomDataset with a DataManager. It shows defining data variables, configuring the DataManager for training, and iterating through data batches. The input and output batch structures are specified. ```python from src.managers import DataManager from src.utils import DataCompose # Define variables and levels data_list = DataCompose.from_config({ "Z": ["Hpa850", "Hpa500"], "T": ["Hpa850", "Meter2"], "U": ["Hpa850", "Meter10"], "V": ["Hpa850", "Meter10"], "SLP": ["SeaSurface"], }) # Initialize data manager data_manager = DataManager( data_list, start_time="2020-05-01 00:00", end_time="2024-10-31 23:59", format="%Y-%m-%d %H:%M", time_interval={"hours": 1}, data_shape=[450, 450], image_shape=[224, 224], batch_size=4, workers=4, sampling_rate=3, add_time_features=True, split_config={"train": 0.8, "valid": 0.1, "test": 0.1}, ) data_manager.setup("fit") train_loader = data_manager.train_dataloader() # Iterate through batches for input_batch, output_batch in train_loader: # input_batch: {'upper_air': (B, lv, H, W, c), 'surface': (B, 1, H, W, c+4)} # output_batch: {'upper_air': (B, lv, H, W, c), 'surface': (B, 1, H, W, c)} pass ``` -------------------------------- ### Start Model Training Source: https://github.com/chia-tung/dlamp/blob/master/README.md Executes the main training script for the DLAMP.tw model. This command assumes that all necessary configurations in `config/**/*.yaml` and `src/const.py` have been correctly set up. ```bash python train.py ``` -------------------------------- ### Install NVIDIA Modulus Package Source: https://github.com/chia-tung/dlamp/blob/master/README.md This command sequence clones the NVIDIA Modulus repository and installs the package. Modulus is a toolkit for developing, training, and deploying physics-ML models, likely used as a foundational component in this project. ```bash git clone https://github.com/NVIDIA/modulus.git && cd modulus make install ``` -------------------------------- ### Iterate Through Predefined Evaluation Cases (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Shows how to access and iterate through predefined evaluation cases stored in EVAL_CASES. This example prints the datetime object for each case, useful for running model evaluations. ```python from src.const import DBZ_COLOR, DBZ_NORM, EVAL_CASES import matplotlib.pyplot as plt import numpy as np # Use predefined evaluation cases typhoon_cases = EVAL_CASES["five_days"] for case_dt in typhoon_cases: print(f"Evaluating case: {case_dt}") ``` -------------------------------- ### Start Model Inference Source: https://github.com/chia-tung/dlamp/blob/master/README.md Initiates the prediction process using the trained DLAMP.tw model. This script will likely load a pre-trained model and generate forecasts based on specified inputs and configurations. ```bash python predict.py ``` -------------------------------- ### Train Pangu-Weather Model using PyTorch Lightning Source: https://context7.com/chia-tung/dlamp/llms.txt This script provides the complete workflow for training the Pangu-weather variant model. It uses PyTorch Lightning, Hydra for configuration, and prepares multi-level atmospheric data for training. The output includes training checkpoints. ```python # train.py - Complete training workflow import logging from pathlib import Path import hydra from lightning.pytorch import seed_everything from omegaconf import DictConfig, OmegaConf from src.managers import DataManager from src.models import get_builder from src.utils import DataCompose @hydra.main(version_base=None, config_path="config", config_name="train_pangu") def main(cfg: DictConfig) -> None: hydra_oup_dir = Path(hydra.core.hydra_config.HydraConfig.get().runtime.output_dir) OmegaConf.set_struct(cfg, True) # Prepare multi-level atmospheric data data_list = DataCompose.from_config(cfg.data.train_data) data_manager = DataManager(data_list, **cfg.data, **cfg.lightning) data_manager.setup("test") # Build Pangu model with Swin-Transformer model_builder = get_builder(cfg.model.model_name)( hydra_oup_dir, data_list, image_shape=data_manager.image_shape, add_time_features=cfg.data.add_time_features, **cfg.model, **cfg.lightning, ) model = model_builder.build_model(data_manager.test_dataloader()) # Initialize trainer with WandB logging wandb_logger = model_builder.wandb_logger() wandb_logger.watch(model, log="all") trainer = model_builder.build_trainer(wandb_logger) # Start training with checkpoint resume support trainer.fit( model, data_manager, ckpt_path=getattr(cfg.lightning, "resume_from_checkpoint", None), ) if __name__ == "__main__": main() # Example configuration: config/data/rwrf_202502.yaml """ start_time: "2020-05-01 00:00" end_time: "2024-10-31 23:59" format: "%Y-%m-%d %H:%M" time_interval: hours: 1 data_shape: [450, 450] image_shape: [224, 224] add_time_features: True use_Kth_hour_pred: 3 train_data: Z: # Geopotential height - Hpa200 - Hpa500 - Hpa850 - Hpa1000 T: # Temperature - Hpa200 - Hpa500 - Hpa850 - Meter2 U: # U-wind component - Hpa850 - Meter10 V: # V-wind component - Hpa850 - Meter10 W: # Vertical velocity - Hpa850 Qv: # Water vapor mixing ratio - Hpa850 - Meter2 SLP: # Sea level pressure - SeaSurface PSFC: # Surface pressure - Surface """ # Run training # python train.py # Output: Checkpoint saved to ./checkpoints/Pangu_model_YYMMDD-epoch-XXX-val_loss_XXX.ckpt ``` -------------------------------- ### Load Pangu Lightning Module from Checkpoint Source: https://context7.com/chia-tung/dlamp/llms.txt This Python code snippet demonstrates loading a Pangu Lightning Module from a specified checkpoint file. It utilizes `PanguLightningModule.load_from_checkpoint` and requires the checkpoint path and the model's backbone. The loaded module is then moved to CUDA for GPU acceleration and set to evaluation mode. ```python self.pl_module = PanguLightningModule.load_from_checkpoint( checkpoint_path=self.cfg.inference.best_ckpt, test_dataloader=None, backbone_model=model_builder._backbone_model(), ) self.pl_module = self.pl_module.cuda() self.pl_module.eval() ``` -------------------------------- ### Define Configuration Constants Source: https://context7.com/chia-tung/dlamp/llms.txt This Python script defines various configuration constants and parameters used throughout the project. It includes settings for data sources, file paths, model parameters, and color scales for visualizations. These constants help in maintaining consistency and simplifying configuration management. ```python # src/const.py - Configuration constants from datetime import datetime import matplotlib as mpl import numpy as np # Data source configuration DATA_SOURCE = "CWA_RWRF" VAR_SUFFIX = "WE01H0202500" # File paths BLACKLIST_PATH = "./assets/blacklist_rwrf_3h.txt" CHECKPOINT_DIR = "./checkpoints/" LAND_SEA_MASK_PATH = "./assets/constant_masks/land_sea_mask_4km.npy" TOPOGRAPHY_MASK_PATH = "./assets/constant_masks/topography_mask_4km.npy" COUNTY_SHP_PATH = "./assets/town_shp/COUNTY_MOI_1090820.shp" STANDARDIZATION_PATH = "./assets/standardization/z_score_3h.json" DATA_PATH = "/work/dong1128/rwrf_data/" FIGURE_PATH = "./gallery/" DATA_CONFIG_PATH = "./config/data/rwrf_202502.yaml" # Radar reflectivity color scale (dBZ) DBZ_LV = np.arange(0, 66, 1) DBZ_COLOR = np.concatenate([ np.array([[255, 255, 255]]) , # 0 dBZ - white np.array([np.linspace(0, 0, 14), np.linspace(255, 0, 14), np.linspace(255, 255, 14)]).T, # 1-14 dBZ - cyan to blue np.array([np.linspace(0, 0, 11), np.linspace(255, 150, 11), np.linspace(0, 0, 11)]).T, # 15-25 dBZ - green np.array([np.linspace(255, 255, 5), np.linspace(255, 211, 5), np.linspace(0, 0, 5)]).T, # 30-34 dBZ - yellow np.array([np.linspace(255, 255, 6), np.linspace(200, 120, 6), np.linspace(0, 0, 6)]).T, # 35-40 dBZ - orange np.array([np.linspace(255, 255, 5), np.linspace(96, 0, 5), np.linspace(0, 0, 5)]).T, # 41-45 dBZ - red np.array([np.linspace(244, 150, 10), np.linspace(0, 0, 10), np.linspace(0, 0, 10)]).T, # 46-55 dBZ - dark red np.array([np.linspace(171, 255, 5), np.linspace(0, 0, 5), np.linspace(51, 255, 5)]).T, # 56-60 dBZ - magenta ]) DBZ_COLOR = mpl.colors.ListedColormap(DBZ_COLOR / 255) DBZ_NORM = mpl.colors.BoundaryNorm(DBZ_LV, DBZ_COLOR.N) ``` -------------------------------- ### Python: Initialize Inference Engine and Run Autoregressive Inference Source: https://context7.com/chia-tung/dlamp/llms.txt Initializes the inference engine based on the specified type ('ckpt' or 'onnx') and runs autoregressive inference with optional boundary swapping. It handles loading the appropriate inference class and setting up the necessary parameters. Dependencies include 'importlib', 'hydra', and custom modules like 'InferenceBase'. ```python import importlib from datetime import datetime from pathlib import Path import hydra import matplotlib.pyplot as plt import numpy as np from omegaconf import DictConfig, OmegaConf from tqdm import tqdm from inference import InferenceBase from src.const import DATA_PATH, FIGURE_PATH from src.utils import DataCompose, DataGenerator from visual import * @hydra.main(version_base=None, config_path="config", config_name="predict") def main(cfg: DictConfig) -> None: OmegaConf.set_struct(cfg, True) # Define evaluation cases eval_cases = [ datetime(2020, 5, 21, 17), # Meiyu front datetime(2022, 9, 11), # Typhoon MUIFA datetime(2024, 10, 31, 2), # Typhoon Kong-rey ] eval_cases.sort() # Initialize inference engine (checkpoint or ONNX) if cfg.inference.infer_type == "ckpt": infer_machine = getattr( importlib.import_module("inference"), "BatchInferenceCkpt" ) save_name = cfg.inference.best_ckpt.split("/")[-1].split("-")[0] elif cfg.inference.infer_type == "onnx": infer_machine = getattr( importlib.import_module("inference"), "BatchInferenceOnnx" ) save_name = cfg.inference.onnx_path.split("/")[-1].split(".")[0] infer_machine = infer_machine(cfg, eval_cases) # Run autoregressive inference with optional boundary swapping infer_machine.infer(bdy_swap_method=cfg.inference.bdy_swap_method) ``` -------------------------------- ### Export PyTorch Lightning Checkpoint to ONNX (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Provides Python code for converting a PyTorch Lightning checkpoint file into the ONNX (Open Neural Network Exchange) format. This is useful for optimizing model inference and deploying models across different platforms. ```python # Placeholder for ONNX export code # Example: model.to_onnx('model.onnx', input_sample=...) # Requires PyTorch Lightning and ONNX export libraries. ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/chia-tung/dlamp/blob/master/README.md This snippet demonstrates how to create and activate a new conda virtual environment with Python 3.11. This is a prerequisite for setting up the project's build environment. ```bash conda create --name [env name] python=3.11 -y conda activate [env name] ``` -------------------------------- ### Define Evaluation Cases with Dates (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Defines a dictionary containing lists of datetime objects for different forecast lead times (one_day, three_days, five_days, seven_days). These cases represent specific meteorological events for model testing and evaluation. ```python EVAL_CASES = { "one_day": [ datetime(2021, 6, 4), # Afternoon thunderstorm datetime(2022, 6, 24), # Graupel observation in Taipei datetime(2022, 8, 25), # Summer convection ], "three_days": [ datetime(2020, 5, 21), # Meiyu front datetime(2021, 8, 7), # South-western flow with tropical depression datetime(2023, 4, 20), # Cold front passage ], "five_days": [ datetime(2022, 9, 12), # Typhoon MUIFA (harsh northward turning) datetime(2024, 7, 24), # Typhoon GAEMI (direct landfall) datetime(2024, 10, 31), # Typhoon Kong-rey (passing eastern Taiwan) ], "seven_days": [ datetime(2024, 10, 3), # Typhoon Krathon (slow-moving landfall) ], } ``` -------------------------------- ### Python: Prepare Geographic Coordinates and Visualize Wind Predictions Source: https://context7.com/chia-tung/dlamp/llms.txt Prepares geographic coordinates (latitude and longitude) and visualizes 850 hPa wind predictions. It uses DataCompose for data processing and VizWind for plotting. The output includes both ground truth and predicted wind fields for specified evaluation cases. Dependencies include 'DataCompose', 'VizWind', and 'save_figure'. ```python # Prepare geographic coordinates data_gnrt = infer_machine.data_manager.data_gnrt dc_lat, dc_lon = DataCompose.from_config({"Lat": ["NoRule"], "Lon": ["NoRule"]}) start_t = datetime.strptime(cfg.data.start_time, cfg.data.format) lat = data_gnrt.yield_data(start_t, dc_lat) lon = data_gnrt.yield_data(start_t, dc_lon) # Visualize 850 hPa wind predictions u_compose, v_compose = DataCompose.from_config({"U": ["Hpa850"], "V": ["Hpa850"]}) painter_gt = VizWind(u_compose.level.name) painter_pd = VizWind() itv = infer_machine.output_itv // infer_machine.data_itv for eval_case in tqdm(eval_cases, desc="Plot wind figures"): gt_u, pd_u = infer_machine.get_figure_materials(eval_case, u_compose) gt_v, pd_v = infer_machine.get_figure_materials(eval_case, v_compose) # Generate time labels t_list, i_list = [], [] for i in range(infer_machine.showcase_length): curr_time = eval_case + infer_machine.output_itv * i t_list.append(curr_time.strftime("%Y-%m-%d %HZ")) i_list.append(f"Init: {eval_case.strftime('%Y-%m-%d %HZ')} Fcst: +{i*itv:02d}H") # Plot ground truth fig, _ = painter_gt.plot_1xn(lon, lat, gt_u, gt_v, titles=t_list) remark = f"itv-{itv}_len-{infer_machine.showcase_length}" save_figure(fig, u_compose, save_name, eval_case, None, "gt", "1xn", remark) # Plot predictions fig, _ = painter_pd.plot_1xn(lon, lat, pd_u, pd_v, titles=i_list) dtype = "pd_bdy" if cfg.inference.bdy_swap_method else "pd" save_figure(fig, u_compose, save_name, eval_case, None, dtype, "1xn", remark) if __name__ == "__main__": main() ``` -------------------------------- ### Export PyTorch Model to ONNX Source: https://context7.com/chia-tung/dlamp/llms.txt This script exports a trained PyTorch model to the ONNX format, enabling faster inference and cross-platform deployment. It prepares sample data, builds the model architecture, loads a checkpoint, and then utilizes the `to_onnx` method for export. The export supports dynamic batch sizes and specifies input/output names. Models larger than 2GB can be saved with external data files. ```python import hydra import onnx from omegaconf import DictConfig, OmegaConf from src.managers import DataManager from src.models import PanguLightningModule, get_builder from src.utils import DataCompose @hydra.main(version_base=None, config_path="../config", config_name="predict") def main(cfg: DictConfig) -> None: OmegaConf.set_struct(cfg, True) # Prepare sample data for tracing data_list = DataCompose.from_config(cfg.data.train_data) data_manager = DataManager(data_list, **cfg.data, **cfg.lightning) data_manager.setup("fit") data_loader = data_manager.train_dataloader() inp_data, oup_data = next(iter(data_loader)) inp_data["upper_air"] = inp_data["upper_air"].to("cuda") inp_data["surface"] = inp_data["surface"].to("cuda") # Build model architecture model_builder = get_builder(cfg.model.model_name)( "export_onnx", data_list, image_shape=data_manager.image_shape, add_time_features=cfg.data.add_time_features, **cfg.model, **cfg.lightning, ) # Load from checkpoint pl_module = PanguLightningModule.load_from_checkpoint( checkpoint_path=cfg.inference.best_ckpt, test_dataloader=None, backbone_model=model_builder._backbone_model(), ) # Export to ONNX with dynamic batch size pl_module = pl_module.cuda() date = cfg.inference.best_ckpt.split("_")[1] # e.g. 240831 pl_module.to_onnx( file_path=f"./export/{cfg.model.model_name}_model_{date}.onnx", input_sample=(inp_data["upper_air"], inp_data["surface"]), export_params=True, verbose=False, input_names=["input_upper", "input_surface"], output_names=["output_upper", "output_surface"], dynamic_axes={ "input_upper": {0: "batch_size"}, "input_surface": {0: "batch_size"}, "output_upper": {0: "batch_size"}, "output_surface": {0: "batch_size"}, }, ) print(f"Model exported to ./export/{cfg.model.model_name}_model_{date}.onnx") def save_single_onnx(): """ Save ONNX model with external data file for models > 2GB """ file_path = "./export/Pangu_model_250215.onnx" model = onnx.load(file_path) onnx.save_model( model, "./export/Pangu_model_250215_168.onnx", save_as_external_data=True, all_tensors_to_one_file=True, location="Pangu_model_250215_168_external_data", size_threshold=10240, convert_attribute=False, ) if __name__ == "__main__": main() ``` -------------------------------- ### Custom PyTorch Dataset for Atmospheric Data (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Implements a PyTorch Dataset for multi-level atmospheric data. It processes data based on input and output lengths, sampling rates, and time features. The dataset returns input and output data in a dictionary format, specifying 'upper_air' and 'surface' data with dimensions for levels, height, width, and channels. ```python from collections import defaultdict from datetime import datetime, timedelta import numpy as np from torch.utils.data import Dataset from ..standardization import standardization from ..utils import DataCompose, DataGenerator, Level, TimeUtil class CustomDataset(Dataset): def __init__( self, inp_len: int, oup_len: int, oup_itv: dict[str, int], data_generator: DataGenerator, sampling_rate: int, init_time_list: list[datetime], data_list: list[DataCompose], add_time_features: bool, use_Kth_hour_pred: int | None, is_train_or_valid: bool, ): """ Custom dataset for multi-level atmospheric data Returns data in format: input: { 'upper_air': (lv, h, w, c), # Pressure level data 'surface': (1, h, w, c+4) # Surface data with time features } """ self._ilen = inp_len self._olen = oup_len self._oitv = timedelta(**oup_itv) self._data_gnrt = data_generator self._sr = sampling_rate self._init_time_list = init_time_list self._data_list = data_list self.add_time_features = add_time_features self.use_Kth_hour_pred = use_Kth_hour_pred self._is_train_or_valid = is_train_or_valid def __getitem__(self, index): if self._is_train_or_valid: index *= self._sr input_time = self._init_time_list[index] input = self._get_variables_from_dt(input_time, is_input=True) output_time = input_time + self._oitv output = self._get_variables_from_dt(output_time, is_input=False) return input, output def _get_variables_from_dt(self, dt: datetime, is_input: bool) -> dict[str, np.ndarray]: """ Retrieve and stack atmospheric variables Returns: { 'upper_air': (lv, h, w, c), # Z, T, U, V, W, Qv, Qw at pressure levels 'surface': (1, h, w, c+4) # SLP, SST, PSFC, SWDOWN, OLR + time features } """ pre_output = defaultdict(list) data_dict = self._data_gnrt.yield_data( dt, self._data_list, use_Kth_hour_pred=self.use_Kth_hour_pred ) for var_level_str, data in data_dict.items(): data = standardization(var_level_str, data) # Z-score normalization _, level = DataCompose.retrive_var_level_from_string(var_level_str) if level.is_surface(): pre_output[Level.Surface].append(data) else: pre_output[level].append(data) # Group by level and stack by variable output = defaultdict(list) for level, value in pre_output.items(): value = np.stack(value, axis=-1) # (h, w, c) if level.is_surface(): output["surface"].append(value) else: output["upper_air"].append(value) # Final assembly final = {} for key, value in output.items(): stack_data = np.stack(value, axis=0) # (lv, h, w, c) if is_input and key == "surface" and self.add_time_features: # Add temporal encoding: sin/cos of day-of-year and time-of-day time_features = TimeUtil.create_time_features(dt, stack_data.shape[1:3]) stack_data = np.concatenate([stack_data, time_features[None]], axis=-1) final[key] = stack_data return final ``` -------------------------------- ### Shell: Run Prediction Script Source: https://context7.com/chia-tung/dlamp/llms.txt Command to execute the prediction script. This command initiates the forecasting and visualization process based on the provided configuration. The output includes figures saved to a specified directory structure. ```shell # python predict.py # Output: Figures saved to ./gallery/model_name/init_YYYYMMDD_HHMM/ ``` -------------------------------- ### Post-process and Store Batch Inference Predictions Source: https://context7.com/chia-tung/dlamp/llms.txt This Python code snippet handles the post-processing of batch inference results. It retrieves a product mapping, uses `prediction_postprocess` to format the raw predictions, and then stores these processed predictions as attributes of the class instance (e.g., `input_upper`, `output_surface`). ```python # Concatenate temporal dimension tmp_upper = np.concatenate(tmp_upper, axis=0) tmp_sfc = np.concatenate(tmp_sfc, axis=0) ret.append(( input["upper_air"].cpu().numpy(), input["surface"].cpu().numpy(), target["upper_air"].cpu().numpy(), target["surface"].cpu().numpy(), tmp_upper, tmp_sfc, )) # Post-process and store results mapping = PanguLightningModule.get_product_mapping() predictions = prediction_postprocess(ret, mapping) for product_type, tensor in predictions.items(): setattr(self, product_type, tensor) ``` -------------------------------- ### Autoregressive Forecasting Loop with Boundary Swapping Source: https://context7.com/chia-tung/dlamp/llms.txt This Python code performs autoregressive forecasting within a batch inference process. It iterates through prediction steps, making predictions using the PanguLightningModule. Time features are added if enabled, and optional boundary swapping can be applied to reduce drift. Predictions are stored at specified intervals and converted to NumPy arrays. ```python # Autoregressive forecasting loop tmp_upper, tmp_sfc = [], [] for step in trange(predict_iters, desc=f"Infer batch {batch_id}"): with torch.inference_mode(): inp_upper, inp_surface = self.pl_module(inp_upper, inp_surface) inp_upper = inp_upper.detach().cpu().numpy() inp_surface = inp_surface.detach().cpu().numpy() # Store at specified intervals if (step + 1) % interval == 0: tmp_upper.append(inp_upper.copy()) tmp_sfc.append(inp_surface.copy()) # Add time features (day of year, time of day) curr_time = self.init_time[batch_id] + timedelta(hours=step + 1) if self.cfg.data.add_time_features: time_features = TimeUtil.create_time_features( curr_time, inp_surface.shape[2:4] ) # (H, W, 4) time_features = np.expand_dims(time_features, axis=(0, 1)) inp_surface = np.concatenate((inp_surface, time_features), axis=-1) # Apply boundary swapping to reduce drift if bdy_swap_method: inp_upper = self._boundary_swapping( inp_upper, curr_time, bdy_swap_method["name"], bdy_swap_method["n_of_grid"], ) inp_surface = self._boundary_swapping( inp_surface, curr_time, bdy_swap_method["name"], bdy_swap_method["n_of_grid"], ) inp_upper = torch.from_numpy(inp_upper).cuda() inp_surface = torch.from_numpy(inp_surface).cuda() ``` -------------------------------- ### Plot Radar Reflectivity with Custom Color Scale (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Demonstrates plotting radar reflectivity data using a custom color scale (DBZ_COLOR) and normalization (DBZ_NORM). Includes adding a color bar and title for the plot. Requires matplotlib and numpy. ```python from src.const import DBZ_COLOR, DBZ_NORM, EVAL_CASES import matplotlib.pyplot as plt import numpy as np # Plot radar reflectivity with standard color scale radar_data = np.random.uniform(0, 60, (224, 224)) plt.imshow(radar_data, cmap=DBZ_COLOR, norm=DBZ_NORM) plt.colorbar(label='Reflectivity (dBZ)') plt.title('Radar Reflectivity') ``` -------------------------------- ### Define Wind Speed Levels (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Defines the discrete levels for wind speed in meters per second (m/s), following established scales like Beaufort and Saffir-Simpson. This list is used for categorizing and visualizing wind intensity. ```python WSP_LV = [0, 4, 6, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 36, 38, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85] ``` -------------------------------- ### Define Temperature Levels (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Defines a sequence of temperature levels in degrees Celsius (°C) using NumPy's linspace function. This creates evenly spaced temperature intervals for analysis or visualization. ```python TEMP_LV = np.linspace(6, 30, 41) ``` -------------------------------- ### Define Rain Rate Color Scale and Normalization (Python) Source: https://context7.com/chia-tung/dlamp/llms.txt Defines the color mapping and normalization levels for rain rate in mm/hr, used for visualizing precipitation intensity. It utilizes Matplotlib's ListedColormap and BoundaryNorm for creating a custom color scale. ```python RR_LV = [0, 1, 2, 5, 10, 15, 20, 30, 40, 50, 70, 90, 110, 130, 150, 200, 300] RR_COLOR = mpl.colors.ListedColormap([ "#FFFFFF", # 0 mm/hr "#9CFCFF", # Light rain "#03C8FF", "#059BFF", "#0363FF", # Moderate rain "#059902", "#39FF03", "#FFFB03", # Heavy rain "#FFC800", "#FF9500", "#FF0000", # Very heavy rain "#CC0000", "#990000", "#960099", # Extreme rain "#C900CC", "#FB00FF", "#FDC9FF", ]) RR_NORM = mpl.colors.BoundaryNorm(RR_LV, RR_COLOR.N) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.