komlos-split 0.1.0__tar.gz → 0.3.0__tar.gz
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.
- {komlos_split-0.1.0 → komlos_split-0.3.0}/Cargo.lock +1 -1
- {komlos_split-0.1.0 → komlos_split-0.3.0}/Cargo.toml +1 -1
- {komlos_split-0.1.0 → komlos_split-0.3.0}/PKG-INFO +28 -1
- {komlos_split-0.1.0 → komlos_split-0.3.0}/README.md +27 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/pyproject.toml +1 -1
- {komlos_split-0.1.0 → komlos_split-0.3.0}/python/komlos_split/__init__.py +163 -62
- {komlos_split-0.1.0 → komlos_split-0.3.0}/src/lib.rs +433 -7
- {komlos_split-0.1.0 → komlos_split-0.3.0}/.gitignore +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/AUDIT_DOSSIER.md +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/BENCHMARK_STUDY.md +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/CITATION.cff +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/benches/baseline.rs +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/examples/ab_test_demo.py +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/examples/crossover_study.rs +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/examples/profile_study.rs +0 -0
- {komlos_split-0.1.0 → komlos_split-0.3.0}/spec/invariants.dfy +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: komlos-split
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Covariate-balanced A/B & train/val splitting via Guo-Fang-Lu Komlos Discrepancy (arXiv:2609.23540 / arXiv:2609.33215) and Gram-Schmidt Walk
|
|
5
5
|
License: MIT
|
|
6
6
|
Requires-Python: >=3.10
|
|
@@ -73,12 +73,20 @@ Works directly on **pandas DataFrames**, **Polars DataFrames**, **NumPy arrays**
|
|
|
73
73
|
import pandas as pd
|
|
74
74
|
import komlos_split
|
|
75
75
|
|
|
76
|
+
# 1. Two-way A/B split (50/50)
|
|
76
77
|
control, treatment, report = komlos_split.split_ab(
|
|
77
78
|
df, # pandas / Polars DataFrame or 2D NumPy array
|
|
78
79
|
method="auto", # auto-routes: gfl for m >= 4n, gsw for n > m
|
|
79
80
|
return_report=True,
|
|
80
81
|
)
|
|
81
82
|
print(report.summary())
|
|
83
|
+
|
|
84
|
+
# 2. Custom-ratio train/val split (e.g., 80/20)
|
|
85
|
+
train, val, tv_report = komlos_split.train_val_split(df, train_size=0.8, return_report=True)
|
|
86
|
+
|
|
87
|
+
# 3. Multi-arm A/B/C/D or k-fold CV (any k >= 2: 3, 4, 5, ...)
|
|
88
|
+
groups, k_report = komlos_split.split_k(df, k=4, return_report=True)
|
|
89
|
+
print(k_report.summary())
|
|
82
90
|
```
|
|
83
91
|
|
|
84
92
|
Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariates, 20 simulated A/B trials):
|
|
@@ -87,6 +95,25 @@ Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariate
|
|
|
87
95
|
- **ATE Estimation RMSE:** `0.1479` vs. `0.5196` random (**91.9% variance reduction**).
|
|
88
96
|
- **High-dimensional trial (64 patients × 320 biomarkers, `auto -> gfl`):** Max SMD `0.5815` vs. `0.7316` random (−20.5%).
|
|
89
97
|
|
|
98
|
+
## Rust Quickstart (Native Parity)
|
|
99
|
+
|
|
100
|
+
The exact same high-level API (`SplitMethod::Auto`, standardization, `k`-way splitting, and SMD balance metrics) is available natively in Rust and powers the Python bindings:
|
|
101
|
+
|
|
102
|
+
```rust
|
|
103
|
+
use komlos_split::{assign_groups, compute_smd, split_k, SplitMethod};
|
|
104
|
+
|
|
105
|
+
// Row-major samples: n_samples rows x n_features columns
|
|
106
|
+
let samples: Vec<Vec<f64>> = vec![/* ... */];
|
|
107
|
+
|
|
108
|
+
// 1. Two-way A/B split (returns labels in {0, 1} + resolved method)
|
|
109
|
+
let (labels, method_used) = assign_groups(&samples, SplitMethod::Auto, 42)?;
|
|
110
|
+
let smd = compute_smd(&samples, &labels)?;
|
|
111
|
+
println!("method={method_used:?} max_smd={:.4} mean_smd={:.4}", smd.max_smd, smd.mean_smd);
|
|
112
|
+
|
|
113
|
+
// 2. Multi-arm k-way split (any k >= 2: 3, 4, 5, ...)
|
|
114
|
+
let (k_labels, _) = split_k(&samples, 4, SplitMethod::Auto, 42)?;
|
|
115
|
+
```
|
|
116
|
+
|
|
90
117
|
## Usage
|
|
91
118
|
|
|
92
119
|
```bash
|
|
@@ -63,12 +63,20 @@ Works directly on **pandas DataFrames**, **Polars DataFrames**, **NumPy arrays**
|
|
|
63
63
|
import pandas as pd
|
|
64
64
|
import komlos_split
|
|
65
65
|
|
|
66
|
+
# 1. Two-way A/B split (50/50)
|
|
66
67
|
control, treatment, report = komlos_split.split_ab(
|
|
67
68
|
df, # pandas / Polars DataFrame or 2D NumPy array
|
|
68
69
|
method="auto", # auto-routes: gfl for m >= 4n, gsw for n > m
|
|
69
70
|
return_report=True,
|
|
70
71
|
)
|
|
71
72
|
print(report.summary())
|
|
73
|
+
|
|
74
|
+
# 2. Custom-ratio train/val split (e.g., 80/20)
|
|
75
|
+
train, val, tv_report = komlos_split.train_val_split(df, train_size=0.8, return_report=True)
|
|
76
|
+
|
|
77
|
+
# 3. Multi-arm A/B/C/D or k-fold CV (any k >= 2: 3, 4, 5, ...)
|
|
78
|
+
groups, k_report = komlos_split.split_k(df, k=4, return_report=True)
|
|
79
|
+
print(k_report.summary())
|
|
72
80
|
```
|
|
73
81
|
|
|
74
82
|
Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariates, 20 simulated A/B trials):
|
|
@@ -77,6 +85,25 @@ Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariate
|
|
|
77
85
|
- **ATE Estimation RMSE:** `0.1479` vs. `0.5196` random (**91.9% variance reduction**).
|
|
78
86
|
- **High-dimensional trial (64 patients × 320 biomarkers, `auto -> gfl`):** Max SMD `0.5815` vs. `0.7316` random (−20.5%).
|
|
79
87
|
|
|
88
|
+
## Rust Quickstart (Native Parity)
|
|
89
|
+
|
|
90
|
+
The exact same high-level API (`SplitMethod::Auto`, standardization, `k`-way splitting, and SMD balance metrics) is available natively in Rust and powers the Python bindings:
|
|
91
|
+
|
|
92
|
+
```rust
|
|
93
|
+
use komlos_split::{assign_groups, compute_smd, split_k, SplitMethod};
|
|
94
|
+
|
|
95
|
+
// Row-major samples: n_samples rows x n_features columns
|
|
96
|
+
let samples: Vec<Vec<f64>> = vec![/* ... */];
|
|
97
|
+
|
|
98
|
+
// 1. Two-way A/B split (returns labels in {0, 1} + resolved method)
|
|
99
|
+
let (labels, method_used) = assign_groups(&samples, SplitMethod::Auto, 42)?;
|
|
100
|
+
let smd = compute_smd(&samples, &labels)?;
|
|
101
|
+
println!("method={method_used:?} max_smd={:.4} mean_smd={:.4}", smd.max_smd, smd.mean_smd);
|
|
102
|
+
|
|
103
|
+
// 2. Multi-arm k-way split (any k >= 2: 3, 4, 5, ...)
|
|
104
|
+
let (k_labels, _) = split_k(&samples, 4, SplitMethod::Auto, 42)?;
|
|
105
|
+
```
|
|
106
|
+
|
|
80
107
|
## Usage
|
|
81
108
|
|
|
82
109
|
```bash
|
|
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "komlos-split"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Covariate-balanced A/B & train/val splitting via Guo-Fang-Lu Komlos Discrepancy (arXiv:2609.23540 / arXiv:2609.33215) and Gram-Schmidt Walk"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""komlos-split:
|
|
1
|
+
"""komlos-split v0.2: Covariate-balanced 2-way, custom-ratio, and k-way splitting backed by Rust.
|
|
2
2
|
|
|
3
3
|
Implements the Guo-Fang-Lu Spectral-Potential Walk (arXiv:2609.23540 / arXiv:2609.33215)
|
|
4
4
|
and Gram-Schmidt Walk (STOC 2018) with automatic regime routing:
|
|
@@ -19,12 +19,15 @@ from ._komlos_split import (
|
|
|
19
19
|
py_guo_fang_lu as guo_fang_lu,
|
|
20
20
|
py_normalize_komlos_columns as normalize_komlos_columns,
|
|
21
21
|
py_rademacher_split as rademacher_split,
|
|
22
|
+
py_split_k as _rust_split_k,
|
|
22
23
|
)
|
|
23
24
|
|
|
24
25
|
__all__ = [
|
|
25
26
|
"BalanceReport",
|
|
27
|
+
"MultiBalanceReport",
|
|
26
28
|
"assign_groups",
|
|
27
29
|
"split_ab",
|
|
30
|
+
"split_k",
|
|
28
31
|
"train_val_split",
|
|
29
32
|
"guo_fang_lu",
|
|
30
33
|
"gram_schmidt_walk",
|
|
@@ -63,6 +66,33 @@ class BalanceReport:
|
|
|
63
66
|
return "\n".join(lines)
|
|
64
67
|
|
|
65
68
|
|
|
69
|
+
@dataclass
|
|
70
|
+
class MultiBalanceReport:
|
|
71
|
+
"""Pairwise covariate balance diagnostics across k >= 2 groups."""
|
|
72
|
+
|
|
73
|
+
k: int
|
|
74
|
+
method_used: str
|
|
75
|
+
group_sizes: list[int]
|
|
76
|
+
max_pairwise_smd: float
|
|
77
|
+
mean_pairwise_smd: float
|
|
78
|
+
random_max_pairwise_smd: float
|
|
79
|
+
|
|
80
|
+
def summary(self) -> str:
|
|
81
|
+
reduction = (
|
|
82
|
+
(1.0 - self.max_pairwise_smd / self.random_max_pairwise_smd) * 100.0
|
|
83
|
+
if self.random_max_pairwise_smd > 0.0
|
|
84
|
+
else 0.0
|
|
85
|
+
)
|
|
86
|
+
return "\n".join(
|
|
87
|
+
[
|
|
88
|
+
f"komlos-split MultiBalanceReport (k={self.k}, method={self.method_used})",
|
|
89
|
+
f" Group sizes : {self.group_sizes}",
|
|
90
|
+
f" Max Pairwise SMD : {self.max_pairwise_smd:.4f} (random: {self.random_max_pairwise_smd:.4f}, {reduction:+.1f}%)",
|
|
91
|
+
f" Mean Pairwise SMD: {self.mean_pairwise_smd:.4f}",
|
|
92
|
+
]
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
66
96
|
def _extract_matrix(
|
|
67
97
|
data: Any, covariates: Sequence[str] | None = None
|
|
68
98
|
) -> tuple[list[list[float]], list[str], str]:
|
|
@@ -70,7 +100,6 @@ def _extract_matrix(
|
|
|
70
100
|
cls_mod = type(data).__module__
|
|
71
101
|
cls_name = type(data).__name__
|
|
72
102
|
|
|
73
|
-
# 1. pandas DataFrame
|
|
74
103
|
if cls_mod.startswith("pandas") and cls_name == "DataFrame":
|
|
75
104
|
if covariates is None:
|
|
76
105
|
num_df = data.select_dtypes(include=["number", "bool"])
|
|
@@ -81,14 +110,12 @@ def _extract_matrix(
|
|
|
81
110
|
rows = num_df.astype(float).values.tolist()
|
|
82
111
|
return rows, [str(c) for c in cols], "pandas"
|
|
83
112
|
|
|
84
|
-
# 2. Polars DataFrame
|
|
85
113
|
if cls_mod.startswith("polars") and cls_name == "DataFrame":
|
|
86
114
|
cols = list(covariates) if covariates is not None else list(data.columns)
|
|
87
115
|
sub = data.select(cols)
|
|
88
116
|
rows = [[float(v) for v in r] for r in sub.iter_rows()]
|
|
89
117
|
return rows, [str(c) for c in cols], "polars"
|
|
90
118
|
|
|
91
|
-
# 3. NumPy ndarray
|
|
92
119
|
if cls_mod.startswith("numpy") and hasattr(data, "ndim"):
|
|
93
120
|
if data.ndim != 2:
|
|
94
121
|
raise ValueError(f"Expected 2D array (n_samples, n_features), got ndim={data.ndim}")
|
|
@@ -97,21 +124,17 @@ def _extract_matrix(
|
|
|
97
124
|
names = [str(c) for c in covariates] if covariates is not None else [f"f{i}" for i in range(n_feat)]
|
|
98
125
|
return rows, names, "numpy"
|
|
99
126
|
|
|
100
|
-
# 4. Plain Python sequence of rows
|
|
101
127
|
rows = [[float(v) for v in r] for r in data]
|
|
102
128
|
n_feat = len(rows[0]) if rows else 0
|
|
103
129
|
names = [str(c) for c in covariates] if covariates is not None else [f"f{i}" for i in range(n_feat)]
|
|
104
130
|
return rows, names, "list"
|
|
105
131
|
|
|
106
132
|
|
|
107
|
-
def
|
|
108
|
-
rows: list[list[float]], feature_names: list[str],
|
|
133
|
+
def _compute_smd_indices(
|
|
134
|
+
rows: list[list[float]], feature_names: list[str], idx_a: list[int], idx_b: list[int]
|
|
109
135
|
) -> tuple[float, float, dict[str, float]]:
|
|
110
|
-
"""Compute absolute Standardized Mean Difference (SMD) per feature between
|
|
111
|
-
n = len(rows)
|
|
136
|
+
"""Compute absolute Standardized Mean Difference (SMD) per feature between two index sets."""
|
|
112
137
|
m = len(feature_names)
|
|
113
|
-
idx_a = [j for j, s in enumerate(signs) if s == 1]
|
|
114
|
-
idx_b = [j for j, s in enumerate(signs) if s == -1]
|
|
115
138
|
if not idx_a or not idx_b:
|
|
116
139
|
inf_map = {name: float("inf") for name in feature_names}
|
|
117
140
|
return float("inf"), float("inf"), inf_map
|
|
@@ -132,6 +155,14 @@ def _compute_smd(
|
|
|
132
155
|
return max(vals, default=0.0), (sum(vals) / len(vals) if vals else 0.0), per_feat
|
|
133
156
|
|
|
134
157
|
|
|
158
|
+
def _compute_smd(
|
|
159
|
+
rows: list[list[float]], feature_names: list[str], signs: list[int]
|
|
160
|
+
) -> tuple[float, float, dict[str, float]]:
|
|
161
|
+
idx_a = [j for j, s in enumerate(signs) if s == 1]
|
|
162
|
+
idx_b = [j for j, s in enumerate(signs) if s == -1]
|
|
163
|
+
return _compute_smd_indices(rows, feature_names, idx_a, idx_b)
|
|
164
|
+
|
|
165
|
+
|
|
135
166
|
def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True) -> tuple[list[float], int, int]:
|
|
136
167
|
"""Z-score features, transpose to (m_rows, n_samples), append size-balance row, and unit-normalize columns."""
|
|
137
168
|
n = len(rows)
|
|
@@ -141,7 +172,6 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
141
172
|
if m == 0:
|
|
142
173
|
raise ValueError("Input data must contain at least 1 numeric covariate.")
|
|
143
174
|
|
|
144
|
-
# Validate finite inputs early
|
|
145
175
|
for r in rows:
|
|
146
176
|
if len(r) != m:
|
|
147
177
|
raise ValueError("All sample rows must have identical feature length.")
|
|
@@ -149,7 +179,6 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
149
179
|
if not math.isfinite(v):
|
|
150
180
|
raise ValueError("Input contains non-finite values (NaN or Inf). Impute or drop before splitting.")
|
|
151
181
|
|
|
152
|
-
# Z-score each feature across samples and pack row-major (m_total x n)
|
|
153
182
|
m_total = m + (1 if balance_size else 0)
|
|
154
183
|
flat = [0.0] * (m_total * n)
|
|
155
184
|
|
|
@@ -164,7 +193,6 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
164
193
|
flat[base + j] = (col[j] - mean) * inv_sd
|
|
165
194
|
|
|
166
195
|
if balance_size:
|
|
167
|
-
# Weight the headcount-balance row so |group_a| ≈ |group_b|
|
|
168
196
|
base = m * n
|
|
169
197
|
for j in range(n):
|
|
170
198
|
flat[base + j] = 1.0
|
|
@@ -173,32 +201,34 @@ def _standardize_for_komlos(rows: list[list[float]], balance_size: bool = True)
|
|
|
173
201
|
return norm_flat, m_total, n
|
|
174
202
|
|
|
175
203
|
|
|
204
|
+
def _random_signs_with_ratio(n: int, ratio: float, seed: int) -> list[int]:
|
|
205
|
+
"""Deterministic Bernoulli(ratio) +/-1 baseline."""
|
|
206
|
+
x = seed ^ 0x9E3779B97F4A7C15
|
|
207
|
+
out: list[int] = []
|
|
208
|
+
for _ in range(n):
|
|
209
|
+
x = (x + 0x9E3779B97F4A7C15) & 0xFFFFFFFFFFFFFFFF
|
|
210
|
+
z = x
|
|
211
|
+
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF
|
|
212
|
+
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & 0xFFFFFFFFFFFFFFFF
|
|
213
|
+
z = z ^ (z >> 31)
|
|
214
|
+
u = (z >> 11) * (1.0 / (1 << 53))
|
|
215
|
+
out.append(1 if u < ratio else -1)
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
|
|
176
219
|
def assign_groups(
|
|
177
220
|
data: Any,
|
|
178
221
|
covariates: Sequence[str] | None = None,
|
|
179
222
|
method: str = "auto",
|
|
223
|
+
ratio: float = 0.5,
|
|
180
224
|
seed: int = 42,
|
|
181
225
|
step_size: float = 2.0,
|
|
182
226
|
balance_size: bool = True,
|
|
183
227
|
) -> list[int]:
|
|
184
|
-
"""Return a balanced {-1, +1} assignment vector
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
data : pandas.DataFrame | polars.DataFrame | numpy.ndarray | list[list[float]]
|
|
189
|
-
Input samples of shape (n_samples, n_features).
|
|
190
|
-
covariates : sequence of str, optional
|
|
191
|
-
Column names to balance (for DataFrames). Defaults to all numeric columns.
|
|
192
|
-
method : {"auto", "gfl", "gsw", "greedy", "random"}
|
|
193
|
-
"auto" routes to Guo-Fang-Lu when n_features >= 4 * n_samples (tall/overconstrained)
|
|
194
|
-
and Gram-Schmidt Walk otherwise.
|
|
195
|
-
seed : int
|
|
196
|
-
Deterministic PRNG seed.
|
|
197
|
-
step_size : float
|
|
198
|
-
Step size eta for Guo-Fang-Lu (default 2.0; use 0.25 for tighter high-m discrepancy).
|
|
199
|
-
balance_size : bool
|
|
200
|
-
Include an explicit headcount-balance constraint so groups stay ~50/50.
|
|
201
|
-
"""
|
|
228
|
+
"""Return a balanced {-1, +1} assignment vector with target `+1` fraction `ratio` in (0, 1)."""
|
|
229
|
+
if not (0.0 < ratio < 1.0):
|
|
230
|
+
raise ValueError(f"ratio must be strictly between 0.0 and 1.0, got {ratio}")
|
|
231
|
+
|
|
202
232
|
rows, _, _ = _extract_matrix(data, covariates=covariates)
|
|
203
233
|
flat, m_total, n = _standardize_for_komlos(rows, balance_size=balance_size)
|
|
204
234
|
|
|
@@ -208,50 +238,37 @@ def assign_groups(
|
|
|
208
238
|
chosen = "gfl" if n_features >= 4 * n else "gsw"
|
|
209
239
|
|
|
210
240
|
if chosen in ("gfl", "guo_fang_lu"):
|
|
211
|
-
return list(guo_fang_lu(flat, m_total, n, step_size=step_size, seed=seed))
|
|
241
|
+
return list(guo_fang_lu(flat, m_total, n, step_size=step_size, seed=seed, ratio=ratio))
|
|
212
242
|
if chosen in ("gsw", "gram_schmidt"):
|
|
213
|
-
return list(gram_schmidt_walk(flat, m_total, n, seed=seed))
|
|
243
|
+
return list(gram_schmidt_walk(flat, m_total, n, seed=seed, ratio=ratio))
|
|
214
244
|
if chosen == "greedy":
|
|
215
245
|
return list(greedy_split(flat, m_total, n))
|
|
216
246
|
if chosen in ("random", "rademacher"):
|
|
217
|
-
return
|
|
247
|
+
return _random_signs_with_ratio(n, ratio, seed)
|
|
218
248
|
raise ValueError(f"Unknown method '{method}'. Expected one of: auto, gfl, gsw, greedy, random.")
|
|
219
249
|
|
|
220
250
|
|
|
221
|
-
def
|
|
222
|
-
mask_b = [not b for b in mask_a]
|
|
251
|
+
def _slice_indices(data: Any, kind: str, indices: list[int]) -> Any:
|
|
223
252
|
if kind == "pandas":
|
|
224
|
-
return data.
|
|
253
|
+
return data.iloc[indices].copy()
|
|
225
254
|
if kind == "polars":
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
return data.filter(pl.Series(mask_a)), data.filter(pl.Series(mask_b))
|
|
255
|
+
return data[indices]
|
|
229
256
|
if kind == "numpy":
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
arr_a = np.asarray(mask_a, dtype=bool)
|
|
233
|
-
return data[arr_a], data[~arr_a]
|
|
234
|
-
return (
|
|
235
|
-
[row for row, m in zip(data, mask_a) if m],
|
|
236
|
-
[row for row, m in zip(data, mask_b) if m],
|
|
237
|
-
)
|
|
257
|
+
return data[indices]
|
|
258
|
+
return [data[i] for i in indices]
|
|
238
259
|
|
|
239
260
|
|
|
240
261
|
def split_ab(
|
|
241
262
|
data: Any,
|
|
242
263
|
covariates: Sequence[str] | None = None,
|
|
243
264
|
method: str = "auto",
|
|
265
|
+
ratio: float = 0.5,
|
|
244
266
|
seed: int = 42,
|
|
245
267
|
step_size: float = 2.0,
|
|
246
268
|
balance_size: bool = True,
|
|
247
269
|
return_report: bool = False,
|
|
248
270
|
) -> Any:
|
|
249
|
-
"""Split `data` into two covariate-balanced groups
|
|
250
|
-
|
|
251
|
-
Preserves the input type (pandas DataFrame, Polars DataFrame, NumPy ndarray, or list).
|
|
252
|
-
Set `return_report=True` to also receive a `BalanceReport` with Standardized Mean
|
|
253
|
-
Difference (SMD) diagnostics compared against a same-seed random split.
|
|
254
|
-
"""
|
|
271
|
+
"""Split `data` into two covariate-balanced groups with target Group A fraction `ratio`."""
|
|
255
272
|
rows, feature_names, kind = _extract_matrix(data, covariates=covariates)
|
|
256
273
|
n = len(rows)
|
|
257
274
|
n_features = len(feature_names)
|
|
@@ -260,23 +277,26 @@ def split_ab(
|
|
|
260
277
|
signs = assign_groups(
|
|
261
278
|
rows,
|
|
262
279
|
method=resolved,
|
|
280
|
+
ratio=ratio,
|
|
263
281
|
seed=seed,
|
|
264
282
|
step_size=step_size,
|
|
265
283
|
balance_size=balance_size,
|
|
266
284
|
)
|
|
267
|
-
|
|
268
|
-
|
|
285
|
+
idx_a = [i for i, s in enumerate(signs) if s == 1]
|
|
286
|
+
idx_b = [i for i, s in enumerate(signs) if s == -1]
|
|
287
|
+
group_a = _slice_indices(data, kind, idx_a)
|
|
288
|
+
group_b = _slice_indices(data, kind, idx_b)
|
|
269
289
|
|
|
270
290
|
if not return_report:
|
|
271
291
|
return group_a, group_b
|
|
272
292
|
|
|
273
|
-
max_smd, mean_smd, per_feat =
|
|
274
|
-
rand_signs =
|
|
293
|
+
max_smd, mean_smd, per_feat = _compute_smd_indices(rows, feature_names, idx_a, idx_b)
|
|
294
|
+
rand_signs = _random_signs_with_ratio(n, ratio, seed)
|
|
275
295
|
r_max_smd, r_mean_smd, _ = _compute_smd(rows, feature_names, rand_signs)
|
|
276
296
|
report = BalanceReport(
|
|
277
297
|
method_used=resolved,
|
|
278
|
-
n_group_a=
|
|
279
|
-
n_group_b=
|
|
298
|
+
n_group_a=len(idx_a),
|
|
299
|
+
n_group_b=len(idx_b),
|
|
280
300
|
max_smd=max_smd,
|
|
281
301
|
mean_smd=mean_smd,
|
|
282
302
|
random_max_smd=r_max_smd,
|
|
@@ -288,16 +308,97 @@ def split_ab(
|
|
|
288
308
|
|
|
289
309
|
def train_val_split(
|
|
290
310
|
data: Any,
|
|
311
|
+
train_size: float = 0.8,
|
|
291
312
|
covariates: Sequence[str] | None = None,
|
|
292
313
|
method: str = "auto",
|
|
293
314
|
seed: int = 42,
|
|
294
315
|
return_report: bool = False,
|
|
295
316
|
) -> Any:
|
|
296
|
-
"""
|
|
317
|
+
"""Split `data` into covariate-balanced `(train, val)` with arbitrary `train_size` (default 0.8)."""
|
|
297
318
|
return split_ab(
|
|
298
319
|
data,
|
|
299
320
|
covariates=covariates,
|
|
300
321
|
method=method,
|
|
322
|
+
ratio=train_size,
|
|
301
323
|
seed=seed,
|
|
302
324
|
return_report=return_report,
|
|
303
325
|
)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def split_k(
|
|
329
|
+
data: Any,
|
|
330
|
+
k: int = 4,
|
|
331
|
+
covariates: Sequence[str] | None = None,
|
|
332
|
+
method: str = "auto",
|
|
333
|
+
seed: int = 42,
|
|
334
|
+
step_size: float = 2.0,
|
|
335
|
+
balance_size: bool = True,
|
|
336
|
+
return_report: bool = False,
|
|
337
|
+
) -> Any:
|
|
338
|
+
"""Split `data` into `k >= 2` equally sized, covariate-balanced groups (A/B/C/D or k-fold CV).
|
|
339
|
+
|
|
340
|
+
Works for any `k >= 2` (including non-powers of 2 like 3, 5, 10) via recursive
|
|
341
|
+
ratio-weighted Komlos / Gram-Schmidt splits.
|
|
342
|
+
"""
|
|
343
|
+
if k < 2:
|
|
344
|
+
raise ValueError(f"k must be >= 2, got {k}")
|
|
345
|
+
rows, feature_names, kind = _extract_matrix(data, covariates=covariates)
|
|
346
|
+
n = len(rows)
|
|
347
|
+
if n < k:
|
|
348
|
+
raise ValueError(f"Cannot split {n} samples into {k} non-empty groups.")
|
|
349
|
+
|
|
350
|
+
n_features = len(feature_names)
|
|
351
|
+
resolved = ("gfl" if n_features >= 4 * n else "gsw") if method.lower() == "auto" else method.lower()
|
|
352
|
+
|
|
353
|
+
flat_samples = [v for r in rows for v in r]
|
|
354
|
+
labels = list(
|
|
355
|
+
_rust_split_k(
|
|
356
|
+
flat_samples,
|
|
357
|
+
n,
|
|
358
|
+
n_features,
|
|
359
|
+
k,
|
|
360
|
+
method=resolved,
|
|
361
|
+
seed=seed,
|
|
362
|
+
step_size=step_size,
|
|
363
|
+
balance_size=balance_size,
|
|
364
|
+
)
|
|
365
|
+
)
|
|
366
|
+
group_indices: list[list[int]] = [[] for _ in range(k)]
|
|
367
|
+
for idx, arm in enumerate(labels):
|
|
368
|
+
group_indices[arm].append(idx)
|
|
369
|
+
groups = [_slice_indices(data, kind, idxs) for idxs in group_indices]
|
|
370
|
+
|
|
371
|
+
if not return_report:
|
|
372
|
+
return groups
|
|
373
|
+
|
|
374
|
+
# Pairwise SMD across all k(k-1)/2 pairs
|
|
375
|
+
pair_maxes: list[float] = []
|
|
376
|
+
pair_means: list[float] = []
|
|
377
|
+
for i in range(k):
|
|
378
|
+
for j in range(i + 1, k):
|
|
379
|
+
mx, mn, _ = _compute_smd_indices(rows, feature_names, group_indices[i], group_indices[j])
|
|
380
|
+
pair_maxes.append(mx)
|
|
381
|
+
pair_means.append(mn)
|
|
382
|
+
|
|
383
|
+
# Same-seed random k-way baseline
|
|
384
|
+
x = seed ^ 0x9E3779B97F4A7C15
|
|
385
|
+
rand_buckets: list[list[int]] = [[] for _ in range(k)]
|
|
386
|
+
for idx in range(n):
|
|
387
|
+
x = (x + 0x9E3779B97F4A7C15) & 0xFFFFFFFFFFFFFFFF
|
|
388
|
+
z = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & 0xFFFFFFFFFFFFFFFF
|
|
389
|
+
rand_buckets[(z >> 16) % k].append(idx)
|
|
390
|
+
rand_pair_maxes = [
|
|
391
|
+
_compute_smd_indices(rows, feature_names, rand_buckets[i], rand_buckets[j])[0]
|
|
392
|
+
for i in range(k)
|
|
393
|
+
for j in range(i + 1, k)
|
|
394
|
+
]
|
|
395
|
+
|
|
396
|
+
report = MultiBalanceReport(
|
|
397
|
+
k=k,
|
|
398
|
+
method_used=resolved,
|
|
399
|
+
group_sizes=[len(g) for g in group_indices],
|
|
400
|
+
max_pairwise_smd=max(pair_maxes, default=0.0),
|
|
401
|
+
mean_pairwise_smd=sum(pair_means) / len(pair_means) if pair_means else 0.0,
|
|
402
|
+
random_max_pairwise_smd=max(rand_pair_maxes, default=0.0),
|
|
403
|
+
)
|
|
404
|
+
return groups, report
|
|
@@ -216,9 +216,24 @@ fn solve_spd(g: &[f64], rhs: &[f64], k: usize) -> Vec<f64> {
|
|
|
216
216
|
/// minimizing `||A_V u||_2^2`, and moves to the boundary +/-1 with zero-mean
|
|
217
217
|
/// randomized step size so at least one coordinate freezes every iteration.
|
|
218
218
|
pub fn gram_schmidt_walk(a: &[f64], m: usize, n: usize, seed: u64) -> Result<Vec<i8>, &'static str> {
|
|
219
|
+
gram_schmidt_walk_with_ratio(a, m, n, 0.5, seed)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// Gram–Schmidt Walk starting from fractional point `x_0 = (2 * ratio - 1) * 1`
|
|
223
|
+
/// for arbitrary split ratios `ratio in (0, 1)` (e.g., 0.8 for 80/20 train/val).
|
|
224
|
+
pub fn gram_schmidt_walk_with_ratio(
|
|
225
|
+
a: &[f64],
|
|
226
|
+
m: usize,
|
|
227
|
+
n: usize,
|
|
228
|
+
ratio: f64,
|
|
229
|
+
seed: u64,
|
|
230
|
+
) -> Result<Vec<i8>, &'static str> {
|
|
219
231
|
validate_matrix(a, m, n)?;
|
|
232
|
+
if !ratio.is_finite() || ratio <= 0.0 || ratio >= 1.0 {
|
|
233
|
+
return Err("ratio must be strictly between 0.0 and 1.0");
|
|
234
|
+
}
|
|
220
235
|
let mut rng = Rng64::new(seed);
|
|
221
|
-
let mut x = vec![0.
|
|
236
|
+
let mut x = vec![2.0 * ratio - 1.0; n];
|
|
222
237
|
let mut alive: Vec<usize> = (0..n).collect();
|
|
223
238
|
let eps = 1e-9;
|
|
224
239
|
|
|
@@ -361,6 +376,8 @@ pub struct GflConfig {
|
|
|
361
376
|
pub step_size: f64,
|
|
362
377
|
/// Slack threshold `sigma_crit` below which a medium row is marked dangerous.
|
|
363
378
|
pub danger_slack: f64,
|
|
379
|
+
/// Target fraction of `+1` assignments in `(0, 1)` (default `0.5` -> `x_0 = 0`).
|
|
380
|
+
pub ratio: f64,
|
|
364
381
|
/// Deterministic PRNG seed for initial subspace direction sampling.
|
|
365
382
|
pub seed: u64,
|
|
366
383
|
}
|
|
@@ -371,6 +388,7 @@ impl Default for GflConfig {
|
|
|
371
388
|
target_beta: 0.0,
|
|
372
389
|
step_size: 2.0,
|
|
373
390
|
danger_slack: 0.5,
|
|
391
|
+
ratio: 0.5,
|
|
374
392
|
seed: 42,
|
|
375
393
|
}
|
|
376
394
|
}
|
|
@@ -446,8 +464,12 @@ pub fn guo_fang_lu_walk(
|
|
|
446
464
|
cfg: GflConfig,
|
|
447
465
|
) -> Result<Vec<i8>, &'static str> {
|
|
448
466
|
validate_matrix(a, m, n)?;
|
|
467
|
+
if !cfg.ratio.is_finite() || cfg.ratio <= 0.0 || cfg.ratio >= 1.0 {
|
|
468
|
+
return Err("cfg.ratio must be strictly between 0.0 and 1.0");
|
|
469
|
+
}
|
|
449
470
|
let mut rng = Rng64::new(cfg.seed);
|
|
450
|
-
let
|
|
471
|
+
let x0_val = 2.0 * cfg.ratio - 1.0;
|
|
472
|
+
let mut x = vec![x0_val; n];
|
|
451
473
|
let mut alive: Vec<usize> = (0..n).collect();
|
|
452
474
|
let eps = 1e-8;
|
|
453
475
|
const K_KOMLOS: f64 = 16.0;
|
|
@@ -473,6 +495,7 @@ pub fn guo_fang_lu_walk(
|
|
|
473
495
|
};
|
|
474
496
|
|
|
475
497
|
// One-sided doubled rows: indices 0..m are +a_i, indices m..2m are -a_i.
|
|
498
|
+
// Track discrepancy relative to starting point x_0 (so d_0(i) = <a_i, x - x_0> = 0).
|
|
476
499
|
let m2 = 2 * m;
|
|
477
500
|
let mut row_disc = vec![0.0f64; m2];
|
|
478
501
|
// Section 4 heavy-entry tracking mask: tracked[i * n + j] == true while j is in S_{i,t}.
|
|
@@ -966,16 +989,341 @@ pub fn guo_fang_lu_walk(
|
|
|
966
989
|
Ok(x.into_iter().map(|v| if v >= 0.0 { 1 } else { -1 }).collect())
|
|
967
990
|
}
|
|
968
991
|
|
|
992
|
+
// ============================================================================
|
|
993
|
+
// High-Level Splitting & Balance Diagnostics (Native Rust Parity with Python)
|
|
994
|
+
// ============================================================================
|
|
995
|
+
|
|
996
|
+
/// Algorithm selector for high-level `assign_groups` and `split_k`.
|
|
997
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
998
|
+
pub enum SplitMethod {
|
|
999
|
+
/// Routes to `GuoFangLu` when `n_features >= 4 * n_samples`, `GramSchmidt` otherwise.
|
|
1000
|
+
Auto,
|
|
1001
|
+
GuoFangLu,
|
|
1002
|
+
GramSchmidt,
|
|
1003
|
+
Greedy,
|
|
1004
|
+
Random,
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/// Standardized Mean Difference (SMD) diagnostics between two groups.
|
|
1008
|
+
#[derive(Debug, Clone, PartialEq)]
|
|
1009
|
+
pub struct BalanceMetrics {
|
|
1010
|
+
pub max_smd: f64,
|
|
1011
|
+
pub mean_smd: f64,
|
|
1012
|
+
pub per_feature_smd: Vec<f64>,
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/// Z-scores features of a row-major `(n_samples x n_features)` matrix, transposes to
|
|
1016
|
+
/// `(m_total x n_samples)` (optionally appending a headcount-balance row), and applies
|
|
1017
|
+
/// Komlós unit-column normalization.
|
|
1018
|
+
pub fn standardize_for_komlos(
|
|
1019
|
+
samples: &[f64],
|
|
1020
|
+
n_samples: usize,
|
|
1021
|
+
n_features: usize,
|
|
1022
|
+
balance_size: bool,
|
|
1023
|
+
) -> Result<(Vec<f64>, usize, usize), &'static str> {
|
|
1024
|
+
validate_matrix(samples, n_samples, n_features)?;
|
|
1025
|
+
let m_total = n_features + usize::from(balance_size);
|
|
1026
|
+
let mut flat = vec![0.0f64; m_total * n_samples];
|
|
1027
|
+
|
|
1028
|
+
for f in 0..n_features {
|
|
1029
|
+
let mut mean = 0.0;
|
|
1030
|
+
for j in 0..n_samples {
|
|
1031
|
+
mean += samples[j * n_features + f];
|
|
1032
|
+
}
|
|
1033
|
+
mean /= n_samples as f64;
|
|
1034
|
+
|
|
1035
|
+
let mut var = 0.0;
|
|
1036
|
+
for j in 0..n_samples {
|
|
1037
|
+
let d = samples[j * n_features + f] - mean;
|
|
1038
|
+
var += d * d;
|
|
1039
|
+
}
|
|
1040
|
+
var /= n_samples as f64;
|
|
1041
|
+
let sd = var.sqrt();
|
|
1042
|
+
let inv_sd = if sd > 1e-12 { 1.0 / sd } else { 0.0 };
|
|
1043
|
+
|
|
1044
|
+
let base = f * n_samples;
|
|
1045
|
+
for j in 0..n_samples {
|
|
1046
|
+
flat[base + j] = (samples[j * n_features + f] - mean) * inv_sd;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
if balance_size {
|
|
1051
|
+
let base = n_features * n_samples;
|
|
1052
|
+
flat[base..base + n_samples].fill(1.0);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
let norm = normalize_komlos_columns(&flat, m_total, n_samples)?;
|
|
1056
|
+
Ok((norm, m_total, n_samples))
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/// Assigns each of `n_samples` rows (in a row-major `n_samples x n_features` matrix)
|
|
1060
|
+
/// to `+1` or `-1` with target `+1` fraction `ratio in (0, 1)`.
|
|
1061
|
+
#[allow(clippy::too_many_arguments)]
|
|
1062
|
+
pub fn assign_groups(
|
|
1063
|
+
samples: &[f64],
|
|
1064
|
+
n_samples: usize,
|
|
1065
|
+
n_features: usize,
|
|
1066
|
+
method: SplitMethod,
|
|
1067
|
+
ratio: f64,
|
|
1068
|
+
seed: u64,
|
|
1069
|
+
step_size: f64,
|
|
1070
|
+
balance_size: bool,
|
|
1071
|
+
) -> Result<Vec<i8>, &'static str> {
|
|
1072
|
+
if !ratio.is_finite() || ratio <= 0.0 || ratio >= 1.0 {
|
|
1073
|
+
return Err("ratio must be strictly between 0.0 and 1.0");
|
|
1074
|
+
}
|
|
1075
|
+
let (flat, m_total, n) = standardize_for_komlos(samples, n_samples, n_features, balance_size)?;
|
|
1076
|
+
let resolved = match method {
|
|
1077
|
+
SplitMethod::Auto => {
|
|
1078
|
+
if n_features >= 4 * n {
|
|
1079
|
+
SplitMethod::GuoFangLu
|
|
1080
|
+
} else {
|
|
1081
|
+
SplitMethod::GramSchmidt
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
other => other,
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
match resolved {
|
|
1088
|
+
SplitMethod::GuoFangLu => guo_fang_lu_walk(
|
|
1089
|
+
&flat,
|
|
1090
|
+
m_total,
|
|
1091
|
+
n,
|
|
1092
|
+
GflConfig {
|
|
1093
|
+
step_size,
|
|
1094
|
+
ratio,
|
|
1095
|
+
seed,
|
|
1096
|
+
..GflConfig::default()
|
|
1097
|
+
},
|
|
1098
|
+
),
|
|
1099
|
+
SplitMethod::GramSchmidt => gram_schmidt_walk_with_ratio(&flat, m_total, n, ratio, seed),
|
|
1100
|
+
SplitMethod::Greedy => greedy_split(&flat, m_total, n),
|
|
1101
|
+
SplitMethod::Random => {
|
|
1102
|
+
let mut rng = Rng64::new(seed);
|
|
1103
|
+
Ok((0..n)
|
|
1104
|
+
.map(|_| if rng.next_f64() < ratio { 1 } else { -1 })
|
|
1105
|
+
.collect())
|
|
1106
|
+
}
|
|
1107
|
+
SplitMethod::Auto => unreachable!(),
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/// Splits `n_samples` rows into `k >= 2` equally sized, covariate-balanced arms (`0..k`).
|
|
1112
|
+
///
|
|
1113
|
+
/// Works for any `k >= 2` (including non-powers of 2 such as 3, 5, 10) via recursive
|
|
1114
|
+
/// ratio-weighted Komlós / Gram-Schmidt splits.
|
|
1115
|
+
#[allow(clippy::too_many_arguments)]
|
|
1116
|
+
pub fn split_k(
|
|
1117
|
+
samples: &[f64],
|
|
1118
|
+
n_samples: usize,
|
|
1119
|
+
n_features: usize,
|
|
1120
|
+
k: usize,
|
|
1121
|
+
method: SplitMethod,
|
|
1122
|
+
seed: u64,
|
|
1123
|
+
step_size: f64,
|
|
1124
|
+
balance_size: bool,
|
|
1125
|
+
) -> Result<Vec<usize>, &'static str> {
|
|
1126
|
+
validate_matrix(samples, n_samples, n_features)?;
|
|
1127
|
+
if k < 2 {
|
|
1128
|
+
return Err("k must be >= 2");
|
|
1129
|
+
}
|
|
1130
|
+
if n_samples < k {
|
|
1131
|
+
return Err("n_samples must be >= k");
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
let resolved = match method {
|
|
1135
|
+
SplitMethod::Auto => {
|
|
1136
|
+
if n_features >= 4 * n_samples {
|
|
1137
|
+
SplitMethod::GuoFangLu
|
|
1138
|
+
} else {
|
|
1139
|
+
SplitMethod::GramSchmidt
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
other => other,
|
|
1143
|
+
};
|
|
1144
|
+
|
|
1145
|
+
#[allow(clippy::too_many_arguments)]
|
|
1146
|
+
fn recurse(
|
|
1147
|
+
samples: &[f64],
|
|
1148
|
+
n_features: usize,
|
|
1149
|
+
indices: &[usize],
|
|
1150
|
+
arms: usize,
|
|
1151
|
+
base_arm: usize,
|
|
1152
|
+
method: SplitMethod,
|
|
1153
|
+
seed: u64,
|
|
1154
|
+
step_size: f64,
|
|
1155
|
+
balance_size: bool,
|
|
1156
|
+
labels: &mut [usize],
|
|
1157
|
+
) -> Result<(), &'static str> {
|
|
1158
|
+
if arms == 1 {
|
|
1159
|
+
for &idx in indices {
|
|
1160
|
+
labels[idx] = base_arm;
|
|
1161
|
+
}
|
|
1162
|
+
return Ok(());
|
|
1163
|
+
}
|
|
1164
|
+
let left_arms = arms / 2;
|
|
1165
|
+
let right_arms = arms - left_arms;
|
|
1166
|
+
let sub_ratio = (left_arms as f64) / (arms as f64);
|
|
1167
|
+
|
|
1168
|
+
let mut sub_samples = Vec::with_capacity(indices.len() * n_features);
|
|
1169
|
+
for &idx in indices {
|
|
1170
|
+
sub_samples.extend_from_slice(&samples[idx * n_features..(idx + 1) * n_features]);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
let signs = assign_groups(
|
|
1174
|
+
&sub_samples,
|
|
1175
|
+
indices.len(),
|
|
1176
|
+
n_features,
|
|
1177
|
+
method,
|
|
1178
|
+
sub_ratio,
|
|
1179
|
+
seed,
|
|
1180
|
+
step_size,
|
|
1181
|
+
balance_size,
|
|
1182
|
+
)?;
|
|
1183
|
+
|
|
1184
|
+
let mut left_idx: Vec<usize> = Vec::new();
|
|
1185
|
+
let mut right_idx: Vec<usize> = Vec::new();
|
|
1186
|
+
for (&idx, &s) in indices.iter().zip(signs.iter()) {
|
|
1187
|
+
if s == 1 {
|
|
1188
|
+
left_idx.push(idx);
|
|
1189
|
+
} else {
|
|
1190
|
+
right_idx.push(idx);
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
if left_idx.len() < left_arms || right_idx.len() < right_arms {
|
|
1194
|
+
let cut = ((indices.len() as f64 * sub_ratio).round() as usize)
|
|
1195
|
+
.clamp(left_arms, indices.len() - right_arms);
|
|
1196
|
+
left_idx = indices[..cut].to_vec();
|
|
1197
|
+
right_idx = indices[cut..].to_vec();
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
recurse(
|
|
1201
|
+
samples,
|
|
1202
|
+
n_features,
|
|
1203
|
+
&left_idx,
|
|
1204
|
+
left_arms,
|
|
1205
|
+
base_arm,
|
|
1206
|
+
method,
|
|
1207
|
+
seed.wrapping_mul(31).wrapping_add(1),
|
|
1208
|
+
step_size,
|
|
1209
|
+
balance_size,
|
|
1210
|
+
labels,
|
|
1211
|
+
)?;
|
|
1212
|
+
recurse(
|
|
1213
|
+
samples,
|
|
1214
|
+
n_features,
|
|
1215
|
+
&right_idx,
|
|
1216
|
+
right_arms,
|
|
1217
|
+
base_arm + left_arms,
|
|
1218
|
+
method,
|
|
1219
|
+
seed.wrapping_mul(31).wrapping_add(2),
|
|
1220
|
+
step_size,
|
|
1221
|
+
balance_size,
|
|
1222
|
+
labels,
|
|
1223
|
+
)
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
let all_indices: Vec<usize> = (0..n_samples).collect();
|
|
1227
|
+
let mut labels = vec![0usize; n_samples];
|
|
1228
|
+
recurse(
|
|
1229
|
+
samples,
|
|
1230
|
+
n_features,
|
|
1231
|
+
&all_indices,
|
|
1232
|
+
k,
|
|
1233
|
+
0,
|
|
1234
|
+
resolved,
|
|
1235
|
+
seed,
|
|
1236
|
+
step_size,
|
|
1237
|
+
balance_size,
|
|
1238
|
+
&mut labels,
|
|
1239
|
+
)?;
|
|
1240
|
+
Ok(labels)
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/// Computes absolute Standardized Mean Difference (SMD) per feature between two index sets.
|
|
1244
|
+
pub fn compute_smd(
|
|
1245
|
+
samples: &[f64],
|
|
1246
|
+
n_samples: usize,
|
|
1247
|
+
n_features: usize,
|
|
1248
|
+
idx_a: &[usize],
|
|
1249
|
+
idx_b: &[usize],
|
|
1250
|
+
) -> Result<BalanceMetrics, &'static str> {
|
|
1251
|
+
validate_matrix(samples, n_samples, n_features)?;
|
|
1252
|
+
if idx_a.is_empty() || idx_b.is_empty() {
|
|
1253
|
+
return Err("both groups must be non-empty to compute SMD");
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
let mut per_feature = Vec::with_capacity(n_features);
|
|
1257
|
+
let mut max_smd = 0.0f64;
|
|
1258
|
+
let mut sum_smd = 0.0f64;
|
|
1259
|
+
|
|
1260
|
+
for f in 0..n_features {
|
|
1261
|
+
let mean_a = idx_a
|
|
1262
|
+
.iter()
|
|
1263
|
+
.map(|&j| samples[j * n_features + f])
|
|
1264
|
+
.sum::<f64>()
|
|
1265
|
+
/ (idx_a.len() as f64);
|
|
1266
|
+
let mean_b = idx_b
|
|
1267
|
+
.iter()
|
|
1268
|
+
.map(|&j| samples[j * n_features + f])
|
|
1269
|
+
.sum::<f64>()
|
|
1270
|
+
/ (idx_b.len() as f64);
|
|
1271
|
+
|
|
1272
|
+
let var_a = idx_a
|
|
1273
|
+
.iter()
|
|
1274
|
+
.map(|&j| {
|
|
1275
|
+
let d = samples[j * n_features + f] - mean_a;
|
|
1276
|
+
d * d
|
|
1277
|
+
})
|
|
1278
|
+
.sum::<f64>()
|
|
1279
|
+
/ (idx_a.len().saturating_sub(1).max(1) as f64);
|
|
1280
|
+
let var_b = idx_b
|
|
1281
|
+
.iter()
|
|
1282
|
+
.map(|&j| {
|
|
1283
|
+
let d = samples[j * n_features + f] - mean_b;
|
|
1284
|
+
d * d
|
|
1285
|
+
})
|
|
1286
|
+
.sum::<f64>()
|
|
1287
|
+
/ (idx_b.len().saturating_sub(1).max(1) as f64);
|
|
1288
|
+
|
|
1289
|
+
let pooled_sd = (0.5 * (var_a + var_b)).sqrt();
|
|
1290
|
+
let smd = if pooled_sd > 1e-12 {
|
|
1291
|
+
(mean_a - mean_b).abs() / pooled_sd
|
|
1292
|
+
} else {
|
|
1293
|
+
0.0
|
|
1294
|
+
};
|
|
1295
|
+
if smd > max_smd {
|
|
1296
|
+
max_smd = smd;
|
|
1297
|
+
}
|
|
1298
|
+
sum_smd += smd;
|
|
1299
|
+
per_feature.push(smd);
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
Ok(BalanceMetrics {
|
|
1303
|
+
max_smd,
|
|
1304
|
+
mean_smd: sum_smd / (n_features as f64),
|
|
1305
|
+
per_feature_smd: per_feature,
|
|
1306
|
+
})
|
|
1307
|
+
}
|
|
1308
|
+
|
|
969
1309
|
// ============================================================================
|
|
970
1310
|
// Python (PyO3) Bindings
|
|
971
1311
|
// ============================================================================
|
|
972
1312
|
|
|
973
1313
|
#[cfg(feature = "python")]
|
|
974
1314
|
#[pyfunction]
|
|
975
|
-
#[pyo3(signature = (a, m, n, step_size = 0
|
|
976
|
-
fn py_guo_fang_lu(
|
|
1315
|
+
#[pyo3(signature = (a, m, n, step_size = 2.0, seed = 42, ratio = 0.5))]
|
|
1316
|
+
fn py_guo_fang_lu(
|
|
1317
|
+
a: Vec<f64>,
|
|
1318
|
+
m: usize,
|
|
1319
|
+
n: usize,
|
|
1320
|
+
step_size: f64,
|
|
1321
|
+
seed: u64,
|
|
1322
|
+
ratio: f64,
|
|
1323
|
+
) -> PyResult<Vec<i8>> {
|
|
977
1324
|
let cfg = GflConfig {
|
|
978
1325
|
step_size,
|
|
1326
|
+
ratio,
|
|
979
1327
|
seed,
|
|
980
1328
|
..GflConfig::default()
|
|
981
1329
|
};
|
|
@@ -984,9 +1332,16 @@ fn py_guo_fang_lu(a: Vec<f64>, m: usize, n: usize, step_size: f64, seed: u64) ->
|
|
|
984
1332
|
|
|
985
1333
|
#[cfg(feature = "python")]
|
|
986
1334
|
#[pyfunction]
|
|
987
|
-
#[pyo3(signature = (a, m, n, seed = 42))]
|
|
988
|
-
fn py_gram_schmidt_walk(
|
|
989
|
-
|
|
1335
|
+
#[pyo3(signature = (a, m, n, seed = 42, ratio = 0.5))]
|
|
1336
|
+
fn py_gram_schmidt_walk(
|
|
1337
|
+
a: Vec<f64>,
|
|
1338
|
+
m: usize,
|
|
1339
|
+
n: usize,
|
|
1340
|
+
seed: u64,
|
|
1341
|
+
ratio: f64,
|
|
1342
|
+
) -> PyResult<Vec<i8>> {
|
|
1343
|
+
gram_schmidt_walk_with_ratio(&a, m, n, ratio, seed)
|
|
1344
|
+
.map_err(pyo3::exceptions::PyValueError::new_err)
|
|
990
1345
|
}
|
|
991
1346
|
|
|
992
1347
|
#[cfg(feature = "python")]
|
|
@@ -1014,6 +1369,36 @@ fn py_rademacher_split(n: usize, seed: u64) -> Vec<i8> {
|
|
|
1014
1369
|
rademacher_split(n, seed)
|
|
1015
1370
|
}
|
|
1016
1371
|
|
|
1372
|
+
#[cfg(feature = "python")]
|
|
1373
|
+
#[pyfunction]
|
|
1374
|
+
#[pyo3(signature = (samples, n_samples, n_features, k, method = "auto", seed = 42, step_size = 2.0, balance_size = true))]
|
|
1375
|
+
#[allow(clippy::too_many_arguments)]
|
|
1376
|
+
fn py_split_k(
|
|
1377
|
+
samples: Vec<f64>,
|
|
1378
|
+
n_samples: usize,
|
|
1379
|
+
n_features: usize,
|
|
1380
|
+
k: usize,
|
|
1381
|
+
method: &str,
|
|
1382
|
+
seed: u64,
|
|
1383
|
+
step_size: f64,
|
|
1384
|
+
balance_size: bool,
|
|
1385
|
+
) -> PyResult<Vec<usize>> {
|
|
1386
|
+
let m = match method.to_lowercase().as_str() {
|
|
1387
|
+
"auto" => SplitMethod::Auto,
|
|
1388
|
+
"gfl" | "guo_fang_lu" => SplitMethod::GuoFangLu,
|
|
1389
|
+
"gsw" | "gram_schmidt" => SplitMethod::GramSchmidt,
|
|
1390
|
+
"greedy" => SplitMethod::Greedy,
|
|
1391
|
+
"random" | "rademacher" => SplitMethod::Random,
|
|
1392
|
+
_ => {
|
|
1393
|
+
return Err(pyo3::exceptions::PyValueError::new_err(
|
|
1394
|
+
"unknown method; expected auto, gfl, gsw, greedy, or random",
|
|
1395
|
+
))
|
|
1396
|
+
}
|
|
1397
|
+
};
|
|
1398
|
+
split_k(&samples, n_samples, n_features, k, m, seed, step_size, balance_size)
|
|
1399
|
+
.map_err(pyo3::exceptions::PyValueError::new_err)
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1017
1402
|
#[cfg(feature = "python")]
|
|
1018
1403
|
#[pymodule]
|
|
1019
1404
|
fn _komlos_split(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
@@ -1023,6 +1408,7 @@ fn _komlos_split(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
|
1023
1408
|
m.add_function(wrap_pyfunction!(py_discrepancy_inf, m)?)?;
|
|
1024
1409
|
m.add_function(wrap_pyfunction!(py_normalize_komlos_columns, m)?)?;
|
|
1025
1410
|
m.add_function(wrap_pyfunction!(py_rademacher_split, m)?)?;
|
|
1411
|
+
m.add_function(wrap_pyfunction!(py_split_k, m)?)?;
|
|
1026
1412
|
Ok(())
|
|
1027
1413
|
}
|
|
1028
1414
|
|
|
@@ -1065,6 +1451,46 @@ mod tests {
|
|
|
1065
1451
|
assert!(d_gsw < d_rand, "expected GSW ({d_gsw}) < Rademacher ({d_rand})");
|
|
1066
1452
|
}
|
|
1067
1453
|
|
|
1454
|
+
#[test]
|
|
1455
|
+
fn rust_high_level_split_k_and_smd_parity() {
|
|
1456
|
+
let n = 160;
|
|
1457
|
+
let m = 12;
|
|
1458
|
+
let mut rng = Rng64::new(777);
|
|
1459
|
+
let samples: Vec<f64> = (0..n * m).map(|_| rng.next_signed_f64() * 5.0).collect();
|
|
1460
|
+
|
|
1461
|
+
// 80/20 ratio split in native Rust
|
|
1462
|
+
let signs = assign_groups(&samples, n, m, SplitMethod::Auto, 0.8, 42, 2.0, true).unwrap();
|
|
1463
|
+
let idx_a: Vec<usize> = signs
|
|
1464
|
+
.iter()
|
|
1465
|
+
.enumerate()
|
|
1466
|
+
.filter(|&(_, &s)| s == 1)
|
|
1467
|
+
.map(|(i, _)| i)
|
|
1468
|
+
.collect();
|
|
1469
|
+
let idx_b: Vec<usize> = signs
|
|
1470
|
+
.iter()
|
|
1471
|
+
.enumerate()
|
|
1472
|
+
.filter(|&(_, &s)| s == -1)
|
|
1473
|
+
.map(|(i, _)| i)
|
|
1474
|
+
.collect();
|
|
1475
|
+
assert!(idx_a.len() >= 115 && idx_a.len() <= 140);
|
|
1476
|
+
let smd = compute_smd(&samples, n, m, &idx_a, &idx_b).unwrap();
|
|
1477
|
+
assert!(
|
|
1478
|
+
smd.max_smd < 0.25,
|
|
1479
|
+
"expected tight SMD on 80/20 split, got {}",
|
|
1480
|
+
smd.max_smd
|
|
1481
|
+
);
|
|
1482
|
+
|
|
1483
|
+
// Multi-arm k=3, 4, 5 in native Rust
|
|
1484
|
+
for k in [3usize, 4, 5] {
|
|
1485
|
+
let labels = split_k(&samples, n, m, k, SplitMethod::Auto, 42, 2.0, true).unwrap();
|
|
1486
|
+
assert_eq!(labels.len(), n);
|
|
1487
|
+
for arm in 0..k {
|
|
1488
|
+
let count = labels.iter().filter(|&&l| l == arm).count();
|
|
1489
|
+
assert!(count > 0, "arm {arm} empty for k={k}");
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1068
1494
|
#[test]
|
|
1069
1495
|
fn verifies_dafny_theorems_4_and_5_in_ieee754_f64() {
|
|
1070
1496
|
// Theorem 4 (Orthogonal Progress): <x, h> = 0, ||h|| = 1 => ||x + eta*h||^2 == ||x||^2 + eta^2
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|