playground / utils /geometry.py
fractben's picture
Fracture-Bench playground
cc3506e verified
Raw History Blame Contribute Delete
8.91 kB
"""Domain geometry + input-field construction for both datasets.
Dataset 1: 128x128 square plate, central circular hole, GRF boundary loading.
Dataset 2: 256x128 (rows x cols) FGM plate, two fixed circular inclusions,
horizontal pre-crack seeded in the left half.
Dataset-2 geometry (inclusion centers/radii, E(x) field, initial crack) is now
derived directly from the training data (ML_benchmark Dataset-2 npz) and the
manuscript (§2.2.2, Fig. 3-5, Table 3), so inputs fed to the real FNO are
in-distribution:
* 4 mm x 8 mm plate on a 128(x) x 256(y) grid (32 px/mm).
* Upper inclusion: 2 mm dia (r=33 px), center (x=48, y=191).
* Lower inclusion: 3 mm dia (r=49 px), center (x=64, y=64).
* E(x) is a *functionally graded* matrix (mean 377 GPa) with hard (10x) or
soft (0.1x) discs -> exactly 4 toggle combos = the 4 dataset cases. The real
(denoised) per-case E fields are stored in sample_data/d2_efield_templates.npz.
* Initial pre-crack: fully damaged (d=1) horizontal band from the left edge
(x=0) to the tip, ~5 px wide, with a sharp tip decay (PF-CZM profile).
Arrays use the dashboard (row=y, col=x) = (256,128) convention; origin="lower"
in plotting so y increases upward (smaller inclusion on top, per the paper).
"""
from __future__ import annotations
import os
import numpy as np
D1_GRID = 128
D2_SHAPE = (256, 128) # (H, W) = (y, x): plate is 4 mm wide (x) x 8 mm tall (y)
# ---------------------------------------------------------------- Dataset 1
_D1_SAMPLES_PATH = os.path.join(
os.path.dirname(__file__), "..", "sample_data", "d1_test_samples.npz")
_D1_CACHE = None
# ---------------------------------------------------------------- Dataset 2
_D2_SAMPLES_PATH = os.path.join(
os.path.dirname(__file__), "..", "sample_data", "d2_test_samples.npz")
_D2_CACHE = None
def d1_samples():
"""Real Dataset-1 test samples (u0 + 44-step phase fields + grids),
extracted from the training npz (test split, indices 900-907)."""
global _D1_CACHE
if _D1_CACHE is None:
_D1_CACHE = np.load(_D1_SAMPLES_PATH)
return _D1_CACHE
def d1_grids():
"""Real (grid_x, grid_y): 128x128, domain [-1.1, 1.1]^2."""
s = d1_samples()
return s["grid_x"], s["grid_y"]
def hole_mask(grid: int = D1_GRID, rel_radius: float = 0.18) -> np.ndarray:
"""True INSIDE the hole (the app masks these pixels out of plots).
Real geometry from the training pipeline: hole of radius 0.5 centered at
the origin of the [-1.1, 1.1]^2 domain — i.e. x^2 + y^2 < 0.25.
"""
try:
gx, gy = d1_grids()
return (gx ** 2 + gy ** 2) < 0.25
except Exception: # sample file missing: fall back to the analytic mask
yy, xx = np.mgrid[0:grid, 0:grid]
c = grid / 2 - 0.5
r = grid * 0.5 / 2.2
return (xx - c) ** 2 + (yy - c) ** 2 < r ** 2
def sample_grf(n: int = D1_GRID, length_scale: float = 0.3,
amplitude: float = 0.25, mean: float = 1.0,
seed: int | None = None) -> np.ndarray:
"""1-D squared-exponential GRF realization f(s), s in [-1, 1].
Used as the boundary profile f(.) of eq. (9) in the manuscript.
"""
rng = np.random.default_rng(seed)
s = np.linspace(-1, 1, n)
cov = amplitude**2 * np.exp(-((s[:, None] - s[None, :]) ** 2)
/ (2 * length_scale**2))
cov += 1e-8 * np.eye(n)
return mean + rng.multivariate_normal(np.zeros(n), cov)
def boundary_displacement_from_grf(f: np.ndarray, grid: int = D1_GRID) -> np.ndarray:
"""Build a coarse (grid,grid,2) initial displacement field u(x,0) from a
GRF boundary profile via the affine map u = alpha(x) * x of eq. (9).
PLACEHOLDER: your real pipeline computes u(x,0) from the FE solve /
dataset preprocessing. Replace this with the exact preprocessing the
models were trained on (including the [-1,1] min-max normalization
constants from the training set).
"""
s = np.linspace(-1, 1, grid)
X, Y = np.meshgrid(s, s)
alpha = np.interp(X.ravel(), s, f).reshape(grid, grid)
u = np.stack([alpha * X, 1.1 * alpha * Y], axis=-1)
u[hole_mask(grid)] = 0.0
return u.astype(np.float32)
# ---------------------------------------------------------------- Dataset 2
# Real inclusion geometry, extracted from the training e_field (variance across
# the 4 hard/soft cases isolates the two discs). (row=y, col=x) on the (256,128)
# grid; 32 px/mm. Upper = smaller (2 mm dia), lower = larger (3 mm dia).
_UPPER = dict(row=191, col=48, r=32) # 2 mm dia -> r = 1.0 mm = 32 px (manuscript)
_LOWER = dict(row=64, col=64, r=48) # 3 mm dia -> r = 1.5 mm = 48 px (manuscript)
# (upper_hard, lower_hard) -> dataset case (E template). Hard = 10*E_mat,
# soft = 0.1*E_mat. Cases match the manuscript Fig. 3 configurations.
_CASE_OF = {
(False, True): "case1", # upper soft, lower hard
(True, True): "case2", # upper hard, lower hard
(False, False): "case3", # upper soft, lower soft
(True, False): "case4", # upper hard, lower soft
}
_E_TEMPLATES_PATH = os.path.join(
os.path.dirname(__file__), "..", "sample_data", "d2_efield_templates.npz")
_E_TEMPLATES = None # lazily loaded cache
def _load_e_templates():
global _E_TEMPLATES
if _E_TEMPLATES is None and os.path.exists(_E_TEMPLATES_PATH):
npz = np.load(_E_TEMPLATES_PATH)
_E_TEMPLATES = {k: npz[k] for k in npz.files}
return _E_TEMPLATES
def inclusion_masks(shape: tuple[int, int] = D2_SHAPE):
H, W = shape
yy, xx = np.mgrid[0:H, 0:W]
upper = (xx - _UPPER["col"]) ** 2 + (yy - _UPPER["row"]) ** 2 < _UPPER["r"] ** 2
lower = (xx - _LOWER["col"]) ** 2 + (yy - _LOWER["row"]) ** 2 < _LOWER["r"] ** 2
return upper, lower
def build_modulus_field(upper_hard: bool, lower_hard: bool,
E_mat: float = 377.0,
shape: tuple[int, int] = D2_SHAPE) -> np.ndarray:
"""Functionally graded E(x) for the chosen inclusion configuration.
Returns the real (denoised) training E field for the matching dataset case
so the input is in-distribution for the FNO. Falls back to a synthetic
graded-free field only if the template file is missing.
"""
tmpl = _load_e_templates()
if tmpl is not None:
return tmpl[_CASE_OF[(bool(upper_hard), bool(lower_hard))]].astype(np.float32)
# fallback (template file absent): constant matrix + discs
E = np.full(shape, E_mat * 1000.0, dtype=np.float32) # MPa, matches data units
upper, lower = inclusion_masks(shape)
E[upper] = E_mat * 1000.0 * (10.0 if upper_hard else 0.1)
E[lower] = E_mat * 1000.0 * (10.0 if lower_hard else 0.1)
return E
def build_initial_crack(tip_x: int, tip_y: int,
half_width: float = 1.6,
shape: tuple[int, int] = D2_SHAPE) -> np.ndarray:
"""PF-CZM horizontal pre-crack d(x,0): fully damaged (d=1) band from the
left edge (x=0) to the tip at (tip_x, tip_y), ~5 px wide, sharp tip decay.
Matches the initial cracks observed in the training data (core d=1 along the
centerline, transverse Gaussian width, ~5 px tip roll-off). The pre-crack is
cut at the inclusion boundaries (with a small clearance) so it can never
merge into an inclusion, exactly as in the dataset where every seed is kept
sufficiently far from both discs (manuscript Fig. 4).
"""
H, W = shape
yy, xx = np.mgrid[0:H, 0:W]
transverse = np.exp(-((yy - tip_y) ** 2) / (2.0 * half_width ** 2))
longitudinal = np.where(
xx <= tip_x, 1.0,
np.exp(-((xx - tip_x) / 1.6) ** 2)) # sharp tip decay
d0 = transverse * longitudinal
# keep the pre-crack clear of the inclusions (3 px clearance)
upper, lower = inclusion_masks(shape)
clear = 3
keep_out = ((xx - _UPPER["col"]) ** 2 + (yy - _UPPER["row"]) ** 2
< (_UPPER["r"] + clear) ** 2) | \
((xx - _LOWER["col"]) ** 2 + (yy - _LOWER["row"]) ** 2
< (_LOWER["r"] + clear) ** 2)
d0[keep_out] = 0.0
return np.clip(d0, 0.0, 1.0).astype(np.float32)
def d2_samples():
"""Real Dataset-2 test samples (d0, E, d_tf, flags), 8 total (2 per case).
Arrays in dashboard (y,x)=(256,128) convention; already transposed from
the training (x,y)=(128,256) layout.
"""
global _D2_CACHE
if _D2_CACHE is None:
_D2_CACHE = np.load(_D2_SAMPLES_PATH)
return _D2_CACHE
def admissible_tip_region(shape: tuple[int, int] = D2_SHAPE) -> tuple[range, range]:
"""Crack-tip placement window, taken from the real training-data
distribution (5th-95th percentile): tip x in [8,60] px (left half), crack
row y in [86,170] px. Tips outside an inclusion propagate freely toward
them; the pre-crack itself is additionally clipped at the disc boundaries."""
return range(8, 61), range(86, 171)