csepartha commited on
Commit
5aee0a0
·
verified ·
1 Parent(s): 04f129a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +1167 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,1167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # ReliaPy-Workbench: Python/Gradio Reliability Analysis Tool for Colab
3
+ # Copy this entire cell after installing gradio.
4
+
5
+ import io
6
+ import math
7
+ import warnings
8
+ import tempfile
9
+ import numpy as np
10
+ import pandas as pd
11
+ import matplotlib.pyplot as plt
12
+ from scipy import optimize, stats
13
+ import gradio as gr
14
+
15
+ warnings.filterwarnings("ignore")
16
+
17
+ EPS = 1e-12
18
+
19
+ def _path(file_obj):
20
+ if file_obj is None:
21
+ return None
22
+ if isinstance(file_obj, str):
23
+ return file_obj
24
+ return getattr(file_obj, "name", None) or getattr(file_obj, "path", None)
25
+
26
+ def read_table(file_obj):
27
+ path = _path(file_obj)
28
+ if path is None:
29
+ raise ValueError("Please upload a CSV file.")
30
+ if path.lower().endswith((".xlsx", ".xls")):
31
+ return pd.read_excel(path)
32
+ return pd.read_csv(path)
33
+
34
+ def _clean_name(s):
35
+ return str(s).strip()
36
+
37
+ def infer_col(df, requested, candidates, fallback_index=0):
38
+ if requested and requested != "Auto":
39
+ if requested not in df.columns:
40
+ raise ValueError(f"Column '{requested}' not found. Available columns: {list(df.columns)}")
41
+ return requested
42
+ lower = {str(c).lower().strip(): c for c in df.columns}
43
+ for cand in candidates:
44
+ if cand.lower() in lower:
45
+ return lower[cand.lower()]
46
+ # fuzzy contains
47
+ for c in df.columns:
48
+ lc = str(c).lower()
49
+ if any(k in lc for k in candidates):
50
+ return c
51
+ if len(df.columns) > fallback_index:
52
+ return df.columns[fallback_index]
53
+ raise ValueError("Could not infer a required column.")
54
+
55
+ def as_event(series):
56
+ s = series.copy()
57
+ if s.dtype == bool:
58
+ return s.astype(int).values
59
+ if pd.api.types.is_numeric_dtype(s):
60
+ return (pd.to_numeric(s, errors="coerce").fillna(0) > 0).astype(int).values
61
+ ss = s.astype(str).str.lower().str.strip()
62
+ return ss.isin(["1", "true", "t", "yes", "y", "event", "failed", "failure", "fail"]).astype(int).values
63
+
64
+ def benard_ranks(n):
65
+ i = np.arange(1, n + 1)
66
+ return (i - 0.3) / (n + 0.4)
67
+
68
+ def life_rank_regression(times, dist="Weibull"):
69
+ t = np.asarray(times, dtype=float)
70
+ t = np.sort(t[t > 0])
71
+ n = len(t)
72
+ if n < 2:
73
+ raise ValueError("Rank regression needs at least two uncensored failure times.")
74
+ F = benard_ranks(n)
75
+ x = np.log(t)
76
+ if dist == "Weibull":
77
+ y = np.log(-np.log(1 - F))
78
+ slope, intercept, r, p, se = stats.linregress(x, y)
79
+ beta = max(slope, EPS)
80
+ eta = float(np.exp(-intercept / beta))
81
+ ll = weibull_loglik(t, np.ones_like(t), beta, eta)
82
+ return {"dist": dist, "method": "Rank regression", "beta_shape": beta, "eta_scale": eta,
83
+ "loglik_uncensored": ll, "rr_r2": r*r}
84
+ else:
85
+ y = stats.norm.ppf(F)
86
+ slope, intercept, r, p, se = stats.linregress(x, y)
87
+ sigma = max(1.0 / slope, EPS)
88
+ mu = -intercept / slope
89
+ ll = lognormal_loglik(t, np.ones_like(t), mu, sigma)
90
+ return {"dist": dist, "method": "Rank regression", "mu_log": mu, "sigma_log": sigma,
91
+ "median_life": float(np.exp(mu)), "loglik_uncensored": ll, "rr_r2": r*r}
92
+
93
+ def weibull_loglik(t, event, beta, eta):
94
+ t = np.asarray(t, dtype=float)
95
+ e = np.asarray(event, dtype=int)
96
+ z = (t / eta) ** beta
97
+ logpdf = np.log(beta) - beta * np.log(eta) + (beta - 1) * np.log(t) - z
98
+ logsf = -z
99
+ return float(np.sum(e * logpdf + (1 - e) * logsf))
100
+
101
+ def lognormal_loglik(t, event, mu, sigma):
102
+ t = np.asarray(t, dtype=float)
103
+ e = np.asarray(event, dtype=int)
104
+ z = (np.log(t) - mu) / sigma
105
+ logpdf = -np.log(t) - np.log(sigma) - 0.5*np.log(2*np.pi) - 0.5*z*z
106
+ logsf = stats.norm.logsf(z)
107
+ return float(np.sum(e * logpdf + (1 - e) * logsf))
108
+
109
+ def life_mle(times, event, dist="Weibull"):
110
+ t = np.asarray(times, dtype=float)
111
+ e = np.asarray(event, dtype=int)
112
+ if len(t) < 2 or e.sum() < 1:
113
+ raise ValueError("MLE needs at least two observations and at least one failure event.")
114
+ fail = t[e == 1]
115
+ rr = life_rank_regression(fail, dist) if len(fail) >= 2 else None
116
+ if dist == "Weibull":
117
+ if rr:
118
+ init = [np.log(rr["beta_shape"]), np.log(rr["eta_scale"])]
119
+ else:
120
+ init = [0.0, np.log(np.median(t))]
121
+ def nll(x):
122
+ beta, eta = np.exp(x[0]), np.exp(x[1])
123
+ return -weibull_loglik(t, e, beta, eta)
124
+ res = optimize.minimize(nll, init, method="Nelder-Mead", options={"maxiter": 20000})
125
+ beta, eta = np.exp(res.x[0]), np.exp(res.x[1])
126
+ ll = -res.fun
127
+ return {"dist": dist, "method": "MLE", "beta_shape": beta, "eta_scale": eta,
128
+ "mean_life": float(eta * math.gamma(1 + 1/beta)),
129
+ "median_life": float(eta * (np.log(2)) ** (1/beta)),
130
+ "loglik": ll, "AIC": 2*2 - 2*ll, "BIC": 2*np.log(len(t)) - 2*ll,
131
+ "events": int(e.sum()), "observations": len(t)}
132
+ else:
133
+ if rr:
134
+ init = [rr["mu_log"], np.log(rr["sigma_log"])]
135
+ else:
136
+ init = [np.log(np.median(fail)), 0.0]
137
+ def nll(x):
138
+ mu, sigma = x[0], np.exp(x[1])
139
+ return -lognormal_loglik(t, e, mu, sigma)
140
+ res = optimize.minimize(nll, init, method="Nelder-Mead", options={"maxiter": 20000})
141
+ mu, sigma = res.x[0], np.exp(res.x[1])
142
+ ll = -res.fun
143
+ return {"dist": dist, "method": "MLE", "mu_log": mu, "sigma_log": sigma,
144
+ "median_life": float(np.exp(mu)), "mean_life": float(np.exp(mu + 0.5*sigma*sigma)),
145
+ "loglik": ll, "AIC": 2*2 - 2*ll, "BIC": 2*np.log(len(t)) - 2*ll,
146
+ "events": int(e.sum()), "observations": len(t)}
147
+
148
+ def reliability_at_time(params, mission_time):
149
+ if mission_time is None or mission_time <= 0:
150
+ return np.nan
151
+ if params["dist"] == "Weibull":
152
+ beta, eta = params["beta_shape"], params["eta_scale"]
153
+ return float(np.exp(- (mission_time / eta) ** beta))
154
+ else:
155
+ mu, sigma = params["mu_log"], params["sigma_log"]
156
+ return float(stats.norm.sf((np.log(mission_time) - mu) / sigma))
157
+
158
+ def life_probability_plot(t, e, params):
159
+ fig, ax = plt.subplots(figsize=(7, 5))
160
+ fail = np.sort(np.asarray(t)[np.asarray(e) == 1])
161
+ if len(fail) < 2:
162
+ ax.text(0.05, 0.5, "At least two failures are needed for a probability plot.", transform=ax.transAxes)
163
+ return fig
164
+ F = benard_ranks(len(fail))
165
+ x = np.log(fail)
166
+ if params["dist"] == "Weibull":
167
+ y = np.log(-np.log(1 - F))
168
+ ax.scatter(x, y, label="Median-rank failures")
169
+ xx = np.linspace(x.min()*0.95, x.max()*1.05, 100)
170
+ beta, eta = params["beta_shape"], params["eta_scale"]
171
+ yy = beta * (xx - np.log(eta))
172
+ ax.plot(xx, yy, label="Fitted Weibull line")
173
+ ax.set_ylabel("ln[-ln(1-F)]")
174
+ ax.set_title("Weibull Probability Plot")
175
+ else:
176
+ y = stats.norm.ppf(F)
177
+ ax.scatter(x, y, label="Median-rank failures")
178
+ xx = np.linspace(x.min()*0.95, x.max()*1.05, 100)
179
+ mu, sigma = params["mu_log"], params["sigma_log"]
180
+ yy = (xx - mu) / sigma
181
+ ax.plot(xx, yy, label="Fitted Lognormal line")
182
+ ax.set_ylabel("Normal quantile")
183
+ ax.set_title("Lognormal Probability Plot")
184
+ ax.set_xlabel("ln(time)")
185
+ ax.grid(True, alpha=0.3)
186
+ ax.legend()
187
+ fig.tight_layout()
188
+ return fig
189
+
190
+ def life_cdf_plot(t, e, params):
191
+ fig, ax = plt.subplots(figsize=(7, 5))
192
+ fail = np.sort(np.asarray(t)[np.asarray(e) == 1])
193
+ F = benard_ranks(len(fail)) if len(fail) else np.array([])
194
+ if len(fail):
195
+ ax.scatter(fail, F, label="Median-rank empirical CDF")
196
+ x = np.linspace(max(min(np.asarray(t)) * 0.1, EPS), max(np.asarray(t)) * 1.15, 200)
197
+ if params["dist"] == "Weibull":
198
+ beta, eta = params["beta_shape"], params["eta_scale"]
199
+ cdf = 1 - np.exp(-(x/eta)**beta)
200
+ else:
201
+ mu, sigma = params["mu_log"], params["sigma_log"]
202
+ cdf = stats.norm.cdf((np.log(x) - mu)/sigma)
203
+ ax.plot(x, cdf, label="Fitted CDF")
204
+ ax.set_xlabel("Time")
205
+ ax.set_ylabel("F(t)")
206
+ ax.set_title("Fitted Life Distribution")
207
+ ax.grid(True, alpha=0.3)
208
+ ax.legend()
209
+ fig.tight_layout()
210
+ return fig
211
+
212
+ def life_contour_plot(t, e, params):
213
+ fig, ax = plt.subplots(figsize=(7, 5))
214
+ try:
215
+ if params["dist"] == "Weibull":
216
+ beta0, eta0 = params["beta_shape"], params["eta_scale"]
217
+ beta_grid = np.linspace(max(beta0*0.35, EPS), beta0*2.5, 70)
218
+ eta_grid = np.linspace(max(eta0*0.35, EPS), eta0*2.5, 70)
219
+ B, E = np.meshgrid(beta_grid, eta_grid)
220
+ LL = np.zeros_like(B)
221
+ for i in range(B.shape[0]):
222
+ for j in range(B.shape[1]):
223
+ LL[i, j] = weibull_loglik(t, e, B[i, j], E[i, j])
224
+ D = -2*(LL - np.max(LL))
225
+ cs = ax.contour(B, E, D, levels=[2.30, 6.18, 11.83])
226
+ ax.clabel(cs, inline=True, fontsize=8)
227
+ ax.scatter([beta0], [eta0], marker="x", s=80, label="Estimate")
228
+ ax.set_xlabel("Shape beta")
229
+ ax.set_ylabel("Scale eta")
230
+ ax.set_title("Weibull Likelihood Contours")
231
+ else:
232
+ mu0, sigma0 = params["mu_log"], params["sigma_log"]
233
+ mu_grid = np.linspace(mu0 - 2.0*sigma0, mu0 + 2.0*sigma0, 70)
234
+ sig_grid = np.linspace(max(sigma0*0.35, EPS), sigma0*2.5, 70)
235
+ M, S = np.meshgrid(mu_grid, sig_grid)
236
+ LL = np.zeros_like(M)
237
+ for i in range(M.shape[0]):
238
+ for j in range(M.shape[1]):
239
+ LL[i, j] = lognormal_loglik(t, e, M[i, j], S[i, j])
240
+ D = -2*(LL - np.max(LL))
241
+ cs = ax.contour(M, S, D, levels=[2.30, 6.18, 11.83])
242
+ ax.clabel(cs, inline=True, fontsize=8)
243
+ ax.scatter([mu0], [sigma0], marker="x", s=80, label="Estimate")
244
+ ax.set_xlabel("mu")
245
+ ax.set_ylabel("sigma")
246
+ ax.set_title("Lognormal Likelihood Contours")
247
+ ax.grid(True, alpha=0.3)
248
+ ax.legend()
249
+ except Exception as exc:
250
+ ax.text(0.05, 0.5, f"Contour plot could not be computed:\n{exc}", transform=ax.transAxes)
251
+ fig.tight_layout()
252
+ return fig
253
+
254
+ def fit_life_data(file_obj, dist, method, time_col, event_col, mission_time):
255
+ try:
256
+ df = read_table(file_obj)
257
+ tc = infer_col(df, time_col, ["time", "ttf", "failure_time", "life", "hours", "cycles"], 0)
258
+ raw_t = pd.to_numeric(df[tc], errors="coerce")
259
+ if event_col and event_col != "Auto" and event_col != "None":
260
+ ec = infer_col(df, event_col, ["event", "status", "failed", "failure", "censor", "censored"], 1)
261
+ event = as_event(df[ec])
262
+ else:
263
+ # Auto uses event/status column if present; otherwise all failures
264
+ possible = [c for c in df.columns if str(c).lower().strip() in ["event", "status", "failed", "failure"]]
265
+ event = as_event(df[possible[0]]) if possible else np.ones(len(df), dtype=int)
266
+ mask = np.isfinite(raw_t) & (raw_t > 0) & np.isfinite(event)
267
+ t = raw_t[mask].values.astype(float)
268
+ e = np.asarray(event)[mask].astype(int)
269
+ if method == "Rank Regression":
270
+ params = life_rank_regression(t[e == 1], dist)
271
+ params["observations"] = len(t)
272
+ params["events_used"] = int(e.sum())
273
+ params["note"] = "Rank regression uses uncensored failures; right-censored rows are not used in the line fit."
274
+ else:
275
+ params = life_mle(t, e, dist)
276
+ params[f"Reliability_at_t={mission_time}"] = reliability_at_time(params, mission_time)
277
+ summary = pd.DataFrame({"Metric": list(params.keys()), "Value": [params[k] for k in params.keys()]})
278
+ fig1 = life_probability_plot(t, e, params)
279
+ fig2 = life_contour_plot(t, e, params)
280
+ fig3 = life_cdf_plot(t, e, params)
281
+ return summary, fig1, fig2, fig3, f"Used time column: {tc}. Observations after cleaning: {len(t)}."
282
+ except Exception as exc:
283
+ return pd.DataFrame({"Error": [str(exc)]}), None, None, None, "Analysis failed."
284
+
285
+ def plp_fit(times, T=None):
286
+ t = np.asarray(times, dtype=float)
287
+ t = t[np.isfinite(t) & (t > 0)]
288
+ if T is None:
289
+ T = np.max(t)
290
+ T = float(T)
291
+ if len(t) < 2 or T <= 0:
292
+ raise ValueError("PLP/Crow-AMSAA needs at least two positive event times.")
293
+ denom = np.sum(np.log(T / np.clip(t, EPS, None)))
294
+ beta = len(t) / max(denom, EPS)
295
+ lam = len(t) / (T ** beta)
296
+ ll = float(np.sum(np.log(lam*beta) + (beta - 1)*np.log(np.clip(t, EPS, None))) - lam*(T**beta))
297
+ return {"lambda": float(lam), "beta": float(beta), "T": T, "n_events": len(t), "loglik": ll, "AIC": 2*2 - 2*ll}
298
+
299
+ def loglinear_nhpp_fit(times, T=None, n_systems=1):
300
+ t = np.asarray(times, dtype=float)
301
+ t = t[np.isfinite(t) & (t >= 0)]
302
+ if T is None:
303
+ T = np.max(t)
304
+ T = float(T)
305
+ n_systems = max(int(n_systems), 1)
306
+ if len(t) < 2:
307
+ raise ValueError("Log-linear NHPP needs at least two event times.")
308
+ init_rate = len(t) / max(n_systems*T, EPS)
309
+ init = [np.log(max(init_rate, EPS)), 0.0]
310
+ def cum_int(a, b):
311
+ if abs(b) < 1e-8:
312
+ return n_systems * np.exp(a) * T
313
+ return n_systems * np.exp(a) * (np.exp(b*T) - 1.0) / b
314
+ def nll(x):
315
+ a, b = x
316
+ val = np.sum(a + b*t) - cum_int(a, b)
317
+ if not np.isfinite(val):
318
+ return 1e100
319
+ return -val
320
+ res = optimize.minimize(nll, init, method="Nelder-Mead", options={"maxiter": 20000})
321
+ a, b = res.x
322
+ ll = -res.fun
323
+ return {"a_log_rate": float(a), "b_time_slope": float(b), "T": T, "n_events": len(t),
324
+ "loglik": float(ll), "AIC": 2*2 - 2*ll}
325
+
326
+ def parse_breakpoints(text):
327
+ if not text or str(text).strip() == "":
328
+ return []
329
+ vals = []
330
+ for x in str(text).replace(";", ",").split(","):
331
+ x = x.strip()
332
+ if x:
333
+ vals.append(float(x))
334
+ return sorted(vals)
335
+
336
+ def segment_plp(times, breakpoints=None, auto=False):
337
+ t = np.sort(np.asarray(times, dtype=float))
338
+ t = t[np.isfinite(t) & (t > 0)]
339
+ T = float(np.max(t))
340
+ if auto:
341
+ candidates = np.unique(t)
342
+ candidates = candidates[(candidates > np.quantile(t, 0.2)) & (candidates < np.quantile(t, 0.8))]
343
+ best = None
344
+ for bp in candidates:
345
+ left = t[t <= bp]
346
+ right = t[t > bp] - bp
347
+ try:
348
+ if len(left) < 3 or len(right) < 3:
349
+ continue
350
+ f1 = plp_fit(left, T=bp)
351
+ f2 = plp_fit(right, T=T-bp)
352
+ aic = f1["AIC"] + f2["AIC"]
353
+ if best is None or aic < best[0]:
354
+ best = (aic, bp, f1, f2)
355
+ except Exception:
356
+ pass
357
+ if best is not None:
358
+ breakpoints = [best[1]]
359
+ else:
360
+ breakpoints = []
361
+ if breakpoints is None:
362
+ breakpoints = []
363
+ cuts = [0.0] + [bp for bp in breakpoints if 0 < bp < T] + [T]
364
+ rows = []
365
+ for i in range(len(cuts)-1):
366
+ start, end = cuts[i], cuts[i+1]
367
+ seg_abs = t[(t > start) & (t <= end)]
368
+ local = seg_abs - start
369
+ if len(local) >= 2:
370
+ fit = plp_fit(np.clip(local, EPS, None), T=end-start)
371
+ rows.append({"segment": i+1, "start": start, "end": end, **fit})
372
+ else:
373
+ rows.append({"segment": i+1, "start": start, "end": end, "n_events": len(local),
374
+ "lambda": np.nan, "beta": np.nan, "loglik": np.nan, "AIC": np.nan})
375
+ return pd.DataFrame(rows), cuts
376
+
377
+ def growth_plots(times, summary_segments, cuts):
378
+ t = np.sort(np.asarray(times, dtype=float))
379
+ n = np.arange(1, len(t)+1)
380
+ T = max(t)
381
+
382
+ fig1, ax = plt.subplots(figsize=(7, 5))
383
+ ax.step(t, n, where="post", label="Observed cumulative failures")
384
+ xx_full = []
385
+ yy_full = []
386
+ cum_prev = 0.0
387
+ for _, row in summary_segments.iterrows():
388
+ start, end = row["start"], row["end"]
389
+ if np.isfinite(row.get("lambda", np.nan)) and np.isfinite(row.get("beta", np.nan)):
390
+ xs = np.linspace(start, end, 80)
391
+ local = np.clip(xs - start, 0, None)
392
+ ys = cum_prev + row["lambda"] * (local ** row["beta"])
393
+ xx_full.extend(xs.tolist())
394
+ yy_full.extend(ys.tolist())
395
+ cum_prev += row.get("n_events", 0)
396
+ if xx_full:
397
+ ax.plot(xx_full, yy_full, label="Fitted NHPP mean")
398
+ for bp in cuts[1:-1]:
399
+ ax.axvline(bp, linestyle="--", alpha=0.6)
400
+ ax.set_xlabel("Cumulative test time")
401
+ ax.set_ylabel("Cumulative failures")
402
+ ax.set_title("Reliability Growth / NHPP Plot")
403
+ ax.grid(True, alpha=0.3)
404
+ ax.legend()
405
+ fig1.tight_layout()
406
+
407
+ fig2, ax = plt.subplots(figsize=(7, 5))
408
+ cum_mtbf = t / n
409
+ ax.plot(t, cum_mtbf, marker="o", linewidth=1)
410
+ ax.set_xscale("log")
411
+ ax.set_yscale("log")
412
+ ax.set_xlabel("Cumulative test time")
413
+ ax.set_ylabel("Cumulative MTBF = time / failures")
414
+ ax.set_title("Duane Plot")
415
+ ax.grid(True, alpha=0.3, which="both")
416
+ fig2.tight_layout()
417
+ return fig1, fig2
418
+
419
+ def fit_growth(file_obj, model_type, time_col, breakpoints_text):
420
+ try:
421
+ df = read_table(file_obj)
422
+ tc = infer_col(df, time_col, ["time", "event_time", "failure_time", "test_time", "hours", "cycles"], 0)
423
+ t = pd.to_numeric(df[tc], errors="coerce").dropna().values.astype(float)
424
+ t = np.sort(t[t > 0])
425
+ if len(t) < 2:
426
+ raise ValueError("At least two positive cumulative event times are required.")
427
+ if model_type == "Crow-AMSAA":
428
+ seg_df, cuts = segment_plp(t, breakpoints=[])
429
+ elif model_type == "Piecewise NHPP":
430
+ seg_df, cuts = segment_plp(t, breakpoints=parse_breakpoints(breakpoints_text), auto=False)
431
+ else:
432
+ seg_df, cuts = segment_plp(t, auto=True)
433
+ fig1, fig2 = growth_plots(t, seg_df, cuts)
434
+ interpretation = []
435
+ for _, r in seg_df.iterrows():
436
+ beta = r.get("beta", np.nan)
437
+ if np.isfinite(beta):
438
+ trend = "improving/decreasing event intensity" if beta < 1 else "deteriorating/increasing event intensity" if beta > 1 else "approximately constant intensity"
439
+ interpretation.append(f"Segment {int(r['segment'])}: beta={beta:.4g}, indicating {trend}.")
440
+ return seg_df, fig1, fig2, "\n".join(interpretation) + f"\nUsed time column: {tc}."
441
+ except Exception as exc:
442
+ return pd.DataFrame({"Error": [str(exc)]}), None, None, "Analysis failed."
443
+
444
+ def repair_plots(t, model_params, model_name, n_systems=1, sys_ids=None):
445
+ t = np.sort(np.asarray(t, dtype=float))
446
+ T = max(t)
447
+ fig1, ax = plt.subplots(figsize=(7, 5))
448
+ ax.step(t, np.arange(1, len(t)+1), where="post", label="Observed cumulative events")
449
+ xx = np.linspace(max(T*0.001, EPS), T, 200)
450
+ if model_name == "Power Law":
451
+ lam, beta = model_params["lambda"], model_params["beta"]
452
+ yy = n_systems * lam * (xx ** beta)
453
+ elif model_name == "Log-Linear":
454
+ a, b = model_params["a_log_rate"], model_params["b_time_slope"]
455
+ if abs(b) < 1e-8:
456
+ yy = n_systems * np.exp(a) * xx
457
+ else:
458
+ yy = n_systems * np.exp(a) * (np.exp(b*xx) - 1) / b
459
+ else:
460
+ yy = None
461
+ if yy is not None:
462
+ ax.plot(xx, yy, label="Fitted cumulative mean")
463
+ ax.set_xlabel("Time")
464
+ ax.set_ylabel("Cumulative events")
465
+ ax.set_title("Repairable-System Cumulative Events")
466
+ ax.grid(True, alpha=0.3)
467
+ ax.legend()
468
+ fig1.tight_layout()
469
+
470
+ fig2, ax = plt.subplots(figsize=(7, 5))
471
+ if model_name == "Power Law":
472
+ lam, beta = model_params["lambda"], model_params["beta"]
473
+ rate = lam * beta * (xx ** (beta - 1))
474
+ elif model_name == "Log-Linear":
475
+ a, b = model_params["a_log_rate"], model_params["b_time_slope"]
476
+ rate = np.exp(a + b*xx)
477
+ else:
478
+ # crude smoothed empirical rate for piecewise
479
+ bins = np.linspace(0, T, 12)
480
+ counts, edges = np.histogram(t, bins=bins)
481
+ centers = 0.5*(edges[1:]+edges[:-1])
482
+ widths = np.diff(edges)
483
+ ax.plot(centers, counts / np.maximum(widths*n_systems, EPS), marker="o")
484
+ rate = None
485
+ if rate is not None:
486
+ ax.plot(xx, rate)
487
+ ax.set_xlabel("Time")
488
+ ax.set_ylabel("Event rate per system")
489
+ ax.set_title("Estimated Event Rate")
490
+ ax.grid(True, alpha=0.3)
491
+ fig2.tight_layout()
492
+
493
+ fig3, ax = plt.subplots(figsize=(7, 5))
494
+ if sys_ids is None:
495
+ # one system MCF equals cumulative events
496
+ ax.step(t, np.arange(1, len(t)+1), where="post")
497
+ else:
498
+ tmp = pd.DataFrame({"time": t, "system": sys_ids}).sort_values("time")
499
+ counts = tmp.groupby("time").size().sort_index()
500
+ mcf = counts.cumsum() / max(n_systems, 1)
501
+ ax.step(mcf.index.values, mcf.values, where="post")
502
+ ax.set_xlabel("Time")
503
+ ax.set_ylabel("Mean cumulative function")
504
+ ax.set_title("Mean Cumulative Function (MCF)")
505
+ ax.grid(True, alpha=0.3)
506
+ fig3.tight_layout()
507
+ return fig1, fig2, fig3
508
+
509
+ def fit_repairable(file_obj, model_type, time_col, system_col, breakpoints_text):
510
+ try:
511
+ df = read_table(file_obj)
512
+ tc = infer_col(df, time_col, ["time", "event_time", "repair_time", "failure_time", "hours", "cycles"], 0)
513
+ time = pd.to_numeric(df[tc], errors="coerce")
514
+ mask = np.isfinite(time) & (time > 0)
515
+ t = time[mask].values.astype(float)
516
+ sys_ids = None
517
+ if system_col and system_col != "Auto" and system_col != "None":
518
+ sc = infer_col(df, system_col, ["system", "unit", "asset", "id"], 1)
519
+ sys_ids = df.loc[mask, sc].astype(str).values
520
+ n_systems = len(pd.unique(sys_ids))
521
+ else:
522
+ possible = [c for c in df.columns if any(k in str(c).lower() for k in ["system", "unit", "asset"])]
523
+ if possible:
524
+ sys_ids = df.loc[mask, possible[0]].astype(str).values
525
+ n_systems = len(pd.unique(sys_ids))
526
+ else:
527
+ n_systems = 1
528
+ if len(t) < 2:
529
+ raise ValueError("At least two repair/failure event times are required.")
530
+ if model_type == "Power Law":
531
+ fit = plp_fit(t, T=max(t))
532
+ summary = pd.DataFrame({"Metric": list(fit.keys()) + ["assumed_number_of_systems"],
533
+ "Value": list(fit.values()) + [n_systems]})
534
+ fig1, fig2, fig3 = repair_plots(t, fit, "Power Law", n_systems, sys_ids)
535
+ elif model_type == "Log-Linear":
536
+ fit = loglinear_nhpp_fit(t, T=max(t), n_systems=n_systems)
537
+ summary = pd.DataFrame({"Metric": list(fit.keys()) + ["assumed_number_of_systems"],
538
+ "Value": list(fit.values()) + [n_systems]})
539
+ fig1, fig2, fig3 = repair_plots(t, fit, "Log-Linear", n_systems, sys_ids)
540
+ else:
541
+ seg_df, cuts = segment_plp(t, parse_breakpoints(breakpoints_text), auto=False)
542
+ summary = seg_df
543
+ # plot observed plus piecewise fitted using growth plot
544
+ fig1, _ = growth_plots(t, seg_df, cuts)
545
+ # empirical rate and MCF
546
+ fig2, _, fig3 = repair_plots(t, {}, "Piecewise", n_systems, sys_ids)
547
+ note = f"Used time column: {tc}. Number of systems inferred: {n_systems}. If systems have different observation windows, add exposure handling before publication-grade inference."
548
+ return summary, fig1, fig2, fig3, note
549
+ except Exception as exc:
550
+ return pd.DataFrame({"Error": [str(exc)]}), None, None, None, "Analysis failed."
551
+
552
+ def alt_transform(stress, relationship):
553
+ s = np.asarray(stress, dtype=float)
554
+ if relationship == "Arrhenius; temperature in Celsius":
555
+ return 1.0 / (s + 273.15), "1 / absolute temperature (K^-1)"
556
+ if relationship == "Arrhenius; temperature in Kelvin":
557
+ return 1.0 / s, "1 / absolute temperature (K^-1)"
558
+ return np.log(s), "ln(stress)"
559
+
560
+ def alt_weibull_loglik(t, event, x, a, b, beta):
561
+ eta = np.exp(a + b*x)
562
+ z = (t / eta) ** beta
563
+ logpdf = np.log(beta) - beta*np.log(eta) + (beta-1)*np.log(t) - z
564
+ logsf = -z
565
+ return float(np.sum(event*logpdf + (1-event)*logsf))
566
+
567
+ def alt_lognormal_loglik(t, event, x, a, b, sigma):
568
+ mu = a + b*x
569
+ z = (np.log(t) - mu) / sigma
570
+ logpdf = -np.log(t) - np.log(sigma) - 0.5*np.log(2*np.pi) - 0.5*z*z
571
+ logsf = stats.norm.logsf(z)
572
+ return float(np.sum(event*logpdf + (1-event)*logsf))
573
+
574
+ def fit_alt_model(t, event, stress, dist, relationship):
575
+ x, xlab = alt_transform(stress, relationship)
576
+ # initialize by regression on log failure time
577
+ fail = event == 1
578
+ if fail.sum() >= 2 and len(np.unique(x[fail])) >= 2:
579
+ slope, intercept, *_ = stats.linregress(x[fail], np.log(t[fail]))
580
+ a0, b0 = intercept, slope
581
+ else:
582
+ a0, b0 = np.log(np.median(t)), 0.0
583
+ if dist == "Weibull":
584
+ init = [a0, b0, 0.0] # log beta
585
+ def nll(par):
586
+ a, b, logbeta = par
587
+ return -alt_weibull_loglik(t, event, x, a, b, np.exp(logbeta))
588
+ res = optimize.minimize(nll, init, method="Nelder-Mead", options={"maxiter": 30000})
589
+ a, b, logbeta = res.x
590
+ beta = np.exp(logbeta)
591
+ ll = -res.fun
592
+ out = {"distribution": "Weibull", "relationship": relationship, "a_intercept_log_eta": a,
593
+ "b_stress_slope": b, "beta_shape_common": beta,
594
+ "loglik": ll, "AIC": 2*3 - 2*ll, "BIC": 3*np.log(len(t)) - 2*ll}
595
+ else:
596
+ init = [a0, b0, 0.0] # log sigma
597
+ def nll(par):
598
+ a, b, logsig = par
599
+ return -alt_lognormal_loglik(t, event, x, a, b, np.exp(logsig))
600
+ res = optimize.minimize(nll, init, method="Nelder-Mead", options={"maxiter": 30000})
601
+ a, b, logsig = res.x
602
+ sigma = np.exp(logsig)
603
+ ll = -res.fun
604
+ out = {"distribution": "Lognormal", "relationship": relationship, "a_intercept_mu": a,
605
+ "b_stress_slope": b, "sigma_common": sigma,
606
+ "loglik": ll, "AIC": 2*3 - 2*ll, "BIC": 3*np.log(len(t)) - 2*ll}
607
+ return out, x, xlab
608
+
609
+ def alt_plots(t, event, stress, params, x, xlab):
610
+ fig1, ax = plt.subplots(figsize=(7, 5))
611
+ for s in sorted(pd.unique(stress)):
612
+ mask = (stress == s) & (event == 1)
613
+ tf = np.sort(t[mask])
614
+ if len(tf) >= 2:
615
+ F = benard_ranks(len(tf))
616
+ if params["distribution"] == "Weibull":
617
+ y = np.log(-np.log(1-F))
618
+ ax.scatter(np.log(tf), y, label=f"stress={s}")
619
+ else:
620
+ y = stats.norm.ppf(F)
621
+ ax.scatter(np.log(tf), y, label=f"stress={s}")
622
+ ax.set_xlabel("ln(time)")
623
+ ax.set_ylabel("Weibull/lognormal probability scale")
624
+ ax.set_title("ALT Probability Plot by Stress Level")
625
+ ax.grid(True, alpha=0.3)
626
+ ax.legend(fontsize=8)
627
+ fig1.tight_layout()
628
+
629
+ fig2, ax = plt.subplots(figsize=(7, 5))
630
+ raw_s_grid = np.linspace(np.min(stress), np.max(stress), 200)
631
+ xg, _ = alt_transform(raw_s_grid, params["relationship"])
632
+ if params["distribution"] == "Weibull":
633
+ life = np.exp(params["a_intercept_log_eta"] + params["b_stress_slope"]*xg)
634
+ ylab = "Characteristic life eta"
635
+ else:
636
+ life = np.exp(params["a_intercept_mu"] + params["b_stress_slope"]*xg)
637
+ ylab = "Median life"
638
+ # Observed stress-wise median failure times
639
+ med = pd.DataFrame({"time": t[event == 1], "stress": stress[event == 1]}).groupby("stress")["time"].median()
640
+ if len(med):
641
+ ax.scatter(med.index.values, med.values, label="Observed median failure time")
642
+ ax.plot(raw_s_grid, life, label="Fitted life-stress curve")
643
+ ax.set_xlabel("Stress")
644
+ ax.set_ylabel(ylab)
645
+ ax.set_yscale("log")
646
+ ax.set_title("Life-Stress Relationship")
647
+ ax.grid(True, alpha=0.3)
648
+ ax.legend()
649
+ fig2.tight_layout()
650
+ return fig1, fig2
651
+
652
+ def fit_alt(file_obj, dist, relationship, time_col, stress_col, event_col, use_stress):
653
+ try:
654
+ df = read_table(file_obj)
655
+ tc = infer_col(df, time_col, ["time", "ttf", "failure_time", "life", "hours", "cycles"], 0)
656
+ sc = infer_col(df, stress_col, ["stress", "temperature", "temp", "voltage", "load"], 1)
657
+ t = pd.to_numeric(df[tc], errors="coerce").values
658
+ stress = pd.to_numeric(df[sc], errors="coerce").values
659
+ if event_col and event_col != "Auto" and event_col != "None":
660
+ ec = infer_col(df, event_col, ["event", "status", "failed", "failure"], 2)
661
+ event = as_event(df[ec])
662
+ else:
663
+ possible = [c for c in df.columns if str(c).lower().strip() in ["event", "status", "failed", "failure"]]
664
+ event = as_event(df[possible[0]]) if possible else np.ones(len(df), dtype=int)
665
+ mask = np.isfinite(t) & np.isfinite(stress) & (t > 0) & (stress > 0) & np.isfinite(event)
666
+ t, stress, event = t[mask].astype(float), stress[mask].astype(float), np.asarray(event)[mask].astype(int)
667
+ if len(t) < 3 or event.sum() < 2:
668
+ raise ValueError("ALT fitting needs at least three rows and at least two failures.")
669
+ params, x, xlab = fit_alt_model(t, event, stress, dist, relationship)
670
+ if use_stress is not None and np.isfinite(use_stress) and use_stress > 0:
671
+ xu, _ = alt_transform(np.array([use_stress]), relationship)
672
+ if dist == "Weibull":
673
+ eta_use = float(np.exp(params["a_intercept_log_eta"] + params["b_stress_slope"]*xu[0]))
674
+ params[f"eta_at_use_stress_{use_stress}"] = eta_use
675
+ else:
676
+ med_use = float(np.exp(params["a_intercept_mu"] + params["b_stress_slope"]*xu[0]))
677
+ params[f"median_life_at_use_stress_{use_stress}"] = med_use
678
+ params["stress_transform"] = xlab
679
+ params["observations"] = len(t)
680
+ params["events"] = int(event.sum())
681
+ summary = pd.DataFrame({"Metric": list(params.keys()), "Value": [params[k] for k in params.keys()]})
682
+ fig1, fig2 = alt_plots(t, event, stress, params, x, xlab)
683
+ note = f"Used time column: {tc}; stress column: {sc}. Relationship transform: {xlab}."
684
+ return summary, fig1, fig2, note
685
+ except Exception as exc:
686
+ return pd.DataFrame({"Error": [str(exc)]}), None, None, "Analysis failed."
687
+
688
+ def sample_life_csv():
689
+ rng = np.random.default_rng(7)
690
+ beta, eta = 1.8, 500
691
+ t = eta * rng.weibull(beta, 80)
692
+ censor = rng.uniform(350, 900, 80)
693
+ obs = np.minimum(t, censor)
694
+ event = (t <= censor).astype(int)
695
+ return pd.DataFrame({"time": np.round(obs, 2), "event": event})
696
+
697
+ def sample_growth_csv():
698
+ rng = np.random.default_rng(9)
699
+ # NHPP with mean lambda*t^beta
700
+ beta, lam = 0.72, 0.45
701
+ n = 50
702
+ u = np.sort(rng.uniform(0, 1, n))
703
+ T = (n/lam)**(1/beta)
704
+ times = T * (u ** (1/beta))
705
+ return pd.DataFrame({"event_time": np.round(times, 2)})
706
+
707
+ def sample_repair_csv():
708
+ rng = np.random.default_rng(3)
709
+ rows = []
710
+ for sys in range(1, 6):
711
+ gaps = rng.exponential(80, size=10)
712
+ times = np.cumsum(gaps)
713
+ for tm in times[times < 600]:
714
+ rows.append({"system": f"S{sys}", "event_time": round(float(tm), 2)})
715
+ return pd.DataFrame(rows)
716
+
717
+ def sample_alt_csv():
718
+ rng = np.random.default_rng(5)
719
+ rows = []
720
+ for temp in [85, 105, 125]:
721
+ x = 1/(temp+273.15)
722
+ eta = np.exp(2.0 + 3800*x) # longer life at lower temperature
723
+ beta = 1.7
724
+ for i in range(30):
725
+ true_t = eta * rng.weibull(beta)
726
+ censor = rng.uniform(1000, 5000)
727
+ rows.append({"time": round(float(min(true_t, censor)), 2),
728
+ "event": int(true_t <= censor),
729
+ "temperature": temp})
730
+ return pd.DataFrame(rows)
731
+
732
+ # -----------------------------------------------------------------------------
733
+ # Presentation and export layer
734
+ # The analytical functions above are intentionally unchanged. The wrapper
735
+ # functions below only call the existing computations and save returned tables
736
+ # and figures as downloadable artifacts for the Gradio interface.
737
+ # -----------------------------------------------------------------------------
738
+ import os
739
+ import time
740
+ import uuid
741
+
742
+ # Gradio can only serve returned files safely from the current working directory,
743
+ # system temp directory, upload directory, or explicit allowed_paths.
744
+ EXPORT_DIR = os.path.join(tempfile.gettempdir(), "reliapy_exports")
745
+ os.makedirs(EXPORT_DIR, exist_ok=True)
746
+
747
+
748
+ def _export_token(prefix):
749
+ return f"{prefix}_{time.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
750
+
751
+
752
+ def _save_summary_csv(df, token):
753
+ path = os.path.join(EXPORT_DIR, f"{token}_summary.csv")
754
+ try:
755
+ if isinstance(df, pd.DataFrame):
756
+ df.to_csv(path, index=False)
757
+ return path
758
+ except Exception:
759
+ pass
760
+ return None
761
+
762
+
763
+ def _save_figure_png(fig, token, suffix):
764
+ if fig is None:
765
+ return None
766
+ path = os.path.join(EXPORT_DIR, f"{token}_{suffix}.png")
767
+ try:
768
+ fig.savefig(path, dpi=300, bbox_inches="tight")
769
+ return path
770
+ except Exception:
771
+ return None
772
+
773
+
774
+ def run_life_with_downloads(file_obj, dist, method, time_col, event_col, mission_time):
775
+ summary, fig1, fig2, fig3, note = fit_life_data(file_obj, dist, method, time_col, event_col, mission_time)
776
+ token = _export_token("life_data")
777
+ csv_path = _save_summary_csv(summary, token)
778
+ p1 = _save_figure_png(fig1, token, "probability_plot")
779
+ p2 = _save_figure_png(fig2, token, "likelihood_contour")
780
+ p3 = _save_figure_png(fig3, token, "fitted_cdf")
781
+ return summary, fig1, fig2, fig3, note, csv_path, p1, p2, p3
782
+
783
+
784
+ def run_growth_with_downloads(file_obj, model_type, time_col, breakpoints_text):
785
+ summary, fig1, fig2, note = fit_growth(file_obj, model_type, time_col, breakpoints_text)
786
+ token = _export_token("reliability_growth")
787
+ csv_path = _save_summary_csv(summary, token)
788
+ p1 = _save_figure_png(fig1, token, "growth_plot")
789
+ p2 = _save_figure_png(fig2, token, "duane_plot")
790
+ return summary, fig1, fig2, note, csv_path, p1, p2
791
+
792
+
793
+ def run_repairable_with_downloads(file_obj, model_type, time_col, system_col, breakpoints_text):
794
+ summary, fig1, fig2, fig3, note = fit_repairable(file_obj, model_type, time_col, system_col, breakpoints_text)
795
+ token = _export_token("repairable_system")
796
+ csv_path = _save_summary_csv(summary, token)
797
+ p1 = _save_figure_png(fig1, token, "cumulative_events")
798
+ p2 = _save_figure_png(fig2, token, "event_rate")
799
+ p3 = _save_figure_png(fig3, token, "mcf")
800
+ return summary, fig1, fig2, fig3, note, csv_path, p1, p2, p3
801
+
802
+
803
+ def run_alt_with_downloads(file_obj, dist, relationship, time_col, stress_col, event_col, use_stress):
804
+ summary, fig1, fig2, note = fit_alt(file_obj, dist, relationship, time_col, stress_col, event_col, use_stress)
805
+ token = _export_token("accelerated_life_testing")
806
+ csv_path = _save_summary_csv(summary, token)
807
+ p1 = _save_figure_png(fig1, token, "alt_probability_plot")
808
+ p2 = _save_figure_png(fig2, token, "life_stress_plot")
809
+ return summary, fig1, fig2, note, csv_path, p1, p2
810
+
811
+
812
+ APP_CSS = """
813
+ :root {
814
+ --rp-red: #d71920;
815
+ --rp-red-dark: #991b1b;
816
+ --rp-red-soft: rgba(215, 25, 32, .10);
817
+ --rp-ink: #0f172a;
818
+ --rp-slate: #334155;
819
+ --rp-muted: #64748b;
820
+ --rp-line: rgba(15, 23, 42, .10);
821
+ --rp-card: rgba(255, 255, 255, .92);
822
+ --rp-bg: #f5f7fb;
823
+ }
824
+
825
+ .gradio-container {
826
+ max-width: 1480px !important;
827
+ margin: 0 auto !important;
828
+ color: var(--rp-ink) !important;
829
+ background:
830
+ radial-gradient(circle at 8% 4%, rgba(215, 25, 32, .14), transparent 28%),
831
+ radial-gradient(circle at 92% 0%, rgba(2, 132, 199, .09), transparent 26%),
832
+ linear-gradient(180deg, #ffffff 0%, var(--rp-bg) 100%) !important;
833
+ }
834
+
835
+ #title-banner {
836
+ position: relative;
837
+ overflow: hidden;
838
+ padding: 34px 38px;
839
+ border-radius: 28px;
840
+ background:
841
+ linear-gradient(135deg, rgba(153, 27, 27, .98), rgba(215, 25, 32, .94) 45%, rgba(15, 23, 42, .96));
842
+ color: white;
843
+ margin: 14px 0 20px 0;
844
+ border: 1px solid rgba(255, 255, 255, .24);
845
+ box-shadow: 0 24px 70px rgba(15, 23, 42, .22);
846
+ }
847
+ #title-banner:before {
848
+ content: "";
849
+ position: absolute;
850
+ right: -95px;
851
+ top: -95px;
852
+ width: 340px;
853
+ height: 340px;
854
+ border-radius: 999px;
855
+ background: rgba(255, 255, 255, .11);
856
+ }
857
+ #title-banner:after {
858
+ content: "";
859
+ position: absolute;
860
+ right: 98px;
861
+ bottom: -120px;
862
+ width: 270px;
863
+ height: 270px;
864
+ border-radius: 999px;
865
+ border: 42px solid rgba(255, 255, 255, .07);
866
+ }
867
+ #title-banner h1 {
868
+ position: relative;
869
+ font-size: 2.8rem;
870
+ letter-spacing: -.05em;
871
+ margin: 0 0 9px 0;
872
+ line-height: 1.02;
873
+ }
874
+ #title-banner p {
875
+ position: relative;
876
+ max-width: 920px;
877
+ margin: 0;
878
+ font-size: 1.07rem;
879
+ color: rgba(255, 255, 255, .89);
880
+ line-height: 1.55;
881
+ }
882
+ #hero-kicker {
883
+ position: relative;
884
+ display: inline-flex;
885
+ align-items: center;
886
+ gap: 9px;
887
+ padding: 7px 13px;
888
+ border-radius: 999px;
889
+ background: rgba(255,255,255,.16);
890
+ color: rgba(255,255,255,.96);
891
+ font-size: .78rem;
892
+ font-weight: 800;
893
+ text-transform: uppercase;
894
+ letter-spacing: .09em;
895
+ margin-bottom: 14px;
896
+ }
897
+
898
+ .metric-card {
899
+ padding: 20px 20px;
900
+ min-height: 128px;
901
+ border: 1px solid var(--rp-line);
902
+ border-radius: 22px;
903
+ background: var(--rp-card);
904
+ box-shadow: 0 14px 38px rgba(15, 23, 42, .075);
905
+ transition: transform .18s ease, box-shadow .18s ease;
906
+ }
907
+ .metric-card:hover { transform: translateY(-2px); box-shadow: 0 20px 48px rgba(15, 23, 42, .10); }
908
+ .metric-card .icon {
909
+ display: inline-flex;
910
+ width: 38px;
911
+ height: 38px;
912
+ align-items: center;
913
+ justify-content: center;
914
+ border-radius: 13px;
915
+ color: #fff;
916
+ background: linear-gradient(135deg, var(--rp-red), #ef4444);
917
+ margin-bottom: 10px;
918
+ font-size: 1.1rem;
919
+ }
920
+ .metric-card h3 { margin: 0 0 7px 0; font-size: 1.02rem; color: var(--rp-ink); }
921
+ .metric-card p { margin: 0; color: var(--rp-muted); font-size: .91rem; line-height: 1.45; }
922
+
923
+ .module-intro {
924
+ padding: 18px 20px;
925
+ border: 1px solid var(--rp-line);
926
+ border-left: 7px solid var(--rp-red);
927
+ border-radius: 20px;
928
+ background: rgba(255, 255, 255, .88);
929
+ box-shadow: 0 10px 30px rgba(15,23,42,.055);
930
+ margin: 10px 0 13px 0;
931
+ }
932
+ .module-intro h2 { margin: 0 0 6px 0; font-size: 1.35rem; letter-spacing: -.02em; }
933
+ .module-intro p { margin: 0; color: var(--rp-muted); line-height: 1.5; }
934
+
935
+ .control-panel, .output-panel, .download-panel {
936
+ border: 1px solid var(--rp-line) !important;
937
+ border-radius: 22px !important;
938
+ background: rgba(255, 255, 255, .90) !important;
939
+ box-shadow: 0 12px 34px rgba(15, 23, 42, .06) !important;
940
+ padding: 14px !important;
941
+ }
942
+ .plot-card {
943
+ border: 1px solid var(--rp-line) !important;
944
+ border-radius: 20px !important;
945
+ background: rgba(255, 255, 255, .92) !important;
946
+ box-shadow: 0 10px 28px rgba(15, 23, 42, .055) !important;
947
+ padding: 9px !important;
948
+ }
949
+ .download-card {
950
+ border: 1px dashed rgba(215, 25, 32, .32) !important;
951
+ border-radius: 18px !important;
952
+ background: linear-gradient(180deg, rgba(255,255,255,.92), rgba(254,242,242,.55)) !important;
953
+ padding: 10px !important;
954
+ }
955
+ .footer-note {
956
+ margin-top: 16px;
957
+ padding: 17px 19px;
958
+ border-radius: 19px;
959
+ background: #fff7ed;
960
+ border: 1px solid rgba(249,115,22,.22);
961
+ color: #7c2d12;
962
+ line-height: 1.48;
963
+ }
964
+
965
+ .gr-button-primary {
966
+ border-radius: 13px !important;
967
+ font-weight: 800 !important;
968
+ box-shadow: 0 10px 24px rgba(215, 25, 32, .22) !important;
969
+ }
970
+ .gr-button-secondary, button { border-radius: 13px !important; }
971
+ .tabitem { padding-top: 14px !important; }
972
+ .block label, .gradio-container label { font-weight: 700 !important; color: #334155 !important; }
973
+ textarea, input, select { border-radius: 13px !important; }
974
+ .table-wrap, .dataframe { border-radius: 15px !important; }
975
+ .file-preview, .upload-container { border-radius: 15px !important; }
976
+ code { background: rgba(15,23,42,.06); padding: 2px 5px; border-radius: 6px; }
977
+ """
978
+
979
+ INTRO_HTML = """
980
+ <div id="title-banner">
981
+ <div id="hero-kicker">Reliability analysis · Python · Gradio · Colab-ready</div>
982
+ <h1>ReliaPy Workbench</h1>
983
+ <p>Publication-oriented reliability analysis dashboard for life data, reliability growth, repairable systems, and accelerated life testing. The calculation layer is preserved; this version enriches the interface and adds downloadable CSV/PNG exports.</p>
984
+ <p style="margin-top:12px;font-size:0.95rem;color:rgba(255,255,255,.86);"><strong>Developer:</strong> Partha Pratim Ray, Sikkim University · July 2026 · <strong>Email:</strong> parthapratimray1986@gmail.com</p>
985
+ </div>
986
+ """
987
+
988
+ CSV_NOTE = """
989
+ <div class="module-intro">
990
+ <h2>Input convention and export support</h2>
991
+ <p>Upload CSV or Excel files with positive numeric times. Optional event/status columns accept <code>1/true/failure</code> as failure and <code>0/false</code> as right-censored. After every run, the result table can be downloaded as CSV and each plot can be downloaded as a 300-dpi PNG image.</p>
992
+ </div>
993
+ """
994
+
995
+
996
+ def download_area(csv_component, plot_components):
997
+ gr.Markdown("### ⬇️ Downloads")
998
+ with gr.Row():
999
+ csv_component.render()
1000
+ with gr.Row():
1001
+ for comp in plot_components:
1002
+ comp.render()
1003
+
1004
+
1005
+ with gr.Blocks(
1006
+ css=APP_CSS,
1007
+ theme=gr.themes.Soft(primary_hue="red", secondary_hue="slate", neutral_hue="slate"),
1008
+ title="ReliaPy Workbench"
1009
+ ) as demo:
1010
+ gr.Markdown(INTRO_HTML)
1011
+ with gr.Row(equal_height=True):
1012
+ gr.Markdown("""<div class="metric-card"><div class="icon">⏳</div><h3>Life Data Analysis</h3><p>Weibull and Lognormal models using MLE or Rank Regression with probability, CDF, and likelihood-contour plots.</p></div>""")
1013
+ gr.Markdown("""<div class="metric-card"><div class="icon">↗</div><h3>Reliability Growth</h3><p>Crow-AMSAA, piecewise NHPP, and automatic change-point analysis with growth and Duane visualizations.</p></div>""")
1014
+ gr.Markdown("""<div class="metric-card"><div class="icon">🔧</div><h3>Repairable Systems</h3><p>Power Law, Log-Linear, and Piecewise NHPP models with cumulative events, event rate, and MCF outputs.</p></div>""")
1015
+ gr.Markdown("""<div class="metric-card"><div class="icon">⚡</div><h3>Accelerated Life Testing</h3><p>Weibull or Lognormal ALT with Arrhenius or Power Law stress relationships and use-condition prediction.</p></div>""")
1016
+ gr.Markdown(CSV_NOTE)
1017
+
1018
+ with gr.Tabs():
1019
+ with gr.Tab("Life Data Analysis"):
1020
+ gr.Markdown("""<div class="module-intro"><h2>Life Data Analysis</h2><p>Fit Weibull or Lognormal life distributions using MLE or median-rank regression. Outputs include parameter estimates, reliability at mission time, probability plot, likelihood contour, fitted CDF, and downloadable artifacts.</p></div>""")
1021
+ with gr.Row():
1022
+ with gr.Column(scale=1, elem_classes="control-panel"):
1023
+ gr.Markdown("### Inputs")
1024
+ life_file = gr.File(label="Upload life-data CSV/XLSX", file_types=[".csv", ".xlsx", ".xls"])
1025
+ with gr.Row():
1026
+ life_dist = gr.Dropdown(["Weibull", "Lognormal"], value="Weibull", label="Distribution")
1027
+ life_method = gr.Dropdown(["MLE", "Rank Regression"], value="MLE", label="Fitting method")
1028
+ life_time_col = gr.Textbox(value="Auto", label="Time column name")
1029
+ life_event_col = gr.Textbox(value="Auto", label="Event/status column name; use None if all failures")
1030
+ life_mission = gr.Number(value=500, label="Mission time for reliability R(t)")
1031
+ with gr.Row():
1032
+ life_btn = gr.Button("Run analysis", variant="primary")
1033
+ life_sample = gr.Button("Load sample table")
1034
+ with gr.Column(scale=2, elem_classes="output-panel"):
1035
+ gr.Markdown("### Results")
1036
+ life_out = gr.Dataframe(label="Parameter summary", wrap=True, interactive=False)
1037
+ life_note = gr.Textbox(label="Notes", lines=3)
1038
+ with gr.Accordion("⬇️ Download result table and plots", open=True):
1039
+ with gr.Row():
1040
+ life_csv = gr.File(label="⬇️ Download results CSV", elem_classes="download-card")
1041
+ with gr.Row():
1042
+ life_png1 = gr.File(label="⬇️ Probability plot PNG", elem_classes="download-card")
1043
+ life_png2 = gr.File(label="⬇️ Likelihood contour PNG", elem_classes="download-card")
1044
+ life_png3 = gr.File(label="⬇️ Fitted CDF PNG", elem_classes="download-card")
1045
+ with gr.Row():
1046
+ with gr.Column(elem_classes="plot-card"):
1047
+ life_plot1 = gr.Plot(label="Probability plot")
1048
+ with gr.Column(elem_classes="plot-card"):
1049
+ life_plot2 = gr.Plot(label="Likelihood contour")
1050
+ with gr.Column(elem_classes="plot-card"):
1051
+ life_plot3 = gr.Plot(label="Fitted CDF")
1052
+ life_sample.click(sample_life_csv, outputs=life_out)
1053
+ life_btn.click(run_life_with_downloads,
1054
+ inputs=[life_file, life_dist, life_method, life_time_col, life_event_col, life_mission],
1055
+ outputs=[life_out, life_plot1, life_plot2, life_plot3, life_note, life_csv, life_png1, life_png2, life_png3])
1056
+
1057
+ with gr.Tab("Reliability Growth"):
1058
+ gr.Markdown("""<div class="module-intro"><h2>Reliability Growth Analysis</h2><p>Model cumulative test failures using Crow-AMSAA/Power Law NHPP, manual piecewise NHPP, or automatic one-change-point detection.</p></div>""")
1059
+ with gr.Row():
1060
+ with gr.Column(scale=1, elem_classes="control-panel"):
1061
+ gr.Markdown("### Inputs")
1062
+ growth_file = gr.File(label="Upload reliability-growth CSV/XLSX", file_types=[".csv", ".xlsx", ".xls"])
1063
+ growth_model = gr.Dropdown(["Crow-AMSAA", "Piecewise NHPP", "Automatic change-point"], value="Crow-AMSAA", label="Model")
1064
+ growth_time_col = gr.Textbox(value="Auto", label="Cumulative event-time column")
1065
+ growth_bps = gr.Textbox(value="", label="Manual breakpoints, comma-separated; used for Piecewise NHPP")
1066
+ with gr.Row():
1067
+ growth_btn = gr.Button("Run growth analysis", variant="primary")
1068
+ growth_sample = gr.Button("Load sample table")
1069
+ with gr.Column(scale=2, elem_classes="output-panel"):
1070
+ gr.Markdown("### Results")
1071
+ growth_out = gr.Dataframe(label="Growth/NHPP summary", wrap=True, interactive=False)
1072
+ growth_note = gr.Textbox(label="Interpretation", lines=6)
1073
+ with gr.Accordion("⬇️ Download result table and plots", open=True):
1074
+ with gr.Row():
1075
+ growth_csv = gr.File(label="⬇️ Download results CSV", elem_classes="download-card")
1076
+ with gr.Row():
1077
+ growth_png1 = gr.File(label="⬇️ Reliability growth plot PNG", elem_classes="download-card")
1078
+ growth_png2 = gr.File(label="⬇️ Duane plot PNG", elem_classes="download-card")
1079
+ with gr.Row():
1080
+ with gr.Column(elem_classes="plot-card"):
1081
+ growth_plot1 = gr.Plot(label="Reliability growth plot")
1082
+ with gr.Column(elem_classes="plot-card"):
1083
+ growth_plot2 = gr.Plot(label="Duane plot")
1084
+ growth_sample.click(sample_growth_csv, outputs=growth_out)
1085
+ growth_btn.click(run_growth_with_downloads,
1086
+ inputs=[growth_file, growth_model, growth_time_col, growth_bps],
1087
+ outputs=[growth_out, growth_plot1, growth_plot2, growth_note, growth_csv, growth_png1, growth_png2])
1088
+
1089
+ with gr.Tab("Repairable Systems"):
1090
+ gr.Markdown("""<div class="module-intro"><h2>Repairable Systems</h2><p>Analyze recurrent repair/failure events with Power Law, Log-Linear, or Piecewise NHPP models. Includes cumulative events, event rate, Mean Cumulative Function, and downloadable exports.</p></div>""")
1091
+ with gr.Row():
1092
+ with gr.Column(scale=1, elem_classes="control-panel"):
1093
+ gr.Markdown("### Inputs")
1094
+ rep_file = gr.File(label="Upload repairable-system CSV/XLSX", file_types=[".csv", ".xlsx", ".xls"])
1095
+ rep_model = gr.Dropdown(["Power Law", "Log-Linear", "Piecewise NHPP"], value="Power Law", label="Model")
1096
+ rep_time_col = gr.Textbox(value="Auto", label="Event-time column")
1097
+ rep_system_col = gr.Textbox(value="Auto", label="System/unit ID column; use None for one system")
1098
+ rep_bps = gr.Textbox(value="", label="Manual breakpoints for Piecewise NHPP")
1099
+ with gr.Row():
1100
+ rep_btn = gr.Button("Run repairable analysis", variant="primary")
1101
+ rep_sample = gr.Button("Load sample table")
1102
+ with gr.Column(scale=2, elem_classes="output-panel"):
1103
+ gr.Markdown("### Results")
1104
+ rep_out = gr.Dataframe(label="Repairable-system summary", wrap=True, interactive=False)
1105
+ rep_note = gr.Textbox(label="Notes", lines=4)
1106
+ with gr.Accordion("⬇️ Download result table and plots", open=True):
1107
+ with gr.Row():
1108
+ rep_csv = gr.File(label="⬇️ Download results CSV", elem_classes="download-card")
1109
+ with gr.Row():
1110
+ rep_png1 = gr.File(label="⬇️ Cumulative events PNG", elem_classes="download-card")
1111
+ rep_png2 = gr.File(label="⬇️ Event rate PNG", elem_classes="download-card")
1112
+ rep_png3 = gr.File(label="⬇️ MCF PNG", elem_classes="download-card")
1113
+ with gr.Row():
1114
+ with gr.Column(elem_classes="plot-card"):
1115
+ rep_plot1 = gr.Plot(label="Cumulative events")
1116
+ with gr.Column(elem_classes="plot-card"):
1117
+ rep_plot2 = gr.Plot(label="Event rate")
1118
+ with gr.Column(elem_classes="plot-card"):
1119
+ rep_plot3 = gr.Plot(label="MCF")
1120
+ rep_sample.click(sample_repair_csv, outputs=rep_out)
1121
+ rep_btn.click(run_repairable_with_downloads,
1122
+ inputs=[rep_file, rep_model, rep_time_col, rep_system_col, rep_bps],
1123
+ outputs=[rep_out, rep_plot1, rep_plot2, rep_plot3, rep_note, rep_csv, rep_png1, rep_png2, rep_png3])
1124
+
1125
+ with gr.Tab("Accelerated Life Testing"):
1126
+ gr.Markdown("""<div class="module-intro"><h2>Accelerated Life Testing</h2><p>Fit accelerated life models under Arrhenius or Power Law stress relationships with common Weibull shape or common Lognormal sigma.</p></div>""")
1127
+ with gr.Row():
1128
+ with gr.Column(scale=1, elem_classes="control-panel"):
1129
+ gr.Markdown("### Inputs")
1130
+ alt_file = gr.File(label="Upload ALT CSV/XLSX", file_types=[".csv", ".xlsx", ".xls"])
1131
+ alt_dist = gr.Dropdown(["Weibull", "Lognormal"], value="Weibull", label="Life distribution")
1132
+ alt_rel = gr.Dropdown(["Arrhenius; temperature in Celsius", "Arrhenius; temperature in Kelvin", "Power law; generic stress"],
1133
+ value="Arrhenius; temperature in Celsius", label="Life-stress relationship")
1134
+ alt_time_col = gr.Textbox(value="Auto", label="Time column")
1135
+ alt_stress_col = gr.Textbox(value="Auto", label="Stress column")
1136
+ alt_event_col = gr.Textbox(value="Auto", label="Event/status column; use None if all failures")
1137
+ alt_use_stress = gr.Number(value=55, label="Use stress for predicted life")
1138
+ with gr.Row():
1139
+ alt_btn = gr.Button("Run ALT analysis", variant="primary")
1140
+ alt_sample = gr.Button("Load sample table")
1141
+ with gr.Column(scale=2, elem_classes="output-panel"):
1142
+ gr.Markdown("### Results")
1143
+ alt_out = gr.Dataframe(label="ALT summary", wrap=True, interactive=False)
1144
+ alt_note = gr.Textbox(label="Notes", lines=4)
1145
+ with gr.Accordion("⬇️ Download result table and plots", open=True):
1146
+ with gr.Row():
1147
+ alt_csv = gr.File(label="⬇️ Download results CSV", elem_classes="download-card")
1148
+ with gr.Row():
1149
+ alt_png1 = gr.File(label="⬇️ ALT probability plot PNG", elem_classes="download-card")
1150
+ alt_png2 = gr.File(label="⬇️ Life-stress plot PNG", elem_classes="download-card")
1151
+ with gr.Row():
1152
+ with gr.Column(elem_classes="plot-card"):
1153
+ alt_plot1 = gr.Plot(label="ALT probability plot")
1154
+ with gr.Column(elem_classes="plot-card"):
1155
+ alt_plot2 = gr.Plot(label="Life-stress plot")
1156
+ alt_sample.click(sample_alt_csv, outputs=alt_out)
1157
+ alt_btn.click(run_alt_with_downloads,
1158
+ inputs=[alt_file, alt_dist, alt_rel, alt_time_col, alt_stress_col, alt_event_col, alt_use_stress],
1159
+ outputs=[alt_out, alt_plot1, alt_plot2, alt_note, alt_csv, alt_png1, alt_png2])
1160
+
1161
+ gr.Markdown("""
1162
+ <div class="footer-note"><strong>Developer:</strong> Partha Pratim Ray, Sikkim University · July 2026 · <strong>Email:</strong> parthapratimray1986@gmail.com<br><br><strong>Publication note.</strong> For an IEEE Reliability Magazine tool paper, validate this workbench against known datasets and report numerical agreement, limitations, censoring assumptions, and reproducible Colab/GitHub availability. Downloaded PNGs are saved at 300 dpi for manuscript drafting and reports.</div>
1163
+ """)
1164
+
1165
+ demo.queue()
1166
+ demo.launch(allowed_paths=[tempfile.gettempdir(), EXPORT_DIR])
1167
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ numpy
3
+ pandas
4
+ scipy
5
+ matplotlib
6
+ openpyxl