File size: 4,452 Bytes
239a1be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773c429
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Masked data loss + optional physics residuals (Clausius-Duhem inspired)."""
from __future__ import annotations

import torch
import torch.nn.functional as F

from .data import TARGET_KEYS

IDX = {k: i for i, k in enumerate(TARGET_KEYS)}
PHASE_KEYS = ["xi_BCC", "xi_FCC", "xi_HCP", "xi_other"]
RHO_KEYS = ["rho_total", "rho_perfect", "rho_shockley", "rho_stairrod",
            "rho_hirth", "rho_other_disl", "rho_112_111"]
TWIN_KEY = "twin"


def masked_mse(pred, Y, M):
    """MSE over observed entries only (missing label != zero label)."""
    w = M
    num = ((pred - Y) ** 2 * w).sum()
    den = w.sum().clamp_min(1.0)
    return num / den


def masked_mse_balanced(pred, Y, M, weights=None):
    """Mean over *variables* of the per-variable masked MSE.

    Each physical output head contributes equally regardless of how many
    samples carry that label -- otherwise rare heads (e.g. twin density,
    6 samples) are swamped by rho_total (16 samples).
    """
    F_ = pred.shape[-1]
    losses = []
    for j in range(F_):
        m = M[..., j]
        n = m.sum()
        if n > 0:
            losses.append((((pred[..., j] - Y[..., j]) ** 2 * m).sum() / n))
    if not losses:
        return torch.zeros((), device=pred.device)
    stack = torch.stack(losses)
    if weights is not None:
        w = weights.to(pred.device).float()
        idx = [j for j in range(F_) if M[..., j].sum() > 0]
        w = w[idx]
        return (stack * w).sum() / w.sum().clamp_min(1e-6)
    return stack.mean()


def masked_l1(pred, Y, M):
    return ((pred - Y).abs() * M).sum() / M.sum().clamp_min(1.0)


def physics_losses(pred, Y, M, strain, cfg):
    """Physics residuals evaluated on the *prediction* trajectory.

    * monotonicity of defect densities (dislocation / twin) outside thermal
      softening: rho_{t+1} >= rho_t ;
    * initial-state consistency: the first frame must reproduce the measured
      initial phase fractions / defect densities when they are observed;
    * stress smoothness: penalise the second difference of the stress curve
      (a weak regularity prior that suppresses non-physical oscillation).
    """
    B, T, _ = pred.shape
    dev = pred.device
    total = torch.zeros((), device=dev)
    logs = {}

    d_eps = (strain[:, 1:] - strain[:, :-1]).clamp_min(1e-8)

    # --- monotonic defect accumulation -----------------------------------
    mono = torch.zeros((), device=dev)
    n_mono = 0
    for k in RHO_KEYS + [TWIN_KEY]:
        j = IDX[k]
        v = pred[..., j]
        dv = (v[:, 1:] - v[:, :-1]) / d_eps
        # only penalise decreases that are not preceded by an observed drop
        obs = M[:, 1:, j]
        pen = F.relu(-dv) * (0.5 + 0.5 * obs)
        mono = mono + pen.mean()
        n_mono += 1
    mono = mono / max(n_mono, 1)
    logs["mono"] = float(mono.detach())
    total = total + cfg.w_mono * mono

    # --- initial state consistency ---------------------------------------
    init = torch.zeros((), device=dev)
    n_init = 0
    for k in PHASE_KEYS + RHO_KEYS:
        j = IDX[k]
        m0 = M[:, 0, j]
        if m0.sum() > 0:
            err = ((pred[:, 0, j] - Y[:, 0, j]) ** 2 * m0).sum() / m0.sum().clamp_min(1.0)
            init = init + err
            n_init += 1
    init = init / max(n_init, 1)
    logs["init"] = float(init.detach())
    total = total + cfg.w_init * init

    # --- stress smoothness ------------------------------------------------
    s = pred[..., IDX["sigma"]]
    if T > 2:
        d2 = s[:, 2:] - 2 * s[:, 1:-1] + s[:, :-2]
        smooth = (d2 ** 2).mean()
    else:
        smooth = torch.zeros((), device=dev)
    logs["smooth"] = float(smooth.detach())
    total = total + cfg.w_smooth * smooth

    logs["total"] = float(total.detach())
    return total, logs

def peak_loss(pred, Y, M, k: int = 0):
    """Curve-level term: match the per-sample peak of the stress curve.

    Point-wise MSE shrinks towards the conditional mean, which systematically
    under-estimates the yield peak (see report §6.1).  This term only looks at
    argmax_t sigma, i.e. one number per trajectory, so it carries little
    over-fitting risk on 33 curves.
    """
    import torch
    m = M[..., k] > 0
    if not bool(m.any()):
        return pred.new_zeros(())
    p = pred[..., k].masked_fill(~m, -1e9)
    y = Y[..., k].masked_fill(~m, -1e9)
    has = m.any(-1)
    return torch.nn.functional.mse_loss(p.max(-1).values[has], y.max(-1).values[has])