File size: 16,232 Bytes
8b37c3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""Battery-grouped sequence-model evaluation with train-only preprocessing."""

from __future__ import annotations

import random
from collections.abc import Callable

import numpy as np
import pandas as pd
from sklearn.model_selection import GroupShuffleSplit

from src.evaluation.metrics import regression_metrics
from src.evaluation.protocol import grouped_train_val_test_folds


TORCH_MODEL_IDS = (
    "vanilla_lstm", "bidirectional_lstm", "gru", "attention_lstm",
    "battery_gpt", "temporal_fusion_transformer", "vae_lstm",
)
TF_MODEL_IDS = ("itransformer", "physics_itransformer", "dynamic_graph_itransformer")


class SequenceStandardizer:
    """Median-impute and standardize sequence channels using training rows only."""

    def fit(self, X: np.ndarray) -> "SequenceStandardizer":
        flat = np.asarray(X, dtype=float).reshape(-1, X.shape[-1])
        self.median_ = np.nanmedian(flat, axis=0)
        filled = np.where(np.isnan(flat), self.median_, flat)
        self.mean_ = filled.mean(axis=0)
        self.scale_ = filled.std(axis=0)
        self.scale_[self.scale_ == 0] = 1.0
        return self

    def transform(self, X: np.ndarray) -> np.ndarray:
        values = np.asarray(X, dtype=float)
        filled = np.where(np.isnan(values), self.median_, values)
        return ((filled - self.mean_) / self.scale_).astype(np.float32)


def _set_seed(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    try:
        import torch
        torch.manual_seed(seed)
        if torch.cuda.is_available():
            torch.cuda.manual_seed_all(seed)
    except ImportError:
        pass


def _torch_factories(n_features: int) -> dict[str, Callable[[], object]]:
    from src.models.deep.lstm import AttentionLSTM, BidirectionalLSTM, GRUModel, VanillaLSTM
    from src.models.deep.transformer import BatteryGPT, TemporalFusionTransformer
    from src.models.deep.vae_lstm import VAE_LSTM

    return {
        "vanilla_lstm": lambda: VanillaLSTM(n_features, hidden_dim=64, n_layers=2),
        "bidirectional_lstm": lambda: BidirectionalLSTM(n_features, hidden_dim=64, n_layers=2),
        "gru": lambda: GRUModel(n_features, hidden_dim=64, n_layers=2),
        "attention_lstm": lambda: AttentionLSTM(n_features, hidden_dim=64, n_layers=2),
        "battery_gpt": lambda: BatteryGPT(n_features, d_model=64, n_heads=4, n_layers=2),
        "temporal_fusion_transformer": lambda: TemporalFusionTransformer(
            n_features, d_model=64, n_heads=4, n_layers=2
        ),
        "vae_lstm": lambda: VAE_LSTM(
            n_features, seq_len=64, hidden_dim=64, latent_dim=16, n_layers=2
        ),
    }


def _train_torch_model(
    model_id: str,
    model: object,
    X_train: np.ndarray,
    y_train: np.ndarray,
    X_val: np.ndarray,
    y_val: np.ndarray,
    X_test: np.ndarray,
    *,
    max_epochs: int,
    patience: int,
    batch_size: int,
    device: str,
) -> tuple[np.ndarray, np.ndarray, int]:
    import torch
    from torch.utils.data import DataLoader, TensorDataset
    from src.models.deep.lstm import train_loop
    from src.models.deep.vae_lstm import train_vae

    y_mean = float(y_train.mean())
    y_scale = float(y_train.std()) or 1.0
    normalize = lambda values: ((values - y_mean) / y_scale).astype(np.float32)
    train_loader = DataLoader(TensorDataset(
        torch.from_numpy(X_train), torch.from_numpy(normalize(y_train))
    ), batch_size=batch_size, shuffle=True)
    val_loader = DataLoader(TensorDataset(
        torch.from_numpy(X_val), torch.from_numpy(normalize(y_val))
    ), batch_size=batch_size, shuffle=False)
    if model_id == "vae_lstm":
        history = train_vae(
            model, train_loader, val_loader, max_epochs=max_epochs,
            patience=patience, device=device, warmup_epochs=min(30, max_epochs // 3),
        )
    else:
        history = train_loop(
            model, train_loader, val_loader, max_epochs=max_epochs,
            patience=patience, device=device,
        )
    model.eval()

    def predict(values: np.ndarray) -> np.ndarray:
        outputs = []
        loader = DataLoader(TensorDataset(torch.from_numpy(values)), batch_size=batch_size)
        with torch.no_grad():
            for (xb,) in loader:
                raw = model(xb.to(device))
                if isinstance(raw, dict):
                    raw = raw["health_pred"]
                outputs.append(raw.detach().cpu().numpy().reshape(-1))
        return np.concatenate(outputs) * y_scale + y_mean

    epochs = len(history.get("train_losses", []))
    return predict(X_train), predict(X_test), epochs


def _train_tensorflow_model(
    model_id: str,
    X_train: np.ndarray,
    y_train: np.ndarray,
    X_val: np.ndarray,
    y_val: np.ndarray,
    X_test: np.ndarray,
    *,
    max_epochs: int,
    patience: int,
    batch_size: int,
) -> tuple[np.ndarray, np.ndarray, int]:
    import tensorflow as tf
    from src.models.deep.itransformer import (
        build_dynamic_graph_itransformer,
        build_itransformer,
        build_physics_itransformer,
    )

    builders = {
        "itransformer": build_itransformer,
        "physics_itransformer": build_physics_itransformer,
        "dynamic_graph_itransformer": build_dynamic_graph_itransformer,
    }
    y_mean = float(y_train.mean())
    y_scale = float(y_train.std()) or 1.0
    train_target = ((y_train - y_mean) / y_scale).astype(np.float32)
    val_target = ((y_val - y_mean) / y_scale).astype(np.float32)
    model = builders[model_id](X_train.shape[1], X_train.shape[2], d_model=32, n_heads=4, n_blocks=2)
    if model_id == "physics_itransformer":
        model.compile(
            optimizer=tf.keras.optimizers.Adam(1e-3),
            loss={"soh_ml": "mae", "soh_phy": "mae"},
            loss_weights={"soh_ml": 1.0, "soh_phy": model.physics_loss_weight},
        )
        fit_y = {"soh_ml": train_target, "soh_phy": train_target}
        val_y = {"soh_ml": val_target, "soh_phy": val_target}
    else:
        model.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss="mae")
        fit_y, val_y = train_target, val_target
    history = model.fit(
        X_train, fit_y, validation_data=(X_val, val_y), epochs=max_epochs,
        batch_size=batch_size, verbose=0,
        callbacks=[tf.keras.callbacks.EarlyStopping(
            monitor="val_loss", patience=patience, restore_best_weights=True
        )],
    )

    def predict(values: np.ndarray) -> np.ndarray:
        raw = model.predict(values, batch_size=batch_size, verbose=0)
        if isinstance(raw, list):
            raw = raw[0]
        return np.asarray(raw).reshape(-1) * y_scale + y_mean

    result = (predict(X_train), predict(X_test), len(history.history["loss"]))
    tf.keras.backend.clear_session()
    return result


def run_grouped_sequence_benchmark(
    X: np.ndarray,
    index: pd.DataFrame,
    *,
    dataset_name: str,
    n_splits: int = 5,
    seeds: tuple[int, ...] = (17, 42, 2026),
    max_epochs: int = 200,
    patience: int = 20,
    batch_size: int = 64,
    model_ids: tuple[str, ...] | None = None,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Evaluate all ten sequence models without using test data for stopping."""
    if len(index) != len(X):
        raise ValueError("Sequence tensor and index have different row counts")
    requested = set(model_ids or (TORCH_MODEL_IDS + TF_MODEL_IDS))
    unknown = requested.difference(TORCH_MODEL_IDS + TF_MODEL_IDS)
    if unknown:
        raise KeyError(f"Unknown sequence model IDs: {sorted(unknown)}")
    y = index["SoH"].to_numpy(dtype=float)
    groups = index["battery_id"].astype(str).to_numpy()
    available_splits = min(n_splits, np.unique(groups).size)
    if available_splits < 2:
        raise ValueError("At least two batteries are required")
    metric_rows: list[dict[str, object]] = []
    prediction_rows: list[dict[str, object]] = []
    for seed in seeds:
        _set_seed(seed)
        folds = grouped_train_val_test_folds(
            groups, n_splits=available_splits, validation_fraction=0.2,
            random_state=seed,
        )
        for fold, (train_idx, val_idx, test_idx) in enumerate(folds, start=1):
            scaler = SequenceStandardizer().fit(X[train_idx])
            X_train, X_val, X_test = (
                scaler.transform(X[subset]) for subset in (train_idx, val_idx, test_idx)
            )
            device = "cuda" if __import__("torch").cuda.is_available() else "cpu"
            for model_id, factory in _torch_factories(X.shape[-1]).items():
                if model_id not in requested:
                    continue
                print(
                    f"[{dataset_name}] seed={seed} fold={fold}/{available_splits} "
                    f"model={model_id} start",
                    flush=True,
                )
                _set_seed(seed)
                train_pred, test_pred, epochs = _train_torch_model(
                    model_id, factory(), X_train, y[train_idx], X_val, y[val_idx], X_test,
                    max_epochs=max_epochs, patience=patience, batch_size=batch_size,
                    device=device,
                )
                _append_results(
                    metric_rows, prediction_rows, dataset_name, seed, fold, model_id,
                    train_idx, test_idx, groups, index, y, train_pred, test_pred, epochs,
                )
                print(
                    f"[{dataset_name}] seed={seed} fold={fold}/{available_splits} "
                    f"model={model_id} done epochs={epochs} mae={metric_rows[-1]['mae']:.4f}",
                    flush=True,
                )
            for model_id in TF_MODEL_IDS:
                if model_id not in requested:
                    continue
                print(
                    f"[{dataset_name}] seed={seed} fold={fold}/{available_splits} "
                    f"model={model_id} start",
                    flush=True,
                )
                _set_seed(seed)
                train_pred, test_pred, epochs = _train_tensorflow_model(
                    model_id, X_train, y[train_idx], X_val, y[val_idx], X_test,
                    max_epochs=max_epochs, patience=patience, batch_size=batch_size,
                )
                _append_results(
                    metric_rows, prediction_rows, dataset_name, seed, fold, model_id,
                    train_idx, test_idx, groups, index, y, train_pred, test_pred, epochs,
                )
                print(
                    f"[{dataset_name}] seed={seed} fold={fold}/{available_splits} "
                    f"model={model_id} done epochs={epochs} mae={metric_rows[-1]['mae']:.4f}",
                    flush=True,
                )
    return pd.DataFrame(metric_rows), pd.DataFrame(prediction_rows)


def _append_results(
    metric_rows: list[dict[str, object]],
    prediction_rows: list[dict[str, object]],
    dataset_name: str,
    seed: int,
    fold: int,
    model_id: str,
    train_idx: np.ndarray,
    test_idx: np.ndarray,
    groups: np.ndarray,
    index: pd.DataFrame,
    y: np.ndarray,
    train_pred: np.ndarray,
    test_pred: np.ndarray,
    epochs: int,
) -> None:
    metrics = regression_metrics(y[test_idx], test_pred)
    train_metrics = regression_metrics(y[train_idx], train_pred)
    metric_rows.append({
        "dataset": dataset_name, "seed": seed, "fold": fold, "model": model_id,
        **metrics, "train_mae": train_metrics["mae"],
        "generalization_gap_mae": metrics["mae"] - train_metrics["mae"],
        "epochs": epochs,
    })
    for local, row_idx in enumerate(test_idx):
        prediction_rows.append({
            "dataset": dataset_name, "seed": seed, "fold": fold, "model": model_id,
            "row_index": int(row_idx), "battery_id": groups[row_idx],
            "cycle_number": int(index.iloc[row_idx]["cycle_number"]),
            "y_true": y[row_idx], "y_pred": float(test_pred[local]),
            "residual": float(y[row_idx] - test_pred[local]),
        })


def run_zero_shot_sequence(
    source_X: np.ndarray,
    source_index: pd.DataFrame,
    targets: dict[str, tuple[np.ndarray, pd.DataFrame]],
    *,
    source_name: str = "NASA",
    seeds: tuple[int, ...] = (17, 42, 2026),
    max_epochs: int = 200,
    patience: int = 20,
    batch_size: int = 64,
    model_ids: tuple[str, ...] | None = None,
) -> tuple[pd.DataFrame, pd.DataFrame]:
    """Train each sequence model on NASA train/validation batteries once per seed.

    All target-domain labels remain untouched until scoring, and the same frozen
    source model is used for every supplied external target.
    """
    y_source = source_index["SoH"].to_numpy(dtype=float)
    source_groups = source_index["battery_id"].astype(str).to_numpy()
    lengths = {name: len(values[0]) for name, values in targets.items()}
    target_concat = np.concatenate([values[0] for values in targets.values()], axis=0)
    metric_rows: list[dict[str, object]] = []
    prediction_rows: list[dict[str, object]] = []
    requested = set(model_ids or (TORCH_MODEL_IDS + TF_MODEL_IDS))
    unknown = requested.difference(TORCH_MODEL_IDS + TF_MODEL_IDS)
    if unknown:
        raise KeyError(f"Unknown sequence model IDs: {sorted(unknown)}")
    for seed in seeds:
        splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=seed)
        train_idx, val_idx = next(splitter.split(source_X, y_source, source_groups))
        scaler = SequenceStandardizer().fit(source_X[train_idx])
        X_train = scaler.transform(source_X[train_idx])
        X_val = scaler.transform(source_X[val_idx])
        X_target = scaler.transform(target_concat)
        device = "cuda" if __import__("torch").cuda.is_available() else "cpu"
        factories = _torch_factories(source_X.shape[-1])
        for model_id in TORCH_MODEL_IDS + TF_MODEL_IDS:
            if model_id not in requested:
                continue
            print(
                f"[{source_name}->external] seed={seed} model={model_id} start",
                flush=True,
            )
            _set_seed(seed)
            if model_id in factories:
                _, combined_pred, epochs = _train_torch_model(
                    model_id, factories[model_id](), X_train, y_source[train_idx],
                    X_val, y_source[val_idx], X_target, max_epochs=max_epochs,
                    patience=patience, batch_size=batch_size, device=device,
                )
            else:
                _, combined_pred, epochs = _train_tensorflow_model(
                    model_id, X_train, y_source[train_idx], X_val, y_source[val_idx],
                    X_target, max_epochs=max_epochs, patience=patience,
                    batch_size=batch_size,
                )
            offset = 0
            for target_name, (_, target_index) in targets.items():
                count = lengths[target_name]
                pred = combined_pred[offset : offset + count]
                offset += count
                y_target = target_index["SoH"].to_numpy(dtype=float)
                metric_rows.append({
                    "source_dataset": source_name,
                    "target_dataset": target_name,
                    "seed": seed,
                    "model": model_id,
                    "epochs": epochs,
                    **regression_metrics(y_target, pred),
                })
                for row, value in enumerate(pred):
                    prediction_rows.append({
                        "source_dataset": source_name,
                        "target_dataset": target_name,
                        "seed": seed,
                        "model": model_id,
                        "battery_id": str(target_index.iloc[row]["battery_id"]),
                        "cycle_number": int(target_index.iloc[row]["cycle_number"]),
                        "y_true": y_target[row],
                        "y_pred": float(value),
                        "residual": float(y_target[row] - value),
                    })
            print(
                f"[{source_name}->external] seed={seed} model={model_id} "
                f"done epochs={epochs}",
                flush=True,
            )
    return pd.DataFrame(metric_rows), pd.DataFrame(prediction_rows)