From 85e21cbb959f5a6fea37511f5b3e1a6800daa8ae Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 6 Jul 2026 08:55:24 +0800 Subject: [PATCH] Add CCLite 0.2.7 contact controller diagnostics --- CMakeLists.txt | 15 + .../checkers/check_v020_contact_controller.py | 225 +++++++++ include/cclite_ipc.h | 1 + src/contact/ccl_contact_force.f90 | 5 +- src/contact/ccl_contact_narrow.f90 | 9 +- src/controller/ccl_controller.f90 | 437 +++++++++++++++++- src/diagnostics/ccl_diagnostics.f90 | 87 +++- src/ipc/ccl_ipc.f90 | 25 + src/ipc/cclite_ipc_win.c | 8 + src/mock_workers/ccl_mock_worker.f90 | 201 +++++++- tests/data/v020_contact_run.inp | 39 ++ tests/unit/test_contact_force.f90 | 1 + todo.md | 24 +- 13 files changed, 1035 insertions(+), 42 deletions(-) create mode 100644 Python/checkers/check_v020_contact_controller.py create mode 100644 tests/data/v020_contact_run.inp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a764a2..2a4edfc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -169,6 +169,10 @@ add_test(NAME dry_run_100_step COMMAND cclite dry-run ${CMAKE_SOURCE_DIR}/tests/data/v010_valid.inp ) +add_test(NAME V020_contact_controller_run + COMMAND cclite run ${CMAKE_SOURCE_DIR}/tests/data/v020_contact_run.inp +) + if(Python3_Interpreter_FOUND) add_test(NAME verify_v010_empty_coupling COMMAND ${Python3_EXECUTABLE} @@ -193,6 +197,17 @@ if(Python3_Interpreter_FOUND) ) set_tests_properties(diagnostics_regression_headers PROPERTIES DEPENDS dry_run_100_step) + add_test(NAME verify_v020_contact_controller + COMMAND ${Python3_EXECUTABLE} + ${CMAKE_SOURCE_DIR}/Python/checkers/check_v020_contact_controller.py + --case-id V020_CONTACT_CONTROLLER + --input ${CMAKE_SOURCE_DIR}/tests/data/v020_contact_run.inp + --output-dir ${CMAKE_BINARY_DIR}/output/v020_contact_run + --report ${CMAKE_BINARY_DIR}/output/v020_contact_run/verification_report.json + --expected-steps 2 + ) + set_tests_properties(verify_v020_contact_controller PROPERTIES DEPENDS V020_contact_controller_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_controller.py b/Python/checkers/check_v020_contact_controller.py new file mode 100644 index 0000000..d056024 --- /dev/null +++ b/Python/checkers/check_v020_contact_controller.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from common_csv import as_float, as_int, read_required_csv + + +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", +] + +FORCE_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 build_report(args: argparse.Namespace) -> dict: + output_dir = Path(args.output_dir) + ipc_path = output_dir / "ipc_report.csv" + contact_path = output_dir / "contact_report.csv" + force_path = output_dir / "force_balance.csv" + log_path = output_dir / "run.log" + failed: list[str] = [] + metrics: dict[str, int | float] = {} + + try: + _, ipc_rows = read_required_csv(ipc_path, IPC_HEADERS) + _, contact_rows = read_required_csv(contact_path, CONTACT_HEADERS) + _, force_rows = read_required_csv(force_path, FORCE_HEADERS) + except AssertionError as exc: + ipc_rows = [] + contact_rows = [] + force_rows = [] + failed.append(str(exc)) + + if not log_path.exists(): + failed.append(f"missing log file: {log_path}") + elif "contact_narrow_force" not in log_path.read_text(encoding="utf-8"): + failed.append("run.log missing contact_narrow_force diagnostics") + + import_load_rows = 0 + advance_rows = 0 + stop_rows = 0 + for index, row in enumerate(ipc_rows, start=1): + 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"ipc row {index}: {exc}") + continue + if command_seq != ack_seq: + failed.append(f"ipc row {index}: seq/ack mismatch {command_seq}/{ack_seq}") + if error_code != 0: + failed.append(f"ipc row {index}: nonzero error_code {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: + failed.append(f"expected {expected_worker_step_rows} IMPORT_LOADS rows, got {import_load_rows}") + if advance_rows != expected_worker_step_rows: + failed.append(f"expected {expected_worker_step_rows} ADVANCE rows, got {advance_rows}") + if stop_rows != 2: + failed.append(f"expected two STOP rows, got {stop_rows}") + + contact_steps: set[int] = set() + for index, row in enumerate(contact_rows, start=1): + 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"contact row {index}: {exc}") + continue + contact_steps.add(step_id) + if node_count != 4: + failed.append(f"contact row {index}: node_count expected 4, got {node_count}") + if penetration <= 0.0: + failed.append(f"contact row {index}: penetration should be positive") + if abs(normal_z - 1.0) > 1.0e-12: + failed.append(f"contact row {index}: normal_z expected 1") + if force_z <= 0.0: + failed.append(f"contact row {index}: force_z should be positive") + + expected_steps = set(range(1, args.expected_steps + 1)) + if contact_steps != expected_steps: + failed.append(f"contact steps mismatch: expected {sorted(expected_steps)}, got {sorted(contact_steps)}") + + force_steps: set[int] = set() + for index, row in enumerate(force_rows, start=1): + 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") + totals = [as_float(row, key) for key in ("total_fx", "total_fy", "total_fz")] + except AssertionError as exc: + failed.append(f"force row {index}: {exc}") + continue + force_steps.add(step_id) + if num_contacts != 1: + failed.append(f"force row {index}: num_contacts expected 1, got {num_contacts}") + if max_penetration <= 0.0: + failed.append(f"force row {index}: max_penetration should be positive") + if total_force_norm <= 0.0: + failed.append(f"force row {index}: total_contact_force_norm should be positive") + if force_balance_error > args.tolerance: + failed.append(f"force row {index}: force_balance_error {force_balance_error}") + if moment_balance_error > args.tolerance: + failed.append(f"force row {index}: moment_balance_error {moment_balance_error}") + if nonfinite_count != 0: + failed.append(f"force row {index}: nonfinite_contact_count {nonfinite_count}") + if max(abs(value) for value in totals) > args.tolerance: + failed.append(f"force row {index}: total force columns are not balanced") + + if force_steps != expected_steps: + failed.append(f"force steps mismatch: expected {sorted(expected_steps)}, got {sorted(force_steps)}") + + metrics["ipc_rows"] = len(ipc_rows) + metrics["contact_rows"] = len(contact_rows) + metrics["force_rows"] = len(force_rows) + metrics["import_load_rows"] = import_load_rows + metrics["advance_rows"] = advance_rows + return make_report(args, failed, ipc_path, contact_path, force_path, log_path, metrics) + + +def make_report( + args: argparse.Namespace, + failed: list[str], + ipc_path: Path, + contact_path: Path, + force_path: 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(Path(args.input)), + "output_files": { + "run_log": str(log_path), + "ipc_report": str(ipc_path), + "contact_report": str(contact_path), + "force_balance": str(force_path), + }, + } + + +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=2) + parser.add_argument("--tolerance", type=float, default=1.0e-7) + args = parser.parse_args() + + report = build_report(args) + report_path = Path(args.report) + 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") + 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/include/cclite_ipc.h b/include/cclite_ipc.h index 2f7a596..e332007 100644 --- a/include/cclite_ipc.h +++ b/include/cclite_ipc.h @@ -18,6 +18,7 @@ extern "C" { int ccl_ipc_shm_create(const char *name, size_t byte_size, void **out_handle, void **out_payload); int ccl_ipc_shm_open(const char *name, size_t byte_size, void **out_handle, void **out_payload); int ccl_ipc_shm_close(void *handle); +void *ccl_ipc_ptr_offset(void *base, size_t byte_offset); int ccl_ipc_event_create(const char *name, int initial_state, void **out_handle); int ccl_ipc_event_open(const char *name, void **out_handle); diff --git a/src/contact/ccl_contact_force.f90 b/src/contact/ccl_contact_force.f90 index 7d00576..144b942 100644 --- a/src/contact/ccl_contact_force.f90 +++ b/src/contact/ccl_contact_force.f90 @@ -45,7 +45,7 @@ contains integer, intent(in) :: particle_count type(CCL_FEM_Facet_View_Type), intent(in) :: facets(:) integer, intent(in) :: facet_count - type(CCL_Contact_Record_Type), intent(in) :: contacts(:) + type(CCL_Contact_Record_Type), intent(inout) :: contacts(:) integer, intent(in) :: contact_count type(CCL_SPH_Force_Accumulator_Type), intent(inout) :: sph_forces type(CCL_FEM_Load_Accumulator_Type), intent(inout) :: fem_loads @@ -82,7 +82,7 @@ contains type(CCL_Surface_Interaction_Config), intent(in) :: interaction type(CCL_SPH_Particle_View_Type), intent(in) :: particle type(CCL_FEM_Facet_View_Type), intent(in) :: facet - type(CCL_Contact_Record_Type), intent(in) :: contact + type(CCL_Contact_Record_Type), intent(inout) :: contact type(CCL_SPH_Force_Accumulator_Type), intent(inout) :: sph_forces type(CCL_FEM_Load_Accumulator_Type), intent(inout) :: fem_loads type(CCL_Contact_Force_Stats_Type), intent(inout) :: stats @@ -108,6 +108,7 @@ contains ierr = CCL_ERROR_INPUT_INVALID_VALUE return end if + contact%force = sph_force call ccl_sph_force_accumulator_add(sph_forces, particle%external_id, particle%internal_index, & sph_force, ierr) diff --git a/src/contact/ccl_contact_narrow.f90 b/src/contact/ccl_contact_narrow.f90 index 2c8eeeb..d1721c1 100644 --- a/src/contact/ccl_contact_narrow.f90 +++ b/src/contact/ccl_contact_narrow.f90 @@ -23,6 +23,7 @@ module ccl_contact_narrow real(c_double) :: gap = 0.0_c_double real(c_double) :: contact_distance = 0.0_c_double real(c_double) :: penetration = 0.0_c_double + real(c_double) :: force(3) = 0.0_c_double end type CCL_Contact_Record_Type type :: CCL_Narrow_Phase_Stats_Type @@ -168,12 +169,14 @@ contains ierr = CCL_ERROR_INPUT_INVALID_VALUE return end if - write(unit_id, '(a)') "step_id,pair_id,sph_id,facet_id,gap,penetration,normal_x,normal_y,normal_z,node_count" + write(unit_id, '(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" do i = 1, contact_count - write(unit_id, '(i0,",",i0,",",i0,",",i0,",",es16.8,",",es16.8,",",es16.8,",",es16.8,",",es16.8,",",i0)') & + write(unit_id, '(i0,",",i0,",",i0,",",i0,8(",",es16.8),",",i0)') & contacts(i)%step_id, contacts(i)%pair_id, contacts(i)%sph_external_id, contacts(i)%facet_id, & contacts(i)%gap, contacts(i)%penetration, contacts(i)%normal(1), contacts(i)%normal(2), & - contacts(i)%normal(3), contacts(i)%node_count + contacts(i)%normal(3), contacts(i)%force(1), contacts(i)%force(2), contacts(i)%force(3), & + contacts(i)%node_count end do close(unit_id) end subroutine ccl_contact_report_write_csv diff --git a/src/controller/ccl_controller.f90 b/src/controller/ccl_controller.f90 index 4390329..7b9ae20 100644 --- a/src/controller/ccl_controller.f90 +++ b/src/controller/ccl_controller.f90 @@ -1,24 +1,38 @@ module ccl_controller - use iso_c_binding, only: c_double, c_f_pointer, c_int32_t, c_int64_t, c_size_t + use iso_c_binding, only: c_double, c_f_pointer, c_int32_t, c_int64_t, c_ptr, c_size_t + use ccl_broad_phase, only: CCL_Broad_Phase_Stats_Type, CCL_Candidate_Pair_Type, & + CCL_Hash_Grid_Type, ccl_broad_phase_stats_reset, ccl_hash_grid_init, & + ccl_hash_grid_insert_facet, ccl_hash_grid_query_particle use ccl_case_types, only: CCL_Case_Type, CCL_CASE_SOLVER_FEM => CCL_SOLVER_FEM, & CCL_CASE_SOLVER_SPH => CCL_SOLVER_SPH, CCL_TEXT_LEN use ccl_command_block, only: CCL_CMD_ADVANCE, CCL_CMD_BUILD_MODEL, CCL_CMD_EXPORT_INTERFACE, & CCL_CMD_IMPORT_LOADS, CCL_CMD_INIT, CCL_CMD_READ_INPUT, CCL_CMD_STOP, CCL_CMD_WRITE_OUTPUT, & CCL_Command_Block_Type, CCL_SOLVER_ID_FEM, CCL_SOLVER_ID_SPH, CCL_WORKER_READY, & ccl_command_block_size, ccl_command_check_ack, ccl_command_dispatch, ccl_command_init + use ccl_contact_force, only: CCL_Contact_Force_Stats_Type, ccl_contact_force_compute, & + ccl_contact_force_stats_reset + use ccl_contact_narrow, only: CCL_Contact_Record_Type, CCL_Narrow_Phase_Stats_Type, & + ccl_narrow_phase_run, ccl_narrow_phase_stats_reset use ccl_data_block, only: CCL_BUFFER_READY, CCL_BUFFER_WRITING, CCL_Data_Block_Header_Type, & CCL_ROLE_CCL_TO_FEM_LOAD, CCL_ROLE_CCL_TO_SPH_FORCE, CCL_ROLE_FEM_TO_CCL_FACET, & - CCL_ROLE_SPH_TO_CCL_PARTICLE, ccl_data_header_init, ccl_data_header_set_count, & - ccl_data_header_set_state, ccl_data_header_size, ccl_data_header_validate, & - ccl_data_record_size_for_role + CCL_ROLE_SPH_TO_CCL_PARTICLE, CCL_FEM_Facet_Record_Type, CCL_FEM_Load_Record_Type, & + CCL_SPH_Force_Record_Type, CCL_SPH_Particle_Record_Type, ccl_data_header_init, & + 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_force_balance, ccl_diagnostics_write_ipc, & - ccl_diagnostics_write_run + ccl_diagnostics_open, 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 + use ccl_geometry, only: CCL_AABB_Type, ccl_facet_aabb, ccl_particle_aabb, ccl_vec3_norm + use ccl_interface_view, only: CCL_FEM_Facet_View_Type, CCL_FEM_Load_Accumulator_Type, & + CCL_SPH_Force_Accumulator_Type, CCL_SPH_Particle_View_Type, ccl_fem_facet_view_from_record, & + ccl_fem_load_accumulator_init, ccl_prepare_fem_load_header, ccl_prepare_sph_force_header, & + ccl_sph_force_accumulator_init, ccl_sph_particle_view_from_record, clear_fem_load_record, & + clear_sph_force_record use ccl_ipc, only: CCL_Named_Event, CCL_Shared_Memory, ccl_event_close, ccl_event_create, & - ccl_event_reset, ccl_event_signal, ccl_event_wait, ccl_shm_close, ccl_shm_create + ccl_event_reset, ccl_event_signal, ccl_event_wait, ccl_ptr_offset, ccl_shm_close, ccl_shm_create use ccl_log, only: ccl_log_error, ccl_log_info use ccl_process, only: CCL_Process_Type, ccl_process_close, ccl_process_is_running, & ccl_process_start, ccl_process_terminate, ccl_process_wait @@ -26,7 +40,10 @@ module ccl_controller integer(c_int32_t), parameter :: CCL_SOLVER_ID_CCL = 3_c_int32_t integer(c_int32_t), parameter :: CCL_EXPORT_RECORD_CAPACITY = 4_c_int32_t - integer(c_int32_t), parameter :: CCL_LOAD_RECORD_CAPACITY = 4_c_int32_t + integer(c_int32_t), parameter :: CCL_LOAD_RECORD_CAPACITY = 16_c_int32_t + integer, parameter :: CCL_GRID_ENTRY_CAPACITY_PER_FACET = 64 + integer, parameter :: CCL_MIN_CANDIDATE_CAPACITY = 16 + integer, parameter :: CCL_CONTACT_RECORD_CAPACITY = 64 type :: CCL_Worker_Runtime character(len=16) :: solver_name = "" @@ -52,6 +69,10 @@ module ccl_controller type(CCL_Command_Block_Type), pointer :: command => null() type(CCL_Data_Block_Header_Type), pointer :: export_header => null() type(CCL_Data_Block_Header_Type), pointer :: load_header => null() + type(CCL_SPH_Particle_Record_Type), pointer :: sph_particle_records(:) => null() + type(CCL_FEM_Facet_Record_Type), pointer :: fem_facet_records(:) => null() + type(CCL_SPH_Force_Record_Type), pointer :: sph_force_records(:) => null() + type(CCL_FEM_Load_Record_Type), pointer :: fem_load_records(:) => null() end type CCL_Worker_Runtime contains @@ -66,6 +87,7 @@ contains integer :: step_count integer :: step_id integer :: close_ierr + logical :: contact_run character(len=128) :: msg ierr = CCL_SUCCESS @@ -78,8 +100,14 @@ contains call ccl_diagnostics_open(diag, ccl_case%output%directory, ccl_case%name, input_file, ierr) if (ierr /= CCL_SUCCESS) return - call ccl_log_info("controller", "starting 0.2.0 empty coupling baseline path") - call ccl_diagnostics_write_run(diag, "INFO", "controller", "starting empty coupling dry-run") + contact_run = ccl_case%num_contact_pairs > 0 + if (contact_run) then + call ccl_log_info("controller", "starting 0.2.7 contact coupling path") + call ccl_diagnostics_write_run(diag, "INFO", "controller", "starting contact coupling run") + else + call ccl_log_info("controller", "starting empty coupling dry-run path") + call ccl_diagnostics_write_run(diag, "INFO", "controller", "starting empty coupling dry-run") + end if call init_worker(sph_worker, ccl_case, CCL_CASE_SOLVER_SPH, ierr) if (ierr /= CCL_SUCCESS) goto 900 call init_worker(fem_worker, ccl_case, CCL_CASE_SOLVER_FEM, ierr) @@ -108,7 +136,11 @@ contains if (ierr /= CCL_SUCCESS) goto 900 do step_id = 1, step_count - call run_empty_step(sph_worker, fem_worker, step_id, ccl_case%time%dt, diag, ierr) + if (contact_run) then + call run_contact_step(ccl_case, sph_worker, fem_worker, step_id, ccl_case%time%dt, diag, ierr) + else + call run_empty_step(sph_worker, fem_worker, step_id, ccl_case%time%dt, diag, ierr) + end if if (ierr /= CCL_SUCCESS) goto 900 end do @@ -122,13 +154,17 @@ contains call stop_worker(fem_worker, diag, ierr) if (ierr /= CCL_SUCCESS) goto 900 - write(msg, '(a,i0)') "empty coupling dry-run completed, steps=", step_count + if (contact_run) then + write(msg, '(a,i0)') "contact coupling run completed, steps=", step_count + else + write(msg, '(a,i0)') "empty coupling dry-run completed, steps=", step_count + end if call ccl_log_info("controller", trim(msg)) call ccl_diagnostics_write_run(diag, "INFO", "controller", trim(msg)) 900 continue if (ierr /= CCL_SUCCESS) then - write(msg, '(a,i0)') "empty coupling failed, ierr=", ierr + write(msg, '(a,i0)') "coupling run failed, ierr=", ierr call ccl_log_error("controller", trim(msg)) call ccl_diagnostics_write_run(diag, "ERROR", "controller", trim(msg)) call terminate_worker_if_running(sph_worker) @@ -209,12 +245,46 @@ contains call c_f_pointer(worker%load_shm%payload, worker%load_header) call ccl_data_header_init(worker%load_header, worker%load_role, CCL_SOLVER_ID_CCL, & worker%solver_id, CCL_LOAD_RECORD_CAPACITY) + call map_worker_payloads(worker, ierr) + if (ierr /= CCL_SUCCESS) return call ccl_event_create(worker%command_event_name, .false., worker%command_event, ierr) if (ierr /= CCL_SUCCESS) return call ccl_event_create(worker%ack_event_name, .false., worker%ack_event, ierr) end subroutine create_worker_resources + subroutine map_worker_payloads(worker, ierr) + type(CCL_Worker_Runtime), intent(inout) :: worker + integer, intent(out) :: ierr + type(c_ptr) :: payload + integer :: shape(1) + + shape = [int(CCL_EXPORT_RECORD_CAPACITY)] + call ccl_ptr_offset(worker%export_shm%payload, int(ccl_data_header_size(), c_size_t), payload, ierr) + if (ierr /= CCL_SUCCESS) return + select case (worker%export_role) + case (CCL_ROLE_SPH_TO_CCL_PARTICLE) + call c_f_pointer(payload, worker%sph_particle_records, shape) + case (CCL_ROLE_FEM_TO_CCL_FACET) + call c_f_pointer(payload, worker%fem_facet_records, shape) + case default + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end select + + shape = [int(CCL_LOAD_RECORD_CAPACITY)] + call ccl_ptr_offset(worker%load_shm%payload, int(ccl_data_header_size(), c_size_t), payload, ierr) + if (ierr /= CCL_SUCCESS) return + select case (worker%load_role) + case (CCL_ROLE_CCL_TO_SPH_FORCE) + call c_f_pointer(payload, worker%sph_force_records, shape) + case (CCL_ROLE_CCL_TO_FEM_LOAD) + call c_f_pointer(payload, worker%fem_load_records, shape) + case default + ierr = CCL_ERROR_SYSTEM_INTERNAL + end select + end subroutine map_worker_payloads + subroutine start_worker(worker, diag, ierr) type(CCL_Worker_Runtime), intent(inout) :: worker type(CCL_Diagnostics_Type), intent(inout) :: diag @@ -293,6 +363,322 @@ contains call ccl_diagnostics_write_force_balance(diag, step_id) end subroutine run_empty_step + subroutine run_contact_step(ccl_case, sph_worker, fem_worker, step_id, dt, diag, ierr) + type(CCL_Case_Type), intent(in) :: ccl_case + type(CCL_Worker_Runtime), intent(inout) :: sph_worker + type(CCL_Worker_Runtime), intent(inout) :: fem_worker + integer, intent(in) :: step_id + real(8), intent(in) :: dt + type(CCL_Diagnostics_Type), intent(inout) :: diag + integer, intent(out) :: ierr + type(CCL_SPH_Particle_View_Type), allocatable :: particles(:) + type(CCL_FEM_Facet_View_Type), allocatable :: facets(:) + type(CCL_Candidate_Pair_Type), allocatable :: candidates(:) + type(CCL_Contact_Record_Type), allocatable :: contacts(:) + type(CCL_SPH_Force_Accumulator_Type) :: sph_forces + type(CCL_FEM_Load_Accumulator_Type) :: fem_loads + type(CCL_Broad_Phase_Stats_Type) :: broad_stats + type(CCL_Narrow_Phase_Stats_Type) :: narrow_stats + type(CCL_Narrow_Phase_Stats_Type) :: total_narrow_stats + type(CCL_Contact_Force_Stats_Type) :: force_stats + type(CCL_Contact_Force_Stats_Type) :: total_force_stats + integer :: particle_count + integer :: facet_count + integer :: candidate_count + integer :: contact_count + integer :: pair_id + integer :: interaction_id + integer :: i + real(c_double) :: max_penetration + real(c_double) :: total_contact_force_norm + + call send_worker_command(sph_worker, CCL_CMD_EXPORT_INTERFACE, step_id, dt, diag, ierr) + if (ierr /= CCL_SUCCESS) return + call send_worker_command(fem_worker, CCL_CMD_EXPORT_INTERFACE, step_id, dt, diag, ierr) + if (ierr /= CCL_SUCCESS) return + + call validate_export_header(sph_worker, step_id, ierr) + if (ierr /= CCL_SUCCESS) return + call validate_export_header(fem_worker, step_id, ierr) + if (ierr /= CCL_SUCCESS) return + + call build_sph_particle_views(sph_worker, particles, particle_count, ierr) + if (ierr /= CCL_SUCCESS) return + call build_fem_facet_views(fem_worker, facets, facet_count, ierr) + if (ierr /= CCL_SUCCESS) return + + call ccl_sph_force_accumulator_init(sph_forces, int(CCL_LOAD_RECORD_CAPACITY)) + call ccl_fem_load_accumulator_init(fem_loads, int(CCL_LOAD_RECORD_CAPACITY)) + call run_broad_phase_search(particles, particle_count, facets, facet_count, candidates, & + candidate_count, broad_stats, ierr) + if (ierr /= CCL_SUCCESS) return + + call ccl_narrow_phase_stats_reset(total_narrow_stats) + call ccl_contact_force_stats_reset(total_force_stats) + max_penetration = 0.0_c_double + allocate(contacts(CCL_CONTACT_RECORD_CAPACITY)) + do pair_id = 1, ccl_case%num_contact_pairs + interaction_id = find_surface_interaction_index(ccl_case, & + ccl_case%contact_pair(pair_id)%interaction_name) + if (interaction_id <= 0) then + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end if + contacts = CCL_Contact_Record_Type() + call ccl_narrow_phase_stats_reset(narrow_stats) + call ccl_narrow_phase_run(int(step_id, c_int32_t), int(pair_id, c_int32_t), particles, & + particle_count, facets, facet_count, candidates, candidate_count, contacts, contact_count, & + CCL_CONTACT_RECORD_CAPACITY, narrow_stats, ierr) + if (ierr /= CCL_SUCCESS) return + + call ccl_contact_force_stats_reset(force_stats) + call ccl_contact_force_compute(ccl_case%surface_interaction(interaction_id), particles, & + particle_count, facets, facet_count, contacts, contact_count, sph_forces, fem_loads, & + force_stats, ierr) + if (ierr /= CCL_SUCCESS) return + + call accumulate_narrow_stats(total_narrow_stats, narrow_stats) + call accumulate_force_stats(total_force_stats, force_stats) + do i = 1, contact_count + max_penetration = max(max_penetration, contacts(i)%penetration) + call ccl_diagnostics_write_contact(diag, contacts(i)) + end do + end do + total_force_stats%force_balance_error = ccl_vec3_norm(total_force_stats%total_sph_force + & + total_force_stats%total_fem_force) + total_force_stats%moment_balance_error = ccl_vec3_norm(total_force_stats%total_sph_moment + & + total_force_stats%total_fem_moment) + total_contact_force_norm = ccl_vec3_norm(total_force_stats%total_sph_force) + + call write_contact_loads(sph_worker, fem_worker, step_id, sph_forces, fem_loads, ierr) + if (ierr /= CCL_SUCCESS) return + call log_step_interface_counts(diag, sph_worker, fem_worker, step_id) + call log_contact_step_diagnostics(diag, step_id, particle_count, facet_count, broad_stats, & + total_narrow_stats, total_force_stats, max_penetration) + call ccl_diagnostics_write_force_balance(diag, step_id, total_force_stats%total_sph_force, & + total_force_stats%total_fem_force, total_force_stats%contact_count, max_penetration, & + total_contact_force_norm, total_force_stats%force_balance_error, & + total_force_stats%moment_balance_error, total_force_stats%nonfinite_force_count, & + total_narrow_stats%skipped_separated_count, total_narrow_stats%skipped_degenerate_count, & + total_narrow_stats%skipped_invalid_count) + + call send_worker_command(sph_worker, CCL_CMD_IMPORT_LOADS, step_id, dt, diag, ierr) + if (ierr /= CCL_SUCCESS) return + call send_worker_command(fem_worker, CCL_CMD_IMPORT_LOADS, step_id, dt, diag, ierr) + if (ierr /= CCL_SUCCESS) return + + call send_worker_command(sph_worker, CCL_CMD_ADVANCE, step_id, dt, diag, ierr) + if (ierr /= CCL_SUCCESS) return + call send_worker_command(fem_worker, CCL_CMD_ADVANCE, step_id, dt, diag, ierr) + end subroutine run_contact_step + + subroutine build_sph_particle_views(worker, particles, particle_count, ierr) + type(CCL_Worker_Runtime), intent(in) :: worker + type(CCL_SPH_Particle_View_Type), allocatable, intent(out) :: particles(:) + integer, intent(out) :: particle_count + integer, intent(out) :: ierr + integer :: i + + ierr = CCL_SUCCESS + particle_count = int(worker%export_header%item_count) + allocate(particles(max(1, particle_count))) + if (particle_count == 0) return + if (.not. associated(worker%sph_particle_records)) then + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end if + do i = 1, particle_count + call ccl_sph_particle_view_from_record(worker%sph_particle_records(i), particles(i), ierr) + if (ierr /= CCL_SUCCESS) return + end do + end subroutine build_sph_particle_views + + subroutine build_fem_facet_views(worker, facets, facet_count, ierr) + type(CCL_Worker_Runtime), intent(in) :: worker + type(CCL_FEM_Facet_View_Type), allocatable, intent(out) :: facets(:) + integer, intent(out) :: facet_count + integer, intent(out) :: ierr + integer :: i + + ierr = CCL_SUCCESS + facet_count = int(worker%export_header%item_count) + allocate(facets(max(1, facet_count))) + if (facet_count == 0) return + if (.not. associated(worker%fem_facet_records)) then + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end if + do i = 1, facet_count + call ccl_fem_facet_view_from_record(worker%fem_facet_records(i), facets(i), ierr) + if (ierr /= CCL_SUCCESS) return + end do + end subroutine build_fem_facet_views + + subroutine run_broad_phase_search(particles, particle_count, facets, facet_count, candidates, & + candidate_count, stats, ierr) + 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), allocatable, intent(out) :: candidates(:) + integer, intent(out) :: candidate_count + type(CCL_Broad_Phase_Stats_Type), intent(out) :: stats + integer, intent(out) :: ierr + type(CCL_Hash_Grid_Type) :: grid + type(CCL_AABB_Type) :: aabb + real(c_double) :: cell_size + integer :: candidate_capacity + integer :: grid_capacity + integer :: i + + ierr = CCL_SUCCESS + candidate_count = 0 + call ccl_broad_phase_stats_reset(stats) + candidate_capacity = max(CCL_MIN_CANDIDATE_CAPACITY, max(1, particle_count * max(1, facet_count))) + allocate(candidates(candidate_capacity)) + if (particle_count == 0 .or. facet_count == 0) return + + cell_size = choose_contact_cell_size(particles, particle_count) + grid_capacity = max(1, facet_count * CCL_GRID_ENTRY_CAPACITY_PER_FACET) + call ccl_hash_grid_init(grid, cell_size, grid_capacity, ierr) + if (ierr /= CCL_SUCCESS) return + + do i = 1, facet_count + call ccl_facet_aabb(facets(i)%x, int(facets(i)%node_count), 0.0_c_double, aabb, ierr) + if (ierr /= CCL_SUCCESS) return + call ccl_hash_grid_insert_facet(grid, i, aabb, stats, ierr) + if (ierr /= CCL_SUCCESS) return + end do + + do i = 1, particle_count + call ccl_particle_aabb(particles(i)%x, particles(i)%contact_radius, aabb, ierr) + if (ierr /= CCL_SUCCESS) return + call ccl_hash_grid_query_particle(grid, i, aabb, candidates, candidate_count, & + size(candidates), stats, ierr) + if (ierr /= CCL_SUCCESS) return + end do + end subroutine run_broad_phase_search + + 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 + integer :: i + + cell_size = 1.0_c_double + do i = 1, particle_count + cell_size = max(cell_size, 2.0_c_double * max(0.0_c_double, particles(i)%contact_radius)) + end do + end function choose_contact_cell_size + + subroutine accumulate_narrow_stats(total_stats, step_stats) + type(CCL_Narrow_Phase_Stats_Type), intent(inout) :: total_stats + type(CCL_Narrow_Phase_Stats_Type), intent(in) :: step_stats + + total_stats%candidate_count = total_stats%candidate_count + step_stats%candidate_count + total_stats%contact_count = total_stats%contact_count + step_stats%contact_count + total_stats%skipped_separated_count = total_stats%skipped_separated_count + & + step_stats%skipped_separated_count + total_stats%skipped_degenerate_count = total_stats%skipped_degenerate_count + & + step_stats%skipped_degenerate_count + total_stats%skipped_invalid_count = total_stats%skipped_invalid_count + step_stats%skipped_invalid_count + end subroutine accumulate_narrow_stats + + subroutine accumulate_force_stats(total_stats, step_stats) + type(CCL_Contact_Force_Stats_Type), intent(inout) :: total_stats + type(CCL_Contact_Force_Stats_Type), intent(in) :: step_stats + + total_stats%contact_count = total_stats%contact_count + step_stats%contact_count + total_stats%nonfinite_force_count = total_stats%nonfinite_force_count + & + step_stats%nonfinite_force_count + total_stats%max_force_norm = max(total_stats%max_force_norm, step_stats%max_force_norm) + total_stats%total_sph_force = total_stats%total_sph_force + step_stats%total_sph_force + total_stats%total_fem_force = total_stats%total_fem_force + step_stats%total_fem_force + total_stats%total_sph_moment = total_stats%total_sph_moment + step_stats%total_sph_moment + total_stats%total_fem_moment = total_stats%total_fem_moment + step_stats%total_fem_moment + end subroutine accumulate_force_stats + + subroutine write_contact_loads(sph_worker, fem_worker, step_id, sph_forces, fem_loads, ierr) + type(CCL_Worker_Runtime), intent(inout) :: sph_worker + type(CCL_Worker_Runtime), intent(inout) :: fem_worker + integer, intent(in) :: step_id + type(CCL_SPH_Force_Accumulator_Type), intent(in) :: sph_forces + type(CCL_FEM_Load_Accumulator_Type), intent(in) :: fem_loads + integer, intent(out) :: ierr + integer :: i + + ierr = CCL_SUCCESS + if (sph_forces%count > int(CCL_LOAD_RECORD_CAPACITY) .or. & + fem_loads%count > int(CCL_LOAD_RECORD_CAPACITY)) then + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end if + if (.not. associated(sph_worker%sph_force_records) .or. & + .not. associated(fem_worker%fem_load_records)) then + ierr = CCL_ERROR_SYSTEM_INTERNAL + return + end if + + do i = 1, int(CCL_LOAD_RECORD_CAPACITY) + call clear_sph_force_record(sph_worker%sph_force_records(i)) + call clear_fem_load_record(fem_worker%fem_load_records(i)) + end do + do i = 1, sph_forces%count + sph_worker%sph_force_records(i) = sph_forces%records(i) + sph_worker%sph_force_records(i)%coupling_step = int(step_id, c_int32_t) + end do + do i = 1, fem_loads%count + fem_worker%fem_load_records(i) = fem_loads%records(i) + end do + + call ccl_prepare_sph_force_header(sph_worker%load_header, int(step_id, c_int32_t), & + int(sph_forces%count, c_int32_t), ierr) + if (ierr /= CCL_SUCCESS) return + call ccl_prepare_fem_load_header(fem_worker%load_header, int(step_id, c_int32_t), & + int(fem_loads%count, c_int32_t), ierr) + end subroutine write_contact_loads + + subroutine log_contact_step_diagnostics(diag, step_id, particle_count, facet_count, broad_stats, & + narrow_stats, force_stats, max_penetration) + type(CCL_Diagnostics_Type), intent(inout) :: diag + integer, intent(in) :: step_id + integer, intent(in) :: particle_count + integer, intent(in) :: facet_count + type(CCL_Broad_Phase_Stats_Type), intent(in) :: broad_stats + type(CCL_Narrow_Phase_Stats_Type), intent(in) :: narrow_stats + type(CCL_Contact_Force_Stats_Type), intent(in) :: force_stats + real(c_double), intent(in) :: max_penetration + character(len=384) :: msg + + write(msg, '(a,i0,a,i0,a,i0,a,i0,a,i0,a,i0)') "step=", step_id, & + " particles=", particle_count, " facets=", facet_count, & + " grid_cells=", broad_stats%grid_cell_count, " candidates=", broad_stats%candidate_count, & + " duplicate_candidates=", broad_stats%duplicate_candidate_count + call ccl_diagnostics_write_run(diag, "INFO", "contact_broad_phase", trim(msg)) + + write(msg, '(a,i0,a,i0,a,es16.8,a,i0,a,i0,a,i0,a,es16.8,a,es16.8)') "step=", step_id, & + " contacts=", force_stats%contact_count, " max_penetration=", max_penetration, & + " skipped_separated=", narrow_stats%skipped_separated_count, & + " skipped_degenerate=", narrow_stats%skipped_degenerate_count, & + " skipped_invalid=", narrow_stats%skipped_invalid_count, & + " force_balance=", force_stats%force_balance_error, & + " moment_balance=", force_stats%moment_balance_error + call ccl_diagnostics_write_run(diag, "INFO", "contact_narrow_force", trim(msg)) + end subroutine log_contact_step_diagnostics + + integer function find_surface_interaction_index(ccl_case, name) result(index_value) + type(CCL_Case_Type), intent(in) :: ccl_case + character(len=*), intent(in) :: name + integer :: i + + index_value = 0 + do i = 1, ccl_case%num_surface_interactions + if (same_name(ccl_case%surface_interaction(i)%name, name)) then + index_value = i + return + end if + end do + end function find_surface_interaction_index + subroutine send_worker_command(worker, command_id, step_id, dt, diag, ierr) type(CCL_Worker_Runtime), intent(inout) :: worker integer(c_int32_t), intent(in) :: command_id @@ -452,6 +838,10 @@ contains nullify(worker%command) nullify(worker%export_header) nullify(worker%load_header) + nullify(worker%sph_particle_records) + nullify(worker%fem_facet_records) + nullify(worker%sph_force_records) + nullify(worker%fem_load_records) end subroutine close_worker integer function compute_step_count(ccl_case) result(step_count) @@ -518,4 +908,25 @@ contains write(name, '(a,"_",a)') trim(prefix), trim(role) end subroutine make_name + logical function same_name(left, right) result(match) + character(len=*), intent(in) :: left + character(len=*), intent(in) :: right + + match = trim(to_upper_text(left)) == trim(to_upper_text(right)) + end function same_name + + character(len=len(text)) function to_upper_text(text) result(value) + character(len=*), intent(in) :: text + integer :: i + integer :: code + + value = text + do i = 1, len(text) + code = iachar(text(i:i)) + if (code >= iachar("a") .and. code <= iachar("z")) then + value(i:i) = achar(code - iachar("a") + iachar("A")) + end if + end do + end function to_upper_text + end module ccl_controller diff --git a/src/diagnostics/ccl_diagnostics.f90 b/src/diagnostics/ccl_diagnostics.f90 index 45108ff..8a65f22 100644 --- a/src/diagnostics/ccl_diagnostics.f90 +++ b/src/diagnostics/ccl_diagnostics.f90 @@ -1,5 +1,7 @@ module ccl_diagnostics use iso_fortran_env, only: error_unit + use iso_c_binding, only: c_double + use ccl_contact_narrow, only: CCL_Contact_Record_Type use ccl_errors, only: CCL_ERROR_SYSTEM_INTERNAL, CCL_SUCCESS use ccl_version, only: CCL_VERSION_LABEL implicit none @@ -9,6 +11,7 @@ module ccl_diagnostics integer :: log_unit = -1 integer :: ipc_unit = -1 integer :: force_unit = -1 + integer :: contact_unit = -1 logical :: is_open = .false. end type CCL_Diagnostics_Type @@ -48,10 +51,21 @@ contains return end if + open(newunit=diag%contact_unit, file=join_path(diag%output_dir, "contact_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" - write(diag%force_unit, '(a)') "step_id,sph_fx,sph_fy,sph_fz,fem_fx,fem_fy,fem_fz,total_fx,total_fy,total_fz" + write(diag%force_unit, '(a)') "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" + 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" 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)) @@ -89,25 +103,90 @@ contains flush(diag%ipc_unit) end subroutine ccl_diagnostics_write_ipc - subroutine ccl_diagnostics_write_force_balance(diag, step_id) + subroutine ccl_diagnostics_write_force_balance(diag, step_id, sph_force, fem_force, 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) type(CCL_Diagnostics_Type), intent(inout) :: diag integer, intent(in) :: step_id + real(c_double), intent(in), optional :: sph_force(3) + real(c_double), intent(in), optional :: fem_force(3) + integer, intent(in), optional :: num_contacts + real(c_double), intent(in), optional :: max_penetration + real(c_double), intent(in), optional :: total_contact_force_norm + real(c_double), intent(in), optional :: force_balance_error + real(c_double), intent(in), optional :: moment_balance_error + integer, intent(in), optional :: nonfinite_contact_count + integer, intent(in), optional :: skipped_separated_count + integer, intent(in), optional :: skipped_degenerate_count + integer, intent(in), optional :: skipped_invalid_count + real(c_double) :: sph_value(3) + real(c_double) :: fem_value(3) + real(c_double) :: total_value(3) + real(c_double) :: max_penetration_value + real(c_double) :: total_force_norm_value + real(c_double) :: force_balance_value + real(c_double) :: moment_balance_value + integer :: contact_count_value + integer :: nonfinite_value + integer :: skipped_separated_value + integer :: skipped_degenerate_value + integer :: skipped_invalid_value if (.not. diag%is_open .or. diag%force_unit == -1) return - write(diag%force_unit, '(i0,9(",",es16.8))') step_id, 0.0d0, 0.0d0, 0.0d0, & - 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0, 0.0d0 + sph_value = 0.0_c_double + fem_value = 0.0_c_double + contact_count_value = 0 + max_penetration_value = 0.0_c_double + total_force_norm_value = 0.0_c_double + force_balance_value = 0.0_c_double + moment_balance_value = 0.0_c_double + nonfinite_value = 0 + skipped_separated_value = 0 + skipped_degenerate_value = 0 + skipped_invalid_value = 0 + if (present(sph_force)) sph_value = sph_force + if (present(fem_force)) fem_value = fem_force + if (present(num_contacts)) contact_count_value = num_contacts + if (present(max_penetration)) max_penetration_value = max_penetration + if (present(total_contact_force_norm)) total_force_norm_value = total_contact_force_norm + if (present(force_balance_error)) force_balance_value = force_balance_error + if (present(moment_balance_error)) moment_balance_value = moment_balance_error + if (present(nonfinite_contact_count)) nonfinite_value = nonfinite_contact_count + if (present(skipped_separated_count)) skipped_separated_value = skipped_separated_count + if (present(skipped_degenerate_count)) skipped_degenerate_value = skipped_degenerate_count + if (present(skipped_invalid_count)) skipped_invalid_value = skipped_invalid_count + total_value = sph_value + fem_value + write(diag%force_unit, '(i0,9(",",es16.8),",",i0,4(",",es16.8),4(",",i0))') step_id, & + sph_value(1), sph_value(2), sph_value(3), fem_value(1), fem_value(2), fem_value(3), & + total_value(1), total_value(2), total_value(3), contact_count_value, max_penetration_value, & + total_force_norm_value, force_balance_value, moment_balance_value, nonfinite_value, & + skipped_separated_value, skipped_degenerate_value, skipped_invalid_value flush(diag%force_unit) end subroutine ccl_diagnostics_write_force_balance + subroutine ccl_diagnostics_write_contact(diag, contact) + type(CCL_Diagnostics_Type), intent(inout) :: diag + type(CCL_Contact_Record_Type), intent(in) :: contact + + if (.not. diag%is_open .or. diag%contact_unit == -1) return + write(diag%contact_unit, '(i0,",",i0,",",i0,",",i0,8(",",es16.8),",",i0)') & + contact%step_id, contact%pair_id, contact%sph_external_id, contact%facet_id, & + contact%gap, contact%penetration, contact%normal(1), contact%normal(2), contact%normal(3), & + contact%force(1), contact%force(2), contact%force(3), contact%node_count + flush(diag%contact_unit) + end subroutine ccl_diagnostics_write_contact + subroutine ccl_diagnostics_close(diag) type(CCL_Diagnostics_Type), intent(inout) :: diag if (diag%log_unit /= -1) close(diag%log_unit) 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) diag%log_unit = -1 diag%ipc_unit = -1 diag%force_unit = -1 + diag%contact_unit = -1 diag%is_open = .false. end subroutine ccl_diagnostics_close diff --git a/src/ipc/ccl_ipc.f90 b/src/ipc/ccl_ipc.f90 index 729d503..3b7209a 100644 --- a/src/ipc/ccl_ipc.f90 +++ b/src/ipc/ccl_ipc.f90 @@ -36,6 +36,12 @@ module ccl_ipc type(c_ptr), value :: handle end function ccl_ipc_shm_close_c + type(c_ptr) function ccl_ipc_ptr_offset_c(base, byte_offset) bind(C, name="ccl_ipc_ptr_offset") + import :: c_ptr, c_size_t + type(c_ptr), value :: base + integer(c_size_t), value :: byte_offset + end function ccl_ipc_ptr_offset_c + integer(c_int) function ccl_ipc_event_create_c(name, initial_state, out_handle) & bind(C, name="ccl_ipc_event_create") import :: c_char, c_int, c_ptr @@ -112,6 +118,25 @@ contains shm%byte_size = 0_c_size_t end subroutine ccl_shm_close + subroutine ccl_ptr_offset(base, byte_offset, ptr, ierr) + type(c_ptr), intent(in) :: base + integer(c_size_t), intent(in) :: byte_offset + type(c_ptr), intent(out) :: ptr + integer, intent(out) :: ierr + + if (.not. c_associated(base)) then + ptr = c_null_ptr + ierr = 2005 + return + end if + ptr = ccl_ipc_ptr_offset_c(base, byte_offset) + if (c_associated(ptr)) then + ierr = 0 + else + ierr = 2005 + end if + end subroutine ccl_ptr_offset + subroutine ccl_event_create(name, initial_state, event, ierr) character(len=*), intent(in) :: name logical, intent(in) :: initial_state diff --git a/src/ipc/cclite_ipc_win.c b/src/ipc/cclite_ipc_win.c index 5428f70..332c400 100644 --- a/src/ipc/cclite_ipc_win.c +++ b/src/ipc/cclite_ipc_win.c @@ -2,6 +2,14 @@ #include +void *ccl_ipc_ptr_offset(void *base, size_t byte_offset) +{ + if (base == NULL) { + return NULL; + } + return (void *)((unsigned char *)base + byte_offset); +} + #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include diff --git a/src/mock_workers/ccl_mock_worker.f90 b/src/mock_workers/ccl_mock_worker.f90 index 6b4f481..ebe9525 100644 --- a/src/mock_workers/ccl_mock_worker.f90 +++ b/src/mock_workers/ccl_mock_worker.f90 @@ -1,5 +1,5 @@ module ccl_mock_worker - use iso_c_binding, only: c_f_pointer, c_int32_t, c_int64_t, c_size_t + use iso_c_binding, only: c_double, c_f_pointer, c_int32_t, c_int64_t, c_ptr, c_size_t use ccl_command_block, only: CCL_CMD_ADVANCE, CCL_CMD_BUILD_MODEL, CCL_CMD_EXPORT_INTERFACE, & CCL_CMD_IMPORT_LOADS, CCL_CMD_INIT, CCL_CMD_READ_INPUT, CCL_CMD_STOP, CCL_CMD_WRITE_OUTPUT, & CCL_Command_Block_Type, CCL_SOLVER_ID_FEM, CCL_SOLVER_ID_SPH, CCL_WORKER_DONE, & @@ -8,12 +8,14 @@ module ccl_mock_worker use ccl_data_block, only: CCL_BUFFER_CONSUMED, CCL_BUFFER_READY, CCL_BUFFER_READING, & CCL_BUFFER_WRITING, CCL_Data_Block_Header_Type, CCL_ROLE_CCL_TO_FEM_LOAD, & CCL_ROLE_CCL_TO_SPH_FORCE, CCL_ROLE_FEM_TO_CCL_FACET, CCL_ROLE_SPH_TO_CCL_PARTICLE, & - ccl_data_header_init, ccl_data_header_set_count, ccl_data_header_set_state, & - ccl_data_header_size, ccl_data_header_validate, ccl_data_record_size_for_role + CCL_FEM_Facet_Record_Type, CCL_FEM_Load_Record_Type, CCL_SPH_Force_Record_Type, & + CCL_SPH_Particle_Record_Type, ccl_data_header_init, 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_errors, only: CCL_ERROR_INPUT_INVALID_VALUE, CCL_ERROR_IPC_BAD_HEADER, & CCL_ERROR_IPC_TIMEOUT, CCL_SUCCESS use ccl_ipc, only: CCL_Named_Event, CCL_Shared_Memory, ccl_event_close, ccl_event_open, & - ccl_event_reset, ccl_event_signal, ccl_event_wait, ccl_shm_close, ccl_shm_open + ccl_event_reset, ccl_event_signal, ccl_event_wait, ccl_ptr_offset, ccl_shm_close, ccl_shm_open use ccl_log, only: ccl_log_info use ccl_version, only: CCL_VERSION_LABEL implicit none @@ -33,6 +35,7 @@ module ccl_mock_worker type :: CCL_Mock_Worker_Runtime character(len=16) :: solver_name = "" character(len=256) :: prefix = "" + character(len=256) :: input_file = "" character(len=256) :: command_name = "" character(len=256) :: command_event_name = "" character(len=256) :: ack_event_name = "" @@ -42,6 +45,7 @@ module ccl_mock_worker integer(c_int32_t) :: export_role = 0_c_int32_t integer(c_int32_t) :: load_role = 0_c_int32_t integer :: timeout_ms = 5000 + logical :: export_contact_fixture = .false. type(CCL_Shared_Memory) :: command_shm type(CCL_Shared_Memory) :: export_shm type(CCL_Shared_Memory) :: load_shm @@ -50,6 +54,10 @@ module ccl_mock_worker type(CCL_Command_Block_Type), pointer :: command => null() type(CCL_Data_Block_Header_Type), pointer :: export_header => null() type(CCL_Data_Block_Header_Type), pointer :: load_header => null() + type(CCL_SPH_Particle_Record_Type), pointer :: sph_particles(:) => null() + type(CCL_FEM_Facet_Record_Type), pointer :: fem_facets(:) => null() + type(CCL_SPH_Force_Record_Type), pointer :: sph_forces(:) => null() + type(CCL_FEM_Load_Record_Type), pointer :: fem_loads(:) => null() end type CCL_Mock_Worker_Runtime contains @@ -174,7 +182,9 @@ contains ierr = CCL_SUCCESS runtime%solver_name = trim(config%solver_name) runtime%prefix = trim(config%prefix) + runtime%input_file = trim(config%input_file) runtime%timeout_ms = config%timeout_ms + runtime%export_contact_fixture = is_contact_fixture(runtime%input_file) if (len_trim(runtime%prefix) == 0) then ierr = CCL_ERROR_INPUT_INVALID_VALUE return @@ -226,12 +236,46 @@ contains call ccl_shm_open(runtime%load_name, load_bytes, runtime%load_shm, ierr) if (ierr /= CCL_SUCCESS) return call c_f_pointer(runtime%load_shm%payload, runtime%load_header) + call map_runtime_payloads(runtime, ierr) + if (ierr /= CCL_SUCCESS) return call ccl_event_open(runtime%command_event_name, runtime%command_event, ierr) if (ierr /= CCL_SUCCESS) return call ccl_event_open(runtime%ack_event_name, runtime%ack_event, ierr) end subroutine open_runtime_resources + subroutine map_runtime_payloads(runtime, ierr) + type(CCL_Mock_Worker_Runtime), intent(inout) :: runtime + integer, intent(out) :: ierr + type(c_ptr) :: payload + integer :: shape(1) + + shape = [int(CCL_EXPORT_RECORD_CAPACITY)] + call ccl_ptr_offset(runtime%export_shm%payload, int(ccl_data_header_size(), c_size_t), payload, ierr) + if (ierr /= CCL_SUCCESS) return + select case (runtime%export_role) + case (CCL_ROLE_SPH_TO_CCL_PARTICLE) + call c_f_pointer(payload, runtime%sph_particles, shape) + case (CCL_ROLE_FEM_TO_CCL_FACET) + call c_f_pointer(payload, runtime%fem_facets, shape) + case default + ierr = CCL_ERROR_IPC_BAD_HEADER + return + end select + + shape = [int(CCL_LOAD_RECORD_CAPACITY)] + call ccl_ptr_offset(runtime%load_shm%payload, int(ccl_data_header_size(), c_size_t), payload, ierr) + if (ierr /= CCL_SUCCESS) return + select case (runtime%load_role) + case (CCL_ROLE_CCL_TO_SPH_FORCE) + call c_f_pointer(payload, runtime%sph_forces, shape) + case (CCL_ROLE_CCL_TO_FEM_LOAD) + call c_f_pointer(payload, runtime%fem_loads, shape) + case default + ierr = CCL_ERROR_IPC_BAD_HEADER + end select + end subroutine map_runtime_payloads + subroutine signal_worker_ready(runtime, ierr) type(CCL_Mock_Worker_Runtime), intent(inout) :: runtime integer, intent(out) :: ierr @@ -298,7 +342,7 @@ contains case (CCL_CMD_INIT, CCL_CMD_READ_INPUT, CCL_CMD_BUILD_MODEL, CCL_CMD_ADVANCE, CCL_CMD_WRITE_OUTPUT) ierr = CCL_SUCCESS case (CCL_CMD_EXPORT_INTERFACE) - call export_empty_block(runtime, ierr) + call export_interface_block(runtime, ierr) case (CCL_CMD_IMPORT_LOADS) call consume_load_block(runtime, ierr) case (CCL_CMD_STOP) @@ -308,19 +352,134 @@ contains end select end subroutine handle_command - subroutine export_empty_block(runtime, ierr) + subroutine export_interface_block(runtime, ierr) type(CCL_Mock_Worker_Runtime), intent(inout) :: runtime integer, intent(out) :: ierr + integer(c_int32_t) :: item_count call ccl_data_header_init(runtime%export_header, runtime%export_role, runtime%solver_id, & CCL_SOLVER_ID_CCL, CCL_EXPORT_RECORD_CAPACITY) runtime%export_header%step_id = int(runtime%command%step_id, c_int32_t) call ccl_data_header_set_state(runtime%export_header, CCL_BUFFER_WRITING, ierr) if (ierr /= CCL_SUCCESS) return - call ccl_data_header_set_count(runtime%export_header, 0_c_int32_t, ierr) + item_count = 0_c_int32_t + if (runtime%export_contact_fixture) then + select case (runtime%export_role) + case (CCL_ROLE_SPH_TO_CCL_PARTICLE) + call write_sph_contact_fixture(runtime, item_count, ierr) + if (ierr /= CCL_SUCCESS) return + case (CCL_ROLE_FEM_TO_CCL_FACET) + call write_fem_contact_fixture(runtime, item_count, ierr) + if (ierr /= CCL_SUCCESS) return + end select + end if + call ccl_data_header_set_count(runtime%export_header, item_count, ierr) if (ierr /= CCL_SUCCESS) return call ccl_data_header_set_state(runtime%export_header, CCL_BUFFER_READY, ierr) - end subroutine export_empty_block + end subroutine export_interface_block + + subroutine write_sph_contact_fixture(runtime, item_count, ierr) + type(CCL_Mock_Worker_Runtime), intent(inout) :: runtime + integer(c_int32_t), intent(out) :: item_count + integer, intent(out) :: ierr + + ierr = CCL_SUCCESS + item_count = 0_c_int32_t + if (.not. associated(runtime%sph_particles)) then + 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 + end subroutine write_sph_contact_fixture + + 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 + integer, intent(out) :: ierr + + ierr = CCL_SUCCESS + item_count = 0_c_int32_t + if (.not. associated(runtime%fem_facets)) then + ierr = CCL_ERROR_IPC_BAD_HEADER + return + end if + call clear_fem_facet_record(runtime%fem_facets(1)) + runtime%fem_facets(1)%facet_id = 201_c_int64_t + runtime%fem_facets(1)%elem_id = 1_c_int64_t + runtime%fem_facets(1)%face_id = 1_c_int32_t + runtime%fem_facets(1)%node_count = 4_c_int32_t + runtime%fem_facets(1)%surface_id = 1_c_int64_t + runtime%fem_facets(1)%valid_flags = 1_c_int32_t + runtime%fem_facets(1)%node_ids(1:4) = [201_c_int64_t, 202_c_int64_t, 203_c_int64_t, 204_c_int64_t] + runtime%fem_facets(1)%area = 1.0_c_double + runtime%fem_facets(1)%thickness = 0.0_c_double + runtime%fem_facets(1)%normal = [0.0_c_double, 0.0_c_double, 1.0_c_double] + runtime%fem_facets(1)%x(:, 1) = [0.0_c_double, 0.0_c_double, 0.0_c_double] + runtime%fem_facets(1)%x(:, 2) = [1.0_c_double, 0.0_c_double, 0.0_c_double] + runtime%fem_facets(1)%x(:, 3) = [1.0_c_double, 1.0_c_double, 0.0_c_double] + runtime%fem_facets(1)%x(:, 4) = [0.0_c_double, 1.0_c_double, 0.0_c_double] + runtime%fem_facets(1)%v = 0.0_c_double + item_count = 1_c_int32_t + end subroutine write_fem_contact_fixture + + subroutine clear_sph_particle_record(record) + type(CCL_SPH_Particle_Record_Type), intent(out) :: record + + record%external_id = 0_c_int64_t + record%internal_index = 0_c_int32_t + record%phase = 0_c_int32_t + record%status = 0_c_int32_t + record%material_id = 0_c_int32_t + record%section_id = 0_c_int32_t + record%valid_flags = 0_c_int32_t + record%reserved_i4 = 0_c_int32_t + record%mass = 0.0_c_double + record%volume = 0.0_c_double + record%density = 0.0_c_double + record%pressure = 0.0_c_double + record%internal_energy = 0.0_c_double + record%temperature = 0.0_c_double + record%h = 0.0_c_double + record%smoothing_length = 0.0_c_double + record%contact_radius = 0.0_c_double + record%sound_speed = 0.0_c_double + record%x = 0.0_c_double + record%v = 0.0_c_double + record%a = 0.0_c_double + end subroutine clear_sph_particle_record + + subroutine clear_fem_facet_record(record) + type(CCL_FEM_Facet_Record_Type), intent(out) :: record + + record%facet_id = 0_c_int64_t + record%elem_id = 0_c_int64_t + record%face_id = 0_c_int32_t + record%node_count = 0_c_int32_t + record%element_type = 0_c_int32_t + record%surface_type = 0_c_int32_t + record%surface_id = 0_c_int64_t + record%valid_flags = 0_c_int32_t + record%reserved_i4 = 0_c_int32_t + record%node_ids = 0_c_int64_t + record%area = 0.0_c_double + record%thickness = 0.0_c_double + record%shell_thickness = 0.0_c_double + record%mass_per_area = 0.0_c_double + record%normal = 0.0_c_double + record%x = 0.0_c_double + record%v = 0.0_c_double + end subroutine clear_fem_facet_record subroutine consume_load_block(runtime, ierr) type(CCL_Mock_Worker_Runtime), intent(inout) :: runtime @@ -356,8 +515,34 @@ contains nullify(runtime%command) nullify(runtime%export_header) nullify(runtime%load_header) + nullify(runtime%sph_particles) + nullify(runtime%fem_facets) + nullify(runtime%sph_forces) + nullify(runtime%fem_loads) end subroutine close_runtime + logical function is_contact_fixture(text) result(enabled) + character(len=*), intent(in) :: text + character(len=len(text)) :: upper + + upper = to_upper_text(text) + enabled = index(upper, "CONTACT") > 0 .or. index(upper, "WALL") > 0 + end function is_contact_fixture + + character(len=len(text)) function to_upper_text(text) result(value) + character(len=*), intent(in) :: text + integer :: i + integer :: code + + value = text + do i = 1, len(text) + code = iachar(text(i:i)) + if (code >= iachar("a") .and. code <= iachar("z")) then + value(i:i) = achar(code - iachar("a") + iachar("A")) + end if + end do + end function to_upper_text + integer(c_size_t) function data_block_bytes(block_role, capacity) result(byte_size) integer(c_int32_t), intent(in) :: block_role integer(c_int32_t), intent(in) :: capacity diff --git a/tests/data/v020_contact_run.inp b/tests/data/v020_contact_run.inp new file mode 100644 index 0000000..86c7c66 --- /dev/null +++ b/tests/data/v020_contact_run.inp @@ -0,0 +1,39 @@ +** CCLite 0.2.7 contact controller run case. +*CCLITE CONTROL, NAME=V020_CONTACT_RUN, 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_RUN +BUFFER=DOUBLE +TIMEOUT_MS=5000 + +*CCLITE TIME +START=0.0 +END=2.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_contact_run +CSV=YES +LOG=YES diff --git a/tests/unit/test_contact_force.f90 b/tests/unit/test_contact_force.f90 index e8569cb..d387e02 100644 --- a/tests/unit/test_contact_force.f90 +++ b/tests/unit/test_contact_force.f90 @@ -35,6 +35,7 @@ program test_contact_force call require_equal(sph_forces%count, 1, "SPH force count") call require_equal(fem_loads%count, 4, "FEM nodal load count") call require_real_close(sph_forces%records(1)%force(3), 20.0_c_double, "SPH penalty damping force") + call require_real_close(contacts(1)%force(3), 20.0_c_double, "contact force") call require_real_close(stats%total_sph_force(3), 20.0_c_double, "total SPH force") call require_real_close(stats%total_fem_force(3), -20.0_c_double, "total FEM force") call require_real_close(stats%force_balance_error, 0.0_c_double, "force balance") diff --git a/todo.md b/todo.md index 836ae7b..49cf4f6 100644 --- a/todo.md +++ b/todo.md @@ -304,40 +304,40 @@ 目标:把接触算法插入 0.1.x step loop,并形成可自动检查的诊断输出。 -- [ ] T0207-01 区分 dry-run 与 contact run。 +- [x] T0207-01 区分 dry-run 与 contact run。 完成判据:无 contact pair 时可保持 dry-run,定义 contact pair 时进入接触路径。 -- [ ] T0207-02 在 step loop 中读取 SPH/FEM interface block。 +- [x] T0207-02 在 step loop 中读取 SPH/FEM interface block。 完成判据:每步接触计算前 view 来自当前 step 的 worker 导出数据。 -- [ ] T0207-03 在 step loop 中调用宽相搜索。 +- [x] T0207-03 在 step loop 中调用宽相搜索。 完成判据:每步生成 candidate 数并写入诊断。 -- [ ] T0207-04 在 step loop 中调用窄相接触。 +- [x] T0207-04 在 step loop 中调用窄相接触。 完成判据:每步生成 contact 数、最大穿透和跳过计数。 -- [ ] T0207-05 在 step loop 中调用 penalty force。 +- [x] T0207-05 在 step loop 中调用 penalty force。 完成判据:接触力写入 accumulator,非接触 step 输出零载荷。 -- [ ] T0207-06 在写回载荷后发送 `IMPORT_LOADS`。 +- [x] T0207-06 在写回载荷后发送 `IMPORT_LOADS`。 完成判据:SPH/FEM worker 均能确认载荷导入命令。 -- [ ] T0207-07 在 `ADVANCE` 前后保持 seq/ack 正确。 +- [x] T0207-07 在 `ADVANCE` 前后保持 seq/ack 正确。 完成判据:0.1.x IPC 报告中的 command seq/ack 不退化。 -- [ ] T0207-08 每步清零接触和载荷 accumulator。 +- [x] T0207-08 每步清零接触和载荷 accumulator。 完成判据:连续 step 不会继承上一 step 的 contact、force 或 load。 -- [ ] T0207-09 异常时停止两个 worker 并释放资源。 +- [x] T0207-09 异常时停止两个 worker 并释放资源。 完成判据:接触算法错误、输入错误或 worker 超时后无残留进程和未释放 IPC。 -- [ ] T0207-10 增强 `contact_report.csv`。 +- [x] T0207-10 增强 `contact_report.csv`。 完成判据:包含 gap、penetration、normal、force 和 node_count 字段。 -- [ ] T0207-11 增强 `force_balance.csv`。 +- [x] T0207-11 增强 `force_balance.csv`。 完成判据:增加接触数、最大穿透、总接触力、力矩误差和非有限计数。 -- [ ] T0207-12 增强 `run.log` 接触诊断。 +- [x] T0207-12 增强 `run.log` 接触诊断。 完成判据:输入、view、搜索、接触、力计算和写回错误均可定位。 # 10. 0.2.8 验证算例与 Python Checker