Release FemLite 0.5.2 V5 closeout
FemLite CI / build-test (push) Has been cancelled

This commit is contained in:
shenw
2026-07-01 14:51:40 +08:00
parent 5e90d58d0e
commit 75d4e735b1
82 changed files with 9972 additions and 2613 deletions
+39 -10
View File
@@ -1,10 +1,12 @@
# Two Arches Contact Benchmark
# Two Arches Geometry/Contact Smoke
This folder contains the reference two-arches notes and a FemLite benchmark
input derived from `models.sme.two_arches.pdf`:
- `two_arches_benchmark.inp`
- `check_two_arches_results.py`
- `run_two_arches_reference_point.py`
- `check_two_arches_reference_point.py`
- `run_case.bat`
The model uses the published geometry parameters: upper radius 80 mm, lower
@@ -12,15 +14,25 @@ radius 100 mm, shell width/thickness 3 mm, upper segment 80 degrees, lower
segment 100 degrees, 30 mapped upper shell elements, and 75 mapped lower shell
elements. The two arches are modeled with frictionless shell contact.
The original reference uses a stationary continuation study, a global equation,
and a load parameter to trace the postcritical response. FemLite does not yet
provide that full continuation solver. This benchmark therefore emulates the
first continuation increment by prescribing the upper midpoint displacement
`60 mm * 0.02 = 1.2 mm` over two explicit micro-steps, while preserving the
reference geometry, materials, mesh density, shell contact, lower end fixity,
upper end in-plane constraints, and out-of-plane plane-strain suppression.
The micro-step time scale is numerical only; it avoids dynamic overshoot and
does not represent the stationary postcritical continuation path.
The original COMSOL reference uses a parametric sweep. FemLite V5 does not add
a general parametric-sweep feature, and this example does not try to reproduce
the whole sweep. The default smoke case checks the completed bounded scope:
reference geometry, materials, mesh density, shell contact binding, lower end
fixity, upper end in-plane constraints and out-of-plane plane-strain
suppression.
The current input emulates the first continuation increment by prescribing the
upper midpoint displacement `60 mm * 0.02 = 1.2 mm` over two explicit
micro-steps. The micro-step time scale is numerical only; it avoids dynamic
overshoot and does not represent the stationary postcritical continuation path.
The single reference-point check remains separate from the default smoke run.
The optional `run_two_arches_reference_point.py` driver creates and runs a
displacement reference deck for the setting `para = 0.02`, where
`disp_upper = max_disp * para = 1.2 mm`. It writes
`two_arches_reference_point.csv` with `para`, `disp_upper`, contact activity,
contact force and solve status. This is not a parametric-sweep implementation,
and it does not use a static edge-load solve.
Run:
@@ -32,3 +44,20 @@ Results are written to `results\auto_run`. The checker verifies node and
element counts, key reference coordinates, the prescribed upper midpoint
displacement, active contact output, and a millimeter-scale displacement bound
so accidental dynamic blow-up is caught.
Optional reference-point preparation:
```bat
python run_two_arches_reference_point.py ..\.. ..\..\build-codex-gcc\femlite.exe results\reference_point --prepare-only
```
Optional reference-point run:
```bat
python run_two_arches_reference_point.py ..\.. ..\..\build-codex-gcc\femlite.exe results\reference_point --para 0.02
python check_two_arches_reference_point.py results\reference_point
```
If a run fails before nodal output is written,
`two_arches_reference_point.csv` still records the solver status, accepted
reference mode and case directory.
@@ -0,0 +1,96 @@
from __future__ import annotations
import csv
import math
import sys
from pathlib import Path
MAX_DISP = 6.0e-2
DISP_TOL = 1.0e-10
def require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
def read_rows(path: Path) -> list[dict[str, str]]:
require(path.exists(), f"missing output file: {path}")
with path.open(newline="", encoding="utf-8") as handle:
return list(csv.DictReader(handle))
def check_generated_deck(case_dir: Path) -> None:
deck = case_dir / "two_arches_reference_point.inp"
require(deck.exists(), "reference-point output has no generated input deck")
text = deck.read_text(encoding="ascii")
require("*MATERIAL, NAME=LOWER_MATERIAL" in text and "4.0E10, 0.20" in text,
"generated deck does not preserve the lower arch material")
require("*MATERIAL, NAME=UPPER_MATERIAL" in text and "2.0E10, 0.30" in text,
"generated deck does not preserve the upper arch material")
require("*BOUNDARY, AMPLITUDE=RAMP" in text and "UPPER_MID, 3, 3" in text,
"generated deck does not use upper midpoint displacement control")
require("*DYNAMIC" in text, "displacement reference deck must remain dynamic")
require("*CLOAD" not in text, "displacement reference deck must not use edge loads")
require("*STATIC" not in text, "displacement reference deck must not use static edge-load control")
def check_path(case_dir: Path) -> None:
rows = read_rows(case_dir / "two_arches_reference_point.csv")
require(len(rows) == 1,
"V5 two_arches acceptance expects one reference point, not a sweep")
row = rows[0]
para = float(row["para"])
target = float(row["target_disp_upper"])
disp = float(row["disp_upper"])
residual = float(row["disp_residual"])
active = int(row["active_contact"])
max_penetration = float(row["max_penetration"])
force_norm = float(row["contact_force_norm"])
work_estimate = float(row["contact_work_estimate"])
cumulative_work = float(row["contact_cumulative_work"])
gap_residual = float(row["contact_gap_residual"])
search_active = float(row["contact_search_active"])
max_displacement = float(row["max_displacement"])
status = row["status"].strip()
mode = row["reference_mode"].strip()
require(status == "CONVERGED", f"unconverged reference point: {status}")
require(mode == "displacement", f"unexpected reference mode: {mode}")
require(math.isclose(target, -MAX_DISP * para, rel_tol=0.0, abs_tol=1.0e-12),
f"target displacement is inconsistent with para={para}")
require(abs(disp - target) <= DISP_TOL,
f"disp_upper residual too large: {disp - target:.12e}")
require(abs(residual - (disp - target)) <= 1.0e-12,
"disp_residual column is inconsistent")
require(active > 0, "reference point did not activate shell contact")
require(search_active >= active,
"contact search active count is inconsistent with active contact")
require(0.0 <= max_penetration <= 5.0e-3,
f"contact penetration is out of expected bound: {max_penetration:.12e}")
require(gap_residual >= 0.0 and gap_residual <= 5.0e-3,
f"contact gap residual is out of expected bound: {gap_residual:.12e}")
require(force_norm > 0.0, "reference point has no contact force")
require(work_estimate >= -1.0e-12,
f"contact work estimate is negative: {work_estimate:.12e}")
require(cumulative_work >= -1.0e-12,
f"cumulative contact work is negative: {cumulative_work:.12e}")
require(max_displacement <= 2.0e-3,
f"reference point developed dynamic overshoot: {max_displacement:.12e}")
require(disp < 0.0, "upper midpoint displacement is not downward")
def main(argv: list[str]) -> int:
if len(argv) != 2:
print("usage: check_two_arches_reference_point.py CASE_OUTPUT_DIR")
return 2
case_dir = Path(argv[1])
check_generated_deck(case_dir)
check_path(case_dir)
print("two_arches displacement reference-point checks passed")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
@@ -93,7 +93,7 @@ def main(argv: list[str]) -> int:
case_dir = Path(argv[1])
check_reference_geometry(case_dir)
check_solution(case_dir)
print("two_arches benchmark checks passed")
print("two_arches geometry/contact smoke checks passed")
return 0
@@ -0,0 +1,293 @@
from __future__ import annotations
import argparse
import csv
import math
import re
import shutil
import subprocess
import sys
from pathlib import Path
UPPER_MID_NODES = (183, 184)
MAX_DISP = 6.0e-2
BASE_PARA = 2.0e-2
def require(condition: bool, message: str) -> None:
if not condition:
raise RuntimeError(message)
def read_csv(path: Path) -> list[dict[str, str]]:
require(path.exists(), f"missing output file: {path}")
with path.open(newline="", encoding="utf-8") as handle:
return list(csv.DictReader(handle))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Prepare and optionally run the two-arches single displacement "
"reference point. The reference point is para=0.02, "
"disp_upper=max_disp*para, not a parameter sweep."
)
)
parser.add_argument("repo_root")
parser.add_argument("femlite_exe")
parser.add_argument("output_dir")
parser.add_argument(
"--input",
default="examples/two_arches/two_arches_benchmark.inp",
help="repo-relative source geometry/contact input",
)
parser.add_argument("--para", type=float, default=BASE_PARA)
parser.add_argument("--max-disp", type=float, default=MAX_DISP)
parser.add_argument("--dynamic-steps", type=int, default=2)
parser.add_argument("--output-interval", type=int, default=1)
parser.add_argument("--solve-timeout", type=float, default=60.0)
parser.add_argument(
"--prepare-only",
action="store_true",
help="write the generated displacement reference deck and CSV header only",
)
return parser.parse_args()
def validate_source(text: str) -> None:
require("Ri_upper=80 mm, Ri_lower=100 mm" in text,
"source input does not record the PDF arch radii")
require("Mesh uses 30 mapped elements on the upper arch and 75 on the lower arch" in text,
"source input does not record the PDF mesh counts")
require("*MATERIAL, NAME=LOWER_MATERIAL" in text and "4.0E10, 0.20" in text,
"source input does not record the lower material")
require("*MATERIAL, NAME=UPPER_MATERIAL" in text and "2.0E10, 0.30" in text,
"source input does not record the upper material")
require("*CONTACT PAIR" in text and "UPPER_CONTACT, LOWER_CONTACT" in text,
"source input does not define the upper/lower shell contact pair")
def write_displacement_reference_deck(
source_text: str,
path: Path,
target_disp: float,
dynamic_steps: int,
) -> None:
require(dynamic_steps > 0, "--dynamic-steps must be positive")
text = source_text
text = re.sub(
r"\*BOUNDARY, AMPLITUDE=RAMP\nUPPER_MID,\s*3,\s*3,\s*[-+0-9.Ee]+\n",
f"*BOUNDARY, AMPLITUDE=RAMP\nUPPER_MID, 3, 3, {target_disp:.10E}\n",
text,
count=1,
)
require("*BOUNDARY, AMPLITUDE=RAMP" in text and "UPPER_MID, 3, 3" in text,
"failed to write the upper midpoint displacement reference")
lines = text.splitlines()
for index, line in enumerate(lines):
if line.strip().upper().startswith("*DYNAMIC"):
data_index = index + 1
require(data_index < len(lines), "source input has *DYNAMIC without data")
parts = [item.strip() for item in lines[data_index].split(",")]
require(parts, "source input has an empty *DYNAMIC data line")
dt = float(parts[0])
lines[data_index] = f"{dt:.10E}, {dt * dynamic_steps:.10E}"
path.write_text("\n".join(lines) + "\n", encoding="ascii")
return
raise RuntimeError("source input does not contain *DYNAMIC")
def write_path_header(path: Path) -> None:
with path.open("w", newline="", encoding="utf-8") as handle:
csv.writer(handle).writerow([
"para",
"target_disp_upper",
"disp_upper",
"disp_residual",
"reference_mode",
"status",
"active_contact",
"max_penetration",
"contact_force_norm",
"contact_work_estimate",
"contact_cumulative_work",
"contact_gap_residual",
"contact_search_active",
"max_displacement",
"history_step",
"history_time",
"case_dir",
])
def last_numbered_csv(case_dir: Path, prefix: str) -> Path | None:
candidates = sorted(case_dir.glob(f"{prefix}_*.csv"))
return candidates[-1] if candidates else None
def average_upper_mid_uz(case_dir: Path) -> float:
node_file = last_numbered_csv(case_dir, "nodes")
require(node_file is not None, f"{case_dir} has no nodal output")
rows = read_csv(node_file)
values = [
float(row["uz"])
for row in rows
if int(row["node_id"]) in UPPER_MID_NODES
]
require(len(values) == len(UPPER_MID_NODES),
f"{node_file} does not contain the upper midpoint node pair")
return sum(values) / len(values)
def contact_summary(case_dir: Path) -> tuple[int, float, float, float, float, float, float]:
contact_file = last_numbered_csv(case_dir, "contact")
require(contact_file is not None, f"{case_dir} has no contact output")
rows = read_csv(contact_file)
summary = next((row for row in rows if row.get("kind") == "SUMMARY"), None)
require(summary is not None, f"{contact_file} does not contain a SUMMARY row")
return (
int(summary["active_count"]),
float(summary.get("max_penetration", "0.0")),
float(summary.get("force_norm", "0.0")),
float(summary.get("work_estimate", "0.0")),
float(summary.get("cumulative_work", "0.0")),
float(summary.get("gap_residual", "0.0")),
float(summary.get("search_active", "0.0")),
)
def final_history(case_dir: Path) -> tuple[int, float, float]:
rows = read_csv(case_dir / "history.csv")
require(rows, "history.csv is empty")
row = rows[-1]
return (
int(row.get("step", "0")),
float(row.get("time", "nan")),
float(row.get("max_displacement", "nan")),
)
def append_result_row(path: Path, row: list[object]) -> None:
with path.open("a", newline="", encoding="utf-8") as handle:
csv.writer(handle).writerow(row)
def run_reference_case(
repo: Path,
femlite: Path,
inp: Path,
case_dir: Path,
args: argparse.Namespace,
) -> str:
if case_dir.exists():
shutil.rmtree(case_dir)
case_dir.mkdir(parents=True, exist_ok=True)
command = [
str(femlite),
str(inp),
"--run",
"--output-dir",
str(case_dir),
"--output-interval",
str(args.output_interval),
]
try:
completed = subprocess.run(
command,
cwd=repo,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=args.solve_timeout,
)
except subprocess.TimeoutExpired as exc:
stdout = exc.stdout or ""
(case_dir / "femlite_stdout.txt").write_text(stdout, encoding="utf-8")
return "TIMEOUT"
(case_dir / "femlite_stdout.txt").write_text(completed.stdout, encoding="utf-8")
return "CONVERGED" if completed.returncode == 0 else f"FAILED_{completed.returncode}"
def main() -> int:
args = parse_args()
repo = Path(args.repo_root).resolve()
femlite = Path(args.femlite_exe).resolve()
out_dir = Path(args.output_dir).resolve()
source = repo / args.input
require(source.exists(), f"missing source input: {source}")
require(args.para > 0.0, "--para must be positive")
require(args.dynamic_steps > 0, "--dynamic-steps must be positive")
validate_source(source.read_text(encoding="utf-8"))
target = -args.max_disp * args.para
source_text = source.read_text(encoding="utf-8")
out_dir.mkdir(parents=True, exist_ok=True)
csv_path = out_dir / "two_arches_reference_point.csv"
write_path_header(csv_path)
deck = out_dir / "two_arches_reference_point.inp"
write_displacement_reference_deck(source_text, deck, target, args.dynamic_steps)
if args.prepare_only:
print(f"prepared {deck}")
print(f"prepared {csv_path}")
return 0
require(femlite.exists(), f"missing femlite executable: {femlite}")
case_dir = out_dir / "case"
status = run_reference_case(repo, femlite, deck, case_dir, args)
disp = math.nan
residual = math.nan
active = 0
max_penetration = 0.0
force_norm = 0.0
work_estimate = 0.0
cumulative_work = 0.0
gap_residual = 0.0
search_active = 0.0
step = 0
time = math.nan
max_displacement = math.nan
if status == "CONVERGED":
disp = average_upper_mid_uz(case_dir)
residual = disp - target
(
active,
max_penetration,
force_norm,
work_estimate,
cumulative_work,
gap_residual,
search_active,
) = contact_summary(case_dir)
step, time, max_displacement = final_history(case_dir)
append_result_row(csv_path, [
f"{args.para:.12e}",
f"{target:.12e}",
f"{disp:.12e}",
f"{residual:.12e}",
"displacement",
status,
active,
f"{max_penetration:.12e}",
f"{force_norm:.12e}",
f"{work_estimate:.12e}",
f"{cumulative_work:.12e}",
f"{gap_residual:.12e}",
f"{search_active:.12e}",
f"{max_displacement:.12e}",
step,
f"{time:.12e}",
case_dir.name,
])
if status != "CONVERGED":
raise RuntimeError(f"two-arches reference point did not converge: {status}")
print(f"two-arches reference point wrote {csv_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())