kaushik7425/Cable_Optimization
0
1import streamlit as st
2import pandas as pd
3import seaborn as sns
4import matplotlib.pyplot as plt
5import numpy as np
6
7from sklearn.linear_model import ElasticNet, Ridge, LinearRegression
8from sklearn.model_selection import train_test_split, GridSearchCV
9from sklearn.metrics import r2_score
10
11st.set_page_config(layout="wide")
12
13# ================= LOAD DATA =================
14@st.cache_data
15def load_data():
16 df = pd.read_csv("cabeldata.csv")
17 df.columns = [c.strip() for c in df.columns]
18 return df
19
20df = load_data()
21target = "Simulated Capacitance(pF) for 4.2ft"
22
23numeric_cols = df.select_dtypes(include="number").columns.tolist()
24numeric_cols.remove(target)
25
26# ================= SIDEBAR =================
27st.sidebar.title("Model & Physics Control")
28
29model_choice = st.sidebar.selectbox(
30 "Select Model",
31 ["ElasticNet (Recommended)", "Ridge", "Linear Regression"]
32)
33
34selected_features = st.sidebar.multiselect(
35 "Select Input Physics",
36 numeric_cols,
37 default=[
38 c for c in [
39 "Conductor OD(mm)",
40 "Conductor Dielectric OD(mm)",
41 "insulated diameter mil",
42 "Packing Ratio %",
43 "TPI",
44 "OD conductor bundle",
45 "Desire shield OD",
46 "Dielectric material PN 155C/ .7 loss tangent",
47 "Free air capacitance for 4.2ft single Twisted Pair",
48 "Free air capacitance for single Twisted Pair pf/ft"
49 ] if c in numeric_cols
50 ]
51)
52
53remove_outliers = st.sidebar.checkbox("Remove Outliers", True)
54train_btn = st.sidebar.button("Train Model")
55
56# ================= TRAIN =================
57if train_btn:
58
59 data = df[selected_features + [target]].dropna()
60 X = data[selected_features]
61 y = data[target]
62
63 if remove_outliers:
64 base = LinearRegression()
65 base.fit(X, y)
66 residuals = y - base.predict(X)
67 mask = residuals.abs() < 10
68 X = X[mask]
69 y = y[mask]
70
71 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
72
73 if model_choice == "Linear Regression":
74 model = LinearRegression()
75 model.fit(X_train, y_train)
76
77 elif model_choice == "Ridge":
78 grid = GridSearchCV(Ridge(), {"alpha":[0.01,0.1,1,10,50]}, cv=5, scoring="r2")
79 grid.fit(X_train, y_train)
80 model = grid.best_estimator_
81 params = grid.best_params_
82
83 else:
84 grid = GridSearchCV(
85 ElasticNet(max_iter=10000),
86 {"alpha":[0.001,0.01,0.1,1,10],"l1_ratio":[0.1,0.3,0.5,0.7,0.9]},
87 cv=5, scoring="r2"
88 )
89 grid.fit(X_train, y_train)
90 model = grid.best_estimator_
91 params = grid.best_params_
92
93 y_pred = model.predict(X_test)
94
95 st.session_state.model = model
96 st.session_state.features = selected_features
97 st.session_state.y_test = y_test
98 st.session_state.y_pred = y_pred
99 st.session_state.r2 = r2_score(y_test, y_pred)
100 st.session_state.model_choice = model_choice
101 st.session_state.params = params if "params" in locals() else None
102
103# ================= UI =================
104st.title("RF Cable Capacitance Digital Twin")
105
106if "model" in st.session_state:
107 st.success(f"{st.session_state.model_choice} | Test R² = {st.session_state.r2}")
108 if st.session_state.params:
109 st.info(f"Model parameters: {st.session_state.params}")
110else:
111 st.warning("Select physics + model and click Train")
112
113# ================= PREDICT =================
114if "model" in st.session_state:
115 st.subheader("Predict Cable")
116
117 inputs = {}
118 cols = st.columns(3)
119 for i,f in enumerate(st.session_state.features):
120 inputs[f] = cols[i%3].number_input(f, value=0.0, step=0.0000001, format="%.10f")
121
122 if st.button("Predict Capacitance"):
123 row = pd.DataFrame([inputs])
124 pred = st.session_state.model.predict(row)[0]
125 st.success(f"Predicted Capacitance = {pred} pF")
126
127# ================= PLOTS =================
128if "model" in st.session_state:
129 st.subheader("Diagnostics")
130
131 plot = st.selectbox("Select Plot",
132 ["None","Correlation Heatmap","Predicted vs Actual","Residuals","Feature vs Capacitance","GGPlot Smooth"]
133 )
134
135 if plot=="Correlation Heatmap":
136 fig,ax=plt.subplots(figsize=(10,6))
137 sns.heatmap(df[st.session_state.features+[target]].corr(), cmap="coolwarm", center=0, ax=ax)
138 st.pyplot(fig)
139
140 elif plot=="Predicted vs Actual":
141 fig,ax=plt.subplots()
142 ax.scatter(st.session_state.y_test, st.session_state.y_pred)
143 ax.plot([st.session_state.y_test.min(),st.session_state.y_test.max()],
144 [st.session_state.y_test.min(),st.session_state.y_test.max()])
145 st.pyplot(fig)
146
147 elif plot=="Residuals":
148 fig,ax=plt.subplots()
149 ax.scatter(st.session_state.y_test, st.session_state.y_test-st.session_state.y_pred)
150 ax.axhline(0)
151 st.pyplot(fig)
152
153 elif plot=="Feature vs Capacitance":
154 f=st.selectbox("Select Feature",st.session_state.features)
155 fig,ax=plt.subplots()
156 ax.scatter(df[f],df[target])
157 st.pyplot(fig)
158
159 elif plot=="GGPlot Smooth":
160 f=st.selectbox("Select Feature",st.session_state.features)
161 x=df[f]; y=df[target]
162 z=np.polyfit(x,y,3)
163 xp=np.linspace(x.min(),x.max(),200)
164 yp=np.polyval(z,xp)
165 fig,ax=plt.subplots()
166 ax.scatter(x,y,alpha=0.4)
167 ax.plot(xp,yp,color="red")
168 st.pyplot(fig)
169 