statstudio 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. statstudio/__init__.py +9 -0
  2. statstudio/__main__.py +3 -0
  3. statstudio/app.py +83 -0
  4. statstudio/cli.py +116 -0
  5. statstudio/core/__init__.py +3 -0
  6. statstudio/core/archive.py +27 -0
  7. statstudio/core/commands.py +67 -0
  8. statstudio/core/formula_catalog.py +74 -0
  9. statstudio/core/formulas.py +605 -0
  10. statstudio/core/joins.py +123 -0
  11. statstudio/core/project.py +358 -0
  12. statstudio/core/runtime.py +321 -0
  13. statstudio/core/scripting.py +594 -0
  14. statstudio/core/table.py +796 -0
  15. statstudio/core/transform.py +450 -0
  16. statstudio/feature_help.py +595 -0
  17. statstudio/io/__init__.py +3 -0
  18. statstudio/io/docx.py +201 -0
  19. statstudio/io/export.py +99 -0
  20. statstudio/io/file_import.py +199 -0
  21. statstudio/io/odbc.py +334 -0
  22. statstudio/io/sample_data.py +164 -0
  23. statstudio/io/table_io.py +118 -0
  24. statstudio/plots/__init__.py +19 -0
  25. statstudio/plots/advanced.py +651 -0
  26. statstudio/plots/basic.py +957 -0
  27. statstudio/plots/bayesian_plots.py +94 -0
  28. statstudio/plots/common.py +334 -0
  29. statstudio/plots/diagnostics.py +214 -0
  30. statstudio/plots/doe_plots.py +235 -0
  31. statstudio/plots/plotly_builders.py +719 -0
  32. statstudio/plots/predictive_plots.py +72 -0
  33. statstudio/plots/registry.py +251 -0
  34. statstudio/plugins.py +111 -0
  35. statstudio/resources/help_topics.json +13195 -0
  36. statstudio/resources/logo.ico +0 -0
  37. statstudio/resources/logo.png +0 -0
  38. statstudio/resources/statstudio.svg +8 -0
  39. statstudio/stats/__init__.py +42 -0
  40. statstudio/stats/bayesian.py +1094 -0
  41. statstudio/stats/bayesian_optimization.py +590 -0
  42. statstudio/stats/common.py +140 -0
  43. statstudio/stats/correlation.py +135 -0
  44. statstudio/stats/custom_doe.py +1714 -0
  45. statstudio/stats/descriptive.py +200 -0
  46. statstudio/stats/desirability.py +132 -0
  47. statstudio/stats/distributions.py +331 -0
  48. statstudio/stats/doe.py +1070 -0
  49. statstudio/stats/hypothesis.py +1305 -0
  50. statstudio/stats/multivariate.py +307 -0
  51. statstudio/stats/optimal_doe.py +264 -0
  52. statstudio/stats/power.py +194 -0
  53. statstudio/stats/predictive.py +605 -0
  54. statstudio/stats/profiler.py +379 -0
  55. statstudio/stats/quality.py +1218 -0
  56. statstudio/stats/regression.py +1600 -0
  57. statstudio/stats/results.py +235 -0
  58. statstudio/stats/simulator.py +95 -0
  59. statstudio/stats/survival.py +637 -0
  60. statstudio/stats/timeseries.py +643 -0
  61. statstudio/stats/tolerance.py +154 -0
  62. statstudio/ui/__init__.py +0 -0
  63. statstudio/ui/analysis_hub.py +271 -0
  64. statstudio/ui/command_catalog.py +460 -0
  65. statstudio/ui/command_palette.py +55 -0
  66. statstudio/ui/console.py +239 -0
  67. statstudio/ui/dialogs/__init__.py +0 -0
  68. statstudio/ui/dialogs/advanced_dialogs.py +392 -0
  69. statstudio/ui/dialogs/base.py +537 -0
  70. statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
  71. statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
  72. statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
  73. statstudio/ui/dialogs/doe_dialogs.py +220 -0
  74. statstudio/ui/dialogs/extended_dialogs.py +665 -0
  75. statstudio/ui/dialogs/graph_builder.py +139 -0
  76. statstudio/ui/dialogs/help_dialog.py +207 -0
  77. statstudio/ui/dialogs/help_topics.py +280 -0
  78. statstudio/ui/dialogs/lazy.py +184 -0
  79. statstudio/ui/dialogs/odbc_dialog.py +311 -0
  80. statstudio/ui/dialogs/plot_dialog.py +1385 -0
  81. statstudio/ui/dialogs/report_composer.py +218 -0
  82. statstudio/ui/dialogs/script_dialogs.py +267 -0
  83. statstudio/ui/dialogs/stats_dialogs.py +1688 -0
  84. statstudio/ui/dialogs/table_dialogs.py +997 -0
  85. statstudio/ui/dialogs/window.py +58 -0
  86. statstudio/ui/docks/__init__.py +0 -0
  87. statstudio/ui/formula_editor.py +121 -0
  88. statstudio/ui/icons.py +257 -0
  89. statstudio/ui/jobs.py +179 -0
  90. statstudio/ui/main_window.py +3934 -0
  91. statstudio/ui/plot_interaction.py +178 -0
  92. statstudio/ui/profiler_widget.py +437 -0
  93. statstudio/ui/recent.py +82 -0
  94. statstudio/ui/reports/__init__.py +0 -0
  95. statstudio/ui/reports/report_view.py +1632 -0
  96. statstudio/ui/script_jobs.py +35 -0
  97. statstudio/ui/scripts_panel.py +271 -0
  98. statstudio/ui/table_document.py +233 -0
  99. statstudio/ui/table_model.py +285 -0
  100. statstudio/ui/table_view.py +285 -0
  101. statstudio/ui/theme.py +645 -0
  102. statstudio/ui/welcome.py +453 -0
  103. statstudio/ui/window_controls.py +53 -0
  104. statstudio/ui/workers.py +53 -0
  105. statstudio-0.1.0.dist-info/METADATA +261 -0
  106. statstudio-0.1.0.dist-info/RECORD +110 -0
  107. statstudio-0.1.0.dist-info/WHEEL +5 -0
  108. statstudio-0.1.0.dist-info/entry_points.txt +5 -0
  109. statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
  110. statstudio-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,637 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ import math
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from scipy import stats
9
+
10
+ from statstudio.stats.common import p_stars
11
+ from statstudio.stats.results import AnalysisResult
12
+
13
+
14
+ def _matches(values: pd.Series, target: Any) -> pd.Series:
15
+ if target is None:
16
+ return pd.Series(False, index=values.index)
17
+ if pd.api.types.is_numeric_dtype(values) and not isinstance(target, bool):
18
+ numeric_target = pd.to_numeric(pd.Series([target]), errors="coerce").iloc[0]
19
+ if not pd.isna(numeric_target):
20
+ return pd.to_numeric(values, errors="coerce") == numeric_target
21
+ return values.astype(str) == str(target)
22
+
23
+
24
+ def _event_indicator(values: pd.Series, event_value: Any | None = None) -> pd.Series:
25
+ result = pd.Series(np.nan, index=values.index, dtype=float)
26
+ valid = values.notna()
27
+ if not valid.any():
28
+ return result
29
+ subset = values[valid]
30
+ if event_value is not None:
31
+ result.loc[valid] = _matches(subset, event_value).astype(float)
32
+ elif pd.api.types.is_bool_dtype(subset):
33
+ result.loc[valid] = subset.astype(float)
34
+ elif pd.api.types.is_numeric_dtype(subset):
35
+ result.loc[valid] = (pd.to_numeric(subset, errors="coerce") != 0).astype(float)
36
+ else:
37
+ truthy = {"1", "true", "yes", "event", "dead", "death", "failed", "failure"}
38
+ result.loc[valid] = subset.astype(str).str.lower().isin(truthy).astype(float)
39
+ return result
40
+
41
+
42
+ def _km_table(time: np.ndarray, event: np.ndarray, confidence: float = 0.95) -> pd.DataFrame:
43
+ frame = pd.DataFrame({"time": time, "event": event}).dropna()
44
+ frame = frame[frame["time"] >= 0]
45
+ unique_times = np.sort(frame["time"].unique())
46
+ survival = 1.0
47
+ cumulative = 0.0
48
+ rows = []
49
+ z_value = float(stats.norm.ppf(1 - (1 - confidence) / 2))
50
+ for value in unique_times:
51
+ at_risk = int((frame["time"] >= value).sum())
52
+ at_time = frame[frame["time"] == value]
53
+ events = int(at_time["event"].sum())
54
+ censored = int(len(at_time) - events)
55
+ if at_risk > 0:
56
+ survival *= 1 - events / at_risk
57
+ if at_risk - events > 0 and events > 0:
58
+ cumulative += events / (at_risk * (at_risk - events))
59
+ se = survival * np.sqrt(cumulative) if survival > 0 else 0.0
60
+ if 0 < survival < 1 and se > 0:
61
+ log_survival = np.log(survival)
62
+ transform = np.log(-log_survival)
63
+ transform_se = se / abs(survival * log_survival)
64
+ ci_low = float(np.exp(-np.exp(transform + z_value * transform_se)))
65
+ ci_high = float(np.exp(-np.exp(transform - z_value * transform_se)))
66
+ else:
67
+ ci_low = max(0.0, survival - z_value * se)
68
+ ci_high = min(1.0, survival + z_value * se)
69
+ rows.append(
70
+ {
71
+ "Time": value,
72
+ "At Risk": at_risk,
73
+ "Events": events,
74
+ "Censored": censored,
75
+ "Survival": survival,
76
+ "Std Error": se,
77
+ "CI Low": ci_low,
78
+ "CI High": ci_high,
79
+ }
80
+ )
81
+ return pd.DataFrame(rows)
82
+
83
+
84
+ def kaplan_meier(
85
+ df: pd.DataFrame,
86
+ time: str,
87
+ event: str,
88
+ group: str | None = None,
89
+ event_value: Any | None = None,
90
+ confidence: float = 0.95,
91
+ ) -> AnalysisResult:
92
+ if not (0 < confidence < 1):
93
+ raise ValueError("Confidence must be between 0 and 1.")
94
+ for column in [time, event] + ([group] if group else []):
95
+ if column not in df.columns:
96
+ raise KeyError(column)
97
+ frame = df.loc[:, [time, event] + ([group] if group else [])].copy()
98
+ frame[time] = pd.to_numeric(frame[time], errors="coerce")
99
+ frame["__event__"] = _event_indicator(frame[event], event_value)
100
+ frame = frame.dropna(subset=[time, "__event__"])
101
+ if frame.empty:
102
+ raise ValueError("No valid survival times.")
103
+ frames = []
104
+ if group and group in frame.columns:
105
+ for label, chunk in frame.groupby(group, dropna=False, sort=True):
106
+ table = _km_table(chunk[time].to_numpy(), chunk["__event__"].to_numpy(), confidence)
107
+ table.insert(0, "Group", "Missing" if pd.isna(label) else str(label))
108
+ frames.append(table)
109
+ combined = pd.concat(frames, ignore_index=True)
110
+ else:
111
+ combined = _km_table(frame[time].to_numpy(), frame["__event__"].to_numpy(), confidence)
112
+ result = AnalysisResult(
113
+ title="Kaplan-Meier Survival",
114
+ analysis_type="kaplan_meier",
115
+ params={"time": time, "event": event, "group": group, "event_value": event_value, "confidence": confidence},
116
+ )
117
+ result.add_table("Survival Estimates", combined)
118
+ plot_frame = combined.copy()
119
+ if "Group" not in plot_frame.columns:
120
+ plot_frame["Group"] = "All"
121
+ result.add_plot("survival", {"time": "Time", "survival": "Survival", "group": "Group", "lower": "CI Low", "upper": "CI High"}, title="Kaplan-Meier Curve", data=plot_frame)
122
+ events = int(frame["__event__"].sum())
123
+ result.summary = f"{len(frame)} subjects, {events} events, {len(frame) - events} censored."
124
+ if group and frame[group].nunique() == 2:
125
+ logrank = logrank_test(df, time, event, group, event_value)
126
+ result.tables.extend(logrank.tables)
127
+ result.summary += " " + logrank.summary
128
+ return result
129
+
130
+
131
+ def logrank_test(
132
+ df: pd.DataFrame,
133
+ time: str,
134
+ event: str,
135
+ group: str,
136
+ event_value: Any | None = None,
137
+ ) -> AnalysisResult:
138
+ frame = df.loc[:, [time, event, group]].copy()
139
+ frame[time] = pd.to_numeric(frame[time], errors="coerce")
140
+ frame["__event__"] = _event_indicator(frame[event], event_value)
141
+ frame = frame.dropna(subset=[time, group, "__event__"])
142
+ levels = list(pd.unique(frame[group]))
143
+ if len(levels) != 2:
144
+ raise ValueError("Log-rank test requires exactly two groups.")
145
+ expected = observed = variance = 0.0
146
+ for value in np.sort(frame[time].unique()):
147
+ at_time = frame[frame[time] == value]
148
+ total_at_risk = int((frame[time] >= value).sum())
149
+ total_events = int(at_time["__event__"].sum())
150
+ if total_at_risk <= 1:
151
+ continue
152
+ group_at_risk = int(((frame[group] == levels[0]) & (frame[time] >= value)).sum())
153
+ group_events = int(((at_time[group] == levels[0]) & (at_time["__event__"] == 1)).sum())
154
+ observed += group_events
155
+ expected += total_events * group_at_risk / total_at_risk
156
+ if total_at_risk > 1:
157
+ variance += (
158
+ total_events
159
+ * (group_at_risk / total_at_risk)
160
+ * (1 - group_at_risk / total_at_risk)
161
+ * (total_at_risk - total_events)
162
+ / (total_at_risk - 1)
163
+ )
164
+ chi2 = (observed - expected) ** 2 / variance if variance > 0 else np.nan
165
+ pvalue = stats.chi2.sf(chi2, 1) if variance > 0 else np.nan
166
+ result = AnalysisResult(
167
+ title="Log-Rank Test",
168
+ analysis_type="logrank",
169
+ params={"time": time, "event": event, "group": group, "event_value": event_value},
170
+ )
171
+ result.add_table(
172
+ "Log-Rank Test",
173
+ pd.DataFrame(
174
+ [
175
+ {
176
+ "Group 1": str(levels[0]),
177
+ "Group 2": str(levels[1]),
178
+ "Observed": observed,
179
+ "Expected": expected,
180
+ "Chi-Square": chi2,
181
+ "df": 1,
182
+ "p-value": pvalue,
183
+ "Significance": p_stars(pvalue),
184
+ }
185
+ ]
186
+ ),
187
+ )
188
+ result.summary = f"Log-rank chi-square = {chi2:.4g}, p = {pvalue:.4g}."
189
+ return result
190
+
191
+
192
+ def cox_regression(
193
+ df: pd.DataFrame,
194
+ time: str,
195
+ event: str,
196
+ predictors: list[str],
197
+ event_value: Any | None = None,
198
+ ties: str = "efron",
199
+ cluster: str | None = None,
200
+ ) -> AnalysisResult:
201
+ try:
202
+ from statsmodels.duration.hazard_regression import PHReg
203
+ except Exception as exc:
204
+ raise ValueError(f"Cox regression is unavailable: {exc}") from exc
205
+ if not predictors:
206
+ raise ValueError("Choose at least one predictor.")
207
+ frame = df.loc[:, [time, event] + predictors + ([cluster] if cluster and cluster in df.columns else [])].copy()
208
+ frame[time] = pd.to_numeric(frame[time], errors="coerce")
209
+ frame["__event__"] = _event_indicator(frame[event], event_value)
210
+ frame = frame.dropna()
211
+ if len(frame) < len(predictors) + 2:
212
+ raise ValueError("Not enough complete observations.")
213
+ design = pd.get_dummies(frame[predictors], drop_first=True, dtype=float)
214
+ design = design.loc[:, design.nunique() > 1]
215
+ if design.empty:
216
+ raise ValueError("Predictors have no variation.")
217
+ try:
218
+ model = PHReg(frame[time].to_numpy(), design.to_numpy(dtype=float), status=frame["__event__"].to_numpy(), ties=ties)
219
+ fit = model.fit(groups=frame[cluster].to_numpy() if cluster and cluster in frame.columns else None)
220
+ except Exception as exc:
221
+ raise ValueError(f"Cox model failed: {exc}") from exc
222
+ names = list(design.columns)
223
+ conf = np.asarray(fit.conf_int())
224
+ frame_result = pd.DataFrame(
225
+ {
226
+ "Term": names,
227
+ "Coefficient": fit.params,
228
+ "Hazard Ratio": np.exp(fit.params),
229
+ "Std Error": fit.bse,
230
+ "z": fit.tvalues,
231
+ "p-value": fit.pvalues,
232
+ "HR CI Low": np.exp(conf[:, 0]),
233
+ "HR CI High": np.exp(conf[:, 1]),
234
+ }
235
+ )
236
+ frame_result["Significance"] = frame_result["p-value"].map(p_stars)
237
+ result = AnalysisResult(
238
+ title="Cox Proportional Hazards",
239
+ analysis_type="cox_regression",
240
+ params={"time": time, "event": event, "predictors": predictors, "event_value": event_value, "ties": ties, "cluster": cluster},
241
+ )
242
+ result.add_table("Coefficients", frame_result)
243
+ try:
244
+ residuals = np.asarray(fit.schoenfeld_residuals, dtype=float)
245
+ event_mask = frame["__event__"].to_numpy() == 1
246
+ times = frame[time].to_numpy(dtype=float)
247
+ ph_rows = []
248
+ for index, name in enumerate(names):
249
+ if residuals.shape[0] != len(frame) or event_mask.sum() < 3:
250
+ continue
251
+ corr, pvalue = stats.pearsonr(residuals[event_mask, index], times[event_mask])
252
+ ph_rows.append({"Term": name, "Schoenfeld/time correlation": float(corr), "p-value": float(pvalue)})
253
+ if ph_rows:
254
+ result.add_table("Proportional Hazards Check", pd.DataFrame(ph_rows))
255
+ result.notes = "Proportional-hazards check uses event-time correlations of scaled Schoenfeld residuals; interpret as a diagnostic screen."
256
+ except Exception:
257
+ pass
258
+ number_parameters = len(fit.params)
259
+ aic = getattr(fit, "aic", -2 * fit.llf + 2 * number_parameters)
260
+ bic = getattr(fit, "bic", -2 * fit.llf + number_parameters * np.log(len(frame)))
261
+ result.add_table(
262
+ "Model Metrics",
263
+ pd.DataFrame(
264
+ [
265
+ ("N", len(frame)),
266
+ ("Events", int(frame["__event__"].sum())),
267
+ ("Log likelihood", fit.llf),
268
+ ("AIC", aic),
269
+ ("BIC", bic),
270
+ ],
271
+ columns=["Metric", "Value"],
272
+ ),
273
+ )
274
+ result.summary = f"Cox model with {len(names)} terms over {len(frame)} subjects and {int(frame['__event__'].sum())} events."
275
+ return result
276
+
277
+
278
+ # ---------------------------------------------------------------------------
279
+ # Competing risks
280
+ # ---------------------------------------------------------------------------
281
+
282
+ def cumulative_incidence(
283
+ df: pd.DataFrame,
284
+ time: str,
285
+ event: str,
286
+ event_value: Any | None = None,
287
+ competing_value: Any | None = None,
288
+ group: str | None = None,
289
+ ) -> AnalysisResult:
290
+ frame = df.loc[:, [time, event] + ([group] if group else [])].copy()
291
+ frame[time] = pd.to_numeric(frame[time], errors="coerce")
292
+ frame["__code__"] = _cause_code(frame[event], event_value, competing_value)
293
+ frame = frame.dropna(subset=[time, "__code__"])
294
+ if frame.empty:
295
+ raise ValueError("No valid survival times.")
296
+ frames = []
297
+ groups = frame.groupby(group, dropna=False, sort=True) if group and group in frame.columns else [(None, frame)]
298
+ for label, chunk in groups:
299
+ table = _aalen_johansen(chunk[time].to_numpy(), chunk["__code__"].to_numpy())
300
+ if group:
301
+ table.insert(0, "Group", "Missing" if pd.isna(label) else str(label))
302
+ frames.append(table)
303
+ combined = pd.concat(frames, ignore_index=True)
304
+ result = AnalysisResult(
305
+ title="Cumulative Incidence (Competing Risks)",
306
+ analysis_type="cumulative_incidence",
307
+ params={"time": time, "event": event, "event_value": event_value, "competing_value": competing_value, "group": group},
308
+ )
309
+ result.add_table("Cumulative Incidence", combined)
310
+ plot_frame = combined.copy()
311
+ if "Group" not in plot_frame.columns:
312
+ plot_frame["Group"] = "All"
313
+ result.add_plot(
314
+ "survival",
315
+ {"time": "Time", "survival": "CIF Event", "group": "Group"},
316
+ title="Cumulative Incidence of the Event of Interest",
317
+ data=plot_frame,
318
+ )
319
+ result.summary = f"Cumulative incidence across {frame[time].nunique()} distinct failure times."
320
+ if group and frame[group].nunique() == 2:
321
+ try:
322
+ result.tables.extend(_cause_specific_logrank(df, time, event, group, event_value, competing_value).tables)
323
+ except Exception:
324
+ pass
325
+ return result
326
+
327
+
328
+ def _cause_code(values: pd.Series, event_value: Any | None, competing_value: Any | None) -> pd.Series:
329
+ event_mask = (
330
+ _matches(values, event_value).fillna(False)
331
+ if event_value is not None
332
+ else (_event_indicator(values, None) == 1)
333
+ )
334
+ competing_mask = (
335
+ _matches(values, competing_value).fillna(False)
336
+ if competing_value is not None
337
+ else pd.Series(False, index=values.index)
338
+ )
339
+ code = pd.Series(0.0, index=values.index)
340
+ code[event_mask] = 1.0
341
+ code[competing_mask & ~event_mask] = 2.0
342
+ code[values.isna()] = np.nan
343
+ return code
344
+
345
+
346
+ def _aalen_johansen(time: np.ndarray, code: np.ndarray) -> pd.DataFrame:
347
+ frame = pd.DataFrame({"time": time, "code": code}).dropna()
348
+ frame = frame[frame["time"] >= 0]
349
+ unique_times = np.sort(frame["time"].unique())
350
+ survival = 1.0
351
+ cif1 = 0.0
352
+ cif2 = 0.0
353
+ rows = []
354
+ for value in unique_times:
355
+ at_risk = int((frame["time"] >= value).sum())
356
+ at_time = frame[frame["time"] == value]
357
+ d1 = int((at_time["code"] == 1).sum())
358
+ d2 = int((at_time["code"] == 2).sum())
359
+ if at_risk > 0:
360
+ cif1 += survival * d1 / at_risk
361
+ cif2 += survival * d2 / at_risk
362
+ survival *= 1 - (d1 + d2) / at_risk
363
+ rows.append({"Time": value, "At Risk": at_risk, "Events": d1, "Competing": d2, "Overall Survival": survival, "CIF Event": cif1, "CIF Competing": cif2})
364
+ return pd.DataFrame(rows)
365
+
366
+
367
+
368
+
369
+ def _cause_specific_logrank(df, time, event, group, event_value, competing_value) -> AnalysisResult:
370
+ frame = df.loc[:, [time, event, group]].copy()
371
+ frame[time] = pd.to_numeric(frame[time], errors="coerce")
372
+ frame["__code__"] = _cause_code(frame[event], event_value, competing_value)
373
+ frame = frame.dropna(subset=[time, group, "__code__"])
374
+ levels = list(pd.unique(frame[group]))
375
+ if len(levels) != 2:
376
+ raise ValueError("The test requires exactly two groups.")
377
+ observed = expected = variance = 0.0
378
+ for value in np.sort(frame[time].unique()):
379
+ at_time = frame[frame[time] == value]
380
+ at_risk = int((frame[time] >= value).sum())
381
+ total_events = int((at_time["__code__"] == 1).sum())
382
+ if at_risk <= 1:
383
+ continue
384
+ group_at_risk = int(((frame[group] == levels[0]) & (frame[time] >= value)).sum())
385
+ group_events = int(((at_time[group] == levels[0]) & (at_time["__code__"] == 1)).sum())
386
+ observed += group_events
387
+ expected += total_events * group_at_risk / at_risk
388
+ variance += total_events * (group_at_risk / at_risk) * (1 - group_at_risk / at_risk) * (at_risk - total_events) / (at_risk - 1)
389
+ chi2 = (observed - expected) ** 2 / variance if variance > 0 else np.nan
390
+ pvalue = float(stats.chi2.sf(chi2, 1)) if variance > 0 else np.nan
391
+ result = AnalysisResult(title="Cause-Specific Log-Rank Test", analysis_type="cause_specific_logrank", params={"time": time, "event": event, "group": group})
392
+ result.add_table("Cause-Specific Log-Rank", pd.DataFrame([{"Group 1": str(levels[0]), "Group 2": str(levels[1]), "Observed": observed, "Expected": expected, "Chi-Square": chi2, "df": 1, "p-value": pvalue, "Significance": p_stars(pvalue)}]))
393
+ result.summary = f"Cause-specific log-rank chi-square = {chi2:.4g}, p = {pvalue:.4g}."
394
+ return result
395
+
396
+
397
+ # ---------------------------------------------------------------------------
398
+ # Weibull / accelerated failure time reliability
399
+ # ---------------------------------------------------------------------------
400
+
401
+ def weibull_aft(
402
+ df: pd.DataFrame,
403
+ time: str,
404
+ event: str,
405
+ predictors: list[str] | None = None,
406
+ distribution: str = "weibull",
407
+ event_value: Any | None = None,
408
+ ) -> AnalysisResult:
409
+ from scipy.optimize import minimize
410
+
411
+ predictors = predictors or []
412
+ frame = df.loc[:, [time, event] + predictors].copy()
413
+ frame[time] = pd.to_numeric(frame[time], errors="coerce")
414
+ frame["__event__"] = _event_indicator(frame[event], event_value)
415
+ frame = frame.dropna()
416
+ frame = frame[frame[time] > 0]
417
+ if len(frame) < 5:
418
+ raise ValueError("At least five positive failure times are required.")
419
+ design = pd.get_dummies(frame[predictors], drop_first=True, dtype=float) if predictors else pd.DataFrame(index=frame.index)
420
+ design = pd.concat([pd.Series(1.0, index=frame.index, name="Intercept"), design], axis=1)
421
+ X = design.to_numpy(dtype=float)
422
+ t = frame[time].to_numpy(dtype=float)
423
+ censored = (frame["__event__"] == 0).to_numpy()
424
+ distribution = distribution.lower()
425
+ if distribution not in {"weibull", "exponential", "lognormal", "loglogistic"}:
426
+ raise ValueError(f"Unsupported AFT distribution: {distribution}.")
427
+
428
+ def unpack(theta):
429
+ log_shape = theta[0]
430
+ beta = theta[1:]
431
+ return log_shape, beta
432
+
433
+ def negative_loglik(theta):
434
+ log_shape, beta = unpack(theta)
435
+ shape = np.exp(log_shape)
436
+ log_scale = X @ beta
437
+ scale = np.exp(np.clip(log_scale, -50, 50))
438
+ if distribution == "exponential":
439
+ shape = 1.0
440
+ if distribution in {"lognormal", "loglogistic"}:
441
+ log_t = np.log(np.clip(t, 1e-12, None))
442
+ if distribution == "lognormal":
443
+ sigma = np.exp(log_shape)
444
+ log_pdf = stats.norm.logpdf(log_t, loc=log_scale, scale=sigma) - log_t
445
+ log_survival = stats.norm.logsf(log_t, loc=log_scale, scale=sigma)
446
+ else:
447
+ ratio = np.clip(t / scale, 1e-12, None)
448
+ power = np.power(ratio, shape)
449
+ log_pdf = np.log(shape) - log_scale + (shape - 1) * np.log(ratio) - 2 * np.log1p(power)
450
+ log_survival = -np.log1p(power)
451
+ ll = np.where(censored, log_survival, log_pdf)
452
+ return -float(np.sum(ll))
453
+ ratio = t / scale
454
+ log_hazard = np.log(shape) - np.log(scale) + (shape - 1) * np.log(np.clip(ratio, 1e-12, None))
455
+ log_survival = -np.power(np.clip(ratio, 1e-12, None), shape)
456
+ ll = np.where(censored, log_survival, log_hazard + log_survival)
457
+ return -float(np.sum(ll))
458
+
459
+ theta0 = np.zeros(1 + X.shape[1])
460
+ theta0[0] = 0.0
461
+ try:
462
+ outcome = minimize(negative_loglik, theta0, method="BFGS", options={"maxiter": 2000})
463
+ if not outcome.success:
464
+ outcome = minimize(negative_loglik, theta0, method="Nelder-Mead", options={"maxiter": 5000})
465
+ except Exception as exc:
466
+ raise ValueError(f"Weibull fit failed: {exc}") from exc
467
+ log_shape, beta = unpack(outcome.x)
468
+ shape = float(np.exp(log_shape))
469
+ if distribution == "exponential":
470
+ shape = 1.0
471
+ loglik = -float(outcome.fun)
472
+ params_count = X.shape[1] if distribution == "exponential" else 1 + X.shape[1]
473
+ aic = 2 * params_count - 2 * loglik
474
+ bic = params_count * np.log(len(t)) - 2 * loglik
475
+ reference = np.zeros(design.shape[1])
476
+ for index, name in enumerate(design.columns):
477
+ values = design.iloc[:, index].to_numpy()
478
+ if name == "Intercept":
479
+ reference[index] = 1.0
480
+ elif np.isin(np.unique(values), [0, 1]).all():
481
+ reference[index] = 0.0
482
+ else:
483
+ reference[index] = float(values.mean())
484
+ scale_reference = float(np.exp(reference @ beta))
485
+ import math as _math
486
+
487
+ if distribution == "lognormal":
488
+ sigma = shape
489
+ mean_life = scale_reference * math.exp(sigma**2 / 2)
490
+ median_life = scale_reference
491
+ b10 = scale_reference * math.exp(-1.2815515655446004 * sigma)
492
+ shape_label = "Sigma (lognormal)"
493
+ elif distribution == "loglogistic":
494
+ median_life = scale_reference
495
+ mean_life = scale_reference * math.pi / shape / math.sin(math.pi / shape) if shape > 1 else np.inf
496
+ b10 = scale_reference * (1 / 9) ** (1 / shape)
497
+ shape_label = "Shape (loglogistic)"
498
+ else:
499
+ mean_life = scale_reference * float(_math.gamma(1 + 1 / shape))
500
+ median_life = scale_reference * (_math.log(2)) ** (1 / shape)
501
+ b10 = scale_reference * (_math.log(1 / 0.9)) ** (1 / shape)
502
+ shape_label = "Shape (Weibull)"
503
+ param_rows = [{"Parameter": shape_label, "Estimate": shape}]
504
+ names = list(design.columns)
505
+ for index, name in enumerate(names):
506
+ if name == "Intercept":
507
+ param_rows.append({"Parameter": "Intercept (log-scale)", "Estimate": float(beta[index])})
508
+ else:
509
+ param_rows.append({"Parameter": name, "Estimate": float(beta[index]), "Time Ratio": float(np.exp(beta[index]))})
510
+ result = AnalysisResult(
511
+ title=f"{distribution.title()} Reliability / AFT: {time}",
512
+ analysis_type="weibull_aft",
513
+ params={"time": time, "event": event, "predictors": predictors, "distribution": distribution, "event_value": event_value},
514
+ )
515
+ result.add_table("Parameters", pd.DataFrame(param_rows))
516
+ result.add_table("Model Metrics", pd.DataFrame([("Distribution", distribution.title()), ("N", len(t)), ("Events", int((~censored).sum())), ("Log likelihood", loglik), ("AIC", aic), ("BIC", bic), ("Shape", shape), ("Scale (reference)", scale_reference)], columns=["Metric", "Value"]))
517
+ result.add_table("Life Estimates", pd.DataFrame([{"Mean Life": mean_life, "Median Life": median_life, "B10 Life": b10}], index=["Reference"]).reset_index().rename(columns={"index": "Profile"}))
518
+ try:
519
+ result.add_plot(
520
+ "weibull_plot",
521
+ {"time": t.tolist(), "censored": censored.tolist(), "shape": shape, "scale": scale_reference},
522
+ title="Weibull Probability Plot",
523
+ )
524
+ except Exception:
525
+ pass
526
+ result.summary = f"{distribution.title()} fit: shape = {shape:.4g}, AIC = {aic:.4g}, N = {len(t)}."
527
+ return result
528
+
529
+
530
+ def reliability_zero_failures(
531
+ test_time: float,
532
+ units: int = 1,
533
+ confidence: float = 0.95,
534
+ shape: float = 1.0,
535
+ ) -> AnalysisResult:
536
+ if test_time <= 0 or units <= 0:
537
+ raise ValueError("Test time and units must be positive.")
538
+ if not (0 < confidence < 1):
539
+ raise ValueError("Confidence must be between 0 and 1.")
540
+ if shape <= 0:
541
+ raise ValueError("Shape must be positive.")
542
+ total_time = float(test_time) * int(units)
543
+ failure_probability = 1 - confidence ** (1 / int(units))
544
+ reliability_at_test = float(confidence ** (1 / int(units)))
545
+ scale_lower = test_time / ((-math.log(confidence) / int(units)) ** (1 / shape))
546
+ mtbf_lower = scale_lower * math.gamma(1 + 1 / shape)
547
+ failure_rate_upper = 1 / mtbf_lower if mtbf_lower else np.inf
548
+ result = AnalysisResult(
549
+ title="Reliability with Zero Failures",
550
+ analysis_type="reliability_zero_failures",
551
+ params={"test_time": test_time, "units": units, "confidence": confidence, "shape": shape},
552
+ )
553
+ result.add_table(
554
+ "Reliability Demonstration",
555
+ pd.DataFrame([{
556
+ "Units": units,
557
+ "Test Time per Unit": test_time,
558
+ "Total Time": total_time,
559
+ "Confidence": confidence,
560
+ "Weibull Shape": shape,
561
+ "Failure Probability Upper Bound": failure_probability,
562
+ "Failure Rate Upper Bound": failure_rate_upper,
563
+ "Weibull Scale Lower Bound": scale_lower,
564
+ "MTBF Lower Bound": mtbf_lower,
565
+ "Reliability at Test Time": reliability_at_test,
566
+ }]),
567
+ )
568
+ result.summary = f"With zero failures over {total_time:g} unit-hours, reliability at test time >= {reliability_at_test:.4g} at {confidence:.0%} confidence (Weibull shape {shape:g})."
569
+ return result
570
+
571
+
572
+ def interval_censored_weibull(
573
+ df: pd.DataFrame,
574
+ lower: str,
575
+ upper: str,
576
+ distribution: str = "weibull",
577
+ ) -> AnalysisResult:
578
+ from scipy.optimize import minimize
579
+
580
+ if lower not in df.columns or upper not in df.columns:
581
+ raise KeyError("Lower and upper time columns are required.")
582
+ frame = df.loc[:, [lower, upper]].copy()
583
+ frame[lower] = pd.to_numeric(frame[lower], errors="coerce").fillna(0.0)
584
+ frame[upper] = pd.to_numeric(frame[upper], errors="coerce")
585
+ frame = frame.dropna(subset=[lower])
586
+ if frame.empty:
587
+ raise ValueError("No valid interval-censored observations.")
588
+ low = np.maximum(frame[lower].to_numpy(dtype=float), 0.0)
589
+ high = frame[upper].to_numpy(dtype=float)
590
+ distribution = distribution.lower()
591
+
592
+ def survival(time: np.ndarray, shape: float, scale: float) -> np.ndarray:
593
+ if distribution == "lognormal":
594
+ return stats.norm.sf(np.log(np.clip(time, 1e-12, None)), loc=np.log(scale), scale=shape)
595
+ ratio = np.clip(time / scale, 1e-12, None)
596
+ return np.exp(-np.power(ratio, shape))
597
+
598
+ def negative_loglik(theta: np.ndarray) -> float:
599
+ shape = float(np.exp(theta[0]))
600
+ scale = float(np.exp(theta[1]))
601
+ exact = np.isfinite(high) & np.isclose(low, high)
602
+ right = ~np.isfinite(high)
603
+ interval = np.isfinite(high) & (high > low) & ~exact
604
+ left = (low <= 0) & np.isfinite(high) & ~exact
605
+ ll = np.zeros(len(low))
606
+ if exact.any():
607
+ t = low[exact]
608
+ if distribution == "lognormal":
609
+ ll[exact] = stats.norm.logpdf(np.log(np.clip(t, 1e-12, None)), loc=np.log(scale), scale=shape) - np.log(np.clip(t, 1e-12, None))
610
+ else:
611
+ ratio = np.clip(t / scale, 1e-12, None)
612
+ ll[exact] = np.log(shape) - np.log(scale) + (shape - 1) * np.log(ratio) - np.power(ratio, shape)
613
+ if right.any():
614
+ ll[right] = np.log(np.clip(survival(low[right], shape, scale), 1e-12, None))
615
+ if interval.any():
616
+ ll[interval] = np.log(np.clip(survival(low[interval], shape, scale) - survival(high[interval], shape, scale), 1e-12, None))
617
+ if left.any():
618
+ ll[left] = np.log(np.clip(1 - survival(high[left], shape, scale), 1e-12, None))
619
+ return -float(np.sum(ll))
620
+
621
+ outcome = minimize(negative_loglik, np.array([0.0, 0.0]), method="Nelder-Mead", options={"maxiter": 10000})
622
+ if not outcome.success:
623
+ outcome = minimize(negative_loglik, outcome.x, method="BFGS", options={"maxiter": 10000})
624
+ shape = float(np.exp(outcome.x[0]))
625
+ scale = float(np.exp(outcome.x[1]))
626
+ loglik = -float(outcome.fun)
627
+ aic = 4 - 2 * loglik
628
+ bic = 2 * np.log(len(low)) - 2 * loglik
629
+ result = AnalysisResult(
630
+ title=f"Interval-Censored {distribution.title()} Fit",
631
+ analysis_type="interval_censored_weibull",
632
+ params={"lower": lower, "upper": upper, "distribution": distribution},
633
+ )
634
+ result.add_table("Parameters", pd.DataFrame([{"Parameter": "Shape / Sigma", "Estimate": shape}, {"Parameter": "Scale", "Estimate": scale}]))
635
+ result.add_table("Model Metrics", pd.DataFrame([{"Distribution": distribution.title(), "N": len(low), "Log likelihood": loglik, "AIC": aic, "BIC": bic}]))
636
+ result.summary = f"Interval-censored {distribution} fit: shape = {shape:.4g}, scale = {scale:.4g}, N = {len(low)}."
637
+ return result