razaali10 commited on
Commit
7b95039
·
verified ·
1 Parent(s): 4f34d0e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -32
app.py CHANGED
@@ -8,27 +8,28 @@ import io
8
  import os
9
  import base64
10
  import json
11
- from typing import Literal
12
 
13
  def simulate(inp_file, sim_type):
14
  try:
15
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
16
  tmp.write(inp_file)
17
- tmp.flush()
18
  tmp_path = tmp.name
19
 
20
  wn = wntr.network.WaterNetworkModel(tmp_path)
 
21
  if sim_type.upper() == "EPANET":
22
- sim = wntr.sim.EpanetSimulator(wn)
 
 
23
  else:
24
  sim = wntr.sim.WNTRSimulator(wn)
 
25
  results = sim.run_sim()
26
  pressure = results.node["pressure"].mean().to_dict()
27
  demand = results.node["demand"].mean().to_dict()
28
  pressure_summary = "\n".join(f"{k}: {v:.2f} m" for k, v in pressure.items())
29
  demand_summary = "\n".join(f"{k}: {v:.2f} L/s" for k, v in demand.items())
30
 
31
- os.remove(tmp_path)
32
  return pressure_summary, demand_summary
33
  except Exception:
34
  return f"Simulation error:\n{traceback.format_exc()}", ""
@@ -37,10 +38,9 @@ def simulate_disaster(inp_file, failure_element, failure_type):
37
  try:
38
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
39
  tmp.write(inp_file)
40
- tmp.flush()
41
- tmp_path = tmp.name
42
 
43
- wn = wntr.network.WaterNetworkModel(tmp_path)
44
  if failure_type == "pipe_break":
45
  wn = wntr.morph.split_pipe(wn, failure_element)
46
  elif failure_type == "node_closure":
@@ -51,7 +51,6 @@ def simulate_disaster(inp_file, failure_element, failure_type):
51
  demand = results.node["demand"].mean().to_dict()
52
  pressure_summary = "\n".join(f"{k}: {v:.2f} m" for k, v in pressure.items())
53
  demand_summary = "\n".join(f"{k}: {v:.2f} L/s" for k, v in demand.items())
54
- os.remove(tmp_path)
55
  return pressure_summary, demand_summary
56
  except Exception as e:
57
  return f"Disaster simulation error: {str(e)}", ""
@@ -60,10 +59,9 @@ def simulate_quality(inp_file, quality_type, trace_node):
60
  try:
61
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
62
  tmp.write(inp_file)
63
- tmp.flush()
64
- tmp_path = tmp.name
65
 
66
- wn = wntr.network.WaterNetworkModel(tmp_path)
67
  wn.options.quality.mode = quality_type
68
  if quality_type == "trace" and trace_node:
69
  wn.options.quality.trace_node = trace_node
@@ -71,7 +69,6 @@ def simulate_quality(inp_file, quality_type, trace_node):
71
  results = sim.run_sim()
72
  quality = results.node["quality"].mean().to_dict()
73
  summary = "\n".join(f"{k}: {v:.2f}" for k, v in quality.items())
74
- os.remove(tmp_path)
75
  return summary
76
  except Exception as e:
77
  return f"Quality simulation error: {str(e)}"
@@ -98,16 +95,14 @@ def simulate_economic_loss(inp_file):
98
  try:
99
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
100
  tmp.write(inp_file)
101
- tmp.flush()
102
- tmp_path = tmp.name
103
 
104
- wn = wntr.network.WaterNetworkModel(tmp_path)
105
  sim = wntr.sim.WNTRSimulator(wn)
106
  results = sim.run_sim()
107
  node_demand = results.node["demand"].mean()
108
  loss_by_node = (1.0 - node_demand / node_demand.max()) * 100
109
  total_loss = loss_by_node.sum()
110
- os.remove(tmp_path)
111
  return f"Total economic loss: {total_loss:.2f}%"
112
  except Exception as e:
113
  return f"Economic loss error: {str(e)}"
@@ -116,19 +111,17 @@ def simulate_criticality(inp_file):
116
  try:
117
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
118
  tmp.write(inp_file)
119
- tmp.flush()
120
- tmp_path = tmp.name
121
 
122
- wn = wntr.network.WaterNetworkModel(tmp_path)
123
  results = {}
124
  for pipe in wn.pipe_name_list[:5]:
125
- wn_temp = wntr.network.WaterNetworkModel(tmp_path)
126
  wn_temp.get_link(pipe).status = "CLOSED"
127
  sim = wntr.sim.WNTRSimulator(wn_temp)
128
  res = sim.run_sim()
129
  demand = res.node["demand"].mean().sum()
130
  results[pipe] = round(demand, 3)
131
- os.remove(tmp_path)
132
  return json.dumps(results, indent=2)
133
  except Exception as e:
134
  return f"Criticality error: {str(e)}"
@@ -137,10 +130,9 @@ def plot_network(inp_file):
137
  try:
138
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
139
  tmp.write(inp_file)
140
- tmp.flush()
141
- tmp_path = tmp.name
142
 
143
- wn = wntr.network.WaterNetworkModel(tmp_path)
144
  fig = plt.figure()
145
  wn.draw_network()
146
  buf = io.BytesIO()
@@ -148,14 +140,11 @@ def plot_network(inp_file):
148
  buf.seek(0)
149
  image_data = base64.b64encode(buf.read()).decode("utf-8")
150
  plt.close(fig)
151
- os.remove(tmp_path)
152
  return f"data:image/png;base64,{image_data}"
153
  except Exception as e:
154
  return f"Plot error: {str(e)}"
155
 
156
- grb = gr.Blocks()
157
-
158
- with grb:
159
  gr.Markdown("# 💧 WNTR Simulation & Analysis Tool")
160
  with gr.Tab("Simulate"):
161
  file_input = gr.File(label="Upload .inp File", type="binary")
@@ -163,30 +152,35 @@ with grb:
163
  pressure_output = gr.Textbox(label="Pressure Summary")
164
  demand_output = gr.Textbox(label="Demand Summary")
165
  gr.Button("Run Simulation").click(simulate, inputs=[file_input, sim_type], outputs=[pressure_output, demand_output])
 
166
  with gr.Tab("Disaster"):
167
- failure_element = gr.Textbox(label="Element (e.g., pipe ID)")
168
  failure_type = gr.Dropdown(["pipe_break", "node_closure"], label="Failure Type")
169
  d_pressure = gr.Textbox(label="Pressure")
170
  d_demand = gr.Textbox(label="Demand")
171
  gr.Button("Simulate Disaster").click(simulate_disaster, inputs=[file_input, failure_element, failure_type], outputs=[d_pressure, d_demand])
 
172
  with gr.Tab("Water Quality"):
173
  quality_type = gr.Dropdown(["AGE", "CHEM", "trace"], label="Quality Type")
174
- trace_node = gr.Textbox(label="Trace Node (for trace mode only)")
175
  quality_output = gr.Textbox(label="Water Quality Result")
176
  gr.Button("Simulate Water Quality").click(simulate_quality, inputs=[file_input, quality_type, trace_node], outputs=quality_output)
 
177
  with gr.Tab("Analysis"):
178
  analysis_type = gr.Dropdown(["Resilience", "Morphology"], label="Analysis Type")
179
  analysis_output = gr.Textbox(label="Analysis Result")
180
  gr.Button("Analyze").click(analyze_results, inputs=[analysis_type, pressure_output, demand_output], outputs=analysis_output)
 
181
  with gr.Tab("Economic Loss"):
182
  econ_output = gr.Textbox(label="Economic Loss Summary")
183
  gr.Button("Compute Economic Loss").click(simulate_economic_loss, inputs=file_input, outputs=econ_output)
 
184
  with gr.Tab("Criticality"):
185
  critical_output = gr.Textbox(label="Criticality Result")
186
  gr.Button("Run Criticality Assessment").click(simulate_criticality, inputs=file_input, outputs=critical_output)
 
187
  with gr.Tab("Network Plot"):
188
  net_plot = gr.Image(label="Network Diagram")
189
  gr.Button("Plot Network").click(plot_network, inputs=file_input, outputs=net_plot)
190
 
191
- if __name__ == "__main__":
192
- grb.launch(server_name="0.0.0.0", server_port=7860)
 
8
  import os
9
  import base64
10
  import json
 
11
 
12
  def simulate(inp_file, sim_type):
13
  try:
14
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
15
  tmp.write(inp_file)
 
16
  tmp_path = tmp.name
17
 
18
  wn = wntr.network.WaterNetworkModel(tmp_path)
19
+
20
  if sim_type.upper() == "EPANET":
21
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as f_out:
22
+ sim = wntr.sim.EpanetSimulator(wn)
23
+ sim._inpfile = f_out.name
24
  else:
25
  sim = wntr.sim.WNTRSimulator(wn)
26
+
27
  results = sim.run_sim()
28
  pressure = results.node["pressure"].mean().to_dict()
29
  demand = results.node["demand"].mean().to_dict()
30
  pressure_summary = "\n".join(f"{k}: {v:.2f} m" for k, v in pressure.items())
31
  demand_summary = "\n".join(f"{k}: {v:.2f} L/s" for k, v in demand.items())
32
 
 
33
  return pressure_summary, demand_summary
34
  except Exception:
35
  return f"Simulation error:\n{traceback.format_exc()}", ""
 
38
  try:
39
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
40
  tmp.write(inp_file)
41
+ path = tmp.name
 
42
 
43
+ wn = wntr.network.WaterNetworkModel(path)
44
  if failure_type == "pipe_break":
45
  wn = wntr.morph.split_pipe(wn, failure_element)
46
  elif failure_type == "node_closure":
 
51
  demand = results.node["demand"].mean().to_dict()
52
  pressure_summary = "\n".join(f"{k}: {v:.2f} m" for k, v in pressure.items())
53
  demand_summary = "\n".join(f"{k}: {v:.2f} L/s" for k, v in demand.items())
 
54
  return pressure_summary, demand_summary
55
  except Exception as e:
56
  return f"Disaster simulation error: {str(e)}", ""
 
59
  try:
60
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
61
  tmp.write(inp_file)
62
+ path = tmp.name
 
63
 
64
+ wn = wntr.network.WaterNetworkModel(path)
65
  wn.options.quality.mode = quality_type
66
  if quality_type == "trace" and trace_node:
67
  wn.options.quality.trace_node = trace_node
 
69
  results = sim.run_sim()
70
  quality = results.node["quality"].mean().to_dict()
71
  summary = "\n".join(f"{k}: {v:.2f}" for k, v in quality.items())
 
72
  return summary
73
  except Exception as e:
74
  return f"Quality simulation error: {str(e)}"
 
95
  try:
96
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
97
  tmp.write(inp_file)
98
+ path = tmp.name
 
99
 
100
+ wn = wntr.network.WaterNetworkModel(path)
101
  sim = wntr.sim.WNTRSimulator(wn)
102
  results = sim.run_sim()
103
  node_demand = results.node["demand"].mean()
104
  loss_by_node = (1.0 - node_demand / node_demand.max()) * 100
105
  total_loss = loss_by_node.sum()
 
106
  return f"Total economic loss: {total_loss:.2f}%"
107
  except Exception as e:
108
  return f"Economic loss error: {str(e)}"
 
111
  try:
112
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
113
  tmp.write(inp_file)
114
+ path = tmp.name
 
115
 
116
+ wn = wntr.network.WaterNetworkModel(path)
117
  results = {}
118
  for pipe in wn.pipe_name_list[:5]:
119
+ wn_temp = wntr.network.WaterNetworkModel(path)
120
  wn_temp.get_link(pipe).status = "CLOSED"
121
  sim = wntr.sim.WNTRSimulator(wn_temp)
122
  res = sim.run_sim()
123
  demand = res.node["demand"].mean().sum()
124
  results[pipe] = round(demand, 3)
 
125
  return json.dumps(results, indent=2)
126
  except Exception as e:
127
  return f"Criticality error: {str(e)}"
 
130
  try:
131
  with tempfile.NamedTemporaryFile(delete=False, suffix=".inp") as tmp:
132
  tmp.write(inp_file)
133
+ path = tmp.name
 
134
 
135
+ wn = wntr.network.WaterNetworkModel(path)
136
  fig = plt.figure()
137
  wn.draw_network()
138
  buf = io.BytesIO()
 
140
  buf.seek(0)
141
  image_data = base64.b64encode(buf.read()).decode("utf-8")
142
  plt.close(fig)
 
143
  return f"data:image/png;base64,{image_data}"
144
  except Exception as e:
145
  return f"Plot error: {str(e)}"
146
 
147
+ with gr.Blocks() as demo:
 
 
148
  gr.Markdown("# 💧 WNTR Simulation & Analysis Tool")
149
  with gr.Tab("Simulate"):
150
  file_input = gr.File(label="Upload .inp File", type="binary")
 
152
  pressure_output = gr.Textbox(label="Pressure Summary")
153
  demand_output = gr.Textbox(label="Demand Summary")
154
  gr.Button("Run Simulation").click(simulate, inputs=[file_input, sim_type], outputs=[pressure_output, demand_output])
155
+
156
  with gr.Tab("Disaster"):
157
+ failure_element = gr.Textbox(label="Element ID")
158
  failure_type = gr.Dropdown(["pipe_break", "node_closure"], label="Failure Type")
159
  d_pressure = gr.Textbox(label="Pressure")
160
  d_demand = gr.Textbox(label="Demand")
161
  gr.Button("Simulate Disaster").click(simulate_disaster, inputs=[file_input, failure_element, failure_type], outputs=[d_pressure, d_demand])
162
+
163
  with gr.Tab("Water Quality"):
164
  quality_type = gr.Dropdown(["AGE", "CHEM", "trace"], label="Quality Type")
165
+ trace_node = gr.Textbox(label="Trace Node")
166
  quality_output = gr.Textbox(label="Water Quality Result")
167
  gr.Button("Simulate Water Quality").click(simulate_quality, inputs=[file_input, quality_type, trace_node], outputs=quality_output)
168
+
169
  with gr.Tab("Analysis"):
170
  analysis_type = gr.Dropdown(["Resilience", "Morphology"], label="Analysis Type")
171
  analysis_output = gr.Textbox(label="Analysis Result")
172
  gr.Button("Analyze").click(analyze_results, inputs=[analysis_type, pressure_output, demand_output], outputs=analysis_output)
173
+
174
  with gr.Tab("Economic Loss"):
175
  econ_output = gr.Textbox(label="Economic Loss Summary")
176
  gr.Button("Compute Economic Loss").click(simulate_economic_loss, inputs=file_input, outputs=econ_output)
177
+
178
  with gr.Tab("Criticality"):
179
  critical_output = gr.Textbox(label="Criticality Result")
180
  gr.Button("Run Criticality Assessment").click(simulate_criticality, inputs=file_input, outputs=critical_output)
181
+
182
  with gr.Tab("Network Plot"):
183
  net_plot = gr.Image(label="Network Diagram")
184
  gr.Button("Plot Network").click(plot_network, inputs=file_input, outputs=net_plot)
185
 
186
+ demo.launch(server_name="0.0.0.0", server_port=7860)