The error you encountered stems from the branca library's LinearColormap failing due to unsorted thresholds. Let's break down the issue and provide steps to diagnose and resolve it.
Understanding the Error
Error Traceback Summary
-
Initial Warnings:
RuntimeWarning: All-NaN axis encountered
vmin = float(np.nanmin(smoothed_masked))
vmax = float(np.nanmax(smoothed_masked))
- These warnings indicate that
smoothed_masked contains only NaN values along the specified axes.
-
Final Exception:
ValueError: Thresholds are not sorted.
- This error arises from the
branca.colormap when it tries to process the colormap with invalid (likely NaN) threshold values.
Root Cause
The RuntimeWarning suggests that the raster data (smoothed_masked) contains only NaN values. Consequently, when you attempt to calculate vmin and vmax using np.nanmin and np.nanmax, they return NaN. Passing NaN values to branca.colormap.LinearColormap results in unsorted thresholds, leading to the ValueError.
Potential Causes
-
Data Loading Issues:
- The solar data CSV (
india_solar_data.csv) might be empty or improperly formatted.
- The GeoJSON file (
india-soi.geojson) might not contain the expected geometries or CRS.
-
Projection Problems:
- Using a single UTM zone (
EPSG:32644) may not cover all regions of India, leading to data points falling outside the raster bounds.
- Incorrect CRS transformations can misplace data points.
-
Rasterization Errors:
- The process of mapping solar potential data to the raster grid might not be populating any data, leaving the raster entirely
NaN.
-
Masking Issues:
- The mask created from India's boundaries might be incorrectly excluding all data.
Step-by-Step Diagnosis and Resolution
1. Verify Input Data
-
Check Solar Data (india_solar_data.csv):
logger.info(f"Solar Data Rows: {len(solar_df)}")
- Ensure that the CSV contains data and that the columns
longitude, latitude, and potential are correctly populated.
-
Check GeoJSON Data (india-soi.geojson):
logger.info(f"India GeoJSON CRS: {india.crs}")
logger.info(f"Number of Geometries: {len(india)}")
- Confirm that the GeoJSON contains the expected geometries and CRS.
2. Validate CRS Transformations
-
Projection to UTM:
# Instead of a fixed UTM zone, consider using an appropriate CRS that covers all of India
india_proj = india.to_crs('EPSG:32644') # EPSG:32644 covers UTM zone 44N
solar_gdf_proj = solar_gdf.to_crs('EPSG:32644')
- Issue: India spans multiple UTM zones (42N to 47N). Using a single UTM zone may exclude data points outside that zone.
-
Solution:
- Option 1: Use a broader CRS like Web Mercator (EPSG:3857) which covers large areas.
- Option 2: Dynamically determine the appropriate UTM zone per data point (more complex).
Implementing Option 1:
india_proj = india.to_crs('EPSG:3857')
solar_gdf_proj = solar_gdf.to_crs('EPSG:3857')
3. Rasterization Process
4. Adjust Masking Logic
5. Handling All-NaN Cases
Implementing the Fix
Here's an updated version of your script with added diagnostic logging and adjustments to the CRS:
import geopandas as gpd
import pandas as pd
import numpy as np
import folium
import branca.colormap as cm
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from rasterio.transform import from_bounds
from rasterio.features import geometry_mask
from shapely.geometry import Point
import logging
from scipy.ndimage import gaussian_filter
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_solar_map(solar_data_path='india_solar_data.csv', geojson_path='india-soi.geojson'):
# Load and prepare data
logger.info("Loading data...")
solar_df = pd.read_csv(solar_data_path)
logger.info(f"Solar Data Rows: {len(solar_df)}")
india = gpd.read_file(geojson_path)
logger.info(f"India GeoJSON CRS: {india.crs}")
logger.info(f"Number of Geometries: {len(india)}")
# Ensure input data is in WGS84
if india.crs != 'EPSG:4326':
india = india.to_crs('EPSG:4326')
# Create GeoDataFrame from solar data
solar_gdf = gpd.GeoDataFrame(
solar_df,
geometry=[Point(xy) for xy in zip(solar_df.longitude, solar_df.latitude)],
crs='EPSG:4326'
)
logger.info(f"Solar GeoDataFrame CRS: {solar_gdf.crs}")
logger.info(f"Solar Points Total Bounds: {solar_gdf.total_bounds}")
# Project to Web Mercator for broader coverage
india_proj = india.to_crs('EPSG:3857')
solar_gdf_proj = solar_gdf.to_crs('EPSG:3857')
# Calculate bounds and create raster
bounds = india_proj.total_bounds
resolution = 2500 # 2.5km resolution for higher detail
width = int((bounds[2] - bounds[0]) / resolution)
height = int((bounds[3] - bounds[1]) / resolution)
transform = from_bounds(bounds[0], bounds[1], bounds[2], bounds[3], width, height)
logger.info(f"Raster Dimensions: {width}x{height}")
# Initialize raster
raster_data = np.full((height, width), np.nan, dtype=np.float32)
# Populate raster with data points
populated = 0
for idx, row in solar_gdf_proj.iterrows():
col_float, row_float = ~transform * (row.geometry.x, row.geometry.y)
col, row_idx = int(col_float), int(row_float)
if 0 <= row_idx < height and 0 <= col < width:
raster_data[row_idx, col] = row['potential']
populated += 1
logger.info(f"Populated Pixels: {populated} out of {len(solar_gdf_proj)}")
if populated == 0:
logger.error("No data points were mapped to the raster. Check input data and projections.")
return
# Create and apply mask for India's boundaries
geometry = [feature['geometry'] for feature in india_proj.__geo_interface__['features']]
mask_raster = geometry_mask(geometry, out_shape=(height, width), transform=transform, invert=True)
logger.info(f"Mask Applied. Number of True Pixels: {np.sum(mask_raster)}")
# Apply mask and smooth data
raster_data = np.ma.masked_array(raster_data, ~mask_raster)
# Apply Gaussian smoothing to fill gaps
smoothed_data = gaussian_filter(raster_data.filled(np.nan), sigma=2)
smoothed_masked = np.ma.masked_array(smoothed_data, ~mask_raster)
if np.all(np.isnan(smoothed_masked)):
logger.error("Smoothed data contains only NaNs. Cannot create visualization.")
return
# Create high-resolution plot
logger.info("Creating visualization...")
fig, ax = plt.subplots(figsize=(20, 20), dpi=300)
ax.set_axis_off()
# Calculate min and max values properly
vmin = float(np.nanmin(smoothed_masked))
vmax = float(np.nanmax(smoothed_masked))
logger.info(f"Visualization Vmin: {vmin}, Vmax: {vmax}")
# Create colormap with properly sorted values
colormap = cm.LinearColormap(
colors=['#440154', '#482878', '#3E4989', '#31688E', '#26828E',
'#1F9E89', '#35B779', '#6DCD59', '#B4DE2C', '#FDE725'],
vmin=vmin,
vmax=vmax,
caption='Solar Potential (kWh/m²/year)'
)
# Plot raster data
img = ax.imshow(
smoothed_masked,
extent=india_proj.total_bounds,
cmap=ListedColormap(colormap.colors),
origin='lower',
interpolation='bilinear' # Add interpolation for smoother appearance
)
# Add boundary outline
india_proj.boundary.plot(ax=ax, color='black', linewidth=1)
# Save high-resolution image
plt.savefig('solar_potential_high_res.png',
bbox_inches='tight',
pad_inches=0,
dpi=300,
facecolor='white',
edgecolor='none')
plt.close(fig)
# Create interactive Folium map
logger.info("Creating interactive map...")
# Convert bounds back to latitude and longitude for Folium
india_bounds_latlon = india.to_crs('EPSG:4326').total_bounds
center_lat = (india_bounds_latlon[1] + india_bounds_latlon[3]) / 2
center_lon = (india_bounds_latlon[0] + india_bounds_latlon[2]) / 2
m = folium.Map(
location=[center_lat, center_lon],
zoom_start=5,
tiles='CartoDB positron'
)
# Add image overlay
img_bounds = [
[india_bounds_latlon[1], india_bounds_latlon[0]],
[india_bounds_latlon[3], india_bounds_latlon[2]]
]
folium.raster_layers.ImageOverlay(
name='Solar Potential',
image='solar_potential_high_res.png',
bounds=img_bounds,
opacity=0.7,
interactive=True,
cross_origin=False,
zindex=1,
).add_to(m)
# Add boundary overlay
folium.GeoJson(
india.__geo_interface__, # Use geo_interface for better compatibility
style_function=lambda x: {
'fillColor': 'none',
'color': 'black',
'weight': 1.5,
'fillOpacity': 0
},
name='India Boundary'
).add_to(m)
# Add colormap and layer control
colormap.add_to(m)
folium.LayerControl().add_to(m)
# Save interactive map
m.save('india_solar_potential.html')
logger.info("Map creation completed!")
if __name__ == "__main__":
create_solar_map()
Key Changes and Additions:
-
CRS Adjustment:
- Changed projection to Web Mercator (EPSG:3857) to cover all of India without excluding data points.
-
Diagnostic Logging:
- Added logs to verify the number of data points loaded, projected, and rasterized.
- Logged raster bounds and mask application details.
-
Conditional Checks:
- Added checks to exit gracefully if no data points are mapped or if the smoothed data contains only
NaN values.
-
Bounds Transformation for Folium:
- Converted raster bounds back to latitude and longitude for accurate placement on the Folium map.
-
Improved Raster Initialization:
- Used
np.full to initialize the raster with NaN values more explicitly.
Next Steps
-
Run the Updated Script:
- Execute the modified script to see if the error persists.
-
Validate Data Integrity:
- Ensure that
india_solar_data.csv contains valid longitude, latitude, and potential values.
- Verify that the GeoJSON file accurately represents India's boundaries and is correctly formatted.
-
Visual Inspection:
- After running the script, inspect
solar_potential_high_res.png to confirm that the raster data visualizes correctly.
- Open
india_solar_potential.html in a browser to interact with the map.
-
Further Enhancements:
- Dynamic CRS Handling: For larger datasets spanning multiple UTM zones, consider more sophisticated projection strategies.
- Data Validation: Implement more robust data validation to handle missing or inconsistent data gracefully.
- Performance Optimization: For very high-resolution rasters, optimize performance by leveraging more efficient data structures or processing techniques.
Conclusion
The primary issue was that the raster data contained only NaN values, leading to invalid colormap thresholds. By adjusting the CRS to cover all of India and adding detailed logging, you can ensure that data points are correctly mapped and visualized. Always validate input data and projections when dealing with geospatial analyses to prevent similar issues.