Sure! Below is a complete Flask web application that calculates the hourly energy consumption for a household based on historical data and then automatically determines the optimal size of a solar panel system for the house based on location-specific solar radiation data.
Overview:
- Frontend: HTML templates using Jinja2 for rendering forms and results.
- Backend: Flask application handling routes, data processing, and calculations.
- Data Sources:
- Historical household energy consumption data (simulated for demonstration).
- Solar radiation data fetched from the National Renewable Energy Laboratory (NREL) Solar Resource API (you need to get an API key).
Prerequisites
- Python 3.x
- Flask
- Requests (for making API calls)
- Pandas (for data manipulation)
Install the required packages:
pip install flask requests pandas
Steps
-
Get an NREL API Key:
-
Set Up the Flask Application Structure:
- Create the following files:
app.py
templates/index.html
templates/result.html
static/ directory (if needed for CSS/JS)
Code Implementation
1. app.py
from flask import Flask, render_template, request
import pandas as pd
import requests
app = Flask(__name__)
# Replace 'YOUR_API_KEY' with your actual NREL API key
NREL_API_KEY = 'YOUR_API_KEY'
# Sample historical consumption data (simulated)
def get_historical_consumption():
# Simulate hourly consumption data for a year (kWh)
hourly_consumption = pd.DataFrame({
'hour': pd.date_range(start='1/1/2022', periods=8760, freq='H'),
'consumption': 0.75 # Average consumption per hour in kWh
})
# Add some variability
hourly_consumption['consumption'] += (pd.Series(pd.np.random.rand(8760)) - 0.5) * 0.5
return hourly_consumption
# Fetch solar radiation data from NREL API
def get_solar_radiation(lat, lon):
url = 'https://developer.nrel.gov/api/solar/solar_resource/v1.json'
params = {
'api_key': NREL_API_KEY,
'lat': lat,
'lon': lon,
}
response = requests.get(url, params=params)
data = response.json()
if 'outputs' in data:
yearly_radiation = data['outputs']['avg_dni']['annual']
return yearly_radiation # in kWh/m^2/day
else:
return None
# Calculate required solar panel size
def calculate_solar_panel_size(total_consumption, solar_radiation):
# Assume panel efficiency and other factors
panel_efficiency = 0.20 # 20%
system_losses = 0.86 # 14% losses
# Total energy production needed per day
daily_consumption = total_consumption / 365 # kWh/day
# Required system size in kW
required_system_size = daily_consumption / (solar_radiation * panel_efficiency * system_losses)
return required_system_size # in kW
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Get user input
lat = request.form.get('latitude')
lon = request.form.get('longitude')
# Get historical consumption data
consumption_data = get_historical_consumption()
total_consumption = consumption_data['consumption'].sum() # Annual consumption in kWh
# Get solar radiation data
solar_radiation = get_solar_radiation(lat, lon)
if solar_radiation is None:
error_message = 'Error fetching solar radiation data. Please check the coordinates.'
return render_template('index.html', error=error_message)
# Calculate required solar panel size
system_size = calculate_solar_panel_size(total_consumption, solar_radiation)
return render_template('result.html',
total_consumption=total_consumption,
solar_radiation=solar_radiation,
system_size=round(system_size, 2),
lat=lat,
lon=lon)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
2. templates/index.html
<!doctype html>
<html lang="en">
<head>
<title>Solar Panel Sizing App</title>
</head>
<body>
<h1>Solar Panel Sizing Application</h1>
{% if error %}
<p style="color: red;">{{ error }}</p>
{% endif %}
<form method="post">
<label for="latitude">Latitude:</label><br>
<input type="text" id="latitude" name="latitude" required><br><br>
<label for="longitude">Longitude:</label><br>
<input type="text" id="longitude" name="longitude" required><br><br>
<input type="submit" value="Calculate">
</form>
</body>
</html>
3. templates/result.html
<!doctype html>
<html lang="en">
<head>
<title>Solar Panel Sizing Results</title>
</head>
<body>
<h1>Results</h1>
<p><strong>Location:</strong> Latitude {{ lat }}, Longitude {{ lon }}</p>
<p><strong>Total Annual Consumption:</strong> {{ total_consumption | round(2) }} kWh</p>
<p><strong>Average Daily Solar Radiation:</strong> {{ solar_radiation }} kWh/m²/day</p>
<p><strong>Required Solar Panel System Size:</strong> {{ system_size }} kW</p>
<br>
<a href="{{ url_for('index') }}">Back</a>
</body>
</html>
Explanation
-
get_historical_consumption():
- Simulates hourly energy consumption data for one year (8760 hours).
- Introduces random variability to mimic real-world data.
- In a real application, replace this with actual historical data from the user or a database.
-
get_solar_radiation(lat, lon):
- Uses the NREL Solar Resource API to fetch average daily solar radiation (Direct Normal Irradiance) based on latitude and longitude.
- Parses the JSON response to extract the annual average radiation value.
-
calculate_solar_panel_size(total_consumption, solar_radiation):
- Calculates the required size of the solar panel system in kilowatts (kW).
- Considers panel efficiency and system losses.
- Formula:
[
\text{Required System Size (kW)} = \frac{\text{Daily Consumption (kWh/day)}}{\text{Average Daily Solar Radiation (kWh/m}^2\text{/day)} \times \text{Panel Efficiency} \times \text{System Losses}}
]
-
Flask Routes:
'/':
- Handles both GET and POST requests.
- On POST, retrieves latitude and longitude, performs calculations, and renders the result.
Running the Application
-
Ensure all dependencies are installed.
-
Replace 'YOUR_API_KEY' in app.py with the API key you obtained from NREL.
-
Run the Flask app:
python app.py
-
Access the application in your web browser at http://localhost:5000.
Notes
-
Error Handling:
- The app includes basic error handling for the API call.
- In case of failure to fetch solar radiation data, it displays an error message.
-
Data Sources:
- For production, integrate real historical consumption data.
- Ensure compliance with data privacy laws when handling user data.
-
Enhancements:
- Add user authentication to save and retrieve user-specific data.
- Incorporate more detailed factors such as tilt angle, shading, and seasonal variations.
- Provide graphical representations of consumption and production.
-
APIs and Data Licensing:
- The NREL Solar Resource API is free to use with an API key but check their terms of use.
- If using other data sources, ensure you comply with their licensing agreements.
Disclaimer
This application is a simplified example intended for educational purposes. In a real-world scenario, you should:
- Validate and sanitize all user inputs.
- Use secured methods to store API keys (avoid hardcoding them).
- Implement robust error handling and logging.
- Consider asynchronous requests for API calls to avoid blocking the main thread.
- Scale the application according to the anticipated load.
Let me know if you need any further assistance or modifications!