File size: 9,261 Bytes
caa4bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train compact PCA/ridge baselines for T4 sparse sensing and rollout."""

from __future__ import annotations

import json
from pathlib import Path

import h5py
import numpy as np

try:
    from .t4_structural_dynamics_v1 import CASE_DIR, DATA_DIR, configuration_design, load_config
except ImportError:
    from t4_structural_dynamics_v1 import CASE_DIR, DATA_DIR, configuration_design, load_config


ARTIFACT_DIR = DATA_DIR.parents[1] / "artifacts" / "t4_structural_dynamics_v1"
PARAMETERS = (
    "length_m",
    "height_m",
    "young_pa",
    "density_kg_m3",
    "damping_ratio",
    "traction_amplitude_pa",
)


def trajectory_arrays(row: dict):
    with h5py.File(CASE_DIR / f"{row['case_id']}.h5", "r") as h5:
        config = json.loads(h5.attrs["config_json"])
        parameter = np.array(
            [
                config["geometry"]["length_m"],
                config["geometry"]["height_m"],
                config["material"]["young_pa"],
                config["material"]["density_kg_m3"],
                config["dynamics"]["target_damping_ratio"],
                config["dynamics"]["traction_amplitude_pa"],
            ],
            dtype=np.float64,
        )
        for name in sorted(h5["trajectories"]):
            group = h5[f"trajectories/{name}"]
            field_time = np.asarray(group["fields/time_s"], dtype=np.float64)
            time = np.asarray(group["time_s"], dtype=np.float64)
            indices = np.rint(field_time / float(group.attrs["dt_s"])).astype(int)
            sensors = np.asarray(group["sensor_displacement_m"], dtype=np.float64)[indices]
            sensor_velocity = np.gradient(sensors, field_time, axis=0, edge_order=2)
            force = np.asarray(group["force_scale"], dtype=np.float64)[indices]
            fields = np.asarray(group["fields/displacement_m"], dtype=np.float64)[:, :, :2]
            output = fields.reshape(fields.shape[0], -1)
            parameter_rows = np.broadcast_to(parameter, (len(field_time), len(parameter)))
            features = np.column_stack(
                (
                    sensors,
                    sensor_velocity,
                    force,
                    field_time / field_time[-1],
                    parameter_rows,
                )
            )
            yield name, output, features, force, parameter


def randomized_pca(values: np.ndarray, rank: int, seed: int = 20260927):
    mean = np.mean(values, axis=0)
    centered = values - mean
    rng = np.random.default_rng(seed)
    omega = rng.normal(size=(centered.shape[1], rank + 8))
    projected = centered @ omega
    projected = centered @ (centered.T @ projected)
    basis, _ = np.linalg.qr(projected, mode="reduced")
    small = basis.T @ centered
    _, singular, vectors = np.linalg.svd(small, full_matrices=False)
    components = vectors[:rank]
    total_variance = float(np.sum(centered * centered))
    explained = float(np.sum(singular[:rank] ** 2) / max(total_variance, np.finfo(float).eps))
    return mean, components, explained


def standardize(values: np.ndarray):
    mean = np.mean(values, axis=0)
    scale = np.std(values, axis=0)
    scale[scale < 1.0e-12] = 1.0
    return mean, scale, (values - mean) / scale


def ridge_fit(features: np.ndarray, targets: np.ndarray, penalty: float):
    augmented = np.column_stack((features, np.ones(len(features))))
    system = augmented.T @ augmented
    regularizer = penalty * np.eye(system.shape[0])
    regularizer[-1, -1] = 0.0
    return np.linalg.solve(system + regularizer, augmented.T @ targets)


def ridge_predict(features: np.ndarray, weights: np.ndarray):
    return np.column_stack((features, np.ones(len(features)))) @ weights


def main() -> None:
    config = load_config()
    rows = configuration_design(config)
    train_rows = [row for row in rows if row["split"] == "train"]
    train_outputs = []
    train_features = []
    for row in train_rows:
        for name, output, features, force, parameter in trajectory_arrays(row):
            train_outputs.append(output.astype(np.float32))
            train_features.append(features.astype(np.float32))
    output_matrix = np.vstack(train_outputs).astype(np.float64)
    feature_matrix = np.vstack(train_features).astype(np.float64)
    del train_outputs, train_features
    field_mean, components, explained = randomized_pca(output_matrix, rank=16)
    latent = (output_matrix - field_mean) @ components.T
    feature_mean, feature_scale, standardized_features = standardize(feature_matrix)
    reconstruction_weights = ridge_fit(standardized_features, latent, penalty=1.0)

    dynamic_features = []
    dynamic_targets = []
    for row in train_rows:
        for _, output, _, force, parameter in trajectory_arrays(row):
            z = (output - field_mean) @ components.T
            count = len(output)
            parameter_rows = np.broadcast_to(parameter, (count - 2, len(parameter)))
            dynamic_features.append(
                np.column_stack((z[1:-1], z[:-2], force[1:-1], force[2:], parameter_rows))
            )
            dynamic_targets.append(z[2:])
    dynamic_matrix = np.vstack(dynamic_features)
    dynamic_target = np.vstack(dynamic_targets)
    dynamic_mean, dynamic_scale, standardized_dynamic = standardize(dynamic_matrix)
    dynamic_weights = ridge_fit(standardized_dynamic, dynamic_target, penalty=10.0)

    def evaluate(selected_rows: list[dict]) -> dict:
        direct_sse = pca_sse = rollout_sse = reference = 0.0
        count = 0
        finite_rollout = True
        for row in selected_rows:
            for _, output, features, force, parameter in trajectory_arrays(row):
                true_z = (output - field_mean) @ components.T
                pca_reconstruction = field_mean + true_z @ components
                predicted_z = ridge_predict((features - feature_mean) / feature_scale, reconstruction_weights)
                direct = field_mean + predicted_z @ components
                rollout_z = np.empty_like(true_z)
                rollout_z[:2] = true_z[:2]
                for step in range(1, len(true_z) - 1):
                    vector = np.concatenate(
                        (
                            rollout_z[step],
                            rollout_z[step - 1],
                            [force[step], force[step + 1]],
                            parameter,
                        )
                    )
                    rollout_z[step + 1] = ridge_predict(
                        ((vector - dynamic_mean) / dynamic_scale)[None, :], dynamic_weights
                    )[0]
                finite_rollout = finite_rollout and bool(np.all(np.isfinite(rollout_z)))
                rollout = field_mean + rollout_z @ components
                direct_sse += float(np.sum((direct - output) ** 2))
                pca_sse += float(np.sum((pca_reconstruction - output) ** 2))
                rollout_sse += float(np.sum((rollout[2:] - output[2:]) ** 2))
                reference += float(np.sum(output * output))
                count += output.size
        return {
            "trajectory_count": 4 * len(selected_rows),
            "pca_rank_16_relative_l2": float(np.sqrt(pca_sse / reference)),
            "sparse_sensor_reconstruction_relative_l2": float(np.sqrt(direct_sse / reference)),
            "sparse_sensor_reconstruction_rmse_m": float(np.sqrt(direct_sse / count)),
            "latent_second_order_rollout_relative_l2": float(np.sqrt(rollout_sse / reference)),
            "latent_second_order_rollout_rmse_m": float(np.sqrt(rollout_sse / count)),
            "rollout_all_finite": finite_rollout,
        }

    cohorts = {
        "train": [row for row in rows if row["split"] == "train"],
        "validation": [row for row in rows if row["split"] == "validation"],
        "test_all": [row for row in rows if row["split"] == "test"],
        "test_id": [row for row in rows if row["split"] == "test" and row["protocol_role"] == "id"],
        "test_excitation_ood": [
            row for row in rows if row["protocol_role"] == "excitation_ood"
        ],
        "test_parameter_ood": [row for row in rows if row["protocol_role"] == "parameter_ood"],
    }
    metrics = {
        "model": "PCA-16 + sparse-sensor ridge; PCA-16 second-order latent ridge rollout",
        "training_configuration_count": len(train_rows),
        "training_trajectory_count": 4 * len(train_rows),
        "pca_explained_energy": explained,
        "cohorts": {name: evaluate(selected) for name, selected in cohorts.items()},
    }
    ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
    (ARTIFACT_DIR / "baseline_metrics.json").write_text(
        json.dumps(metrics, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    np.savez_compressed(
        ARTIFACT_DIR / "pca_ridge_baselines.npz",
        field_mean=field_mean,
        components=components,
        feature_mean=feature_mean,
        feature_scale=feature_scale,
        reconstruction_weights=reconstruction_weights,
        dynamic_mean=dynamic_mean,
        dynamic_scale=dynamic_scale,
        dynamic_weights=dynamic_weights,
        parameter_names=np.asarray(PARAMETERS),
    )
    print(json.dumps(metrics, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()