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
statstudio/io/odbc.py ADDED
@@ -0,0 +1,334 @@
1
+ from __future__ import annotations
2
+
3
+ import getpass
4
+ import re
5
+ from dataclasses import asdict, dataclass
6
+ from decimal import Decimal
7
+ from datetime import date, datetime
8
+ from typing import Any
9
+
10
+ import pandas as pd
11
+
12
+ from statstudio.core.table import DataTable
13
+
14
+ try: # pragma: no cover - optional runtime dependency
15
+ import pyodbc
16
+ except Exception: # pragma: no cover
17
+ pyodbc = None # type: ignore[assignment]
18
+
19
+ try: # pragma: no cover - optional runtime dependency
20
+ import keyring
21
+ except Exception: # pragma: no cover
22
+ keyring = None # type: ignore[assignment]
23
+
24
+
25
+ SERVICE_NAME = "statstudio-odbc"
26
+ _SENSITIVE_KEYS = {"pwd", "password", "uid", "user", "user id", "username", "pass"}
27
+ _WRITE_KEYWORDS = re.compile(
28
+ r"\b(insert|update|delete|merge|drop|alter|create|truncate|grant|revoke|call|exec|execute|attach|detach|vacuum|into)\b",
29
+ re.IGNORECASE,
30
+ )
31
+
32
+
33
+ class OdbcError(RuntimeError):
34
+ pass
35
+
36
+
37
+ def _odbc_value(value: str) -> str:
38
+ text = str(value)
39
+ if any(character in text for character in ";{}") or text != text.strip():
40
+ return "{" + text.replace("}", "}}") + "}"
41
+ return text
42
+
43
+
44
+ def _scrub_extra(extra: str) -> str:
45
+ parts = []
46
+ for part in str(extra or "").replace("\r", ";").replace("\n", ";").split(";"):
47
+ if not part.strip():
48
+ continue
49
+ key = part.split("=", 1)[0].strip().lower()
50
+ if key in _SENSITIVE_KEYS:
51
+ continue
52
+ parts.append(part.strip())
53
+ return ";".join(parts)
54
+
55
+
56
+ def quote_identifier(name: str) -> str:
57
+ return '"' + str(name).replace('"', '""') + '"'
58
+
59
+
60
+ _quote_identifier = quote_identifier
61
+
62
+
63
+ def validate_read_query(query: str) -> str:
64
+ text = str(query or "").strip()
65
+ if not text:
66
+ raise OdbcError("Enter a SQL query.")
67
+ body = text[:-1].rstrip() if text.endswith(";") else text
68
+ if ";" in body:
69
+ raise OdbcError("Only one read-only SQL statement can be previewed or imported at a time.")
70
+ first = body.lstrip().split(None, 1)[0].lower()
71
+ if first not in {"select", "with", "show", "describe", "desc", "explain"}:
72
+ raise OdbcError("Only read-only SELECT/WITH/EXPLAIN queries are allowed.")
73
+ if _WRITE_KEYWORDS.search(body):
74
+ raise OdbcError("The SQL query contains a statement that can modify the database.")
75
+ return text
76
+
77
+
78
+ @dataclass
79
+ class OdbcProfile:
80
+ name: str = "New Connection"
81
+ dsn: str = ""
82
+ driver: str = ""
83
+ server: str = ""
84
+ database: str = ""
85
+ username: str = ""
86
+ password: str = ""
87
+ trusted_connection: bool = False
88
+ extra: str = ""
89
+ use_dsn: bool = True
90
+ remember_password: bool = False
91
+
92
+ def connection_string(self) -> str:
93
+ if self.use_dsn and self.dsn:
94
+ parts = [f"DSN={_odbc_value(self.dsn)}"]
95
+ if self.username:
96
+ parts.append(f"UID={_odbc_value(self.username)}")
97
+ if self.password:
98
+ parts.append(f"PWD={_odbc_value(self.password)}")
99
+ if self.extra:
100
+ parts.append(self.extra)
101
+ return ";".join(parts) + ";"
102
+ if not self.driver:
103
+ raise OdbcError("Choose an ODBC driver or a DSN.")
104
+ parts = [f"DRIVER={{{self.driver}}}"]
105
+ if self.server:
106
+ parts.append(f"SERVER={_odbc_value(self.server)}")
107
+ if self.database:
108
+ parts.append(f"DATABASE={_odbc_value(self.database)}")
109
+ if self.trusted_connection:
110
+ parts.append("Trusted_Connection=yes")
111
+ else:
112
+ if self.username:
113
+ parts.append(f"UID={_odbc_value(self.username)}")
114
+ if self.password:
115
+ parts.append(f"PWD={_odbc_value(self.password)}")
116
+ if self.extra:
117
+ parts.append(self.extra)
118
+ return ";".join(parts) + ";"
119
+
120
+ def to_dict(self) -> dict[str, Any]:
121
+ payload = asdict(self)
122
+ payload["password"] = ""
123
+ payload["extra"] = _scrub_extra(self.extra)
124
+ return payload
125
+
126
+ @classmethod
127
+ def from_dict(cls, payload: dict[str, Any]) -> "OdbcProfile":
128
+ known = {f.name for f in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
129
+ profile = cls(**{k: v for k, v in payload.items() if k in known})
130
+ if profile.remember_password:
131
+ profile.password = load_password(profile.name) or ""
132
+ return profile
133
+
134
+
135
+ def available_drivers() -> list[str]:
136
+ if pyodbc is None:
137
+ return []
138
+ try:
139
+ return list(pyodbc.drivers())
140
+ except Exception:
141
+ return []
142
+
143
+
144
+ def available_dsns() -> dict[str, str]:
145
+ if pyodbc is None:
146
+ return {}
147
+ try:
148
+ return dict(pyodbc.dataSources())
149
+ except Exception:
150
+ return {}
151
+
152
+
153
+ def default_username() -> str:
154
+ try:
155
+ return getpass.getuser()
156
+ except Exception:
157
+ return ""
158
+
159
+
160
+ def _require_pyodbc() -> None:
161
+ if pyodbc is None:
162
+ raise OdbcError("pyodbc is not installed. Install it with: pip install pyodbc")
163
+
164
+
165
+ def _coerce_frame(frame: pd.DataFrame) -> pd.DataFrame:
166
+ """Convert driver-native scalar types (Decimal, date) into pandas-friendly types."""
167
+ for column in frame.columns:
168
+ series = frame[column]
169
+ if series.dtype != object:
170
+ continue
171
+ non_missing = series.dropna()
172
+ if non_missing.empty:
173
+ continue
174
+ sample = non_missing.iloc[:100]
175
+ if all(isinstance(value, Decimal) for value in sample):
176
+ converted = series.map(lambda value: float(value) if isinstance(value, Decimal) else value)
177
+ if pd.to_numeric(converted, errors="coerce").notna().sum() == len(non_missing):
178
+ frame[column] = pd.to_numeric(converted, errors="coerce")
179
+ elif all(isinstance(value, (date, datetime)) for value in sample):
180
+ frame[column] = pd.to_datetime(series, errors="coerce")
181
+ return frame
182
+
183
+
184
+ def connect(profile: OdbcProfile, timeout: int = 15):
185
+ _require_pyodbc()
186
+ try:
187
+ return pyodbc.connect(profile.connection_string(), timeout=timeout)
188
+ except Exception as exc:
189
+ raise OdbcError(str(exc)) from exc
190
+
191
+
192
+ def test_connection(profile: OdbcProfile) -> tuple[bool, str]:
193
+ try:
194
+ connection = connect(profile)
195
+ cursor = connection.cursor()
196
+ cursor.execute("SELECT 1")
197
+ cursor.fetchone()
198
+ cursor.close()
199
+ connection.close()
200
+ return True, "Connection successful."
201
+ except Exception as exc:
202
+ return False, str(exc)
203
+
204
+
205
+ def list_schemas(profile: OdbcProfile) -> list[str]:
206
+ connection = connect(profile)
207
+ try:
208
+ cursor = connection.cursor()
209
+ schemas = set()
210
+ for row in cursor.tables(tableType="TABLE"):
211
+ schema = row.table_schem or ""
212
+ if schema:
213
+ schemas.add(str(schema))
214
+ return sorted(schemas)
215
+ finally:
216
+ connection.close()
217
+
218
+
219
+ def list_tables(profile: OdbcProfile) -> list[dict[str, str]]:
220
+ connection = connect(profile)
221
+ try:
222
+ cursor = connection.cursor()
223
+ tables = []
224
+ for row in cursor.tables():
225
+ table_type = (row.table_type or "").upper()
226
+ if "TABLE" not in table_type and "VIEW" not in table_type:
227
+ continue
228
+ tables.append(
229
+ {
230
+ "schema": str(row.table_schem or ""),
231
+ "table": str(row.table_name or ""),
232
+ "type": str(row.table_type or ""),
233
+ }
234
+ )
235
+ return sorted(tables, key=lambda item: (item["schema"], item["table"]))
236
+ finally:
237
+ connection.close()
238
+
239
+
240
+ def preview_query(profile: OdbcProfile, query: str, limit: int = 100) -> pd.DataFrame:
241
+ query = validate_read_query(query)
242
+ connection = connect(profile)
243
+ try:
244
+ cursor = connection.cursor()
245
+ cursor.execute(query)
246
+ if cursor.description is None:
247
+ return pd.DataFrame()
248
+ columns = [item[0] for item in cursor.description]
249
+ rows = cursor.fetchmany(limit)
250
+ return _coerce_frame(pd.DataFrame.from_records(rows, columns=columns))
251
+ except Exception as exc:
252
+ raise OdbcError(str(exc)) from exc
253
+ finally:
254
+ connection.close()
255
+
256
+
257
+ def import_query(
258
+ profile: OdbcProfile,
259
+ query: str,
260
+ name: str = "ODBC Query",
261
+ chunk_size: int = 50_000,
262
+ ) -> DataTable:
263
+ query = validate_read_query(query)
264
+ connection = connect(profile)
265
+ frames: list[pd.DataFrame] = []
266
+ try:
267
+ cursor = connection.cursor()
268
+ cursor.execute(query)
269
+ if cursor.description is None:
270
+ raise OdbcError("The query did not return a result set.")
271
+ columns = [item[0] for item in cursor.description]
272
+ while True:
273
+ rows = cursor.fetchmany(chunk_size)
274
+ if not rows:
275
+ break
276
+ frames.append(pd.DataFrame.from_records(rows, columns=columns))
277
+ if sum(len(f) for f in frames) > 20_000_000:
278
+ raise OdbcError("Result set is too large to load into memory.")
279
+ frame = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame(columns=columns)
280
+ frame = _coerce_frame(frame)
281
+ except OdbcError:
282
+ raise
283
+ except Exception as exc:
284
+ raise OdbcError(str(exc)) from exc
285
+ finally:
286
+ connection.close()
287
+ table = DataTable(frame, name=name, source=f"ODBC: {profile.name}")
288
+ table.metadata["odbc"] = {"profile": profile.name, "query": query}
289
+ return table
290
+
291
+
292
+ def import_table(
293
+ profile: OdbcProfile,
294
+ schema: str,
295
+ table_name: str,
296
+ limit: int | None = None,
297
+ ) -> DataTable:
298
+ qualified = (
299
+ f"{_quote_identifier(schema)}.{_quote_identifier(table_name)}"
300
+ if schema
301
+ else _quote_identifier(table_name)
302
+ )
303
+ query = f"SELECT * FROM {qualified}"
304
+ if limit:
305
+ # LIMIT is supported by many engines but not all; use only when requested.
306
+ query += f" LIMIT {int(limit)}"
307
+ return import_query(profile, query, name=table_name)
308
+
309
+
310
+ def save_password(profile: OdbcProfile) -> None:
311
+ if keyring is None:
312
+ return
313
+ try:
314
+ keyring.set_password(SERVICE_NAME, profile.name, profile.password)
315
+ except Exception:
316
+ pass
317
+
318
+
319
+ def load_password(profile_name: str) -> str | None:
320
+ if keyring is None:
321
+ return None
322
+ try:
323
+ return keyring.get_password(SERVICE_NAME, profile_name)
324
+ except Exception:
325
+ return None
326
+
327
+
328
+ def delete_password(profile_name: str) -> None:
329
+ if keyring is None:
330
+ return
331
+ try:
332
+ keyring.delete_password(SERVICE_NAME, profile_name)
333
+ except Exception:
334
+ pass
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ from statstudio.core.table import DataTable
7
+
8
+ _SAMPLE_NAMES = ["Manufacturing", "Gage R&R", "Predictive", "Survival", "Time Series", "Custom DOE"]
9
+
10
+
11
+ def sample_names() -> list[str]:
12
+ return list(_SAMPLE_NAMES)
13
+
14
+
15
+ def _manufacturing() -> DataTable:
16
+ rng = np.random.default_rng(11)
17
+ n = 240
18
+ batch = np.repeat([f"Batch {i}" for i in range(1, 13)], 20)
19
+ date = pd.date_range("2024-01-01", periods=n, freq="D")
20
+ machine = rng.choice(["M1", "M2", "M3"], n)
21
+ operator = rng.choice(["A. Lee", "B. Ortiz", "C. Khan"], n)
22
+ temperature = rng.normal(180, 8, n)
23
+ pressure = rng.normal(60, 4, n) + 0.05 * (temperature - 180)
24
+ speed = rng.normal(120, 10, n)
25
+ strength = 40 + 0.12 * temperature + 0.25 * pressure - 0.08 * speed + rng.normal(0, 2.0, n)
26
+ defects = rng.poisson(np.clip(0.4 + 0.03 * np.sqrt(np.abs(temperature - 180)) - 0.01 * (pressure - 60), 0.05, 5.0), n)
27
+ frame = pd.DataFrame(
28
+ {
29
+ "Batch": batch,
30
+ "Date": date,
31
+ "Machine": machine,
32
+ "Operator": operator,
33
+ "Temperature": temperature.round(2),
34
+ "Pressure": pressure.round(2),
35
+ "Speed": speed.round(2),
36
+ "Strength": strength.round(3),
37
+ "Defects": defects,
38
+ }
39
+ )
40
+ table = DataTable(frame, name="Manufacturing")
41
+ table.specs["Batch"].modeling_type = "nominal"
42
+ table.specs["Machine"].modeling_type = "nominal"
43
+ table.specs["Operator"].modeling_type = "nominal"
44
+ return table
45
+
46
+
47
+ def _gage() -> DataTable:
48
+ rng = np.random.default_rng(21)
49
+ parts = np.repeat(np.arange(1, 11), 6)
50
+ operators = np.tile(np.repeat(["Op 1", "Op 2", "Op 3"], 2), 10)
51
+ true_value = parts * 1.5
52
+ measurement = true_value + rng.normal(0, 0.35, len(parts)) + (operators == "Op 2") * 0.2
53
+ frame = pd.DataFrame({"Part": parts, "Operator": operators, "Measurement": measurement.round(3)})
54
+ table = DataTable(frame, name="Gage R&R")
55
+ table.specs["Part"].modeling_type = "nominal"
56
+ table.specs["Operator"].modeling_type = "nominal"
57
+ return table
58
+
59
+
60
+ def _predictive() -> DataTable:
61
+ rng = np.random.default_rng(31)
62
+ n = 300
63
+ age = rng.normal(45, 12, n)
64
+ income = rng.normal(60000, 15000, n)
65
+ tenure = rng.exponential(6, n)
66
+ churn_score = 0.03 * age - 0.00002 * income - 0.4 * tenure + rng.normal(0, 1.0, n)
67
+ churn = (churn_score > np.median(churn_score)).astype(int)
68
+ revenue = 200 + 0.5 * income / 100 + 12 * tenure + rng.normal(0, 40, n)
69
+ frame = pd.DataFrame(
70
+ {
71
+ "Age": age.round(1),
72
+ "Income": income.round(0),
73
+ "Tenure": tenure.round(2),
74
+ "Churn": churn,
75
+ "Revenue": revenue.round(2),
76
+ }
77
+ )
78
+ table = DataTable(frame, name="Predictive")
79
+ table.specs["Churn"].modeling_type = "nominal"
80
+ return table
81
+
82
+
83
+ def _survival() -> DataTable:
84
+ rng = np.random.default_rng(41)
85
+ n = 200
86
+ group = rng.choice(["Treatment", "Control"], n)
87
+ rate = np.where(group == "Treatment", 0.06, 0.10)
88
+ time = rng.exponential(1 / rate, n).round(2) + 0.5
89
+ censor_time = rng.uniform(5, 25, n)
90
+ event = (time <= censor_time).astype(int)
91
+ observed = np.minimum(time, censor_time)
92
+ frame = pd.DataFrame({"Time": observed.round(2), "Event": event, "Group": group})
93
+ table = DataTable(frame, name="Survival")
94
+ table.specs["Group"].modeling_type = "nominal"
95
+ return table
96
+
97
+
98
+ def _time_series() -> DataTable:
99
+ rng = np.random.default_rng(51)
100
+ n = 180
101
+ date = pd.date_range("2023-01-01", periods=n, freq="D")
102
+ trend = 100 + 0.15 * np.arange(n)
103
+ season = 6 * np.sin(2 * np.pi * np.arange(n) / 7)
104
+ noise = rng.normal(0, 2.0, n)
105
+ sales = trend + season + noise
106
+ frame = pd.DataFrame({"Date": date, "Sales": sales.round(2)})
107
+ return DataTable(frame, name="Time Series")
108
+
109
+
110
+ def _custom_doe() -> DataTable:
111
+ from statstudio.stats import custom_doe
112
+
113
+ factors = [
114
+ custom_doe.CustomFactor("Temperature", role="continuous", low=160, high=200, units="C"),
115
+ custom_doe.CustomFactor("Time", role="continuous", low=10, high=20, units="min"),
116
+ custom_doe.CustomFactor("Material", role="categorical", levels=["A", "B", "C"]),
117
+ ]
118
+ spec = custom_doe.CustomDesignSpec(
119
+ factors=factors,
120
+ responses=[
121
+ custom_doe.ResponseSpec("Strength", goal="Maximize", lower=40, upper=70, units="MPa"),
122
+ custom_doe.ResponseSpec("Defects", goal="Minimize", lower=0, upper=8),
123
+ ],
124
+ terms=custom_doe.default_terms(factors),
125
+ criterion="D",
126
+ runs=18,
127
+ block_size=6,
128
+ seed=17,
129
+ starts=1,
130
+ name="Custom DOE",
131
+ )
132
+ table = custom_doe.build_custom_design(spec)
133
+ rng = np.random.default_rng(77)
134
+ temp = table.data["Temperature"].to_numpy(dtype=float)
135
+ time = table.data["Time"].to_numpy(dtype=float)
136
+ material = table.data["Material"].astype(str).to_numpy()
137
+ material_effect = np.where(material == "B", 2.0, np.where(material == "C", -1.5, 0.0))
138
+ strength = 50 + 0.20 * (temp - 180) - 0.55 * (time - 15) + material_effect
139
+ strength += 0.02 * (temp - 180) * (time - 15) + rng.normal(0, 0.8, len(table))
140
+ defects = 3.0 - 0.035 * (temp - 180) + 0.08 * (time - 15) - 0.4 * material_effect
141
+ defects = np.clip(defects + rng.normal(0, 0.3, len(table)), 0, None)
142
+ table.data["Strength"] = np.round(strength, 3)
143
+ table.data["Defects"] = np.round(defects, 2)
144
+ for name in ("Strength", "Defects"):
145
+ table.specs[name].modeling_type = "continuous"
146
+ table.name = "Custom DOE"
147
+ return table
148
+
149
+
150
+ _BUILDERS = {
151
+ "Manufacturing": _manufacturing,
152
+ "Gage R&R": _gage,
153
+ "Predictive": _predictive,
154
+ "Survival": _survival,
155
+ "Time Series": _time_series,
156
+ "Custom DOE": _custom_doe,
157
+ }
158
+
159
+
160
+ def load_sample(name: str) -> DataTable:
161
+ builder = _BUILDERS.get(name)
162
+ if builder is None:
163
+ raise KeyError(name)
164
+ return builder()
@@ -0,0 +1,118 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import tempfile
6
+ import zipfile
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from statstudio.core.archive import validate_archive
15
+ from statstudio.core.table import DataTable
16
+
17
+ TABLE_SUFFIX = ".stbl"
18
+ TABLE_FORMAT = "statstudio-table"
19
+ CURRENT_TABLE_VERSION = 1
20
+
21
+
22
+ class TableFileError(ValueError):
23
+ pass
24
+
25
+
26
+ def _validate_table_payload(payload: Any) -> dict[str, Any]:
27
+ if not isinstance(payload, dict):
28
+ raise TableFileError("The table payload is not a JSON object.")
29
+ if payload.get("format") != TABLE_FORMAT:
30
+ raise TableFileError("Not a StatStudio table file.")
31
+ try:
32
+ version = int(payload.get("version", 1))
33
+ except (TypeError, ValueError) as exc:
34
+ raise TableFileError("The table file has an invalid version.") from exc
35
+ if version < 1:
36
+ raise TableFileError(f"Unsupported table version: {version}.")
37
+ if version > CURRENT_TABLE_VERSION:
38
+ raise TableFileError(
39
+ f"This table uses version {version}, but this build supports up to "
40
+ f"version {CURRENT_TABLE_VERSION}. Please update StatStudio."
41
+ )
42
+ return payload
43
+
44
+
45
+ def _json_default(value: Any) -> Any:
46
+ if isinstance(value, np.integer):
47
+ return int(value)
48
+ if isinstance(value, np.floating):
49
+ return float(value)
50
+ if isinstance(value, np.bool_):
51
+ return bool(value)
52
+ if isinstance(value, (pd.Timestamp, datetime)):
53
+ return value.isoformat()
54
+ if isinstance(value, set):
55
+ return list(value)
56
+ if isinstance(value, np.ndarray):
57
+ return value.tolist()
58
+ return str(value)
59
+
60
+
61
+ def save_table(table: DataTable, path: str | Path) -> Path:
62
+ path = Path(path)
63
+ if path.suffix.lower() != TABLE_SUFFIX:
64
+ path = path.with_suffix(TABLE_SUFFIX)
65
+ zip_fd, zip_name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".zip.tmp", dir=path.parent)
66
+ os.close(zip_fd)
67
+ parquet_fd, parquet_name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".parquet.tmp", dir=path.parent)
68
+ os.close(parquet_fd)
69
+ tmp_zip = Path(zip_name)
70
+ tmp_parquet = Path(parquet_name)
71
+ try:
72
+ table.data.to_parquet(tmp_parquet, index=True)
73
+ payload = {
74
+ "format": TABLE_FORMAT,
75
+ "version": CURRENT_TABLE_VERSION,
76
+ "saved_at": datetime.now().isoformat(timespec="seconds"),
77
+ "table": table.to_payload("data/table.parquet"),
78
+ }
79
+ with zipfile.ZipFile(tmp_zip, "w", compression=zipfile.ZIP_DEFLATED) as archive:
80
+ archive.write(tmp_parquet, "data/table.parquet")
81
+ archive.writestr("table.json", json.dumps(payload, indent=2, default=_json_default))
82
+ os.replace(tmp_zip, path)
83
+ finally:
84
+ for temp_path in (tmp_zip, tmp_parquet):
85
+ if temp_path.exists():
86
+ temp_path.unlink()
87
+ return path
88
+
89
+
90
+ def load_table(path: str | Path) -> DataTable:
91
+ path = Path(path)
92
+ try:
93
+ with zipfile.ZipFile(path, "r") as archive:
94
+ validate_archive(archive, TableFileError)
95
+ try:
96
+ raw = archive.read("table.json")
97
+ except KeyError as exc:
98
+ raise TableFileError("The table file is missing table.json.") from exc
99
+ try:
100
+ payload = json.loads(raw.decode("utf-8"))
101
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
102
+ raise TableFileError("The table file contains invalid JSON.") from exc
103
+ payload = _validate_table_payload(payload)
104
+ table_payload = payload.get("table") or {}
105
+ data_file = table_payload.get("data_file")
106
+ if not data_file:
107
+ raise TableFileError("The table file is missing its data payload.")
108
+ try:
109
+ with archive.open(data_file) as handle:
110
+ frame = pd.read_parquet(handle)
111
+ except (KeyError, OSError, ValueError) as exc:
112
+ raise TableFileError(f"Could not read table data {data_file!r}: {exc}") from exc
113
+ except zipfile.BadZipFile as exc:
114
+ raise TableFileError(f"Could not read table file: {exc}") from exc
115
+ try:
116
+ return DataTable.from_payload(frame, table_payload)
117
+ except (TypeError, ValueError, KeyError) as exc:
118
+ raise TableFileError(f"Invalid table definition: {exc}") from exc
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+
5
+
6
+ def __getattr__(name: str):
7
+ if name in {"PLOT_DEFINITIONS", "build_figure", "save_figure"}:
8
+ registry = importlib.import_module(f"{__name__}.registry")
9
+ value = getattr(registry, name)
10
+ globals()[name] = value
11
+ return value
12
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
13
+
14
+
15
+ def __dir__() -> list[str]:
16
+ return sorted({"PLOT_DEFINITIONS", "build_figure", "save_figure", *globals()})
17
+
18
+
19
+ __all__ = ["PLOT_DEFINITIONS", "build_figure", "save_figure"]