File size: 13,224 Bytes
0ef4ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Material-conditioned DENIM constitutive core.

The module retains the small-strain elastic/J2/associative-flow return map
used by DENIM and conditions only the unknown hardening closure on a compact
material descriptor.  It deliberately does not encode the closed-form J2 or
Chaboche hardening equations.
"""

from __future__ import annotations

from dataclasses import dataclass

import torch
from torch import nn
from torch.nn import functional as F

from src.t2_graybox_discrete_energy import (
    GrayboxState,
    deviatoric,
    double_contract,
    elastic_stress,
    initial_state,
    von_mises,
)


DESCRIPTOR_NAMES = (
    "young_scaled",
    "poisson",
    "yield_scaled",
    "linear_isotropic_scaled",
    "backstress_c1_scaled",
    "backstress_gamma1_scaled",
    "backstress_c2_scaled",
    "backstress_gamma2_scaled",
    "isotropic_saturation_scaled",
    "isotropic_rate_scaled",
    "family_j2",
    "family_chaboche",
    "family_incomplete",
)


def material_descriptor(parameters: dict[str, float | str]) -> torch.Tensor:
    """Build a dimensionless descriptor without exposing hidden DENIM laws."""

    family = str(parameters["material_model"])
    indicators = {
        "j2_linear_isotropic": (1.0, 0.0, 0.0),
        "chaboche_combined": (0.0, 1.0, 0.0),
        "hidden_three_memory_tabulated_hardening": (0.0, 0.0, 1.0),
    }
    if family not in indicators:
        raise ValueError(f"Unsupported material family: {family}")
    # The incomplete family exposes only E, nu and initial yield stress.  The
    # zero entries are intentional, not missing-data imputation.
    hidden = family == "hidden_three_memory_tabulated_hardening"
    value = (
        float(parameters["young_pa"]) / 200.0e9,
        float(parameters["poisson"]),
        float(parameters["yield_stress_pa"]) / 300.0e6,
        0.0 if hidden else float(parameters.get("hardening_modulus_pa", 0.0)) / 5.0e9,
        0.0 if hidden else float(parameters.get("backstress_c1_pa", 0.0)) / 30.0e9,
        0.0 if hidden else float(parameters.get("backstress_gamma1", 0.0)) / 80.0,
        0.0 if hidden else float(parameters.get("backstress_c2_pa", 0.0)) / 10.0e9,
        0.0 if hidden else float(parameters.get("backstress_gamma2", 0.0)) / 20.0,
        0.0 if hidden else float(parameters.get("isotropic_saturation_pa", 0.0)) / 100.0e6,
        0.0 if hidden else float(parameters.get("isotropic_rate", 0.0)) / 10.0,
        *indicators[family],
    )
    return torch.tensor(value, dtype=torch.float32)


class MaterialEncoder(nn.Module):
    def __init__(self, descriptor_size: int = len(DESCRIPTOR_NAMES), hidden: int = 32):
        super().__init__()
        self.network = nn.Sequential(
            nn.Linear(descriptor_size, hidden),
            nn.SiLU(),
            nn.Linear(hidden, hidden),
            nn.SiLU(),
        )

    def forward(self, descriptor: torch.Tensor) -> torch.Tensor:
        return self.network(descriptor)


class ConditionalIsotropicHardening(nn.Module):
    """Descriptor-conditioned, zero-anchored monotone hardening curve."""

    def __init__(self, embedding: int = 32, neurons: int = 12, plastic_scale: float = 0.01):
        super().__init__()
        self.neurons = int(neurons)
        self.plastic_scale = float(plastic_scale)
        self.parameter_head = nn.Linear(embedding, 2 * neurons + 1)

    def _positive_parameters(
        self, embedding: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        raw = self.parameter_head(embedding)
        weight = 0.45 * torch.sigmoid(raw[..., : self.neurons])
        slope = F.softplus(raw[..., self.neurons : 2 * self.neurons]) + 1.0e-5
        linear = 0.60 * torch.sigmoid(raw[..., -1])
        return weight, slope, linear

    def forward(
        self,
        peeq: torch.Tensor,
        stress_scale: torch.Tensor,
        embedding: torch.Tensor,
    ) -> torch.Tensor:
        weight, slope, linear = self._positive_parameters(embedding)
        coordinate = peeq[..., None] / self.plastic_scale
        saturation = -torch.expm1(-slope * coordinate)
        dimensionless = linear * coordinate.squeeze(-1) + (weight * saturation).sum(dim=-1)
        return stress_scale * dimensionless


class ConditionalDENIM(nn.Module):
    """Shared neural hardening closure conditioned on material metadata."""

    def __init__(self, channels: int = 2, embedding: int = 32, hidden: int = 48):
        super().__init__()
        self.channels = int(channels)
        self.encoder = MaterialEncoder(hidden=embedding)
        self.isotropic = ConditionalIsotropicHardening(embedding=embedding)
        self.modulus_head = nn.Sequential(
            nn.Linear(embedding, hidden), nn.SiLU(), nn.Linear(hidden, channels)
        )
        state_size = 3 + 3 * channels + embedding
        self.recovery = nn.Sequential(
            nn.Linear(state_size, hidden),
            nn.SiLU(),
            nn.Linear(hidden, hidden),
            nn.SiLU(),
            nn.Linear(hidden, channels),
        )

    def encode(self, descriptor: torch.Tensor) -> torch.Tensor:
        return self.encoder(descriptor)

    def moduli(self, stress_scale: torch.Tensor, embedding: torch.Tensor) -> torch.Tensor:
        # 0--400 times the initial yield stress covers the synthetic families
        # while retaining a bounded, nonnegative kinematic modulus.
        return 400.0 * stress_scale[..., None] * torch.sigmoid(self.modulus_head(embedding))

    def isotropic_radius(
        self,
        peeq: torch.Tensor,
        stress_scale: torch.Tensor,
        embedding: torch.Tensor,
    ) -> torch.Tensor:
        return self.isotropic(peeq, stress_scale, embedding)

    def update_memories(
        self,
        state: GrayboxState,
        flow_direction: torch.Tensor,
        increment: torch.Tensor,
        stress_scale: torch.Tensor,
        embedding: torch.Tensor,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        radius = self.isotropic_radius(state.peeq, stress_scale, embedding)
        old_norm = torch.sqrt(torch.clamp(double_contract(state.previous_flow, state.previous_flow), min=0.0))
        current_norm = torch.sqrt(torch.clamp(double_contract(flow_direction, flow_direction), min=0.0))
        reversal = double_contract(state.previous_flow, flow_direction) / (
            old_norm * current_norm
        ).clamp_min(1.0e-12)
        scale = stress_scale.clamp_min(1.0)
        norms = torch.sqrt(torch.clamp(double_contract(state.memories, state.memories), min=0.0)) / scale[..., None]
        projections = double_contract(state.memories, flow_direction[..., None, :]) / scale[..., None]
        cross = torch.zeros_like(norms)
        if self.channels > 1:
            for index in range(self.channels):
                other = (index + 1) % self.channels
                cross[..., index] = double_contract(
                    state.memories[..., index, :], state.memories[..., other, :]
                ) / scale.square()
        scalars = torch.stack((state.peeq / 0.05, radius / scale, reversal), dim=-1)
        features = torch.cat((scalars, norms, projections, cross, embedding), dim=-1)
        recovery = 250.0 * torch.sigmoid(self.recovery(features)) + 1.0e-7
        moduli = self.moduli(stress_scale, embedding)
        numerator = state.memories + (
            (2.0 / 3.0)
            * moduli[..., :, None]
            * increment[..., None, None]
            * flow_direction[..., None, :]
        )
        denominator = 1.0 + recovery * increment[..., None]
        return numerator / denominator[..., None], recovery, moduli


def _candidate_update(
    trial_deviatoric: torch.Tensor,
    state: GrayboxState,
    increment: torch.Tensor,
    shear: torch.Tensor,
    yield_stress: torch.Tensor,
    embedding: torch.Tensor,
    law: ConditionalDENIM,
    *,
    direction_iterations: int = 6,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    shifted = trial_deviatoric - state.backstress
    direction = 1.5 * shifted / von_mises(shifted).clamp_min(1.0)[..., None]
    memories = state.memories
    recovery = moduli = None
    for _ in range(direction_iterations):
        memories, recovery, moduli = law.update_memories(
            state, direction, increment, yield_stress, embedding
        )
        denominator = 1.0 + recovery * increment[..., None]
        effective = trial_deviatoric - (
            state.memories / denominator[..., None]
        ).sum(dim=-2)
        direction = 1.5 * effective / von_mises(effective).clamp_min(1.0)[..., None]
    memories, recovery, moduli = law.update_memories(
        state, direction, increment, yield_stress, embedding
    )
    denominator = 1.0 + recovery * increment[..., None]
    effective = trial_deviatoric - (state.memories / denominator[..., None]).sum(dim=-2)
    radius = yield_stress + law.isotropic_radius(
        state.peeq + increment, yield_stress, embedding
    )
    effective_modulus = 3.0 * shear + (moduli / denominator).sum(dim=-1)
    residual = von_mises(effective) - effective_modulus * increment - radius
    return residual, direction, memories, recovery, moduli


def advance(
    strain: torch.Tensor,
    state: GrayboxState,
    young: torch.Tensor,
    poisson: torch.Tensor,
    yield_stress: torch.Tensor,
    descriptor: torch.Tensor,
    law: ConditionalDENIM,
    *,
    bisection_iterations: int = 24,
    direction_iterations: int = 6,
) -> tuple[torch.Tensor, GrayboxState, dict[str, torch.Tensor]]:
    embedding = law.encode(descriptor)
    trial = elastic_stress(strain, state.plastic_strain, young, poisson)
    trial_deviatoric = deviatoric(trial)
    shifted = trial_deviatoric - state.backstress
    old_radius = yield_stress + law.isotropic_radius(state.peeq, yield_stress, embedding)
    trial_function = von_mises(shifted) - old_radius
    plastic = trial_function > yield_stress.clamp_min(1.0) * 1.0e-12
    shear = young / (2.0 * (1.0 + poisson))
    lower = torch.zeros_like(trial_function)
    upper = 2.0 * F.relu(trial_function) / (3.0 * shear).clamp_min(1.0) + 1.0e-14
    for _ in range(16):
        residual, *_ = _candidate_update(
            trial_deviatoric, state, upper, shear, yield_stress, embedding, law,
            direction_iterations=direction_iterations,
        )
        upper = torch.where(plastic & (residual > 0.0), 2.0 * upper, upper)
    for _ in range(bisection_iterations):
        middle = 0.5 * (lower + upper)
        residual, *_ = _candidate_update(
            trial_deviatoric, state, middle, shear, yield_stress, embedding, law,
            direction_iterations=direction_iterations,
        )
        lower = torch.where(plastic & (residual > 0.0), middle, lower)
        upper = torch.where(plastic & (residual <= 0.0), middle, upper)
    increment = torch.where(plastic, 0.5 * (lower + upper), torch.zeros_like(lower))
    residual, direction, memories, recovery, moduli = _candidate_update(
        trial_deviatoric, state, increment, shear, yield_stress, embedding, law,
        direction_iterations=direction_iterations,
    )
    direction = torch.where(plastic[..., None], direction, torch.zeros_like(direction))
    memories = torch.where(plastic[..., None, None], memories, state.memories)
    updated = GrayboxState(
        plastic_strain=state.plastic_strain + increment[..., None] * direction,
        peeq=state.peeq + increment,
        memories=memories,
        previous_flow=torch.where(plastic[..., None], direction, state.previous_flow),
    )
    stress = elastic_stress(strain, updated.plastic_strain, young, poisson)
    return stress, updated, {
        "plastic_increment": increment,
        "yield_residual": torch.where(plastic, residual, torch.zeros_like(residual)),
        "recovery": recovery,
        "moduli": moduli,
        "plastic": plastic,
    }


def rollout(
    strain: torch.Tensor,
    young: torch.Tensor,
    poisson: torch.Tensor,
    yield_stress: torch.Tensor,
    descriptor: torch.Tensor,
    law: ConditionalDENIM,
    *,
    bisection_iterations: int = 24,
) -> dict[str, torch.Tensor]:
    batch, points, _ = strain.shape
    state = initial_state(batch, channels=law.channels, dtype=strain.dtype, device=strain.device)
    result: dict[str, list[torch.Tensor]] = {
        name: []
        for name in (
            "stress", "plastic_strain", "peeq", "memories",
            "plastic_increment", "yield_residual", "recovery", "moduli",
        )
    }
    for point in range(points):
        stress, state, diagnostics = advance(
            strain[:, point], state, young, poisson, yield_stress, descriptor, law,
            bisection_iterations=bisection_iterations,
        )
        result["stress"].append(stress)
        result["plastic_strain"].append(state.plastic_strain)
        result["peeq"].append(state.peeq)
        result["memories"].append(state.memories)
        for name in ("plastic_increment", "yield_residual", "recovery", "moduli"):
            result[name].append(diagnostics[name])
    return {name: torch.stack(values, dim=1) for name, values in result.items()}


__all__ = [
    "ConditionalDENIM",
    "DESCRIPTOR_NAMES",
    "advance",
    "material_descriptor",
    "rollout",
]