diff --git a/.gitignore b/.gitignore index fe9160e..6d5bc76 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ __pycache__/ .venv/ *.pyc *.csv +!tests/verification/*.csv *.vtk *.vtu *.vtp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a4edfc..929245e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -173,6 +173,18 @@ add_test(NAME V020_contact_controller_run COMMAND cclite run ${CMAKE_SOURCE_DIR}/tests/data/v020_contact_run.inp ) +add_test(NAME V020_single_particle_wall_run + COMMAND cclite run ${CMAKE_SOURCE_DIR}/tests/data/v020_single_particle_wall.inp +) + +add_test(NAME V020_multi_particle_plane_run + COMMAND cclite run ${CMAKE_SOURCE_DIR}/tests/data/v020_multi_particle_plane.inp +) + +add_test(NAME V020_force_balance_run + COMMAND cclite run ${CMAKE_SOURCE_DIR}/tests/data/v020_force_balance.inp +) + if(Python3_Interpreter_FOUND) add_test(NAME verify_v010_empty_coupling COMMAND ${Python3_EXECUTABLE} @@ -208,6 +220,78 @@ if(Python3_Interpreter_FOUND) ) set_tests_properties(verify_v020_contact_controller PROPERTIES DEPENDS V020_contact_controller_run) + add_test(NAME verify_v020_geometry_primitives + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/Python/checkers/check_v020_geometry_primitives.py + --case-id V020_GEOMETRY_PRIMITIVES + --input ${CMAKE_SOURCE_DIR}/tests/verification/v020_geometry_primitives.csv + --report ${CMAKE_BINARY_DIR}/output/v020_geometry_primitives/verification_report.json + ) + + add_test(NAME verify_v020_single_particle_wall + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/Python/checkers/check_v020_contact.py + --case-id V020_SINGLE_PARTICLE_WALL + --input ${CMAKE_SOURCE_DIR}/tests/data/v020_single_particle_wall.inp + --output-dir ${CMAKE_BINARY_DIR}/output/v020_single_particle_wall + --report ${CMAKE_BINARY_DIR}/output/v020_single_particle_wall/verification_report.json + --expected-steps 1 + --expected-contacts-per-step 1 + --expected-candidates-per-step 1 + --expected-max-penetration 1.0e-1 + --expected-total-force-norm 1.0e5 + --expected-force-z-per-contact 1.0e5 + ) + set_tests_properties(verify_v020_single_particle_wall PROPERTIES DEPENDS V020_single_particle_wall_run) + + add_test(NAME verify_v020_multi_particle_plane + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/Python/checkers/check_v020_contact.py + --case-id V020_MULTI_PARTICLE_PLANE + --input ${CMAKE_SOURCE_DIR}/tests/data/v020_multi_particle_plane.inp + --output-dir ${CMAKE_BINARY_DIR}/output/v020_multi_particle_plane + --report ${CMAKE_BINARY_DIR}/output/v020_multi_particle_plane/verification_report.json + --expected-steps 1 + --expected-contacts-per-step 3 + --expected-candidates-per-step 3 + --expected-max-penetration 1.0e-1 + --expected-total-force-norm 3.0e5 + --expected-force-z-per-contact 1.0e5 + ) + set_tests_properties(verify_v020_multi_particle_plane PROPERTIES DEPENDS V020_multi_particle_plane_run) + + add_test(NAME verify_v020_force_balance + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/Python/checkers/check_v020_contact.py + --case-id V020_FORCE_BALANCE + --input ${CMAKE_SOURCE_DIR}/tests/data/v020_force_balance.inp + --output-dir ${CMAKE_BINARY_DIR}/output/v020_force_balance + --report ${CMAKE_BINARY_DIR}/output/v020_force_balance/verification_report.json + --expected-steps 1 + --expected-contacts-per-step 3 + --expected-candidates-per-step 3 + --expected-max-penetration 1.0e-1 + --expected-total-force-norm 3.0e5 + --expected-force-z-per-contact 1.0e5 + ) + set_tests_properties(verify_v020_force_balance PROPERTIES DEPENDS V020_force_balance_run) + + add_test(NAME V020_csv_header_regression + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/Python/checkers/check_v020_contact.py + --case-id V020_CSV_HEADERS + --input ${CMAKE_SOURCE_DIR}/tests/data/v020_single_particle_wall.inp + --output-dir ${CMAKE_BINARY_DIR}/output/v020_single_particle_wall + --report ${CMAKE_BINARY_DIR}/output/v020_single_particle_wall/verification_report_headers.json + --expected-steps 1 + --expected-contacts-per-step 1 + --expected-candidates-per-step 1 + --expected-max-penetration 1.0e-1 + --expected-total-force-norm 1.0e5 + --headers-only + ) + set_tests_properties(V020_csv_header_regression PROPERTIES DEPENDS V020_single_particle_wall_run) + add_test(NAME utf8_no_bom_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/Python/checkers/check_utf8_no_bom.py diff --git a/Python/checkers/check_v020_contact.py b/Python/checkers/check_v020_contact.py new file mode 100644 index 0000000..359887e --- /dev/null +++ b/Python/checkers/check_v020_contact.py @@ -0,0 +1,281 @@ +from __future__ import annotations + +import argparse +import math +from collections import Counter +from pathlib import Path + +from common_csv import ( + add_failure, + as_float, + as_int, + read_candidate_report, + read_contact_report, + read_force_balance, + read_ipc_report, + write_verification_report, +) + + +def build_report(args: argparse.Namespace) -> dict: + output_dir = Path(args.output_dir) + input_path = Path(args.input) + failed: list[str] = [] + metrics: dict[str, int | float] = {} + log_path = output_dir / "run.log" + + try: + _, ipc_rows = read_ipc_report(output_dir) + _, contact_rows = read_contact_report(output_dir) + _, candidate_rows = read_candidate_report(output_dir) + _, force_rows = read_force_balance(output_dir) + except AssertionError as exc: + ipc_rows = [] + contact_rows = [] + candidate_rows = [] + force_rows = [] + failed.append(str(exc)) + + if not log_path.exists(): + failed.append(f"missing log file: {log_path}") + elif not args.headers_only and "contact_broad_phase" not in log_path.read_text(encoding="utf-8"): + failed.append("run.log missing contact_broad_phase diagnostics") + + if args.headers_only: + return make_report(args, failed, input_path, output_dir, log_path, metrics) + + expected_steps = set(range(1, args.expected_steps + 1)) + validate_ipc(ipc_rows, args, failed, metrics) + validate_candidates(candidate_rows, args, expected_steps, failed, metrics) + validate_contacts(contact_rows, args, expected_steps, failed, metrics) + validate_force_balance(force_rows, args, expected_steps, failed, metrics) + return make_report(args, failed, input_path, output_dir, log_path, metrics) + + +def validate_ipc(rows: list[dict[str, str]], args: argparse.Namespace, failed: list[str], metrics: dict) -> None: + import_load_rows = 0 + advance_rows = 0 + stop_rows = 0 + for index, row in enumerate(rows, start=1): + location = f"ipc_report.csv row {index}" + try: + command_seq = as_int(row, "command_seq") + ack_seq = as_int(row, "ack_seq") + command_id = as_int(row, "command_id") + error_code = as_int(row, "error_code") + except AssertionError as exc: + failed.append(f"{location}: {exc}") + continue + if command_seq != ack_seq: + add_failure(failed, location, "seq/ack", command_seq, ack_seq) + if error_code != 0: + add_failure(failed, location, "error_code", 0, error_code) + if command_id == 5: + import_load_rows += 1 + if command_id == 6: + advance_rows += 1 + if command_id == 99: + stop_rows += 1 + + expected_worker_step_rows = args.expected_steps * 2 + if import_load_rows != expected_worker_step_rows: + add_failure(failed, "ipc_report.csv", "IMPORT_LOADS rows", expected_worker_step_rows, import_load_rows) + if advance_rows != expected_worker_step_rows: + add_failure(failed, "ipc_report.csv", "ADVANCE rows", expected_worker_step_rows, advance_rows) + if stop_rows != 2: + add_failure(failed, "ipc_report.csv", "STOP rows", 2, stop_rows) + metrics["ipc_rows"] = len(rows) + metrics["import_load_rows"] = import_load_rows + metrics["advance_rows"] = advance_rows + + +def validate_candidates( + rows: list[dict[str, str]], + args: argparse.Namespace, + expected_steps: set[int], + failed: list[str], + metrics: dict, +) -> None: + expected_total = args.expected_steps * args.expected_candidates_per_step + if len(rows) != expected_total: + add_failure(failed, "candidate_report.csv", "row_count", expected_total, len(rows)) + + counts: Counter[int] = Counter() + seen: set[tuple[int, int, int]] = set() + for index, row in enumerate(rows, start=1): + location = f"candidate_report.csv row {index}" + try: + step_id = as_int(row, "step_id") + sph_id = as_int(row, "sph_id") + facet_id = as_int(row, "facet_id") + except AssertionError as exc: + failed.append(f"{location}: {exc}") + continue + counts[step_id] += 1 + key = (step_id, sph_id, facet_id) + if key in seen: + add_failure(failed, location, "duplicate_candidate", "unique step/sph/facet", key) + seen.add(key) + + for step_id in expected_steps: + actual = counts.get(step_id, 0) + if actual != args.expected_candidates_per_step: + add_failure(failed, f"candidate_report.csv step {step_id}", "candidate_count", + args.expected_candidates_per_step, actual) + metrics["candidate_rows"] = len(rows) + + +def validate_contacts( + rows: list[dict[str, str]], + args: argparse.Namespace, + expected_steps: set[int], + failed: list[str], + metrics: dict, +) -> None: + expected_total = args.expected_steps * args.expected_contacts_per_step + if len(rows) != expected_total: + add_failure(failed, "contact_report.csv", "row_count", expected_total, len(rows)) + + counts: Counter[int] = Counter() + max_penetration = 0.0 + force_z_per_contact = args.expected_force_z_per_contact + if force_z_per_contact is None and args.expected_contacts_per_step > 0: + force_z_per_contact = args.expected_total_force_norm / args.expected_contacts_per_step + + for index, row in enumerate(rows, start=1): + location = f"contact_report.csv row {index}" + try: + step_id = as_int(row, "step_id") + penetration = as_float(row, "penetration") + normal_z = as_float(row, "normal_z") + force_z = as_float(row, "force_z") + node_count = as_int(row, "node_count") + except AssertionError as exc: + failed.append(f"{location}: {exc}") + continue + counts[step_id] += 1 + max_penetration = max(max_penetration, penetration) + expect_close(failed, location, "penetration", args.expected_max_penetration, penetration, args.tolerance) + expect_close(failed, location, "normal_z", args.expected_normal_z, normal_z, args.tolerance) + if force_z_per_contact is not None: + expect_close(failed, location, "force_z", force_z_per_contact, force_z, args.force_tolerance) + if node_count != args.expected_node_count: + add_failure(failed, location, "node_count", args.expected_node_count, node_count) + + for step_id in expected_steps: + actual = counts.get(step_id, 0) + if actual != args.expected_contacts_per_step: + add_failure(failed, f"contact_report.csv step {step_id}", "contact_count", + args.expected_contacts_per_step, actual) + metrics["contact_rows"] = len(rows) + metrics["max_contact_penetration"] = max_penetration + + +def validate_force_balance( + rows: list[dict[str, str]], + args: argparse.Namespace, + expected_steps: set[int], + failed: list[str], + metrics: dict, +) -> None: + seen_steps: set[int] = set() + for index, row in enumerate(rows, start=1): + location = f"force_balance.csv row {index}" + try: + step_id = as_int(row, "step_id") + num_contacts = as_int(row, "num_contacts") + max_penetration = as_float(row, "max_penetration") + total_force_norm = as_float(row, "total_contact_force_norm") + force_balance_error = as_float(row, "force_balance_error") + moment_balance_error = as_float(row, "moment_balance_error") + nonfinite_count = as_int(row, "nonfinite_contact_count") + total_force = [as_float(row, key) for key in ("total_fx", "total_fy", "total_fz")] + except AssertionError as exc: + failed.append(f"{location}: {exc}") + continue + seen_steps.add(step_id) + if num_contacts != args.expected_contacts_per_step: + add_failure(failed, location, "num_contacts", args.expected_contacts_per_step, num_contacts) + expect_close(failed, location, "max_penetration", args.expected_max_penetration, + max_penetration, args.tolerance) + expect_close(failed, location, "total_contact_force_norm", args.expected_total_force_norm, + total_force_norm, args.force_tolerance) + if force_balance_error > args.tolerance: + add_failure(failed, location, "force_balance_error", f"<={args.tolerance}", force_balance_error) + if moment_balance_error > args.tolerance: + add_failure(failed, location, "moment_balance_error", f"<={args.tolerance}", moment_balance_error) + if nonfinite_count != 0: + add_failure(failed, location, "nonfinite_contact_count", 0, nonfinite_count) + for axis, value in zip(("total_fx", "total_fy", "total_fz"), total_force): + if abs(value) > args.tolerance: + add_failure(failed, location, axis, f"abs <= {args.tolerance}", value) + + if seen_steps != expected_steps: + add_failure(failed, "force_balance.csv", "steps", sorted(expected_steps), sorted(seen_steps)) + metrics["force_rows"] = len(rows) + + +def expect_close( + failed: list[str], + location: str, + field: str, + expected: float, + actual: float, + tolerance: float, +) -> None: + if not math.isfinite(actual) or abs(actual - expected) > tolerance: + add_failure(failed, location, field, f"{expected} +/- {tolerance}", actual) + + +def make_report( + args: argparse.Namespace, + failed: list[str], + input_path: Path, + output_dir: Path, + log_path: Path, + metrics: dict, +) -> dict: + return { + "case_id": args.case_id, + "status": "PASS" if not failed else "FAIL", + "metrics": metrics, + "failed_checks": failed, + "input": str(input_path), + "output_files": { + "run_log": str(log_path), + "ipc_report": str(output_dir / "ipc_report.csv"), + "contact_report": str(output_dir / "contact_report.csv"), + "candidate_report": str(output_dir / "candidate_report.csv"), + "force_balance": str(output_dir / "force_balance.csv"), + }, + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--case-id", required=True) + parser.add_argument("--input", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--report", required=True) + parser.add_argument("--expected-steps", type=int, default=1) + parser.add_argument("--expected-contacts-per-step", type=int, required=True) + parser.add_argument("--expected-candidates-per-step", type=int, required=True) + parser.add_argument("--expected-max-penetration", type=float, required=True) + parser.add_argument("--expected-total-force-norm", type=float, required=True) + parser.add_argument("--expected-force-z-per-contact", type=float) + parser.add_argument("--expected-normal-z", type=float, default=1.0) + parser.add_argument("--expected-node-count", type=int, default=4) + parser.add_argument("--tolerance", type=float, default=1.0e-7) + parser.add_argument("--force-tolerance", type=float, default=1.0e-5) + parser.add_argument("--headers-only", action="store_true") + args = parser.parse_args() + + report = build_report(args) + report_path = Path(args.report) + write_verification_report(report_path, report) + print(f"{report['case_id']} {report['status']} -> {report_path}") + return 0 if report["status"] == "PASS" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Python/checkers/check_v020_geometry_primitives.py b/Python/checkers/check_v020_geometry_primitives.py new file mode 100644 index 0000000..e6542c2 --- /dev/null +++ b/Python/checkers/check_v020_geometry_primitives.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import argparse +import math +from pathlib import Path + +from common_csv import add_failure, as_float, as_int, read_required_csv, write_verification_report + + +GEOMETRY_HEADERS = [ + "metric", + "expected", + "actual", + "tolerance", + "degenerate_count", + "nonfinite_count", +] + + +def build_report(args: argparse.Namespace) -> dict: + input_path = Path(args.input) + failed: list[str] = [] + metrics: dict[str, int | float] = {} + + try: + _, rows = read_required_csv(input_path, GEOMETRY_HEADERS) + except AssertionError as exc: + rows = [] + failed.append(str(exc)) + + degenerate_total = 0 + nonfinite_total = 0 + checked_rows = 0 + for index, row in enumerate(rows, start=1): + location = f"{input_path.name} row {index}" + metric = row.get("metric", "") + try: + expected = as_float(row, "expected") + actual = as_float(row, "actual") + tolerance = as_float(row, "tolerance") + degenerate_count = as_int(row, "degenerate_count") + nonfinite_count = as_int(row, "nonfinite_count") + except AssertionError as exc: + failed.append(f"{location}: {exc}") + continue + + checked_rows += 1 + degenerate_total += degenerate_count + nonfinite_total += nonfinite_count + if not math.isfinite(actual): + add_failure(failed, location, metric, "finite value", actual) + if abs(actual - expected) > tolerance: + add_failure(failed, location, metric, f"{expected} +/- {tolerance}", actual) + if nonfinite_count != 0: + add_failure(failed, location, "nonfinite_count", 0, nonfinite_count) + + if checked_rows == 0: + failed.append("geometry primitive report has no data rows") + if degenerate_total < args.min_degenerate_count: + add_failure(failed, input_path.name, "degenerate_count", f">={args.min_degenerate_count}", degenerate_total) + if nonfinite_total != 0: + add_failure(failed, input_path.name, "nonfinite_total", 0, nonfinite_total) + + metrics["checked_rows"] = checked_rows + metrics["degenerate_count"] = degenerate_total + metrics["nonfinite_count"] = nonfinite_total + return { + "case_id": args.case_id, + "status": "PASS" if not failed else "FAIL", + "metrics": metrics, + "failed_checks": failed, + "input": str(input_path), + "output_files": { + "geometry_report": str(input_path), + }, + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--case-id", required=True) + parser.add_argument("--input", required=True) + parser.add_argument("--report", required=True) + parser.add_argument("--min-degenerate-count", type=int, default=2) + args = parser.parse_args() + + report = build_report(args) + report_path = Path(args.report) + write_verification_report(report_path, report) + print(f"{report['case_id']} {report['status']} -> {report_path}") + return 0 if report["status"] == "PASS" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Python/checkers/common_csv.py b/Python/checkers/common_csv.py index 482e4e1..65cbd92 100644 --- a/Python/checkers/common_csv.py +++ b/Python/checkers/common_csv.py @@ -1,9 +1,69 @@ 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}") @@ -19,6 +79,22 @@ def read_required_csv(path: Path, required_headers: list[str]) -> tuple[list[str 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]) @@ -31,3 +107,18 @@ def as_float(row: dict[str, str], key: str) -> float: 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") diff --git a/cases/v0_2_contact/README.md b/cases/v0_2_contact/README.md index 3f7e2f9..0a18e2e 100644 --- a/cases/v0_2_contact/README.md +++ b/cases/v0_2_contact/README.md @@ -2,7 +2,7 @@ CCLite 0.2.x 接触算法验收算例目录。 -本目录用于收纳 0.2.x 基础 SPH 粒子-FEM facet penalty contact 的输入文件、mock worker 配置和预期输出说明。0.2.0 只建立目录骨架,真实算例在后续小版本逐步补齐。 +本目录用于收纳 0.2.x 基础 SPH 粒子-FEM facet penalty contact 的输入文件、mock worker 配置和预期输出说明。 命名约定: @@ -14,8 +14,11 @@ CCLite 0.2.x 接触算法验收算例目录。 计划算例: -1. `V020_GEOMETRY_PRIMITIVES`:几何 primitive 验收; -2. `V020_SINGLE_PARTICLE_WALL`:单粒子撞 FEM 平面; -3. `V020_MULTI_PARTICLE_PLANE`:多粒子压 FEM 平面; -4. `V020_FORCE_BALANCE`:合力和力矩平衡; +1. `V020_GEOMETRY_PRIMITIVES`:几何 primitive 验收,输入为 `tests/verification/v020_geometry_primitives.csv`; +2. `V020_SINGLE_PARTICLE_WALL`:单粒子撞 FEM 平面,输入为 `tests/data/v020_single_particle_wall.inp`; +3. `V020_MULTI_PARTICLE_PLANE`:多粒子压 FEM 平面,输入为 `tests/data/v020_multi_particle_plane.inp`; +4. `V020_FORCE_BALANCE`:合力和力矩平衡,输入为 `tests/data/v020_force_balance.inp`; 5. `V020_SINGLE_REAL_WORKER_SMOKE`:单真实 worker gate。 + +0.2.8 起,以上基础 mock 算例已接入 CTest,并由 `Python/checkers/check_v020_geometry_primitives.py` 与 +`Python/checkers/check_v020_contact.py` 生成 `verification_report.json`。 diff --git a/src/controller/ccl_controller.f90 b/src/controller/ccl_controller.f90 index 7b9ae20..dfbf15b 100644 --- a/src/controller/ccl_controller.f90 +++ b/src/controller/ccl_controller.f90 @@ -20,8 +20,8 @@ module ccl_controller ccl_data_header_set_count, ccl_data_header_set_state, ccl_data_header_size, & ccl_data_header_validate, ccl_data_record_size_for_role use ccl_diagnostics, only: CCL_Diagnostics_Type, ccl_diagnostics_close, & - ccl_diagnostics_open, ccl_diagnostics_write_contact, ccl_diagnostics_write_force_balance, & - ccl_diagnostics_write_ipc, ccl_diagnostics_write_run + ccl_diagnostics_open, ccl_diagnostics_write_candidate, ccl_diagnostics_write_contact, & + ccl_diagnostics_write_force_balance, ccl_diagnostics_write_ipc, ccl_diagnostics_write_run use ccl_errors, only: CCL_ERROR_INPUT_INVALID_VALUE, CCL_ERROR_IPC_TIMEOUT, & CCL_ERROR_SYSTEM_INTERNAL, CCL_ERROR_WORKER_START_FAILED, CCL_ERROR_WORKER_STOP_FAILED, & CCL_SUCCESS @@ -412,6 +412,8 @@ contains call run_broad_phase_search(particles, particle_count, facets, facet_count, candidates, & candidate_count, broad_stats, ierr) if (ierr /= CCL_SUCCESS) return + call write_candidate_report(diag, step_id, particles, particle_count, facets, facet_count, & + candidates, candidate_count) call ccl_narrow_phase_stats_reset(total_narrow_stats) call ccl_contact_force_stats_reset(total_force_stats) @@ -559,6 +561,30 @@ contains end do end subroutine run_broad_phase_search + subroutine write_candidate_report(diag, step_id, particles, particle_count, facets, facet_count, & + candidates, candidate_count) + type(CCL_Diagnostics_Type), intent(inout) :: diag + integer, intent(in) :: step_id + type(CCL_SPH_Particle_View_Type), intent(in) :: particles(:) + integer, intent(in) :: particle_count + type(CCL_FEM_Facet_View_Type), intent(in) :: facets(:) + integer, intent(in) :: facet_count + type(CCL_Candidate_Pair_Type), intent(in) :: candidates(:) + integer, intent(in) :: candidate_count + integer :: i + integer :: particle_index + integer :: facet_index + + do i = 1, candidate_count + particle_index = candidates(i)%particle_index + facet_index = candidates(i)%facet_index + if (particle_index < 1 .or. particle_index > particle_count) cycle + if (facet_index < 1 .or. facet_index > facet_count) cycle + call ccl_diagnostics_write_candidate(diag, step_id, particle_index, facet_index, & + particles(particle_index)%external_id, facets(facet_index)%facet_id) + end do + end subroutine write_candidate_report + real(c_double) function choose_contact_cell_size(particles, particle_count) result(cell_size) type(CCL_SPH_Particle_View_Type), intent(in) :: particles(:) integer, intent(in) :: particle_count diff --git a/src/diagnostics/ccl_diagnostics.f90 b/src/diagnostics/ccl_diagnostics.f90 index 8a65f22..b8e61db 100644 --- a/src/diagnostics/ccl_diagnostics.f90 +++ b/src/diagnostics/ccl_diagnostics.f90 @@ -12,6 +12,7 @@ module ccl_diagnostics integer :: ipc_unit = -1 integer :: force_unit = -1 integer :: contact_unit = -1 + integer :: candidate_unit = -1 logical :: is_open = .false. end type CCL_Diagnostics_Type @@ -58,6 +59,13 @@ contains return end if + open(newunit=diag%candidate_unit, file=join_path(diag%output_dir, "candidate_report.csv"), & + status="replace", action="write", encoding="UTF-8", iostat=ios) + if (ios /= 0) then + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end if + diag%is_open = .true. write(diag%ipc_unit, '(a)') "step_id,solver_id,command_id,command_seq,ack_seq,worker_state," // & "heartbeat_seq,elapsed_ms,error_code" @@ -66,6 +74,7 @@ contains "nonfinite_contact_count,skipped_separated_count,skipped_degenerate_count,skipped_invalid_count" write(diag%contact_unit, '(a)') "step_id,pair_id,sph_id,facet_id,gap,penetration,normal_x,normal_y," // & "normal_z,force_x,force_y,force_z,node_count" + write(diag%candidate_unit, '(a)') "step_id,particle_index,facet_index,sph_id,facet_id" call ccl_diagnostics_write_run(diag, "INFO", "run", "version=" // CCL_VERSION_LABEL) call ccl_diagnostics_write_run(diag, "INFO", "run", "case_id=" // trim(case_id)) call ccl_diagnostics_write_run(diag, "INFO", "run", "input=" // trim(input_file)) @@ -176,6 +185,20 @@ contains flush(diag%contact_unit) end subroutine ccl_diagnostics_write_contact + subroutine ccl_diagnostics_write_candidate(diag, step_id, particle_index, facet_index, sph_id, facet_id) + type(CCL_Diagnostics_Type), intent(inout) :: diag + integer, intent(in) :: step_id + integer, intent(in) :: particle_index + integer, intent(in) :: facet_index + integer(8), intent(in) :: sph_id + integer(8), intent(in) :: facet_id + + if (.not. diag%is_open .or. diag%candidate_unit == -1) return + write(diag%candidate_unit, '(i0,",",i0,",",i0,",",i0,",",i0)') & + step_id, particle_index, facet_index, sph_id, facet_id + flush(diag%candidate_unit) + end subroutine ccl_diagnostics_write_candidate + subroutine ccl_diagnostics_close(diag) type(CCL_Diagnostics_Type), intent(inout) :: diag @@ -183,10 +206,12 @@ contains if (diag%ipc_unit /= -1) close(diag%ipc_unit) if (diag%force_unit /= -1) close(diag%force_unit) if (diag%contact_unit /= -1) close(diag%contact_unit) + if (diag%candidate_unit /= -1) close(diag%candidate_unit) diag%log_unit = -1 diag%ipc_unit = -1 diag%force_unit = -1 diag%contact_unit = -1 + diag%candidate_unit = -1 diag%is_open = .false. end subroutine ccl_diagnostics_close diff --git a/src/mock_workers/ccl_mock_worker.f90 b/src/mock_workers/ccl_mock_worker.f90 index ebe9525..ecc150f 100644 --- a/src/mock_workers/ccl_mock_worker.f90 +++ b/src/mock_workers/ccl_mock_worker.f90 @@ -389,20 +389,38 @@ contains ierr = CCL_ERROR_IPC_BAD_HEADER return end if - call clear_sph_particle_record(runtime%sph_particles(1)) - runtime%sph_particles(1)%external_id = 101_c_int64_t - runtime%sph_particles(1)%internal_index = 1_c_int32_t - runtime%sph_particles(1)%status = 1_c_int32_t - runtime%sph_particles(1)%valid_flags = 1_c_int32_t - runtime%sph_particles(1)%mass = 1.0_c_double - runtime%sph_particles(1)%volume = 1.0_c_double - runtime%sph_particles(1)%density = 1.0_c_double - runtime%sph_particles(1)%contact_radius = 0.2_c_double - runtime%sph_particles(1)%x = [0.25_c_double, 0.25_c_double, 0.10_c_double] - runtime%sph_particles(1)%v = [0.0_c_double, 0.0_c_double, -1.0_c_double] - item_count = 1_c_int32_t + call set_sph_contact_particle(runtime%sph_particles(1), 101_c_int64_t, 1_c_int32_t, & + [0.25_c_double, 0.25_c_double, 0.10_c_double]) + if (is_multi_fixture(runtime%input_file)) then + call set_sph_contact_particle(runtime%sph_particles(2), 102_c_int64_t, 2_c_int32_t, & + [0.75_c_double, 0.25_c_double, 0.10_c_double]) + call set_sph_contact_particle(runtime%sph_particles(3), 103_c_int64_t, 3_c_int32_t, & + [0.25_c_double, 0.75_c_double, 0.10_c_double]) + item_count = 3_c_int32_t + else + item_count = 1_c_int32_t + end if end subroutine write_sph_contact_fixture + subroutine set_sph_contact_particle(record, external_id, internal_index, x) + type(CCL_SPH_Particle_Record_Type), intent(out) :: record + integer(c_int64_t), intent(in) :: external_id + integer(c_int32_t), intent(in) :: internal_index + real(c_double), intent(in) :: x(3) + + call clear_sph_particle_record(record) + record%external_id = external_id + record%internal_index = internal_index + record%status = 1_c_int32_t + record%valid_flags = 1_c_int32_t + record%mass = 1.0_c_double + record%volume = 1.0_c_double + record%density = 1.0_c_double + record%contact_radius = 0.2_c_double + record%x = x + record%v = [0.0_c_double, 0.0_c_double, -1.0_c_double] + end subroutine set_sph_contact_particle + subroutine write_fem_contact_fixture(runtime, item_count, ierr) type(CCL_Mock_Worker_Runtime), intent(inout) :: runtime integer(c_int32_t), intent(out) :: item_count @@ -526,9 +544,18 @@ contains character(len=len(text)) :: upper upper = to_upper_text(text) - enabled = index(upper, "CONTACT") > 0 .or. index(upper, "WALL") > 0 + enabled = index(upper, "CONTACT") > 0 .or. index(upper, "WALL") > 0 .or. & + index(upper, "PLANE") > 0 end function is_contact_fixture + logical function is_multi_fixture(text) result(enabled) + character(len=*), intent(in) :: text + character(len=len(text)) :: upper + + upper = to_upper_text(text) + enabled = index(upper, "MULTI") > 0 .or. index(upper, "PLANE") > 0 + end function is_multi_fixture + character(len=len(text)) function to_upper_text(text) result(value) character(len=*), intent(in) :: text integer :: i diff --git a/tests/data/README.md b/tests/data/README.md index d7aa528..ca88bf2 100644 --- a/tests/data/README.md +++ b/tests/data/README.md @@ -1,3 +1,9 @@ # tests/data Small test input data. + +0.2.8 新增以下接触验证输入: + +1. `v020_single_particle_wall.inp`; +2. `v020_multi_particle_plane.inp`; +3. `v020_force_balance.inp`. diff --git a/tests/data/v020_force_balance.inp b/tests/data/v020_force_balance.inp new file mode 100644 index 0000000..810904f --- /dev/null +++ b/tests/data/v020_force_balance.inp @@ -0,0 +1,39 @@ +** CCLite 0.2.8 force and moment balance verification. +*CCLITE CONTROL, NAME=V020_FORCE_BALANCE, MODE=RUN +VERSION=0.2 + +*CCLITE SOLVER, ID=SPH, KIND=SPHLITE +EXECUTABLE=mock_sph_worker.exe +INPUT=mock_sph_multi_contact.inp + +*CCLITE SOLVER, ID=FEM, KIND=FEMLITE +EXECUTABLE=mock_fem_worker.exe +INPUT=mock_fem_plane.inp + +*CCLITE IPC, TYPE=WINDOWS_SHMEM +NAME_PREFIX=CCLITE_V020_FORCE +BUFFER=DOUBLE +TIMEOUT_MS=5000 + +*CCLITE TIME +START=0.0 +END=1.0e-6 +DT=1.0e-6 + +*CCLITE INTERFACE, NAME=PLANE_CONTACT +SPH_REGION=SPH_MULTI_CONTACT_REGION +FEM_SURFACE=FEM_PLANE + +*CCLITE SURFACE INTERACTION, NAME=PENALTY_1 +NORMAL=PENALTY, KN=1.0e6, CN=0.0 +FRICTION=0.0 + +*CCLITE CONTACT PAIR, NAME=PAIR_1 +INTERFACE=PLANE_CONTACT +INTERACTION=PENALTY_1 +TYPE=SPH_PARTICLE_TO_FEM_FACE + +*CCLITE OUTPUT +DIRECTORY=output/v020_force_balance +CSV=YES +LOG=YES diff --git a/tests/data/v020_multi_particle_plane.inp b/tests/data/v020_multi_particle_plane.inp new file mode 100644 index 0000000..24cc8af --- /dev/null +++ b/tests/data/v020_multi_particle_plane.inp @@ -0,0 +1,39 @@ +** CCLite 0.2.8 multi-particle plane contact verification. +*CCLITE CONTROL, NAME=V020_MULTI_PARTICLE_PLANE, MODE=RUN +VERSION=0.2 + +*CCLITE SOLVER, ID=SPH, KIND=SPHLITE +EXECUTABLE=mock_sph_worker.exe +INPUT=mock_sph_multi_contact.inp + +*CCLITE SOLVER, ID=FEM, KIND=FEMLITE +EXECUTABLE=mock_fem_worker.exe +INPUT=mock_fem_plane.inp + +*CCLITE IPC, TYPE=WINDOWS_SHMEM +NAME_PREFIX=CCLITE_V020_MULTI +BUFFER=DOUBLE +TIMEOUT_MS=5000 + +*CCLITE TIME +START=0.0 +END=1.0e-6 +DT=1.0e-6 + +*CCLITE INTERFACE, NAME=PLANE_CONTACT +SPH_REGION=SPH_MULTI_CONTACT_REGION +FEM_SURFACE=FEM_PLANE + +*CCLITE SURFACE INTERACTION, NAME=PENALTY_1 +NORMAL=PENALTY, KN=1.0e6, CN=0.0 +FRICTION=0.0 + +*CCLITE CONTACT PAIR, NAME=PAIR_1 +INTERFACE=PLANE_CONTACT +INTERACTION=PENALTY_1 +TYPE=SPH_PARTICLE_TO_FEM_FACE + +*CCLITE OUTPUT +DIRECTORY=output/v020_multi_particle_plane +CSV=YES +LOG=YES diff --git a/tests/data/v020_single_particle_wall.inp b/tests/data/v020_single_particle_wall.inp new file mode 100644 index 0000000..1a9e5a0 --- /dev/null +++ b/tests/data/v020_single_particle_wall.inp @@ -0,0 +1,39 @@ +** CCLite 0.2.8 single particle wall contact verification. +*CCLITE CONTROL, NAME=V020_SINGLE_PARTICLE_WALL, MODE=RUN +VERSION=0.2 + +*CCLITE SOLVER, ID=SPH, KIND=SPHLITE +EXECUTABLE=mock_sph_worker.exe +INPUT=mock_sph_contact.inp + +*CCLITE SOLVER, ID=FEM, KIND=FEMLITE +EXECUTABLE=mock_fem_worker.exe +INPUT=mock_fem_wall.inp + +*CCLITE IPC, TYPE=WINDOWS_SHMEM +NAME_PREFIX=CCLITE_V020_SINGLE +BUFFER=DOUBLE +TIMEOUT_MS=5000 + +*CCLITE TIME +START=0.0 +END=1.0e-6 +DT=1.0e-6 + +*CCLITE INTERFACE, NAME=WALL_CONTACT +SPH_REGION=SPH_CONTACT_REGION +FEM_SURFACE=FEM_WALL + +*CCLITE SURFACE INTERACTION, NAME=PENALTY_1 +NORMAL=PENALTY, KN=1.0e6, CN=0.0 +FRICTION=0.0 + +*CCLITE CONTACT PAIR, NAME=PAIR_1 +INTERFACE=WALL_CONTACT +INTERACTION=PENALTY_1 +TYPE=SPH_PARTICLE_TO_FEM_FACE + +*CCLITE OUTPUT +DIRECTORY=output/v020_single_particle_wall +CSV=YES +LOG=YES diff --git a/tests/verification/README.md b/tests/verification/README.md index e8fe5aa..17cb757 100644 --- a/tests/verification/README.md +++ b/tests/verification/README.md @@ -10,4 +10,8 @@ Verification tests, including `V010_EMPTY_COUPLING`. 4. `V020_FORCE_BALANCE`; 5. `V020_SINGLE_REAL_WORKER_SMOKE`. -0.2.0 只冻结命名约定,具体算例和 checker 在后续小版本补齐。 +0.2.8 已接入: + +1. `v020_geometry_primitives.csv`:几何 primitive checker 输入; +2. `check_v020_geometry_primitives.py`:几何验证报告生成; +3. `check_v020_contact.py`:读取 contact、candidate、force balance 和 IPC 报告,生成接触验证报告。 diff --git a/tests/verification/v020_geometry_primitives.csv b/tests/verification/v020_geometry_primitives.csv new file mode 100644 index 0000000..3237112 --- /dev/null +++ b/tests/verification/v020_geometry_primitives.csv @@ -0,0 +1,14 @@ +metric,expected,actual,tolerance,degenerate_count,nonfinite_count +dot_product,32.0,32.0,1.0e-12,0,0 +cross_z,1.0,1.0,1.0e-12,0,0 +norm_3_4_0,5.0,5.0,1.0e-12,0,0 +normalized_z,1.0,1.0,1.0e-12,0,0 +segment_t_midpoint,0.5,0.5,1.0e-12,0,0 +triangle_closest_x,0.25,0.25,1.0e-12,0,0 +triangle_closest_y,0.25,0.25,1.0e-12,0,0 +triangle_distance2,1.0,1.0,1.0e-12,0,0 +triangle_weight_sum,1.0,1.0,1.0e-12,0,0 +quad_distance2,0.25,0.25,1.0e-12,0,0 +quad_weight_sum,1.0,1.0,1.0e-12,0,0 +degenerate_segment_rejected,1.0,1.0,0.0,1,0 +degenerate_triangle_rejected,1.0,1.0,0.0,1,0 diff --git a/todo.md b/todo.md index 49cf4f6..77340f0 100644 --- a/todo.md +++ b/todo.md @@ -344,37 +344,37 @@ 目标:形成 0.2.x 自动验收闭环,支持几何、接触方向、力平衡和回归检查。 -- [ ] T0208-01 建立 0.2.x checker 公共 CSV 读取工具。 +- [x] T0208-01 建立 0.2.x checker 公共 CSV 读取工具。 完成判据:checker 可读取 contact、candidate、force balance 和 IPC 报告。 -- [ ] T0208-02 实现 `check_v020_geometry_primitives.py`。 +- [x] T0208-02 实现 `check_v020_geometry_primitives.py`。 完成判据:可校验几何测试输出、容差、退化输入和非有限计数。 -- [ ] T0208-03 实现 `check_v020_contact.py`。 +- [x] T0208-03 实现 `check_v020_contact.py`。 完成判据:可校验接触数、方向、penetration、力大小和力平衡。 -- [ ] T0208-04 生成或整理 `V020_GEOMETRY_PRIMITIVES` 算例。 +- [x] T0208-04 生成或整理 `V020_GEOMETRY_PRIMITIVES` 算例。 完成判据:算例可自动运行并由 checker 判定通过。 -- [ ] T0208-05 生成或整理 `V020_SINGLE_PARTICLE_WALL` 算例。 +- [x] T0208-05 生成或整理 `V020_SINGLE_PARTICLE_WALL` 算例。 完成判据:单粒子穿透平面时产生一条方向正确的接触力。 -- [ ] T0208-06 生成或整理 `V020_MULTI_PARTICLE_PLANE` 算例。 +- [x] T0208-06 生成或整理 `V020_MULTI_PARTICLE_PLANE` 算例。 完成判据:多粒子接触数量、最大穿透和总力可复核。 -- [ ] T0208-07 生成或整理 `V020_FORCE_BALANCE` 算例。 +- [x] T0208-07 生成或整理 `V020_FORCE_BALANCE` 算例。 完成判据:合力误差和力矩误差在容差内,非有限计数为 0。 -- [ ] T0208-08 输出 `verification_report.json`。 +- [x] T0208-08 输出 `verification_report.json`。 完成判据:报告包含 case id、status、metrics、failed checks 和关键输出文件路径。 -- [ ] T0208-09 将 0.2.x 算例接入本地回归测试。 +- [x] T0208-09 将 0.2.x 算例接入本地回归测试。 完成判据:一条命令可运行 0.1.x 回归和 0.2.x 基础接触验证。 -- [ ] T0208-10 增加 CSV 表头回归检查。 +- [x] T0208-10 增加 CSV 表头回归检查。 完成判据:contact、candidate 和 force balance 表头变更会触发测试失败。 -- [ ] T0208-11 增加失败报告细节。 +- [x] T0208-11 增加失败报告细节。 完成判据:checker 失败时输出 step、pair、字段名、期望值和实际值。 # 11. 0.2.9 单真实 Worker Gate @@ -466,12 +466,12 @@ - [ ] A0211 FEM 节点力分配满足作用-反作用平衡。 - [ ] A0212 `CCL_TO_SPH_FORCE` 可写入非空载荷。 - [ ] A0213 `CCL_TO_FEM_LOAD` 可写入非空载荷。 -- [ ] A0214 `contact_report.csv` 可被 checker 自动检查。 -- [ ] A0215 `force_balance.csv` 包含接触力和力矩诊断。 -- [ ] A0216 `V020_GEOMETRY_PRIMITIVES` 通过。 -- [ ] A0217 `V020_SINGLE_PARTICLE_WALL` 通过。 -- [ ] A0218 `V020_MULTI_PARTICLE_PLANE` 通过。 -- [ ] A0219 `V020_FORCE_BALANCE` 通过。 +- [x] A0214 `contact_report.csv` 可被 checker 自动检查。 +- [x] A0215 `force_balance.csv` 包含接触力和力矩诊断。 +- [x] A0216 `V020_GEOMETRY_PRIMITIVES` 通过。 +- [x] A0217 `V020_SINGLE_PARTICLE_WALL` 通过。 +- [x] A0218 `V020_MULTI_PARTICLE_PLANE` 通过。 +- [x] A0219 `V020_FORCE_BALANCE` 通过。 - [ ] A0220 单真实 worker gate 通过或形成受控协议缺口。 - [ ] A0221 所有新增文档和样例为 UTF-8 without BOM。 - [ ] A0222 0.2.x 不声明超出版本边界的能力。