fitcdf 0.5.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.
fitcdf/__init__.py ADDED
@@ -0,0 +1,70 @@
1
+ """Public package facade for the standalone fitcdf statistical library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from fitcdf.data import (
8
+ normalize_dataset_name,
9
+ read_dataset,
10
+ resolve_dataset_input,
11
+ resolve_results_directory,
12
+ summarize_observations,
13
+ )
14
+ from fitcdf.distributions import (
15
+ catalog_snapshot,
16
+ get_distribution,
17
+ list_available_families,
18
+ )
19
+ from fitcdf.inference import (
20
+ estimate_parameters,
21
+ evaluate_model_adequacy,
22
+ predict_quantiles,
23
+ )
24
+ from fitcdf.plotting import plot_distributions
25
+ from fitcdf.uncertainty import resample_parameter_uncertainty
26
+
27
+ if TYPE_CHECKING:
28
+ from fitcdf.analysis import analyze_dataset
29
+ from fitcdf.comparison import compare_distributions
30
+
31
+ __version__ = "0.5.0"
32
+
33
+ __all__ = [
34
+ "__version__",
35
+ "analyze_dataset",
36
+ "compare_distributions",
37
+ "plot_distributions",
38
+ "read_dataset",
39
+ "summarize_observations",
40
+ "normalize_dataset_name",
41
+ "resolve_dataset_input",
42
+ "resolve_results_directory",
43
+ "catalog_snapshot",
44
+ "list_available_families",
45
+ "get_distribution",
46
+ "estimate_parameters",
47
+ "evaluate_model_adequacy",
48
+ "predict_quantiles",
49
+ "resample_parameter_uncertainty",
50
+ ]
51
+
52
+
53
+ def __getattr__(attribute_name: str) -> Any:
54
+ """Resolve orchestration entry points lazily to avoid circular or eager imports."""
55
+ if attribute_name == "analyze_dataset":
56
+ from fitcdf.analysis import analyze_dataset
57
+
58
+ globals()["analyze_dataset"] = analyze_dataset
59
+ return analyze_dataset
60
+ if attribute_name == "compare_distributions":
61
+ from fitcdf.comparison import compare_distributions
62
+
63
+ globals()["compare_distributions"] = compare_distributions
64
+ return compare_distributions
65
+ raise AttributeError(f"module 'fitcdf' has no attribute {attribute_name!r}")
66
+
67
+
68
+ def __dir__() -> list[str]:
69
+ """Expose the complete public API for introspection and interactive completion."""
70
+ return sorted(__all__)
fitcdf/acceleration.py ADDED
@@ -0,0 +1,250 @@
1
+ """Optional GPU reductions; SciPy estimation and CDF evaluation remain on CPU.
2
+
3
+ Importing this module does not import CuPy or create a CUDA context, allowing
4
+ hardware inspection in the coordinator process before spawning workers.
5
+ """
6
+
7
+ import csv
8
+ import importlib
9
+ import importlib.util
10
+ import os
11
+ import shutil
12
+ import statistics
13
+
14
+ # Local query with fixed arguments, no shell, and no user input.
15
+ import subprocess # nosec B404
16
+ import time
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+
21
+ __all__ = [
22
+ "AUTO_GPU_THRESHOLD",
23
+ "detect_acceleration_without_cuda_init",
24
+ "compute_gpu_distances",
25
+ "select_backend",
26
+ ]
27
+
28
+ # Conservative operational threshold, not a universal benchmark. Above this size,
29
+ # auto mode still requires a local process/device measurement including transfers.
30
+ AUTO_GPU_THRESHOLD = 1_000_000
31
+ _RUNTIME_BY_PROCESS: dict[int, dict[str, Any]] = {}
32
+ _BENCHMARK_BY_PROCESS: dict[tuple[int, int], dict[str, float]] = {}
33
+
34
+
35
+ def detect_acceleration_without_cuda_init() -> dict[str, Any]:
36
+ """Query NVML via nvidia-smi without conflating visible GPU with usable CUDA."""
37
+ result: dict[str, Any] = {
38
+ "gpu_detected": False,
39
+ "cupy_installed": importlib.util.find_spec("cupy") is not None,
40
+ "cuda_initialized": False,
41
+ "devices": [],
42
+ "fitting": "cpu",
43
+ "gpu_scope": "CvM/AD reductions only after CPU-computed CDF and log-CDF.",
44
+ }
45
+ executable = shutil.which("nvidia-smi")
46
+ if executable is None:
47
+ result["reason"] = "nvidia-smi not found; falling back to CPU."
48
+ return result
49
+ try:
50
+ # Resolved executable; constant arguments and no shell invocation.
51
+ probe = subprocess.run( # nosec B603
52
+ [
53
+ executable,
54
+ "--query-gpu=index,name,memory.total,memory.free,driver_version",
55
+ "--format=csv,noheader,nounits",
56
+ ],
57
+ capture_output=True,
58
+ text=True,
59
+ timeout=3,
60
+ check=False,
61
+ )
62
+ except (OSError, subprocess.TimeoutExpired) as exc:
63
+ result["reason"] = "Could not query GPU; falling back to CPU."
64
+ result["technical_details"] = str(exc)
65
+ return result
66
+ if probe.returncode:
67
+ result["reason"] = "GPU query failed; falling back to CPU."
68
+ result["technical_details"] = (probe.stderr or probe.stdout).strip()
69
+ return result
70
+ for fields in csv.reader(probe.stdout.splitlines()):
71
+ if len(fields) != 5:
72
+ continue
73
+ index, name, total_memory, free_memory, driver = (field.strip() for field in fields)
74
+ result["devices"].append(
75
+ {
76
+ "index": index,
77
+ "name": name,
78
+ "total_memory_mib": total_memory,
79
+ "free_memory_mib": free_memory,
80
+ "driver": driver,
81
+ }
82
+ )
83
+ result["gpu_detected"] = bool(result["devices"])
84
+ result["reason"] = (
85
+ "GPU visible on the system; CUDA has not yet been initialized or validated."
86
+ if result["gpu_detected"]
87
+ else "No GPU reported by the system; falling back to CPU."
88
+ )
89
+ return result
90
+
91
+
92
+ def _get_gpu_runtime() -> tuple[Any, str]:
93
+ process_id = os.getpid()
94
+ state = _RUNTIME_BY_PROCESS.get(process_id)
95
+ if state is not None:
96
+ if state.get("error"):
97
+ raise RuntimeError(state["error"])
98
+ return state["cupy"], state["device"]
99
+ if _RUNTIME_BY_PROCESS:
100
+ raise RuntimeError(
101
+ "Attempted to initialize CUDA after fork inheritance; use CPU or a fresh process."
102
+ )
103
+ try:
104
+ cupy = importlib.import_module("cupy")
105
+ if cupy.cuda.runtime.getDeviceCount() < 1:
106
+ raise RuntimeError("CUDA runtime reported no usable device.")
107
+ device = cupy.cuda.runtime.getDeviceProperties(0)["name"]
108
+ if isinstance(device, bytes):
109
+ device = device.decode("utf-8", errors="replace")
110
+ # A real device operation distinguishes driver metadata from usable execution.
111
+ cupy.zeros(1, dtype=cupy.float64).sum().item()
112
+ cupy.cuda.get_current_stream().synchronize()
113
+ except Exception as exc:
114
+ message = f"CUDA unavailable in this process: {type(exc).__name__}: {exc}"
115
+ _RUNTIME_BY_PROCESS[process_id] = {"error": message}
116
+ raise RuntimeError(message) from exc
117
+ _RUNTIME_BY_PROCESS[process_id] = {
118
+ "cupy": cupy,
119
+ "device": str(device),
120
+ }
121
+ return cupy, str(device)
122
+
123
+
124
+ def compute_gpu_distances(
125
+ cdfs: Any,
126
+ log_cdfs: Any,
127
+ log_sfs: Any,
128
+ ) -> dict[str, Any]:
129
+ """Compute CvM and AD in float64 from vectors aligned to the ascending sorted sample.
130
+
131
+ Survival inversion for the AD formula occurs here. No CDF evaluation,
132
+ parameter estimation, or p-value calibration is offloaded to GPU.
133
+ """
134
+ cdf_array = np.asarray(cdfs, dtype=np.float64)
135
+ log_cdf_array = np.asarray(log_cdfs, dtype=np.float64)
136
+ log_sf_array = np.asarray(log_sfs, dtype=np.float64)
137
+ vectors = (cdf_array, log_cdf_array, log_sf_array)
138
+ if any(vector.ndim != 1 for vector in vectors) or len(cdf_array) == 0:
139
+ raise ValueError("Probabilities must be non-empty one-dimensional vectors.")
140
+ if any(len(vector) != len(cdf_array) for vector in vectors):
141
+ raise ValueError("All three probability vectors must have the same length.")
142
+ if not np.all(np.isfinite(cdf_array)) or np.any((cdf_array < 0) | (cdf_array > 1)):
143
+ raise ValueError("Cumulative probabilities must be finite and within [0, 1].")
144
+ if any(np.any(np.isnan(vector)) or np.any(vector > 0) for vector in vectors[1:]):
145
+ raise ValueError("Log-probabilities must be non-positive and contain no NaN values.")
146
+ cupy, device = _get_gpu_runtime()
147
+ sample_length = len(cdf_array)
148
+ cdfs_gpu = cupy.asarray(cdf_array, dtype=cupy.float64)
149
+ log_cdfs_gpu = cupy.asarray(log_cdf_array, dtype=cupy.float64)
150
+ log_sfs_gpu = cupy.asarray(log_sf_array, dtype=cupy.float64)
151
+ positions_gpu = cupy.arange(1, sample_length + 1, dtype=cupy.float64)
152
+ cvm_distance = 1 / (12 * sample_length) + cupy.sum(
153
+ (cdfs_gpu - (positions_gpu - 0.5) / sample_length) ** 2
154
+ )
155
+ ad_distance = (
156
+ -sample_length
157
+ - cupy.sum((2 * positions_gpu - 1) * (log_cdfs_gpu + log_sfs_gpu[::-1])) / sample_length
158
+ )
159
+ values = cupy.asnumpy(cupy.stack((cvm_distance, ad_distance)))
160
+ return {
161
+ "cvm": float(values[0]),
162
+ "ad": float(values[1]),
163
+ "backend": "gpu",
164
+ "device": device,
165
+ }
166
+
167
+
168
+ def _measure_gpu_benefit(sample_size: int) -> dict[str, float]:
169
+ """Compare warmed-up end-to-end work, including all three host-to-device transfers."""
170
+ cache_key = (os.getpid(), sample_size)
171
+ if cache_key in _BENCHMARK_BY_PROCESS:
172
+ return _BENCHMARK_BY_PROCESS[cache_key]
173
+ cdfs = np.linspace(0.000001, 0.999999, sample_size)
174
+ log_cdfs = np.log(cdfs)
175
+ log_sfs = np.log1p(-cdfs)
176
+ positions = np.arange(1, sample_size + 1)
177
+ reference_cvm = 1 / (12 * sample_size) + np.sum((cdfs - (positions - 0.5) / sample_size) ** 2)
178
+ reference_ad = (
179
+ -sample_size - np.sum((2 * positions - 1) * (log_cdfs + log_sfs[::-1])) / sample_size
180
+ )
181
+ warmup = compute_gpu_distances(cdfs, log_cdfs, log_sfs)
182
+ if not np.allclose(
183
+ [warmup["cvm"], warmup["ad"]],
184
+ [reference_cvm, reference_ad],
185
+ rtol=1e-10,
186
+ atol=1e-7,
187
+ ):
188
+ raise RuntimeError("GPU reductions diverged from CPU reference in local check.")
189
+ cpu_times = []
190
+ gpu_times = []
191
+ for _repetition in range(3):
192
+ started = time.perf_counter()
193
+ 1 / (12 * sample_size) + np.sum((cdfs - (positions - 0.5) / sample_size) ** 2)
194
+ -sample_size - np.sum((2 * positions - 1) * (log_cdfs + log_sfs[::-1])) / sample_size
195
+ cpu_times.append(time.perf_counter() - started)
196
+ started = time.perf_counter()
197
+ compute_gpu_distances(cdfs, log_cdfs, log_sfs)
198
+ gpu_times.append(time.perf_counter() - started)
199
+ result = {
200
+ "cpu_seconds": statistics.median(cpu_times),
201
+ "gpu_seconds": statistics.median(gpu_times),
202
+ }
203
+ _BENCHMARK_BY_PROCESS[cache_key] = result
204
+ return result
205
+
206
+
207
+ def select_backend(sample_size: int, preference: str = "auto") -> dict[str, Any]:
208
+ """Select GPU in auto mode only if a local measurement shows at least a 20% speedup."""
209
+ if isinstance(sample_size, bool) or not isinstance(sample_size, int) or sample_size < 1:
210
+ raise ValueError("Sample size must be a positive integer.")
211
+ if preference not in {"auto", "cpu", "gpu"}:
212
+ raise ValueError("Accelerator must be 'auto', 'cpu', or 'gpu'.")
213
+ result: dict[str, Any] = {
214
+ "backend": "cpu",
215
+ "requested": preference,
216
+ "device": None,
217
+ "auto_threshold": AUTO_GPU_THRESHOLD,
218
+ "benchmark": None,
219
+ "scope": "CvM/AD reductions; estimation and CDFs remain on CPU.",
220
+ }
221
+ if preference == "cpu":
222
+ result["reason"] = "CPU explicitly requested."
223
+ return result
224
+ if preference == "auto" and sample_size < AUTO_GPU_THRESHOLD:
225
+ result["reason"] = (
226
+ "CPU selected by conservative policy for vectors smaller than 1,000,000 observations; "
227
+ "transfers and CUDA initialization can outweigh reduction cost. "
228
+ "No GPU benchmark was run for this selection."
229
+ )
230
+ return result
231
+ try:
232
+ _cupy, device = _get_gpu_runtime()
233
+ if preference == "auto":
234
+ benchmark = _measure_gpu_benefit(sample_size)
235
+ result["benchmark"] = benchmark
236
+ if benchmark["gpu_seconds"] >= 0.8 * benchmark["cpu_seconds"]:
237
+ result["reason"] = "Local measurement did not show at least a 20% GPU speedup."
238
+ return result
239
+ except Exception as exc:
240
+ result["reason"] = "GPU unavailable; falling back to CPU."
241
+ result["technical_details"] = str(exc)
242
+ return result
243
+ result.update(
244
+ backend="gpu",
245
+ device=device,
246
+ reason="GPU explicitly requested and runtime validated."
247
+ if preference == "gpu"
248
+ else "Local measurement showed greater than 20% GPU speedup on reductions.",
249
+ )
250
+ return result
fitcdf/analysis.py ADDED
@@ -0,0 +1,172 @@
1
+ """Column-by-column univariate dataset analysis and artifact persistence orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ from collections import Counter
7
+ from collections.abc import Callable, Iterable
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from fitcdf.comparison import compare_distributions
12
+ from fitcdf.data import (
13
+ read_dataset,
14
+ resolve_dataset_input,
15
+ resolve_results_directory,
16
+ summarize_observations,
17
+ )
18
+ from fitcdf.model_selection import normalize_policy
19
+
20
+ __all__ = ["analyze_dataset"]
21
+
22
+
23
+ def analyze_dataset(
24
+ path: str | Path,
25
+ *,
26
+ columns: Iterable[str] | None = None,
27
+ ignore: Iterable[str] | None = None,
28
+ separator: str | None = None,
29
+ decimal: str = ".",
30
+ file_name: str | None = None,
31
+ results_dir: str | Path | None = None,
32
+ save_artifacts: bool = True,
33
+ progress: Callable[[str], None] | None = None,
34
+ attempt_progress: Callable[[int, int, dict[str, Any]], None] | None = None,
35
+ stage_progress: Callable[[str, str], None] | None = None,
36
+ summary_progress: Callable[[str, dict[str, Any]], None] | None = None,
37
+ substage_progress: Callable[[dict[str, Any]], None] | None = None,
38
+ execution_context: dict[str, Any] | None = None,
39
+ audit_metadata: dict[str, Any] | None = None,
40
+ **comparison_options: Any,
41
+ ) -> dict[str, Any]:
42
+ """Analyze selected columns of a tabular CSV dataset independently."""
43
+ normalize_policy(
44
+ comparison_options.get("alternative_tolerances"),
45
+ comparison_options.get("alternative_ks_tolerance", 0.01),
46
+ )
47
+ if columns is None or isinstance(columns, str):
48
+ raise ValueError(
49
+ "Explicitly provide 'columns' as a non-empty collection of column names, not a string."
50
+ )
51
+ selected_list = list(columns)
52
+ if not selected_list:
53
+ raise ValueError("Explicitly select at least one column for analysis.")
54
+ if isinstance(ignore, str):
55
+ raise ValueError("Pass 'ignore' as a collection of column names, not a string.")
56
+
57
+ resolved_path = resolve_dataset_input(path, file_name=file_name)
58
+ if stage_progress is not None:
59
+ stage_progress("reading", str(resolved_path))
60
+
61
+ profile, column_profiles = read_dataset(resolved_path, separator=separator, decimal=decimal)
62
+ selected_set = set(selected_list)
63
+ ignored_set = set(ignore or ())
64
+ unknown_columns = (selected_set | ignored_set) - set(column_profiles)
65
+ if unknown_columns:
66
+ raise ValueError("Columns not found: " + ", ".join(sorted(unknown_columns)))
67
+
68
+ active_columns = selected_set - ignored_set
69
+ if not active_columns:
70
+ raise ValueError("No columns remain selected after applying exclusions.")
71
+
72
+ results: dict[str, dict[str, Any]] = {}
73
+ samples: dict[str, list[float]] = {}
74
+ interrupted = False
75
+
76
+ for column_name, column_profile in column_profiles.items():
77
+ values: list[float] = column_profile.pop("values")
78
+ if column_name in active_columns:
79
+ samples[column_name] = values
80
+ column_result: dict[str, Any] = {
81
+ "quality": column_profile,
82
+ "numeric_observations": len(values),
83
+ }
84
+ results[column_name] = column_result
85
+
86
+ if column_name in active_columns:
87
+ column_result["summary"] = summarize_observations(values, column_profile)
88
+ if summary_progress is not None:
89
+ summary_progress(column_name, column_result["summary"])
90
+
91
+ if column_name not in selected_set or column_name in ignored_set:
92
+ column_result.update(
93
+ status="ignored",
94
+ reason="Column excluded by explicit configuration.",
95
+ )
96
+ elif interrupted:
97
+ column_result.update(
98
+ status="cancelled",
99
+ reason="Analysis was interrupted before processing this column.",
100
+ )
101
+ elif not values and column_profile["non_numeric"] and not column_profile["non_finite"]:
102
+ column_result.update(
103
+ status="non_numeric",
104
+ reason="Column contains no finite numeric observations.",
105
+ )
106
+ elif any(column_profile.values()):
107
+ column_result.update(
108
+ status="invalid_data",
109
+ reason=(
110
+ "Column contains missing, non-numeric, or non-finite entries; "
111
+ "no rows were dropped for fitting."
112
+ ),
113
+ )
114
+ elif len(values) < 2:
115
+ column_result.update(
116
+ status="insufficient",
117
+ reason="At least two finite numeric observations are required.",
118
+ )
119
+ elif min(values) == max(values):
120
+ column_result.update(
121
+ status="constant",
122
+ reason="Column has zero variability.",
123
+ )
124
+ else:
125
+ if progress is not None:
126
+ progress(column_name)
127
+ try:
128
+ comparison_result = compare_distributions(
129
+ values,
130
+ progress=attempt_progress,
131
+ substage_progress=substage_progress,
132
+ execution_context={
133
+ **(execution_context or {}),
134
+ "column": column_name,
135
+ "file": str(resolved_path),
136
+ },
137
+ **comparison_options,
138
+ )
139
+ except ValueError as exc:
140
+ column_result.update(status="incompatible", reason=str(exc))
141
+ continue
142
+
143
+ column_result["comparison"] = comparison_result
144
+ interrupted = bool(comparison_result["interrupted"])
145
+ has_eligible_fit = any(group["fits"] for group in comparison_result["rankings"])
146
+ column_result["status"] = (
147
+ "cancelled"
148
+ if interrupted
149
+ else ("analyzed" if has_eligible_fit else "no_eligible_fit")
150
+ )
151
+
152
+ report: dict[str, Any] = {
153
+ "profile": profile,
154
+ "columns": results,
155
+ "interrupted": interrupted,
156
+ "statuses": dict(Counter(item["status"] for item in results.values())),
157
+ "warning": (
158
+ "Independent univariate analyses per column. Column names do not determine "
159
+ "domain semantics, target roles, identifiers, or probability laws."
160
+ ),
161
+ }
162
+ if audit_metadata:
163
+ report["audit"] = audit_metadata
164
+
165
+ if save_artifacts:
166
+ reports_module = importlib.import_module("fitcdf.reports")
167
+ target_results_dir = resolve_results_directory(resolved_path, results_dir)
168
+ if stage_progress is not None:
169
+ stage_progress("reports", str(target_results_dir))
170
+ report["artifacts"] = reports_module.save_reports(report, samples, target_results_dir)
171
+
172
+ return report