universal-log-ts 7.6.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,30 @@
1
+ # -*- coding: utf-8 -*-
2
+ """UNIVERSAL_LOG — Domain-agnostic threshold detection and falsification instrument."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from .config import MODE_PRESETS, VERSION, VERSION_MASTER, UniversalConfig
7
+ from .data import UniversalDataset, demo_dataset, generate_example_csv, load_universal_dataset
8
+ from .falsification import grade_evidence
9
+ from .pipeline import analyze
10
+ from .prediction import predict_universal
11
+ from .regression import run_regression_tests
12
+ from .report_html import render_html_report
13
+
14
+ __version__ = "7.6.0"
15
+
16
+ __all__ = [
17
+ "VERSION",
18
+ "VERSION_MASTER",
19
+ "MODE_PRESETS",
20
+ "UniversalConfig",
21
+ "UniversalDataset",
22
+ "load_universal_dataset",
23
+ "demo_dataset",
24
+ "generate_example_csv",
25
+ "analyze",
26
+ "predict_universal",
27
+ "grade_evidence",
28
+ "render_html_report",
29
+ "run_regression_tests",
30
+ ]
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Module entry point for ``python -m universal_log``."""
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == "__main__":
7
+ main()
universal_log/cli.py ADDED
@@ -0,0 +1,156 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Command-line interface for UNIVERSAL_LOG."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from typing import Any, List, Optional
8
+
9
+ from .config import VERSION, UniversalConfig
10
+ from .data import generate_example_csv
11
+ from .estimators import ESTIMATORS
12
+ from .pipeline import DEFAULT_ROUTING_GATES, analyze
13
+ from .regression import run_regression_tests
14
+
15
+
16
+ def describe_limits() -> str:
17
+ """Return a human-readable summary of frozen gates, stubs, and non-claims."""
18
+ lines = [
19
+ f"UNIVERSAL_LOG {VERSION} — frozen limits and non-claims",
20
+ "",
21
+ "Routing gates (DEFAULT_ROUTING_GATES):",
22
+ ]
23
+ for k, v in DEFAULT_ROUTING_GATES.items():
24
+ lines.append(f" {k} = {v}")
25
+ n_stubs = 1 # Danco
26
+ lines += [
27
+ "",
28
+ f"Estimators registered: {len(ESTIMATORS)} total "
29
+ f"(13 unique dimension estimators evaluated in default L5 contrast; "
30
+ f"Danco is a permanent NaN stub; PersistentHomology uses ripser if installed else autonomous H0_UnionFind; "
31
+ f"{n_stubs} stub total).",
32
+ "Surrogate null: Kendall/Marriott-Pope bias-corrected AR(1), integrated ARIMA(1,1,0) when phi_within >= 0.75 and phi_diff1 >= 0.25, "
33
+ "and pipeline-matched raw-to-volatility surrogates (vol_arima_0_1_0 / vol_arima_1_1_0 / vol_ar1) on volatility_shift.",
34
+ "Grading: compound falsification failure (AR/ARIMA + unstable/WF/white-noise/split-half, or unstable + opposite split-half) drops to Grade D.",
35
+ "T_log: permutation-calibrated diagnostic, n_perm=25 -> p-value floor 1/26 ~= 0.0385 "
36
+ "(resolution limit, not proof).",
37
+ "T_log never changes the A/B/C/D grade.",
38
+ "",
39
+ "Non-claims: detection + falsification only. NOT causal proof, NOT medical diagnosis, "
40
+ "NOT financial advice.",
41
+ "Any threshold (even Grade A) requires independent replication before action.",
42
+ ]
43
+ return "\n".join(lines)
44
+
45
+
46
+ def main(argv: Optional[List[str]] = None) -> Any:
47
+ """Parse CLI arguments and dispatch analysis, demo, or regression self-test."""
48
+ ap = argparse.ArgumentParser(
49
+ description=f"UNIVERSAL_LOG ({VERSION}) — Domain-agnostic threshold detection & falsification."
50
+ )
51
+ ap.add_argument("--input", type=str, default=None, help="Input CSV, Parquet, or JSON file.")
52
+ ap.add_argument(
53
+ "--describe-limits",
54
+ action="store_true",
55
+ help="Print frozen gates, placeholders, and non-claims, then exit.",
56
+ )
57
+ ap.add_argument(
58
+ "--control",
59
+ type=str,
60
+ default=None,
61
+ help="Ordered control column name (auto-inferred if omitted).",
62
+ )
63
+ ap.add_argument(
64
+ "--target",
65
+ type=str,
66
+ default=None,
67
+ help="Target variable column name (auto-inferred if omitted).",
68
+ )
69
+ ap.add_argument(
70
+ "--mode",
71
+ type=str,
72
+ default="fast",
73
+ choices=["fast", "robust", "full"],
74
+ help="Sampling intensity preset.",
75
+ )
76
+ ap.add_argument(
77
+ "--detection-mode",
78
+ type=str,
79
+ default="auto",
80
+ choices=["auto", "mean"],
81
+ help="'auto' evaluates structural channels (jump/slope/vol) alongside level shifts; 'mean' restricts primary scan to level shift.",
82
+ )
83
+ ap.add_argument(
84
+ "--output",
85
+ type=str,
86
+ default="./results_v7",
87
+ help="Output directory for results.json, thresholds.csv, report.txt, and report.html.",
88
+ )
89
+ ap.add_argument(
90
+ "--demo",
91
+ type=str,
92
+ default=None,
93
+ choices=["step", "logistic", "null"],
94
+ help="Generate and analyze a synthetic domain-free demo dataset.",
95
+ )
96
+ ap.add_argument(
97
+ "--harmonic-ablation",
98
+ action="store_true",
99
+ help="Run comparative harmonic-jitter ablation test (P4).",
100
+ )
101
+ ap.add_argument(
102
+ "--complexity-diagnostics",
103
+ action="store_true",
104
+ help="Enable exploratory 29-estimator complexity (L5 T_log) and L7 sliding interactions.",
105
+ )
106
+ ap.add_argument(
107
+ "--full-validation",
108
+ action="store_true",
109
+ help="Run the heavy 3-cohort segmented MC + trajectory validation suite.",
110
+ )
111
+ ap.add_argument(
112
+ "--self-test",
113
+ action="store_true",
114
+ help="Run the built-in non-regression test suite.",
115
+ )
116
+ ap.add_argument("--seed", type=int, default=42, help="Random seed (default: 42).")
117
+ ap.add_argument("--quiet", action="store_true", help="Suppress verbose console output.")
118
+
119
+ args = ap.parse_args(argv)
120
+ cfg = UniversalConfig(
121
+ mode=args.mode,
122
+ seed=args.seed,
123
+ output_dir=args.output,
124
+ harmonic_ablation=args.harmonic_ablation,
125
+ run_complexity_diagnostics=args.complexity_diagnostics,
126
+ run_estimator_validation=args.full_validation,
127
+ detection_mode=args.detection_mode,
128
+ verbose=not args.quiet,
129
+ )
130
+
131
+ if args.describe_limits:
132
+ print(describe_limits())
133
+ return None
134
+
135
+ if args.self_test:
136
+ res = run_regression_tests()
137
+ if not res.get("all_passed"):
138
+ raise SystemExit(1)
139
+ return res
140
+
141
+ if args.demo:
142
+ path = generate_example_csv(args.demo, f"./demo_{args.demo}.csv", seed=args.seed)
143
+ if cfg.verbose:
144
+ print(f"[DEMO {args.demo}] generated: {path}", flush=True)
145
+ return analyze(path, config=cfg, output_dir=args.output)
146
+
147
+ if not args.input:
148
+ ap.error("--input is required (or specify --demo step|logistic|null or --self-test)")
149
+
150
+ return analyze(
151
+ args.input,
152
+ control=args.control,
153
+ target=args.target,
154
+ config=cfg,
155
+ output_dir=args.output,
156
+ )
@@ -0,0 +1,106 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Configuration and constants for UNIVERSAL_LOG.
3
+
4
+ v7 Design Principles (unchanged):
5
+ - P1: No domain names or domain-specific heuristics in code.
6
+ - P2: No hand-tuned weights (inverse-variance stability weighting, or equal weights).
7
+ - P3: No semantic direction from column names (direction = empirical Cohen's d sign).
8
+ - P4: No harmonic prior (uniform MC + permutation; harmonic ablation is comparative only).
9
+ - P5: Falsification first (permutation, white noise, surrogate, split-half, walk-forward).
10
+ - P6: Effect size + 95% CI + p-value, never a bare score alone.
11
+ - P7: Full reproducibility (seed, manifest, input/code SHA-256 hashes).
12
+ - P8: T_log = permutation-calibrated complexity diagnostic, never a proof.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from dataclasses import asdict, dataclass, field
19
+ from typing import Any, Dict, List
20
+
21
+ VERSION = "v7.6.0-universal"
22
+ VERSION_MASTER = "v7.6.0-universal-modular-calibrated"
23
+ RANDOM_SEED = 42
24
+
25
+ # Mathematical constants retained solely for optional harmonic ablation tests (P4).
26
+ PHI = (1.0 + 5.0 ** 0.5) / 2.0
27
+ PI = math.pi
28
+ E = math.e
29
+ SQRT2 = math.sqrt(2.0)
30
+ SQRT3 = math.sqrt(3.0)
31
+
32
+ MODE_PRESETS: Dict[str, Dict[str, Any]] = {
33
+ "fast": {
34
+ "n_bootstrap": 100,
35
+ "n_permutations": 200,
36
+ "n_mc_paths": 100,
37
+ "window_sizes": [50, 80],
38
+ "n_scan_permutations": 200,
39
+ },
40
+ "robust": {
41
+ "n_bootstrap": 300,
42
+ "n_permutations": 500,
43
+ "n_mc_paths": 200,
44
+ "window_sizes": [50, 80, 120],
45
+ "n_scan_permutations": 500,
46
+ },
47
+ "full": {
48
+ "n_bootstrap": 1000,
49
+ "n_permutations": 1000,
50
+ "n_mc_paths": 400,
51
+ "window_sizes": [50, 80, 120, 180, 220],
52
+ "n_scan_permutations": 1000,
53
+ },
54
+ }
55
+
56
+
57
+ @dataclass
58
+ class UniversalConfig:
59
+ """Centralized configuration for UNIVERSAL_LOG analyses."""
60
+
61
+ seed: int = 42
62
+ mode: str = "fast"
63
+ horizons: List[int] = field(default_factory=lambda: list(range(1, 13)))
64
+ n_bootstrap: int = 200
65
+ n_permutations: int = 500
66
+ n_mc_paths: int = 200
67
+ window_sizes: List[int] = field(default_factory=lambda: [50, 80, 120])
68
+ min_group: int = 4
69
+ min_length: int = 50
70
+ harmonic_ablation: bool = False
71
+ harmonic_prob: float = 0.45
72
+ use_relative_windows: bool = True
73
+ n_scan_permutations: int = 200
74
+ n_scan_refined_permutations: int = 2000
75
+ min_analyses_for_prediction: int = 5
76
+ run_complexity_diagnostics: bool = False # Exploratory 29 estimators + L5/L7 sliding interactions
77
+ run_estimator_validation: bool = False
78
+ detection_mode: str = "auto" # "auto" (mean / detrended_jump / slope / vol) or "mean"
79
+ grade_rules: Dict[str, Any] = field(
80
+ default_factory=lambda: {
81
+ "min_cohen_d": 0.5,
82
+ "max_p_perm": 0.05,
83
+ "min_stability": 0.60,
84
+ "min_walkforward_f1": 0.50,
85
+ }
86
+ )
87
+ output_dir: str = "./results_v7"
88
+ verbose: bool = True
89
+
90
+ def to_dict(self) -> Dict[str, Any]:
91
+ """Serialize configuration to a plain dictionary."""
92
+ return asdict(self)
93
+
94
+ @classmethod
95
+ def from_mode(cls, mode: str = "fast", **overrides: Any) -> "UniversalConfig":
96
+ """Create a UniversalConfig pre-populated with MODE_PRESETS[mode] plus overrides."""
97
+ params: Dict[str, Any] = dict(MODE_PRESETS.get(mode, {}))
98
+ params.update(overrides)
99
+ params["mode"] = mode
100
+ return cls(**params)
101
+
102
+
103
+ def log_message(cfg: UniversalConfig, msg: str) -> None:
104
+ """Print log line when verbose mode is enabled."""
105
+ if cfg.verbose:
106
+ print(msg, flush=True)
universal_log/data.py ADDED
@@ -0,0 +1,182 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Data loading, validation, numeric guards, and synthetic demo generators."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import math
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Sequence
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+
15
+ def _safe_float(x: Any, default: float = float("nan")) -> float:
16
+ """Convert a scalar to float, returning default if non-finite or unconvertible."""
17
+ try:
18
+ v = float(x)
19
+ return v if math.isfinite(v) else default
20
+ except Exception:
21
+ return default
22
+
23
+
24
+ def _finite(arr: Any) -> np.ndarray:
25
+ """Return a 1D float64 NumPy array containing only finite elements."""
26
+ a = np.asarray(arr, dtype=float).ravel()
27
+ return a[np.isfinite(a)]
28
+
29
+
30
+ @dataclass
31
+ class UniversalDataset:
32
+ """Domain-agnostic container for ordered control, target, and auxiliary fluxes."""
33
+
34
+ control: np.ndarray
35
+ control_name: str
36
+ target: np.ndarray
37
+ target_name: str
38
+ fluxes: Dict[str, np.ndarray]
39
+ flux_names: List[str]
40
+ n: int
41
+ control_monotone: bool
42
+ source_hash: str = ""
43
+ source_name: str = ""
44
+ dropped_rows: int = 0
45
+ metadata: Dict[str, Any] = field(default_factory=dict)
46
+
47
+
48
+ def load_universal_dataset(
49
+ df: pd.DataFrame,
50
+ control: Optional[Any] = None,
51
+ target: Optional[Any] = None,
52
+ fluxes: Optional[Sequence[Any]] = None,
53
+ source_name: str = "dataframe",
54
+ source_hash: str = "",
55
+ ) -> UniversalDataset:
56
+ """Infer control, target, and auxiliary fluxes with zero domain priors.
57
+
58
+ - Control: explicitly provided, else first strictly monotonic numeric column,
59
+ else synthetic row index ``__index__`` (if >= 2 numeric columns exist or
60
+ if target is explicitly provided with >= 1 numeric column).
61
+ - Target: explicitly provided, else first numeric column != control.
62
+ - Fluxes: all numeric columns != control (normalized-name match excluded).
63
+ - Rows with NaN/Inf in control or target are dropped explicitly and logged,
64
+ never silently imputed.
65
+ """
66
+ if df is None or len(df) == 0:
67
+ raise ValueError("Input DataFrame is empty.")
68
+
69
+ numeric = df.select_dtypes(include=[np.number]).columns.tolist()
70
+ if control is None and target is None and len(numeric) < 2:
71
+ raise ValueError(f"At least 2 numeric columns are required, found {numeric}.")
72
+ if len(numeric) < 1:
73
+ raise ValueError("At least 1 numeric column is required.")
74
+
75
+ if control is not None and control not in df.columns:
76
+ raise ValueError(f"Control column '{control}' not found. Available: {list(df.columns)}")
77
+
78
+ control_name = control
79
+ if control_name is None:
80
+ mono = [
81
+ c
82
+ for c in numeric
83
+ if len(_finite(df[c].values)) >= 2
84
+ and bool(np.all(np.diff(_finite(df[c].values)) > 0))
85
+ ]
86
+ control_name = mono[0] if mono else None
87
+
88
+ if control_name is None:
89
+ control_name = "__index__"
90
+ control_values = np.arange(len(df), dtype=float)
91
+ else:
92
+ control_values = pd.to_numeric(df[control_name], errors="coerce").to_numpy(dtype=float)
93
+
94
+ if target is not None and target not in df.columns:
95
+ raise ValueError(f"Target column '{target}' not found. Available: {list(df.columns)}")
96
+
97
+ if target is not None:
98
+ target_name = target
99
+ else:
100
+ target_name = next((c for c in numeric if c != control_name), numeric[0])
101
+
102
+ if target_name in df.columns:
103
+ target_values = pd.to_numeric(df[target_name], errors="coerce").to_numpy(dtype=float)
104
+ else:
105
+ target_values = control_values.copy()
106
+
107
+ def _norm(s: Any) -> str:
108
+ return "".join(ch for ch in str(s).lower() if ch.isalnum())
109
+
110
+ ctrl_norm = _norm(control_name)
111
+ if fluxes is None:
112
+ flux_names = [c for c in numeric if _norm(c) != ctrl_norm]
113
+ else:
114
+ flux_names = [c for c in fluxes if c in df.columns and _norm(c) != ctrl_norm]
115
+
116
+ order = np.argsort(control_values, kind="stable")
117
+ c_sorted = control_values[order]
118
+ y_sorted = target_values[order]
119
+ mask = np.isfinite(c_sorted) & np.isfinite(y_sorted)
120
+ n_drop = int((~mask).sum())
121
+ if n_drop:
122
+ print(
123
+ f"[DATA] Dropped {n_drop}/{len(df)} rows with non-finite control/target. "
124
+ "No silent imputation performed.",
125
+ flush=True,
126
+ )
127
+
128
+ c_sorted = c_sorted[mask]
129
+ y_sorted = y_sorted[mask]
130
+ control_monotone = bool(len(c_sorted) >= 2 and np.all(np.diff(c_sorted) > 0))
131
+
132
+ fluxes_dict: Dict[str, np.ndarray] = {}
133
+ for name in flux_names:
134
+ arr = pd.to_numeric(df[name], errors="coerce").to_numpy(dtype=float)
135
+ fluxes_dict[str(name)] = arr[order][mask]
136
+
137
+ if str(target_name) not in fluxes_dict and target_name in df.columns:
138
+ fluxes_dict[str(target_name)] = y_sorted
139
+
140
+ return UniversalDataset(
141
+ control=c_sorted,
142
+ control_name=str(control_name),
143
+ target=y_sorted,
144
+ target_name=str(target_name),
145
+ fluxes=fluxes_dict,
146
+ flux_names=list(fluxes_dict.keys()),
147
+ n=int(len(c_sorted)),
148
+ control_monotone=control_monotone,
149
+ source_hash=source_hash,
150
+ source_name=source_name,
151
+ dropped_rows=n_drop,
152
+ )
153
+
154
+
155
+ def demo_dataset(kind: str = "logistic", n: int = 300, seed: int = 42) -> pd.DataFrame:
156
+ """Generate a domain-agnostic synthetic dataset ('step', 'logistic', or 'null')."""
157
+ rng = np.random.default_rng(seed)
158
+ x = np.linspace(0.0, 100.0, n)
159
+ if kind == "step":
160
+ y = np.where(x < 50.0, 0.0, 1.0) + rng.normal(0.0, 0.15, n)
161
+ elif kind == "null":
162
+ y = rng.normal(0.0, 1.0, n)
163
+ else: # logistic
164
+ y = 1.0 / (1.0 + np.exp(-(x - 50.0) / 5.0)) + rng.normal(0.0, 0.08, n)
165
+
166
+ return pd.DataFrame(
167
+ {
168
+ "axis": x,
169
+ "observable": y,
170
+ "observable_noisy": y + rng.normal(0.0, 0.1, n),
171
+ "pure_noise": rng.normal(0.0, 1.0, n),
172
+ }
173
+ )
174
+
175
+
176
+ def generate_example_csv(kind: str, path: str | Path, n: int = 300, seed: int = 42) -> Path:
177
+ """Write a synthetic demo CSV to disk and return its Path."""
178
+ df = demo_dataset(kind=kind, n=n, seed=seed)
179
+ out_path = Path(path)
180
+ out_path.parent.mkdir(parents=True, exist_ok=True)
181
+ df.to_csv(out_path, index=False)
182
+ return out_path