razaali10 commited on
Commit
a5ce6dd
Β·
verified Β·
1 Parent(s): 7e3a1d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -37
app.py CHANGED
@@ -1,67 +1,97 @@
1
- # app.py
2
  import gradio as gr
3
  import wntr
 
4
  import pandas as pd
5
  import plotly.graph_objects as go
6
- import tempfile
7
- import shutil
8
  import os
 
9
 
10
  def run_simulation(inp_file):
11
  try:
12
- # Save uploaded file to temp dir
13
- temp_dir = tempfile.mkdtemp()
14
- inp_path = os.path.join(temp_dir, "network.inp")
15
- shutil.copy(inp_file, inp_path)
16
 
 
 
 
 
17
  wn = wntr.network.WaterNetworkModel(inp_path)
18
  sim = wntr.sim.EpanetSimulator(wn)
19
  results = sim.run_sim()
20
 
21
- # Collect outputs
22
- outputs = []
23
- metrics = {
24
- "Node Pressure": (results.node["pressure"], "Pressure (m)"),
25
- "Tank Levels": (results.node["head"].loc[:, list(wn.tanks()):], "Level (m)"),
26
- "Node Demand": (results.node["demand"], "Demand (m3/s)"),
27
- "Link Flowrate": (results.link["flowrate"], "Flowrate (m3/s)")
 
 
 
 
 
 
 
 
 
28
  }
29
 
30
- for title, (df, ylabel) in metrics.items():
31
- csv_path = os.path.join(temp_dir, f"{title.replace(' ', '_')}.csv")
 
 
32
  df.to_csv(csv_path)
33
 
34
  fig = go.Figure()
35
- for col in df.columns[:5]: # Plot first 5 only for brevity
36
- fig.add_trace(go.Scatter(x=df.index/60, y=df[col], mode="lines", name=col))
37
- fig.update_layout(title=title, xaxis_title="Time (min)", yaxis_title=ylabel)
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- outputs.extend([csv_path, df.head(), fig])
 
 
 
 
40
 
41
- return outputs
42
 
43
  except Exception as e:
44
- return [str(e)] * 12
45
 
46
- # Input
47
- file_input = gr.File(label="Upload .inp file", file_types=[".inp"])
48
 
49
- # Outputs (4 metrics x [csv, table, plot])
50
- output_components = []
51
- for label in ["Node Pressure", "Tank Levels", "Node Demand", "Link Flowrate"]:
52
- output_components += [
53
- gr.File(label=f"{label} CSV"),
54
- gr.Dataframe(label=f"{label} Table (preview)"),
55
- gr.Plot(label=f"{label} Plot")
56
- ]
 
 
57
 
58
- # Interface
59
  demo = gr.Interface(
60
  fn=run_simulation,
61
- inputs=file_input,
62
- outputs=output_components,
63
- title="πŸ’§ EPANET WNTR Simulator",
64
- description="Upload a valid EPANET .inp file to simulate with WNTR and view results.",
65
  allow_flagging="never"
66
  )
67
 
 
 
1
  import gradio as gr
2
  import wntr
3
+ import tempfile
4
  import pandas as pd
5
  import plotly.graph_objects as go
 
 
6
  import os
7
+ import shutil
8
 
9
  def run_simulation(inp_file):
10
  try:
11
+ # Create temporary working directory
12
+ work_dir = tempfile.mkdtemp()
13
+ inp_path = os.path.join(work_dir, "network.inp")
 
14
 
15
+ # Save uploaded file to temp path
16
+ shutil.copy(inp_file.name, inp_path)
17
+
18
+ # Load and simulate the EPANET model
19
  wn = wntr.network.WaterNetworkModel(inp_path)
20
  sim = wntr.sim.EpanetSimulator(wn)
21
  results = sim.run_sim()
22
 
23
+ output_list = []
24
+
25
+ # Simulation result groups
26
+ simulation_groups = {
27
+ "Node Pressures": {
28
+ "data": results.node["pressure"],
29
+ "ylabel": "Pressure (m)"
30
+ },
31
+ "Tank Levels": {
32
+ "data": results.node["head"][[name for name, _ in wn.tanks()]],
33
+ "ylabel": "Tank Head (m)"
34
+ },
35
+ "Demands": {
36
+ "data": results.node["demand"],
37
+ "ylabel": "Demand (mΒ³/s)"
38
+ }
39
  }
40
 
41
+ # Append simulation group results
42
+ for title, group in simulation_groups.items():
43
+ df = group["data"]
44
+ csv_path = os.path.join(work_dir, f"{title.replace(' ', '_')}.csv")
45
  df.to_csv(csv_path)
46
 
47
  fig = go.Figure()
48
+ for col in df.columns:
49
+ fig.add_trace(go.Scatter(
50
+ x=df.index / 60, # seconds β†’ minutes
51
+ y=df[col],
52
+ mode="lines",
53
+ name=str(col)
54
+ ))
55
+ fig.update_layout(
56
+ title=title,
57
+ xaxis_title="Time (min)",
58
+ yaxis_title=group["ylabel"],
59
+ height=400
60
+ )
61
+
62
+ output_list.extend([csv_path, df.reset_index(), fig])
63
 
64
+ # Tank metadata
65
+ tank_data = [(name, tank.elevation, tank.min_level, tank.max_level, tank.diameter)
66
+ for name, tank in wn.tanks()]
67
+ df_tanks = pd.DataFrame(tank_data, columns=["Tank ID", "Elevation", "Min Level", "Max Level", "Diameter"])
68
+ output_list.append(df_tanks)
69
 
70
+ return tuple(output_list)
71
 
72
  except Exception as e:
73
+ return [f"❌ ERROR: {str(e)}"] + [None] * 9
74
 
75
+ # Gradio interface
76
+ input_file = gr.File(label="πŸ“ Upload .inp File", file_types=[".inp"])
77
 
78
+ outputs = [
79
+ # Node Pressures
80
+ gr.File(label="πŸ“₯ Pressure CSV"), gr.Dataframe(label="Pressure Table"), gr.Plot(label="Pressure Plot"),
81
+ # Tank Levels
82
+ gr.File(label="πŸ“₯ Tank Level CSV"), gr.Dataframe(label="Tank Level Table"), gr.Plot(label="Tank Level Plot"),
83
+ # Demands
84
+ gr.File(label="πŸ“₯ Demand CSV"), gr.Dataframe(label="Demand Table"), gr.Plot(label="Demand Plot"),
85
+ # Tank metadata table
86
+ gr.Dataframe(label="πŸ“Š Tank Metadata")
87
+ ]
88
 
 
89
  demo = gr.Interface(
90
  fn=run_simulation,
91
+ inputs=input_file,
92
+ outputs=outputs,
93
+ title="πŸ’§ EPANET Simulation Viewer (Gradio)",
94
+ description="Upload a valid EPANET `.inp` file. This app runs hydraulic simulation using WNTR and returns pressure, tank levels, demands, and tank properties.",
95
  allow_flagging="never"
96
  )
97