missinglab-workbench 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.
@@ -0,0 +1,79 @@
1
+ """Build and export a summary of the current MissingLab session (no raw rows)."""
2
+ from datetime import datetime, timezone
3
+ from importlib.metadata import version, PackageNotFoundError
4
+ import json
5
+ from pathlib import Path
6
+ import platform
7
+ import math
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from missinglab.core.analyzer import summarize_dataset, column_missingness
13
+ from missinglab.config import DEFAULT_RANDOM_STATE
14
+
15
+
16
+ def _json_value(value):
17
+ if isinstance(value, pd.DataFrame):
18
+ return _json_value(value.to_dict(orient="records"))
19
+ if isinstance(value, dict):
20
+ return {str(k): _json_value(v) for k, v in value.items()}
21
+ if isinstance(value, (tuple, list)):
22
+ return [_json_value(v) for v in value]
23
+ if isinstance(value, np.generic):
24
+ return _json_value(value.item())
25
+ if value is pd.NA or (isinstance(value, float) and not math.isfinite(value)):
26
+ return None
27
+ return value
28
+
29
+
30
+ def _version(name):
31
+ try:
32
+ return version(name)
33
+ except PackageNotFoundError:
34
+ return None
35
+
36
+
37
+ def build_session_report(df, source, *, mcar=None, simulation=None,
38
+ evaluation=None, imputation=None, benchmark=None):
39
+ """Capture summaries and completed-operation metadata, not raw datasets.
40
+
41
+ Optional sections must contain aggregate results/configuration only.
42
+ A null section means no current completed result is available.
43
+ """
44
+ if not isinstance(df, pd.DataFrame) or df.empty:
45
+ raise ValueError("Import a nonempty dataset before exporting a session report.")
46
+ report = {
47
+ "schema_version": 1,
48
+ "random_state": DEFAULT_RANDOM_STATE,
49
+ "created_at_utc": datetime.now(timezone.utc).isoformat(),
50
+ "software": {"application": "MissingLab", "python": platform.python_version(),
51
+ "versions": {name: _version(name) for name in
52
+ ("missinglab-workbench", "pandas", "numpy", "scipy", "scikit-learn", "pyampute")}},
53
+ "dataset": {"filename": Path(source).name,
54
+ "summary": summarize_dataset(df).to_dict(),
55
+ "complete_rows": int(df.notna().all(axis=1).sum()),
56
+ "columns": column_missingness(df)},
57
+ "mcar": mcar,
58
+ "simulation": simulation,
59
+ "evaluation": evaluation,
60
+ "imputation": imputation,
61
+ "benchmark": benchmark,
62
+ "notes": ["Only the latest available completed results for the current dataset are included.",
63
+ "No raw source, reference, simulated or imputed rows are included.",
64
+ "Reproduction requires the same original CSV and compatible software versions.",
65
+ "Benchmark errors pool numerical cells in their original units."],
66
+ }
67
+ return _json_value(report)
68
+
69
+
70
+ def export_session_report(report, destination, source):
71
+ """Export strict JSON, refusing to overwrite the imported source file."""
72
+ destination, source = Path(destination), Path(source)
73
+ if destination.suffix.lower() != ".json":
74
+ raise ValueError("Choose a JSON destination.")
75
+ if destination.resolve() == source.resolve() or (
76
+ destination.exists() and source.exists() and destination.samefile(source)):
77
+ raise ValueError("The source file must not be overwritten.")
78
+ content = json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False)
79
+ destination.write_text(content + "\n", encoding="utf-8")
File without changes