Files
FemLite/tests/scripts/run_example_smoke.py
T
shenw d8dbc0b346
FemLite CI / build-test (push) Has been cancelled
Complete V4.7 shell stabilization and benchmarks
2026-06-25 10:07:48 +08:00

177 lines
7.1 KiB
Python

from __future__ import annotations
import argparse
import csv
import re
import subprocess
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run a lightweight FemLite example smoke test.")
parser.add_argument("repo_root")
parser.add_argument("femlite_exe")
parser.add_argument("build_dir")
parser.add_argument("case_name")
parser.add_argument("input_relpath")
parser.add_argument("mode", choices=("run", "static-linear"))
parser.add_argument("--dynamic-steps", type=int, default=0)
parser.add_argument("--output-interval", type=int, default=0)
parser.add_argument("--require-contact", action="store_true")
parser.add_argument("--require-friction", action="store_true")
parser.add_argument("--probe-node", type=int)
parser.add_argument("--probe-field", choices=("ux", "uy", "uz"))
parser.add_argument("--min-abs-displacement", type=float, default=0.0)
parser.add_argument("--sign", choices=("negative", "positive", "either"), default="either")
return parser.parse_args()
def shortened_dynamic_input(source: Path, destination: Path, steps: int) -> Path:
lines = source.read_text(encoding="utf-8").splitlines()
for index, line in enumerate(lines):
if line.strip().upper().startswith("*DYNAMIC"):
data_index = index + 1
if data_index >= len(lines):
raise ValueError(f"{source} has *DYNAMIC without a data line")
parts = lines[data_index].split(",")
if not parts:
raise ValueError(f"{source} has an empty *DYNAMIC data line")
dt = float(parts[0])
lines[data_index] = f"{dt:.10E}, {dt * steps:.10E}"
destination.write_text("\n".join(lines) + "\n", encoding="utf-8")
return destination
raise ValueError(f"{source} does not contain *DYNAMIC")
def run_case(args: argparse.Namespace) -> tuple[str, int]:
repo_root = Path(args.repo_root).resolve()
femlite_exe = Path(args.femlite_exe).resolve()
build_dir = Path(args.build_dir).resolve()
source_inp = repo_root / args.input_relpath
case_dir = build_dir / "example_smoke" / args.case_name
case_dir.mkdir(parents=True, exist_ok=True)
inp = source_inp
expected_steps = 1 if args.mode == "static-linear" else None
if args.dynamic_steps > 0:
inp = shortened_dynamic_input(source_inp, case_dir / source_inp.name, args.dynamic_steps)
expected_steps = args.dynamic_steps
command = [str(femlite_exe), str(inp)]
if args.mode == "run":
command.append("--run")
elif args.mode == "static-linear":
command.append("--static-linear")
command.extend(["--output-dir", str(case_dir)])
command.extend(["--output-interval", str(args.output_interval)])
completed = subprocess.run(
command,
cwd=repo_root,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
print(completed.stdout)
if completed.returncode != 0:
raise RuntimeError(f"FemLite exited with code {completed.returncode}")
match = re.search(r"steps:\s*(\d+)", completed.stdout)
if not match:
raise RuntimeError("FemLite output did not contain a step count")
steps = int(match.group(1))
if expected_steps is not None and steps != expected_steps:
raise RuntimeError(f"expected {expected_steps} steps, got {steps}")
return completed.stdout, steps
def check_contact_output(build_dir: Path, case_name: str, step: int) -> None:
contact_file = build_dir / "example_smoke" / case_name / f"contact_{step:08d}.csv"
if not contact_file.exists():
raise RuntimeError(f"missing contact output: {contact_file}")
with contact_file.open(newline="", encoding="utf-8") as handle:
rows = list(csv.DictReader(handle))
summary = next((row for row in rows if row.get("kind") == "SUMMARY"), None)
if summary is None:
raise RuntimeError(f"{contact_file} does not contain a SUMMARY row")
active = int(summary["active_count"])
if active <= 0:
raise RuntimeError(f"{contact_file} did not record active contact")
def check_friction_output(build_dir: Path, case_name: str, step: int) -> None:
contact_file = build_dir / "example_smoke" / case_name / f"contact_{step:08d}.csv"
if not contact_file.exists():
raise RuntimeError(f"missing contact output: {contact_file}")
with contact_file.open(newline="", encoding="utf-8") as handle:
rows = [row for row in csv.DictReader(handle) if row.get("kind") == "PAIR"]
if not rows:
raise RuntimeError(f"{contact_file} does not contain contact pair rows")
max_slip = max(float(row["accumulated_slip"]) for row in rows)
max_work = max(float(row["friction_work_total"]) for row in rows)
min_work = min(float(row["friction_work_total"]) for row in rows)
max_reg = max(float(row["friction_regularization"]) for row in rows)
max_ft = max(
max(abs(float(row["ftx"])), abs(float(row["fty"])), abs(float(row["ftz"])))
for row in rows
)
if max_reg <= 0.0:
raise RuntimeError(f"{contact_file} did not report friction regularization")
if max_slip <= 0.0 or max_ft <= 0.0:
raise RuntimeError(f"{contact_file} did not record frictional slip")
if min_work < -1.0e-12 or max_work <= 0.0:
raise RuntimeError(f"{contact_file} did not record positive friction work")
def check_node_probe(args: argparse.Namespace, step: int) -> None:
if args.probe_node is None:
return
if args.probe_field is None:
raise RuntimeError("--probe-field is required when --probe-node is set")
build_dir = Path(args.build_dir).resolve()
node_file = build_dir / "example_smoke" / args.case_name / f"nodes_{step:08d}.csv"
if not node_file.exists():
raise RuntimeError(f"missing node output: {node_file}")
with node_file.open(newline="", encoding="utf-8") as handle:
rows = list(csv.DictReader(handle))
row = next(
(item for item in rows if int(item["node_id"]) == args.probe_node),
None,
)
if row is None:
raise RuntimeError(f"{node_file} does not contain node {args.probe_node}")
value = float(row[args.probe_field])
if abs(value) < args.min_abs_displacement:
raise RuntimeError(
f"{args.probe_field} at node {args.probe_node} is too small: {value}"
)
if args.sign == "negative" and value >= 0.0:
raise RuntimeError(
f"{args.probe_field} at node {args.probe_node} is not negative: {value}"
)
if args.sign == "positive" and value <= 0.0:
raise RuntimeError(
f"{args.probe_field} at node {args.probe_node} is not positive: {value}"
)
def main() -> int:
args = parse_args()
_, steps = run_case(args)
if args.require_contact:
check_contact_output(Path(args.build_dir).resolve(), args.case_name, steps)
if args.require_friction:
check_friction_output(Path(args.build_dir).resolve(), args.case_name, steps)
check_node_probe(args, steps)
return 0
if __name__ == "__main__":
raise SystemExit(main())