komlos-split 0.2.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.2.0 → komlos_split-0.3.0}/Cargo.lock +1 -1
- {komlos_split-0.2.0 → komlos_split-0.3.0}/Cargo.toml +1 -1
- {komlos_split-0.2.0 → komlos_split-0.3.0}/PKG-INFO +20 -1
- {komlos_split-0.2.0 → komlos_split-0.3.0}/README.md +19 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/pyproject.toml +1 -1
- {komlos_split-0.2.0 → komlos_split-0.3.0}/python/komlos_split/__init__.py +13 -23
- {komlos_split-0.2.0 → komlos_split-0.3.0}/src/lib.rs +388 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/.gitignore +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/AUDIT_DOSSIER.md +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/BENCHMARK_STUDY.md +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/CITATION.cff +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/benches/baseline.rs +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/examples/ab_test_demo.py +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/examples/crossover_study.rs +0 -0
- {komlos_split-0.2.0 → komlos_split-0.3.0}/examples/profile_study.rs +0 -0
- {komlos_split-0.2.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
|
|
@@ -95,6 +95,25 @@ Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariate
|
|
|
95
95
|
- **ATE Estimation RMSE:** `0.1479` vs. `0.5196` random (**91.9% variance reduction**).
|
|
96
96
|
- **High-dimensional trial (64 patients × 320 biomarkers, `auto -> gfl`):** Max SMD `0.5815` vs. `0.7316` random (−20.5%).
|
|
97
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
|
+
|
|
98
117
|
## Usage
|
|
99
118
|
|
|
100
119
|
```bash
|
|
@@ -85,6 +85,25 @@ Verified output from `examples/ab_test_demo.py` (256 users × 24 mixed covariate
|
|
|
85
85
|
- **ATE Estimation RMSE:** `0.1479` vs. `0.5196` random (**91.9% variance reduction**).
|
|
86
86
|
- **High-dimensional trial (64 patients × 320 biomarkers, `auto -> gfl`):** Max SMD `0.5815` vs. `0.7316` random (−20.5%).
|
|
87
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
|
+
|
|
88
107
|
## Usage
|
|
89
108
|
|
|
90
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"
|
|
@@ -19,6 +19,7 @@ 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__ = [
|
|
@@ -349,33 +350,22 @@ def split_k(
|
|
|
349
350
|
n_features = len(feature_names)
|
|
350
351
|
resolved = ("gfl" if n_features >= 4 * n else "gsw") if method.lower() == "auto" else method.lower()
|
|
351
352
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
signs = assign_groups(
|
|
360
|
-
sub_rows,
|
|
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,
|
|
361
360
|
method=resolved,
|
|
362
|
-
|
|
363
|
-
seed=cur_seed,
|
|
361
|
+
seed=seed,
|
|
364
362
|
step_size=step_size,
|
|
365
363
|
balance_size=balance_size,
|
|
366
364
|
)
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
cut = max(left_arms, min(len(indices) - right_arms, round(len(indices) * sub_ratio)))
|
|
372
|
-
left_idx = indices[:cut]
|
|
373
|
-
right_idx = indices[cut:]
|
|
374
|
-
return _recurse(left_idx, left_arms, cur_seed * 31 + 1) + _recurse(
|
|
375
|
-
right_idx, right_arms, cur_seed * 31 + 2
|
|
376
|
-
)
|
|
377
|
-
|
|
378
|
-
group_indices = _recurse(list(range(n)), k, seed)
|
|
365
|
+
)
|
|
366
|
+
group_indices: list[list[int]] = [[] for _ in range(k)]
|
|
367
|
+
for idx, arm in enumerate(labels):
|
|
368
|
+
group_indices[arm].append(idx)
|
|
379
369
|
groups = [_slice_indices(data, kind, idxs) for idxs in group_indices]
|
|
380
370
|
|
|
381
371
|
if not return_report:
|
|
@@ -989,6 +989,323 @@ pub fn guo_fang_lu_walk(
|
|
|
989
989
|
Ok(x.into_iter().map(|v| if v >= 0.0 { 1 } else { -1 }).collect())
|
|
990
990
|
}
|
|
991
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
|
+
|
|
992
1309
|
// ============================================================================
|
|
993
1310
|
// Python (PyO3) Bindings
|
|
994
1311
|
// ============================================================================
|
|
@@ -1052,6 +1369,36 @@ fn py_rademacher_split(n: usize, seed: u64) -> Vec<i8> {
|
|
|
1052
1369
|
rademacher_split(n, seed)
|
|
1053
1370
|
}
|
|
1054
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
|
+
|
|
1055
1402
|
#[cfg(feature = "python")]
|
|
1056
1403
|
#[pymodule]
|
|
1057
1404
|
fn _komlos_split(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
@@ -1061,6 +1408,7 @@ fn _komlos_split(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
|
|
1061
1408
|
m.add_function(wrap_pyfunction!(py_discrepancy_inf, m)?)?;
|
|
1062
1409
|
m.add_function(wrap_pyfunction!(py_normalize_komlos_columns, m)?)?;
|
|
1063
1410
|
m.add_function(wrap_pyfunction!(py_rademacher_split, m)?)?;
|
|
1411
|
+
m.add_function(wrap_pyfunction!(py_split_k, m)?)?;
|
|
1064
1412
|
Ok(())
|
|
1065
1413
|
}
|
|
1066
1414
|
|
|
@@ -1103,6 +1451,46 @@ mod tests {
|
|
|
1103
1451
|
assert!(d_gsw < d_rand, "expected GSW ({d_gsw}) < Rademacher ({d_rand})");
|
|
1104
1452
|
}
|
|
1105
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
|
+
|
|
1106
1494
|
#[test]
|
|
1107
1495
|
fn verifies_dafny_theorems_4_and_5_in_ieee754_f64() {
|
|
1108
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
|