zainulabedin949's picture
Update app.py
ec55a6f verified
raw
history blame
9.46 kB
# app.py
import streamlit as st
import pandas as pd
import numpy as np
# Set page title and layout
st.set_page_config(page_title="Water System Analysis", layout="centered")
st.title("Water Network Leak, Surge, and Gas Flow Analyzer")
# Allow user to upload an Excel or CSV file
uploaded_file = st.file_uploader("Upload Excel or CSV File", type=["xlsx", "csv"])
if uploaded_file:
try:
# Read the uploaded file into a pandas DataFrame
if uploaded_file.name.endswith('.xlsx'):
df = pd.read_excel(uploaded_file)
else:
df = pd.read_csv(uploaded_file)
st.success("Data loaded successfully!")
except Exception as e:
st.error(f"Error reading the file: {e}")
st.stop()
# Detect if a "Serial Number" column exists (case-insensitive)
serial_col = None
for col in df.columns:
if col.strip().lower().startswith("serial"):
serial_col = col
break
# If serial number column is found, let user select one
if serial_col:
serial_list = df[serial_col].unique().tolist()
selected_serial = st.selectbox(f"Select {serial_col}", serial_list)
df_filtered = df[df[serial_col] == selected_serial]
if df_filtered.empty:
st.warning("No data found for the selected serial number.")
st.stop()
else:
# If no serial number column, use the entire dataset
df_filtered = df
selected_serial = None
# Let the user select which parameter (column) to analyze
# Exclude the serial column itself from selection
columns = [col for col in df_filtered.columns if col != serial_col]
selected_column = st.selectbox("Select a parameter to analyze", columns)
if selected_column:
# Retrieve the value(s) for the selected parameter
# If only one row is present, get the scalar; otherwise get list of values
if len(df_filtered) == 1:
value = df_filtered[selected_column].iloc[0]
else:
value = df_filtered[selected_column].tolist()
rec = "" # This will hold the recommendation string
# Leak detection (Water Pressure)
if "water pressure" in selected_column.lower():
# Compute mean pressure if multiple readings, else use the single value
if isinstance(value, list):
mean_val = np.mean(value)
else:
mean_val = value
# Apply simple threshold rules
if mean_val < 20:
rec = ("🚨 **Alert:** The water pressure is significantly low. "
"This suggests a strong likelihood of a leak or supply issue. "
"Inspect the pipeline and valves immediately. ")
elif mean_val < 40:
rec = ("⚠️ The water pressure is on the lower side. "
"There may be a leak or high demand. "
"Monitor the system closely and check for any anomalies. ")
elif mean_val > 80:
rec = ("⚠️ The water pressure is very high. "
"Ensure the pressure-regulating devices are functioning. "
"High pressure can stress the pipes. ")
else:
rec = ("βœ… The water pressure is within normal range. "
"No immediate issues detected for leaks based on pressure. ")
# Surge detection (Transient Pressure)
elif "transient pressure" in selected_column.lower():
# Use the highest transient pressure to check for spikes
if isinstance(value, list):
peak_val = np.max(value)
else:
peak_val = value
if peak_val > 60:
rec = ("🚨 **Alert:** Detected a high transient pressure (pressure surge). "
"This could indicate water hammer or sudden valve closure. "
"Check surge protection devices and ensure valves operate smoothly. ")
else:
rec = ("βœ… Transient pressure levels are within a safe range. "
"No significant pressure surges detected. ")
# Gas flow analysis
elif "gas flow" in selected_column.lower():
if isinstance(value, list):
mean_flow = np.mean(value)
else:
mean_flow = value
if mean_flow > 150:
rec = ("⚠️ Gas flow rate is high. "
"This could indicate heavy usage or a potential leak. "
"Check the gas lines and usage patterns. ")
elif mean_flow < 50:
rec = ("⚠️ Gas flow rate is very low. "
"Ensure that valves are open or that the demand is correct. "
"No gas might indicate a supply issue. ")
else:
rec = ("βœ… Gas flow rate is within normal operating range. "
"No obvious anomalies detected in gas flow. ")
# Network Design Type advice
elif "network design" in selected_column.lower():
design = str(df_filtered[selected_column].iloc[0]).strip().lower()
if "grid" in design:
rec = ("βœ… A grid network provides redundancy and reliability. "
"Ensure maintenance of all loops for continuous supply. ")
elif "radial" in design:
rec = ("⚠️ A radial network is simpler but has less redundancy. "
"A failure in a main line may isolate downstream areas. "
"Consider backup routes if possible. ")
elif "ring" in design or "loop" in design:
rec = ("βœ… A ring (loop) network allows for good circulation and redundancy. "
"Keep valves balanced to maintain pressure. ")
else:
rec = ("βœ… The network design type is noted. "
"Regular inspection ensures reliability. ")
# Population Density advice
elif "population density" in selected_column.lower():
val = df_filtered[selected_column].iloc[0]
if val > 1500:
rec = ("⚠️ High population density indicates heavy demand on the water network. "
"Ensure the infrastructure is scaled properly to serve the community. "
"Consider capacity upgrades or demand management programs. ")
elif val > 800:
rec = ("βœ… Population density is moderate. "
"Maintain regular monitoring to meet demand and plan for growth. ")
else:
rec = ("βœ… Low population density suggests light demand. "
"Focus on efficient resource allocation and cost-effective maintenance. ")
# Average Water Usage advice
elif "water usage" in selected_column.lower():
val = df_filtered[selected_column].iloc[0]
if val > 200:
rec = ("⚠️ Very high per-capita water usage detected. "
"Promote water conservation measures and check for leaks in consumption systems. ")
elif val > 120:
rec = ("βœ… Average water usage is within a moderate range. "
"Continue to encourage efficient use of water. ")
else:
rec = ("βœ… Water usage per person is low. "
"This is efficient, but ensure basic needs are met. ")
# Available Water Resources advice
elif "available water" in selected_column.lower():
val = df_filtered[selected_column].iloc[0]
if val < 80:
rec = ("⚠️ Limited available water resources. "
"Implement conservation strategies and consider alternative sources. ")
elif val > 150:
rec = ("βœ… Ample water resources are available. "
"Still practice sustainable usage to maintain supply levels. ")
else:
rec = ("βœ… Water resource levels are moderate. "
"Monitor usage rates to avoid shortages. ")
# Pipe Sizes advice
elif "pipe sizes" in selected_column.lower():
val = df_filtered[selected_column].iloc[0]
if val < 30:
rec = ("⚠️ Small pipe diameter detected. "
"This may limit flow capacity. "
"Check for potential bottlenecks in the network. ")
elif val > 40:
rec = ("βœ… Pipe size is large. "
"Adequate flow capacity is available. "
"Ensure regular inspections for longevity. ")
else:
rec = ("βœ… Standard pipe size. "
"Flow capacity is adequate for normal operation. ")
else:
# Default case if the column is unrecognized
rec = ("βœ… No specific recommendations for the selected parameter. "
"Data value is noted and appears within expected range. ")
# Display the recommendations
st.markdown(f"### Recommendations for **{selected_column}**")
st.write(rec)