# Filter and clean Traxelektronik data
for station, temperature in zip(trax_stations, trax_temperatures):
cleaned_station = clean_station_name(station)
cleaned_temperature = clean_temperature(temperature)
if station in trax_coords and cleaned_temperature is not None:
lat, lon = trax_coords[station]
trax_filtered_stations.append(cleaned_station)
trax_filtered_temperatures.append(cleaned_temperature)
trax_geometries.append(Point(lon, lat))
# Create GeoDataFrame for Traxelektronik data
trax_gdf = gpd.GeoDataFrame({
'Station': trax_filtered_stations,
'Temperature': trax_filtered_temperatures,
'Source': 'Traxelektronik'
}, geometry=trax_geometries, crs="EPSG:4326")
# Handle Netatmo data
netatmo_filtered_coords = []
netatmo_filtered_temperatures = []
netatmo_filtered_stations = []
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")
# Handle IMGW data
imgw_filtered_stations = []
imgw_filtered_temperatures = []
imgw_geometries = []
# Clean and process IMGW data
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))
# Create GeoDataFrame for IMGW data
imgw_gdf = gpd.GeoDataFrame({
'Station': imgw_filtered_stations,
'Temperature': imgw_filtered_temperatures,
'Source': 'IMGW'
}, geometry=imgw_geometries, crs="EPSG:4326")
# Read and clip DEM
dem_data, dem_transform = read_and_clip_dem(masovian_boundary)
# Read and clip Forest Cover
forest_data, forest_transform = read_and_clip_forest(masovian_boundary)
# Read and clip Water Bodies
water_data, water_transform = read_and_clip_water_bodies(masovian_boundary)
# Read ECOSTRESS data
ecostress_data, ecostress_transform = read_and_clip_ecostress(masovian_boundary)
# Ensure geometries are in EPSG:4326
trax_gdf_dem_crs = trax_gdf.to_crs("EPSG:4326")
netatmo_gdf_dem_crs = netatmo_gdf.to_crs("EPSG:4326")
imgw_gdf_dem_crs = imgw_gdf.to_crs("EPSG:4326")
# Get elevation at station points using dem_data and dem_transform
trax_elevations = get_elevation_at_points(
trax_gdf_dem_crs.geometry,
dem_data=dem_data,
dem_transform=dem_transform
)
netatmo_elevations = get_elevation_at_points(
netatmo_gdf_dem_crs.geometry,
dem_data=dem_data,
dem_transform=dem_transform
)
imgw_elevations = get_elevation_at_points(
imgw_gdf_dem_crs.geometry,
dem_data=dem_data,
dem_transform=dem_transform
)
# Add elevation to the GeoDataFrames
trax_gdf['Elevation'] = trax_elevations
netatmo_gdf['Elevation'] = netatmo_elevations
imgw_gdf['Elevation'] = imgw_elevations
# Get tree cover density at station points using forest_data and forest_transform
trax_forest = get_raster_value_at_points(
trax_gdf_dem_crs.geometry,
raster_data=forest_data,
raster_transform=forest_transform
)
netatmo_forest = get_raster_value_at_points(
netatmo_gdf_dem_crs.geometry,
raster_data=forest_data,
raster_transform=forest_transform
)
imgw_forest = get_raster_value_at_points(
imgw_gdf_dem_crs.geometry,
raster_data=forest_data,
raster_transform=forest_transform
)
# Add tree cover density to the GeoDataFrames
trax_gdf['Tree_Cover'] = trax_forest
netatmo_gdf['Tree_Cover'] = netatmo_forest
imgw_gdf['Tree_Cover'] = imgw_forest
# Get water body data at station points
trax_water = get_water_body_at_points(
trax_gdf_dem_crs.geometry,
water_data=water_data,
water_transform=water_transform
)
netatmo_water = get_water_body_at_points(
netatmo_gdf_dem_crs.geometry,
water_data=water_data,
water_transform=water_transform
)
imgw_water = get_water_body_at_points(
imgw_gdf_dem_crs.geometry,
water_data=water_data,
water_transform=water_transform
)
# Add water body data to the GeoDataFrames
trax_gdf['Water_Body'] = trax_water
netatmo_gdf['Water_Body'] = netatmo_water
imgw_gdf['Water_Body'] = imgw_water
# Add 'Priority' column to each GeoDataFrame
trax_gdf['Priority'] = 2
netatmo_gdf['Priority'] = 1
imgw_gdf['Priority'] = 3 # Higher priority
# Combine GeoDataFrames
stations_gdf = gpd.GeoDataFrame(pd.concat([trax_gdf, netatmo_gdf, imgw_gdf], ignore_index=True))
stations_gdf.crs = "EPSG:4326"
stations_gdf = stations_gdf.dropna(subset=['Temperature', 'Elevation', 'Tree_Cover'])
# Extract coordinates
stations_gdf['X'] = stations_gdf.geometry.x
stations_gdf['Y'] = stations_gdf.geometry.y
# Prepare data for regression
X = stations_gdf[['X', 'Y', 'Elevation', 'Tree_Cover', 'Water_Body']]
y = stations_gdf['Temperature']
# Normalize covariates
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Fit Random Forest Regression model
print("Training Random Forest Regression model...")
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_scaled, y)
# Predict temperatures and compute residuals
stations_gdf['Predicted_Temperature'] = rf_model.predict(X_scaled)
stations_gdf['Residual'] = stations_gdf['Temperature'] - stations_gdf['Predicted_Temperature']
# Outlier detection using Z-score
stations_gdf['Residual_Z'] = zscore(stations_gdf['Residual'])
z_threshold = 2 # Set your threshold
stations_gdf_inliers = stations_gdf[np.abs(stations_gdf['Residual_Z']) <= z_threshold].copy()
# Remove duplicates by prioritizing IMGW data
data = stations_gdf_inliers.copy()
# Sort by priority (higher priority first)
data = data.sort_values('Priority', ascending=False)
# Group by coordinates and keep the first record in each group (highest priority)
data = data.groupby(['X', 'Y'], as_index=False).first()
unique_points = data[['X', 'Y']].values
unique_residuals = data['Residual'].values
unique_elevation = data['Elevation'].values
unique_tree_cover = data['Tree_Cover'].values
unique_water_body = data['Water_Body'].values
# Create grid in EPSG:4326 using rasterio's transform functions
# Adjust grid_spacing as per your requirements
grid_spacing = 0.0025 # Approximately ~5 km
x_min, y_min, x_max, y_max = masovian_boundary.total_bounds
# Compute the number of cols and rows with the new grid_spacing
ncols = int(np.ceil((x_max - x_min) / grid_spacing))
nrows = int(np.ceil((y_max - y_min) / grid_spacing))
# Create the affine transform for the grid
transform = from_origin(x_min, y_max, grid_spacing, grid_spacing)
# Create arrays of row and column indices
cols = np.arange(ncols)
rows = np.arange(nrows)
# Create a meshgrid of indices
cols_indices, rows_indices = np.meshgrid(cols, rows)
# Flatten the indices
cols_flat = cols_indices.ravel()
rows_flat = rows_indices.ravel()
# Get the x and y coordinates for each grid cell center
xs_flat, ys_flat = rasterio.transform.xy(transform, rows_flat, cols_flat)
# Create grid dataframe
grid_df = pd.DataFrame({
'X': xs_flat,
'Y': ys_flat,
'row_idx': rows_flat,
'col_idx': cols_flat
})
# Retrieve elevations from DEM
grid_elevations = get_elevation_at_points(
[Point(x, y) for x, y in zip(grid_df['X'], grid_df['Y'])],
dem_data=dem_data,
dem_transform=dem_transform
)
grid_df['Elevation'] = grid_elevations
# Retrieve tree cover density from forest cover raster
grid_forest = get_raster_value_at_points(
[Point(x, y) for x, y in zip(grid_df['X'], grid_df['Y'])],
raster_data=forest_data,
raster_transform=forest_transform
)
grid_df['Tree_Cover'] = grid_forest
# Retrieve water body data at grid points
grid_water = get_water_body_at_points(
[Point(x, y) for x, y in zip(grid_df['X'], grid_df['Y'])],
water_data=water_data,
water_transform=water_transform
)
grid_df['Water_Body'] = grid_water
# Remove grid points with NaN values (i.e., outside data coverage)
grid_df = grid_df.dropna(subset=['Elevation', 'Tree_Cover'])
# Prepare data for regression prediction
X_grid = grid_df[['X', 'Y', 'Elevation', 'Tree_Cover', 'Water_Body']]
X_grid_scaled = scaler.transform(X_grid)
grid_df['Predicted_Temperature'] = rf_model.predict(X_grid_scaled)
# Set up variogram model with adjusted parameters
variogram_model = 'spherical'
# Adjust these parameters based on your data; you'll need to experiment with them
variogram_parameters = {'nugget': 0.2, 'sill': 1.0, 'range': 0.05}
# Perform Universal Kriging
print("Performing Universal Kriging interpolation for residuals with adjusted variogram parameters...")
uk = UniversalKriging(
x=data['X'].values,
y=data['Y'].values,
z=data['Residual'].values,
variogram_model=variogram_model,
variogram_parameters=variogram_parameters,
nlags=20,
verbose=True
)
z, ss = uk.execute(
'points',
grid_df['X'].values,
grid_df['Y'].values
)
grid_df['Residual'] = z
grid_df['Kriging_Variance'] = ss
# Handle NaNs in residuals by filling them with zero
grid_df['Residual'].fillna(0, inplace=True)
# Final temperature estimation
grid_df['Temperature'] = grid_df['Predicted_Temperature'] + grid_df['Residual']
num_nans_in_predicted_temp = grid_df['Predicted_Temperature'].isnull().sum()
print(f"Number of NaNs in Predicted Temperature: {num_nans_in_predicted_temp}")
# Save a copy of the temperature before ECOSTRESS adjustments
grid_df['Temperature_No_ECOSTRESS'] = grid_df['Temperature'].copy()
# Handle NaNs in residuals by filling them with zero
grid_df['Residual'].fillna(0, inplace=True)
# Final temperature estimation (before topographic cooling)
grid_df['Temperature'] = grid_df['Predicted_Temperature'] + grid_df['Residual']
# Save a copy of the temperature before any adjustments
grid_df['Temperature_Before_Adjustments'] = grid_df['Temperature'].copy()
# Determine the current time in CET
cet = pytz.timezone('CET')
now_cet = datetime.now(cet)
hour = now_cet.hour + now_cet.minute / 60.0
# Compute hour angle for cosine function
hour_angle = ((hour % 24) / 24) * 2 * math.pi # Convert hour to radians
# Compute night_weight: maximum at midnight, zero at noon
night_weight = (math.cos(hour_angle) + 1) / 2 # Ranges from 1 at midnight to 0 at noon
# Topographic Cooling Effect
max_cooling_effect = 3.0 # Maximum cooling effect in degrees Celsius
# Normalize elevation to range from 0 to 1
elevation_min = grid_df['Elevation'].min()
elevation_max = grid_df['Elevation'].max()
grid_df['Normalized_Elevation'] = (grid_df['Elevation'] - elevation_min) / (elevation_max - elevation_min)
# Compute the topographic cooling effect
grid_df['Topographic_Cooling'] = grid_df['Normalized_Elevation'] * max_cooling_effect * night_weight
# Ensure topographic cooling is not applied over water bodies
grid_df.loc[grid_df['Water_Body'] == 1, 'Topographic_Cooling'] = 0
# Apply the topographic cooling effect to the temperature
grid_df['Temperature'] -= grid_df['Topographic_Cooling']
# ECOSTRESS Adjustments Begin Here
# Retrieve ECOSTRESS LST values at grid points (same as before)
grid_ecostress = get_raster_value_at_points(
[Point(x, y) for x, y in zip(grid_df['X'], grid_df['Y'])],
raster_data=ecostress_data,
raster_transform=ecostress_transform
)
grid_df['ECOSTRESS_LST'] = grid_ecostress
# Handle NaNs in ECOSTRESS_LST by filling with the mean value
grid_df['ECOSTRESS_LST'].fillna(grid_df['ECOSTRESS_LST'].mean(), inplace=True)
# Compute ECOSTRESS anomalies (deviation from mean)
ecostress_mean = grid_df['ECOSTRESS_LST'].mean()
grid_df['ECOSTRESS_Anomaly'] = grid_df['ECOSTRESS_LST'] - ecostress_mean
# Normalize anomalies to range [-1, 1]
ecostress_anomaly_min = grid_df['ECOSTRESS_Anomaly'].min()
ecostress_anomaly_max = grid_df['ECOSTRESS_Anomaly'].max()
grid_df['ECOSTRESS_Anomaly_Normalized'] = (
(grid_df['ECOSTRESS_Anomaly'] - ecostress_anomaly_min) / (ecostress_anomaly_max - ecostress_anomaly_min) * 2 - 1
)
# Increase the impact of ECOSTRESS LST data
amplification_factor = 3.0 # Adjust as needed
# Determine the current time in CET
cet = pytz.timezone('CET')
now_cet = datetime.now(cet)
hour = now_cet.hour + now_cet.minute / 60.0
# Compute hour angle for cosine function
hour_angle = ((hour % 24) / 24) * 2 * math.pi # Convert hour to radians
# Compute night_weight: maximum at midnight, zero at noon
night_weight = (math.cos(hour_angle) + 1) / 2 # Ranges from 1 at midnight to 0 at noon
# Define threshold for coldest areas (e.g., where ECOSTRESS anomaly is significantly low)
coldest_threshold = -0.5 # You can adjust this value
coldest_areas_mask = grid_df['ECOSTRESS_Anomaly_Normalized'] <= coldest_threshold
# Apply anomalies with the new night_weight and only to coldest areas
adjustment = grid_df['ECOSTRESS_Anomaly_Normalized'] * amplification_factor * night_weight
# Apply adjustments only in the coldest areas
adjustment[coldest_areas_mask] = 0
# Prevent ECOSTRESS adjustments on water bodies
adjustment[grid_df['Water_Body'] == 1] = 0
# Limit maximum adjustment to avoid over-adjusting
max_adjustment = 5.0 # degrees Celsius
adjustment = adjustment.clip(-max_adjustment, max_adjustment)
# Apply adjustments to the interpolated temperatures
grid_df['Temperature'] += adjustment
# Apply cooling effect on water bodies
cooling_effect = -2.0 # degrees Celsius
grid_df.loc[grid_df['Water_Body'] == 1, 'Temperature'] += cooling_effect
# Remove Gaussian smoothing from the interpolated temperature grid
# First, create 2D arrays of temperatures without smoothing
grid_temperature_no_ecostress = np.full((nrows, ncols), np.nan)
grid_temperature_no_ecostress[grid_df['row_idx'], grid_df['col_idx']] = grid_df['Temperature_No_ECOSTRESS'].values
grid_temperature_with_ecostress = np.full((nrows, ncols), np.nan)
grid_temperature_with_ecostress[grid_df['row_idx'], grid_df['col_idx']] = grid_df['Temperature'].values
# Mask the grid_temperature with the Masovian boundary
masovian_shape = [masovian_boundary.geometry.unary_union]
mask = rasterize(
masovian_shape,
out_shape=(nrows, ncols),
transform=transform,
fill=0,
all_touched=True,
default_value=1,
dtype='uint8'
)
# Apply the mask
grid_temperature_no_ecostress = np.ma.array(grid_temperature_no_ecostress, mask=mask == 0)
grid_temperature_with_ecostress = np.ma.array(grid_temperature_with_ecostress, mask=mask == 0)
# Use the unsmoothed temperature grids
temperature_no_ecostress = grid_temperature_no_ecostress
temperature_with_ecostress = grid_temperature_with_ecostress
# Also create grid_variance array (we'll skip smoothing variance for simplicity)
grid_variance = np.full((nrows, ncols), np.nan)
grid_variance[grid_df['row_idx'], grid_df['col_idx']] = grid_df['Kriging_Variance']
grid_variance = np.ma.array(grid_variance, mask=mask == 0)
# Compute Standard Deviation from Variance
grid_std_dev = np.sqrt(grid_variance)
grid_std_dev = np.ma.array(grid_std_dev, mask=mask == 0)
# Read the custom color scale from the CSV file
color_scale_df = pd.read_csv('input/color_scale.csv')
color_scale_df = color_scale_df.sort_values('value')
values = color_scale_df['value'].values
hex_colors = color_scale_df['color'].values
# Ensure colors start with '#'
hex_colors = [color if color.startswith('#') else f"#{color}" for color in hex_colors]
# Create a custom colormap
# Normalize the values to 0..1
vmin = values.min()
vmax = values.max()
normalized_values = (values - vmin) / (vmax - vmin)
# Create a list of tuples (position, color)
color_tuples = list(zip(normalized_values, hex_colors))
# Create a LinearSegmentedColormap
cmap = mcolors.LinearSegmentedColormap.from_list('custom_cmap', color_tuples)
# Set the normalization
norm = mcolors.Normalize(vmin=vmin, vmax=vmax)
with rasterio.open('input/masovian_dem.tif') as dem_src:
# Reproject Masovian boundary to DEM CRS if necessary
if masovian_boundary.crs != dem_src.crs:
masovian_boundary_dem_crs = masovian_boundary.to_crs(dem_src.crs)
else:
masovian_boundary_dem_crs = masovian_boundary
# Clip the DEM to the Masovian boundary
dem_plot_data, dem_plot_transform = rasterio.mask.mask(
dem_src, masovian_boundary_dem_crs.geometry, crop=True, filled=True, nodata=np.nan
)
# Read the first band (assuming single-band DEM)
dem_plot_data = dem_plot_data[0] # Since mask returns data as (bands, rows, cols)
# Handle NaNs in the DEM data
dem_plot_data = np.nan_to_num(dem_plot_data, nan=np.nanmin(dem_plot_data))
# Calculate the extent of the clipped DEM for plotting
dem_left, dem_top = dem_plot_transform * (0, 0)
dem_right, dem_bottom = dem_plot_transform * (dem_plot_data.shape[1], dem_plot_data.shape[0])
dem_extent = [dem_left, dem_right, dem_bottom, dem_top]
# Compute extent for plotting (same as before)
def get_extent(transform, array):
x_min = transform.c
y_max = transform.f
x_max = x_min + transform.a * array.shape[1]
y_min = y_max + transform.e * array.shape[0]
return [x_min, x_max, y_min, y_max]
hs = hillshade(dem_plot_data, azimuth=315, angle_altitude=45)
extent = get_extent(transform, temperature_with_ecostress)
dem_extent = get_extent(dem_plot_transform, dem_plot_data)
# Plotting Temperature Map without ECOSTRESS Adjustments
fig1, ax1 = plt.subplots(figsize=(15, 15))
# Set modern and minimalistic font properties with increased size
plt.rcParams.update({
'font.size': 10,
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans']
})
# Plot the interpolated temperature grid without ECOSTRESS adjustments
img1 = ax1.imshow(temperature_no_ecostress, extent=extent, origin='upper',
cmap=cmap, norm=norm, alpha=1)
# Plot hillshade on top
ax1.imshow(hs, extent=dem_extent, cmap='gray', origin='upper', alpha=0.3)
# Overlay water bodies with blue color
water_mask = np.where(water_data > 0, 1, 0) # Adjust condition based on water_data values
ax1.imshow(water_mask, extent=extent, origin='upper', cmap='Blues', alpha=0.5) # Increased alpha to 0.5
# Plot Masovian Voivodeship boundary
masovian_boundary.boundary.plot(ax=ax1, color='black', linewidth=2)
# Plot stations as smaller rectangles
stations_gdf.plot(ax=ax1, color='black', marker='s', markersize=5, label='Stations')
# Add contours for every 1°C value
min_temp = np.floor(temperature_no_ecostress.min())
max_temp = np.ceil(temperature_no_ecostress.max())
contour_levels = np.arange(min_temp, max_temp + 1, 1)
# Add contours
contours1 = ax1.contour(
temperature_no_ecostress, levels=contour_levels, colors='black', linewidths=0.5,
extent=extent, origin='upper'
)
contour_labels1 = ax1.clabel(
contours1, inline=False, fontsize=8, fmt='%d', colors='white',
inline_spacing=4, manual=False
)
for txt in contour_labels1:
txt.set_path_effects([
patheffects.Stroke(linewidth=3, foreground='black'),
patheffects.Normal()
])
# Add colorbar and labels
cbar1 = fig1.colorbar(img1, ax=ax1, label="Temperature (°C)")
ticks = np.arange(np.floor(vmin / 5) * 5, np.ceil(vmax / 5) * 5 + 1, 5)
cbar1.set_ticks(ticks)
cbar1.set_ticklabels(ticks.astype(int))
ax1.set_title("Temperature Interpolation without ECOSTRESS Adjustments", fontsize=18)
ax1.legend()
ax1.set_xlabel("Longitude")
ax1.set_ylabel("Latitude")
plt.savefig('output/temperature_without_ecostress.png', dpi=300, bbox_inches='tight')
plt.show()
print(f"Temperature interpolation plot created successfully without smoothing.")
# Plotting Temperature Map with ECOSTRESS Adjustments
fig2, ax2 = plt.subplots(figsize=(15, 15))
# Plot the interpolated temperature grid with ECOSTRESS adjustments
img2 = ax2.imshow(temperature_with_ecostress, extent=extent, origin='upper',
cmap=cmap, norm=norm, alpha=1)
# Plot hillshade on top
ax2.imshow(hs, extent=dem_extent, cmap='gray', origin='upper', alpha=0.3)
# Overlay water bodies
ax2.imshow(water_mask, extent=extent, origin='upper', cmap='Blues', alpha=0.5)
# Plot Masovian Voivodeship boundary with a light, dark stroke
masovian_boundary.boundary.plot(ax=ax2, edgecolor='#333333', linewidth=1.5)
# Plot stations
stations_gdf.plot(ax=ax2, color='black', marker='s', markersize=5)
# Remove axes for a minimalistic look
ax2.axis('off')
# Draw a light, dark stroke around the plot extent
from matplotlib.patches import Rectangle
rect = Rectangle(
(extent[0], extent[2]), # Lower-left corner (x0, y0)
extent[1] - extent[0], # Width
extent[3] - extent[2], # Height
linewidth=1.5,
edgecolor='#333333',
facecolor='none',
transform=ax2.transData
)
ax2.add_patch(rect)
# Introduce a subtle background gradient
from matplotlib.colors import LinearSegmentedColormap
background_cmap = LinearSegmentedColormap.from_list(
'background_gradient', ['#ffffff', '#f0f0f0'], N=256)
ax2.imshow(
np.linspace(0, 1, 256).reshape(1, -1),
cmap=background_cmap,
extent=(extent[0], extent[1], extent[2], extent[3]),
aspect='auto',
alpha=0.2,
zorder=-1 # Place it below other elements
)
# Adjust font properties for a modern look
plt.rcParams.update({
'font.size': 14, # Base font size
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
'text.color': '#333333'
})
# Enlarge and reposition the product name (Title)
fig2.text(
0.5, 0.94, # Adjusted y-position for better placement
"High-Resolution Mesoscale Temperature Analysis",
fontsize=28, # Increased font size
fontweight='bold',
ha='center',
va='top',
fontname='DejaVu Sans',
color='#333333'
)
# Move the model name/resolution text closer to the product name text
fig2.text(
0.5, 0.91, # Adjusted y-position to move it closer
"Model: TempMeso v1.0 (Preview) | Resolution: 250 m",
fontsize=18, # Increased font size
ha='center',
va='top',
fontname='DejaVu Sans',
color='#666666'
)
# Adjust colorbar position and style
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax2)
cax = divider.append_axes("right", size="3%", pad=0.1)
cbar2 = fig2.colorbar(img2, cax=cax)
cbar2.set_ticks(ticks)
cbar2.set_ticklabels(ticks.astype(int))
cbar2.ax.tick_params(labelsize=14)
cbar2.set_label("Temperature (°C)", fontsize=16, fontname='DejaVu Sans', color='#333333')
# Enhance colorbar aesthetics
cbar2.outline.set_visible(False)
cbar2.ax.yaxis.set_tick_params(width=0.5)
cbar2.ax.tick_params(labelsize=14, colors='#333333')
# Move the GeoStorm logo to the bottom right corner
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# Read the logo image
logo_path = 'input/logo.png'
logo_img = mpimg.imread(logo_path)
# Adjust the size of the logo
logo_zoom = 0.25 # Keep the logo size as previously adjusted
imagebox = OffsetImage(logo_img, zoom=logo_zoom)
# Position the logo at the bottom-right corner with some padding
ab = AnnotationBbox(
imagebox,
xy=(0.98, 0.05), # Adjusted x and y coordinates to bottom-right
xycoords='figure fraction',
frameon=False,
box_alignment=(1, 0) # Align box at right-bottom
)
fig2.add_artist(ab)
# Reduce the space below the logo by adjusting the bottom margin
plt.subplots_adjust(left=0.05, right=0.95, top=0.88, bottom=0.05)
# On the map, add texts at the coldest and warmest temperature locations
# Find the locations of the minimum and maximum temperatures
min_temp = np.nanmin(temperature_with_ecostress)
max_temp = np.nanmax(temperature_with_ecostress)
# Get the indices of the min and max temperatures
min_indices = np.unravel_index(np.nanargmin(temperature_with_ecostress), temperature_with_ecostress.shape)
max_indices = np.unravel_index(np.nanargmax(temperature_with_ecostress), temperature_with_ecostress.shape)
# Convert grid indices to coordinates
min_lon, min_lat = rasterio.transform.xy(transform, min_indices[0], min_indices[1])
max_lon, max_lat = rasterio.transform.xy(transform, max_indices[0], max_indices[1])
# Plot the temperature values on the map (without markers)
# Use white text with a thick black stroke
text_kwargs = dict(
fontsize=14,
fontname='Arial',
ha='center',
va='center',
color='white',
transform=ax2.transData,
path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]
)
# Format temperature values without decimal points
ax2.text(min_lon, min_lat, f"{min_temp:.0f}", **text_kwargs)
ax2.text(max_lon, max_lat, f"{max_temp:.0f}", **text_kwargs)
# Save and show the plot
plt.savefig('output/temperature_analysis_modern.png', dpi=300)
plt.show()
print("Updated temperature analysis plot created successfully.")
# Plotting the Difference Map
# Compute the difference between the two temperature grids
# Compute the difference due to ECOSTRESS adjustments only
temperature_difference_ecostress = temperature_with_ecostress - temperature_no_ecostress
# Plotting the Difference Map Due to ECOSTRESS Adjustments Only
fig_ecostress_diff, ax_ecostress_diff = plt.subplots(figsize=(15, 15))
# Use a diverging colormap to show positive and negative differences
diff_cmap = 'RdBu'
diff_norm = mcolors.TwoSlopeNorm(
vmin=-np.nanmax(np.abs(temperature_difference_ecostress)),
vcenter=0,
vmax=np.nanmax(np.abs(temperature_difference_ecostress))
)
# Plot the temperature difference grid
img_ecostress_diff = ax_ecostress_diff.imshow(temperature_difference_ecostress, extent=extent, origin='upper',
cmap=diff_cmap, norm=diff_norm, alpha=1)
# Plot hillshade
ax_ecostress_diff.imshow(hs, extent=dem_extent, cmap='gray', origin='upper', alpha=0.3)
# Overlay water bodies
ax_ecostress_diff.imshow(water_mask, extent=extent, origin='upper', cmap='Blues', alpha=0.5)
# Plot Masovian Voivodeship boundary
masovian_boundary.boundary.plot(ax=ax_ecostress_diff, color='black', linewidth=2)
# Plot stations
stations_gdf.plot(ax=ax_ecostress_diff, color='black', marker='s', markersize=5, label='Stations')
# Add colorbar
cbar_ecostress_diff = fig_ecostress_diff.colorbar(img_ecostress_diff, ax=ax_ecostress_diff, label="Temperature Difference (°C)")
ax_ecostress_diff.set_title("Temperature Adjustments Due to ECOSTRESS Only", fontsize=18)
ax_ecostress_diff.legend()
ax_ecostress_diff.set_xlabel("Longitude")
ax_ecostress_diff.set_ylabel("Latitude")
plt.savefig('output/temperature_difference_ecostress_only.png', dpi=300, bbox_inches='tight')
plt.show()
print(f"Temperature difference plot due to ECOSTRESS adjustments (excluding topographic cooling) created successfully.")
return temperature_with_ecostress, transform
Certainly! Here is the updated code that incorporates your requests:
-
Map before adjustments and ECOSTRESS adjustments plots are no longer generated.
-
There are only two plots:
- The existing
img2 plot with adjusted logo position, min/max temperature text including decimals, and increased font size.
- A new plot that is
img2 but with contours and contour labels added, similar to the map before adjustments.
-
The logo in img2 is moved more towards the bottom to avoid overlapping with color scales or map elements.
-
The min/max temperature texts now include decimals and have a slightly increased font size.
Here is the updated plot_stations_with_boundary_and_interpolation function:
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):
# [Data processing code remains the same up to the plotting section]
# After computing the final temperature grid, proceed to plotting.
# Note: We will only plot two figures as per your request.
# First, adjust the existing plotting code for img2 (now called fig1) as per your requirements.
# Plotting Temperature Map with ECOSTRESS Adjustments
fig1, ax1 = plt.subplots(figsize=(15, 15))
# Plot the interpolated temperature grid with ECOSTRESS adjustments
img1 = ax1.imshow(temperature_with_ecostress, extent=extent, origin='upper',
cmap=cmap, norm=norm, alpha=1)
# Plot hillshade on top
ax1.imshow(hs, extent=dem_extent, cmap='gray', origin='upper', alpha=0.3)
# Overlay water bodies
ax1.imshow(water_mask, extent=extent, origin='upper', cmap='Blues', alpha=0.5)
# Plot Masovian Voivodeship boundary with a light, dark stroke
masovian_boundary.boundary.plot(ax=ax1, edgecolor='#333333', linewidth=1.5)
# Plot stations
stations_gdf.plot(ax=ax1, color='black', marker='s', markersize=5)
# Remove axes for a minimalistic look
ax1.axis('off')
# Draw a light, dark stroke around the plot extent
from matplotlib.patches import Rectangle
rect = Rectangle(
(extent[0], extent[2]), # Lower-left corner (x0, y0)
extent[1] - extent[0], # Width
extent[3] - extent[2], # Height
linewidth=1.5,
edgecolor='#333333',
facecolor='none',
transform=ax1.transData
)
ax1.add_patch(rect)
# Introduce a subtle background gradient
from matplotlib.colors import LinearSegmentedColormap
background_cmap = LinearSegmentedColormap.from_list(
'background_gradient', ['#ffffff', '#f0f0f0'], N=256)
ax1.imshow(
np.linspace(0, 1, 256).reshape(1, -1),
cmap=background_cmap,
extent=(extent[0], extent[1], extent[2], extent[3]),
aspect='auto',
alpha=0.2,
zorder=-1 # Place it below other elements
)
# Adjust font properties for a modern look
plt.rcParams.update({
'font.size': 14, # Base font size
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
'text.color': '#333333'
})
# Enlarge and reposition the product name (Title)
fig1.text(
0.5, 0.94, # Adjusted y-position for better placement
"High-Resolution Mesoscale Temperature Analysis",
fontsize=28, # Increased font size
fontweight='bold',
ha='center',
va='top',
fontname='DejaVu Sans',
color='#333333'
)
# Move the model name/resolution text closer to the product name text
fig1.text(
0.5, 0.91, # Adjusted y-position to move it closer
"Model: TempMeso v1.0 (Preview) | Resolution: 250 m",
fontsize=18, # Increased font size
ha='center',
va='top',
fontname='DejaVu Sans',
color='#666666'
)
# Adjust colorbar position and style
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="3%", pad=0.1)
cbar1 = fig1.colorbar(img1, cax=cax)
cbar1.set_ticks(ticks)
cbar1.set_ticklabels(ticks.astype(int))
cbar1.ax.tick_params(labelsize=14)
cbar1.set_label("Temperature (°C)", fontsize=16, fontname='DejaVu Sans', color='#333333')
# Enhance colorbar aesthetics
cbar1.outline.set_visible(False)
cbar1.ax.yaxis.set_tick_params(width=0.5)
cbar1.ax.tick_params(labelsize=14, colors='#333333')
# Move the logo to the bottom right corner
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# Read the logo image
logo_path = 'input/logo.png'
logo_img = mpimg.imread(logo_path)
# Adjust the size of the logo
logo_zoom = 0.25
imagebox = OffsetImage(logo_img, zoom=logo_zoom)
# Adjust logo position to prevent overlap with colorbar
ab = AnnotationBbox(
imagebox,
xy=(0.95, 0.02), # Moved lower to avoid overlapping with map elements
xycoords='figure fraction',
frameon=False,
box_alignment=(1, 0) # Align box at right-bottom
)
fig1.add_artist(ab)
# Reduce the space below the logo by adjusting the bottom margin
plt.subplots_adjust(left=0.05, right=0.95, top=0.88, bottom=0.05)
# On the map, add texts at the coldest and warmest temperature locations
# Find the locations of the minimum and maximum temperatures
min_temp = np.nanmin(temperature_with_ecostress)
max_temp = np.nanmax(temperature_with_ecostress)
# Get the indices of the min and max temperatures
min_indices = np.unravel_index(np.nanargmin(temperature_with_ecostress), temperature_with_ecostress.shape)
max_indices = np.unravel_index(np.nanargmax(temperature_with_ecostress), temperature_with_ecostress.shape)
# Convert grid indices to coordinates
min_lon, min_lat = rasterio.transform.xy(transform, min_indices[0], min_indices[1])
max_lon, max_lat = rasterio.transform.xy(transform, max_indices[0], max_indices[1])
# Plot the temperature values on the map (without markers)
# Use white text with a thick black stroke
text_kwargs = dict(
fontsize=18, # Increased font size
fontname='Arial',
ha='center',
va='center',
color='white',
transform=ax1.transData,
path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]
)
# Format temperature values with one decimal point
ax1.text(min_lon, min_lat, f"{min_temp:.1f}", **text_kwargs)
ax1.text(max_lon, max_lat, f"{max_temp:.1f}", **text_kwargs)
# Save and show the plot
plt.savefig('output/temperature_analysis_modern.png', dpi=300)
plt.show()
print("Updated temperature analysis plot created successfully.")
# Now, create the second plot with contours added
# Plotting Temperature Map with Contours
fig2, ax2 = plt.subplots(figsize=(15, 15))
# Copy the plotting code from the first plot
img2 = ax2.imshow(temperature_with_ecostress, extent=extent, origin='upper',
cmap=cmap, norm=norm, alpha=1)
# Plot hillshade on top
ax2.imshow(hs, extent=dem_extent, cmap='gray', origin='upper', alpha=0.3)
# Overlay water bodies
ax2.imshow(water_mask, extent=extent, origin='upper', cmap='Blues', alpha=0.5)
# Plot Masovian Voivodeship boundary with a light, dark stroke
masovian_boundary.boundary.plot(ax=ax2, edgecolor='#333333', linewidth=1.5)
# Plot stations
stations_gdf.plot(ax=ax2, color='black', marker='s', markersize=5)
# Remove axes for a minimalistic look
ax2.axis('off')
# Draw a light, dark stroke around the plot extent
rect = Rectangle(
(extent[0], extent[2]), # Lower-left corner (x0, y0)
extent[1] - extent[0], # Width
extent[3] - extent[2], # Height
linewidth=1.5,
edgecolor='#333333',
facecolor='none',
transform=ax2.transData
)
ax2.add_patch(rect)
# Introduce a subtle background gradient
ax2.imshow(
np.linspace(0, 1, 256).reshape(1, -1),
cmap=background_cmap,
extent=(extent[0], extent[1], extent[2], extent[3]),
aspect='auto',
alpha=0.2,
zorder=-1 # Place it below other elements
)
# Adjust font properties for a modern look
plt.rcParams.update({
'font.size': 14, # Base font size
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
'text.color': '#333333'
})
# Enlarge and reposition the product name (Title)
fig2.text(
0.5, 0.94, # Adjusted y-position for better placement
"High-Resolution Mesoscale Temperature Analysis with Contours",
fontsize=28, # Increased font size
fontweight='bold',
ha='center',
va='top',
fontname='DejaVu Sans',
color='#333333'
)
# Move the model name/resolution text closer to the product name text
fig2.text(
0.5, 0.91, # Adjusted y-position to move it closer
"Model: TempMeso v1.0 (Preview) | Resolution: 250 m",
fontsize=18, # Increased font size
ha='center',
va='top',
fontname='DejaVu Sans',
color='#666666'
)
# Adjust colorbar position and style
divider = make_axes_locatable(ax2)
cax = divider.append_axes("right", size="3%", pad=0.1)
cbar2 = fig2.colorbar(img2, cax=cax)
cbar2.set_ticks(ticks)
cbar2.set_ticklabels(ticks.astype(int))
cbar2.ax.tick_params(labelsize=14)
cbar2.set_label("Temperature (°C)", fontsize=16, fontname='DejaVu Sans', color='#333333')
# Enhance colorbar aesthetics
cbar2.outline.set_visible(False)
cbar2.ax.yaxis.set_tick_params(width=0.5)
cbar2.ax.tick_params(labelsize=14, colors='#333333')
# Move the logo to the bottom right corner
imagebox = OffsetImage(logo_img, zoom=logo_zoom)
ab = AnnotationBbox(
imagebox,
xy=(0.95, 0.02), # Adjusted position to avoid overlap
xycoords='figure fraction',
frameon=False,
box_alignment=(1, 0) # Align box at right-bottom
)
fig2.add_artist(ab)
# Reduce the space below the logo by adjusting the bottom margin
plt.subplots_adjust(left=0.05, right=0.95, top=0.88, bottom=0.05)
# On the map, add texts at the coldest and warmest temperature locations
text_kwargs = dict(
fontsize=18, # Increased font size
fontname='Arial',
ha='center',
va='center',
color='white',
transform=ax2.transData,
path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]
)
ax2.text(min_lon, min_lat, f"{min_temp:.1f}", **text_kwargs)
ax2.text(max_lon, max_lat, f"{max_temp:.1f}", **text_kwargs)
# Add contours to the plot
min_temp_c = np.floor(np.nanmin(temperature_with_ecostress))
max_temp_c = np.ceil(np.nanmax(temperature_with_ecostress))
contour_levels = np.arange(min_temp_c, max_temp_c + 1, 1)
contours = ax2.contour(
temperature_with_ecostress, levels=contour_levels, colors='black', linewidths=0.5,
extent=extent, origin='upper'
)
contour_labels = ax2.clabel(
contours, inline=False, fontsize=8, fmt='%d', colors='white',
inline_spacing=4, manual=False
)
for txt in contour_labels:
txt.set_path_effects([
patheffects.Stroke(linewidth=3, foreground='black'),
patheffects.Normal()
])
# Save and show the plot
plt.savefig('output/temperature_analysis_with_contours.png', dpi=300)
plt.show()
print("Temperature analysis plot with contours created successfully.")
return temperature_with_ecostress, transform
With these changes, your code now only produces two plots:
-
The updated img2 plot (now fig1) with adjusted logo position, min/max temperature texts including decimals, and increased font size.
-
A new plot (fig2) that is the same as img2 but with contours and contour labels added, similar to the map before adjustments.
Note on Adjustments:
-
Logo Position: The logo's y coordinate in xy=(0.95, 0.02) has been set to 0.02 to place it more towards the bottom, avoiding overlapping with the color bar or map elements.
-
Min/Max Temperature Text: The temperature values are formatted to include one decimal place using f"{min_temp:.1f}", and the fontsize is increased to 18 for better visibility.
-
Contours: Added contours and contour labels to the second plot to provide the combined effect you requested.
I hope this helps!