CoolFace
Apppublic

arsalan36/load-profiling

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
app.py102 linesDownload Raw Back to root
1import gradio as gr2import pandas as pd3import numpy as np4import matplotlib.pyplot as plt5from sklearn.linear_model import LinearRegression6from sklearn.metrics import mean_absolute_error, r2_score7from datetime import datetime, timedelta8 9# -----------------------------10# 1️⃣  Generate or Load Data11# -----------------------------12def generate_sample_data():13    np.random.seed(42)14    base_date = datetime.now() - timedelta(days=30)15    data = []16    for i in range(30):17        date = base_date + timedelta(days=i)18        # Simulate industrial load in MW19        load = 80 + 10 * np.sin(i / 5) + np.random.uniform(-3, 3)20        data.append([date, load])21    df = pd.DataFrame(data, columns=["Date", "Load(MW)"])22    return df23 24# -----------------------------25# 2️⃣  Forecasting Function26# -----------------------------27def forecast_load(data):28    if data is None:29        df = generate_sample_data()30    else:31        df = pd.read_csv(data.name)32 33    df['Date'] = pd.to_datetime(df['Date'])34    df['Day'] = np.arange(len(df))35    36    model = LinearRegression()37    model.fit(df[['Day']], df['Load(MW)'])38    39    # Predict next 7 days40    future_days = np.arange(len(df), len(df)+7)41    predictions = model.predict(future_days.reshape(-1, 1))42    43    future_dates = [df['Date'].iloc[-1] + timedelta(days=i+1) for i in range(7)]44    forecast_df = pd.DataFrame({45        "Date": future_dates,46        "Forecasted Load(MW)": predictions47    })48    49    mae = mean_absolute_error(df['Load(MW)'], model.predict(df[['Day']]))50    r2 = r2_score(df['Load(MW)'], model.predict(df[['Day']]))51    52    # -----------------------------53    # Plot Load Curve54    # -----------------------------55    plt.figure(figsize=(8, 4))56    plt.plot(df['Date'], df['Load(MW)'], label="Actual Load", color='blue')57    plt.plot(forecast_df['Date'], forecast_df['Forecasted Load(MW)'], label="Forecast", color='orange', linestyle='--')58    plt.title("Industrial Load Curve Profiling (Daily)")59    plt.xlabel("Date")60    plt.ylabel("Load (MW)")61    plt.legend()62    plt.grid(True)63    64    plt.tight_layout()65    plt.savefig("load_curve.png")66    plt.close()67 68    # -----------------------------69    # DMS Strategy Recommendation70    # -----------------------------71    strategy = "AI DMS Strategy:\n"72    avg_load = df['Load(MW)'].mean()73    max_load = df['Load(MW)'].max()74    75    if max_load > avg_load * 1.15:76        strategy += "- Peak shaving is recommended.\n"77    if avg_load < max_load * 0.85:78        strategy += "- Encourage load shifting to balance demand.\n"79    strategy += "- Apply predictive control for transformer tap changers.\n"80    strategy += "- Schedule maintenance during low-load periods.\n"81 82    return forecast_df, "load_curve.png", f"Model MAE: {mae:.2f}, R²: {r2:.2f}\n\n{strategy}"83 84# -----------------------------85# 3️⃣  Build Gradio UI86# -----------------------------87with gr.Blocks(title="AI Load Forecasting and DMS System") as demo:88    gr.Markdown("## ⚡ Industrial Load Forecasting & DMS Strategy (AI-Based)")89    gr.Markdown("Upload your CSV file with columns: `Date, Load(MW)` or leave empty to use sample data.")90    91    data_input = gr.File(label="Upload Daily/Weekly Load Data (CSV)", file_types=[".csv"])92    forecast_button = gr.Button("Run Forecast")93    94    forecast_output = gr.Dataframe(label="📊 Forecasted Load (Next 7 Days)")95    image_output = gr.Image(label="Load Curve Profile")96    text_output = gr.Textbox(label="AI Analysis & DMS Strategy")97 98    forecast_button.click(forecast_load, inputs=[data_input], outputs=[forecast_output, image_output, text_output])99 100# Run app101demo.launch()102