I have two files: 1. collectsolardata.py: import asyncio import aiohttp import geopandas…
- User
I have two files:
- collect_solar_data.py: import asyncio import aiohttp import geopandas as gpd import pandas as pd from shapely.geometry import Point import time import logging import diskcache as dc from rasterio.transform import from_bounds import numpy as np
logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler("solar_data_collection.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()
codeasync def acquire(self): async with self.lock: current = time.time() self.calls = [t for t in self.calls if t > current - self.period] if len(self.calls) >= self.max_calls: sleep_time = self.period - (current - min(self.calls)) + 0.1 await asyncio.sleep(sleep_time) self.calls.append(current)rate_limiter = RateLimiter(max_calls=2, period=1)
async def fetch_solar_data(session, latitude, longitude, cache): cache_key = f"solar_data_{latitude}_{longitude}" if cache_key in cache: return cache[cache_key]
codeapi_url = "https://power.larc.nasa.gov/api/temporal/daily/point" params = { "parameters": "ALLSKY_SFC_SW_DWN", "community": "SB", "longitude": longitude, "latitude": latitude, "start": "20200101", "end": "20201231", "format": "JSON" } try: await rate_limiter.acquire() async with session.get(api_url, params=params, timeout=30) as response: if response.status == 429: logger.warning("Rate limit exceeded, sleeping for 60 seconds") await asyncio.sleep(60) return None elif response.status != 200: logger.error(f"Error {response.status} for ({latitude}, {longitude})") return None data = await response.json() solar_data = data.get("properties", {}).get("parameter", {}).get("ALLSKY_SFC_SW_DWN", {}) if not solar_data: return None avg_radiation = sum(solar_data.values()) / len(solar_data) * 0.0036 result = { "latitude": latitude, "longitude": longitude, "potential": round(avg_radiation, 2) } cache[cache_key] = result return result except Exception as e: logger.error(f"Error fetching data for ({latitude}, {longitude}): {e}") return None - Assistant