### Python API: Get Location Data and Weather Sensors Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt Provides functions to parse location strings, generate coordinate grids for weather data collection, find nearest weather sensors, and retrieve location data from asset IDs. It supports single points and bounding box regions with hexagonal or square grid generation. ```python from flexmeasures_weather.utils.locating import ( get_locations, find_weather_sensor_by_location, get_location_by_asset_id, ) # Single location locations = get_locations("52.3676,4.9041", num_cells=1, method="hex") # Returns: [(52.3676, 4.9041)] # Bounding box with grid - creates 9 measurement points locations = get_locations( location="52.5,4.0:51.5,5.5", # top-left:bottom-right num_cells=9, method="hex" # or "square" ) # Returns: list of 9 (latitude, longitude) tuples distributed across the region # Find nearest weather sensor to a location sensor = find_weather_sensor_by_location( location=(52.3676, 4.9041), max_degree_difference_for_nearest_weather_sensor=1, sensor_name="temperature" ) # Returns: Sensor object or None if no sensor within distance threshold # Get location from existing asset location = get_location_by_asset_id(asset_id=7) # Returns: (latitude, longitude) tuple ``` -------------------------------- ### Python: Extend to New Weather Providers Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt Demonstrates how to add support for new weather API services by implementing a new API function and integrating it into the existing dispatcher. The new function must return data in an OWM-compatible format, including at least 48 hours of hourly forecast data. ```python # In flexmeasures_weather/utils/weather.py from typing import Tuple, List, Dict from datetime import datetime def call_newapi_api( api_key: str, location: Tuple[float, float] ) -> Tuple[datetime, List[Dict]]: """ Call your new weather API and return data in OWM-compatible format. Must return at least 48 hours of hourly forecast data. """ latitude, longitude = location # Make API request response = requests.get( f"https://api.newweather.com/forecast", params={"lat": latitude, "lon": longitude, "key": api_key} ) data = response.json() # Convert to standardized format time_of_call = datetime.fromtimestamp(data["timestamp"]) hourly = [ { "dt": hour["timestamp"], "temp": hour["temperature_celsius"], "wind_speed": hour["wind_ms"], "clouds": hour["cloud_percent"], "humidity": hour["humidity"], # ... other fields } for hour in data["hourly"][:48] ] return time_of_call, hourly # Update call_api() dispatcher def call_api(api_key: str, location: Tuple[float, float]) -> Tuple[datetime, List[Dict]]: provider = str(current_app.config.get("WEATHER_PROVIDER", "")) if provider not in ["OWM", "WAPI", "NEWAPI"]: raise Exception("Invalid provider. Use OWM, WAPI, or NEWAPI.") if provider == "OWM": return call_openweatherapi(api_key, location) elif provider == "WAPI": return call_weatherapi(api_key, location) else: return call_newapi_api(api_key, location) ``` -------------------------------- ### Collect Weather Forecasts CLI Command Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt CLI commands to collect 48-hour weather forecasts from the configured API provider. Supports collecting data for single locations, grids of locations using bounding boxes, and options for storing data in the database or exporting as JSON files. ```bash # Get forecasts for a single location and store in database flexmeasures weather get-weather-forecasts --location 52.3676,4.9041 # Output: # [FLEXMEASURES-WEATHER] Getting weather forecasts: # [FLEXMEASURES-WEATHER] Latitude, Longitude # [FLEXMEASURES-WEATHER] ----------------------- # [FLEXMEASURES] 52.3676, 4.9041 # [FLEXMEASURES-WEATHER] Called OpenWeatherMap API successfully at 2024-01-15 14:30:00+00:00. # [FLEXMEASURES-WEATHER] Processing forecast for 2024-01-15 14:00:00+00:00 ... # [FLEXMEASURES-WEATHER] Saving temperature forecasts ... # Get forecasts for an existing weather station asset flexmeasures weather get-weather-forecasts --asset-id 7 # Get forecasts for a grid of locations (bounding box) flexmeasures weather get-weather-forecasts \ --location "52.5,4.0:51.5,5.5" \ --num_cells 9 \ --method hex # Save raw JSON files instead of database storage flexmeasures weather get-weather-forecasts \ --location 52.3676,4.9041 \ --store-as-json-files \ --region netherlands # Files saved to: /app/weather-forecasts/netherlands/2024-01-15T14-30-00/forecast_lat_52.3676_lng_4.9041.json ``` -------------------------------- ### Configure PostgreSQL Extensions for Geographical Calculations Source: https://github.com/flexmeasures/flexmeasures-weather/blob/main/README.md SQL commands required to enable the 'cube' and 'earthdistance' extensions in PostgreSQL, which are necessary for performing geographical calculations like finding the nearest weather station. ```sql CREATE EXTENSION IF NOT EXISTS cube; CREATE EXTENSION IF NOT EXISTS earthdistance; ``` -------------------------------- ### Extend Plugin with New Weather API Services Source: https://github.com/flexmeasures/flexmeasures-weather/blob/main/README.md Guidelines for adding new weather providers by implementing a specific API call function and updating the main dispatcher in the plugin code. ```python def call_NEWAPI_api(...): # Your logic to call the API and return data in the expected format pass def call_api(...): if provider not in ['OWM', 'WAPI', ..., 'NEWAPI']: raise Exception if provider == 'NEWAPI': return call_NEWAPI_api(...) ``` -------------------------------- ### FlexMeasures Configuration for Weather Plugin Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt Configuration settings for the FlexMeasures Weather plugin. This includes enabling the plugin, selecting a weather provider (OpenWeatherMap or Weather API), providing API keys, and setting optional parameters for data storage and location. ```ini # FlexMeasures configuration file # Add plugin to FlexMeasures FLEXMEASURES_PLUGINS = ["flexmeasures_weather"] # Select weather provider: "OWM" (OpenWeatherMap) or "WAPI" (Weather API) WEATHER_PROVIDER = "OWM" # API key for the selected provider WEATHERAPI_KEY = "your-api-key-here" # Optional: Custom data source name (default: "Weather") WEATHER_DATA_SOURCE_NAME = "OpenWeatherMap" # Optional: File path for JSON storage WEATHER_FILE_PATH_LOCATION = "/path/to/weather_output" # Optional: Weather station name WEATHER_STATION_NAME = "My Weather Station" # Optional: Maximum distance in degrees for weather sensor lookup (default: 1) WEATHER_MAXIMAL_DEGREE_LOCATION_DISTANCE = 1 ``` -------------------------------- ### Manage Weather Stations and Data Sources in Flexmeasures Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt This set of functions facilitates the management of weather station assets and data sources within Flexmeasures. `get_or_create_weather_station` creates or retrieves a weather station asset at specified coordinates, serving as a parent for weather sensors. `get_or_create_weather_station_type` ensures the existence of the 'weather station' asset type, and `get_weather_station_by_asset_id` retrieves an existing station. `get_or_create_owm_data_source` configures the data source for weather beliefs. ```python from flexmeasures_weather.utils.modeling import ( get_or_create_weather_station, get_or_create_weather_station_type, get_weather_station_by_asset_id, get_or_create_owm_data_source, ) # Get or create weather station at location weather_station = get_or_create_weather_station( latitude=52.3676, longitude=4.9041 ) # Returns: GenericAsset with type "weather station" # Get weather station type (creates if doesn't exist) station_type = get_or_create_weather_station_type() # Returns: GenericAssetType(name="weather station") # Retrieve existing weather station by asset ID station = get_weather_station_by_asset_id(asset_id=7) # Raises Exception if not found or missing location data # Get or create the data source for weather beliefs data_source = get_or_create_owm_data_source() # Returns: Source object with configured WEATHER_DATA_SOURCE_NAME ``` -------------------------------- ### Compute Solar Irradiance with Cloud Adjustment using pvlib Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt The `compute_irradiance` function calculates solar irradiance at a given location and time, incorporating cloud coverage adjustments. It utilizes the `pvlib` library to derive irradiance from cloud cover data, as direct irradiance is not always provided by weather APIs. A lower-level function `ghi_clear_to_ghi` is also available for converting clear-sky GHI to actual GHI. ```python from flexmeasures_weather.utils.radiating import compute_irradiance, ghi_clear_to_ghi from datetime import datetime from zoneinfo import ZoneInfo # Compute irradiance for a location at a specific datetime latitude = 52.3676 longitude = 4.9041 dt = datetime(2024, 6, 21, 12, 0, tzinfo=ZoneInfo("Europe/Amsterdam")) cloud_coverage = 0.3 # 30% cloud cover (0.0 to 1.0) irradiance = compute_irradiance(latitude, longitude, dt, cloud_coverage) # Returns: ~650 W/m² (varies based on solar position and cloud cover) # Lower-level function: convert clear-sky GHI to actual GHI ghi_clear = 850.0 # Clear-sky Global Horizontal Irradiance ghi_actual = ghi_clear_to_ghi(ghi_clear, cloud_coverage) # Returns: ~642.5 W/m² using Perez et al. (2007) model ``` -------------------------------- ### Manage Weather Sensors and Forecasts via CLI Source: https://github.com/flexmeasures/flexmeasures-weather/blob/main/README.md Commands to register weather sensors in the database and retrieve weather forecasts for specific geographic coordinates. These commands interact directly with the FlexMeasures system to store or export weather data. ```bash flexmeasures weather register-weather-sensor --name "wind speed" --latitude 30 --longitude 40 flexmeasures weather get-weather-forecasts --location 30,40 flexmeasures weather get-weather-forecasts --location 30,40 --store-as-json-files --region somewhere ``` -------------------------------- ### Python: Define and Retrieve Supported Sensor Specifications Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt Defines sensor types for weather data integration, including their FlexMeasures mapping, units, and attributes. It allows retrieval of specific sensor configurations and a formatted string of all supported sensors. ```python from flexmeasures_weather.sensor_specs import mapping from flexmeasures_weather.utils.weather import get_supported_sensor_spec, get_supported_sensors_str from datetime import timedelta # Available sensor specifications sensor_mapping = [ { "fm_sensor_name": "temperature", "weather_sensor_name": "temp", "unit": "°C", "event_resolution": timedelta(minutes=60), "attributes": {"daily_seasonality": True, "weekly_seasonality": False, "yearly_seasonality": True} }, { "fm_sensor_name": "wind speed", "weather_sensor_name": "wind_speed", "unit": "m/s", "event_resolution": timedelta(minutes=60), "attributes": {...} }, { "fm_sensor_name": "cloud cover", "weather_sensor_name": "clouds", "unit": "%", "event_resolution": timedelta(minutes=60), "attributes": {...} }, { "fm_sensor_name": "irradiance", # Computed from cloud cover "weather_sensor_name": "clouds", "unit": "W/m²", "event_resolution": timedelta(minutes=60), "attributes": {...} } ] # Get specific sensor spec temp_spec = get_supported_sensor_spec("temperature") # Returns: dict with sensor configuration # Get formatted string of all supported sensors supported = get_supported_sensors_str() # Returns: "temperature (°C), wind speed (m/s), cloud cover (%), irradiance (W/m²)" ``` -------------------------------- ### Register Weather Sensor CLI Command Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt Command-line interface (CLI) commands for registering new weather sensors within FlexMeasures. This allows specifying sensor name, location (latitude/longitude or asset ID), and timezone for different weather data types like temperature, wind speed, cloud cover, and irradiance. ```bash # Register a temperature sensor at specific coordinates flexmeasures weather register-weather-sensor \ --name "temperature" \ --latitude 52.3676 \ --longitude 4.9041 \ --timezone "Europe/Amsterdam" # Output: # [FLEXMEASURES-WEATHER] Successfully created weather sensor with ID 42, at weather station with ID 7 # [FLEXMEASURES-WEATHER] You can access this sensor at its entity address ea1.2023-01.io.flexmeasures:fm1.42 # Register wind speed sensor at existing weather station flexmeasures weather register-weather-sensor \ --name "wind speed" \ --asset-id 7 # Register irradiance sensor (computed from cloud cover) flexmeasures weather register-weather-sensor \ --name "irradiance" \ --latitude 51.9225 \ --longitude 4.4792 # View all options flexmeasures weather register-weather-sensor --help ``` -------------------------------- ### Configure FlexMeasures Weather Settings Source: https://github.com/flexmeasures/flexmeasures-weather/blob/main/README.md Configuration variables to be added to the FlexMeasures config file, including provider selection, API keys, and data storage paths. ```ini WEATHER_PROVIDER = OWM WEATHERAPI_KEY = your-api-key-here WEATHER_DATA_SOURCE_NAME = 'OpenWeatherMap' WEATHER_FILE_PATH_LOCATION = /path/to/weather_output.json ``` -------------------------------- ### PostgreSQL Extensions for Geographical Calculations Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt SQL commands to enable necessary PostgreSQL extensions for performing geographical calculations, which are required by the FlexMeasures Weather plugin for location-based services. ```sql -- Required PostgreSQL extensions for geographical calculations CREATE EXTENSION IF NOT EXISTS cube; CREATE EXTENSION IF NOT EXISTS earthdistance; ``` -------------------------------- ### Save Raw Weather Forecasts as JSON using Flexmeasures API Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt The `save_forecasts_as_json` function allows saving raw weather forecast responses directly to JSON files. This is useful for offline analysis or subsequent processing without immediate database integration. It requires an API key, a list of locations, and a specified data path for saving the files. ```python from flexmeasures_weather.utils.weather import save_forecasts_as_json api_key = "your-api-key" locations = [(52.3676, 4.9041)] data_path = "/path/to/weather-data/netherlands" save_forecasts_as_json(api_key, locations, data_path) # Creates files at: # /path/to/weather-data/netherlands/2024-01-15T14-30-00/forecast_lat_52.3676_lng_4.9041.json # JSON file contains the raw 48-hour forecast array from the weather API ``` -------------------------------- ### Save Weather Forecasts to Database using Flexmeasures API Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt The `save_forecasts_in_db` function processes weather forecasts fetched from external APIs and stores them as TimedBelief objects in the FlexMeasures database. It automatically identifies and utilizes registered weather sensors near the specified locations. This function requires an API key and a list of geographical coordinates. ```python from flexmeasures_weather.utils.weather import save_forecasts_in_db api_key = "your-api-key" locations = [ (52.3676, 4.9041), # Amsterdam (51.9225, 4.4792), # Rotterdam (52.0907, 5.1214), # Utrecht ] # Fetches forecasts and saves to database for all registered sensors at each location save_forecasts_in_db(api_key, locations) # Output: # [FLEXMEASURES-WEATHER] Getting weather forecasts: # [FLEXMEASURES-WEATHER] Latitude, Longitude # [FLEXMEASURES-WEATHER] ----------------------- # [FLEXMEASURES] 52.3676, 4.9041 # [FLEXMEASURES-WEATHER] Called OpenWeatherMap API successfully at 2024-01-15 14:30:00. # [FLEXMEASURES-WEATHER] Processing forecast for 2024-01-15 14:00:00+00:00 ... # Found pre-configured weather sensor temperature ... # [FLEXMEASURES-WEATHER] Saving temperature forecasts ... ``` -------------------------------- ### Python API to Call Weather Forecast API Source: https://context7.com/flexmeasures/flexmeasures-weather/llms.txt Python function to dispatch weather API calls based on the configured provider in FlexMeasures. It returns the timestamp of the API call and 48 hours of hourly forecast data in a normalized format. ```python from flexmeasures_weather.utils.weather import call_api, call_openweatherapi, call_weatherapi from flask import current_app # Using the dispatcher function (respects WEATHER_PROVIDER config) api_key = current_app.config.get("WEATHERAPI_KEY") location = (52.3676, 4.9041) # (latitude, longitude) time_of_api_call, hourly_forecasts = call_api(api_key, location) # time_of_api_call: datetime object of when the API was called ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.