Sure! To adapt your existing solar potential mapping script from India to Gujarat, you'll need to make a few modifications:
-
Update the GeoJSON Path: Change the default GeoJSON file from india-soi.geojson to gujarat.geojson.
-
Adjust Logging and Documentation: Update log messages and comments to reflect that the focus is now on Gujarat instead of India.
-
Optimize Grid Parameters (Optional): Since Gujarat is smaller than India, you might want to adjust the grid step sizes (lat_step and lon_step) to increase the resolution if needed. However, this is optional and depends on your requirements.
Below is the updated script with these changes implemented:
import asyncio
import aiohttp
import numpy as np
import pandas as pd
import geopandas as gpd
import folium
from shapely.geometry import Point
from scipy.interpolate import griddata
import time
import branca.colormap as cm
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import os
import logging
import diskcache as dc
from tqdm.asyncio import tqdm_asyncio
import json
# Logging setup
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.FileHandler("solar_map.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class RateLimiter:
def __init__(self, max_calls, period):
self.max_calls = max_calls
self.period = period
self.calls = []
self.lock = asyncio.Lock()
async def acquire(self):
async with self.lock:
current = time.time()
while self.calls and self.calls[0] <= current - self.period:
self.calls.pop(0)
if len(self.calls) >= self.max_calls:
sleep_time = self.period - (current - self.calls[0]) + 0.1
logger.info(f"Rate limit reached. Sleeping for {sleep_time:.2f} seconds.")
await asyncio.sleep(sleep_time)
self.calls.append(time.time())
rate_limiter = RateLimiter(max_calls=1, period=2) # 1 call every 2 seconds
async def fetch_nasa_power_data(session, lat, lon, cache):
key = f"{lat}_{lon}"
if key in cache:
return cache.get(key)
base_url = "https://power.larc.nasa.gov/api/temporal/daily/point"
params = {
'parameters': 'ALLSKY_SFC_SW_DWN',
'community': 'RE',
'longitude': lon,
'latitude': lat,
'start': '20230101',
'end': '20231231',
'format': 'JSON'
}
while True:
try:
await rate_limiter.acquire()
async with session.get(base_url, params=params) as response:
if response.status == 429:
retry_after = response.headers.get('Retry-After')
sleep_time = int(retry_after) + 1 if retry_after else 60
logger.warning(f"Received 429 for lat={lat}, lon={lon}. Retrying after {sleep_time} seconds.")
await asyncio.sleep(sleep_time)
continue
response.raise_for_status()
data = await response.json()
cache.set(key, data)
return data
except aiohttp.ClientError as e:
logger.error(f"ClientError for lat={lat}, lon={lon}: {e}. Retrying in 10 seconds.")
await asyncio.sleep(10)
except asyncio.TimeoutError:
logger.error(f"TimeoutError for lat={lat}, lon={lon}. Retrying in 10 seconds.")
await asyncio.sleep(10)
except json.JSONDecodeError as e:
logger.error(f"JSONDecodeError for lat={lat}, lon={lon}: {e}. Skipping this point.")
cache.set(key, None)
return None
def calculate_solar_potential(power_data, panel_efficiency=0.2):
if not power_data:
return None
try:
daily_data = power_data['properties']['parameter']['ALLSKY_SFC_SW_DWN']
radiation_values = [v * 0.277778 for v in daily_data.values()
if isinstance(v, (int, float)) and v != -999]
if not radiation_values:
return None
return np.mean(radiation_values) * 365 * panel_efficiency
except KeyError as e:
logger.error(f"KeyError while calculating solar potential: {e}")
return None
except Exception as e:
logger.error(f"Unexpected error while calculating solar potential: {e}")
return None
async def fetch_and_calculate(session, lat, lon, cache):
power_data = await fetch_nasa_power_data(session, lat, lon, cache)
potential = calculate_solar_potential(power_data)
if potential is not None:
return {'latitude': lat, 'longitude': lon, 'potential': potential}
return None
async def create_gujarat_solar_map_async(geojson_path='gujarat.geojson'):
logger.info(f"Reading GeoJSON file from: {geojson_path}")
gujarat = gpd.read_file(geojson_path)
bounds = gujarat.total_bounds
logger.info(f"Map bounds: {bounds}")
center_lat = (bounds[1] + bounds[3]) / 2
center_lon = (bounds[0] + bounds[2]) / 2
m = folium.Map(location=[center_lat, center_lon], zoom_start=7, tiles='CartoDB positron') # Adjusted zoom_start for smaller area
# Adjust grid step size if necessary
lat_step = 0.5
lon_step = 0.5
lat_range = np.arange(bounds[1], bounds[3] + lat_step, lat_step)
lon_range = np.arange(bounds[0], bounds[2] + lon_step, lon_step)
cache = dc.Cache('nasa_power_cache_gujarat') # Separate cache for Gujarat
connector = aiohttp.TCPConnector(limit=10) # Limit concurrency
timeout = aiohttp.ClientTimeout(total=60) # Set timeout for requests
logger.info("Starting data collection with asynchronous requests...")
solar_data = []
gujarat_union = gujarat.unary_union
grid_points = [(lat, lon) for lat in lat_range for lon in lon_range
if gujarat_union.contains(Point(lon, lat)) or gujarat_union.touches(Point(lon, lat))]
total_grid_points = len(grid_points)
logger.info(f"Total grid points to process: {total_grid_points}")
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
tasks = [
fetch_and_calculate(session, lat, lon, cache)
for lat, lon in grid_points
]
for future in tqdm_asyncio.as_completed(tasks, total=total_grid_points, desc="Processing Points"):
result = await future
if result:
solar_data.append(result)
cache.close()
solar_df = pd.DataFrame(solar_data)
if solar_df.empty:
raise ValueError("No solar data collected for Gujarat")
logger.info("Creating visualization...")
grid_size = 500 # Adjust grid size if necessary
grid_lat = np.linspace(bounds[1], bounds[3], grid_size)
grid_lon = np.linspace(bounds[0], bounds[2], grid_size)
grid_lon, grid_lat = np.meshgrid(grid_lon, grid_lat)
points = solar_df[['longitude', 'latitude']].values
values = solar_df['potential'].values
grid_z = griddata(points, values, (grid_lon, grid_lat), method='linear')
gujarat_gdf = gpd.GeoSeries([Point(lon, lat) for lon, lat in zip(grid_lon.flatten(), grid_lat.flatten())])
mask = gujarat_gdf.within(gujarat_union).values.reshape(grid_z.shape)
grid_z = np.ma.masked_array(grid_z, ~mask)
colormap = cm.LinearColormap(
['#440154', '#482878', '#3E4989', '#31688E', '#26828E',
'#1F9E89', '#35B779', '#6DCD59', '#B4DE2C', '#FDE725'],
vmin=np.nanmin(values),
vmax=np.nanmax(values),
caption='Solar Potential (kWh/m²/year)'
)
fig, ax = plt.subplots(figsize=(10, 12)) # Adjust figure size for Gujarat
ax.set_axis_off()
img = ax.imshow(
grid_z,
cmap=ListedColormap(colormap.colors),
extent=[bounds[0], bounds[2], bounds[1], bounds[3]],
origin='lower',
aspect='auto'
)
gujarat.boundary.plot(ax=ax, color='black', linewidth=1)
image_path = 'gujarat_solar_potential_high_res.png'
plt.savefig(image_path, bbox_inches='tight', pad_inches=0, dpi=300) # Adjusted file name
plt.close(fig)
folium.raster_layers.ImageOverlay(
name='Solar Potential',
image=image_path,
bounds=[[bounds[1], bounds[0]], [bounds[3], bounds[2]]],
opacity=0.7,
interactive=True,
cross_origin=False,
zindex=1,
).add_to(m)
folium.GeoJson(
gujarat,
style_function=lambda x: {
'fillColor': 'none',
'color': 'black',
'weight': 1.5,
'fillOpacity': 0
},
name='Gujarat Boundary'
).add_to(m)
colormap.add_to(m)
folium.LayerControl().add_to(m)
output_csv = 'gujarat_solar_data.csv'
output_html = 'gujarat_solar_potential.html'
logger.info(f"Saving data to {output_csv}")
solar_df.to_csv(output_csv, index=False)
logger.info(f"Saving map to {output_html}")
m.save(output_html)
return m, solar_df
async def main_async():
try:
logger.info("Starting solar potential map generation for Gujarat with improved alignment...")
solar_map, solar_data = await create_gujarat_solar_map_async()
logger.info("Process completed successfully!")
logger.info("Map has been saved as 'gujarat_solar_potential.html'")
logger.info("Raw data has been saved as 'gujarat_solar_data.csv'")
except Exception as e:
logger.error(f"An error occurred: {e}")
def main():
asyncio.run(main_async())
if __name__ == "__main__":
main()
Detailed Changes Explained
-
GeoJSON Path Update:
- Changed the default GeoJSON file from
'india-soi.geojson' to 'gujarat.geojson' in the create_gujarat_solar_map_async function.
- Ensure that
gujarat.geojson is correctly formatted and located in the same directory as your script or provide the correct path.
-
Logging and Naming Adjustments:
- Updated log messages from "India" to "Gujarat" to reflect the new focus area.
- Changed cache directory name to
'nasa_power_cache_gujarat' to distinguish it from any previous caches.
- Updated output filenames from
'india_solar_data.csv' and 'india_solar_potential.html' to 'gujarat_solar_data.csv' and 'gujarat_solar_potential.html' respectively.
- Adjusted the
folium.Map's zoom_start parameter to 7 for a more appropriate zoom level for Gujarat. You can tweak this value based on how zoomed-in you want the initial map view to be.
-
Visualization Adjustments:
- Updated the image saving path to
'gujarat_solar_potential_high_res.png'.
- Adjusted the
figsize in matplotlib to better suit Gujarat's geographical size (10, 12) instead of (20, 24) used for India. Adjust as necessary.
- Ensured that the GeoJSON layer in Folium is now labeled
'Gujarat Boundary' instead of 'India Boundary'.
-
Cache Management:
- Changed the cache directory to
'nasa_power_cache_gujarat' to prevent any potential conflicts with prior India-related cache data.
-
Function Renaming:
- Renamed the main mapping function from
create_india_solar_map_async to create_gujarat_solar_map_async for clarity and consistency.
-
Error Handling:
- Updated error messages to mention Gujarat, ensuring that any issues are clearly attributed to the correct geographic focus.
Additional Recommendations
-
Grid Step Size: Depending on Gujarat's size and the desired resolution, you might consider adjusting lat_step and lon_step. Smaller steps yield higher resolution but increase the number of requests and processing time.
-
Concurrency Limits: The aiohttp.TCPConnector limit is set to 10. Depending on your system's capabilities and the API's rate limits, you might adjust this number for optimal performance.
-
Caching Strategy: Ensure that the cache directory ('nasa_power_cache_gujarat') has sufficient storage space, especially if you're planning to run this script multiple times or for large areas.
-
GeoJSON Projections: Ensure that your gujarat.geojson file uses the correct coordinate reference system (CRS), typically WGS84 (EPSG:4326). If not, you may need to reproject it using GeoPandas before processing.
-
Visualization Enhancements: You can further enhance the Folium map by adding tooltips, pop-ups, or additional layers as needed.
Running the Script
-
Ensure Dependencies are Installed:
Make sure you have all the required Python packages installed. You can install them using pip:
pip install asyncio aiohttp numpy pandas geopandas folium shapely scipy matplotlib diskcache tqdm branca
-
Place gujarat.geojson in the Correct Directory:
Ensure that the gujarat.geojson file is in the same directory as your script or provide the correct path when calling the create_gujarat_solar_map_async function.
-
Execute the Script:
Run the script using Python:
python your_script_name.py
Replace your_script_name.py with the actual name of your Python script file.
-
Output:
- CSV File:
gujarat_solar_data.csv containing the raw solar potential data for each grid point.
- HTML Map:
gujarat_solar_potential.html interactive map visualizing the solar potential.
- Image Overlay:
gujarat_solar_potential_high_res.png used as the image overlay on the Folium map.
- Log File:
solar_map.log containing detailed logs of the script's execution.
By following these modifications and recommendations, your script should successfully generate a solar potential map focused on Gujarat using the provided gujarat.geojson file.