import numpy as np
import pandas as pd
import geopandas as gpd
import folium
from folium import plugins
import requests
from scipy.interpolate import griddata
import time
def fetch_nasa_power_data(lat, lon):
"""
Fetch solar radiation data from NASA POWER API
"""
base_url = "https://power.larc.nasa.gov/api/temporal/daily/point"
params = {
'parameters': 'ALLSKY_SFC_SW_DWN',
'community': 'RE',
'longitude': str(lon),
'latitude': str(lat),
'start': '20230101',
'end': '20231231',
'format': 'JSON'
}
code
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"Error making request: {e}")
return None
except ValueError as e:
print(f"Error parsing JSON: {e}")
return None
def calculate_solar_potential(power_data, panel_efficiency=0.2):
"""
Calculate solar potential based on radiation data
"""
if power_data is None:
return None
code
try:
daily_data = power_data.get('properties', {}).get('parameter', {}).get('ALLSKY_SFC_SW_DWN', {})
if not daily_data:
print("No daily data found in response")
return None
radiation_values = []
for value in daily_data.values():
if isinstance(value, (int, float)) and value != -999:
radiation_values.append(value * 0.277778) # Convert MJ to kWh
if not radiation_values:
print("No valid radiation values found")
return None
annual_potential = np.mean(radiation_values) * 365 * panel_efficiency
return annual_potential
except (KeyError, TypeError) as e:
print(f"Error processing data: {e}")
return None
def create_india_solar_map(geojson_path):
"""
Create an interactive map of India's solar potential with interpolated contours
"""
# Read India GeoJSON
india = gpd.read_file(geojson_path)
Assistant
code
# Create a base map centered on India
m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
# Create a grid for sampling points
lat_range = np.arange(8.4, 37.6, 1.0) # Using 1.0 degree step for faster processing
lon_range = np.arange(68.7, 97.25, 1.0)
# Store solar potential data
solar_data = []
# Fetch data for each grid point
total_points = len(lat_range) * len(lon_range)
current_point = 0
for lat in lat_range:
for lon in lon_range:
current_point += 1
print(f"\nProcessing point {current_point}/{total_points}")
point = gpd.points_from_xy([lon], [lat])[0]
# Check if point is within India
if any(india.geometry.contains(point)):
power_data = fetch_nasa_power_data(lat, lon)
time.sleep(2) # Rate limiting
if power_data:
potential = calculate_solar_potential(power_data)
if potential is not None:
solar_data.append({
'latitude': lat,
'longitude': lon,
'potential': potential
})
# Create DataFrame from collected data
solar_df = pd.DataFrame(solar_data)
if solar_df.empty:
raise ValueError("No solar data could be collected. Please check API access and coordinates.")
# Create a finer mesh grid for interpolation
grid_lat = np.linspace(solar_df['latitude'].min(), solar_df['latitude'].max(), 200)
grid_lon = np.linspace(solar_df['longitude'].min(), solar_df['longitude'].max(), 200)
grid_lon, grid_lat = np.meshgrid(grid_lon, grid_lat)
# Interpolate the data
points = solar_df[['longitude', 'latitude']].values
values = solar_df['potential'].values
grid_z = griddata(points, values, (grid_lon, grid_lat), method='cubic')
# Add the heatmap layer
locations = [[lat, lon] for lat, lon in zip(solar_df['latitude'], solar_df['longitude'])]
values = solar_df['potential'].tolist()
hm = plugins.HeatMap(
locations,
values,
min_opacity=0.4,
radius=25,
blur=15,
gradient={
0.4: '#ffffb2',
0.6: '#fecc5c',
0.7: '#fd8d3c',
0.8: '#f03b20',
1.0: '#bd0026'
}
)
hm.add_to(m)
# Add GeoJSON boundary
folium.GeoJson(
india,
style_function=lambda x: {
'fillColor': 'none',
'color': 'black',
'weight': 1.5
}
).add_to(m)
# Add legend
legend_html = f'''
<div style="position: fixed;
bottom: 50px; right: 50px; width: 250px;
border:2px solid grey; z-index:9999; font-size:14px;
background-color:white;
padding: 10px;
border-radius: 5px;">
<p style="margin: 0 0 5px 0;"><strong>Solar Potential (kWh/m²/year)</strong></p>
<table style="width:100%; border-collapse: collapse;">
'''
# Add color gradient and value ranges
min_val = min(values)
max_val = max(values)
colors = ['#ffffb2', '#fecc5c', '#fd8d3c', '#f03b20', '#bd0026']
step = (max_val - min_val) / len(colors)
for i, color in enumerate(colors):
value = min_val + i * step
legend_html += f'''
<tr>
<td style="width:30px; background-color:{color}; height:20px;"></td>
<td style="padding-left:10px;">{value:.0f} - {value + step:.0f}</td>
</tr>
'''
legend_html += '''
</table>
</div>
'''
m.get_root().html.add_child(folium.Element(legend_html))
# Save the solar potential data
solar_df.to_csv('india_solar_data.csv', index=False)
return m, solar_df
def main():
"""
Main function to run the application
"""
geojson_path = 'india-soi.geojson'
code
try:
print("Creating India's solar potential map...")
solar_map, solar_data = create_india_solar_map(geojson_path)
solar_map.save('india_solar_potential.html')
print("\nMap has been generated and saved as 'india_solar_potential.html'")
print("Raw data has been saved as 'india_solar_data.csv'")
except Exception as e:
print(f"An error occurred: {e}")
if name == "main":
main()
Do you think the above code will generate a solar potential map of India like a proper heatmap and not just hotspots? if not, please write a code which can generate countour like heatmap for solar potential.
The current code you provided utilizes Folium's HeatMap plugin to visualize solar potential across India. While this approach effectively highlights areas with higher solar potential (hotspots), it doesn't generate contour-like visualizations that display gradients and smooth transitions between different levels of solar potential.
To create a more nuanced, contour-like heatmap for solar potential across India, you can enhance the visualization by adding contour layers. This can be achieved by:
Interpolating the Solar Potential Data: Using a finer grid and interpolation methods (which you've already implemented).
Generating Contour Lines or Filled Contours: Utilizing libraries like matplotlib to create contour lines or filled contour images based on the interpolated data.
Overlaying Contours onto the Folium Map: Integrating the generated contours with the interactive Folium map.
Below, I'll provide an enhanced version of your code that incorporates contour lines using matplotlib and overlays them onto the Folium map. This approach combines the interactivity of Folium with the detailed visualizations from matplotlib.
Enhanced Code with Contour Visualization
python
import numpy as np
import pandas as pd
import geopandas as gpd
import folium
from folium import plugins
import requests
from scipy.interpolate import griddata
import time
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import branca.colormap as bcm
def fetch_nasa_power_data(lat, lon):
"""
Fetch solar radiation data from NASA POWER API
"""
base_url = "https://power.larc.nasa.gov/api/temporal/daily/point"
params = {
'parameters': 'ALLSKY_SFC_SW_DWN',
'community': 'RE',
'longitude': str(lon),
'latitude': str(lat),
'start': '20230101',
'end': '20231231',
'format': 'JSON'
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json()
return data
except requests.exceptions.RequestException as e:
print(f"Error making request: {e}")
return None
except ValueError as e:
print(f"Error parsing JSON: {e}")
return None
def calculate_solar_potential(power_data, panel_efficiency=0.2):
"""
Calculate solar potential based on radiation data
"""
if power_data is None:
return None
try:
daily_data = power_data.get('properties', {}).get('parameter', {}).get('ALLSKY_SFC_SW_DWN', {})
if not daily_data:
print("No daily data found in response")
return None
radiation_values = []
for value in daily_data.values():
if isinstance(value, (int, float)) and value != -999:
radiation_values.append(value * 0.277778) # Convert MJ to kWh
if not radiation_values:
print("No valid radiation values found")
return None
annual_potential = np.mean(radiation_values) * 365 * panel_efficiency
return annual_potential
except (KeyError, TypeError) as e:
print(f"Error processing data: {e}")
return None
def create_india_solar_map(geojson_path):
"""
Create an interactive map of India's solar potential with interpolated contours
"""
# Read India GeoJSON
india = gpd.read_file(geojson_path)
# Create a base map centered on India
m = folium.Map(location=[20.5937, 78.9629], zoom_start=5)
# Create a grid for sampling points
lat_range = np.arange(8.4, 37.6, 1.0) # Using 1.0 degree step for faster processing
lon_range = np.arange(68.7, 97.25, 1.0)
# Store solar potential data
solar_data = []
# Fetch data for each grid point
total_points = len(lat_range) * len(lon_range)
current_point = 0
for lat in lat_range:
for lon in lon_range:
current_point += 1
print(f"Processing point {current_point}/{total_points}")
point = gpd.points_from_xy([lon], [lat])[0]
# Check if point is within India
if any(india.geometry.contains(point)):
power_data = fetch_nasa_power_data(lat, lon)
time.sleep(2) # Rate limiting
if power_data:
potential = calculate_solar_potential(power_data)
if potential is not None:
solar_data.append({
'latitude': lat,
'longitude': lon,
'potential': potential
})
# Create DataFrame from collected data
solar_df = pd.DataFrame(solar_data)
if solar_df.empty:
raise ValueError("No solar data could be collected. Please check API access and coordinates.")
# Create a finer mesh grid for interpolation
grid_lat = np.linspace(solar_df['latitude'].min(), solar_df['latitude'].max(), 500)
grid_lon = np.linspace(solar_df['longitude'].min(), solar_df['longitude'].max(), 500)
grid_lon, grid_lat = np.meshgrid(grid_lon, grid_lat)
# Interpolate the data
points = solar_df[['longitude', 'latitude']].values
values = solar_df['potential'].values
grid_z = griddata(points, values, (grid_lon, grid_lat), method='cubic')
# Mask points outside India using GeoPandas
grid_points = gpd.GeoDataFrame(geometry=gpd.points_from_xy(grid_lon.flatten(), grid_lat.flatten()))
grid_points['z'] = grid_z.flatten()
grid_points = grid_points.dropna(subset=['z'])
grid_points = grid_points[grid_points['z'] != -999]
# Optionally, you can clip the interpolated data to India's boundaries
grid_clip = gpd.clip(grid_points, india.unary_union)
# Add the heatmap layer (optional: you can remove this if you prefer only contours)
locations = [[lat, lon] for lat, lon in zip(solar_df['latitude'], solar_df['longitude'])]
heatmap_values = solar_df['potential'].tolist()
hm = plugins.HeatMap(
locations,
heatmap_values,
min_opacity=0.4,
radius=15,
blur=15,
max_zoom=7,
gradient={
0.4: '#ffffb2',
0.6: '#fecc5c',
0.7: '#fd8d3c',
0.8: '#f03b20',
1.0: '#bd0026'
}
)
hm.add_to(m)
# Create a contour plot using matplotlib
fig, ax = plt.subplots(figsize=(8, 6))
contour = ax.contourf(grid_lon, grid_lat, grid_z, levels=15, cmap='viridis', alpha=0.6)
# Save the contour as a PNG image with transparent background
plt.axis('off')
contour_cb = fig.colorbar(contour, ax=ax, orientation='vertical', shrink=0.5)
plt.savefig('contour.png', bbox_inches='tight', pad_inches=0, transparent=True)
plt.close()
# Get the bounds of the grid
bounds = [grid_lat.min(), grid_lon.min(), grid_lat.max(), grid_lon.max()]
# Add the contour image as an overlay
img_path = 'contour.png'
folium.raster_layers.ImageOverlay(
name='Solar Potential Contours',
image=img_path,
bounds=[[bounds[0], bounds[1]], [bounds[2], bounds[3]]],
opacity=0.6,
interactive=True,
cross_origin=False,
zindex=1,
).add_to(m)
# Add GeoJSON boundary
folium.GeoJson(
india,
style_function=lambda x: {
'fillColor': 'none',
'color': 'black',
'weight': 1.5
}
).add_to(m)
# Add layer control
folium.LayerControl().add_to(m)
# Add legend using branca
min_val = solar_df['potential'].min()
max_val = solar_df['potential'].max()
colormap = bcm.linear.Viridis_09.scale(min_val, max_val)
colormap.caption = 'Solar Potential (kWh/m²/year)'
colormap.add_to(m)
# Save the solar potential data
solar_df.to_csv('india_solar_data.csv', index=False)
return m, solar_df
def main():
"""
Main function to run the application
"""
geojson_path = 'india-soi.geojson' # Ensure this path is correct and the file exists
try:
print("Creating India's solar potential map...")
solar_map, solar_data = create_india_solar_map(geojson_path)
solar_map.save('india_solar_potential.html')
print("\nMap has been generated and saved as 'india_solar_potential.html'")
print("Raw data has been saved as 'india_solar_data.csv'")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
Explanation of Enhancements
Interpolated Grid Refinement:
Increased Grid Resolution: Changed the grid resolution to 500x500 for smoother contour transitions.
Data Clipping: Optionally clipped the interpolated data to India's boundaries to ensure contours are only generated within the country.
Contour Generation with Matplotlib:
Contour Plot Creation: Utilized matplotlib to generate filled contour plots (contourf) based on the interpolated solar potential data.
Transparent Background: Saved the contour plot as a PNG image with a transparent background to overlay it seamlessly onto the Folium map.
Overlaying Contours onto Folium Map:
Image Overlay: Used folium.raster_layers.ImageOverlay to add the contour image to the Folium map. The opacity can be adjusted (opacity=0.6) to allow visibility of underlying map features.
Bounds Definition: Defined the geographical bounds for the overlay based on the interpolated grid to ensure accurate placement.
Color Mapping and Legend:
Branca Colormap: Integrated branca.colormap to create an interactive legend that reflects the color gradients used in the contour plot.
Layer Control: Added folium.LayerControl() to allow toggling between different layers (e.g., heatmap and contour overlay).
Optional Heatmap Layer:
Retained the HeatMap layer as an optional feature. You can choose to keep it for additional density visualization or remove it if you prefer only contour visualizations.
Additional Recommendations
Optimizing API Requests:
Caching: Implement caching mechanisms to store and reuse API responses, especially if running the script multiple times.
Parallel Processing: Consider using parallel processing (e.g., multiprocessing or concurrent.futures) to speed up data fetching, keeping in mind the API's rate limits.
Handling Missing Data:
Ensure robust handling of missing or erroneous data points to prevent interpolation artifacts.
Enhancing the Referenced GeoJSON:
Verify that the india-soi.geojson file accurately represents India's boundaries and is suitable for spatial operations.
Dynamic Contour Resolution:
Adjust the number of contour levels (levels=15) and the colormap (cmap='viridis') based on your preference for visualization clarity.
Interactive Features:
You can enhance interactivity by adding tooltips or popups that display specific solar potential values when users hover over or click on certain areas.
Visual Improvements
Transparency Adjustment: Adjust the transparency (opacity) of both the heatmap and the contour overlay to ensure that multiple layers complement each other without obscuring essential map details.
Color Consistency: Ensure that the color scales used in both the heatmap and contour plots are consistent to prevent confusion.
Potential Limitations
Performance: Generating high-resolution contour plots and overlaying large images on Folium maps can impact performance, especially in web browsers. Balance the grid resolution with performance considerations based on your use case.
Accuracy of Interpolation: The accuracy of the contour visualization depends on the interpolation method (cubic) and the density of the original data points. Ensure that the interpolated data realistically represents the solar potential across Indonesia.
By incorporating contour overlays along with the existing heatmap, you achieve a more detailed and informative visualization of India's solar potential. This approach provides both a broad overview (via the heatmap) and detailed gradient information (via contours), enhancing the map's utility for analysis and decision-making.