Certainly! Below is a unified Python script that combines all the provided Colab cells into a single, executable script. This script allows you to specify the root data directory containing the ifs and aifs folders and an output directory where the extracted data will be saved.
Script Overview
- Imports: Includes all necessary libraries.
- Functions:
sort_grib_files_by_time: Sorts GRIB2 files based on date and time.
get_variable: Extracts a specified variable from a GRIB2 file.
extract_variables_from_all_grib_files: Extracts variables from all sorted GRIB2 files in a directory.
- Main Execution:
- Parses command-line arguments for input and output directories.
- Processes both
ifs and aifs directories.
- Saves the extracted data to the specified output directory.
Complete Python Script
#!/usr/bin/env python3
import os
import glob
import re
import argparse
import pickle
from typing import List, Tuple
import cfgrib
import xarray as xr # Ensure xarray is installed
def sort_grib_files_by_time(directory: str) -> List[str]:
"""
Parses and sorts GRIB2 files by date and time within a directory.
Args:
directory: The directory containing the GRIB2 files.
Returns:
A list of sorted GRIB2 file paths.
"""
file_list = glob.glob(os.path.join(directory, '*.grib2'))
file_data = []
for file_path in file_list:
filename = os.path.basename(file_path)
match = re.search(r'(\d{8})(\d{4})-(\d+)h', filename)
if match:
date_str = match.group(1) # e.g., YYYYMMDD
time_str = match.group(2) # e.g., HHMM
hour_str = match.group(3) # e.g., 12h -> 12
file_data.append((file_path, date_str, int(hour_str)))
else:
print(f"Filename {filename} does not match the expected pattern and will be skipped.")
# Sort by date and hour
sorted_files = sorted(file_data, key=lambda x: (x[1], x[2]))
sorted_file_paths = [file_path for file_path, _, _ in sorted_files]
return sorted_file_paths
def get_variable(path: str, name: str, level: int = 0) -> Tuple:
"""
Extracts a specified variable from a GRIB2 file.
Args:
path: Path to the GRIB2 file.
name: Variable name to extract.
level: Level to select for vertical variables (e.g., isobaricInhPa).
Returns:
A tuple containing the variable values and the valid times.
"""
try:
datasets = xr.open_dataset(path, engine='cfgrib')
if name in datasets:
if level:
data = datasets[name].sel(isobaricInhPa=level).values
else:
data = datasets[name].values
times = datasets["valid_time"].values
return data, times
else:
print(f"Variable '{name}' not found in {path}.")
return None, None
except Exception as e:
print(f"Error opening {path}: {e}")
return None, None
def extract_variables_from_all_grib_files(
directory: str, variable_name: str, level: int = 0
) -> Tuple[List, List]:
"""
Extracts a specified variable from all sorted GRIB2 files in a directory.
Args:
directory: The directory containing the GRIB2 files.
variable_name: The name of the variable to extract.
level: The level to select for vertical variables.
Returns:
A tuple containing two lists:
- List of extracted variable data.
- List of corresponding valid times.
"""
sorted_files = sort_grib_files_by_time(directory)
print(f"Processing {len(sorted_files)} files in '{directory}'...")
data = []
datetimes = []
for file_path in sorted_files:
val, time = get_variable(file_path, variable_name, level)
if val is not None and time is not None:
data.append(val)
datetimes.append(time)
return data, datetimes
def save_data(data: List, datetimes: List, output_path: str, prefix: str):
"""
Saves the extracted data and datetimes to pickle files.
Args:
data: The extracted variable data.
datetimes: The corresponding valid times.
output_path: Directory where the data will be saved.
prefix: Prefix for the output filenames.
"""
os.makedirs(output_path, exist_ok=True)
data_file = os.path.join(output_path, f"{prefix}_data.pkl")
time_file = os.path.join(output_path, f"{prefix}_times.pkl")
with open(data_file, 'wb') as f:
pickle.dump(data, f)
print(f"Saved data to {data_file}")
with open(time_file, 'wb') as f:
pickle.dump(datetimes, f)
print(f"Saved times to {time_file}")
def main(args):
"""
Main function to process GRIB2 files and extract variables.
"""
root_dir = args.data_dir
output_dir = args.output_dir
variable_name = args.variable
level = args.level
# Define subdirectories
ifs_dir = os.path.join(root_dir, 'ifs')
aifs_dir = os.path.join(root_dir, 'aifs')
# Check if directories exist
if not os.path.isdir(ifs_dir):
print(f"IFS directory '{ifs_dir}' does not exist.")
return
if not os.path.isdir(aifs_dir):
print(f"AIFS directory '{aifs_dir}' does not exist.")
return
# Process IFS files
print("Processing IFS files...")
ifs_data, ifs_times = extract_variables_from_all_grib_files(
ifs_dir, variable_name, level
)
save_data(ifs_data, ifs_times, output_dir, 'ifs_msl')
# Process AIFS files
print("Processing AIFS files...")
aifs_data, aifs_times = extract_variables_from_all_grib_files(
aifs_dir, variable_name, level
)
save_data(aifs_data, aifs_times, output_dir, 'aifs_msl')
print("Processing completed successfully.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process GRIB2 files to extract variables.")
parser.add_argument(
"--data_dir",
type=str,
required=True,
help="Path to the root data directory containing 'ifs' and 'aifs' folders."
)
parser.add_argument(
"--output_dir",
type=str,
required=True,
help="Path to the output directory where extracted data will be saved."
)
parser.add_argument(
"--variable",
type=str,
default="msl",
help="Name of the variable to extract from GRIB2 files (default: 'msl')."
)
parser.add_argument(
"--level",
type=int,
default=0,
help="Level to select for vertical variables (e.g., isobaricInhPa). Use 0 if not applicable."
)
args = parser.parse_args()
main(args)
Explanation of the Script
-
Imports:
os, glob, re, argparse, pickle: Standard Python libraries for file handling, pattern matching, argument parsing, and data serialization.
cfgrib, xarray as xr: Libraries for handling GRIB2 files. Make sure to install them using pip install cfgrib xarray.
-
Function sort_grib_files_by_time:
- Searches for
.grib2 files in the specified directory.
- Uses regex to extract date and hour information from filenames.
- Sorts the files based on extracted date and hour.
-
Function get_variable:
- Opens a GRIB2 file using
xarray with the cfgrib engine.
- Extracts the specified variable. If a
level is provided and applicable, it selects data at that level.
- Returns the variable data and corresponding valid times.
-
Function extract_variables_from_all_grib_files:
- Sorts all GRIB2 files in the given directory.
- Iterates through each file, extracting the desired variable using
get_variable.
- Collects all extracted data and valid times into lists.
-
Function save_data:
- Saves the extracted data and times into pickle files for later use.
- Files are named with a prefix indicating whether they are from
ifs or aifs.
-
Function main:
- Parses the input and output directories, variable name, and level from command-line arguments.
- Processes both
ifs and aifs directories.
- Saves the extracted data to the output directory.
-
Command-Line Interface:
How to Use the Script
-
Save the Script:
- Save the above script to a file, e.g.,
extract_grib_variables.py.
-
Install Required Libraries:
-
Prepare Directory Structure:
-
Run the Script:
-
Output:
-
Loading the Data:
- You can load the saved pickle files in Python as follows:
import pickle
with open('/path/to/output/ifs_msl_data.pkl', 'rb') as f:
ifs_data = pickle.load(f)
with open('/path/to/output/ifs_msl_times.pkl', 'rb') as f:
ifs_times = pickle.load(f)
with open('/path/to/output/aifs_msl_data.pkl', 'rb') as f:
aifs_data = pickle.load(f)
with open('/path/to/output/aifs_msl_times.pkl', 'rb') as f:
aifs_times = pickle.load(f)
Notes
-
Error Handling: The script includes basic error handling, such as skipping files that do not match the expected naming pattern and handling missing variables.
-
Customization: You can modify the variable_name and level as needed to extract different variables or levels from the GRIB2 files.
-
Performance: For a large number of files, consider optimizing the script further, possibly by parallelizing the extraction process.
Feel free to modify the script to better fit your specific requirements!