OSCR

Causality-enhanced and symmetry-preserving PINNs for damped elastodynamic PDEs.

Code ↔ Paper

3 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 3 matches
  1. [1] § 2 Preleminaries › 2.2 Physics-informed neural networks ↔ Reduced_ODE_solution.ipynb, lines 53 to 78 · score 0.61 · linear transformation, activation function, hidden layer, neural, networks · Report a mismatch
  2. [2] § 5 Numerical experiments ↔ symmetry_pinns_updated.py, lines 74 to 101 · score 0.60 · Xavier normal, hidden layers, zero, neural network, bias, activation · Report a mismatch
  3. [3] § 5 Numerical experiments › 5.2 Case II › 5.2.9 Overall discussion for case II. ↔ symmetry_pinns_updated.py, lines 593 to 710 · score 0.52 · anchor loss, gradient norm, symmetry loss, boundary, epochs, PINN · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 965 lines · 24 KB · MIT · 2 matches

  1. # -*- coding: utf-8 -*-
  2. """Symmetry_PINNs_updated.ipynb
  3. Automatically generated by Colab.
  4. Original file is located at
  5. https://colab.research.google.com/drive/1MYtbtLTBgCt0gQXo67LB7Ew0devS6pa_
  6. """
  7. # ============================================================
  8. # ONE-CELL S-PINN TRAINING CODE FOR FOUR SYMMETRY CASES
  9. # Cases:
  10. # Case I : Scaling symmetry
  11. # Case II : Translation symmetry
  12. # Case III : Damped symmetry
  13. # Case IV : Generalized damped symmetry
  14. # Each case is trained for 500 epochs.
  15. # ============================================================
  16. import os
  17. import time
  18. import math
  19. import pickle
  20. import numpy as np
  21. import pandas as pd
  22. import torch
  23. import torch.nn as nn
  24. import matplotlib.pyplot as plt
  25. try:
  26. from google.colab import files
  27. IN_COLAB = True
  28. except Exception:
  29. IN_COLAB = False
  30. # ============================================================
  31. # GLOBAL SETTINGS
  32. # ============================================================
  33. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  34. SEED = 1234
  35. torch.manual_seed(SEED)
  36. np.random.seed(SEED)
  37. if torch.cuda.is_available():
  38. torch.cuda.manual_seed_all(SEED)
  39. PLOT_SIZE = (8, 4)
  40. DPI = 300
  41. N_EPOCHS = 500
  42. N_COLLOCATION = 256
  43. N_SYM = 128
  44. INPUT_DIMENSION = 1
  45. OUTPUT_DIMENSION = 1
  46. N_HIDDEN_LAYERS = 4
  47. NEURONS = 128
  48. A = 2.0
  49. c = 0.5
  50. gamma = 0.5
  51. TAU_BC = 10.0
  52. TAU_SYM = 1.0
  53. EPS_CAUSALITY = 0.05
  54. OUTPUT_DIR = "Four_Case_SPINN_Results"
  55. os.makedirs(OUTPUT_DIR, exist_ok=True)
  56. plt.rcParams.update({"font.size": 10})
  57. plt.rcParams["figure.constrained_layout.use"] = True
  58. # ============================================================
  59. # NEURAL NETWORK
  60. # ============================================================
  61. class NeuralNet(nn.Module):
  62. def __init__(self, input_dimension=1, output_dimension=1,
  63. n_hidden_layers=4, neurons=128):
  64. super().__init__()
  65. self.input_layer = nn.Linear(input_dimension, neurons)
  66. self.hidden_layers = nn.ModuleList([
  67. nn.Linear(neurons, neurons) for _ in range(n_hidden_layers)
  68. ])
  69. self.output_layer = nn.Linear(neurons, output_dimension)
  70. self.activation = nn.Tanh()
  71. self.initialize_weights()
  72. def initialize_weights(self):
  73. for module in self.modules():
  74. if isinstance(module, nn.Linear):
  75. nn.init.xavier_normal_(module.weight, gain=1.0)
  76. nn.init.zeros_(module.bias)
  77. def forward(self, x):
  78. x = self.activation(self.input_layer(x))
  79. for layer in self.hidden_layers:
  80. x = self.activation(layer(x))
  81. return self.output_layer(x)
  82. # ============================================================
  83. # AUTOGRAD HELPERS
  84. # ============================================================
  85. def grad(outputs, inputs):
  86. return torch.autograd.grad(
  87. outputs,
  88. inputs,
  89. grad_outputs=torch.ones_like(outputs),
  90. create_graph=True,
  91. retain_graph=True,
  92. allow_unused=False
  93. )[0]
  94. def causal_weighted_loss(pointwise_residual_square, eps=EPS_CAUSALITY):
  95. """
  96. Causality-weighted residual loss:
  97. w_1 = 1,
  98. w_j = exp(-eps * cumulative previous losses).
  99. """
  100. r2 = pointwise_residual_square.view(-1)
  101. if r2.numel() == 1:
  102. return torch.mean(r2)
  103. cumulative = torch.cumsum(r2.detach(), dim=0)
  104. previous = torch.cat([
  105. torch.zeros(1, device=r2.device, dtype=r2.dtype),
  106. cumulative[:-1]
  107. ], dim=0)
  108. weights = torch.exp(-eps * previous)
  109. return torch.mean(weights * r2)
  110. def global_gradient_norm(model):
  111. total = 0.0
  112. for param in model.parameters():
  113. if param.grad is not None:
  114. value = param.grad.detach().data.norm(2).item()
  115. total += value ** 2
  116. return float(math.sqrt(total))
  117. def get_layerwise_gradient_norms(model):
  118. """
  119. Combines weight and bias gradient norms for each layer.
  120. Layer 1 = input layer
  121. Layers 2--5 = hidden layers
  122. Layer 6 = output layer
  123. """
  124. layer_squares = {}
  125. for name, param in model.named_parameters():
  126. if param.grad is None:
  127. continue
  128. if name.startswith("input_layer"):
  129. layer_name = "Layer 1"
  130. elif name.startswith("hidden_layers"):
  131. idx = int(name.split(".")[1]) + 2
  132. layer_name = f"Layer {idx}"
  133. elif name.startswith("output_layer"):
  134. layer_name = f"Layer {N_HIDDEN_LAYERS + 2}"
  135. else:
  136. layer_name = name.rsplit(".", 1)[0]
  137. norm_value = param.grad.detach().data.norm(2).item()
  138. layer_squares[layer_name] = layer_squares.get(layer_name, 0.0) + norm_value ** 2
  139. ordered = [f"Layer {i}" for i in range(1, N_HIDDEN_LAYERS + 3)]
  140. out = {}
  141. for key in ordered:
  142. if key in layer_squares:
  143. out[key] = float(math.sqrt(layer_squares[key]))
  144. for key, value in layer_squares.items():
  145. if key not in out:
  146. out[key] = float(math.sqrt(value))
  147. return out
  148. # ============================================================
  149. # EXACT INVARIANT SOLUTIONS FOR TRAINING ANCHORS
  150. # ============================================================
  151. def exact_case_1(alpha):
  152. """
  153. Case I branch:
  154. V(alpha) = C1 alpha + C2
  155. """
  156. C1, C2 = 1.0, 0.5
  157. return C1 * alpha + C2
  158. def exact_case_2(alpha):
  159. """
  160. Case II branch:
  161. V(alpha) = C4 alpha + C5
  162. """
  163. C4, C5 = 1.0, 0.25
  164. return C4 * alpha + C5
  165. def exact_case_3(t):
  166. """
  167. Case III:
  168. f(t) = C7 + C8 exp(-gamma t)
  169. """
  170. C7, C8 = 0.5, 1.0
  171. return C7 + C8 * torch.exp(-gamma * t)
  172. def exact_case_4(t):
  173. """
  174. Case IV:
  175. f(t) = C9 + C10 exp(-gamma t)
  176. """
  177. C9, C10 = 0.25, 0.8
  178. return C9 + C10 * torch.exp(-gamma * t)
  179. # ============================================================
  180. # CASE I LOSS: SCALING SYMMETRY
  181. # ============================================================
  182. def case_1_loss(model):
  183. """
  184. Case I:
  185. alpha = t/x,
  186. v = x V(alpha).
  187. Reduced residual:
  188. R1 = V'' [1 - A alpha^2 {1 + 3(V-alpha V') + 3/2(V-alpha V')^2}].
  189. Symmetry constraint:
  190. x v_x + t v_t - v = 0.
  191. """
  192. alpha = torch.linspace(0.5, 2.0, N_COLLOCATION, device=device).view(-1, 1)
  193. alpha.requires_grad_(True)
  194. V = model(alpha)
  195. V_a = grad(V, alpha)
  196. V_aa = grad(V_a, alpha)
  197. invariant_part = V - alpha * V_a
  198. R = V_aa * (
  199. 1.0
  200. - A * alpha ** 2 * (
  201. 1.0
  202. + 3.0 * invariant_part
  203. + 1.5 * invariant_part ** 2
  204. )
  205. )
  206. ode_loss = causal_weighted_loss(R ** 2)
  207. alpha_bc = torch.tensor([[0.5], [2.0]], dtype=torch.float32, device=device)
  208. V_bc_exact = exact_case_1(alpha_bc)
  209. V_bc_pred = model(alpha_bc)
  210. bc_loss = torch.mean((V_bc_pred - V_bc_exact) ** 2)
  211. x = torch.linspace(0.5, 1.0, N_SYM, device=device).view(-1, 1)
  212. t = torch.linspace(0.5, 1.0, N_SYM, device=device).view(-1, 1)
  213. x.requires_grad_(True)
  214. t.requires_grad_(True)
  215. alpha_xt = t / x
  216. v = x * model(alpha_xt)
  217. v_x = grad(v, x)
  218. v_t = grad(v, t)
  219. sym_res = x * v_x + t * v_t - v
  220. sym_loss = torch.mean(sym_res ** 2)
  221. total_loss = ode_loss + TAU_SYM * sym_loss + TAU_BC * bc_loss
  222. components = {
  223. "total_loss": total_loss,
  224. "ode_loss": ode_loss,
  225. "symmetry_loss": sym_loss,
  226. "bc_loss": bc_loss
  227. }
  228. return total_loss, components
  229. # ============================================================
  230. # CASE II LOSS: TRANSLATION SYMMETRY
  231. # ============================================================
  232. def case_2_loss(model):
  233. """
  234. Case II:
  235. alpha = t - c x,
  236. v = V(alpha).
  237. Reduced residual:
  238. R2 = [1 - A c^2 {1 - 3c V' + 3/2 c^2 (V')^2}] V''.
  239. Symmetry constraint:
  240. v_x + c v_t = 0.
  241. """
  242. alpha = torch.linspace(-0.5, 1.0, N_COLLOCATION, device=device).view(-1, 1)
  243. alpha.requires_grad_(True)
  244. V = model(alpha)
  245. V_a = grad(V, alpha)
  246. V_aa = grad(V_a, alpha)
  247. R = (
  248. 1.0
  249. - A * c ** 2 * (
  250. 1.0
  251. - 3.0 * c * V_a
  252. + 1.5 * c ** 2 * V_a ** 2
  253. )
  254. ) * V_aa
  255. ode_loss = causal_weighted_loss(R ** 2)
  256. alpha_bc = torch.tensor([[-0.5], [1.0]], dtype=torch.float32, device=device)
  257. V_bc_exact = exact_case_2(alpha_bc)
  258. V_bc_pred = model(alpha_bc)
  259. bc_loss = torch.mean((V_bc_pred - V_bc_exact) ** 2)
  260. x = torch.linspace(0.0, 1.0, N_SYM, device=device).view(-1, 1)
  261. t = torch.linspace(0.0, 1.0, N_SYM, device=device).view(-1, 1)
  262. x.requires_grad_(True)
  263. t.requires_grad_(True)
  264. alpha_xt = t - c * x
  265. v = model(alpha_xt)
  266. v_x = grad(v, x)
  267. v_t = grad(v, t)
  268. sym_res = v_x + c * v_t
  269. sym_loss = torch.mean(sym_res ** 2)
  270. total_loss = ode_loss + TAU_SYM * sym_loss + TAU_BC * bc_loss
  271. components = {
  272. "total_loss": total_loss,
  273. "ode_loss": ode_loss,
  274. "symmetry_loss": sym_loss,
  275. "bc_loss": bc_loss
  276. }
  277. return total_loss, components
  278. # ============================================================
  279. # CASE III LOSS: DAMPED SYMMETRY
  280. # ============================================================
  281. def case_3_loss(model):
  282. """
  283. Case III:
  284. v = x exp(-gamma t) + f(t).
  285. Reduced residual:
  286. R3 = f''(t) + gamma f'(t).
  287. Symmetry constraint:
  288. v_x - exp(-gamma t) = 0.
  289. """
  290. t = torch.linspace(0.0, 2.0, N_COLLOCATION, device=device).view(-1, 1)
  291. t.requires_grad_(True)
  292. f = model(t)
  293. f_t = grad(f, t)
  294. f_tt = grad(f_t, t)
  295. R = f_tt + gamma * f_t
  296. ode_loss = causal_weighted_loss(R ** 2)
  297. t_bc = torch.tensor([[0.0], [2.0]], dtype=torch.float32, device=device)
  298. f_bc_exact = exact_case_3(t_bc)
  299. f_bc_pred = model(t_bc)
  300. bc_loss = torch.mean((f_bc_pred - f_bc_exact) ** 2)
  301. x = torch.linspace(0.5, 1.0, N_SYM, device=device).view(-1, 1)
  302. tt = torch.linspace(0.0, 2.0, N_SYM, device=device).view(-1, 1)
  303. x.requires_grad_(True)
  304. tt.requires_grad_(True)
  305. v = x * torch.exp(-gamma * tt) + model(tt)
  306. v_x = grad(v, x)
  307. sym_res = v_x - torch.exp(-gamma * tt)
  308. sym_loss = torch.mean(sym_res ** 2)
  309. total_loss = ode_loss + TAU_SYM * sym_loss + TAU_BC * bc_loss
  310. components = {
  311. "total_loss": total_loss,
  312. "ode_loss": ode_loss,
  313. "symmetry_loss": sym_loss,
  314. "bc_loss": bc_loss
  315. }
  316. return total_loss, components
  317. # ============================================================
  318. # CASE IV LOSS: GENERALIZED DAMPED SYMMETRY
  319. # ============================================================
  320. def case_4_loss(model):
  321. """
  322. Case IV:
  323. v = c x + x exp(-gamma t) + f(t).
  324. Reduced residual:
  325. R4 = f''(t) + gamma f'(t).
  326. Symmetry constraint:
  327. v_x - (c + exp(-gamma t)) = 0.
  328. """
  329. t = torch.linspace(0.0, 2.0, N_COLLOCATION, device=device).view(-1, 1)
  330. t.requires_grad_(True)
  331. f = model(t)
  332. f_t = grad(f, t)
  333. f_tt = grad(f_t, t)
  334. R = f_tt + gamma * f_t
  335. ode_loss = causal_weighted_loss(R ** 2)
  336. t_bc = torch.tensor([[0.0], [2.0]], dtype=torch.float32, device=device)
  337. f_bc_exact = exact_case_4(t_bc)
  338. f_bc_pred = model(t_bc)
  339. bc_loss = torch.mean((f_bc_pred - f_bc_exact) ** 2)
  340. x = torch.linspace(0.5, 1.0, N_SYM, device=device).view(-1, 1)
  341. tt = torch.linspace(0.0, 2.0, N_SYM, device=device).view(-1, 1)
  342. x.requires_grad_(True)
  343. tt.requires_grad_(True)
  344. v = c * x + x * torch.exp(-gamma * tt) + model(tt)
  345. v_x = grad(v, x)
  346. sym_res = v_x - (c + torch.exp(-gamma * tt))
  347. sym_loss = torch.mean(sym_res ** 2)
  348. total_loss = ode_loss + TAU_SYM * sym_loss + TAU_BC * bc_loss
  349. components = {
  350. "total_loss": total_loss,
  351. "ode_loss": ode_loss,
  352. "symmetry_loss": sym_loss,
  353. "bc_loss": bc_loss
  354. }
  355. return total_loss, components
  356. # ============================================================
  357. # TRAINING FUNCTION
  358. # ============================================================
  359. def train_one_case(case_key, case_name, loss_function, epochs=N_EPOCHS):
  360. print("\n" + "=" * 70)
  361. print(f"Training {case_key}: {case_name}")
  362. print("=" * 70)
  363. model = NeuralNet(
  364. input_dimension=INPUT_DIMENSION,
  365. output_dimension=OUTPUT_DIMENSION,
  366. n_hidden_layers=N_HIDDEN_LAYERS,
  367. neurons=NEURONS
  368. ).to(device)
  369. optimizer = torch.optim.LBFGS(
  370. model.parameters(),
  371. lr=1.0,
  372. max_iter=1,
  373. max_eval=2,
  374. tolerance_grad=1e-10,
  375. tolerance_change=1e-12,
  376. history_size=50,
  377. line_search_fn="strong_wolfe"
  378. )
  379. history = {
  380. "epoch": [],
  381. "total_loss": [],
  382. "ode_loss": [],
  383. "symmetry_loss": [],
  384. "bc_loss": [],
  385. "update_cost": [],
  386. "global_gradient_norm": [],
  387. "layerwise_gradient_norms": []
  388. }
  389. for epoch in range(1, epochs + 1):
  390. t0 = time.time()
  391. def closure():
  392. optimizer.zero_grad()
  393. total_loss, _ = loss_function(model)
  394. total_loss.backward()
  395. return total_loss
  396. optimizer.step(closure)
  397. update_cost = time.time() - t0
  398. optimizer.zero_grad()
  399. total_loss, components = loss_function(model)
  400. total_loss.backward()
  401. layer_norms = get_layerwise_gradient_norms(model)
  402. global_norm = global_gradient_norm(model)
  403. history["epoch"].append(epoch)
  404. history["total_loss"].append(float(components["total_loss"].detach().cpu()))
  405. history["ode_loss"].append(float(components["ode_loss"].detach().cpu()))
  406. history["symmetry_loss"].append(float(components["symmetry_loss"].detach().cpu()))
  407. history["bc_loss"].append(float(components["bc_loss"].detach().cpu()))
  408. history["update_cost"].append(update_cost)
  409. history["global_gradient_norm"].append(global_norm)
  410. history["layerwise_gradient_norms"].append(layer_norms)
  411. optimizer.zero_grad()
  412. if epoch == 1 or epoch % 50 == 0 or epoch == epochs:
  413. print(
  414. f"{case_key} | Epoch {epoch:04d}/{epochs} | "
  415. f"Loss = {history['total_loss'][-1]:.6e} | "
  416. f"ODE = {history['ode_loss'][-1]:.6e} | "
  417. f"Sym = {history['symmetry_loss'][-1]:.6e} | "
  418. f"BC = {history['bc_loss'][-1]:.6e} | "
  419. f"Grad = {global_norm:.6e}"
  420. )
  421. case_dir = os.path.join(OUTPUT_DIR, case_key)
  422. os.makedirs(case_dir, exist_ok=True)
  423. torch.save(
  424. model.state_dict(),
  425. os.path.join(case_dir, f"{case_key}_model.pth")
  426. )
  427. with open(os.path.join(case_dir, f"{case_key}_history.pkl"), "wb") as f:
  428. pickle.dump(history, f)
  429. pd.DataFrame({
  430. "epoch": history["epoch"],
  431. "total_loss": history["total_loss"],
  432. "ode_loss": history["ode_loss"],
  433. "symmetry_loss": history["symmetry_loss"],
  434. "bc_loss": history["bc_loss"],
  435. "update_cost": history["update_cost"],
  436. "global_gradient_norm": history["global_gradient_norm"]
  437. }).to_csv(
  438. os.path.join(case_dir, f"{case_key}_training_history.csv"),
  439. index=False
  440. )
  441. print(f"Finished training {case_key}. Results saved in: {case_dir}")
  442. return model, history
  443. # ============================================================
  444. # PLOTTING FUNCTIONS
  445. # ============================================================
  446. def plot_loss_history(case_key, case_name, history):
  447. case_dir = os.path.join(OUTPUT_DIR, case_key)
  448. epochs = history["epoch"]
  449. plt.figure(figsize=PLOT_SIZE)
  450. plt.plot(
  451. epochs,
  452. history["total_loss"],
  453. linewidth=1.5,
  454. label="Total loss"
  455. )
  456. plt.xlabel("Epoch")
  457. plt.ylabel("Total Loss")
  458. plt.yscale("log")
  459. plt.grid(True, alpha=0.3)
  460. plt.legend()
  461. plt.tight_layout()
  462. plt.savefig(
  463. os.path.join(case_dir, f"{case_key}_Total_Loss.pdf"),
  464. dpi=DPI,
  465. bbox_inches="tight"
  466. )
  467. plt.savefig(
  468. os.path.join(case_dir, f"{case_key}_Total_Loss.png"),
  469. dpi=DPI,
  470. bbox_inches="tight"
  471. )
  472. plt.show()
  473. plt.figure(figsize=PLOT_SIZE)
  474. plt.plot(
  475. epochs,
  476. history["ode_loss"],
  477. linewidth=1.5,
  478. label="ODE loss"
  479. )
  480. plt.plot(
  481. epochs,
  482. history["symmetry_loss"],
  483. linewidth=1.5,
  484. label="Symmetry loss"
  485. )
  486. plt.plot(
  487. epochs,
  488. history["bc_loss"],
  489. linewidth=1.5,
  490. label="Boundary/anchor loss"
  491. )
  492. plt.xlabel("Epoch")
  493. plt.ylabel("Loss Components")
  494. plt.yscale("log")
  495. plt.grid(True, alpha=0.3)
  496. plt.legend()
  497. plt.tight_layout()
  498. plt.savefig(
  499. os.path.join(case_dir, f"{case_key}_Loss_Components.pdf"),
  500. dpi=DPI,
  501. bbox_inches="tight"
  502. )
  503. plt.savefig(
  504. os.path.join(case_dir, f"{case_key}_Loss_Components.png"),
  505. dpi=DPI,
  506. bbox_inches="tight"
  507. )
  508. plt.show()
  509. plt.figure(figsize=PLOT_SIZE)
  510. plt.plot(
  511. epochs,
  512. history["update_cost"],
  513. linewidth=1.5,
  514. label="Update cost"
  515. )
  516. plt.xlabel("Epoch")
  517. plt.ylabel("Update Cost (s)")
  518. plt.grid(True, alpha=0.3)
  519. plt.legend()
  520. plt.tight_layout()
  521. plt.savefig(
  522. os.path.join(case_dir, f"{case_key}_Update_Cost.pdf"),
  523. dpi=DPI,
  524. bbox_inches="tight"
  525. )
  526. plt.savefig(
  527. os.path.join(case_dir, f"{case_key}_Update_Cost.png"),
  528. dpi=DPI,
  529. bbox_inches="tight"
  530. )
  531. plt.show()
  532. plt.figure(figsize=PLOT_SIZE)
  533. plt.plot(
  534. epochs,
  535. history["global_gradient_norm"],
  536. linewidth=1.5,
  537. label="Global gradient norm"
  538. )
  539. plt.xlabel("Epoch")
  540. plt.ylabel("Gradient Norm")
  541. plt.yscale("log")
  542. plt.grid(True, alpha=0.3)
  543. plt.legend()
  544. plt.tight_layout()
  545. plt.savefig(
  546. os.path.join(case_dir, f"{case_key}_Global_Gradient_Norm.pdf"),
  547. dpi=DPI,
  548. bbox_inches="tight"
  549. )
  550. plt.savefig(
  551. os.path.join(case_dir, f"{case_key}_Global_Gradient_Norm.png"),
  552. dpi=DPI,
  553. bbox_inches="tight"
  554. )
  555. plt.show()
  556. def plot_layerwise_gradient_norm(case_key, case_name, history):
  557. case_dir = os.path.join(OUTPUT_DIR, case_key)
  558. epochs = history["epoch"]
  559. layer_keys = [f"Layer {i}" for i in range(1, N_HIDDEN_LAYERS + 3)]
  560. plt.figure(figsize=PLOT_SIZE)
  561. for layer in layer_keys:
  562. values = []
  563. for row in history["layerwise_gradient_norms"]:
  564. values.append(row.get(layer, np.nan))
  565. plt.plot(
  566. epochs,
  567. values,
  568. linewidth=1.5,
  569. label=layer
  570. )
  571. plt.xlabel("Epoch")
  572. plt.ylabel("Layer-wise Gradient Norm")
  573. plt.yscale("log")
  574. plt.grid(True, alpha=0.3)
  575. plt.legend()
  576. plt.tight_layout()
  577. plt.savefig(
  578. os.path.join(case_dir, f"{case_key}_Layerwise_Gradient_Norm.pdf"),
  579. dpi=DPI,
  580. bbox_inches="tight"
  581. )
  582. plt.savefig(
  583. os.path.join(case_dir, f"{case_key}_Layerwise_Gradient_Norm.png"),
  584. dpi=DPI,
  585. bbox_inches="tight"
  586. )
  587. plt.show()
  588. layerwise_table = {"epoch": epochs}
  589. for layer in layer_keys:
  590. layerwise_table[layer] = [
  591. row.get(layer, np.nan) for row in history["layerwise_gradient_norms"]
  592. ]
  593. pd.DataFrame(layerwise_table).to_csv(
  594. os.path.join(case_dir, f"{case_key}_Layerwise_Gradient_Norm.csv"),
  595. index=False
  596. )
  597. def plot_solution_comparison(case_key, case_name, model):
  598. case_dir = os.path.join(OUTPUT_DIR, case_key)
  599. model.eval()
  600. with torch.no_grad():
  601. if case_key == "Case_I":
  602. x = torch.linspace(0.5, 2.0, 300, device=device).view(-1, 1)
  603. y_exact = exact_case_1(x)
  604. y_pred = model(x)
  605. xlabel = r"$\alpha$"
  606. ylabel = r"$V(\alpha)$"
  607. elif case_key == "Case_II":
  608. x = torch.linspace(-0.5, 1.0, 300, device=device).view(-1, 1)
  609. y_exact = exact_case_2(x)
  610. y_pred = model(x)
  611. xlabel = r"$\alpha$"
  612. ylabel = r"$V(\alpha)$"
  613. elif case_key == "Case_III":
  614. x = torch.linspace(0.0, 2.0, 300, device=device).view(-1, 1)
  615. y_exact = exact_case_3(x)
  616. y_pred = model(x)
  617. xlabel = r"$t$"
  618. ylabel = r"$f(t)$"
  619. elif case_key == "Case_IV":
  620. x = torch.linspace(0.0, 2.0, 300, device=device).view(-1, 1)
  621. y_exact = exact_case_4(x)
  622. y_pred = model(x)
  623. xlabel = r"$t$"
  624. ylabel = r"$f(t)$"
  625. else:
  626. return
  627. x_np = x.detach().cpu().numpy().flatten()
  628. exact_np = y_exact.detach().cpu().numpy().flatten()
  629. pred_np = y_pred.detach().cpu().numpy().flatten()
  630. abs_error = np.abs(exact_np - pred_np)
  631. plt.figure(figsize=PLOT_SIZE)
  632. plt.plot(
  633. x_np,
  634. exact_np,
  635. "k--",
  636. linewidth=1.5,
  637. label="Exact"
  638. )
  639. plt.plot(
  640. x_np,
  641. pred_np,
  642. linewidth=1.5,
  643. label="S-PINN"
  644. )
  645. plt.xlabel(xlabel)
  646. plt.ylabel(ylabel)
  647. plt.grid(True, alpha=0.3)
  648. plt.legend()
  649. plt.tight_layout()
  650. plt.savefig(
  651. os.path.join(case_dir, f"{case_key}_Solution_Comparison.pdf"),
  652. dpi=DPI,
  653. bbox_inches="tight"
  654. )
  655. plt.savefig(
  656. os.path.join(case_dir, f"{case_key}_Solution_Comparison.png"),
  657. dpi=DPI,
  658. bbox_inches="tight"
  659. )
  660. plt.show()
  661. plt.figure(figsize=PLOT_SIZE)
  662. plt.plot(
  663. x_np,
  664. abs_error,
  665. linewidth=1.5,
  666. label="Absolute error"
  667. )
  668. plt.xlabel(xlabel)
  669. plt.ylabel("Absolute Error")
  670. plt.yscale("log")
  671. plt.grid(True, alpha=0.3)
  672. plt.legend()
  673. plt.tight_layout()
  674. plt.savefig(
  675. os.path.join(case_dir, f"{case_key}_Absolute_Error.pdf"),
  676. dpi=DPI,
  677. bbox_inches="tight"
  678. )
  679. plt.savefig(
  680. os.path.join(case_dir, f"{case_key}_Absolute_Error.png"),
  681. dpi=DPI,
  682. bbox_inches="tight"
  683. )
  684. plt.show()
  685. pd.DataFrame({
  686. "input": x_np,
  687. "exact": exact_np,
  688. "spinn": pred_np,
  689. "absolute_error": abs_error
  690. }).to_csv(
  691. os.path.join(case_dir, f"{case_key}_solution_data.csv"),
  692. index=False
  693. )
  694. def create_summary_table(all_histories):
  695. rows = []
  696. for case_key, item in all_histories.items():
  697. hist = item["history"]
  698. rows.append({
  699. "Case": case_key,
  700. "Description": item["case_name"],
  701. "Epochs": len(hist["epoch"]),
  702. "Final Total Loss": hist["total_loss"][-1],
  703. "Final ODE Loss": hist["ode_loss"][-1],
  704. "Final Symmetry Loss": hist["symmetry_loss"][-1],
  705. "Final BC Loss": hist["bc_loss"][-1],
  706. "Final Gradient Norm": hist["global_gradient_norm"][-1],
  707. "Mean Update Cost (s)": float(np.mean(hist["update_cost"]))
  708. })
  709. df = pd.DataFrame(rows)
  710. df.to_csv(
  711. os.path.join(OUTPUT_DIR, "four_case_training_summary.csv"),
  712. index=False
  713. )
  714. print("\nTraining Summary")
  715. print(df)
  716. return df
  717. # ============================================================
  718. # MAIN EXECUTION
  719. # ============================================================
  720. def main():
  721. cases = [
  722. ("Case_I", "Scaling symmetry", case_1_loss),
  723. ("Case_II", "Translation symmetry", case_2_loss),
  724. ("Case_III", "Damped symmetry", case_3_loss),
  725. ("Case_IV", "Generalized damped symmetry", case_4_loss),
  726. ]
  727. all_results = {}
  728. for case_key, case_name, loss_function in cases:
  729. model, history = train_one_case(
  730. case_key=case_key,
  731. case_name=case_name,
  732. loss_function=loss_function,
  733. epochs=N_EPOCHS
  734. )
  735. plot_loss_history(case_key, case_name, history)
  736. plot_layerwise_gradient_norm(case_key, case_name, history)
  737. plot_solution_comparison(case_key, case_name, model)
  738. all_results[case_key] = {
  739. "case_name": case_name,
  740. "model": model,
  741. "history": history
  742. }
  743. summary_df = create_summary_table(all_results)
  744. with open(os.path.join(OUTPUT_DIR, "all_four_case_results.pkl"), "wb") as f:
  745. pickle.dump({
  746. case_key: {
  747. "case_name": item["case_name"],
  748. "history": item["history"]
  749. }
  750. for case_key, item in all_results.items()
  751. }, f)
  752. print("\nAll four S-PINN cases completed.")
  753. print(f"All outputs are saved in folder: {OUTPUT_DIR}")
  754. if IN_COLAB:
  755. import shutil
  756. zip_path = shutil.make_archive(OUTPUT_DIR, "zip", OUTPUT_DIR)
  757. files.download(zip_path)
  758. if __name__ == "__main__":
  759. main()

symmetry_pinns_updated.py at commit 7025873, under MIT · at the source

Overview

Authors: Muhammad Israr1, Shahbaz Ahmad2, F. D. Zaman2, Iftikhar Ali3
  1. Department of Sciences and Humanities, National University of Computer and Emerging Sciences, Peshawar, Khyber Pakhtunkhwa, Pakistan
  2. Abdus Salam School of Mathematical Sciences, GC University Lahore, Lahore, Pakistan
  3. Department of Mathematics, University of Hafr Al Batin, Hafar Al-Batin, Saudi Arabia
Journal: PloS one, volume 21, issue 10, article e0360636
Dates: received 8 January 2026; accepted 29 September 2026; published online 27 October 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1371/journal.pone.0360636 · PMID 42945381 · PMCID PMC13712689 · OpenAlex W7223983385
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: computational modeling (no new data) (modality), none (in silico) (organism)
MeSH: Neural Networks, Computer*, Algorithms, Computer Simulation, Elasticity, Nonlinear Dynamics (* major topic)
Journal subjects: Physical Sciences, Mathematics, Geometry, Symmetry, Biology and Life Sciences, Neuroscience, Cognitive Science, Cognitive Psychology, Learning, Psychology, Social Sciences, Learning and Memory, Computer and Information Sciences, Neural Networks, Evolutionary Biology, Evolutionary Processes, Convergent Evolution, Behavior, Optimization, Differential Equations, Materials Science, Material Properties, Elasticity
Topic: Model Reduction and Neural Networks (Statistical and Nonlinear Physics, Physics and Astronomy), according to OpenAlex
Citations: not cited yet (Europe PMC); 43 references in the paper

Abstract

This study develops a causality-enhanced and symmetry-preserving Physics-Informed Neural Network (S-PINN) framework for nonlinear damped elastodynamic partial differential equations. The governing nonlinear elastic wave equation with viscous damping is reduced through Lie symmetry analysis into four invariant ordinary differential equation forms, including scaling, translation, damped, and generalized damped symmetries. The proposed framework combines symmetry-aware solution reconstruction, composite residual and symmetry losses, and causality-based temporal weighting to improve the training stability and physical consistency of PINNs. Numerical experiments are performed using a fully connected neural network with four hidden layers, 128 neurons per layer, the tanh activation function, and the L-BFGS optimizer. The S-PINN solutions are compared with conventional PINNs and exact analytical references for all four symmetry-reduced cases. The results show that the proposed S-PINN framework provides faster convergence, lower loss, and improved solution accuracy. In Case IV, S-PINNs achieve a 35% faster convergence rate during the first 500 epochs and reduce the final loss from 3.8 for PINNs to 2.4. The S-PINN loss stabilizes after approximately 1000 epochs, whereas the PINN loss continues to oscillate with fluctuations up to 15%. The gradient norm remains within 0.5–1.5 for S-PINNs, compared with 0.2–2.5 for PINNs. At α=0.4, the S-PINN solution attains 98% agreement with the exact solution, and its maximum absolute error remains below 0.05, compared with 0.18 for the standard PINN. Contour comparisons further show less than 5% distortion for S-PINNs, while PINNs exhibit distortions up to 18%. These findings demonstrate that embedding Lie symmetries and causal temporal learning into PINNs constrains the solution space to physically admissible manifolds and improves the reliability of neural solvers for nonlinear wave propagation in computational mechanics.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repository

Its files are read in the Code ↔ Paper reader above, with 3 matches between paragraphs and lines of code.

shahbaz1982/Symmetry-PINNs-

License: MIT
State: the link answers, verified on 30 October 2026
Evidence: files inventoried
Commit: 7025873d5a500403a2e1907b4df9be8cee682c13, 19 July 2026
Languages: Jupyter (3), Python (1)
Size: 6 files, 4 scripts
Software Heritage: not archived
Found in: “Data Availability”
Holds: README, license file, 3 notebooks
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Matplotlib (4 files), NumPy (4 files), PyTorch (4 files), pandas (3 files), SciPy (3 files)
Availability: 1 check, the latest on 30 October 2026: the link answers
  • 30 October 2026: the link answers
6 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 4 scripts, each with its path and the digest of its content;
  • 3 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data Availability

All relevant data are within the paper and its Supporting Information files. The code is also publicly available from GitHub (https://github.com/shahbaz1982/Symmetry-PINNs-).

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 30 October 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 4 authors, 5 MeSH terms, 1 funder, 36 references.

Cite

This paper

Israr, M., Ahmad, S., Zaman, F. D., & Ali, I. (2026). Causality-enhanced and symmetry-preserving PINNs for damped elastodynamic PDEs. PloS one, 21(10), e0360636. https://doi.org/10.1371/journal.pone.0360636

BibTeX

@article{israr2026causality,
author = {Israr, Muhammad and Ahmad, Shahbaz and Zaman, F. D. and Ali, Iftikhar},
title = {{Causality-enhanced and symmetry-preserving PINNs for damped elastodynamic PDEs}},
journal = {PloS one},
year = {2026},
month = oct,
volume = {21},
number = {10},
pages = {e0360636},
publisher = {PLOS},
issn = {1932-6203},
doi = {10.1371/journal.pone.0360636},
url = {https://doi.org/10.1371/journal.pone.0360636},
pmid = {42945381},
pmcid = {PMC13712689}
}

RIS

TY - JOUR
AU - Israr, Muhammad
AU - Ahmad, Shahbaz
AU - Zaman, F. D.
AU - Ali, Iftikhar
TI - Causality-enhanced and symmetry-preserving PINNs for damped elastodynamic PDEs
T2 - PloS one
J2 - PLoS One
PY - 2026
DA - 2026/10/27
VL - 21
IS - 10
SP - e0360636
SN - 1932-6203
PB - PLOS
DO - 10.1371/journal.pone.0360636
UR - https://doi.org/10.1371/journal.pone.0360636
LA - en
ER -

CSL-JSON

{
"id": "10.1371/journal.pone.0360636",
"type": "article-journal",
"title": "Causality-enhanced and symmetry-preserving PINNs for damped elastodynamic PDEs",
"container-title": "PloS one",
"author": [
{
"family": "Israr",
"given": "Muhammad"
},
{
"family": "Ahmad",
"given": "Shahbaz"
},
{
"family": "Zaman",
"given": "F. D."
},
{
"family": "Ali",
"given": "Iftikhar"
}
],
"container-title-short": "PLoS One",
"volume": "21",
"issue": "10",
"page": "e0360636",
"DOI": "10.1371/journal.pone.0360636",
"PMID": "42945381",
"PMCID": "PMC13712689",
"ISSN": "1932-6203",
"publisher": "PLOS",
"URL": "https://doi.org/10.1371/journal.pone.0360636",
"language": "en",
"issued": {
"date-parts": [
[
2026,
10,
27
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.3390/biomimetics11030171
Hybrid Neuro-Symbolic State-Space Modeling for Industrial Robot Calibration via Adaptive Wavelet Networks and PSO.
Journal: Biomimetics (Basel, Switzerland)
In common: 2 references
[2] doi:10.3389/fnbot.2023.1166911
Bidirectional recurrent learning of inverse dynamic models for robots with elastic joints: a real-time real-world implementation.
Journal: Frontiers in neurorobotics
In common: 1 reference

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1371/journal.pone.0360636.svg)](https://openscicode.org/badge/doi/10.1371/journal.pone.0360636)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1371/journal.pone.0360636.svg
   :target: https://openscicode.org/badge/doi/10.1371/journal.pone.0360636
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1371/journal.pone.0360636"><img src="https://openscicode.org/badge/doi/10.1371/journal.pone.0360636.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.