File size: 11,121 Bytes
492fcd4
 
 
 
 
 
 
0be2dd5
492fcd4
 
 
 
 
0be2dd5
492fcd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0be2dd5
 
 
 
 
 
 
492fcd4
 
 
 
0be2dd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492fcd4
 
 
0be2dd5
 
 
492fcd4
0be2dd5
492fcd4
0be2dd5
 
 
 
 
492fcd4
0be2dd5
 
492fcd4
 
 
 
 
 
 
 
 
0be2dd5
 
492fcd4
 
 
0be2dd5
492fcd4
 
 
0be2dd5
492fcd4
0be2dd5
 
 
492fcd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0be2dd5
 
492fcd4
 
0be2dd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492fcd4
 
0be2dd5
492fcd4
 
 
 
0be2dd5
 
 
492fcd4
 
 
 
0be2dd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492fcd4
 
 
0be2dd5
 
 
 
 
 
 
bf46733
492fcd4
0be2dd5
 
 
492fcd4
 
 
 
 
0be2dd5
492fcd4
0be2dd5
 
 
 
 
 
 
 
492fcd4
0be2dd5
492fcd4
 
 
0be2dd5
492fcd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf46733
 
0be2dd5
 
492fcd4
bf46733
 
0be2dd5
 
492fcd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0be2dd5
492fcd4
0be2dd5
492fcd4
 
 
 
 
 
 
 
 
 
0be2dd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492fcd4
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import gradio as gr
import pandas as pd
import numpy as np
import requests
import plotly.graph_objects as go
from datetime import datetime, timedelta
import os
import re
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Set your Groq API key
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

# Constants
OPENPOWER_API_URL = "https://openpower.gridsingularity.com/api/v1/"
GROQ_API_URL = "https://api.groq.com/v1/chat/completions"

# CSS for styling
custom_css = """
.gradio-container {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    font-family: 'Arial', sans-serif;
}
.header {
    text-align: center;
    padding: 20px;
    background: linear-gradient(90deg, #1e3c72 0%, #2a5298 100%);
    color: white;
    border-radius: 10px;
    margin-bottom: 20px;
}
.footer {
    text-align: center;
    margin-top: 20px;
    padding: 10px;
    font-size: 12px;
    color: #666;
}
.plot-container {
    background: white;
    padding: 15px;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.forecast-result {
    background: white;
    padding: 15px;
    border-radius: 10px;
    margin-top: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.error {
    color: red;
    padding: 15px;
    background-color: #ffeeee;
    border-radius: 5px;
    margin-top: 10px;
}
"""

def fetch_openpower_data(region, start_date, end_date):
    """Fetch data from OpenPower API (simulated for this example)"""
    try:
        # In a real implementation, you would call the actual API here
        # For this example, we'll generate realistic synthetic data
        date_range = pd.date_range(start=start_date, end=end_date, freq='H')
        
        # Create more realistic load patterns (higher during day, lower at night)
        base_load = 800 + 400 * np.sin(np.linspace(0, 2*np.pi, len(date_range)))
        noise = np.random.normal(0, 50, len(date_range))
        load_data = np.clip(base_load + noise, 500, 1500)
        
        temperature = 15 + 10 * np.sin(np.linspace(0, 2*np.pi, len(date_range))) + np.random.normal(0, 2, len(date_range))
        
        df = pd.DataFrame({
            'timestamp': date_range,
            'load': load_data,
            'temperature': temperature
        })
        
        return df
    except Exception as e:
        print(f"Error generating synthetic data: {e}")
        return None

def extract_forecast_values(content):
    """Extract forecast values from Groq API response"""
    try:
        # Try to find a list pattern in the response
        match = re.search(r'\[([\d\.,\s]+)\]', content)
        if match:
            numbers = match.group(1).split(',')
            return [float(num.strip()) for num in numbers]
        
        # If no list found, try to parse numbers directly
        numbers = re.findall(r'\d+\.?\d*', content)
        if numbers:
            return [float(num) for num in numbers[:48]]  # Limit to 48 hours max
        
        return None
    except Exception as e:
        print(f"Error extracting forecast values: {e}")
        return None

def generate_forecast_with_groq(historical_data, forecast_horizon):
    """Generate forecast using Groq API"""
    if historical_data is None or len(historical_data) == 0:
        return None
    
    prompt = f"""
    You are an energy load forecasting expert. Analyze this hourly energy load data and predict the next {forecast_horizon} hours.
    
    Historical Data Statistics:
    - Mean: {historical_data['load'].mean():.2f} MW
    - Min: {historical_data['load'].min():.2f} MW
    - Max: {historical_data['load'].max():.2f} MW
    - Last 5 values: {historical_data['load'].tail(5).values.tolist()}
    
    Provide only the forecasted values as a Python list of numbers, formatted like this: [1234.5, 1256.7, ...]
    Important: Return ONLY the list of numbers, no additional text or explanation.
    """
    
    headers = {
        "Authorization": f"Bearer {GROQ_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "messages": [{"role": "user", "content": prompt}],
        "model": "mixtral-8x7b-32768",
        "temperature": 0.3  # Reduce randomness for more consistent results
    }
    
    try:
        response = requests.post(GROQ_API_URL, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        
        content = response.json()["choices"][0]["message"]["content"]
        forecast = extract_forecast_values(content)
        
        if forecast and len(forecast) >= forecast_horizon:
            return forecast[:forecast_horizon]
        return None
    
    except Exception as e:
        print(f"Error calling Groq API: {e}")
        return None

def create_forecast_plot(historical_data, forecast_values):
    """Create interactive plot with historical data and forecast"""
    fig = go.Figure()
    
    # Add historical data
    fig.add_trace(go.Scatter(
        x=historical_data['timestamp'],
        y=historical_data['load'],
        mode='lines+markers',
        name='Historical Load',
        line=dict(color='#1f77b4', width=2),
        marker=dict(size=4)
    ))
    
    # Add forecast data if available
    if forecast_values:
        forecast_timestamps = [historical_data['timestamp'].iloc[-1] + timedelta(hours=i+1) 
                             for i in range(len(forecast_values))]
        
        fig.add_trace(go.Scatter(
            x=forecast_timestamps,
            y=forecast_values,
            mode='lines+markers',
            name='Forecast',
            line=dict(color='#ff7f0e', width=2, dash='dot'),
            marker=dict(size=6, symbol='diamond')
        ))
        
        # Add confidence interval
        fig.add_trace(go.Scatter(
            x=forecast_timestamps + forecast_timestamps[::-1],
            y=[val * 1.1 for val in forecast_values] + [val * 0.9 for val in forecast_values[::-1]],
            fill='toself',
            fillcolor='rgba(255, 127, 14, 0.2)',
            line=dict(color='rgba(255,255,255,0)'),
            hoverinfo="skip",
            showlegend=False
        ))
    
    fig.update_layout(
        title='Energy Load Forecast (MW)',
        xaxis_title='Time',
        yaxis_title='Load (MW)',
        plot_bgcolor='rgba(255,255,255,0.9)',
        paper_bgcolor='rgba(255,255,255,0)',
        legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
        margin=dict(l=50, r=50, b=50, t=50, pad=4),
        hovermode="x unified"
    )
    
    return fig

def validate_dates(start_date, end_date):
    """Validate date inputs"""
    try:
        start = datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.strptime(end_date, "%Y-%m-%d")
        
        if start > end:
            return False, "Start date must be before end date"
        if (end - start).days > 30:
            return False, "Date range cannot exceed 30 days"
        
        return True, ""
    except ValueError:
        return False, "Invalid date format. Use YYYY-MM-DD"

def run_forecast(region, start_date, end_date, forecast_horizon):
    """Main function to run the forecast"""
    try:
        # Validate inputs
        valid, msg = validate_dates(start_date, end_date)
        if not valid:
            return None, None, msg
        
        start_dt = datetime.strptime(start_date, "%Y-%m-%d")
        end_dt = datetime.strptime(end_date, "%Y-%m-%d")
        
        # Fetch historical data
        historical_data = fetch_openpower_data(region, start_dt, end_dt)
        if historical_data is None:
            return None, None, "Error loading historical data"
        
        # Generate forecast
        forecast_values = generate_forecast_with_groq(historical_data, forecast_horizon)
        
        # Create plot
        fig = create_forecast_plot(historical_data, forecast_values if forecast_values else [])
        
        # Prepare forecast table
        forecast_df = None
        if forecast_values:
            forecast_df = pd.DataFrame({
                'Time': [historical_data['timestamp'].iloc[-1] + timedelta(hours=i+1) 
                        for i in range(len(forecast_values))],
                'Forecasted Load (MW)': forecast_values
            })
        
        return fig, forecast_df, ""
    
    except Exception as e:
        print(f"Error in run_forecast: {e}")
        return None, None, f"An error occurred: {str(e)}"

# Create Gradio interface
with gr.Blocks(css=custom_css) as demo:
    with gr.Column():
        gr.Markdown("""
        <div class="header">
            <h1>Smart Energy Load Forecasting</h1>
            <p>Predict future energy demand using AI and historical data</p>
        </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                region = gr.Dropdown(
                    label="Region",
                    choices=["North", "South", "East", "West", "Central"],
                    value="North"
                )
                start_date = gr.Textbox(
                    label="Start Date (YYYY-MM-DD)",
                    value=(datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"),
                    placeholder="YYYY-MM-DD"
                )
                end_date = gr.Textbox(
                    label="End Date (YYYY-MM-DD)",
                    value=datetime.now().strftime("%Y-%m-%d"),
                    placeholder="YYYY-MM-DD"
                )
                forecast_horizon = gr.Slider(
                    label="Forecast Horizon (hours)",
                    minimum=1,
                    maximum=48,
                    step=1,
                    value=24
                )
                submit_btn = gr.Button("Generate Forecast", variant="primary")
            
            with gr.Column(scale=2):
                plot_output = gr.Plot(label="Energy Load Forecast")
                forecast_table = gr.Dataframe(
                    label="Forecast Details",
                    headers=["Time", "Forecasted Load (MW)"],
                    interactive=False
                )
                error_output = gr.HTML()
        
        gr.Markdown("""
        <div class="footer">
            <p>Powered by Groq API and OpenPower data | Built with Gradio</p>
        </div>
        """)
    
    submit_btn.click(
        fn=run_forecast,
        inputs=[region, start_date, end_date, forecast_horizon],
        outputs=[plot_output, forecast_table, error_output]
    )

    # Add examples for quick testing
    examples = gr.Examples(
        examples=[
            ["North", (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"), 
             datetime.now().strftime("%Y-%m-%d"), 24],
            ["South", (datetime.now() - timedelta(days=14)).strftime("%Y-%m-%d"), 
             (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"), 12]
        ],
        inputs=[region, start_date, end_date, forecast_horizon],
        outputs=[plot_output, forecast_table, error_output],
        fn=run_forecast,
        cache_examples=False
    )

# Run the app
if __name__ == "__main__":
    demo.launch()