Files
CCLite/Python/checkers/common_csv.py
T
2026-07-06 09:12:22 +08:00

125 lines
3.1 KiB
Python

from __future__ import annotations
import csv
import json
from pathlib import Path
IPC_HEADERS = [
"step_id",
"solver_id",
"command_id",
"command_seq",
"ack_seq",
"worker_state",
"heartbeat_seq",
"elapsed_ms",
"error_code",
]
CONTACT_HEADERS = [
"step_id",
"pair_id",
"sph_id",
"facet_id",
"gap",
"penetration",
"normal_x",
"normal_y",
"normal_z",
"force_x",
"force_y",
"force_z",
"node_count",
]
CANDIDATE_HEADERS = [
"step_id",
"particle_index",
"facet_index",
"sph_id",
"facet_id",
]
FORCE_BALANCE_HEADERS = [
"step_id",
"sph_fx",
"sph_fy",
"sph_fz",
"fem_fx",
"fem_fy",
"fem_fz",
"total_fx",
"total_fy",
"total_fz",
"num_contacts",
"max_penetration",
"total_contact_force_norm",
"force_balance_error",
"moment_balance_error",
"nonfinite_contact_count",
"skipped_separated_count",
"skipped_degenerate_count",
"skipped_invalid_count",
]
def read_required_csv(path: Path, required_headers: list[str]) -> tuple[list[str], list[dict[str, str]]]:
if not path.exists():
raise AssertionError(f"missing CSV file: {path}")
with path.open("r", encoding="utf-8", newline="") as stream:
reader = csv.DictReader(stream)
headers = list(reader.fieldnames or [])
missing = [name for name in required_headers if name not in headers]
if missing:
raise AssertionError(f"{path.name} missing headers: {', '.join(missing)}")
rows = list(reader)
return headers, rows
def read_ipc_report(output_dir: Path) -> tuple[list[str], list[dict[str, str]]]:
return read_required_csv(output_dir / "ipc_report.csv", IPC_HEADERS)
def read_contact_report(output_dir: Path) -> tuple[list[str], list[dict[str, str]]]:
return read_required_csv(output_dir / "contact_report.csv", CONTACT_HEADERS)
def read_candidate_report(output_dir: Path) -> tuple[list[str], list[dict[str, str]]]:
return read_required_csv(output_dir / "candidate_report.csv", CANDIDATE_HEADERS)
def read_force_balance(output_dir: Path) -> tuple[list[str], list[dict[str, str]]]:
return read_required_csv(output_dir / "force_balance.csv", FORCE_BALANCE_HEADERS)
def as_int(row: dict[str, str], key: str) -> int:
try:
return int(row[key])
except Exception as exc:
raise AssertionError(f"invalid integer in {key}: {row.get(key)!r}") from exc
def as_float(row: dict[str, str], key: str) -> float:
try:
return float(row[key])
except Exception as exc:
raise AssertionError(f"invalid float in {key}: {row.get(key)!r}") from exc
def add_failure(
failed: list[str],
location: str,
field: str,
expected: object,
actual: object,
) -> None:
failed.append(f"{location}: field={field}, expected={expected}, actual={actual}")
def write_verification_report(report_path: Path, report: dict) -> None:
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")