206 lines
7.3 KiB
Python
206 lines
7.3 KiB
Python
from __future__ import annotations
|
|
|
|
import csv
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def require(condition: bool, message: str) -> None:
|
|
if not condition:
|
|
raise AssertionError(message)
|
|
|
|
|
|
def parse_float_marker(text: str, name: str) -> float:
|
|
match = re.search(rf"{name}=([+-]?\d+\.\d+E[+-]\d+)", text)
|
|
require(match is not None, f"missing {name} marker")
|
|
return float(match.group(1))
|
|
|
|
|
|
def clean_output(out_dir: Path) -> None:
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
for pattern in ("history.csv", "nodes_*.csv", "elements_*.csv", "reactions_*.csv", "result_*.vtk"):
|
|
for path in out_dir.glob(pattern):
|
|
path.unlink()
|
|
contact_dir = out_dir / "contact"
|
|
if contact_dir.exists():
|
|
shutil.rmtree(contact_dir)
|
|
|
|
|
|
def parse_input_mesh(path: Path) -> tuple[dict[int, tuple[float, float, float]], dict[int, list[int]]]:
|
|
nodes: dict[int, tuple[float, float, float]] = {}
|
|
elements: dict[int, list[int]] = {}
|
|
mode = ""
|
|
for raw_line in path.read_text(encoding="ascii").splitlines():
|
|
line = raw_line.strip()
|
|
if not line or line.startswith("**"):
|
|
continue
|
|
if line.startswith("*"):
|
|
upper = line.upper()
|
|
if upper.startswith("*NODE"):
|
|
mode = "node"
|
|
elif upper.startswith("*ELEMENT"):
|
|
mode = "element"
|
|
else:
|
|
mode = ""
|
|
continue
|
|
|
|
parts = [part.strip() for part in line.split(",") if part.strip()]
|
|
if mode == "node":
|
|
nodes[int(parts[0])] = (float(parts[1]), float(parts[2]), float(parts[3]))
|
|
elif mode == "element":
|
|
elements[int(parts[0])] = [int(part) for part in parts[1:]]
|
|
return nodes, elements
|
|
|
|
|
|
def latest_step_file(out_dir: Path, prefix: str) -> Path:
|
|
files = sorted(out_dir.glob(f"{prefix}_*.csv"))
|
|
require(files, f"missing {prefix} output")
|
|
return max(files, key=lambda item: int(item.stem.split("_")[1]))
|
|
|
|
|
|
def read_csv_rows(path: Path) -> list[dict[str, str]]:
|
|
require(path.exists(), f"missing output: {path}")
|
|
with path.open(newline="", encoding="utf-8") as handle:
|
|
return list(csv.DictReader(handle))
|
|
|
|
|
|
def centroid(conn: list[int], nodes: dict[int, tuple[float, float, float]]) -> tuple[float, float, float]:
|
|
x = sum(nodes[nid][0] for nid in conn) / float(len(conn))
|
|
y = sum(nodes[nid][1] for nid in conn) / float(len(conn))
|
|
z = sum(nodes[nid][2] for nid in conn) / float(len(conn))
|
|
return x, y, z
|
|
|
|
|
|
def bending_profile(
|
|
rows: list[dict[str, str]],
|
|
nodes: dict[int, tuple[float, float, float]],
|
|
elements: dict[int, list[int]],
|
|
length: float,
|
|
) -> list[tuple[float, float]]:
|
|
by_z: dict[float, list[float]] = {}
|
|
centroids = {eid: centroid(conn, nodes) for eid, conn in elements.items()}
|
|
dx = min(
|
|
abs(centroids[a][0] - centroids[b][0])
|
|
for a in centroids
|
|
for b in centroids
|
|
if a < b and abs(centroids[a][0] - centroids[b][0]) > 1.0e-12
|
|
)
|
|
for row in rows:
|
|
eid = int(row["elem_id"])
|
|
cx, _cy, cz = centroids[eid]
|
|
if abs(cx - 0.5 * length) > 0.75 * dx:
|
|
continue
|
|
by_z.setdefault(round(cz, 12), []).append(float(row["s11"]))
|
|
|
|
require(len(by_z) >= 8, "midspan profile has too few height samples")
|
|
return sorted((z, sum(values) / len(values)) for z, values in by_z.items())
|
|
|
|
|
|
def neutral_axis(profile: list[tuple[float, float]]) -> float:
|
|
for (z0, s0), (z1, s1) in zip(profile, profile[1:]):
|
|
if s0 == 0.0:
|
|
return z0
|
|
if s0 * s1 <= 0.0:
|
|
return z0 - s0 * (z1 - z0) / (s1 - s0)
|
|
raise AssertionError("midspan s11 profile does not cross zero")
|
|
|
|
|
|
def check_profile(profile: list[tuple[float, float]], height: float) -> tuple[float, float, float]:
|
|
z0 = neutral_axis(profile)
|
|
half_h = 0.5 * height
|
|
bottom_s = profile[0][1]
|
|
top_s = profile[-1][1]
|
|
require(-half_h < z0 < half_h, f"neutral axis outside section: {z0:.6E}")
|
|
|
|
if top_s < 0.0 and bottom_s > 0.0:
|
|
compression_thickness = half_h - z0
|
|
tension_thickness = z0 + half_h
|
|
elif top_s > 0.0 and bottom_s < 0.0:
|
|
compression_thickness = z0 + half_h
|
|
tension_thickness = half_h - z0
|
|
else:
|
|
raise AssertionError(
|
|
f"unexpected stress signs at section faces: bottom={bottom_s:.6E}, top={top_s:.6E}"
|
|
)
|
|
|
|
compression_peak = max(abs(s11) for _z, s11 in profile if s11 < 0.0)
|
|
tension_peak = max(abs(s11) for _z, s11 in profile if s11 > 0.0)
|
|
max_peak = max(compression_peak, tension_peak)
|
|
|
|
require(compression_thickness < tension_thickness, "compression band is not thinner than tension band")
|
|
require(abs(z0) > 4.0e-4, f"neutral axis shift is too small: {z0:.6E}")
|
|
require(abs(z0) < 2.2e-3, f"neutral axis shift is too large: {z0:.6E}")
|
|
require(max_peak > 4.0e4, f"peak bending stress is too small: {max_peak:.6E}")
|
|
require(max_peak < 2.5e5, f"peak bending stress is too large: {max_peak:.6E}")
|
|
require(
|
|
compression_peak > 1.10 * tension_peak,
|
|
f"compression peak {compression_peak:.6E} is not above tension peak {tension_peak:.6E}",
|
|
)
|
|
return z0, compression_peak, tension_peak
|
|
|
|
|
|
def main() -> int:
|
|
if len(sys.argv) != 4:
|
|
raise SystemExit("usage: check_stress_dependent_results.py REPO_ROOT FEMLITE_EXE OUTPUT_DIR")
|
|
|
|
repo = Path(sys.argv[1]).resolve()
|
|
femlite = Path(sys.argv[2]).resolve()
|
|
out_dir = Path(sys.argv[3]).resolve()
|
|
inp = repo / "examples" / "stress_dependent_elasticity" / "stress_dependent_elasticity.inp"
|
|
text = inp.read_text(encoding="ascii")
|
|
|
|
require("smoke" not in text.lower(), "stress-dependent input still describes a smoke case")
|
|
require("Modeling Stress Dependent Elasticity" in text, "input does not identify the reference model")
|
|
length = parse_float_marker(text, "LENGTH_M")
|
|
height = parse_float_marker(text, "HEIGHT_M")
|
|
moment = parse_float_marker(text, "BENDING_MOMENT_NM")
|
|
total_fx = parse_float_marker(text, "TOTAL_FX")
|
|
total_my = parse_float_marker(text, "TOTAL_MY")
|
|
require(abs(total_fx) <= 1.0e-9, f"right-end traction has nonzero resultant Fx: {total_fx:.6E}")
|
|
require(abs(total_my - moment) <= 1.0e-8, f"right-end moment mismatch: {total_my:.6E} vs {moment:.6E}")
|
|
|
|
clean_output(out_dir)
|
|
completed = subprocess.run(
|
|
[
|
|
str(femlite),
|
|
str(inp),
|
|
"--static-nonlinear",
|
|
"--allow-cutback",
|
|
"--max-newton",
|
|
"80",
|
|
"--newton-tol",
|
|
"1e-4",
|
|
"--output-dir",
|
|
str(out_dir),
|
|
"--output-interval",
|
|
"1",
|
|
],
|
|
cwd=repo,
|
|
text=True,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
)
|
|
print(completed.stdout)
|
|
if completed.returncode != 0:
|
|
raise RuntimeError(f"{femlite} exited with code {completed.returncode}")
|
|
|
|
nodes, elements = parse_input_mesh(inp)
|
|
rows = read_csv_rows(latest_step_file(out_dir, "elements"))
|
|
profile = bending_profile(rows, nodes, elements, length)
|
|
z0, compression_peak, tension_peak = check_profile(profile, height)
|
|
|
|
print(
|
|
"stress-dependent elasticity: "
|
|
f"neutral_axis={z0:.6E} m, "
|
|
f"compression_peak={compression_peak:.6E} Pa, "
|
|
f"tension_peak={tension_peak:.6E} Pa"
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|