import importlib
import sys
# Force reload of all modules
for mod in ['simulation.mccabe_thiele', 'simulation.thermodynamics',
'simulation.distillation_model', 'optimization.surrogate_model',
'optimization.optimizer', 'utils.pdf_generator']:
if mod in sys.modules:
del sys.modules[mod]
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import torch
import joblib
import os
import sys
import io
import base64
import time
from datetime import datetime
def pdf_download_button(buffer, filename, button_text):
buffer.seek(0)
b64 = base64.b64encode(buffer.read()).decode()
href = f''
href += f''
st.markdown(href, unsafe_allow_html=True)
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from simulation.distillation_model import DistillationColumn
from simulation.mccabe_thiele import McCabeThiele
from simulation.thermodynamics import Thermodynamics, SYSTEMS, get_system_list
from optimization.surrogate_model import DistillationSurrogate, train_model
from optimization.optimizer import DistillationOptimizer
try:
import torch
import optuna
AI_AVAILABLE = True
except ImportError:
AI_AVAILABLE = False
st.warning("β οΈ PyTorch/Optuna not available. Running in lightweight mode.")
# ==================== PAGE CONFIG ====================
st.set_page_config(
page_title="DistilAI Pro - Industrial Distillation Suite",
page_icon="βοΈ",
layout="wide",
initial_sidebar_state="expanded"
)
# ==================== CUSTOM CSS ====================
st.markdown("""
""", unsafe_allow_html=True)
# ==================== SESSION STATE ====================
defaults = {
'trained_model': False, 'current_system': 'benzene-toluene',
'simulation_results': None, 'optimization_results': None,
'mccabe_data': None, 'uploaded_data': None, 'monitor_data': [],
'monitoring': False, 'industrial_data': None,
'use_industrial': False
}
for key, val in defaults.items():
if key not in st.session_state:
st.session_state[key] = val
# ==================== SIDEBAR ====================
with st.sidebar:
st.markdown("""
βοΈ DistilAI
Industrial Distillation Suite
""", unsafe_allow_html=True)
st.markdown("---")
page = st.radio("Navigation",
["π Home", "π System Database", "π¬ Thermodynamics", "π McCabe-Thiele",
"π§ Process Simulation", "π€ AI Optimization", "π€ Industrial Data Upload", "π‘ Live Monitor"],
label_visibility="collapsed")
st.markdown("---")
st.markdown("### βοΈ Active System")
# Build system options with industrial data at top if available
physical_systems = list(SYSTEMS.keys())
system_labels = {}
for name in physical_systems:
info = SYSTEMS[name]
badge = "AZEOTROPE" if "azeotrope" in info['description'].lower() else "IDEAL" if info['model'] == 'ideal' else "NON-IDEAL"
system_labels[name] = f"{name.replace('-', ' ').title()} [{badge}]"
industrial_key = 'industrial-custom'
has_industrial = st.session_state.industrial_data is not None
if has_industrial:
df = st.session_state.industrial_data
n_points = len(df)
system_labels[industrial_key] = f"π Plant Data ({n_points} points) [EMPIRICAL]"
all_options = [industrial_key] + physical_systems
else:
all_options = physical_systems
# Determine current selection
current = st.session_state.current_system
if current not in all_options:
current = all_options[0]
selected_label = st.selectbox(
"Select System",
[system_labels[k] for k in all_options],
index=all_options.index(current),
label_visibility="collapsed"
)
# Map back to key
selected_key = None
for k, v in system_labels.items():
if v == selected_label:
selected_key = k
break
# Update state
if selected_key == industrial_key:
st.session_state.use_industrial = True
st.session_state.current_system = industrial_key
df = st.session_state.industrial_data
st.markdown(f"""
π PLANT DATA
{len(df)} operating points loaded
KNN surrogate model active
")
# ==================== HELPERS ====================
def get_active_column():
if st.session_state.use_industrial and st.session_state.industrial_data is not None:
return DistillationColumn(system='industrial-custom', industrial_data=st.session_state.industrial_data)
return DistillationColumn(system=st.session_state.current_system)
def show_empirical_banner():
if st.session_state.use_industrial:
st.markdown("""
π Empirical Mode Active
Using KNN surrogate trained from plant data. Physical properties are approximate.
""", unsafe_allow_html=True)
# ==================== HOME ====================
if page == "π Home":
st.markdown('
""", unsafe_allow_html=True)
st.markdown(" ", unsafe_allow_html=True)
st.markdown("### π― Platform Capabilities")
feat_cols = st.columns(3)
features = [
("π System Database", "8+ pre-loaded chemical systems + your uploaded plant data with real thermodynamic data", "667eea"),
("π McCabe-Thiele", "Interactive graphical stage design with empirical VLE from plant data or rigorous thermodynamics", "764ba2"),
("π€ AI Optimization", "Neural network surrogate models with Bayesian optimization for minimum energy consumption", "f093fb"),
("π¬ Thermodynamics", "Real VLE calculations using Antoine equation, Wilson/NRTL models, and rigorous enthalpy balances", "10b981"),
("π€ Industrial Upload", "Upload your plant CSV data, build empirical models, and optimize your actual process", "f59e0b"),
("π‘ Live Monitor", "Real-time trending with configurable alarm limits for purity, duty, and temperature", "ef4444")
]
for i, (title, desc, color) in enumerate(features):
with feat_cols[i % 3]:
st.markdown(f"""
{title}
{desc}
""", unsafe_allow_html=True)
# ==================== SYSTEM DATABASE ====================
elif page == "π System Database":
st.markdown('
π Chemical System Database
', unsafe_allow_html=True)
if st.session_state.industrial_data is not None:
st.markdown("### π Your Uploaded Plant Data")
with st.expander("**π Plant Data (Custom)** EMPIRICAL", expanded=True):
cols = st.columns([2, 1])
with cols[0]:
df = st.session_state.industrial_data
st.markdown(f"**{len(df)}** operating points loaded")
st.markdown(f"**Columns:** {', '.join(df.columns.tolist())}")
st.markdown("**Statistics:**")
st.dataframe(df.describe().round(3), use_container_width=True)
st.markdown("**Data Preview:**")
st.dataframe(df.head(10), use_container_width=True, height=250)
with cols[1]:
st.markdown("### π Distributions")
fig = make_subplots(rows=2, cols=2, subplot_titles=('Reflux Ratio', 'Feed Rate', 'Feed Composition', 'Reboiler Duty'))
for idx, col in enumerate(['reflux_ratio', 'feed_rate', 'feed_composition', 'reboiler_duty']):
row, col_idx = idx // 2 + 1, idx % 2 + 1
fig.add_trace(go.Histogram(x=df[col], name=col, showlegend=False, marker_color='#667eea'), row=row, col=col_idx)
fig.update_layout(height=400, template='plotly_white')
st.plotly_chart(fig, use_container_width=True)
if 'top_purity' in df.columns and 'bottom_purity' in df.columns:
alphas = []
for _, row in df.iterrows():
xd, xb = row['top_purity'], row['bottom_purity']
if xd > xb and xb > 0.01 and xd < 0.99:
try:
alpha = (xd/(1-xd) / (xb/(1-xb))) ** (1/20)
if 1 < alpha < 50: alphas.append(alpha)
except: pass
if alphas: st.metric("Est. Relative Volatility", f"{np.median(alphas):.2f}")
st.markdown("---")
st.markdown("### Pre-loaded Physical Systems")
for name, info in SYSTEMS.items():
is_azeo = "azeotrope" in info['description'].lower()
badge = "AZEOTROPE" if is_azeo else "IDEAL" if info['model'] == 'ideal' else "NON-IDEAL"
badge_color = "#ef4444" if is_azeo else "#10b981" if info['model'] == 'ideal' else "#f59e0b"
with st.expander(f"**{name.replace('-', ' ').title()}** {badge}", expanded=False):
cols = st.columns([2, 1])
with cols[0]:
components = info['components']()
st.markdown("**Components:**")
for comp in components:
st.markdown(f"
", unsafe_allow_html=True)
st.markdown("### π Additional Data")
acols = st.columns(3)
with acols[0]: st.metric("Distillate", f"{r['distillate_rate']:.1f} mol/hr")
with acols[1]: st.metric("Bottoms", f"{r['bottoms_rate']:.1f} mol/hr")
with acols[2]: st.metric("Ξ± (Rel. Vol.)", f"{r['relative_volatility']:.2f}")
if not r.get('empirical_mode') and 'gilliland_efficiency' in r:
with st.expander("π Design Details"):
st.markdown(f"**Gilliland Efficiency:** {r['gilliland_efficiency']:.3f}")
st.markdown(f"**Stage Efficiency:** {r['stage_efficiency']:.2f}")
st.markdown(f"**Actual Stages (eff. adjusted):** {r['n_stages'] * r['stage_efficiency']:.1f}")
st.markdown("### π‘οΈ Temperature Profile")
t_df = pd.DataFrame({'Location': ['Top', 'Feed', 'Bottom'], 'Temperature (Β°C)': [r['top_temperature'], r['feed_temperature'], r['bottom_temperature']]})
fig = px.bar(t_df, x='Location', y='Temperature (Β°C)', color='Temperature (Β°C)', color_continuous_scale='RdYlBu_r', text='Temperature (Β°C)')
fig.update_traces(texttemplate='%{text:.1f}', textposition='outside')
st.plotly_chart(fig, use_container_width=True)
st.markdown("---")
st.markdown("### π Export Report")
if st.button("π Generate PDF Report", key="sim_pdf", type="secondary", use_container_width=True):
with st.spinner("Generating PDF..."):
try:
from utils.pdf_generator import PDFReportGenerator
pdf_gen = PDFReportGenerator()
inputs = st.session_state.get('simulation_inputs', {'n_stages': 20, 'feed_stage': 10, 'pressure': 101.325, 'rr': rr, 'fr': fr, 'fc': fc})
buffer, filename = pdf_gen.generate_simulation_report(system, inputs, r)
pdf_download_button(buffer, filename, "Download Simulation Report")
except Exception as e:
st.error(f"PDF Error: {str(e)}")
else:
st.info("Click 'Run Simulation' to see results")
# ==================== AI OPTIMIZATION ====================
elif page == "π€ AI Optimization":
st.markdown('
π€ AI-Powered Optimization
', unsafe_allow_html=True)
show_empirical_banner()
# ==================== KEY FIX: Check if industrial data is active ====================
if st.session_state.use_industrial and st.session_state.industrial_data is not None:
# EMPRICAL MODE: Use plant data directly for optimization
st.markdown("""
π Using plant data for optimization (no neural network needed)
""", unsafe_allow_html=True)
if uploaded is not None:
try:
df = pd.read_csv(uploaded)
st.success(f"β {len(df):,} rows Γ {len(df.columns)} cols")
expected = ['reflux_ratio', 'feed_rate', 'feed_composition', 'top_purity', 'bottom_purity', 'reboiler_duty', 'condenser_duty']
mapping = {}
for exp in expected:
mapping[exp] = st.selectbox(exp, df.columns, index=df.columns.tolist().index(exp) if exp in df.columns else 0, key=f"map_{exp}")
df_mapped = df.rename(columns={v: k for k, v in mapping.items()})
st.session_state.industrial_data = df_mapped
if st.button("πΎ Save & Use", type="primary", use_container_width=True):
os.makedirs('data', exist_ok=True)
df_mapped.to_csv('data/industrial_data.csv', index=False)
st.session_state.use_industrial = True
st.session_state.current_system = 'industrial-custom'
st.success("β Data saved! Now select 'π Plant Data' from the sidebar dropdown.")
st.markdown("""
β Ready! Your plant data is now available in the system selector.
Go to any tab and select "π Plant Data" from the sidebar dropdown.
""")
st.balloons()
except Exception as e:
st.error(f"β Error: {str(e)}")
with col_preview:
if st.session_state.industrial_data is not None:
st.markdown("### ποΈ Data Preview")
st.dataframe(st.session_state.industrial_data.head(15), use_container_width=True, height=300)
st.markdown("### π Statistics")
st.dataframe(st.session_state.industrial_data.describe(), use_container_width=True)
st.markdown("### π Distributions")
fig = make_subplots(rows=2, cols=2, subplot_titles=('Reflux Ratio', 'Feed Rate', 'Feed Composition', 'Reboiler Duty'))
for idx, col in enumerate(['reflux_ratio', 'feed_rate', 'feed_composition', 'reboiler_duty']):
row, col_idx = idx // 2 + 1, idx % 2 + 1
fig.add_trace(go.Histogram(x=st.session_state.industrial_data[col], name=col, showlegend=False), row=row, col=col_idx)
fig.update_layout(height=500, template='plotly_white')
st.plotly_chart(fig, use_container_width=True)
st.markdown("---")
st.markdown('
π€ Train AI on Industrial Data
', unsafe_allow_html=True)
if st.session_state.industrial_data is not None or uploaded is not None:
train_cols = st.columns([1, 1, 1, 2])
with train_cols[0]: epochs = st.number_input("Epochs", 10, 500, 100, 10)
with train_cols[1]: hidden = st.selectbox("Hidden", ["[64,128]", "[128,256]", "[256,512]"], index=1)
with train_cols[2]: lr = st.selectbox("LR", [0.001, 0.0001], index=0)
with train_cols[3]:
if st.button("π Train AI Model", type="primary", use_container_width=True):
with st.spinner("Training neural network..."):
progress = st.progress(0)
df_train = st.session_state.industrial_data if st.session_state.industrial_data is not None else pd.read_csv(uploaded)
df_train.to_csv('data/train_temp.csv', index=False)
for i in range(5):
time.sleep(0.3)
progress.progress((i+1)*20)
train_model('data/train_temp.csv', epochs=epochs)
st.session_state.trained_model = True
progress.progress(100)
st.success("β AI Model Trained Successfully!")
st.balloons()
st.markdown("
β Model saved to models/surrogate_model.pth β Scalers saved to models/ β Ready for optimization in \"AI Optimization\" tab
", unsafe_allow_html=True)
else:
st.info("π Upload data first to enable training")
# ==================== LIVE MONITOR ====================
elif page == "π‘ Live Monitor":
st.markdown('