📊 Data Processing and Inspecting¶
Overview¶
This tutorial guides you through setting up a Python environment for climate data processing, harmonizing disparate climate datasets into a unified format, and verifying the processed data. You'll learn to:
- Set up a Python virtual environment in VS Code
- Install required packages for climate data processing
- Process and harmonize climate, population, and soil datasets
- Inspect and verify processed data using Jupyter notebooks
-
Setup
Environment: Python virtual environment
IDE: VS Code
Packages: xarray, numpy, pandas, scipy, etc.
Folders: Organized data structure -
Processing
Tasks: Inspect, standardize, regrid
Output: Harmonized NetCDF files
Format: Unified grid and units
Target: VECTRI-ready data -
Verification
Method: Jupyter notebook
Checks: Metadata, resolution, units
Visualization: Plot verification
Output: Processed data ready for use
🎯 What You'll Learn¶
graph TD
A[Setup Environment] --> B[Install Packages]
B --> C[Create Folders]
C --> D[Process Data]
D --> E[Inspect Results]
E --> F[Verify Output]
style A fill:#e8eaf6
style F fill:#c8e6c9 By the end of this tutorial, you will:
- Set up a Python virtual environment in VS Code
- Install all required packages for climate data processing
- Organize data into structured folders
- Process raw climate datasets into a unified format
- Inspect and verify processed data quality
🚀 Part 1: Setting Up Your Environment¶
Step 1: Open Your Project Folder¶
- Open VS Code
- Go to File > Open Folder...
- Navigate to your project folder (e.g.,
VECTRI-PYTHON) - Select the folder and click "Select Folder"
Step 2: Open a Command Prompt Terminal¶
- Open the terminal in VS Code (View > Terminal or
Ctrl+`) - If the default is PowerShell, click the dropdown arrow next to the
+sign in the terminal panel - Select Command Prompt from the dropdown
Step 3: Create the Virtual Environment¶
In the Command Prompt terminal, run:
This creates a virtual environment in a folder named .venv. A new folder named .venv will appear in your project's file explorer.
Step 4: Activate the Virtual Environment¶
To activate the environment in your Command Prompt session, run:
You will know it's active because the name of the environment will appear in parentheses at the start of your command prompt, like this: (.venv).
Step 5: Select the Python Interpreter¶
VS Code should automatically detect the new environment and ask if you want to use it for the workspace. If you see a notification, click "Yes".
If not, you can set it manually:
- Press
Ctrl+Shift+Pto open the Command Palette - Type and select
Python: Select Interpreter - Choose the Python interpreter from the list that includes
.venvin its path. It should be marked as "Recommended"
Your Command Prompt is now configured with the project's isolated Python environment. Any packages you install will be specific to this project.
📦 Part 2: Installing Required Packages¶
Install Core Packages¶
Install the required packages one by one:
Install Xarray with Complete Dependencies¶
Install xarray with all optional dependencies:
Verify Installation¶
Verify that the packages are installed correctly:
📁 Part 3: Creating Data Folders and download data¶
Create the following folders to organize your data:
Create Processed Data Folder¶
Create a folder for processed data:
Download the data using the following link and place it in the correct folders:
🔄 Part 4: Data Processing¶
Overview of Data Processing¶
The data processing script (process_climate_data.py) performs the following core tasks:
- Inspects raw NetCDF files for metadata (resolution, bounding box, units)
- Standardizes spatial dimensions (renames
lat/lontolatitude/longitude) - Regrids all data to match the resolution and domain of the Precipitation dataset
- Converts Units (e.g., Kelvin to Celsius, kg/m²/s to mm/day)
- Formats attributes and dimensions (e.g., handles specific time dimension requirements)
Step-by-Step Processing Logic¶
Step 1: Configuration & Loading¶
What it does: - Defines file paths for Input (Precip, Temp, Soil, Pop) and Output (data/processed) - Loads all datasets using xarray
Step 2: Data Inspection (inspect_dataset)¶
What it does: Before processing, the script prints key metadata for every input file:
- Variables: Lists available data variables
- Resolution: Calculates the grid step size (e.g.,
0.25degrees) - Bounding Box: Shows the min/max Latitude and Longitude to verify coverage
- Time: Shows the start/end dates and calculates the time step (e.g.,
1.0 days) - Units: Checks the units attribute (e.g.,
mm/day,Kelvin)
Step 3: Dimension Standardization (standardize_dims)¶
Why this is needed: Different datasets often name dimensions differently (e.g., lat vs latitude, lon vs longitude). xarray requires matching names to regrid correctly.
What it does: - Checks if a dataset uses lon/lat - Renames them to longitude/latitude to match the target Precipitation dataset
Step 4: Defining the Target Grid¶
Strategy: The Precipitation dataset is treated as the "Master Grid".
- All other datasets (Temperature, Population, Soil) will be interpolated (regridded) to match this dataset's grid points and resolution exactly
Step 5: Processing Individual Datasets¶
A. Precipitation¶
- Action: The data remains on its original grid
- Unit Conversion: Checks if units are
kg m-2 s-1. If so, multiplies by86400to convert tomm/day - Formatting: Saves variable as
tpwith standard attributes (_FillValue,missing_value)
B. Temperature¶
- Action: Regrids to the Precipitation grid using Linear Interpolation
- Unit Conversion: Checks if units are
Kelvin(K). If so, subtracts273.15to convert todeg C - Formatting: Saves variable as
t2m
C. Population¶
- Action: Regrids to the Precipitation grid
- Method: Uses
nearestneighbor by default (or user selection) to preserve discrete population counts better than linear interpolation - Dimension Handling: Removes the time dimension. The output is a static map
(latitude, longitude) - Attributes: Sets units to
per km2
D. Soil Texture¶
- Action: Regrids to the Precipitation grid
- Variables: Extracts
sand,silt, andclayfractions - Dimension Handling:
- The script creates a single time step (size 1) anchored to the first date of the precipitation data
- It saves this time dimension as UNLIMITED, allowing future tools (like CDO) to append data if needed
- Attributes: Sets specific physical ranges (
vmin,vmax) for each soil type
Step 6: Saving Output¶
All processed files are saved to data/processed/ as NetCDF files:
precip_processed.nctemp_processed.ncpop_processed.ncsoil_processed.nc
Running the Processing Script¶
Default (Linear Interpolation)¶
Use Nearest Neighbor (Better for Population/Categorical Data)¶
🔍 Part 5: Data Inspection and Verification¶
Overview¶
After processing your data, you need to verify that:
- All datasets have been processed correctly
- Metadata (resolution, bounding box, units) is correct
- Data values are reasonable
- Visual inspection confirms proper processing
Using the Verification Notebook¶
The verification notebook (notebooks/verify_processed_data.ipynb) is designed to:
- Load all the processed files from
data/processed/ - Print the same metadata (Resolution, BBox, Time, Units) as the script
- Plot the first time step of each dataset for visual verification
Opening the Notebook¶
- Open VS Code
- Navigate to the
notebooksfolder - Open
verify_processed_data.ipynb - Select the Python interpreter (
.venvenvironment) - Run cells one by one or all at once
Notebook Contents¶
1. Import Libraries¶
2. Define Paths¶
DATA_DIR = r'../data/processed'
FILE_PRECIP = os.path.join(DATA_DIR, 'precip_processed.nc')
FILE_TEMP = os.path.join(DATA_DIR, 'temp_processed.nc')
FILE_POP = os.path.join(DATA_DIR, 'pop_processed.nc')
FILE_SOIL = os.path.join(DATA_DIR, 'soil_processed.nc')
3. Inspection Function¶
The notebook includes an inspect_dataset function that:
- Lists available variables
- Calculates grid resolution
- Shows bounding box (lat/lon ranges)
- Displays time duration and time step
- Reports units for each variable
4. Verify Each Dataset¶
Precipitation Data¶
ds_pr = xr.open_dataset(FILE_PRECIP)
inspect_dataset("Precipitation", ds_pr)
# Plot first time step
plt.figure(figsize=(10, 6))
ds_pr['tp'].isel(time=0).plot()
plt.title("Precipitation (First Time Step)")
plt.show()
Temperature Data¶
ds_t2 = xr.open_dataset(FILE_TEMP)
inspect_dataset("Temperature", ds_t2)
plt.figure(figsize=(10, 6))
ds_t2['t2m'].isel(time=0).plot(cmap='coolwarm')
plt.title("Temperature (First Time Step)")
plt.show()
Population Data¶
ds_pop = xr.open_dataset(FILE_POP)
inspect_dataset("Population", ds_pop)
plt.figure(figsize=(10, 6))
ds_pop['population'].plot(cmap='viridis')
plt.title("Population Density")
plt.show()
Soil Data¶
ds_soil = xr.open_dataset(FILE_SOIL)
inspect_dataset("Soil", ds_soil)
# Plot Clay
if 'soilfraction_clay' in ds_soil:
plt.figure(figsize=(10, 6))
ds_soil['soilfraction_clay'].isel(time=0).plot(cmap='copper_r')
plt.title("Soil Fraction: Clay (First Time Step)")
plt.show()
What to Check¶
When verifying your processed data, ensure:
- Resolution: All datasets should have the same resolution (matching the precipitation dataset)
- Bounding Box: All datasets should cover the same geographic area
- Time Coverage: Temperature and precipitation should have matching time dimensions
- Units:
- Precipitation:
mm/day - Temperature:
degCorK - Population:
per km2 - Values: Check that data values are within reasonable ranges
- Visual Inspection: Maps should look correct and show expected patterns
⚠️ Troubleshooting¶
Common Issues and Solutions¶
Problem: NetCDF library not properly installed
Solution:
If the issue persists, try:
Problem: Dimension names not standardized correctly
Solution: 1. Check the Inspection output to ensure dimension names were standardized correctly 2. Verify that lat/lon were renamed to latitude/longitude 3. Check that the target grid (precipitation) has the correct dimensions
Problem: Required package not installed
Solution:
For example:
Problem: Activation script not found
Solution: 1. Ensure you're in the correct directory 2. Check that .venv folder exists 3. Try using the full path:
Problem: Jupyter not installed or not in environment
Solution:
Or use VS Code's built-in notebook support (recommended)
Problem: Unit conversion may have failed
Solution: 1. Check the original data units 2. Verify unit conversion logic in the processing script 3. Inspect the processed data attributes to confirm units
📋 Quick Reference Checklist¶
Use this checklist to ensure you've completed all steps:
- Opened project folder in VS Code
- Created virtual environment (
.venv) - Activated virtual environment
- Selected Python interpreter in VS Code
- Installed all required packages
- Created all data folders (arc2, chc_cmip6, chirps, etc.)
- Created
data/processedfolder - Placed raw data files in appropriate folders
- Ran data processing script
- Verified processed files exist in
data/processed/ - Opened verification notebook
- Ran all notebook cells
- Verified metadata (resolution, bounding box, units)
- Checked visual plots for each dataset
- Confirmed all datasets are ready for VECTRI
🎓 Best Practices¶
Data Organization¶
- Keep raw data separate from processed data
- Use descriptive folder names for different data sources
- Maintain a consistent naming convention for processed files
- Document data sources and processing steps
Processing¶
- Always inspect raw data before processing
- Verify units before and after processing
- Check for missing values and handle them appropriately
- Use appropriate interpolation methods (linear for continuous, nearest for categorical)
Verification¶
- Always verify processed data before using in models
- Compare processed data with original data visually
- Check metadata matches expectations
- Document any issues or anomalies found
📖 Additional Resources¶
Documentation¶
- Xarray Documentation: https://xarray.pydata.org/
- NetCDF Documentation: https://www.unidata.ucar.edu/software/netcdf/
- SciPy Interpolation: https://docs.scipy.org/doc/scipy/reference/interpolate.html
Related Tutorials¶
🚀 Next Steps¶
-
Run VECTRI Simulations
Use processed data for VECTRI
Configure model parameters -
Analyze Results
Visualize VECTRI outputs
Compare with observations -
Parameter Sensitivity
Test different parameters
Understand model behavior
Need Help?
If you encounter issues or have questions:
- Check the Troubleshooting section
- Review the processing script documentation
- Verify all packages are installed correctly
- Check that data files are in the correct locations
- Contact workshop instructors
📊 Ready for Data Processing!
You now have everything you need to process, harmonize, and verify climate datasets for use with VECTRI and other modeling applications.