Download conditional_v2/src/t2_denim_conditional.py from HaomingLuo/AgentFEM-Material-Loading-Memory: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/datasets/HaomingLuo/AgentFEM-Material-Loading-Memory/resolve/main/conditional_v2/src/t2_denim_conditional.py
- Command line
-
hf download hf://datasets/HaomingLuo/AgentFEM-Material-Loading-Memory/conditional_v2/src/t2_denim_conditional.py
-
curl -L -o t2_denim_conditional.py https://huggingface.co/datasets/HaomingLuo/AgentFEM-Material-Loading-Memory/resolve/main/conditional_v2/src/t2_denim_conditional.py
13.2 kB
| """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", | |
| ] | |