Repository navigation
Expand file tree
/
Copy pathschema.rs
More file actions
317 lines (292 loc) · 12.2 KB
/
Copy pathschema.rs
File metadata and controls
317 lines (292 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use chrono::{DateTime, Utc};
use polars::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlackoutConfig {
pub feature: String,
/// Columns nulled together with `feature` (e.g. `TSH_measured`), so a
/// blacked-out assay does not keep claiming it was observed. A null assay
/// beside a `_measured == 1` flag appears in no real record and in no
/// training set, so leaving companions untouched makes the resulting flip
/// rate measure extrapolation rather than robustness.
#[serde(default)]
pub companions: Vec<String>,
pub rate: f64,
pub window_frac: f64,
pub patient_id_col: Option<String>,
pub time_col: Option<String>,
pub random_state: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JitterConfig {
pub feature: String,
pub scale: f64,
pub random_state: Option<u64>,
}
/// How a scrambled row is re-encoded. Each mimics a real export habit; some
/// still parse as numbers (sentinels, `5.2e0`) and some do not (`<0.01`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ScrambleEncoding {
/// `5,2`, `1,200.5`, ` 5.2 `, `5.2e0`.
NumericText,
/// `<0.01`, `>500`, `ND`, `QNS`.
Censored,
/// `5.2 mg/dL`.
UnitSuffix,
/// `-999`, `9999`: numeric stand-ins for missing.
Sentinel,
}
impl ScrambleEncoding {
pub const ALL: [ScrambleEncoding; 4] = [
ScrambleEncoding::NumericText,
ScrambleEncoding::Censored,
ScrambleEncoding::UnitSuffix,
ScrambleEncoding::Sentinel,
];
}
/// Re-encodes a seeded `rate` of `feature`'s rows as text the way a messy
/// export would. The whole column becomes a string column; untouched rows
/// keep a representation that parses back to the same value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScrambleConfig {
pub feature: String,
pub rate: f64,
pub encodings: Vec<ScrambleEncoding>,
pub random_state: Option<u64>,
}
/// Rewrites a seeded `rate` of `feature`'s rows as `value * factor + offset`,
/// a site exporting the same analyte in another unit.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnitsConfig {
pub feature: String,
pub factor: f64,
pub offset: f64,
pub rate: f64,
pub random_state: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohortConfig {
pub query: Option<String>,
}
/// Samples `n_pairs` pairs of rows with different label values and, for
/// each pair, linearly interpolates their raw feature vectors across
/// `n_steps` points from one to the other (`t=0`..`t=1`, inclusive) — no PCA,
/// no inverse transform, since the interpolation already lives in the same
/// space the model takes as input. `flip_threshold`/`positive_class_label`
/// aren't consulted here; they're for the evaluation-side flip finder that
/// consumes the generated grid.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlipperConfig {
pub n_pairs: usize,
pub n_steps: usize,
pub flip_threshold: f64,
pub positive_class_label: Option<serde_json::Value>,
pub random_state: Option<u64>,
}
/// One feature to sweep and, optionally, its decision cutoff.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SweepFeature {
pub name: String,
pub cutoff: Option<f64>,
}
/// Sets one feature at a time to each value of a grid, holding the rest of
/// the row fixed. The grid is `n_steps` points over `range`, absolute by
/// default. With `relative_to` set, the range is a multiplier of each
/// feature's cutoff: its own `cutoff` if given, else `relative_to`. `near`
/// adds `n_steps` more points within ±`near` (a fraction) of the cutoff.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SweepConfig {
pub features: Vec<SweepFeature>,
pub range: (f64, f64),
pub relative_to: Option<f64>,
pub n_steps: usize,
pub near: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SimulationConfig {
pub blackout: Option<BlackoutConfig>,
pub jitter: Option<JitterConfig>,
pub cohort: Option<CohortConfig>,
pub flipper: Option<FlipperConfig>,
#[serde(default)]
pub sweep: Option<SweepConfig>,
}
/// What a model's output means. Binary models emit one positive-class
/// column; multiclass models emit K mutually exclusive class probabilities
/// (one row sums to 1); multilabel models emit K independent per-label
/// probabilities; regression models emit one predicted value, in the
/// target's units.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TaskType {
#[default]
Binary,
Multiclass,
Multilabel,
Regression,
}
impl TaskType {
pub fn is_binary(&self) -> bool {
*self == TaskType::Binary
}
}
impl std::fmt::Display for TaskType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
TaskType::Binary => "binary",
TaskType::Multiclass => "multiclass",
TaskType::Multilabel => "multilabel",
TaskType::Regression => "regression",
})
}
}
/// `y` is a label matrix with one 0/1 column per model output column, in the
/// model's class order: one column for binary, a one-hot row for multiclass,
/// a multi-hot row for multilabel. For regression it is one column holding
/// the true target value.
#[derive(Debug, Clone)]
pub struct SimulationVariant {
pub x: DataFrame,
pub y: DataFrame,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvaluationConfig {
pub n_jitter_iters: usize,
pub allow_partial: bool,
// Note: Callables (metrics) are harder in Rust to serialize,
// we might just use a registry or predefined names.
pub metrics: Vec<String>,
/// Probability threshold for flipper stability (decision-boundary crossing).
/// For multilabel models without per-label `output.thresholds`, applies
/// to every label. Unused for multiclass, whose decision is the argmax.
/// For regression it is a clinical cutoff in the target's units.
pub flip_threshold: f64,
#[serde(default)]
pub task: TaskType,
/// Set when every variant's `y` holds per-row oracle labels rather than
/// a copy of the clean row's label; turns on `EvaluationResult::oracle`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oracle: Option<crate::evaluate::OracleConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricInvariantScores {
pub jitter_stability: f64,
pub flipper_stability: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricBasedScores {
/// Stress metric ÷ clean metric; the mean over site draws when several
/// were scored.
pub resiliency: f64,
/// The worst site draw's resiliency. `1.0` (neutral) unless site draws
/// (`site_0`, `site_1`, ...) were scored.
pub generalizability: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvaluationScores {
pub metric_invariant: MetricInvariantScores,
pub metric_based: std::collections::HashMap<String, MetricBasedScores>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvaluationResult {
pub baselines: std::collections::HashMap<String, f64>,
pub evaluations: EvaluationScores,
pub created_at: DateTime<Utc>,
/// Multiclass/multilabel detail. The headline fields above hold macro
/// averages over labels; this section holds what the averages hide.
/// Absent for binary models, so binary output is unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub multi: Option<MultiOutputScores>,
/// Regression detail, in the target's units. Absent for classifiers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub regression: Option<RegressionScores>,
/// Metrics against per-row oracle labels (`--oracle-labels`). Absent
/// without them, so the output is unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oracle: Option<crate::evaluate::OracleScores>,
/// Single-feature sweep metrics, one entry per swept feature. Present
/// only when a `sweep` variant was scored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sweep: Option<Vec<crate::evaluate::SweepScores>>,
/// Values in the stress variant (blackout, scramble or units), per column,
/// that were present in the file but
/// became null when cast to numbers for the model. Scoring casts
/// leniently, so text like `<0.01` turns into silent missingness; this
/// makes it visible. Summed over datasets; absent when nothing was lost.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parse_loss: Option<BTreeMap<String, BTreeMap<String, usize>>>,
/// One entry per stress variant (blackout, scramble, units, site, or each
/// site draw): how many rows changed and how many decisions changed with
/// them. Classifiers only; absent when no stress variant was loaded.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stress: Option<Vec<crate::evaluate::StressScores>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegressionScores {
/// Name of the target column.
pub target: String,
pub n_rows: usize,
/// Standard deviation of the true target on the clean cohort. Jitter
/// stability is scaled by its square, so it reads the same in any unit.
pub target_sd: f64,
/// RMSE on the stress variant (blackout, scramble or units; the field
/// name predates the latter two).
pub blackout_rmse: Option<f64>,
/// R² on the stress variant; `metric_based.r2.resiliency` is this
/// divided by `baselines.r2`.
pub blackout_r2: Option<f64>,
/// Mean per-patient standard deviation of the prediction across jitter
/// draws, in target units. `None` with fewer than two draws.
pub jitter_prediction_sd: Option<f64>,
/// The cutoff flipper pairs were scored against, when flipper ran.
pub flip_threshold: Option<f64>,
/// Share of flipper pairs whose prediction never crossed the cutoff.
pub flipper_never_flipped: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiOutputScores {
pub task: TaskType,
/// ROC AUC over every (patient, label) pair pooled. Dominated by common
/// labels; the macro average in `baselines.roc_auc` weighs labels equally.
pub roc_auc_micro: Option<f64>,
/// Lowest per-label resiliency. Blacking out one assay often wrecks a
/// single label while the macro average barely moves.
pub worst_label_resiliency: Option<f64>,
/// Share of patients whose decision (argmax class for multiclass, set of
/// labels over threshold for multilabel) differs between jitter draws.
pub decision_flip_rate: Option<f64>,
/// Share of flipper pairs whose prediction never crossed the boundary.
/// Those pairs count as 1.0 in `flipper_stability`, so read them together.
pub flipper_never_flipped: Option<f64>,
/// Multiclass only: share of flipper pairs whose path passes through a
/// third class (argmax is neither endpoint's class at some step).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flipper_detour_rate: Option<f64>,
/// Labels left out of the macro averages because the clean cohort has
/// only one class for them, so their ROC AUC is undefined.
pub excluded_labels: Vec<String>,
pub per_label: Vec<LabelScores>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabelScores {
pub label: String,
pub roc_auc: Option<f64>,
pub resiliency: Option<f64>,
pub jitter_stability: f64,
pub flipper_stability: Option<f64>,
}
/// One model's evaluation, tagged with a caller-supplied label (e.g. an HF
/// repo id) so a list of these is self-describing about which is which.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LabeledEvaluation {
pub model_label: String,
pub evaluation: EvaluationResult,
}
/// Any number of models evaluated against the same clean/simulated
/// datasets, side by side.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComparisonResult {
pub evaluations: Vec<LabeledEvaluation>,
}