hareshchander's picture
Update app.py
befe14f verified
Raw History Blame Contribute Delete
2.28 kB
import gradio as gr
from pyomo.environ import *
def optimize_dispatch(solar, wind, grid, load):
total_capacity = solar + wind + grid
if load > total_capacity:
return {"error": "Load exceeds total available capacity!"}
sources = {
"solar": {"max": solar, "cost": 0},
"wind": {"max": wind, "cost": 0},
"grid": {"max": grid, "cost": 5}
}
model = ConcreteModel()
model.sources = Set(initialize=sources.keys())
model.P = Var(model.sources, bounds=(0, None))
# Objective: minimize cost
model.cost = Objective(expr=sum(sources[s]['cost'] * model.P[s] for s in model.sources), sense=minimize)
# Load balance constraint
model.balance = Constraint(expr=sum(model.P[s] for s in model.sources) == load)
# Capacity constraints per source
model.capacity = ConstraintList()
for s in sources:
model.capacity.add(model.P[s] <= sources[s]['max'])
solver = SolverFactory('glpk')
result = solver.solve(model)
if (result.solver.status != SolverStatus.ok) or (result.solver.termination_condition != TerminationCondition.optimal):
return {"error": "Solver failed to find an optimal solution."}
dispatch = {s: round(model.P[s](), 2) for s in sources}
return dispatch
def ui(solar, wind, grid, load):
try:
output = optimize_dispatch(solar, wind, grid, load)
if isinstance(output, dict) and "error" in output:
return f"Error: {output['error']}", ""
explanation = f"Optimized dispatch: {output}. Priority given to renewables (zero cost), rest from grid."
return str(output), explanation
except Exception as e:
return f"Unexpected Error: {str(e)}", ""
demo = gr.Interface(
fn=ui,
inputs=[
gr.Slider(0, 100, step=1, label="Solar Capacity (MW)"),
gr.Slider(0, 100, step=1, label="Wind Capacity (MW)"),
gr.Slider(0, 200, step=1, label="Grid Capacity (MW)"),
gr.Slider(0, 300, step=1, label="Total Load (MW)")
],
outputs=["text", "text"],
title="Renewable Integration Optimization Assistant",
description="Enter available renewable sources, grid limits, and total load to receive optimized dispatch output."
)
if __name__ == "__main__":
demo.launch()