294 lines
9.7 KiB
Python
294 lines
9.7 KiB
Python
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())
|