[TASK]
"Enhance the temperature interpolation model to improve accuracy and resolution without over-smoothing."
[CURRENT LIMITATION]
"The model produces isolated 'hot' and 'cold' isolated spots due to sparse weather station data and limited dataset coverage."
[DESIRED OUTCOME]
"Ensure high-resolution output with realistic transitions across the grid. Preserve the model’s sensitivity to microclimatic influences, correcting isolated anomalies for a seamless, high-quality output without compromising detail."
[CODE]
def plot_stations_with_boundary_and_interpolation(
trax_stations, trax_temperatures, trax_coords,
netatmo_stations, netatmo_temperatures, netatmo_coords,
imgw_stations, imgw_temperatures, imgw_coords,
modis_day_folder, modis_night_folder):
def compute_water_body_temperature_adjustment(grid_gdf, hour, is_daytime, grid_transform, grid_shape):
"""
Computes the temperature adjustment for water bodies using a physics-based heat balance model.
Adjusts the strength of the temperature adjustment based on time of day.
Parameters:
grid_gdf: GeoDataFrame containing grid points with necessary attributes.
hour: Current hour of the day.
is_daytime: Boolean indicating if it's daytime.
grid_transform: Affine transform of the temperature grid.
grid_shape: Tuple indicating the shape of the temperature grid.
Returns:
A NumPy array with temperature adjustments for each grid cell.
"""
max_temp_change = 2.0 # Maximum temperature change in degrees Celsius per hour
grid_gdf['Water_Temp_Change'] = np.clip(grid_gdf['Water_Temp_Change'], -max_temp_change, max_temp_change)
Apply the temperature adjustment only to water bodies
def apply_water_body_influence(grid_gdf, max_distance=5000):
"""
Applies the influence of water bodies to nearby land areas using a spatial decay function.
Parameters:
Assistant
grid_gdf: GeoDataFrame containing grid points.
max_distance: Maximum distance in meters for water influence.
Returns:
Adjusted temperature values.
"""
from scipy.spatial import cKDTree
def apply_smooth_temperature_adjustment(grid_gdf, temperature_adjustment, is_daytime, buffer_distance_day=3, buffer_distance_night=6):
"""
Applies a smooth temperature adjustment based on distance to water bodies.
Uses a smaller buffer during daytime to preserve spatial variability.
Parameters:
grid_gdf: GeoDataFrame containing grid points.
temperature_adjustment: NumPy array of temperature adjustments.
is_daytime: Boolean indicating if it's daytime.
buffer_distance_day: Buffer distance for daytime in grid units.
buffer_distance_night: Buffer distance for nighttime in grid units.
Returns:
Smoothed temperature adjustment as a NumPy array.
"""
buffer_distance = buffer_distance_day if is_daytime else buffer_distance_night
water_mask = grid_gdf['Water_Body'].values.astype(int)
distance = distance_transform_edt(1 - water_mask) * grid_spacing # Convert to actual distance
transition_zone = (distance > 0) & (distance <= buffer_distance * grid_spacing)
weights = np.ones_like(temperature_adjustment)
weights[transition_zone] = distance[transition_zone] / (buffer_distance * grid_spacing)
temperature_adjustment_smooth = temperature_adjustment * weights
return temperature_adjustment_smooth
for station, temperature in zip(trax_stations, trax_temperatures):
cleaned_station = cleaned_station_dict[station]
Exclude certain stations during daytime
if is_daytime and cleaned_station in exclude_trax_stations_daytime_cleaned:
continue # Skip this station
cleaned_temperature = clean_temperature(temperature)
if cleaned_station in trax_coords and cleaned_temperature is not None:
lat, lon = trax_coords[cleaned_station]
trax_filtered_stations.append(cleaned_station)
trax_filtered_temperatures.append(cleaned_temperature)
trax_geometries.append(Point(lon, lat))
for station, temperature, coord in zip(netatmo_stations, netatmo_temperatures, netatmo_coords):
if isinstance(temperature, (int, float)) and coord is not None:
netatmo_filtered_coords.append(coord)
netatmo_filtered_temperatures.append(temperature)
netatmo_filtered_stations.append(station)
if len(netatmo_filtered_coords) > 0:
netatmo_geometries = [Point(lon, lat) for lat, lon in netatmo_filtered_coords]
netatmo_gdf = gpd.GeoDataFrame({
'Station': netatmo_filtered_stations,
'Temperature': netatmo_filtered_temperatures,
'Source': 'Netatmo'
}, geometry=netatmo_geometries, crs="EPSG:4326")
else:
netatmo_gdf = gpd.GeoDataFrame(columns=['Station', 'Temperature', 'Source', 'geometry'], crs="EPSG:4326")
for station, temperature in zip(imgw_stations, imgw_temperatures):
cleaned_temperature = clean_temperature(temperature)
if station in imgw_coords and cleaned_temperature is not None:
lat, lon = imgw_coords[station]
imgw_filtered_stations.append(station)
imgw_filtered_temperatures.append(cleaned_temperature)
imgw_geometries.append(Point(lon, lat))
1: 'Urban', # Continuous urban fabric
2: 'Urban', # Discontinuous urban fabric
3: 'Industrial', # Industrial or commercial units
4: 'Infrastructure', # Road and rail networks and associated land
5: 'Port', # Port areas (if applicable)
6: 'Airport', # Airports
Mining and extraction areas
7: 'Mine', # Mineral extraction sites
8: 'Dump', # Dump sites
9: 'Construction', # Construction sites
Urban green areas
10: 'Green Urban', # Green urban areas
11: 'Sport Leisure', # Sport and leisure facilities
Agricultural areas
12: 'Arable Land', # Non-irrigated arable land
16: 'Orchards', # Fruit trees and berry plantations
18: 'Pastures', # Pastures
20: 'Complex Cultivation', # Complex cultivation patterns
21: 'Agro-Forest Mix', # Land principally occupied by agriculture, with significant areas of natural vegetation
Ensure that both datasets have the same dummy columns
missing_cols = set(land_cover_dummies_stations.columns) - set(land_cover_dummies_grid.columns)
for col in missing_cols:
grid_gdf[col] = 0
missing_cols = set(land_cover_dummies_grid.columns) - set(land_cover_dummies_stations.columns)
for col in missing_cols:
stations_gdf[col] = 0
required_columns = ['Northness', 'Eastness', 'Hour']
missing_columns = [col for col in required_columns if col not in stations_gdf.columns]
if missing_columns:
raise KeyError(f"The following required columns are missing in stations_gdf: {missing_columns}")
else:
print("All required columns are present in stations_gdf.")
Update feature_columns to include new temporal and interaction features
Define the Stacking Regressor with advanced models
stacking_regressor = StackingRegressor(
estimators=base_estimators,
final_estimator=meta_model,
passthrough=False,
n_jobs=4, # Limited for memory efficiency
cv=3 # Reduced folds for memory efficiency in final estimator
)
Create a pipeline with StandardScaler and Stacking Regressor
pipeline = Pipeline([
('scaler', StandardScaler()), # For linear meta-model (Ridge)
('stack', stacking_regressor)
])
Define BayesSearchCV for advanced hyperparameter optimization
bayes_search = BayesSearchCV(
estimator=pipeline,
search_spaces=param_spaces,
n_iter=40, # Number of iterations for the search
cv=group_kfold.split(X, y, groups=groups),
scoring='r2',
n_jobs=4, # Limit for stability and memory usage
verbose=1,
random_state=42,
pre_dispatch='2*n_jobs', # Memory-efficient dispatch
error_score='raise'
)
Fit BayesSearchCV with sample weights
fit_params = {'stack__sample_weight': sample_weights} if sample_weights is not None else {}
bayes_search.fit(X, y, **fit_params)
print("BayesSearchCV completed with Spatial GroupKFold and Feature Scaling.")
required_columns = ['Northness', 'Eastness', 'Hour']
missing_columns = [col for col in required_columns if col not in grid_gdf.columns]
if missing_columns:
raise KeyError(f"The following required columns are missing in grid_gdf: {missing_columns}")
else:
print("All required columns are present in grid_gdf.")
Include MODIS_LST in grid_gdf (Already included)
Prepare data for regression prediction
Include land cover dummy variables and new temporal/interactions
for col in land_cover_dummies_stations.columns:
if col not in grid_gdf.columns:
grid_gdf[col] = 0
rbf_func = Rbf(
residuals_df['X'].values,
residuals_df['Y'].values,
residuals_df['Residual_Normalized'].values,
function='multiquadric', # More stable than thin_plate
smooth=0.1, # Small non-zero smoothing factor
epsilon=np.mean([
np.diff(np.sort(residuals_df['X'].unique())).mean(),
np.diff(np.sort(residuals_df['Y'].unique())).mean()
]) # Adaptive epsilon based on average point spacing
)
Apply adjustments to the interpolated temperatures (no changes here)
grid_gdf['Temperature'] += adjustment
def compute_dynamic_forest_cooling(grid_gdf, hour, is_daytime):
"""
Compute dynamic forest cooling effect based on tree cover density,
time of day, and local environmental conditions.
Adjusts cooling intensity based on whether it's daytime or nighttime.
Parameters:
grid_gdf: GeoDataFrame containing grid points.
hour: Current hour of the day.
is_daytime: Boolean indicating if it's daytime.
Returns:
Cooling effect as a NumPy array.
"""
Base cooling parameters
max_cooling_day = 2.0 # Reduced maximum cooling during daytime
max_cooling_night = 1.5 # Reduced maximum cooling during nighttime
Time-based modulation (stronger during day, weaker at night)
To enhance your temperature interpolation model for improved accuracy and resolution while avoiding over-smoothing and correcting isolated anomalies, you can implement several key modifications. The primary goal is to ensure seamless temperature transitions across the grid, preserve microclimatic sensitivities, and eliminate unrealistic isolated hot and cold spots.
Below are detailed recommendations and corresponding code enhancements to achieve the desired outcomes:
Replace RBF Interpolation with Kriging for Residuals:
Radial Basis Function (RBF) interpolation tends to produce smooth surfaces, which might lead to over-smoothing in areas with sparse data. Kriging, on the other hand, is a geostatistical method that provides Best Linear Unbiased Predictions (BLUP) and can better handle spatial dependencies and variogram structures.
Implement Adaptive Variogram Models:
Utilize spatially varying variogram parameters to capture local spatial dependencies more effectively. This approach allows the model to adapt to different spatial structures across the study area, preserving local variations without over-smoothing.
Introduce Spatial Regularization in Machine Learning Models:
Integrate spatial regularization techniques within your machine learning pipeline to enforce spatial smoothness constraints while maintaining local details.
Apply Conditional Smoothing to Correct Isolated Anomalies:
Detect and correct isolated anomalies using conditional smoothing techniques that preserve significant local variations while smoothing out unrealistic extremes.
Enhance Cross-Validation with Spatial Blocking:
Improve your cross-validation strategy by incorporating spatial blocking to ensure that training and validation sets are spatially segregated, preventing data leakage and capturing spatial dependencies more effectively.
Below, I provide detailed code modifications and explanations for each recommendation.
1. Replace RBF Interpolation with Kriging for Residuals
Why Kriging?
Kriging offers several advantages over RBF:
Spatial Dependency: It considers the spatial autocorrelation in the data.
Variogram Modeling: It allows explicit modeling of spatial structures.
Uncertainty Quantification: It provides variance estimates for predictions.
Implementation Steps:
Install Required Libraries:
You'll need the pykrige library for Kriging. Install it using pip if you haven't already.
bash
pip install pykrige
Modify Residual Interpolation:
Replace the RBF interpolation of residuals with Ordinary Kriging.
python
from pykrige.ok import OrdinaryKriging
from scipy.ndimage import gaussian_filter
def perform_kriging_interpolation(residuals_df, grid_gdf):
"""
Perform Ordinary Kriging interpolation on residuals.
Parameters:
- residuals_df: DataFrame containing 'X', 'Y', and 'Residual_Normalized' columns.
- grid_gdf: GeoDataFrame containing grid points where residuals need to be interpolated.
Returns:
- interpolated_residuals: NumPy array of interpolated residuals for each grid point.
"""
# Extract coordinates and residuals
x = residuals_df['X'].values
y = residuals_df['Y'].values
residuals = residuals_df['Residual_Normalized'].values
# Define variogram parameters (these may need tuning)
variogram_model = 'exponential' # Options: 'linear', 'power', 'gaussian', 'exponential', etc.
variogram_parameters = {
'sill': np.var(residuals),
'range': estimate_optimal_range(residuals_df) * 1.2,
'nugget': 0.1 * np.var(residuals)
}
# Initialize Kriging model
OK = OrdinaryKriging(
x, y, residuals,
variogram_model=variogram_model,
variogram_parameters=variogram_parameters,
verbose=False,
enable_plotting=False
)
# Perform Kriging on grid points
z, ss = OK.execute('points', grid_gdf['X'].values, grid_gdf['Y'].values)
# Denormalize residuals
residual_mean = residuals_df['Residual'].mean()
residual_std = residuals_df['Residual'].std()
interpolated_residuals = z * residual_std + residual_mean
# Apply conditional smoothing to remove over-smoothing
interpolated_residuals = gaussian_filter(interpolated_residuals, sigma=1.0)
return interpolated_residuals
Integrate Kriging into the Existing Pipeline:
Replace the RBF interpolation section in your code with the Kriging-based interpolation.
python
# 2.1. Regression-Kriging Interpolation
# Calculate predicted global trend for 'data'
global_trend_data = best_pipeline.predict(data[feature_columns])
# Calculate residuals based on 'data'
residuals = data['Temperature'] - global_trend_data
# Prepare a DataFrame with 'X', 'Y', and 'Residual' aligned with 'data'
residuals_df = data.copy()
residuals_df['Residual'] = residuals
# Remove outliers from residuals using IQR
residuals_df = remove_outliers_iqr(residuals_df)
# Normalize residuals to prevent extreme values
residuals_mean = residuals_df['Residual'].mean()
residuals_std = residuals_df['Residual'].std()
residuals_df['Residual_Normalized'] = (residuals_df['Residual'] - residuals_mean) / residuals_std
# Perform Kriging interpolation
interpolated_residuals = perform_kriging_interpolation(residuals_df, grid_gdf)
# Assign interpolated residuals to grid_gdf
grid_gdf['Residual'] = interpolated_residuals
# Add validation to catch any remaining extreme values
final_std = np.std(grid_gdf['Residual'])
final_mean = np.mean(grid_gdf['Residual'])
z_threshold = 3 # Number of standard deviations for clipping
grid_gdf['Residual'] = grid_gdf['Residual'].clip(
lower=final_mean - z_threshold * final_std,
upper=final_mean + z_threshold * final_std
)
# Apply corrections with physical constraints
grid_gdf['Residual'] = grid_gdf['Residual'].fillna(0)
# Continue with the rest of your pipeline...
Benefits:
Preserves Local Variations: Kriging better captures local anomalies without enforcing global smoothness.
Spatially Informed: It inherently accounts for spatial autocorrelation based on the variogram.
2. Implement Adaptive Variogram Models
Why Adaptive Variogram Models?
Spatial structures can vary across different regions of your study area. A single variogram model may not capture all spatial dependencies effectively. By adapting variogram parameters locally, you can better model heterogeneous spatial processes.
Implementation Steps:
Define a Function for Adaptive Variogram Estimation:
python
def adaptive_variogram_parameters(data, model='exponential', block_size=10):
"""
Perform adaptive variogram parameter estimation by dividing the study area into blocks.
Parameters:
- data: DataFrame containing 'X', 'Y', and 'Residual' columns.
- model: Variogram model to use.
- block_size: Number of clusters to divide the data into.
Returns:
- A list of variogram parameter dictionaries for each block.
"""
from sklearn.cluster import KMeans
# Cluster the data spatially
kmeans = KMeans(n_clusters=block_size, random_state=42)
clusters = kmeans.fit_predict(data[['X', 'Y']])
variogram_params_list = []
for cluster in range(block_size):
cluster_data = data[data['Cluster'] == cluster]
if len(cluster_data) < 10:
continue # Skip clusters with insufficient data
x = cluster_data['X'].values
y = cluster_data['Y'].values
residuals = cluster_data['Residual'].values
sill = np.var(residuals)
range_param = estimate_optimal_range(cluster_data) * 1.2
nugget = 0.1 * sill
variogram_params = {
'sill': sill,
'range': range_param,
'nugget': nugget,
'model': model
}
variogram_params_list.append(variogram_params)
return variogram_params_list
Modify the Kriging Function to Use Adaptive Variograms:
Update the perform_kriging_interpolation function to handle multiple variogram models based on spatial clusters.
Benefits:
Local Adaptation: Captures varying spatial structures across different regions.
Improved Accuracy: Provides more accurate residual estimates by tailoring variogram parameters locally.
Preserved Spatial Detail: Reduces the risk of over-smoothing by adapting to local spatial dependencies.
3. Introduce Spatial Regularization in Machine Learning Models
Why Spatial Regularization?
Incorporating spatial information directly into your machine learning models can help enforce spatial smoothness constraints, ensuring that predictions in neighboring grid cells are coherent, thereby reducing isolated anomalies.
Implementation Steps:
Add Spatial Features:
Incorporate neighboring grid information as features in your model. For example, include average temperature of adjacent grid cells as additional features.
python
def add_spatial_features(grid_gdf, radius=250):
"""
Add spatially derived features based on neighboring grid points.
Parameters:
- grid_gdf: GeoDataFrame containing grid points with 'Temperature'.
- radius: Radius in meters to consider for neighboring points.
Returns:
- grid_gdf: GeoDataFrame with new spatial features.
"""
from sklearn.neighbors import BallTree
import numpy as np
# Convert degrees to radians for BallTree
coords = np.vstack((grid_gdf['Y'], grid_gdf['X'])).T
rad_coords = np.radians(coords)
# Build BallTree
tree = BallTree(rad_coords, metric='haversine')
# Radius in radians
radius_rad = radius / 6371000 # Earth's radius in meters
# Query neighbors
indices = tree.query_radius(rad_coords, r=radius_rad)
# Compute average temperature of neighbors
avg_temp = []
for i, neighbors in enumerate(indices):
if len(neighbors) > 1:
mean_temp = grid_gdf['Temperature'].iloc[neighbors].mean()
else:
mean_temp = grid_gdf['Temperature'].iloc[neighbors].mean()
avg_temp.append(mean_temp)
grid_gdf['Avg_Neighbor_Temp'] = avg_temp
return grid_gdf
Integrate Spatial Features into the Model:
Update your feature set to include the newly added spatial features.
python
Benefits:
Spatial Coherence: Encourages the model to produce predictions that are coherent with neighboring grid cells.
Enhanced Feature Space: Provides the model with contextual spatial information, improving prediction accuracy.
Reduction of Isolated Anomalies: Helps mitigate the issue of isolated hot/cold spots by leveraging spatial dependencies.
4. Apply Conditional Smoothing to Correct Isolated Anomalies
Why Conditional Smoothing?
While spatial interpolation ensures overall smoothness, isolated anomalies can still occur due to data sparsity or localized microclimatic effects. Conditional smoothing selectively smooths regions with unrealistic anomalies while preserving genuine local variations.
Implementation Steps:
Define Anomaly Detection Criteria:
Identify grid points with residuals exceeding a certain threshold (e.g., based on standard deviations).
python
def detect_anomalies(grid_gdf, threshold=3):
"""
Detect anomalies in the residuals.
Parameters:
- grid_gdf: GeoDataFrame containing 'Residual' column.
- threshold: Number of standard deviations to consider as anomalies.
Returns:
- anomaly_mask: Boolean array indicating anomaly locations.
"""
residual_std = np.std(grid_gdf['Residual'])
residual_mean = np.mean(grid_gdf['Residual'])
anomaly_mask = (grid_gdf['Residual'] > residual_mean + threshold * residual_std) | \
(grid_gdf['Residual'] < residual_mean - threshold * residual_std)
return anomaly_mask
Apply Conditional Smoothing:
Smooth only the anomalous regions by replacing them with the average of neighboring non-anomalous points.
python
Benefits:
Targeted Correction: Only abnormal residuals are smoothed, preserving genuine local temperature variations.
Enhanced Realism: Reduces the likelihood of unrealistic isolated hot/cold spots without compromising overall spatial continuity.
Flexibility: Thresholds and smoothing radii can be adjusted based on data characteristics and desired outcomes.
5. Enhance Cross-Validation with Spatial Blocking
Why Spatial Blocking?
Standard cross-validation can lead to overestimation of model performance due to spatial autocorrelation (i.e., similar observations appearing in both training and validation sets). Spatial blocking ensures that training and validation sets are spatially separated, providing a more realistic assessment of model performance.
Implementation Steps:
Define Spatial Blocks:
Divide the study area into spatial blocks (e.g., using KMeans clustering) and use these blocks as groups in GroupKFold.
python
def define_spatial_blocks(X, Y, n_blocks=5):
"""
Define spatial blocks using KMeans clustering.
Parameters:
- X: Array-like, X coordinates.
- Y: Array-like, Y coordinates.
- n_blocks: Number of spatial blocks.
Returns:
- groups: Array of group labels for each sample.
"""
from sklearn.cluster import KMeans
import numpy as np
coords = np.vstack((X, Y)).T
kmeans = KMeans(n_clusters=n_blocks, random_state=42)
groups = kmeans.fit_predict(coords)
return groups
Integrate Spatial Blocking into Cross-Validation:
Update your GroupKFold implementation to use spatial blocks.
python
# Define spatial blocks
groups = define_spatial_blocks(stations_gdf_filtered['X'], stations_gdf_filtered['Y'], n_blocks=10)
# Define GroupKFold cross-validator
group_kfold = GroupKFold(n_splits=5)
# Update BayesSearchCV with the new groups
bayes_search = BayesSearchCV(
estimator=pipeline,
search_spaces=param_spaces,
n_iter=40, # Number of iterations for the search
cv=group_kfold.split(X, y, groups=groups),
scoring='r2',
n_jobs=4, # Limit for stability and memory usage
verbose=1,
random_state=42,
pre_dispatch='2*n_jobs', # Memory-efficient dispatch
error_score='raise'
)
Update Cross-Validation During Model Evaluation:
Ensure that the cross-validation during model evaluation also uses spatial blocking.
python
Benefits:
Realistic Performance Metrics: Provides an unbiased estimate of model performance in spatial contexts.
Prevents Data Leakage: Ensures that spatially close data points do not appear in both training and validation sets.
Enhances Model Generalization: Encourages the model to generalize better to unseen spatial regions.
Summary of Enhancements
By implementing the above modifications, your temperature interpolation model will benefit from:
Improved Spatial Accuracy: Kriging captures spatial dependencies more effectively than RBF.
Adaptive Modeling: Local variogram parameters adapt to varying spatial structures, preserving local details.
Spatial Awareness in Machine Learning: Incorporating spatial features enforces spatial coherence in predictions.
Robust Cross-Validation: Spatial blocking ensures realistic performance evaluation and enhances model generalization.
These enhancements collectively contribute to a high-resolution, accurate, and seamless temperature interpolation model that preserves microclimatic influences and eliminates unrealistic temperature anomalies.
Complete Enhanced Code Snippet
Below is a consolidated version of the enhanced sections of your code incorporating the above recommendations. Please integrate these sections appropriately into your existing codebase.
python
By incorporating these enhancements, your temperature interpolation model will achieve higher accuracy and resolution, maintain realistic spatial transitions, and effectively eliminate isolated temperature anomalies. These modifications leverage advanced geostatistical methods, spatial regularization, and targeted smoothing techniques to ensure a seamless and high-quality temperature grid.
Not yet included in a published release.
python
def perform_adaptive_kriging_interpolation(residuals_df, grid_gdf, block_size=10):
"""
Perform Adaptive Ordinary Kriging interpolation on residuals.
Parameters:
- residuals_df: DataFrame containing 'X', 'Y', and 'Residual_Normalized' columns.
- grid_gdf: GeoDataFrame containing grid points where residuals need to be interpolated.
- block_size: Number of spatial clusters for adaptive variogram.
Returns:
- interpolated_residuals: NumPy array of interpolated residuals for each grid point.
"""
from pykrige.ok import OrdinaryKriging
from sklearn.cluster import KMeans
from scipy.ndimage import gaussian_filter
# Cluster the residuals spatially
kmeans = KMeans(n_clusters=block_size, random_state=42)
residuals_df['Cluster'] = kmeans.fit_predict(residuals_df[['X', 'Y']])
# Initialize the interpolated residuals array
interpolated_residuals = np.zeros(len(grid_gdf))
for cluster in range(block_size):
cluster_data = residuals_df[residuals_df['Cluster'] == cluster]
if len(cluster_data) < 10:
continue # Skip clusters with insufficient data
x = cluster_data['X'].values
y = cluster_data['Y'].values
residuals = cluster_data['Residual_Normalized'].values
variogram_model = 'exponential'
sill = np.var(residuals)
range_param = estimate_optimal_range(cluster_data) * 1.2
nugget = 0.1 * sill
OK = OrdinaryKriging(
x, y, residuals,
variogram_model=variogram_model,
variogram_parameters={'sill': sill, 'range': range_param, 'nugget': nugget},
verbose=False,
enable_plotting=False
)
# Identify grid points within the range of the cluster
cluster_center_x = cluster_data['X'].mean()
cluster_center_y = cluster_data['Y'].mean()
distances = np.sqrt((grid_gdf['X'] - cluster_center_x)**2 + (grid_gdf['Y'] - cluster_center_y)**2)
max_range = range_param * 1.5 # Buffer around the variogram range
mask = distances <= max_range
if not mask.any():
continue # No grid points to interpolate for this cluster
z, ss = OK.execute('points', grid_gdf.loc[mask, 'X'].values, grid_gdf.loc[mask, 'Y'].values)
interpolated_residuals[mask] += z # Accumulate interpolated values
# Denormalize residuals
residual_mean = residuals_df['Residual'].mean()
residual_std = residuals_df['Residual'].std()
interpolated_residuals = interpolated_residuals * residual_std + residual_mean
# Apply conditional smoothing to remove over-smoothing
interpolated_residuals = gaussian_filter(interpolated_residuals, sigma=1.0)
return interpolated_residuals
Integrate Adaptive Kriging into the Pipeline:
python
# 2.1. Regression-Adaptive Kriging Interpolation
# Calculate predicted global trend for 'data'
global_trend_data = best_pipeline.predict(data[feature_columns])
# Calculate residuals based on 'data'
residuals = data['Temperature'] - global_trend_data
# Prepare a DataFrame with 'X', 'Y', and 'Residual' aligned with 'data'
residuals_df = data.copy()
residuals_df['Residual'] = residuals
# Remove outliers from residuals using IQR
residuals_df = remove_outliers_iqr(residuals_df)
# Normalize residuals to prevent extreme values
residuals_mean = residuals_df['Residual'].mean()
residuals_std = residuals_df['Residual'].std()
residuals_df['Residual_Normalized'] = (residuals_df['Residual'] - residuals_mean) / residuals_std
# Perform Adaptive Kriging interpolation
interpolated_residuals = perform_adaptive_kriging_interpolation(residuals_df, grid_gdf, block_size=10)
# Assign interpolated residuals to grid_gdf
grid_gdf['Residual'] = interpolated_residuals
# Add validation to catch any remaining extreme values
final_std = np.std(grid_gdf['Residual'])
final_mean = np.mean(grid_gdf['Residual'])
z_threshold = 3 # Number of standard deviations for clipping
grid_gdf['Residual'] = grid_gdf['Residual'].clip(
lower=final_mean - z_threshold * final_std,
upper=final_mean + z_threshold * final_std
)
# Apply corrections with physical constraints
grid_gdf['Residual'] = grid_gdf['Residual'].fillna(0)
# Continue with the rest of your pipeline...
# After predicting Temperatures and before residual correction
grid_gdf = add_spatial_features(grid_gdf, radius=250) # 250 meters
# Update feature_columns to include 'Avg_Neighbor_Temp'
feature_columns = [
'X', 'Y', 'Elevation', 'Tree_Cover', 'Distance_to_Water', 'Water_Body',
'MODIS_LST', 'Population_Density', 'Built_Up', 'Slope', 'Aspect',
'Northness', 'Eastness',
'sin_hour', 'cos_hour',
'Elevation_sin_hour', 'Elevation_cos_hour',
'Avg_Neighbor_Temp' # New spatial feature
] + list(land_cover_dummies_stations.columns)
Retrain the Model:
Retrain your machine learning models to incorporate the new spatial features, enabling them to learn spatial dependencies directly.
python
# Re-define X with the updated feature_columns
X = stations_gdf[feature_columns]
y = stations_gdf['Temperature']
# Continue with the existing pipeline and model training steps
def conditional_smoothing(grid_gdf, anomaly_mask, radius=250):
"""
Apply conditional smoothing to anomalous grid points.
Parameters:
- grid_gdf: GeoDataFrame containing grid points with 'Residual'.
- anomaly_mask: Boolean array indicating anomaly locations.
- radius: Radius in meters to consider for smoothing neighbors.
Returns:
- grid_gdf: GeoDataFrame with smoothed residuals.
"""
from sklearn.neighbors import BallTree
import numpy as np
# Convert degrees to radians for BallTree
coords = np.vstack((grid_gdf['Y'], grid_gdf['X'])).T
rad_coords = np.radians(coords)
# Build BallTree
tree = BallTree(rad_coords, metric='haversine')
# Radius in radians
radius_rad = radius / 6371000 # Earth's radius in meters
# Iterate over anomalous points
for i, is_anomaly in enumerate(anomaly_mask):
if is_anomaly:
# Find neighbors within radius
indices = tree.query_radius([rad_coords[i]], r=radius_rad)[0]
# Exclude self
indices = indices[indices != i]
if len(indices) > 0:
# Compute mean of non-anomalous neighbors
non_anomalies = ~anomaly_mask[indices]
if non_anomalies.any():
mean_val = grid_gdf['Residual'].iloc[indices[non_anomalies]].mean()
grid_gdf.at[grid_gdf.index[i], 'Residual'] = mean_val
return grid_gdf
Integrate Conditional Smoothing into the Pipeline:
Apply anomaly detection and conditional smoothing after residual interpolation.