From 7d460992431df9872395e8e2f081e0af751e58e2 Mon Sep 17 00:00:00 2001 From: Xiangyu Date: Wed, 5 Feb 2025 18:29:55 +0100 Subject: [PATCH 01/33] naming --- .../{io_vtk_fvm_2d.cpp => io_vtk_mesh_2d.cpp} | 8 +++--- .../{io_vtk_fvm_3d.cpp => io_vtk_mesh_3d.cpp} | 8 +++--- src/shared/io_system/io_all.h | 2 +- .../{io_vtk_fvm.cpp => io_vtk_mesh.cpp} | 8 +++--- .../io_system/{io_vtk_fvm.h => io_vtk_mesh.h} | 25 ++++++++++--------- .../2d_FVM_double_mach_reflection.cpp | 2 +- .../CMakeLists.txt | 2 +- .../2d_FVM_flow_around_cylinder.cpp | 6 ++--- ...est_3d_FVM_incompressible_channel_flow.cpp | 2 +- .../test_2d_FVM_turbulent_channelflow.cpp | 17 ++++++------- 10 files changed, 40 insertions(+), 40 deletions(-) rename src/for_2D_build/io_system/{io_vtk_fvm_2d.cpp => io_vtk_mesh_2d.cpp} (91%) rename src/for_3D_build/io_system/{io_vtk_fvm_3d.cpp => io_vtk_mesh_3d.cpp} (87%) rename src/shared/io_system/{io_vtk_fvm.cpp => io_vtk_mesh.cpp} (72%) rename src/shared/io_system/{io_vtk_fvm.h => io_vtk_mesh.h} (79%) diff --git a/src/for_2D_build/io_system/io_vtk_fvm_2d.cpp b/src/for_2D_build/io_system/io_vtk_mesh_2d.cpp similarity index 91% rename from src/for_2D_build/io_system/io_vtk_fvm_2d.cpp rename to src/for_2D_build/io_system/io_vtk_mesh_2d.cpp index 661e56eed5..b5c69620f4 100644 --- a/src/for_2D_build/io_system/io_vtk_fvm_2d.cpp +++ b/src/for_2D_build/io_system/io_vtk_mesh_2d.cpp @@ -1,9 +1,9 @@ #include "io_vtk.hpp" -#include "io_vtk_fvm.h" +#include "io_vtk_mesh.h" namespace SPH { //=================================================================================================// -void BodyStatesRecordingInMeshToVtp::writeWithFileName(const std::string &sequence) +void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence) { for (SPHBody *body : bodies_) { @@ -83,10 +83,10 @@ void BodyStatesRecordingInMeshToVtp::writeWithFileName(const std::string &sequen } } //=================================================================================================// -void BodyStatesRecordingInMeshToVtu::writeWithFileName(const std::string &sequence) +void BodyStatesRecordingToMeshVtu::writeWithFileName(const std::string &sequence) { std::cout << "For 2D build:" - << "The method BodyStatesRecordingInMeshToVtu::writeWithFileName not implemented yet." + << "The method BodyStatesRecordingToMeshVtu::writeWithFileName not implemented yet." << std::endl; exit(1); } diff --git a/src/for_3D_build/io_system/io_vtk_fvm_3d.cpp b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp similarity index 87% rename from src/for_3D_build/io_system/io_vtk_fvm_3d.cpp rename to src/for_3D_build/io_system/io_vtk_mesh_3d.cpp index 998d17ec2c..3b34e05724 100644 --- a/src/for_3D_build/io_system/io_vtk_fvm_3d.cpp +++ b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp @@ -1,11 +1,11 @@ #include "io_vtk.hpp" -#include "io_vtk_fvm.h" +#include "io_vtk_mesh.h" #include "mesh_helper.h" namespace SPH { //=================================================================================================// -void BodyStatesRecordingInMeshToVtu::writeWithFileName(const std::string &sequence) +void BodyStatesRecordingToMeshVtu::writeWithFileName(const std::string &sequence) { for (SPHBody *body : bodies_) { @@ -47,10 +47,10 @@ void BodyStatesRecordingInMeshToVtu::writeWithFileName(const std::string &sequen } } //=================================================================================================// -void BodyStatesRecordingInMeshToVtp::writeWithFileName(const std::string &sequence) +void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence) { std::cout << "For 3D build:" - << "The method BodyStatesRecordingInMeshToVtp::writeWithFileName not implemented yet." + << "The method BodyStatesRecordingToMeshVtp::writeWithFileName not implemented yet." << std::endl; exit(1); } diff --git a/src/shared/io_system/io_all.h b/src/shared/io_system/io_all.h index 066a8153ba..482a9304d1 100644 --- a/src/shared/io_system/io_all.h +++ b/src/shared/io_system/io_all.h @@ -32,6 +32,6 @@ io class used in SPHinXsys. **/ #include "io_plt.h" #include "io_simbody.h" #include "io_vtk.h" -#include "io_vtk_fvm.h" +#include "io_vtk_mesh.h" #endif // IO_ALL_H diff --git a/src/shared/io_system/io_vtk_fvm.cpp b/src/shared/io_system/io_vtk_mesh.cpp similarity index 72% rename from src/shared/io_system/io_vtk_fvm.cpp rename to src/shared/io_system/io_vtk_mesh.cpp index f3ecec2794..4207b40f8a 100644 --- a/src/shared/io_system/io_vtk_fvm.cpp +++ b/src/shared/io_system/io_vtk_mesh.cpp @@ -1,14 +1,14 @@ -#include "io_vtk_fvm.h" +#include "io_vtk_mesh.h" namespace SPH { //=================================================================================================// -BodyStatesRecordingInMeshToVtp::BodyStatesRecordingInMeshToVtp(SPHBody &body, ANSYSMesh &ansys_mesh) +BodyStatesRecordingToMeshVtp::BodyStatesRecordingToMeshVtp(SPHBody &body, ANSYSMesh &ansys_mesh) : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), elements_nodes_connection_(ansys_mesh.elements_nodes_connection_) {} //=================================================================================================// -BodyStatesRecordingInMeshToVtu::BodyStatesRecordingInMeshToVtu(SPHBody &body, ANSYSMesh &ansys_mesh) +BodyStatesRecordingToMeshVtu::BodyStatesRecordingToMeshVtu(SPHBody &body, ANSYSMesh &ansys_mesh) : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), - elements_nodes_connection_(ansys_mesh.elements_nodes_connection_), bounds_(body){}; + elements_nodes_connection_(ansys_mesh.elements_nodes_connection_), bounds_(body) {}; //=================================================================================================// } // namespace SPH diff --git a/src/shared/io_system/io_vtk_fvm.h b/src/shared/io_system/io_vtk_mesh.h similarity index 79% rename from src/shared/io_system/io_vtk_fvm.h rename to src/shared/io_system/io_vtk_mesh.h index f017a3a249..6410a853c7 100644 --- a/src/shared/io_system/io_vtk_fvm.h +++ b/src/shared/io_system/io_vtk_mesh.h @@ -21,13 +21,13 @@ * * * ------------------------------------------------------------------------- */ /** - * @file io_vtk_fvm.h + * @file io_vtk_mesh.h * @brief Classes for input and output with vtk (Paraview) for FVM unstructured mesh. * @author Xiangyu Hu */ -#ifndef IO_VTK_FVM_H -#define IO_VTK_FVM_H +#ifndef IO_VTK_MESH_H +#define IO_VTK_MESH_H #include "io_vtk.h" #include "unstructured_mesh.h" @@ -35,15 +35,16 @@ namespace SPH { /** - * @class BodyStatesRecordingInMeshToVtp + * @class BodyStatesRecordingToMeshVtp * @brief Write files for bodies - * the output file is VTK XML format in FVMcan visualized by ParaView the data type vtkPolyData + * the output file is VTK XML format can be visualized by ParaView + * with the data type vtkPolyData */ -class BodyStatesRecordingInMeshToVtp : public BodyStatesRecordingToVtp +class BodyStatesRecordingToMeshVtp : public BodyStatesRecordingToVtp { public: - BodyStatesRecordingInMeshToVtp(SPHBody &body, ANSYSMesh &ansys_mesh); - virtual ~BodyStatesRecordingInMeshToVtp(){}; + BodyStatesRecordingToMeshVtp(SPHBody &body, ANSYSMesh &ansys_mesh); + virtual ~BodyStatesRecordingToMeshVtp() {}; protected: virtual void writeWithFileName(const std::string &sequence) override; @@ -51,11 +52,11 @@ class BodyStatesRecordingInMeshToVtp : public BodyStatesRecordingToVtp StdLargeVec> &elements_nodes_connection_; }; -class BodyStatesRecordingInMeshToVtu : public BodyStatesRecordingToVtp +class BodyStatesRecordingToMeshVtu : public BodyStatesRecordingToVtp { public: - BodyStatesRecordingInMeshToVtu(SPHBody &body, ANSYSMesh &ansys_mesh); - virtual ~BodyStatesRecordingInMeshToVtu(){}; + BodyStatesRecordingToMeshVtu(SPHBody &body, ANSYSMesh &ansys_mesh); + virtual ~BodyStatesRecordingToMeshVtu() {}; protected: virtual void writeWithFileName(const std::string &sequence) override; @@ -64,4 +65,4 @@ class BodyStatesRecordingInMeshToVtu : public BodyStatesRecordingToVtp SPHBody &bounds_; }; } // namespace SPH -#endif // IO_VTK_FVM_H +#endif // IO_VTK_MESH_H diff --git a/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp b/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp index a7087759a7..883c936bce 100644 --- a/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp +++ b/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp @@ -46,7 +46,7 @@ int main(int ac, char *av[]) // Define the methods for I/O operations, observations // and regression tests of the simulation. //---------------------------------------------------------------------- - BodyStatesRecordingInMeshToVtp write_real_body_states(wave_block, ansys_mesh); + BodyStatesRecordingToMeshVtp write_real_body_states(wave_block, ansys_mesh); write_real_body_states.addToWrite(wave_block, "Density"); write_real_body_states.addToWrite(wave_block, "Pressure"); RegressionTestEnsembleAverage> write_maximum_speed(wave_block); diff --git a/tests/2d_examples/test_2d_FVM_double_mach_reflection/CMakeLists.txt b/tests/2d_examples/test_2d_FVM_double_mach_reflection/CMakeLists.txt index de8fa92f03..3a6186d260 100644 --- a/tests/2d_examples/test_2d_FVM_double_mach_reflection/CMakeLists.txt +++ b/tests/2d_examples/test_2d_FVM_double_mach_reflection/CMakeLists.txt @@ -25,4 +25,4 @@ set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY " add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME} --state_recording=${TEST_STATE_RECORDING} WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) -set_tests_properties(${PROJECT_NAME} PROPERTIES LABELS "compressible flow, Eulerian") +set_tests_properties(${PROJECT_NAME} PROPERTIES LABELS "compressible flow, Eulerian, FVM") diff --git a/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp b/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp index 062e0599bd..0b8c5414fa 100644 --- a/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp +++ b/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp @@ -58,8 +58,8 @@ class FACBoundaryConditionSetup : public BoundaryConditionSetupInFVM public: FACBoundaryConditionSetup(BaseInnerRelationInFVM &inner_relation, GhostCreationFromMesh &ghost_creation) : BoundaryConditionSetupInFVM(inner_relation, ghost_creation), - fluid_(DynamicCast(this, particles_->getBaseMaterial())){}; - virtual ~FACBoundaryConditionSetup(){}; + fluid_(DynamicCast(this, particles_->getBaseMaterial())) {}; + virtual ~FACBoundaryConditionSetup() {}; void applyNonSlipWallBoundary(size_t ghost_index, size_t index_i) override { @@ -125,7 +125,7 @@ int main(int ac, char *av[]) //---------------------------------------------------------------------- // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- - BodyStatesRecordingInMeshToVtp write_real_body_states(water_block, ansys_mesh); + BodyStatesRecordingToMeshVtp write_real_body_states(water_block, ansys_mesh); write_real_body_states.addToWrite(water_block, "Density"); RegressionTestDynamicTimeWarping>> write_total_viscous_force_on_inserted_body(water_block, "ViscousForceOnSolid"); ReducedQuantityRecording> write_total_pressure_force_on_inserted_body(water_block, "PressureForceOnSolid"); diff --git a/tests/3d_examples/test_3d_FVM_incompressible_channel_flow/test_3d_FVM_incompressible_channel_flow.cpp b/tests/3d_examples/test_3d_FVM_incompressible_channel_flow/test_3d_FVM_incompressible_channel_flow.cpp index 0b3c4905df..407932c357 100644 --- a/tests/3d_examples/test_3d_FVM_incompressible_channel_flow/test_3d_FVM_incompressible_channel_flow.cpp +++ b/tests/3d_examples/test_3d_FVM_incompressible_channel_flow/test_3d_FVM_incompressible_channel_flow.cpp @@ -45,7 +45,7 @@ int main(int ac, char *av[]) /** Boundary conditions set up */ InvCFBoundaryConditionSetup boundary_condition_setup(air_block_inner, ghost_creation); //---------------------------------------------------------------------- - BodyStatesRecordingInMeshToVtu write_real_body_states(air_block, read_mesh_data); + BodyStatesRecordingToMeshVtu write_real_body_states(air_block, read_mesh_data); write_real_body_states.addToWrite(air_block, "Density"); write_real_body_states.addToWrite(air_block, "Pressure"); ReducedQuantityRecording write_maximum_speed(air_block); diff --git a/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp b/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp index f824ddb06f..81ecc9044a 100644 --- a/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp +++ b/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp @@ -42,20 +42,19 @@ int main(int ac, char *av[]) InteractionWithUpdate density_relaxation(water_block_inner, 10000.0); SimpleDynamics initial_condition(water_block); SimpleDynamics wall_adj_cell(water_block_inner, ghost_creation); - + InteractionWithUpdate tke(water_block_inner, ghost_creation, 0.0); InteractionWithUpdate dissipationrate(water_block_inner, ghost_creation, 0.0); - TurbulentChannelFlowBoundaryConditionSetup boundary_condition_setup(water_block_inner, ghost_creation); /** Time step size with considering sound wave speed. */ ReduceDynamics get_fluid_time_step_size(water_block, read_mesh_data.MinMeshEdge(), 1.0); InteractionWithUpdate turbulent_viscous_force(water_block_inner); InteractionWithUpdate viscous_force(water_block_inner); - InteractionWithUpdate tke_gradient_force(water_block_inner); - - // visualization in FVM with data in cell - BodyStatesRecordingInMeshToVtp write_real_body_states(water_block, read_mesh_data); + InteractionWithUpdate tke_gradient_force(water_block_inner); + + // visualization in FVM with data in cell + BodyStatesRecordingToMeshVtp write_real_body_states(water_block, read_mesh_data); ReducedQuantityRecording write_maximum_speed(water_block); initial_condition.exec(); @@ -79,7 +78,7 @@ int main(int ac, char *av[]) int screen_output_interval = 1000; Real end_time = 100.0; - Real output_interval = 5.0; /**< time stamps for output. */ + Real output_interval = 5.0; /**< time stamps for output. */ //---------------------------------------------------------------------- // Statistics for CPU time //---------------------------------------------------------------------- @@ -114,8 +113,8 @@ int main(int ac, char *av[]) if (number_of_iterations % screen_output_interval == 0) { cout << fixed << setprecision(9) << "N=" << number_of_iterations << " Time = " - << physical_time - << " dt = " << dt << "\n"; + << physical_time + << " dt = " << dt << "\n"; } number_of_iterations++; } From 8e977ef88b9d03b85bbb67806b012a903d3ecbf4 Mon Sep 17 00:00:00 2001 From: Xiangyu Date: Wed, 5 Feb 2025 18:51:29 +0100 Subject: [PATCH 02/33] not finished --- src/for_3D_build/bodies/mesh_helper_3d.cpp | 105 ----------------- .../bodies/complex_bodies/mesh_helper.h | 12 +- src/shared/io_system/io_vtk_mesh.cpp | 110 ++++++++++++++++++ src/shared/io_system/io_vtk_mesh.h | 8 ++ 4 files changed, 120 insertions(+), 115 deletions(-) diff --git a/src/for_3D_build/bodies/mesh_helper_3d.cpp b/src/for_3D_build/bodies/mesh_helper_3d.cpp index fa5506765b..bced887b55 100644 --- a/src/for_3D_build/bodies/mesh_helper_3d.cpp +++ b/src/for_3D_build/bodies/mesh_helper_3d.cpp @@ -403,111 +403,6 @@ void MeshFileHelpers::minimumDistance(StdVec &all_data_of_distance_between } } -void MeshFileHelpers::vtuFileHeader(std::ofstream &out_file) -{ - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "0\n"; - out_file << "\n"; - out_file << "\n"; -} - -void MeshFileHelpers::vtuFileNodeCoordinates(std::ofstream &out_file, StdLargeVec &node_coordinates_, - StdLargeVec> &elements_nodes_connection_, SPHBody &bounds_, Real &rangemax) -{ - // Write point data - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - BoundingBox bounds = bounds_.getSPHSystemBounds(); - Real first_max = bounds.first_.cwiseAbs().maxCoeff(); - Real second_max = bounds.second_.cwiseAbs().maxCoeff(); - rangemax = 1.03075 * (std::max(first_max, second_max)); - out_file << "\n"; - - size_t total_nodes = node_coordinates_.size(); - for (size_t node = 0; node != total_nodes; ++node) - { - out_file << node_coordinates_[node][0] << " " << node_coordinates_[node][1] << " " << node_coordinates_[node][2] << " \n"; - } -} - -void MeshFileHelpers::vtuFileInformationKey(std::ofstream &out_file, Real &rangemax) -{ - out_file << "\n"; - out_file << "\n"; - out_file << "0\n"; - out_file << "\n"; - out_file << "\n"; - out_file << rangemax << " \n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "0\n"; - out_file << "\n"; - out_file << "\n"; - out_file << rangemax << " \n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; -} - -void MeshFileHelpers::vtuFileCellConnectivity(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_, StdLargeVec &node_coordinates_) -{ - out_file << "\n"; - // Write Cell data - out_file << "\n"; - - for (const auto &cell : elements_nodes_connection_) - { - for (const auto &vertex : cell) - { - out_file << vertex << " "; - } - out_file << "\n"; - } - - out_file << "\n"; -} - -void MeshFileHelpers::vtuFileOffsets(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_) -{ - out_file << "\n"; - - size_t offset = 0; - for (const auto &face : elements_nodes_connection_) - { - offset += face.size(); - out_file << offset << " "; - } - out_file << "\n\n"; -} - -void MeshFileHelpers::vtuFileTypeOfCell(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_) -{ - size_t type = 10; - // Specifies type of cell 10 = tetrahedral - out_file << "\n"; - for (const auto &types : elements_nodes_connection_) - { - for (size_t i = 0; i < types.size(); ++i) - { - out_file << type << " "; - } - out_file << "\n"; - } - // Write face attribute data - out_file << "\n"; - out_file << "\n"; -} - void MeshFileHelpers::numberOfNodesFluent(std::ifstream &mesh_file, size_t &number_of_points, std::string &text_line) { diff --git a/src/shared/bodies/complex_bodies/mesh_helper.h b/src/shared/bodies/complex_bodies/mesh_helper.h index 5de292066d..b558e11d1e 100644 --- a/src/shared/bodies/complex_bodies/mesh_helper.h +++ b/src/shared/bodies/complex_bodies/mesh_helper.h @@ -41,8 +41,8 @@ namespace SPH class MeshFileHelpers { public: - MeshFileHelpers(){}; - virtual ~MeshFileHelpers(){}; + MeshFileHelpers() {}; + virtual ~MeshFileHelpers() {}; static void meshDimension(std::ifstream &mesh_file, size_t &dimension, std::string &text_line); static void numberOfNodes(std::ifstream &mesh_file, size_t &number_of_points, std::string &text_line); @@ -65,14 +65,6 @@ class MeshFileHelpers StdLargeVec &node_coordinates_, StdLargeVec &elements_volumes_); static void minimumDistance(StdVec &all_data_of_distance_between_nodes, StdLargeVec &elements_volumes_, StdVec>> &mesh_topology_, StdLargeVec &node_coordinates_); - static void vtuFileHeader(std::ofstream &out_file); - static void vtuFileNodeCoordinates(std::ofstream &out_file, StdLargeVec &nodes_coordinates_, - StdLargeVec> &elements_nodes_connection_, SPHBody &bounds_, Real &range_max); - static void vtuFileInformationKey(std::ofstream &out_file, Real &range_max); - static void vtuFileCellConnectivity(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_, StdLargeVec &node_coordinates_); - static void vtuFileOffsets(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_); - static void vtuFileTypeOfCell(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_); - /*Functions for .msh file from FLUENT*/ static void numberOfNodesFluent(std::ifstream &mesh_file, size_t &number_of_points, std::string &text_line); static void numberOfElementsFluent(std::ifstream &mesh_file, size_t &number_of_elements, std::string &text_line); diff --git a/src/shared/io_system/io_vtk_mesh.cpp b/src/shared/io_system/io_vtk_mesh.cpp index 4207b40f8a..3ca82e3a42 100644 --- a/src/shared/io_system/io_vtk_mesh.cpp +++ b/src/shared/io_system/io_vtk_mesh.cpp @@ -11,4 +11,114 @@ BodyStatesRecordingToMeshVtu::BodyStatesRecordingToMeshVtu(SPHBody &body, ANSYSM : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), elements_nodes_connection_(ansys_mesh.elements_nodes_connection_), bounds_(body) {}; //=================================================================================================// +void BodyStatesRecordingToMeshVtu::FileHeader(std::ofstream &out_file) +{ + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "0\n"; + out_file << "\n"; + out_file << "\n"; +} +//=================================================================================================// +void BodyStatesRecordingToMeshVtu::FileNodeCoordinates( + std::ofstream &out_file, StdLargeVec &node_coordinates_, + StdLargeVec> &elements_nodes_connection_, SPHBody &bounds_, Real &rangemax) +{ + // Write point data + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + BoundingBox bounds = bounds_.getSPHSystemBounds(); + Real first_max = bounds.first_.cwiseAbs().maxCoeff(); + Real second_max = bounds.second_.cwiseAbs().maxCoeff(); + rangemax = 1.03075 * (std::max(first_max, second_max)); + out_file << "\n"; + + size_t total_nodes = node_coordinates_.size(); + for (size_t node = 0; node != total_nodes; ++node) + { + out_file << node_coordinates_[node][0] << " " << node_coordinates_[node][1] << " " << node_coordinates_[node][2] << " \n"; + } +} +//=================================================================================================// +void BodyStatesRecordingToMeshVtu::FileInformationKey(std::ofstream &out_file, Real &rangemax) +{ + out_file << "\n"; + out_file << "\n"; + out_file << "0\n"; + out_file << "\n"; + out_file << "\n"; + out_file << rangemax << " \n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "0\n"; + out_file << "\n"; + out_file << "\n"; + out_file << rangemax << " \n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; +} +//=================================================================================================// +void BodyStatesRecordingToMeshVtu::FileCellConnectivity( + std::ofstream &out_file, + StdLargeVec> &elements_nodes_connection_, StdLargeVec &node_coordinates_) +{ + out_file << "\n"; + // Write Cell data + out_file << "\n"; + + for (const auto &cell : elements_nodes_connection_) + { + for (const auto &vertex : cell) + { + out_file << vertex << " "; + } + out_file << "\n"; + } + + out_file << "\n"; +} +//=================================================================================================// +void BodyStatesRecordingToMeshVtu::FileOffsets(std::ofstream &out_file, + StdLargeVec> &elements_nodes_connection_) +{ + out_file << "\n"; + + size_t offset = 0; + for (const auto &face : elements_nodes_connection_) + { + offset += face.size(); + out_file << offset << " "; + } + out_file << "\n\n"; +} +//=================================================================================================// +void BodyStatesRecordingToMeshVtu::FileTypeOfCell(std::ofstream &out_file, + StdLargeVec> &elements_nodes_connection_) +{ + size_t type = 10; + // Specifies type of cell 10 = tetrahedral + out_file << "\n"; + for (const auto &types : elements_nodes_connection_) + { + for (size_t i = 0; i < types.size(); ++i) + { + out_file << type << " "; + } + out_file << "\n"; + } + // Write face attribute data + out_file << "\n"; + out_file << "\n"; +} +//=================================================================================================// } // namespace SPH diff --git a/src/shared/io_system/io_vtk_mesh.h b/src/shared/io_system/io_vtk_mesh.h index 6410a853c7..9284641a88 100644 --- a/src/shared/io_system/io_vtk_mesh.h +++ b/src/shared/io_system/io_vtk_mesh.h @@ -63,6 +63,14 @@ class BodyStatesRecordingToMeshVtu : public BodyStatesRecordingToVtp StdLargeVec &node_coordinates_; StdLargeVec> &elements_nodes_connection_; SPHBody &bounds_; + + void FileHeader(std::ofstream &out_file); + void FileNodeCoordinates(std::ofstream &out_file, StdLargeVec &nodes_coordinates_, + StdLargeVec> &elements_nodes_connection_, SPHBody &bounds_, Real &range_max); + void FileInformationKey(std::ofstream &out_file, Real &range_max); + void FileCellConnectivity(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_, StdLargeVec &node_coordinates_); + void FileOffsets(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_); + void FileTypeOfCell(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_); }; } // namespace SPH #endif // IO_VTK_MESH_H From 8586772a46d5fbb4655aa31ed2770b6fb295f8f4 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Wed, 5 Feb 2025 21:00:39 +0000 Subject: [PATCH 03/33] to check locally --- src/for_2D_build/io_system/io_vtk_mesh_2d.cpp | 94 ----------- src/for_3D_build/io_system/io_vtk_mesh_3d.cpp | 58 ------- src/shared/io_system/io_vtk_mesh.cpp | 154 ++++++++++++++++-- src/shared/io_system/io_vtk_mesh.h | 9 +- 4 files changed, 140 insertions(+), 175 deletions(-) delete mode 100644 src/for_2D_build/io_system/io_vtk_mesh_2d.cpp delete mode 100644 src/for_3D_build/io_system/io_vtk_mesh_3d.cpp diff --git a/src/for_2D_build/io_system/io_vtk_mesh_2d.cpp b/src/for_2D_build/io_system/io_vtk_mesh_2d.cpp deleted file mode 100644 index b5c69620f4..0000000000 --- a/src/for_2D_build/io_system/io_vtk_mesh_2d.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "io_vtk.hpp" -#include "io_vtk_mesh.h" -namespace SPH -{ -//=================================================================================================// -void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence) -{ - for (SPHBody *body : bodies_) - { - if (body->checkNewlyUpdated() && state_recording_) - { - // TODO: we can short the file name by without using SPHBody - std::string filefullpath = io_environment_.output_folder_ + "/" + body->getName() + "_" + sequence + ".vtp"; - if (fs::exists(filefullpath)) - { - fs::remove(filefullpath); - } - std::ofstream out_file(filefullpath.c_str(), std::ios::trunc); - // begin of the XML file - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - - // Write point data - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - - size_t total_nodes = node_coordinates_.size(); - for (size_t node = 0; node != total_nodes; ++node) - { - Vec3d particle_position = upgradeToVec3d(node_coordinates_[node]); - out_file << particle_position[0] << " " << particle_position[1] << " " << particle_position[2] << "\n"; - } - - out_file << "\n"; - out_file << "\n"; - - // Write face data - out_file << "\n"; - out_file << "\n"; - - for (const auto &element : elements_nodes_connection_) - { - for (const auto &vertex : element) - { - out_file << vertex << " "; - } - out_file << "\n"; - } - - out_file << "\n"; - out_file << "\n"; - - size_t offset = 0; - for (const auto &face : elements_nodes_connection_) - { - offset += face.size(); - out_file << offset << " "; - } - - out_file << "\n\n"; - out_file << "\n"; - - // Write face attribute data - out_file << "\n"; - - BaseParticles &particles = body->getBaseParticles(); - writeParticlesToVtk(out_file, particles); - - out_file << "\n"; - - // Write file footer - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - - out_file.close(); - } - body->setNotNewlyUpdated(); - } -} -//=================================================================================================// -void BodyStatesRecordingToMeshVtu::writeWithFileName(const std::string &sequence) -{ - std::cout << "For 2D build:" - << "The method BodyStatesRecordingToMeshVtu::writeWithFileName not implemented yet." - << std::endl; - exit(1); -} -//=================================================================================================// -} // namespace SPH diff --git a/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp deleted file mode 100644 index 3b34e05724..0000000000 --- a/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "io_vtk.hpp" -#include "io_vtk_mesh.h" -#include "mesh_helper.h" - -namespace SPH -{ -//=================================================================================================// -void BodyStatesRecordingToMeshVtu::writeWithFileName(const std::string &sequence) -{ - for (SPHBody *body : bodies_) - { - if (body->checkNewlyUpdated() && state_recording_) - { - std::string filefullpath = io_environment_.output_folder_ + "/SPHBody_" + body->getName() + "_" + sequence + ".vtu"; - if (fs::exists(filefullpath)) - { - fs::remove(filefullpath); - } - std::ofstream out_file(filefullpath.c_str(), std::ios::trunc); - - MeshFileHelpers::vtuFileHeader(out_file); - Real range_max = 0.0; - MeshFileHelpers::vtuFileNodeCoordinates(out_file, node_coordinates_, elements_nodes_connection_, bounds_, range_max); - - MeshFileHelpers::vtuFileInformationKey(out_file, range_max); - - MeshFileHelpers::vtuFileCellConnectivity(out_file, elements_nodes_connection_, node_coordinates_); - - MeshFileHelpers::vtuFileOffsets(out_file, elements_nodes_connection_); - - MeshFileHelpers::vtuFileTypeOfCell(out_file, elements_nodes_connection_); - - // write Particle data to vtu file - out_file << "\n"; - - BaseParticles &particles = body->getBaseParticles(); - writeParticlesToVtk(out_file, particles); - - out_file << "\n"; - // Write VTU file footer - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - out_file.close(); - } - body->setNotNewlyUpdated(); - } -} -//=================================================================================================// -void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence) -{ - std::cout << "For 3D build:" - << "The method BodyStatesRecordingToMeshVtp::writeWithFileName not implemented yet." - << std::endl; - exit(1); -} -//=================================================================================================// -} // namespace SPH diff --git a/src/shared/io_system/io_vtk_mesh.cpp b/src/shared/io_system/io_vtk_mesh.cpp index 3ca82e3a42..3d183c83bd 100644 --- a/src/shared/io_system/io_vtk_mesh.cpp +++ b/src/shared/io_system/io_vtk_mesh.cpp @@ -7,10 +7,127 @@ BodyStatesRecordingToMeshVtp::BodyStatesRecordingToMeshVtp(SPHBody &body, ANSYSM : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), elements_nodes_connection_(ansys_mesh.elements_nodes_connection_) {} //=================================================================================================// +void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence) +{ + for (SPHBody *body : bodies_) + { + if (body->checkNewlyUpdated() && state_recording_) + { + // TODO: we can short the file name by without using SPHBody + std::string filefullpath = io_environment_.output_folder_ + "/" + body->getName() + "_" + sequence + ".vtp"; + if (fs::exists(filefullpath)) + { + fs::remove(filefullpath); + } + std::ofstream out_file(filefullpath.c_str(), std::ios::trunc); + // begin of the XML file + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + + // Write point data + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + + size_t total_nodes = node_coordinates_.size(); + for (size_t node = 0; node != total_nodes; ++node) + { + Vec3d particle_position = upgradeToVec3d(node_coordinates_[node]); + out_file << particle_position[0] << " " << particle_position[1] << " " << particle_position[2] << "\n"; + } + + out_file << "\n"; + out_file << "\n"; + + // Write face data + out_file << "\n"; + out_file << "\n"; + + for (const auto &element : elements_nodes_connection_) + { + for (const auto &vertex : element) + { + out_file << vertex << " "; + } + out_file << "\n"; + } + + out_file << "\n"; + out_file << "\n"; + + size_t offset = 0; + for (const auto &face : elements_nodes_connection_) + { + offset += face.size(); + out_file << offset << " "; + } + + out_file << "\n\n"; + out_file << "\n"; + + // Write face attribute data + out_file << "\n"; + + BaseParticles &particles = body->getBaseParticles(); + writeParticlesToVtk(out_file, particles); + + out_file << "\n"; + + // Write file footer + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + + out_file.close(); + } + body->setNotNewlyUpdated(); + } +} +//=================================================================================================// BodyStatesRecordingToMeshVtu::BodyStatesRecordingToMeshVtu(SPHBody &body, ANSYSMesh &ansys_mesh) : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), elements_nodes_connection_(ansys_mesh.elements_nodes_connection_), bounds_(body) {}; //=================================================================================================// +void BodyStatesRecordingToMeshVtu::writeWithFileName(const std::string &sequence) +{ + for (SPHBody *body : bodies_) + { + if (body->checkNewlyUpdated() && state_recording_) + { + std::string filefullpath = io_environment_.output_folder_ + "/SPHBody_" + body->getName() + "_" + sequence + ".vtu"; + if (fs::exists(filefullpath)) + { + fs::remove(filefullpath); + } + std::ofstream out_file(filefullpath.c_str(), std::ios::trunc); + + FileHeader(out_file); + Real range_max = FileNodeCoordinates(out_file); + FileInformationKey(out_file, range_max); + FileCellConnectivity(out_file); + FileOffsets(out_file); + FileTypeOfCell(out_file); + + // write Particle data to vtu file + out_file << "\n"; + + BaseParticles &particles = body->getBaseParticles(); + writeParticlesToVtk(out_file, particles); + + out_file << "\n"; + // Write VTU file footer + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + out_file.close(); + } + body->setNotNewlyUpdated(); + } +} +//=================================================================================================// void BodyStatesRecordingToMeshVtu::FileHeader(std::ofstream &out_file) { out_file << "\n"; @@ -22,12 +139,11 @@ void BodyStatesRecordingToMeshVtu::FileHeader(std::ofstream &out_file) out_file << "\n"; } //=================================================================================================// -void BodyStatesRecordingToMeshVtu::FileNodeCoordinates( - std::ofstream &out_file, StdLargeVec &node_coordinates_, - StdLargeVec> &elements_nodes_connection_, SPHBody &bounds_, Real &rangemax) +Real BodyStatesRecordingToMeshVtu::FileNodeCoordinates(std::ofstream &out_file) { // Write point data - out_file << "\n"; + out_file << "\n"; out_file << "\n"; out_file << "\n"; out_file << "\n"; @@ -36,14 +152,16 @@ void BodyStatesRecordingToMeshVtu::FileNodeCoordinates( BoundingBox bounds = bounds_.getSPHSystemBounds(); Real first_max = bounds.first_.cwiseAbs().maxCoeff(); Real second_max = bounds.second_.cwiseAbs().maxCoeff(); - rangemax = 1.03075 * (std::max(first_max, second_max)); - out_file << "\n"; + Real rangemax = 1.03075 * (std::max(first_max, second_max)); + out_file << "\n"; - size_t total_nodes = node_coordinates_.size(); - for (size_t node = 0; node != total_nodes; ++node) + for (size_t node = 0; node != node_coordinates_.size(); ++node) { - out_file << node_coordinates_[node][0] << " " << node_coordinates_[node][1] << " " << node_coordinates_[node][2] << " \n"; + Vec3d node_position = upgradeToVec3d(node_coordinates_[node]); + out_file << node_position[0] << " " << node_position[1] << " " << node_position[2] << " \n"; } + return rangemax; } //=================================================================================================// void BodyStatesRecordingToMeshVtu::FileInformationKey(std::ofstream &out_file, Real &rangemax) @@ -68,13 +186,13 @@ void BodyStatesRecordingToMeshVtu::FileInformationKey(std::ofstream &out_file, R out_file << "\n"; } //=================================================================================================// -void BodyStatesRecordingToMeshVtu::FileCellConnectivity( - std::ofstream &out_file, - StdLargeVec> &elements_nodes_connection_, StdLargeVec &node_coordinates_) +void BodyStatesRecordingToMeshVtu::FileCellConnectivity(std::ofstream &out_file) { out_file << "\n"; // Write Cell data - out_file << "\n"; + out_file << "\n"; for (const auto &cell : elements_nodes_connection_) { @@ -88,10 +206,11 @@ void BodyStatesRecordingToMeshVtu::FileCellConnectivity( out_file << "\n"; } //=================================================================================================// -void BodyStatesRecordingToMeshVtu::FileOffsets(std::ofstream &out_file, - StdLargeVec> &elements_nodes_connection_) +void BodyStatesRecordingToMeshVtu::FileOffsets(std::ofstream &out_file) { - out_file << "\n"; + out_file << "\n"; size_t offset = 0; for (const auto &face : elements_nodes_connection_) @@ -102,8 +221,7 @@ void BodyStatesRecordingToMeshVtu::FileOffsets(std::ofstream &out_file, out_file << "\n\n"; } //=================================================================================================// -void BodyStatesRecordingToMeshVtu::FileTypeOfCell(std::ofstream &out_file, - StdLargeVec> &elements_nodes_connection_) +void BodyStatesRecordingToMeshVtu::FileTypeOfCell(std::ofstream &out_file) { size_t type = 10; // Specifies type of cell 10 = tetrahedral diff --git a/src/shared/io_system/io_vtk_mesh.h b/src/shared/io_system/io_vtk_mesh.h index 9284641a88..bf42583224 100644 --- a/src/shared/io_system/io_vtk_mesh.h +++ b/src/shared/io_system/io_vtk_mesh.h @@ -65,12 +65,11 @@ class BodyStatesRecordingToMeshVtu : public BodyStatesRecordingToVtp SPHBody &bounds_; void FileHeader(std::ofstream &out_file); - void FileNodeCoordinates(std::ofstream &out_file, StdLargeVec &nodes_coordinates_, - StdLargeVec> &elements_nodes_connection_, SPHBody &bounds_, Real &range_max); + Real FileNodeCoordinates(std::ofstream &out_file); void FileInformationKey(std::ofstream &out_file, Real &range_max); - void FileCellConnectivity(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_, StdLargeVec &node_coordinates_); - void FileOffsets(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_); - void FileTypeOfCell(std::ofstream &out_file, StdLargeVec> &elements_nodes_connection_); + void FileCellConnectivity(std::ofstream &out_file); + void FileOffsets(std::ofstream &out_file); + void FileTypeOfCell(std::ofstream &out_file); }; } // namespace SPH #endif // IO_VTK_MESH_H From a0e6edc2e993cd46327f48b25999681106a44b95 Mon Sep 17 00:00:00 2001 From: xiangyu_hu Date: Wed, 5 Feb 2025 23:37:10 +0100 Subject: [PATCH 04/33] 2 and 3d mesh vtu and vtp use shared code --- src/shared/io_system/io_vtk_mesh.cpp | 4 ++-- .../2d_FVM_double_mach_reflection.cpp | 2 +- .../2d_FVM_flow_around_cylinder.cpp | 2 +- .../test_2d_FVM_turbulent_channelflow.cpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/shared/io_system/io_vtk_mesh.cpp b/src/shared/io_system/io_vtk_mesh.cpp index 3d183c83bd..2b0f37c5c7 100644 --- a/src/shared/io_system/io_vtk_mesh.cpp +++ b/src/shared/io_system/io_vtk_mesh.cpp @@ -97,7 +97,7 @@ void BodyStatesRecordingToMeshVtu::writeWithFileName(const std::string &sequence { if (body->checkNewlyUpdated() && state_recording_) { - std::string filefullpath = io_environment_.output_folder_ + "/SPHBody_" + body->getName() + "_" + sequence + ".vtu"; + std::string filefullpath = io_environment_.output_folder_ + "/" + body->getName() + "_" + sequence + ".vtu"; if (fs::exists(filefullpath)) { fs::remove(filefullpath); @@ -223,7 +223,7 @@ void BodyStatesRecordingToMeshVtu::FileOffsets(std::ofstream &out_file) //=================================================================================================// void BodyStatesRecordingToMeshVtu::FileTypeOfCell(std::ofstream &out_file) { - size_t type = 10; + size_t type = Dimensions == 2 ? 5 : 10; // VTK_Triangle (5) in 2D, VTK_Tetrahedron(10) in 3D // Specifies type of cell 10 = tetrahedral out_file << "\n"; for (const auto &types : elements_nodes_connection_) diff --git a/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp b/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp index 883c936bce..d312414003 100644 --- a/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp +++ b/tests/2d_examples/test_2d_FVM_double_mach_reflection/2d_FVM_double_mach_reflection.cpp @@ -46,7 +46,7 @@ int main(int ac, char *av[]) // Define the methods for I/O operations, observations // and regression tests of the simulation. //---------------------------------------------------------------------- - BodyStatesRecordingToMeshVtp write_real_body_states(wave_block, ansys_mesh); + BodyStatesRecordingToMeshVtu write_real_body_states(wave_block, ansys_mesh); write_real_body_states.addToWrite(wave_block, "Density"); write_real_body_states.addToWrite(wave_block, "Pressure"); RegressionTestEnsembleAverage> write_maximum_speed(wave_block); diff --git a/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp b/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp index 0b8c5414fa..82e8527d67 100644 --- a/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp +++ b/tests/2d_examples/test_2d_FVM_flow_around_cylinder/2d_FVM_flow_around_cylinder.cpp @@ -125,7 +125,7 @@ int main(int ac, char *av[]) //---------------------------------------------------------------------- // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- - BodyStatesRecordingToMeshVtp write_real_body_states(water_block, ansys_mesh); + BodyStatesRecordingToMeshVtu write_real_body_states(water_block, ansys_mesh); write_real_body_states.addToWrite(water_block, "Density"); RegressionTestDynamicTimeWarping>> write_total_viscous_force_on_inserted_body(water_block, "ViscousForceOnSolid"); ReducedQuantityRecording> write_total_pressure_force_on_inserted_body(water_block, "PressureForceOnSolid"); diff --git a/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp b/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp index 81ecc9044a..15468a2079 100644 --- a/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp +++ b/tests/extra_source_and_tests/test_2d_FVM_turbulent_channelflow/test_2d_FVM_turbulent_channelflow.cpp @@ -54,7 +54,7 @@ int main(int ac, char *av[]) InteractionWithUpdate tke_gradient_force(water_block_inner); // visualization in FVM with data in cell - BodyStatesRecordingToMeshVtp write_real_body_states(water_block, read_mesh_data); + BodyStatesRecordingToMeshVtu write_real_body_states(water_block, read_mesh_data); ReducedQuantityRecording write_maximum_speed(water_block); initial_condition.exec(); From ec8b7c156b3ffe34696b198a808bdc2e8ff05c93 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Thu, 6 Feb 2025 09:05:09 +0000 Subject: [PATCH 05/33] include io_vtk.hpp --- src/shared/io_system/io_vtk_mesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/io_system/io_vtk_mesh.cpp b/src/shared/io_system/io_vtk_mesh.cpp index 2b0f37c5c7..2804b8a5c7 100644 --- a/src/shared/io_system/io_vtk_mesh.cpp +++ b/src/shared/io_system/io_vtk_mesh.cpp @@ -1,4 +1,5 @@ #include "io_vtk_mesh.h" +#include "io_vtk.hpp" namespace SPH { @@ -13,7 +14,6 @@ void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence { if (body->checkNewlyUpdated() && state_recording_) { - // TODO: we can short the file name by without using SPHBody std::string filefullpath = io_environment_.output_folder_ + "/" + body->getName() + "_" + sequence + ".vtp"; if (fs::exists(filefullpath)) { From 282ec5e7830f898ef710dcd2097e0e9f5d354a70 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Thu, 6 Feb 2025 22:08:50 +0000 Subject: [PATCH 06/33] add surface indication from shape --- .../execution/execution_policy.h | 11 ++++- .../general_dynamics/geometric_dynamics.cpp | 13 ++++++ .../general_dynamics/geometric_dynamics.h | 45 ++++++++++++++++++- .../general_dynamics/geometric_dynamics.hpp | 20 +++++---- 4 files changed, 78 insertions(+), 11 deletions(-) diff --git a/src/shared/particle_dynamics/execution/execution_policy.h b/src/shared/particle_dynamics/execution/execution_policy.h index 24503f3662..548f88dd3d 100644 --- a/src/shared/particle_dynamics/execution/execution_policy.h +++ b/src/shared/particle_dynamics/execution/execution_policy.h @@ -50,8 +50,17 @@ class ParallelUnsequencedPolicy { }; +template +class DeviceExecution; + +template <> +class DeviceExecution<> +{ +}; + template -class DeviceExecution : public PolicyType +class DeviceExecution + : public DeviceExecution<>, public PolicyType { }; diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp index 8d9d6366b3..b2939fb3ce 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp @@ -21,5 +21,18 @@ void NormalFromBodyShapeCK::UpdateKernel::update(size_t index_i, Real dt) phi_[index_i] = signed_distance; phi0_[index_i] = signed_distance; } +//=============================================================================================// +SurfaceIndicationFromBodyShape::SurfaceIndicationFromBodyShape(SPHBody &sph_body) + : LocalDynamics(sph_body), + initial_shape_(&sph_body.getInitialShape()), + spacing_ref_(sph_body.sph_adaptation_->ReferenceSpacing()), + dv_indicator_(particles_->registerStateVariableOnly("SurfaceIndicator")), + dv_pos_(particles_->getVariableByName("Position")) {} +//=============================================================================================// +void SurfaceIndicationFromBodyShape::UpdateKernel::update(size_t index_i, Real dt) +{ + Real signed_distance = initial_shape_->findSignedDistance(pos_[index_i]); + indicator_[index_i] = signed_distance > -spacing_ref_ ? 1 : 0; +} //=================================================================================================// } // namespace SPH diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.h b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.h index 3c8c4a4360..5807d34e5d 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.h +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.h @@ -33,13 +33,26 @@ namespace SPH { +class HostKernel +{ + public: + template + HostKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + { + // not implemented for device policy due to virtual function call in inital_shape_, + // which is not allowed in device code + static_assert(!std::is_base_of, ExecutionPolicy>::value, + "This compute kernel is not designed for execution on device!"); + } +}; + class NormalFromBodyShapeCK : public LocalDynamics { public: explicit NormalFromBodyShapeCK(SPHBody &sph_body); - virtual ~NormalFromBodyShapeCK(){}; + virtual ~NormalFromBodyShapeCK() {}; - class UpdateKernel + class UpdateKernel : public HostKernel { public: template @@ -58,5 +71,33 @@ class NormalFromBodyShapeCK : public LocalDynamics DiscreteVariable *dv_pos_, *dv_n_, *dv_n0_; DiscreteVariable *dv_phi_, *dv_phi0_; }; + +class SurfaceIndicationFromBodyShape : public LocalDynamics +{ + public: + explicit SurfaceIndicationFromBodyShape(SPHBody &sph_body); + virtual ~SurfaceIndicationFromBodyShape() {}; + + class UpdateKernel : public HostKernel + { + public: + template + UpdateKernel(const ExecutionPolicy &ex_policy, + SurfaceIndicationFromBodyShape &encloser); + void update(size_t index_i, Real dt = 0.0); + + protected: + Shape *initial_shape_; + Real spacing_ref_; + int *indicator_; + Vecd *pos_; + }; + + protected: + Shape *initial_shape_; + Real spacing_ref_; + DiscreteVariable *dv_indicator_; + DiscreteVariable *dv_pos_; +}; } // namespace SPH #endif // GEOMETRIC_DYNAMICS_H diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.hpp b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.hpp index 8850e63071..b56211a26d 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.hpp +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.hpp @@ -10,18 +10,22 @@ namespace SPH template NormalFromBodyShapeCK::UpdateKernel:: UpdateKernel(const ExecutionPolicy &ex_policy, NormalFromBodyShapeCK &encloser) - : initial_shape_(encloser.initial_shape_), + : HostKernel(ex_policy, encloser), + initial_shape_(encloser.initial_shape_), pos_(encloser.dv_pos_->DelegatedData(ex_policy)), n_(encloser.dv_n_->DelegatedData(ex_policy)), n0_(encloser.dv_n0_->DelegatedData(ex_policy)), phi_(encloser.dv_phi_->DelegatedData(ex_policy)), - phi0_(encloser.dv_phi0_->DelegatedData(ex_policy)) -{ - // not implemented for device policy due to virtual function call in inital_shape_, - // which is not allowed in device code - static_assert(!std::is_base_of::value, - "This compute kernel is not designed for execution::ParallelDevicePolicy!"); -} + phi0_(encloser.dv_phi0_->DelegatedData(ex_policy)) {} +//=================================================================================================// +template +SurfaceIndicationFromBodyShape::UpdateKernel:: + UpdateKernel(const ExecutionPolicy &ex_policy, SurfaceIndicationFromBodyShape &encloser) + : HostKernel(ex_policy, encloser), + initial_shape_(encloser.initial_shape_), + spacing_ref_(encloser.spacing_ref_), + indicator_(encloser.dv_indicator_->DelegatedData(ex_policy)), + pos_(encloser.dv_pos_->DelegatedData(ex_policy)) {} //=================================================================================================// } // namespace SPH #endif // GEOMETRIC_DYNAMICS_HPP From e2086b97349b7296d92ef826a560ac35bc746aee Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Fri, 7 Feb 2025 09:10:14 +0000 Subject: [PATCH 07/33] add 3d dambreak ck case --- .../test_2d_dambreak_ck/dambreak_ck.cpp | 6 +- .../test_3d_dambreak/CMakeLists.txt | 21 ++ .../test_3d_dambreak/dambreak.cpp | 253 ++++++++++++++++++ .../FluidObserver_Pressure_Run_0_result.xml | 14 + .../FluidObserver_Pressure_Run_18_result.xml | 14 + .../FluidObserver_Pressure_Run_9_result.xml | 14 + .../FluidObserver_Pressure_dtwdistance.xml | 4 + .../FluidObserver_Pressure_runtimes.dat | 3 + ...ody_TotalMechanicalEnergy_Run_0_result.xml | 9 + ...ody_TotalMechanicalEnergy_Run_3_result.xml | 9 + ...ody_TotalMechanicalEnergy_Run_6_result.xml | 9 + ...Body_TotalMechanicalEnergy_dtwdistance.xml | 4 + ...terBody_TotalMechanicalEnergy_runtimes.dat | 3 + .../regression_test_tool.py | 46 ++++ 14 files changed, 406 insertions(+), 3 deletions(-) create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/CMakeLists.txt create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_runtimes.dat create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/regression_test_tool.py diff --git a/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp b/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp index c62ac58d4e..11c1f3281e 100644 --- a/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp +++ b/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp @@ -114,7 +114,7 @@ int main(int ac, char *av[]) InteractionDynamicsCK fluid_density_regularization(water_block_inner, water_wall_contact); InteractionDynamicsCK - fluid_boundary_indicator(water_block_inner,water_wall_contact); + fluid_boundary_indicator(water_block_inner, water_wall_contact); ReduceDynamicsCK fluid_advection_time_step(water_block, U_ref); ReduceDynamicsCK fluid_acoustic_time_step(water_block); //---------------------------------------------------------------------- @@ -125,7 +125,7 @@ int main(int ac, char *av[]) body_states_recording.addToWrite(wall_boundary, "NormalDirection"); body_states_recording.addToWrite(water_block, "Density"); body_states_recording.addToWrite(water_block, "Indicator"); - body_states_recording.addToWrite(water_block, "PositionDivergence"); + body_states_recording.addToWrite(water_block, "PositionDivergence"); RestartIO restart_io(sph_system); @@ -146,7 +146,7 @@ int main(int ac, char *av[]) sv_physical_time->setValue(restart_io.readRestartFiles(sph_system.RestartStep())); } - wall_boundary_normal_direction.exec(); // run particle dynamics on CPU first + wall_boundary_normal_direction.exec(); // run particle dynamics with host kernels first constant_gravity.exec(); water_cell_linked_list.exec(); diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/CMakeLists.txt b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/CMakeLists.txt new file mode 100644 index 0000000000..066da02fda --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/CMakeLists.txt @@ -0,0 +1,21 @@ +STRING(REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}) +PROJECT("${CURRENT_FOLDER}") + +SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) +SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin/") +SET(BUILD_INPUT_PATH "${EXECUTABLE_OUTPUT_PATH}/input") +SET(BUILD_RELOAD_PATH "${EXECUTABLE_OUTPUT_PATH}/reload") + +file(MAKE_DIRECTORY ${BUILD_INPUT_PATH}) +execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${BUILD_INPUT_PATH}) +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/regression_test_tool/ DESTINATION ${BUILD_INPUT_PATH}) + +add_executable(${PROJECT_NAME}) +aux_source_directory(. DIR_SRCS) +target_sources(${PROJECT_NAME} PRIVATE ${DIR_SRCS}) +target_link_libraries(${PROJECT_NAME} sphinxsys_3d) +set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}") + +add_test(NAME ${PROJECT_NAME} + COMMAND ${PROJECT_NAME} --state_recording=${TEST_STATE_RECORDING} + WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp new file mode 100644 index 0000000000..a6da79e2da --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp @@ -0,0 +1,253 @@ +/** + * @file dambreak.cpp + * @brief 3D dambreak example using computing kernels. + * @author Xiangyu Hu + */ +#include "sphinxsys_ck.h" +using namespace SPH; +//---------------------------------------------------------------------- +// Basic geometry parameters and numerical setup. +//---------------------------------------------------------------------- +Real resolution_ref = 0.05; // particle spacing +Real BW = resolution_ref * 4; // boundary width +Real DL = 5.366; // tank length +Real DH = 2.0; // tank height +Real DW = 0.5; // tank width +Real LL = 2.0; // liquid length +Real LH = 1.0; // liquid height +Real LW = 0.5; // liquid width +//---------------------------------------------------------------------- +// Material parameters. +//---------------------------------------------------------------------- +Real rho0_f = 1.0; +Real gravity_g = 1.0; +Real U_f = 2.0 * sqrt(gravity_g * LH); +Real c_f = 10.0 * U_f; +//---------------------------------------------------------------------- +// Geometric shapes used in this case. +//---------------------------------------------------------------------- +class WaterBlock : public ComplexShape +{ + public: + explicit WaterBlock(const std::string &shape_name) : ComplexShape(shape_name) + { + Vecd halfsize_water(0.5 * LL, 0.5 * LH, 0.5 * LW); + Transform translation_water(halfsize_water); + add>(Transform(translation_water), halfsize_water); + } +}; + +class WallBoundary : public ComplexShape // define the static solid wall boundary shape +{ + public: + explicit WallBoundary(const std::string &shape_name) : ComplexShape(shape_name) + { + Vecd halfsize_outer(0.5 * DL + BW, 0.5 * DH + BW, 0.5 * DW + BW); + Vecd halfsize_inner(0.5 * DL, 0.5 * DH, 0.5 * DW); + Transform translation_wall(halfsize_inner); + add>(Transform(translation_wall), halfsize_outer); + subtract>(Transform(translation_wall), halfsize_inner); + } +}; +//---------------------------------------------------------------------- +// A group of observation points. +//---------------------------------------------------------------------- +StdVec createObservationPoints() +{ + StdVec observation_points; + observation_points.push_back(Vecd(DL, 0.01, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.1, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.2, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.24, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.252, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.266, 0.5 * DW)); + return observation_points; +}; +//---------------------------------------------------------------------- +// Main program starts here. +//---------------------------------------------------------------------- +int main(int ac, char *av[]) +{ + //---------------------------------------------------------------------- + // Build up an SPHSystem and IO environment. + //---------------------------------------------------------------------- + BoundingBox system_domain_bounds(Vecd(-BW, -BW, -BW), Vecd(DL + BW, DH + BW, DW + BW)); + SPHSystem sph_system(system_domain_bounds, resolution_ref); + sph_system.handleCommandlineOptions(ac, av)->setIOEnvironment(); + //---------------------------------------------------------------------- + // Creating bodies with corresponding materials and particles. + //---------------------------------------------------------------------- + WaterBlock initial_water_block("WaterBody"); + FluidBody water_block(sph_system, initial_water_block); + water_block.defineMaterial(rho0_f, c_f); + water_block.generateParticles(); + + SolidBody wall_boundary(sph_system, makeShared("WallBoundary")); + wall_boundary.defineMaterial(); + wall_boundary.generateParticles(); + + ObserverBody fluid_observer(sph_system, "FluidObserver"); + fluid_observer.generateParticles(createObservationPoints()); + //---------------------------------------------------------------------- + // Define body relation map. + // The contact map gives the topological connections between the bodies. + // Basically the the range of bodies to build neighbor particle lists. + // Generally, we first define all the inner relations, then the contact relations. + //---------------------------------------------------------------------- + Relation> water_block_inner(water_block); + Relation> water_wall_contact(water_block, {&wall_boundary}); + Relation> fluid_observer_contact(fluid_observer, {&water_block}); + //---------------------------------------------------------------------- + // Define the main execution policy for this case. + //---------------------------------------------------------------------- + using MainExecutionPolicy = execution::ParallelPolicy; + //---------------------------------------------------------------------- + // Define the numerical methods used in the simulation. + // Note that there may be data dependence on the sequence of constructions. + // Generally, the configuration dynamics, such as update cell linked list, + // update body relations, are defiend first. + // Then the geometric models or simple objects without data dependencies, + // such as gravity, initialized normal direction. + // After that, the major physical particle dynamics model should be introduced. + // Finally, the auxiliary models such as time step estimator, initial condition, + // boundary condition and other constraints should be defined. + //---------------------------------------------------------------------- + UpdateCellLinkedList water_cell_linked_list(water_block); + UpdateCellLinkedList wall_cell_linked_list(wall_boundary); + UpdateRelation, Contact<>> water_block_update_complex_relation(water_block_inner, water_wall_contact); + UpdateRelation> fluid_observer_contact_relation(fluid_observer_contact); + ParticleSortCK particle_sort(water_block); + + Gravity gravity(Vecd(0.0, -gravity_g)); + StateDynamics> constant_gravity(water_block, gravity); + StateDynamics wall_boundary_normal_direction(wall_boundary); // run on CPU + StateDynamics water_advection_step_setup(water_block); + StateDynamics water_advection_step_close(water_block); + + InteractionDynamicsCK + fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + InteractionDynamicsCK + fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); + InteractionDynamicsCK + fluid_acoustic_step_2nd_half(water_block_inner, water_wall_contact); + InteractionDynamicsCK + fluid_density_regularization(water_block_inner, water_wall_contact); + InteractionDynamicsCK + fluid_boundary_indicator(water_block_inner, water_wall_contact); + ReduceDynamicsCK fluid_advection_time_step(water_block, U_ref); + ReduceDynamicsCK fluid_acoustic_time_step(water_block); + //---------------------------------------------------------------------- + // Define the methods for I/O operations, observations + // and regression tests of the simulation. + //---------------------------------------------------------------------- + BodyStatesRecordingToVtp body_states_recording(sph_system); + body_states_recording.addToWrite(wall_boundary, "NormalDirection"); + body_states_recording.addToWrite(water_block, "Density"); + body_states_recording.addToWrite(water_block, "Indicator"); + body_states_recording.addToWrite(water_block, "PositionDivergence"); + RegressionTestDynamicTimeWarping> + record_water_mechanical_energy(water_block, gravity); + RegressionTestDynamicTimeWarping> + fluid_observer_pressure("Pressure", fluid_observer_contact); + //---------------------------------------------------------------------- + // Prepare the simulation with cell linked list, configuration + // and case specified initial condition if necessary. + //---------------------------------------------------------------------- + SingularVariable *sv_physical_time = sph_system.getSystemVariableByName("PhysicalTime"); + wall_boundary_normal_direction.exec(); // run particle dynamics with host kernels first + constant_gravity.exec(); + + water_cell_linked_list.exec(); + wall_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); + fluid_observer_contact_relation.exec(); + //---------------------------------------------------------------------- + // Setup for time-stepping control + //---------------------------------------------------------------------- + size_t number_of_iterations = 0; + int screen_output_interval = 100; + Real end_time = 20.0; + Real output_interval = end_time / 20.0; + //---------------------------------------------------------------------- + // Statistics for CPU time + //---------------------------------------------------------------------- + TickCount t1 = TickCount::now(); + TimeInterval interval; + //---------------------------------------------------------------------- + // First output before the main loop. + //---------------------------------------------------------------------- + body_states_recording.writeToFile(MainExecutionPolicy{}); + record_water_mechanical_energy.writeToFile(number_of_iterations); + fluid_observer_pressure.writeToFile(number_of_iterations); + //---------------------------------------------------------------------- + // Main loop starts here. + //---------------------------------------------------------------------- + while (sv_physical_time->getValue() < end_time) + { + Real integration_time = 0.0; + while (integration_time < output_interval) + { + fluid_density_regularization.exec(); + water_advection_step_setup.exec(); + Real advection_dt = fluid_advection_time_step.exec(); + fluid_boundary_indicator.exec(); + fluid_linear_correction_matrix.exec(); + + Real relaxation_time = 0.0; + Real acoustic_dt = 0.0; + while (relaxation_time < advection_dt) + { + + acoustic_dt = fluid_acoustic_time_step.exec(); + fluid_acoustic_step_1st_half.exec(acoustic_dt); + fluid_acoustic_step_2nd_half.exec(acoustic_dt); + relaxation_time += acoustic_dt; + integration_time += acoustic_dt; + sv_physical_time->incrementValue(acoustic_dt); + } + water_advection_step_close.exec(); + + if (number_of_iterations % screen_output_interval == 0) + { + std::cout << std::fixed << std::setprecision(9) << "N=" << number_of_iterations << " Time = " + << sv_physical_time->getValue() + << " advection_dt = " << advection_dt << " acoustic_dt = " << acoustic_dt << "\n"; + } + number_of_iterations++; + + if (number_of_iterations % 100 == 0 && number_of_iterations != 1) + { + particle_sort.exec(); + } + water_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); + fluid_observer_contact_relation.exec(); + write_recorded_water_pressure.writeToFile(number_of_iterations); + } + + write_water_mechanical_energy.writeToFile(number_of_iterations); + + TickCount t2 = TickCount::now(); + body_states_recording.writeToFile(MainExecutionPolicy{}); + TickCount t3 = TickCount::now(); + interval += t3 - t2; + } + TickCount t4 = TickCount::now(); + + TimeInterval tt; + tt = t4 - t1 - interval; + std::cout << "Total wall time for computation: " << tt.seconds() << " seconds." << std::endl; + + if (sph_system.GenerateRegressionData()) + { + write_water_mechanical_energy.generateDataBase(1.0e-3); + write_recorded_water_pressure.generateDataBase(1.0e-3); + } + else + { + write_water_mechanical_energy.testResult(); + write_recorded_water_pressure.testResult(); + } + + return 0; +} diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml new file mode 100644 index 0000000000..c99bab799b --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml new file mode 100644 index 0000000000..2837d6f823 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml new file mode 100644 index 0000000000..a52e5d1ce1 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml new file mode 100644 index 0000000000..c2bf017a34 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_runtimes.dat new file mode 100644 index 0000000000..57574ea953 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_runtimes.dat @@ -0,0 +1,3 @@ +true +19 +4 \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml new file mode 100644 index 0000000000..b126d034a0 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml new file mode 100644 index 0000000000..4a3668c2f3 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml new file mode 100644 index 0000000000..135dcf035b --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml new file mode 100644 index 0000000000..adaed6dbb5 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat new file mode 100644 index 0000000000..34de7daedb --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat @@ -0,0 +1,3 @@ +true +7 +4 \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/regression_test_tool.py b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/regression_test_tool.py new file mode 100644 index 0000000000..8edaf9970c --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/regression_test_tool.py @@ -0,0 +1,46 @@ +# !/usr/bin/env python3 +import os +import sys + +path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') +sys.path.append(path) +from regression_test_base_tool import SphinxsysRegressionTest + + +""" +case name: test_3d_dambreak +""" + +case_name = "test_3d_dambreak" +body_name = "WaterBody" +parameter_name = "TotalMechanicalEnergy" +body_name_1 = "FluidObserver" +parameter_name_1 = "Pressure" + +number_of_run_times = 0 +converged = 0 +sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) +sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) +clean_input_folder(sphinxsys.input_file_path) + + +while True: + print("Now start a new run......") + sphinxsys.run_case() + number_of_run_times += 1 + converged = sphinxsys.read_dat_file() + converged_1 = sphinxsys_1.read_dat_file() + print("Please note: This is the", number_of_run_times, "run!") + if number_of_run_times <= 200: + if (converged == "true") and (converged_1 == "true"): + print("The tested parameters of all variables are converged, and the run will stop here!") + break + elif converged != "true": + print("The tested parameters of", sphinxsys.sphinxsys_parameter_name, "are not converged!") + continue + elif converged_1 != "true": + print("The tested parameters of", sphinxsys_1.sphinxsys_parameter_name, "are not converged!") + continue + else: + print("It's too many runs but still not converged, please try again!") + break From 6112b228dfd96a04366ffa1a9f824cdb38f36ca7 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Fri, 7 Feb 2025 10:24:36 +0000 Subject: [PATCH 08/33] to add sycl version --- tests/3d_examples/3d_examples_ck/CMakeLists.txt | 7 +++++++ .../CMakeLists.txt | 0 .../dambreak.cpp | 16 ++++++++-------- .../FluidObserver_Pressure_Run_0_result.xml | 0 .../FluidObserver_Pressure_Run_18_result.xml | 0 .../FluidObserver_Pressure_Run_9_result.xml | 0 .../FluidObserver_Pressure_dtwdistance.xml | 0 .../FluidObserver_Pressure_runtimes.dat | 0 ...erBody_TotalMechanicalEnergy_Run_0_result.xml | 0 ...erBody_TotalMechanicalEnergy_Run_3_result.xml | 0 ...erBody_TotalMechanicalEnergy_Run_6_result.xml | 0 ...terBody_TotalMechanicalEnergy_dtwdistance.xml | 0 .../WaterBody_TotalMechanicalEnergy_runtimes.dat | 0 .../regression_test_tool/regression_test_tool.py | 0 14 files changed, 15 insertions(+), 8 deletions(-) create mode 100644 tests/3d_examples/3d_examples_ck/CMakeLists.txt rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/CMakeLists.txt (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/dambreak.cpp (96%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/FluidObserver_Pressure_runtimes.dat (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat (100%) rename tests/3d_examples/3d_examples_ck/{test_3d_dambreak => test_3d_dambreak_ck}/regression_test_tool/regression_test_tool.py (100%) diff --git a/tests/3d_examples/3d_examples_ck/CMakeLists.txt b/tests/3d_examples/3d_examples_ck/CMakeLists.txt new file mode 100644 index 0000000000..8eb174fa72 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/CMakeLists.txt @@ -0,0 +1,7 @@ +SUBDIRLIST(SUBDIRS ${CMAKE_CURRENT_SOURCE_DIR}) + +foreach(subdir ${SUBDIRS}) + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${subdir}/CMakeLists.txt) + add_subdirectory(${subdir}) + endif() +endforeach() \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/CMakeLists.txt b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/CMakeLists.txt similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/CMakeLists.txt rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/CMakeLists.txt diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp similarity index 96% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp index a6da79e2da..d15bb06855 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/dambreak.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp @@ -118,7 +118,7 @@ int main(int ac, char *av[]) UpdateRelation> fluid_observer_contact_relation(fluid_observer_contact); ParticleSortCK particle_sort(water_block); - Gravity gravity(Vecd(0.0, -gravity_g)); + Gravity gravity(Vec3d(0.0, -gravity_g, 0.0)); StateDynamics> constant_gravity(water_block, gravity); StateDynamics wall_boundary_normal_direction(wall_boundary); // run on CPU StateDynamics water_advection_step_setup(water_block); @@ -134,7 +134,7 @@ int main(int ac, char *av[]) fluid_density_regularization(water_block_inner, water_wall_contact); InteractionDynamicsCK fluid_boundary_indicator(water_block_inner, water_wall_contact); - ReduceDynamicsCK fluid_advection_time_step(water_block, U_ref); + ReduceDynamicsCK fluid_advection_time_step(water_block, U_f); ReduceDynamicsCK fluid_acoustic_time_step(water_block); //---------------------------------------------------------------------- // Define the methods for I/O operations, observations @@ -222,10 +222,10 @@ int main(int ac, char *av[]) water_cell_linked_list.exec(); water_block_update_complex_relation.exec(); fluid_observer_contact_relation.exec(); - write_recorded_water_pressure.writeToFile(number_of_iterations); + fluid_observer_pressure.writeToFile(number_of_iterations); } - write_water_mechanical_energy.writeToFile(number_of_iterations); + record_water_mechanical_energy.writeToFile(number_of_iterations); TickCount t2 = TickCount::now(); body_states_recording.writeToFile(MainExecutionPolicy{}); @@ -240,13 +240,13 @@ int main(int ac, char *av[]) if (sph_system.GenerateRegressionData()) { - write_water_mechanical_energy.generateDataBase(1.0e-3); - write_recorded_water_pressure.generateDataBase(1.0e-3); + record_water_mechanical_energy.generateDataBase(1.0e-3); + fluid_observer_pressure.generateDataBase(1.0e-3); } else { - write_water_mechanical_energy.testResult(); - write_recorded_water_pressure.testResult(); + record_water_mechanical_energy.testResult(); + fluid_observer_pressure.testResult(); } return 0; diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_runtimes.dat similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/FluidObserver_Pressure_runtimes.dat rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_runtimes.dat diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/regression_test_tool.py b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_tool.py similarity index 100% rename from tests/3d_examples/3d_examples_ck/test_3d_dambreak/regression_test_tool/regression_test_tool.py rename to tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_tool.py From 91afdd7f31a264a0c2fcefc6774bc750b943cc52 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Fri, 7 Feb 2025 11:23:42 +0000 Subject: [PATCH 09/33] case runs but need to check locally --- tests/tests_sycl/3d_examples/CMakeLists.txt | 7 + .../test_3d_dambreak_sycl/CMakeLists.txt | 21 ++ .../test_3d_dambreak_sycl/dambreak.cpp | 253 ++++++++++++++++++ .../FluidObserver_Pressure_Run_0_result.xml | 14 + .../FluidObserver_Pressure_Run_18_result.xml | 14 + .../FluidObserver_Pressure_Run_9_result.xml | 14 + .../FluidObserver_Pressure_dtwdistance.xml | 4 + .../FluidObserver_Pressure_runtimes.dat | 3 + ...ody_TotalMechanicalEnergy_Run_0_result.xml | 9 + ...ody_TotalMechanicalEnergy_Run_3_result.xml | 9 + ...ody_TotalMechanicalEnergy_Run_6_result.xml | 9 + ...Body_TotalMechanicalEnergy_dtwdistance.xml | 4 + ...terBody_TotalMechanicalEnergy_runtimes.dat | 3 + .../regression_test_tool.py | 46 ++++ 14 files changed, 410 insertions(+) create mode 100644 tests/tests_sycl/3d_examples/CMakeLists.txt create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/CMakeLists.txt create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py diff --git a/tests/tests_sycl/3d_examples/CMakeLists.txt b/tests/tests_sycl/3d_examples/CMakeLists.txt new file mode 100644 index 0000000000..8eb174fa72 --- /dev/null +++ b/tests/tests_sycl/3d_examples/CMakeLists.txt @@ -0,0 +1,7 @@ +SUBDIRLIST(SUBDIRS ${CMAKE_CURRENT_SOURCE_DIR}) + +foreach(subdir ${SUBDIRS}) + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${subdir}/CMakeLists.txt) + add_subdirectory(${subdir}) + endif() +endforeach() \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/CMakeLists.txt b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/CMakeLists.txt new file mode 100644 index 0000000000..066da02fda --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/CMakeLists.txt @@ -0,0 +1,21 @@ +STRING(REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}) +PROJECT("${CURRENT_FOLDER}") + +SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) +SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin/") +SET(BUILD_INPUT_PATH "${EXECUTABLE_OUTPUT_PATH}/input") +SET(BUILD_RELOAD_PATH "${EXECUTABLE_OUTPUT_PATH}/reload") + +file(MAKE_DIRECTORY ${BUILD_INPUT_PATH}) +execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${BUILD_INPUT_PATH}) +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/regression_test_tool/ DESTINATION ${BUILD_INPUT_PATH}) + +add_executable(${PROJECT_NAME}) +aux_source_directory(. DIR_SRCS) +target_sources(${PROJECT_NAME} PRIVATE ${DIR_SRCS}) +target_link_libraries(${PROJECT_NAME} sphinxsys_3d) +set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}") + +add_test(NAME ${PROJECT_NAME} + COMMAND ${PROJECT_NAME} --state_recording=${TEST_STATE_RECORDING} + WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp new file mode 100644 index 0000000000..5270194aec --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp @@ -0,0 +1,253 @@ +/** + * @file dambreak.cpp + * @brief 3D dambreak example using computing kernels. + * @author Xiangyu Hu + */ +#include "sphinxsys_sycl.h" +using namespace SPH; +//---------------------------------------------------------------------- +// Basic geometry parameters and numerical setup. +//---------------------------------------------------------------------- +Real resolution_ref = 0.05; // particle spacing +Real BW = resolution_ref * 4; // boundary width +Real DL = 5.366; // tank length +Real DH = 2.0; // tank height +Real DW = 0.5; // tank width +Real LL = 2.0; // liquid length +Real LH = 1.0; // liquid height +Real LW = 0.5; // liquid width +//---------------------------------------------------------------------- +// Material parameters. +//---------------------------------------------------------------------- +Real rho0_f = 1.0; +Real gravity_g = 1.0; +Real U_f = 2.0 * sqrt(gravity_g * LH); +Real c_f = 10.0 * U_f; +//---------------------------------------------------------------------- +// Geometric shapes used in this case. +//---------------------------------------------------------------------- +class WaterBlock : public ComplexShape +{ + public: + explicit WaterBlock(const std::string &shape_name) : ComplexShape(shape_name) + { + Vecd halfsize_water(0.5 * LL, 0.5 * LH, 0.5 * LW); + Transform translation_water(halfsize_water); + add>(Transform(translation_water), halfsize_water); + } +}; + +class WallBoundary : public ComplexShape // define the static solid wall boundary shape +{ + public: + explicit WallBoundary(const std::string &shape_name) : ComplexShape(shape_name) + { + Vecd halfsize_outer(0.5 * DL + BW, 0.5 * DH + BW, 0.5 * DW + BW); + Vecd halfsize_inner(0.5 * DL, 0.5 * DH, 0.5 * DW); + Transform translation_wall(halfsize_inner); + add>(Transform(translation_wall), halfsize_outer); + subtract>(Transform(translation_wall), halfsize_inner); + } +}; +//---------------------------------------------------------------------- +// A group of observation points. +//---------------------------------------------------------------------- +StdVec createObservationPoints() +{ + StdVec observation_points; + observation_points.push_back(Vecd(DL, 0.01, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.1, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.2, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.24, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.252, 0.5 * DW)); + observation_points.push_back(Vecd(DL, 0.266, 0.5 * DW)); + return observation_points; +}; +//---------------------------------------------------------------------- +// Main program starts here. +//---------------------------------------------------------------------- +int main(int ac, char *av[]) +{ + //---------------------------------------------------------------------- + // Build up an SPHSystem and IO environment. + //---------------------------------------------------------------------- + BoundingBox system_domain_bounds(Vecd(-BW, -BW, -BW), Vecd(DL + BW, DH + BW, DW + BW)); + SPHSystem sph_system(system_domain_bounds, resolution_ref); + sph_system.handleCommandlineOptions(ac, av)->setIOEnvironment(); + //---------------------------------------------------------------------- + // Creating bodies with corresponding materials and particles. + //---------------------------------------------------------------------- + WaterBlock initial_water_block("WaterBody"); + FluidBody water_block(sph_system, initial_water_block); + water_block.defineMaterial(rho0_f, c_f); + water_block.generateParticles(); + + SolidBody wall_boundary(sph_system, makeShared("WallBoundary")); + wall_boundary.defineMaterial(); + wall_boundary.generateParticles(); + + ObserverBody fluid_observer(sph_system, "FluidObserver"); + fluid_observer.generateParticles(createObservationPoints()); + //---------------------------------------------------------------------- + // Define body relation map. + // The contact map gives the topological connections between the bodies. + // Basically the the range of bodies to build neighbor particle lists. + // Generally, we first define all the inner relations, then the contact relations. + //---------------------------------------------------------------------- + Relation> water_block_inner(water_block); + Relation> water_wall_contact(water_block, {&wall_boundary}); + Relation> fluid_observer_contact(fluid_observer, {&water_block}); + //---------------------------------------------------------------------- + // Define the main execution policy for this case. + //---------------------------------------------------------------------- + using MainExecutionPolicy = execution::ParallelDevicePolicy; + //---------------------------------------------------------------------- + // Define the numerical methods used in the simulation. + // Note that there may be data dependence on the sequence of constructions. + // Generally, the configuration dynamics, such as update cell linked list, + // update body relations, are defiend first. + // Then the geometric models or simple objects without data dependencies, + // such as gravity, initialized normal direction. + // After that, the major physical particle dynamics model should be introduced. + // Finally, the auxiliary models such as time step estimator, initial condition, + // boundary condition and other constraints should be defined. + //---------------------------------------------------------------------- + UpdateCellLinkedList water_cell_linked_list(water_block); + UpdateCellLinkedList wall_cell_linked_list(wall_boundary); + UpdateRelation, Contact<>> water_block_update_complex_relation(water_block_inner, water_wall_contact); + UpdateRelation> fluid_observer_contact_relation(fluid_observer_contact); + ParticleSortCK particle_sort(water_block); + + Gravity gravity(Vec3d(0.0, -gravity_g, 0.0)); + StateDynamics> constant_gravity(water_block, gravity); + StateDynamics wall_boundary_normal_direction(wall_boundary); // run on CPU + StateDynamics water_advection_step_setup(water_block); + StateDynamics water_advection_step_close(water_block); + + InteractionDynamicsCK + fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + InteractionDynamicsCK + fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); + InteractionDynamicsCK + fluid_acoustic_step_2nd_half(water_block_inner, water_wall_contact); + InteractionDynamicsCK + fluid_density_regularization(water_block_inner, water_wall_contact); + InteractionDynamicsCK + fluid_boundary_indicator(water_block_inner, water_wall_contact); + ReduceDynamicsCK fluid_advection_time_step(water_block, U_f); + ReduceDynamicsCK fluid_acoustic_time_step(water_block); + //---------------------------------------------------------------------- + // Define the methods for I/O operations, observations + // and regression tests of the simulation. + //---------------------------------------------------------------------- + BodyStatesRecordingToVtp body_states_recording(sph_system); + body_states_recording.addToWrite(wall_boundary, "NormalDirection"); + body_states_recording.addToWrite(water_block, "Density"); + body_states_recording.addToWrite(water_block, "Indicator"); + body_states_recording.addToWrite(water_block, "PositionDivergence"); + RegressionTestDynamicTimeWarping> + record_water_mechanical_energy(water_block, gravity); + RegressionTestDynamicTimeWarping> + fluid_observer_pressure("Pressure", fluid_observer_contact); + //---------------------------------------------------------------------- + // Prepare the simulation with cell linked list, configuration + // and case specified initial condition if necessary. + //---------------------------------------------------------------------- + SingularVariable *sv_physical_time = sph_system.getSystemVariableByName("PhysicalTime"); + wall_boundary_normal_direction.exec(); // run particle dynamics with host kernels first + constant_gravity.exec(); + + water_cell_linked_list.exec(); + wall_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); + fluid_observer_contact_relation.exec(); + //---------------------------------------------------------------------- + // Setup for time-stepping control + //---------------------------------------------------------------------- + size_t number_of_iterations = 0; + int screen_output_interval = 100; + Real end_time = 20.0; + Real output_interval = end_time / 20.0; + //---------------------------------------------------------------------- + // Statistics for CPU time + //---------------------------------------------------------------------- + TickCount t1 = TickCount::now(); + TimeInterval interval; + //---------------------------------------------------------------------- + // First output before the main loop. + //---------------------------------------------------------------------- + body_states_recording.writeToFile(MainExecutionPolicy{}); + record_water_mechanical_energy.writeToFile(number_of_iterations); + fluid_observer_pressure.writeToFile(number_of_iterations); + //---------------------------------------------------------------------- + // Main loop starts here. + //---------------------------------------------------------------------- + while (sv_physical_time->getValue() < end_time) + { + Real integration_time = 0.0; + while (integration_time < output_interval) + { + fluid_density_regularization.exec(); + water_advection_step_setup.exec(); + Real advection_dt = fluid_advection_time_step.exec(); + fluid_boundary_indicator.exec(); + fluid_linear_correction_matrix.exec(); + + Real relaxation_time = 0.0; + Real acoustic_dt = 0.0; + while (relaxation_time < advection_dt) + { + + acoustic_dt = fluid_acoustic_time_step.exec(); + fluid_acoustic_step_1st_half.exec(acoustic_dt); + fluid_acoustic_step_2nd_half.exec(acoustic_dt); + relaxation_time += acoustic_dt; + integration_time += acoustic_dt; + sv_physical_time->incrementValue(acoustic_dt); + } + water_advection_step_close.exec(); + + if (number_of_iterations % screen_output_interval == 0) + { + std::cout << std::fixed << std::setprecision(9) << "N=" << number_of_iterations << " Time = " + << sv_physical_time->getValue() + << " advection_dt = " << advection_dt << " acoustic_dt = " << acoustic_dt << "\n"; + } + number_of_iterations++; + + if (number_of_iterations % 100 == 0 && number_of_iterations != 1) + { + particle_sort.exec(); + } + water_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); + fluid_observer_contact_relation.exec(); + fluid_observer_pressure.writeToFile(number_of_iterations); + } + + record_water_mechanical_energy.writeToFile(number_of_iterations); + + TickCount t2 = TickCount::now(); + body_states_recording.writeToFile(MainExecutionPolicy{}); + TickCount t3 = TickCount::now(); + interval += t3 - t2; + } + TickCount t4 = TickCount::now(); + + TimeInterval tt; + tt = t4 - t1 - interval; + std::cout << "Total wall time for computation: " << tt.seconds() << " seconds." << std::endl; + + if (sph_system.GenerateRegressionData()) + { + record_water_mechanical_energy.generateDataBase(1.0e-3); + fluid_observer_pressure.generateDataBase(1.0e-3); + } + else + { + record_water_mechanical_energy.testResult(); + fluid_observer_pressure.testResult(); + } + + return 0; +} diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml new file mode 100644 index 0000000000..c99bab799b --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml new file mode 100644 index 0000000000..2837d6f823 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml new file mode 100644 index 0000000000..a52e5d1ce1 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml new file mode 100644 index 0000000000..c2bf017a34 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat new file mode 100644 index 0000000000..57574ea953 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat @@ -0,0 +1,3 @@ +true +19 +4 \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml new file mode 100644 index 0000000000..b126d034a0 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml new file mode 100644 index 0000000000..4a3668c2f3 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml new file mode 100644 index 0000000000..135dcf035b --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml new file mode 100644 index 0000000000..adaed6dbb5 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat new file mode 100644 index 0000000000..34de7daedb --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat @@ -0,0 +1,3 @@ +true +7 +4 \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py new file mode 100644 index 0000000000..8edaf9970c --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py @@ -0,0 +1,46 @@ +# !/usr/bin/env python3 +import os +import sys + +path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') +sys.path.append(path) +from regression_test_base_tool import SphinxsysRegressionTest + + +""" +case name: test_3d_dambreak +""" + +case_name = "test_3d_dambreak" +body_name = "WaterBody" +parameter_name = "TotalMechanicalEnergy" +body_name_1 = "FluidObserver" +parameter_name_1 = "Pressure" + +number_of_run_times = 0 +converged = 0 +sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) +sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) +clean_input_folder(sphinxsys.input_file_path) + + +while True: + print("Now start a new run......") + sphinxsys.run_case() + number_of_run_times += 1 + converged = sphinxsys.read_dat_file() + converged_1 = sphinxsys_1.read_dat_file() + print("Please note: This is the", number_of_run_times, "run!") + if number_of_run_times <= 200: + if (converged == "true") and (converged_1 == "true"): + print("The tested parameters of all variables are converged, and the run will stop here!") + break + elif converged != "true": + print("The tested parameters of", sphinxsys.sphinxsys_parameter_name, "are not converged!") + continue + elif converged_1 != "true": + print("The tested parameters of", sphinxsys_1.sphinxsys_parameter_name, "are not converged!") + continue + else: + print("It's too many runs but still not converged, please try again!") + break From cdbc5b1c0554cab5e0f5d0e84551ccd9acc10453 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Fri, 7 Feb 2025 14:46:29 +0000 Subject: [PATCH 10/33] drafting 3d stfb case --- .../2d_examples_ck/test_2d_stfb_ck/stfb.cpp | 4 +- .../test_3d_stfb_ck/CMakeLists.txt | 24 + ...hapeBox_FreeSurfaceHeight_Run_0_result.xml | 9 + ...hapeBox_FreeSurfaceHeight_Run_3_result.xml | 9 + ...hapeBox_FreeSurfaceHeight_Run_5_result.xml | 9 + ...ShapeBox_FreeSurfaceHeight_dtwdistance.xml | 4 + ...ricShapeBox_FreeSurfaceHeight_runtimes.dat | 3 + .../Observer_Position_Run_0_result.xml | 9 + .../Observer_Position_Run_3_result.xml | 9 + .../Observer_Position_Run_6_result.xml | 9 + .../Observer_Position_dtwdistance.xml | 4 + .../Observer_Position_runtimes.dat | 3 + .../regression_test_tool.py | 45 ++ .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 413 ++++++++++++++++++ 14 files changed, 553 insertions(+), 1 deletion(-) create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/CMakeLists.txt create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_0_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_3_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_6_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_dtwdistance.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_runtimes.dat create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/regression_test_tool.py create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp diff --git a/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp b/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp index 03d0344ec8..a19e07a6b0 100644 --- a/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp +++ b/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp @@ -100,7 +100,9 @@ class WaterBlock : public ComplexShape Real h = 1.3 * particle_spacing_ref; Vec2d gauge_halfsize = Vec2d(0.5 * h, 0.5 * DH); Vec2d gauge_translation = Vec2d(DL / 3, 0.5 * DH); -// +//---------------------------------------------------------------------- +// Main program starts here. +//---------------------------------------------------------------------- int main(int ac, char *av[]) { std::cout << "Mass " << StructureMass << " str_sup " << FlStA << " rho_s " << rho_s << std::endl; diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/CMakeLists.txt b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/CMakeLists.txt new file mode 100644 index 0000000000..1df97abcfa --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/CMakeLists.txt @@ -0,0 +1,24 @@ +STRING(REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}) +PROJECT("${CURRENT_FOLDER}") + +SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) +SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin/") +SET(BUILD_INPUT_PATH "${EXECUTABLE_OUTPUT_PATH}/input") +SET(BUILD_RELOAD_PATH "${EXECUTABLE_OUTPUT_PATH}/reload") + +file(MAKE_DIRECTORY ${BUILD_INPUT_PATH}) +execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${BUILD_INPUT_PATH}) +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/regression_test_tool/ + DESTINATION ${BUILD_INPUT_PATH}) + +add_executable(${PROJECT_NAME}) +aux_source_directory(. DIR_SRCS) +target_sources(${PROJECT_NAME} PRIVATE ${DIR_SRCS}) +target_link_libraries(${PROJECT_NAME} sphinxsys_3d) +set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}") + +add_test(NAME ${PROJECT_NAME} + COMMAND ${PROJECT_NAME} --state_recording=${TEST_STATE_RECORDING} + WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) + +set_tests_properties(${PROJECT_NAME} PROPERTIES LABELS "fluid dynamics, Simbody") diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml new file mode 100644 index 0000000000..05cf9cd33e --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml new file mode 100644 index 0000000000..ff38e15646 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml new file mode 100644 index 0000000000..a342adeb4d --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml new file mode 100644 index 0000000000..5b459b5e2b --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat new file mode 100644 index 0000000000..de07de18db --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat @@ -0,0 +1,3 @@ +true +6 +4 \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_0_result.xml new file mode 100644 index 0000000000..9e3427c2b7 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_3_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_3_result.xml new file mode 100644 index 0000000000..cb0aeb2627 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_3_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_6_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_6_result.xml new file mode 100644 index 0000000000..ab2fef3ede --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_Run_6_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_dtwdistance.xml new file mode 100644 index 0000000000..6a83063405 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_runtimes.dat new file mode 100644 index 0000000000..34de7daedb --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/Observer_Position_runtimes.dat @@ -0,0 +1,3 @@ +true +7 +4 \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/regression_test_tool.py b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/regression_test_tool.py new file mode 100644 index 0000000000..c60eb85953 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/regression_test_tool/regression_test_tool.py @@ -0,0 +1,45 @@ +# !/usr/bin/env python3 +import os +import sys + +path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') +sys.path.append(path) +from regression_test_base_tool import SphinxsysRegressionTest + +""" +case name: test_3d_stfb +""" + +case_name = "test_3d_stfb" +body_name = "GeometricShapeBox" +parameter_name = "FreeSurfaceHeight" +body_name_1 = "Observer" +parameter_name_1 = "Position" + +number_of_run_times = 0 +converged = 0 +sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) +sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) +clean_input_folder(sphinxsys.input_file_path) + + +while True: + print("Now start a new run......") + sphinxsys.run_case() + number_of_run_times += 1 + converged = sphinxsys.read_dat_file() + converged_1 = sphinxsys_1.read_dat_file() + print("Please note: This is the", number_of_run_times, "run!") + if number_of_run_times <= 200: + if (converged == "true") and (converged_1 == "true"): + print("The tested parameters of all variables are converged, and the run will stop here!") + break + elif converged != "true": + print("The tested parameters of", sphinxsys.sphinxsys_parameter_name, "are not converged!") + continue + elif converged_1 != "true": + print("The tested parameters of", sphinxsys_1.sphinxsys_parameter_name, "are not converged!") + continue + else: + print("It's too many runs but still not converged, please try again!") + break diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp new file mode 100644 index 0000000000..002520962b --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -0,0 +1,413 @@ +/** + * @file stfb.cpp + * @brief This is the case file for 3D still floating body using computing kernel. + * @author Nicolò Salis and Xiangyu Hu + */ +#include "sphinxsys.h" //SPHinXsys Library. +using namespace SPH; +//---------------------------------------------------------------------- +// Basic geometry parameters and numerical setup. +//---------------------------------------------------------------------- +Real total_physical_time = 5.0; /**< TOTAL SIMULATION TIME*/ +Real DW = 3.0; /**< Water length. */ +Real DL = 3.0; /**< Tank length. */ +Real DH = 2.5; /**< Tank height. */ +Real WH = 2.0; /**< Water block height. */ +Real L = 1.0; /**< Base of the floating body. */ +Real particle_spacing_ref = L / 10; +Real BW = particle_spacing_ref * 4.0; /**< Extending width for BCs. */ +Real Maker_width = particle_spacing_ref * 4.0; /**< Width of the wave_maker. */ +BoundingBox system_domain_bounds(Vecd(-BW, -BW, -BW), Vecd(DW + BW, DL + BW, DH + BW)); +Vecd offset = Vecd::Zero(); +//---------------------------------------------------------------------- +// Material properties of the fluid. +//---------------------------------------------------------------------- +Real rho0_f = 1000.0; /**< Reference density of fluid. */ +Real gravity_g = 9.81; /**< Value of gravity. */ +Real U_f = 2.0 * sqrt(WH * gravity_g); /**< Characteristic velocity. */ +Real c_f = 10.0 * U_f; /**< Reference sound speed. */ +Real mu_f = 1.0e-3; +//---------------------------------------------------------------------- +// Structure Properties G and Inertia +//---------------------------------------------------------------------- +/* Weight of the solid structure*/ +Real StructureMass = 700; +/**< Area of the solid structure*/ +Real FlStA = L * L * L; +/**< Density of the solid structure*/ +Real rho_s = StructureMass / FlStA; +/* Equilibrium position of the solid structure*/ +Real H = WH - (rho_s / rho0_f * L - L / 2); /**< Strart placement of Flt Body*/ + +Real bcmx = DL / 2; +Real bcmy = DL / 2; +Real bcmz = H; +Vecd G(bcmx, bcmy, bcmz); +Real Ix = StructureMass / 12 * (L * L + L * L); +Real Iy = StructureMass / 12 * (L * L + L * L); +Real Iz = StructureMass / 12 * (L * L + L * L); +/** Structure observer position */ +Vecd obs = G; +/** Geometry definition. */ +Vecd halfsize_structure(0.5 * L, 0.5 * L, 0.5 * L); +Vecd structure_pos(G[0], G[1], G[2]); +Transform translation_str(structure_pos); +//------------------------------------------------------------------------------ +// Geometric shapes used in the case +//------------------------------------------------------------------------------ +class FloatingStructure : public ComplexShape +{ + public: + explicit FloatingStructure(const std::string &shape_name) : ComplexShape(shape_name) + { + add>(Transform(translation_str), halfsize_structure); + } +}; + +class StructureSystemForSimbody : public SolidBodyPartForSimbody +{ + public: + StructureSystemForSimbody(SPHBody &sph_body, Shape &shape) + : SolidBodyPartForSimbody(sph_body, shape) + { + // Vec2d mass_center(G[0], G[1]); + // initial_mass_center_ = SimTKVec3(mass_center[0], mass_center[1], 0.0); + body_part_mass_properties_ = + mass_properties_ptr_keeper_ + .createPtr(StructureMass, SimTKVec3(0.0), SimTK::UnitInertia(Ix, Iy, Iz)); + } +}; +//---------------------------------------------------------------------- +// Water block +//---------------------------------------------------------------------- +class WaterBlock : public ComplexShape +{ + public: + explicit WaterBlock(const std::string &shape_name) : ComplexShape(shape_name) + { + /** Geometry definition. */ + Vecd halfsize_water(0.5 * DW, 0.5 * DL, 0.5 * WH); + Vecd water_pos(0.5 * DW, 0.5 * DL, 0.5 * WH); + Transform translation_water(water_pos); + add>(Transform(translation_water), halfsize_water); + subtract>(Transform(translation_str), halfsize_structure); + } +}; +//---------------------------------------------------------------------- +// Wall geometries. +//---------------------------------------------------------------------- +class WallBoundary : public ComplexShape +{ + public: + explicit WallBoundary(const std::string &shape_name) : ComplexShape(shape_name) + { + Vecd halfsize_wall_outer(0.5 * DW + BW, 0.5 * DL + BW, 0.5 * DH + BW); + Vecd wall_outer_pos(0.5 * DW, 0.5 * DL, 0.5 * DH); + Transform translation_wall_outer(wall_outer_pos); + add>(Transform(translation_wall_outer), halfsize_wall_outer); + + Vecd halfsize_wall_inner(0.5 * DW, 0.5 * DL, 0.5 * DH + BW); + Vecd wall_inner_pos(0.5 * DW, 0.5 * DL, 0.5 * DH + BW); + Transform translation_wall_inner(wall_inner_pos); + subtract>(Transform(translation_wall_inner), halfsize_wall_inner); + } +}; +//---------------------------------------------------------------------- +// create measuring probes +//---------------------------------------------------------------------- +Real h = 1.3 * particle_spacing_ref; +Vecd FS_gaugeDim(0.5 * h, 0.5 * h, 0.5 * DH); +Vecd FS_gauge(DW / 3, DL / 3, 0.5 * DH); +Transform translation_FS_gauge(FS_gauge); +//---------------------------------------------------------------------- +// Main program starts here. +//---------------------------------------------------------------------- +int main(int ac, char *av[]) +{ + std::cout << "Mass " << StructureMass << " str_sup " << FlStA << " rho_s " << rho_s << std::endl; + //---------------------------------------------------------------------- + // Build up the environment of a SPHSystem with global controls. + //---------------------------------------------------------------------- + SPHSystem sph_system(system_domain_bounds, particle_spacing_ref); + sph_system.handleCommandlineOptions(ac, av)->setIOEnvironment(); + //---------------------------------------------------------------------- + // Creating body, materials and particles. + //---------------------------------------------------------------------- + FluidBody water_block(sph_system, makeShared("WaterBody")); + water_block.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); + water_block.generateParticles(); + + SolidBody wall_boundary(sph_system, makeShared("WallBoundary")); + wall_boundary.defineMaterial(); + wall_boundary.generateParticles(); + + SolidBody structure(sph_system, makeShared("Structure")); + structure.defineMaterial(rho_s); + structure.generateParticles(); + + ObserverBody observer(sph_system, "Observer"); + observer.defineAdaptationRatios(1.15, 2.0); + observer.generateParticles(StdVec{obs}); + //---------------------------------------------------------------------- + // Creating body parts. + //---------------------------------------------------------------------- + TransformShape wave_probe_buffer_shape(Transform(translation_FS_gauge), FS_gauge); + BodyRegionByCell wave_probe_buffer(water_block, wave_probe_buffer_shape); + //---------------------------------------------------------------------- + // Define body relation map. + // The contact map gives the topological connections between the bodies. + // Basically the the range of bodies to build neighbor particle lists. + // Generally, we first define all the inner relations, then the contact relations. + // At last, we define the complex relaxations by combining previous defined + // inner and contact relations. + //---------------------------------------------------------------------- + Relation> water_block_inner(water_block); + Relation> water_block_contact(water_block, {&wall_boundary, &structure}); + Relation> structure_contact(structure, {&water_block}); + Relation> observer_contact_with_water(observer, {&water_block}); + Relation> observer_contact_with_structure(observer, {&structure}); + //---------------------------------------------------------------------- + // Combined relations built from basic relations + // which is only used for update configuration. + //---------------------------------------------------------------------- + ComplexRelation water_block_complex(water_block_inner, water_block_contact); + //---------------------------------------------------------------------- + // Define the numerical methods used in the simulation. + // Note that there may be data dependence on the sequence of constructions. + // Generally, the geometric models or simple objects without data dependencies, + // such as gravity, should be initiated first. + // Then the major physical particle dynamics model should be introduced. + // Finally, the auxiliary models such as time step estimator, initial condition, + // boundary condition and other constraints should be defined. + // For typical fluid-structure interaction, we first define structure dynamics, + // Then fluid dynamics and the corresponding coupling dynamics. + // The coupling with multi-body dynamics will be introduced at last. + //---------------------------------------------------------------------- + SimpleDynamics structure_offset_position(structure, offset); + SimpleDynamics wall_boundary_normal_direction(wall_boundary); + SimpleDynamics str_normal(structure); + + Gravity gravity(Vec3d(0.0, 0.0, -gravity_g)); + SimpleDynamics> constant_gravity(water_block, gravity); + + Dynamics1Level pressure_relaxation(water_block_inner, water_block_contact); + Dynamics1Level density_relaxation(water_block_inner, water_block_contact); + InteractionWithUpdate update_density_by_summation(water_block_inner, water_block_contact); + InteractionWithUpdate viscous_force(water_block_inner, water_block_contact); + + ReduceDynamics get_fluid_advection_time_step_size(water_block, U_f); + ReduceDynamics get_fluid_time_step_size(water_block); + + InteractionWithUpdate viscous_force_on_solid(structure_contact); + InteractionWithUpdate> pressure_force_on_solid(structure_contact); + /*-------------------------------------------------------------------------------*/ + /*--------------------------FREE SURFACE IDENTIFICATION--------------------------*/ + /*-------------------------------------------------------------------------------*/ + InteractionWithUpdate + free_stream_surface_indicator(water_block_inner, water_block_contact); + /** Impose transport velocity formulation. */ + InteractionWithUpdate> + transport_velocity_correction(water_block_inner, water_block_contact); + //---------------------------------------------------------------------- + // Define the configuration related particles dynamics. + //---------------------------------------------------------------------- + ParticleSorting particle_sorting(water_block); + /*-------------------------------------------------------------------------------*/ + //---------------------------------------------------------------------- + // Define the multi-body system + //---------------------------------------------------------------------- + /** set up the multi body system. */ + SimTK::MultibodySystem MBsystem; + /** the bodies or matter of the system. */ + SimTK::SimbodyMatterSubsystem matter(MBsystem); + /** the forces of the system. */ + SimTK::GeneralForceSubsystem forces(MBsystem); + /** mass properties of the fixed spot. */ + TransformShape fix_spot_shape(Transform(translation_str), halfsize_structure); + StructureSystemForSimbody structure_multibody(structure, fix_spot_shape); + /** Mass properties of the constrained spot. + * SimTK::MassProperties(mass, center of mass, inertia) + */ + SimTK::Body::Rigid structure_info(*structure_multibody.body_part_mass_properties_); + /** + * @brief ** Create a %Planar mobilizer between an existing parent (inboard) body P + * and a new child (outboard) body B created by copying the given \a bodyInfo + * into a privately-owned Body within the constructed %MobilizedBody object. + * Specify the mobilizer frames F fixed to parent P and M fixed to child B. + * @param[in] inboard(SimTKVec3) Defines the location of the joint point relative to the parent body. + * @param[in] outboard(SimTKVec3) Defines the body's origin location to the joint point. + * @note The body's origin location can be the mass center, the the center of mass should be SimTKVec3(0) + * in SimTK::MassProperties(mass, com, inertia) + */ + SimTK::MobilizedBody::Planar structure_mob(matter.Ground(), SimTK::Transform(SimTKVec3(G[0], G[1], G[2])), structure_info, SimTK::Transform(SimTKVec3(0.0, 0.0, 0.0))); + /** + * @details Add gravity to mb body. + * @param[in,out] forces, The subsystem to which this force should be added. + * @param[in] matter, The subsystem containing the bodies that will be affected. + * @param[in] gravity, The default gravity vector v, interpreted as v=g*d where g=|\a gravity| is + * a positive scalar and d is the "down" direction unit vector d=\a gravity/g. + * @param[in] zeroHeight This is an optional specification of the default value for the height + * up the gravity vector that is considered to be "zero" for purposes of + * calculating the gravitational potential energy. The default is + * \a zeroHeight == 0, i.e., a body's potential energy is defined to be zero + * when the height of its mass center is the same as the height of the Ground + * origin. The zero height will have the value specified here unless + * explicitly changed within a particular State use the setZeroHeight() + * method. + * @par Force Each body B that has not been explicitly excluded will experience a force + * fb = mb*g*d, applied to its center of mass, where mb is the mass of body B. + * @par Potential Energy + * Gravitational potential energy for a body B is mb*g*hb where hb is the height of + * body B's mass center over an arbitrary "zero" height hz (default is hz=0), + * measured along the "up" direction -d. If pb is the Ground frame vector giving + * the position of body B's mass center, its height over or under hz is + * hb=pb*(-d) - hz. Note that this is a signed quantity so the potential energy is + * also signed. 0.475 + */ + SimTK::Force::UniformGravity sim_gravity(forces, matter, SimTKVec3(0.0, 0.0, -gravity_g), 0.0); + /** discrete forces acting on the bodies. */ + SimTK::Force::DiscreteForces force_on_bodies(forces, matter); + /** Time stepping method for multibody system.*/ + SimTK::State state = MBsystem.realizeTopology(); + SimTK::RungeKuttaMersonIntegrator integ(MBsystem); + integ.setAccuracy(1e-3); + integ.setAllowInterpolation(false); + integ.initialize(state); + //---------------------------------------------------------------------- + // Coupling between SimBody and SPH + //---------------------------------------------------------------------- + ReduceDynamics + force_on_structure(structure_multibody, MBsystem, structure_mob, integ); + SimpleDynamics + constraint_on_structure(structure_multibody, MBsystem, structure_mob, integ); + //---------------------------------------------------------------------- + // Define the methods for I/O operations and observations of the simulation. + //---------------------------------------------------------------------- + BodyStatesRecordingToVtp write_real_body_states(sph_system); + RegressionTestDynamicTimeWarping>> + wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); + InteractionDynamics> + interpolation_observer_position(observer_contact_with_structure, "Position", "Position"); + RegressionTestDynamicTimeWarping> + write_str_displacement("Position", observer_contact_with_structure); + //---------------------------------------------------------------------- + // Basic control parameters for time stepping. + //---------------------------------------------------------------------- + Real &physical_time = *sph_system.getSystemVariableDataByName("PhysicalTime"); + int number_of_iterations = 0; + int screen_output_interval = 1000; + Real end_time = total_physical_time; + Real output_interval = end_time / 200; + Real dt = 0.0; + Real total_time = 0.0; + Real relax_time = 1.0; + /** statistics for computing time. */ + TickCount t1 = TickCount::now(); + TimeInterval interval; + //---------------------------------------------------------------------- + // Prepare the simulation with cell linked list, configuration + // and case specified initial condition if necessary. + //---------------------------------------------------------------------- + structure_offset_position.exec(); + sph_system.initializeSystemCellLinkedLists(); + sph_system.initializeSystemConfigurations(); + wall_boundary_normal_direction.exec(); + str_normal.exec(); + constant_gravity.exec(); + //---------------------------------------------------------------------- + // First output before the main loop. + //---------------------------------------------------------------------- + write_real_body_states.writeToFile(number_of_iterations); + write_str_displacement.writeToFile(number_of_iterations); + wave_gauge.writeToFile(number_of_iterations); + //---------------------------------------------------------------------- + // Main loop of time stepping starts here. + //---------------------------------------------------------------------- + while (physical_time < end_time) + { + Real integral_time = 0.0; + while (integral_time < output_interval) + { + Real Dt = get_fluid_advection_time_step_size.exec(); + update_density_by_summation.exec(); + viscous_force.exec(); + viscous_force_on_solid.exec(); + + Real relaxation_time = 0.0; + while (relaxation_time < Dt) + { + dt = get_fluid_time_step_size.exec(); + + pressure_relaxation.exec(dt); + pressure_force_on_solid.exec(); + density_relaxation.exec(dt); + /** coupled rigid body dynamics. */ + if (total_time >= relax_time) + { + SimTK::State &state_for_update = integ.updAdvancedState(); + force_on_bodies.clearAllBodyForces(state_for_update); + force_on_bodies.setOneBodyForce(state_for_update, structure_mob, force_on_structure.exec()); + integ.stepBy(dt); + constraint_on_structure.exec(); + } + interpolation_observer_position.exec(); + + relaxation_time += dt; + integral_time += dt; + total_time += dt; + if (total_time >= relax_time) + physical_time += dt; + } + + if (number_of_iterations % screen_output_interval == 0) + { + std::cout << std::fixed << std::setprecision(9) << "N=" << number_of_iterations + << " Total Time = " << total_time + << " Physical Time = " << physical_time + << " Dt = " << Dt << " dt = " << dt << "\n"; + } + number_of_iterations++; + if (number_of_iterations % 100 == 0 && number_of_iterations != 1) + { + particle_sorting.exec(); + } + water_block.updateCellLinkedList(); + wall_boundary.updateCellLinkedList(); + structure.updateCellLinkedList(); + water_block_complex.updateConfiguration(); + structure_contact.updateConfiguration(); + observer_contact_with_water.updateConfiguration(); + + if (total_time >= relax_time) + { + write_str_displacement.writeToFile(number_of_iterations); + wave_gauge.writeToFile(number_of_iterations); + } + } + + TickCount t2 = TickCount::now(); + if (total_time >= relax_time) + write_real_body_states.writeToFile(); + TickCount t3 = TickCount::now(); + interval += t3 - t2; + } + + TickCount t4 = TickCount::now(); + + TimeInterval tt; + tt = t4 - t1 - interval; + std::cout << "Total wall time for computation: " << tt.seconds() << " seconds." << std::endl; + + if (sph_system.GenerateRegressionData()) + { + write_str_displacement.generateDataBase(1e-3); + wave_gauge.generateDataBase(1e-3); + } + else + { + write_str_displacement.testResult(); + wave_gauge.testResult(); + } + + return 0; +} From 363dfa8bc4a4e5b4e837697f9a58a198f95a7d19 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Fri, 7 Feb 2025 17:56:46 +0000 Subject: [PATCH 11/33] to add sycl version --- .../2d_examples_ck/test_2d_stfb_ck/stfb.cpp | 3 +- .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 185 +++++++++--------- 2 files changed, 96 insertions(+), 92 deletions(-) diff --git a/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp b/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp index a19e07a6b0..41fd95e515 100644 --- a/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp +++ b/tests/2d_examples/2d_examples_ck/test_2d_stfb_ck/stfb.cpp @@ -267,7 +267,8 @@ int main(int ac, char *av[]) // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- BodyStatesRecordingToVtp write_real_body_states(sph_system); - RegressionTestDynamicTimeWarping>> + RegressionTestDynamicTimeWarping>> wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); RegressionTestDynamicTimeWarping> write_structure_position("Position", observer_contact); diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index 002520962b..0102d472f9 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -3,7 +3,7 @@ * @brief This is the case file for 3D still floating body using computing kernel. * @author Nicolò Salis and Xiangyu Hu */ -#include "sphinxsys.h" //SPHinXsys Library. +#include "sphinxsys_ck.h" //SPHinXsys Library. using namespace SPH; //---------------------------------------------------------------------- // Basic geometry parameters and numerical setup. @@ -164,55 +164,56 @@ int main(int ac, char *av[]) Relation> water_block_inner(water_block); Relation> water_block_contact(water_block, {&wall_boundary, &structure}); Relation> structure_contact(structure, {&water_block}); - Relation> observer_contact_with_water(observer, {&water_block}); - Relation> observer_contact_with_structure(observer, {&structure}); + Relation> observer_contact(observer, {&structure}); //---------------------------------------------------------------------- - // Combined relations built from basic relations - // which is only used for update configuration. + // Define the main execution policy for this case. //---------------------------------------------------------------------- - ComplexRelation water_block_complex(water_block_inner, water_block_contact); + using MainExecutionPolicy = execution::ParallelPolicy; //---------------------------------------------------------------------- // Define the numerical methods used in the simulation. // Note that there may be data dependence on the sequence of constructions. - // Generally, the geometric models or simple objects without data dependencies, - // such as gravity, should be initiated first. - // Then the major physical particle dynamics model should be introduced. + // Generally, the configuration dynamics, such as update cell linked list, + // update body relations, are defiend first. + // Then the geometric models or simple objects without data dependencies, + // such as gravity, initialized normal direction. + // After that, the major physical particle dynamics model should be introduced. // Finally, the auxiliary models such as time step estimator, initial condition, // boundary condition and other constraints should be defined. - // For typical fluid-structure interaction, we first define structure dynamics, - // Then fluid dynamics and the corresponding coupling dynamics. - // The coupling with multi-body dynamics will be introduced at last. //---------------------------------------------------------------------- - SimpleDynamics structure_offset_position(structure, offset); - SimpleDynamics wall_boundary_normal_direction(wall_boundary); - SimpleDynamics str_normal(structure); + UpdateCellLinkedList water_cell_linked_list(water_block); + UpdateCellLinkedList wall_cell_linked_list(wall_boundary); + UpdateCellLinkedList structure_cell_linked_list(structure); - Gravity gravity(Vec3d(0.0, 0.0, -gravity_g)); - SimpleDynamics> constant_gravity(water_block, gravity); + UpdateRelation, Contact<>> + water_block_update_complex_relation(water_block_inner, water_block_contact); + UpdateRelation> + structure_update_contact_relation(structure_contact); + UpdateRelation> + observer_update_contact_relation(observer_contact); + ParticleSortCK particle_sort(water_block); - Dynamics1Level pressure_relaxation(water_block_inner, water_block_contact); - Dynamics1Level density_relaxation(water_block_inner, water_block_contact); - InteractionWithUpdate update_density_by_summation(water_block_inner, water_block_contact); - InteractionWithUpdate viscous_force(water_block_inner, water_block_contact); + Gravity gravity(Vec3d(0.0, 0.0, -gravity_g)); + StateDynamics> constant_gravity(water_block, gravity); + StateDynamics wall_boundary_normal_direction(wall_boundary); + StateDynamics structure_boundary_normal_direction(structure); + StateDynamics water_advection_step_setup(water_block); + StateDynamics water_advection_step_close(water_block); - ReduceDynamics get_fluid_advection_time_step_size(water_block, U_f); - ReduceDynamics get_fluid_time_step_size(water_block); + InteractionDynamicsCK + fluid_acoustic_step_1st_half(water_block_inner, water_block_contact); + InteractionDynamicsCK + fluid_acoustic_step_2nd_half(water_block_inner, water_block_contact); + InteractionDynamicsCK + fluid_density_regularization(water_block_inner, water_block_contact); + InteractionDynamicsCK + fluid_viscous_force(water_block_inner, water_block_contact); + InteractionDynamicsCK> + viscous_force_on_structure(structure_contact); + InteractionDynamicsCK> + pressure_force_on_structure(structure_contact); - InteractionWithUpdate viscous_force_on_solid(structure_contact); - InteractionWithUpdate> pressure_force_on_solid(structure_contact); - /*-------------------------------------------------------------------------------*/ - /*--------------------------FREE SURFACE IDENTIFICATION--------------------------*/ - /*-------------------------------------------------------------------------------*/ - InteractionWithUpdate - free_stream_surface_indicator(water_block_inner, water_block_contact); - /** Impose transport velocity formulation. */ - InteractionWithUpdate> - transport_velocity_correction(water_block_inner, water_block_contact); - //---------------------------------------------------------------------- - // Define the configuration related particles dynamics. - //---------------------------------------------------------------------- - ParticleSorting particle_sorting(water_block); - /*-------------------------------------------------------------------------------*/ + ReduceDynamicsCK fluid_advection_time_step(water_block, U_f); + ReduceDynamicsCK fluid_acoustic_time_step(water_block); //---------------------------------------------------------------------- // Define the multi-body system //---------------------------------------------------------------------- @@ -239,7 +240,8 @@ int main(int ac, char *av[]) * @note The body's origin location can be the mass center, the the center of mass should be SimTKVec3(0) * in SimTK::MassProperties(mass, com, inertia) */ - SimTK::MobilizedBody::Planar structure_mob(matter.Ground(), SimTK::Transform(SimTKVec3(G[0], G[1], G[2])), structure_info, SimTK::Transform(SimTKVec3(0.0, 0.0, 0.0))); + SimTK::MobilizedBody::Planar structure_mob(matter.Ground(), SimTK::Transform(SimTKVec3(G[0], G[1], G[2])), + structure_info, SimTK::Transform(SimTKVec3(0.0, 0.0, 0.0))); /** * @details Add gravity to mb body. * @param[in,out] forces, The subsystem to which this force should be added. @@ -276,111 +278,112 @@ int main(int ac, char *av[]) //---------------------------------------------------------------------- // Coupling between SimBody and SPH //---------------------------------------------------------------------- - ReduceDynamics + ReduceDynamicsCK force_on_structure(structure_multibody, MBsystem, structure_mob, integ); - SimpleDynamics + StateDynamics constraint_on_structure(structure_multibody, MBsystem, structure_mob, integ); //---------------------------------------------------------------------- // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- BodyStatesRecordingToVtp write_real_body_states(sph_system); - RegressionTestDynamicTimeWarping>> + RegressionTestDynamicTimeWarping>> wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); - InteractionDynamics> - interpolation_observer_position(observer_contact_with_structure, "Position", "Position"); - RegressionTestDynamicTimeWarping> - write_str_displacement("Position", observer_contact_with_structure); + RegressionTestDynamicTimeWarping> + write_structure_position("Position", observer_contact); + //---------------------------------------------------------------------- + // Prepare the simulation with cell linked list, configuration + // and case specified initial condition if necessary. + //---------------------------------------------------------------------- + wall_boundary_normal_direction.exec(); + structure_boundary_normal_direction.exec(); + constant_gravity.exec(); + + water_cell_linked_list.exec(); + wall_cell_linked_list.exec(); + structure_cell_linked_list.exec(); + + water_block_update_complex_relation.exec(); + structure_update_contact_relation.exec(); + observer_update_contact_relation.exec(); //---------------------------------------------------------------------- // Basic control parameters for time stepping. //---------------------------------------------------------------------- - Real &physical_time = *sph_system.getSystemVariableDataByName("PhysicalTime"); + SingularVariable *sv_physical_time = sph_system.getSystemVariableByName("PhysicalTime"); int number_of_iterations = 0; int screen_output_interval = 1000; Real end_time = total_physical_time; Real output_interval = end_time / 200; - Real dt = 0.0; Real total_time = 0.0; Real relax_time = 1.0; /** statistics for computing time. */ TickCount t1 = TickCount::now(); TimeInterval interval; //---------------------------------------------------------------------- - // Prepare the simulation with cell linked list, configuration - // and case specified initial condition if necessary. - //---------------------------------------------------------------------- - structure_offset_position.exec(); - sph_system.initializeSystemCellLinkedLists(); - sph_system.initializeSystemConfigurations(); - wall_boundary_normal_direction.exec(); - str_normal.exec(); - constant_gravity.exec(); - //---------------------------------------------------------------------- // First output before the main loop. //---------------------------------------------------------------------- - write_real_body_states.writeToFile(number_of_iterations); - write_str_displacement.writeToFile(number_of_iterations); + write_real_body_states.writeToFile(MainExecutionPolicy{}); + write_structure_position.writeToFile(number_of_iterations); wave_gauge.writeToFile(number_of_iterations); //---------------------------------------------------------------------- // Main loop of time stepping starts here. //---------------------------------------------------------------------- - while (physical_time < end_time) + while (sv_physical_time->getValue() < end_time) { Real integral_time = 0.0; while (integral_time < output_interval) { - Real Dt = get_fluid_advection_time_step_size.exec(); - update_density_by_summation.exec(); - viscous_force.exec(); - viscous_force_on_solid.exec(); + fluid_density_regularization.exec(); + water_advection_step_setup.exec(); + Real advection_dt = fluid_advection_time_step.exec(); + fluid_viscous_force.exec(); + viscous_force_on_structure.exec(); Real relaxation_time = 0.0; - while (relaxation_time < Dt) + Real acoustic_dt = 0.0; + while (relaxation_time < advection_dt) { - dt = get_fluid_time_step_size.exec(); - - pressure_relaxation.exec(dt); - pressure_force_on_solid.exec(); - density_relaxation.exec(dt); - /** coupled rigid body dynamics. */ - if (total_time >= relax_time) + acoustic_dt = fluid_acoustic_time_step.exec(); + fluid_acoustic_step_1st_half.exec(acoustic_dt); + pressure_force_on_structure.exec(); + if (total_time >= relax_time) // coupled rigid body dynamics. { SimTK::State &state_for_update = integ.updAdvancedState(); force_on_bodies.clearAllBodyForces(state_for_update); force_on_bodies.setOneBodyForce(state_for_update, structure_mob, force_on_structure.exec()); - integ.stepBy(dt); + integ.stepBy(acoustic_dt); constraint_on_structure.exec(); } - interpolation_observer_position.exec(); + fluid_acoustic_step_2nd_half.exec(acoustic_dt); - relaxation_time += dt; - integral_time += dt; - total_time += dt; + relaxation_time += acoustic_dt; + integral_time += acoustic_dt; + total_time += acoustic_dt; if (total_time >= relax_time) - physical_time += dt; + sv_physical_time->incrementValue(acoustic_dt); } + water_advection_step_close.exec(); if (number_of_iterations % screen_output_interval == 0) { std::cout << std::fixed << std::setprecision(9) << "N=" << number_of_iterations << " Total Time = " << total_time - << " Physical Time = " << physical_time - << " Dt = " << Dt << " dt = " << dt << "\n"; + << " Physical Time = " << sv_physical_time->getValue() + << " advection_dt = " << advection_dt << " acoustic_dt = " << acoustic_dt << "\n"; } number_of_iterations++; if (number_of_iterations % 100 == 0 && number_of_iterations != 1) { - particle_sorting.exec(); + particle_sort.exec(); } - water_block.updateCellLinkedList(); - wall_boundary.updateCellLinkedList(); - structure.updateCellLinkedList(); - water_block_complex.updateConfiguration(); - structure_contact.updateConfiguration(); - observer_contact_with_water.updateConfiguration(); + water_cell_linked_list.exec(); + structure_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); + structure_update_contact_relation.exec(); if (total_time >= relax_time) { - write_str_displacement.writeToFile(number_of_iterations); + write_structure_position.writeToFile(number_of_iterations); wave_gauge.writeToFile(number_of_iterations); } } @@ -400,12 +403,12 @@ int main(int ac, char *av[]) if (sph_system.GenerateRegressionData()) { - write_str_displacement.generateDataBase(1e-3); + write_structure_position.generateDataBase(1e-3); wave_gauge.generateDataBase(1e-3); } else { - write_str_displacement.testResult(); + write_structure_position.testResult(); wave_gauge.testResult(); } From 8192c03084e3076a637df2e87f5c78ee997a2ceb Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Fri, 7 Feb 2025 18:21:42 +0000 Subject: [PATCH 12/33] to test locally --- .../test_3d_stfb_sycl/CMakeLists.txt | 24 + ...hapeBox_FreeSurfaceHeight_Run_0_result.xml | 9 + ...hapeBox_FreeSurfaceHeight_Run_3_result.xml | 9 + ...hapeBox_FreeSurfaceHeight_Run_5_result.xml | 9 + ...ShapeBox_FreeSurfaceHeight_dtwdistance.xml | 4 + ...ricShapeBox_FreeSurfaceHeight_runtimes.dat | 3 + .../Observer_Position_Run_0_result.xml | 9 + .../Observer_Position_Run_3_result.xml | 9 + .../Observer_Position_Run_6_result.xml | 9 + .../Observer_Position_dtwdistance.xml | 4 + .../Observer_Position_runtimes.dat | 3 + .../regression_test_tool.py | 45 ++ .../3d_examples/test_3d_stfb_sycl/stfb.cpp | 416 ++++++++++++++++++ 13 files changed, 553 insertions(+) create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/CMakeLists.txt create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_0_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_3_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_6_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_dtwdistance.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_runtimes.dat create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/regression_test_tool.py create mode 100644 tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/CMakeLists.txt b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/CMakeLists.txt new file mode 100644 index 0000000000..1df97abcfa --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/CMakeLists.txt @@ -0,0 +1,24 @@ +STRING(REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}) +PROJECT("${CURRENT_FOLDER}") + +SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) +SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin/") +SET(BUILD_INPUT_PATH "${EXECUTABLE_OUTPUT_PATH}/input") +SET(BUILD_RELOAD_PATH "${EXECUTABLE_OUTPUT_PATH}/reload") + +file(MAKE_DIRECTORY ${BUILD_INPUT_PATH}) +execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${BUILD_INPUT_PATH}) +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/regression_test_tool/ + DESTINATION ${BUILD_INPUT_PATH}) + +add_executable(${PROJECT_NAME}) +aux_source_directory(. DIR_SRCS) +target_sources(${PROJECT_NAME} PRIVATE ${DIR_SRCS}) +target_link_libraries(${PROJECT_NAME} sphinxsys_3d) +set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}") + +add_test(NAME ${PROJECT_NAME} + COMMAND ${PROJECT_NAME} --state_recording=${TEST_STATE_RECORDING} + WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) + +set_tests_properties(${PROJECT_NAME} PROPERTIES LABELS "fluid dynamics, Simbody") diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml new file mode 100644 index 0000000000..05cf9cd33e --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml new file mode 100644 index 0000000000..ff38e15646 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_3_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml new file mode 100644 index 0000000000..a342adeb4d --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_Run_5_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml new file mode 100644 index 0000000000..5b459b5e2b --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat new file mode 100644 index 0000000000..de07de18db --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/GeometricShapeBox_FreeSurfaceHeight_runtimes.dat @@ -0,0 +1,3 @@ +true +6 +4 \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_0_result.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_0_result.xml new file mode 100644 index 0000000000..9e3427c2b7 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_3_result.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_3_result.xml new file mode 100644 index 0000000000..cb0aeb2627 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_3_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_6_result.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_6_result.xml new file mode 100644 index 0000000000..ab2fef3ede --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_Run_6_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_dtwdistance.xml b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_dtwdistance.xml new file mode 100644 index 0000000000..6a83063405 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_runtimes.dat b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_runtimes.dat new file mode 100644 index 0000000000..34de7daedb --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/Observer_Position_runtimes.dat @@ -0,0 +1,3 @@ +true +7 +4 \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/regression_test_tool.py b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/regression_test_tool.py new file mode 100644 index 0000000000..c60eb85953 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/regression_test_tool/regression_test_tool.py @@ -0,0 +1,45 @@ +# !/usr/bin/env python3 +import os +import sys + +path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') +sys.path.append(path) +from regression_test_base_tool import SphinxsysRegressionTest + +""" +case name: test_3d_stfb +""" + +case_name = "test_3d_stfb" +body_name = "GeometricShapeBox" +parameter_name = "FreeSurfaceHeight" +body_name_1 = "Observer" +parameter_name_1 = "Position" + +number_of_run_times = 0 +converged = 0 +sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) +sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) +clean_input_folder(sphinxsys.input_file_path) + + +while True: + print("Now start a new run......") + sphinxsys.run_case() + number_of_run_times += 1 + converged = sphinxsys.read_dat_file() + converged_1 = sphinxsys_1.read_dat_file() + print("Please note: This is the", number_of_run_times, "run!") + if number_of_run_times <= 200: + if (converged == "true") and (converged_1 == "true"): + print("The tested parameters of all variables are converged, and the run will stop here!") + break + elif converged != "true": + print("The tested parameters of", sphinxsys.sphinxsys_parameter_name, "are not converged!") + continue + elif converged_1 != "true": + print("The tested parameters of", sphinxsys_1.sphinxsys_parameter_name, "are not converged!") + continue + else: + print("It's too many runs but still not converged, please try again!") + break diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp new file mode 100644 index 0000000000..08978d3637 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp @@ -0,0 +1,416 @@ +/** + * @file stfb.cpp + * @brief This is the case file for 3D still floating body using computing kernel. + * @author Nicolò Salis and Xiangyu Hu + */ +#include "sphinxsys_sycl.h" //SPHinXsys Library. +using namespace SPH; +//---------------------------------------------------------------------- +// Basic geometry parameters and numerical setup. +//---------------------------------------------------------------------- +Real total_physical_time = 5.0; /**< TOTAL SIMULATION TIME*/ +Real DW = 3.0; /**< Water length. */ +Real DL = 3.0; /**< Tank length. */ +Real DH = 2.5; /**< Tank height. */ +Real WH = 2.0; /**< Water block height. */ +Real L = 1.0; /**< Base of the floating body. */ +Real particle_spacing_ref = L / 10; +Real BW = particle_spacing_ref * 4.0; /**< Extending width for BCs. */ +Real Maker_width = particle_spacing_ref * 4.0; /**< Width of the wave_maker. */ +BoundingBox system_domain_bounds(Vecd(-BW, -BW, -BW), Vecd(DW + BW, DL + BW, DH + BW)); +Vecd offset = Vecd::Zero(); +//---------------------------------------------------------------------- +// Material properties of the fluid. +//---------------------------------------------------------------------- +Real rho0_f = 1000.0; /**< Reference density of fluid. */ +Real gravity_g = 9.81; /**< Value of gravity. */ +Real U_f = 2.0 * sqrt(WH * gravity_g); /**< Characteristic velocity. */ +Real c_f = 10.0 * U_f; /**< Reference sound speed. */ +Real mu_f = 1.0e-3; +//---------------------------------------------------------------------- +// Structure Properties G and Inertia +//---------------------------------------------------------------------- +/* Weight of the solid structure*/ +Real StructureMass = 700; +/**< Area of the solid structure*/ +Real FlStA = L * L * L; +/**< Density of the solid structure*/ +Real rho_s = StructureMass / FlStA; +/* Equilibrium position of the solid structure*/ +Real H = WH - (rho_s / rho0_f * L - L / 2); /**< Strart placement of Flt Body*/ + +Real bcmx = DL / 2; +Real bcmy = DL / 2; +Real bcmz = H; +Vecd G(bcmx, bcmy, bcmz); +Real Ix = StructureMass / 12 * (L * L + L * L); +Real Iy = StructureMass / 12 * (L * L + L * L); +Real Iz = StructureMass / 12 * (L * L + L * L); +/** Structure observer position */ +Vecd obs = G; +/** Geometry definition. */ +Vecd halfsize_structure(0.5 * L, 0.5 * L, 0.5 * L); +Vecd structure_pos(G[0], G[1], G[2]); +Transform translation_str(structure_pos); +//------------------------------------------------------------------------------ +// Geometric shapes used in the case +//------------------------------------------------------------------------------ +class FloatingStructure : public ComplexShape +{ + public: + explicit FloatingStructure(const std::string &shape_name) : ComplexShape(shape_name) + { + add>(Transform(translation_str), halfsize_structure); + } +}; + +class StructureSystemForSimbody : public SolidBodyPartForSimbody +{ + public: + StructureSystemForSimbody(SPHBody &sph_body, Shape &shape) + : SolidBodyPartForSimbody(sph_body, shape) + { + // Vec2d mass_center(G[0], G[1]); + // initial_mass_center_ = SimTKVec3(mass_center[0], mass_center[1], 0.0); + body_part_mass_properties_ = + mass_properties_ptr_keeper_ + .createPtr(StructureMass, SimTKVec3(0.0), SimTK::UnitInertia(Ix, Iy, Iz)); + } +}; +//---------------------------------------------------------------------- +// Water block +//---------------------------------------------------------------------- +class WaterBlock : public ComplexShape +{ + public: + explicit WaterBlock(const std::string &shape_name) : ComplexShape(shape_name) + { + /** Geometry definition. */ + Vecd halfsize_water(0.5 * DW, 0.5 * DL, 0.5 * WH); + Vecd water_pos(0.5 * DW, 0.5 * DL, 0.5 * WH); + Transform translation_water(water_pos); + add>(Transform(translation_water), halfsize_water); + subtract>(Transform(translation_str), halfsize_structure); + } +}; +//---------------------------------------------------------------------- +// Wall geometries. +//---------------------------------------------------------------------- +class WallBoundary : public ComplexShape +{ + public: + explicit WallBoundary(const std::string &shape_name) : ComplexShape(shape_name) + { + Vecd halfsize_wall_outer(0.5 * DW + BW, 0.5 * DL + BW, 0.5 * DH + BW); + Vecd wall_outer_pos(0.5 * DW, 0.5 * DL, 0.5 * DH); + Transform translation_wall_outer(wall_outer_pos); + add>(Transform(translation_wall_outer), halfsize_wall_outer); + + Vecd halfsize_wall_inner(0.5 * DW, 0.5 * DL, 0.5 * DH + BW); + Vecd wall_inner_pos(0.5 * DW, 0.5 * DL, 0.5 * DH + BW); + Transform translation_wall_inner(wall_inner_pos); + subtract>(Transform(translation_wall_inner), halfsize_wall_inner); + } +}; +//---------------------------------------------------------------------- +// create measuring probes +//---------------------------------------------------------------------- +Real h = 1.3 * particle_spacing_ref; +Vecd FS_gaugeDim(0.5 * h, 0.5 * h, 0.5 * DH); +Vecd FS_gauge(DW / 3, DL / 3, 0.5 * DH); +Transform translation_FS_gauge(FS_gauge); +//---------------------------------------------------------------------- +// Main program starts here. +//---------------------------------------------------------------------- +int main(int ac, char *av[]) +{ + std::cout << "Mass " << StructureMass << " str_sup " << FlStA << " rho_s " << rho_s << std::endl; + //---------------------------------------------------------------------- + // Build up the environment of a SPHSystem with global controls. + //---------------------------------------------------------------------- + SPHSystem sph_system(system_domain_bounds, particle_spacing_ref); + sph_system.handleCommandlineOptions(ac, av)->setIOEnvironment(); + //---------------------------------------------------------------------- + // Creating body, materials and particles. + //---------------------------------------------------------------------- + FluidBody water_block(sph_system, makeShared("WaterBody")); + water_block.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); + water_block.generateParticles(); + + SolidBody wall_boundary(sph_system, makeShared("WallBoundary")); + wall_boundary.defineMaterial(); + wall_boundary.generateParticles(); + + SolidBody structure(sph_system, makeShared("Structure")); + structure.defineMaterial(rho_s); + structure.generateParticles(); + + ObserverBody observer(sph_system, "Observer"); + observer.defineAdaptationRatios(1.15, 2.0); + observer.generateParticles(StdVec{obs}); + //---------------------------------------------------------------------- + // Creating body parts. + //---------------------------------------------------------------------- + TransformShape wave_probe_buffer_shape(Transform(translation_FS_gauge), FS_gauge); + BodyRegionByCell wave_probe_buffer(water_block, wave_probe_buffer_shape); + //---------------------------------------------------------------------- + // Define body relation map. + // The contact map gives the topological connections between the bodies. + // Basically the the range of bodies to build neighbor particle lists. + // Generally, we first define all the inner relations, then the contact relations. + // At last, we define the complex relaxations by combining previous defined + // inner and contact relations. + //---------------------------------------------------------------------- + Relation> water_block_inner(water_block); + Relation> water_block_contact(water_block, {&wall_boundary, &structure}); + Relation> structure_contact(structure, {&water_block}); + Relation> observer_contact(observer, {&structure}); + //---------------------------------------------------------------------- + // Define the main execution policy for this case. + //---------------------------------------------------------------------- + using MainExecutionPolicy = execution::ParallelDevicePolicy; + //---------------------------------------------------------------------- + // Define the numerical methods used in the simulation. + // Note that there may be data dependence on the sequence of constructions. + // Generally, the configuration dynamics, such as update cell linked list, + // update body relations, are defiend first. + // Then the geometric models or simple objects without data dependencies, + // such as gravity, initialized normal direction. + // After that, the major physical particle dynamics model should be introduced. + // Finally, the auxiliary models such as time step estimator, initial condition, + // boundary condition and other constraints should be defined. + //---------------------------------------------------------------------- + UpdateCellLinkedList water_cell_linked_list(water_block); + UpdateCellLinkedList wall_cell_linked_list(wall_boundary); + UpdateCellLinkedList structure_cell_linked_list(structure); + + UpdateRelation, Contact<>> + water_block_update_complex_relation(water_block_inner, water_block_contact); + UpdateRelation> + structure_update_contact_relation(structure_contact); + UpdateRelation> + observer_update_contact_relation(observer_contact); + ParticleSortCK particle_sort(water_block); + + Gravity gravity(Vec3d(0.0, 0.0, -gravity_g)); + StateDynamics> constant_gravity(water_block, gravity); + StateDynamics wall_boundary_normal_direction(wall_boundary); + StateDynamics structure_boundary_normal_direction(structure); + StateDynamics water_advection_step_setup(water_block); + StateDynamics water_advection_step_close(water_block); + + InteractionDynamicsCK + fluid_acoustic_step_1st_half(water_block_inner, water_block_contact); + InteractionDynamicsCK + fluid_acoustic_step_2nd_half(water_block_inner, water_block_contact); + InteractionDynamicsCK + fluid_density_regularization(water_block_inner, water_block_contact); + InteractionDynamicsCK + fluid_viscous_force(water_block_inner, water_block_contact); + InteractionDynamicsCK> + viscous_force_on_structure(structure_contact); + InteractionDynamicsCK> + pressure_force_on_structure(structure_contact); + + ReduceDynamicsCK fluid_advection_time_step(water_block, U_f); + ReduceDynamicsCK fluid_acoustic_time_step(water_block); + //---------------------------------------------------------------------- + // Define the multi-body system + //---------------------------------------------------------------------- + /** set up the multi body system. */ + SimTK::MultibodySystem MBsystem; + /** the bodies or matter of the system. */ + SimTK::SimbodyMatterSubsystem matter(MBsystem); + /** the forces of the system. */ + SimTK::GeneralForceSubsystem forces(MBsystem); + /** mass properties of the fixed spot. */ + TransformShape fix_spot_shape(Transform(translation_str), halfsize_structure); + StructureSystemForSimbody structure_multibody(structure, fix_spot_shape); + /** Mass properties of the constrained spot. + * SimTK::MassProperties(mass, center of mass, inertia) + */ + SimTK::Body::Rigid structure_info(*structure_multibody.body_part_mass_properties_); + /** + * @brief ** Create a %Planar mobilizer between an existing parent (inboard) body P + * and a new child (outboard) body B created by copying the given \a bodyInfo + * into a privately-owned Body within the constructed %MobilizedBody object. + * Specify the mobilizer frames F fixed to parent P and M fixed to child B. + * @param[in] inboard(SimTKVec3) Defines the location of the joint point relative to the parent body. + * @param[in] outboard(SimTKVec3) Defines the body's origin location to the joint point. + * @note The body's origin location can be the mass center, the the center of mass should be SimTKVec3(0) + * in SimTK::MassProperties(mass, com, inertia) + */ + SimTK::MobilizedBody::Planar structure_mob(matter.Ground(), SimTK::Transform(SimTKVec3(G[0], G[1], G[2])), + structure_info, SimTK::Transform(SimTKVec3(0.0, 0.0, 0.0))); + /** + * @details Add gravity to mb body. + * @param[in,out] forces, The subsystem to which this force should be added. + * @param[in] matter, The subsystem containing the bodies that will be affected. + * @param[in] gravity, The default gravity vector v, interpreted as v=g*d where g=|\a gravity| is + * a positive scalar and d is the "down" direction unit vector d=\a gravity/g. + * @param[in] zeroHeight This is an optional specification of the default value for the height + * up the gravity vector that is considered to be "zero" for purposes of + * calculating the gravitational potential energy. The default is + * \a zeroHeight == 0, i.e., a body's potential energy is defined to be zero + * when the height of its mass center is the same as the height of the Ground + * origin. The zero height will have the value specified here unless + * explicitly changed within a particular State use the setZeroHeight() + * method. + * @par Force Each body B that has not been explicitly excluded will experience a force + * fb = mb*g*d, applied to its center of mass, where mb is the mass of body B. + * @par Potential Energy + * Gravitational potential energy for a body B is mb*g*hb where hb is the height of + * body B's mass center over an arbitrary "zero" height hz (default is hz=0), + * measured along the "up" direction -d. If pb is the Ground frame vector giving + * the position of body B's mass center, its height over or under hz is + * hb=pb*(-d) - hz. Note that this is a signed quantity so the potential energy is + * also signed. 0.475 + */ + SimTK::Force::UniformGravity sim_gravity(forces, matter, SimTKVec3(0.0, 0.0, -gravity_g), 0.0); + /** discrete forces acting on the bodies. */ + SimTK::Force::DiscreteForces force_on_bodies(forces, matter); + /** Time stepping method for multibody system.*/ + SimTK::State state = MBsystem.realizeTopology(); + SimTK::RungeKuttaMersonIntegrator integ(MBsystem); + integ.setAccuracy(1e-3); + integ.setAllowInterpolation(false); + integ.initialize(state); + //---------------------------------------------------------------------- + // Coupling between SimBody and SPH + //---------------------------------------------------------------------- + ReduceDynamicsCK + force_on_structure(structure_multibody, MBsystem, structure_mob, integ); + StateDynamics + constraint_on_structure(structure_multibody, MBsystem, structure_mob, integ); + //---------------------------------------------------------------------- + // Define the methods for I/O operations and observations of the simulation. + //---------------------------------------------------------------------- + BodyStatesRecordingToVtp write_real_body_states(sph_system); + RegressionTestDynamicTimeWarping>> + wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); + RegressionTestDynamicTimeWarping> + write_structure_position("Position", observer_contact); + //---------------------------------------------------------------------- + // Prepare the simulation with cell linked list, configuration + // and case specified initial condition if necessary. + //---------------------------------------------------------------------- + wall_boundary_normal_direction.exec(); + structure_boundary_normal_direction.exec(); + constant_gravity.exec(); + + water_cell_linked_list.exec(); + wall_cell_linked_list.exec(); + structure_cell_linked_list.exec(); + + water_block_update_complex_relation.exec(); + structure_update_contact_relation.exec(); + observer_update_contact_relation.exec(); + //---------------------------------------------------------------------- + // Basic control parameters for time stepping. + //---------------------------------------------------------------------- + SingularVariable *sv_physical_time = sph_system.getSystemVariableByName("PhysicalTime"); + int number_of_iterations = 0; + int screen_output_interval = 1000; + Real end_time = total_physical_time; + Real output_interval = end_time / 200; + Real total_time = 0.0; + Real relax_time = 1.0; + /** statistics for computing time. */ + TickCount t1 = TickCount::now(); + TimeInterval interval; + //---------------------------------------------------------------------- + // First output before the main loop. + //---------------------------------------------------------------------- + write_real_body_states.writeToFile(MainExecutionPolicy{}); + write_structure_position.writeToFile(number_of_iterations); + wave_gauge.writeToFile(number_of_iterations); + //---------------------------------------------------------------------- + // Main loop of time stepping starts here. + //---------------------------------------------------------------------- + while (sv_physical_time->getValue() < end_time) + { + Real integral_time = 0.0; + while (integral_time < output_interval) + { + fluid_density_regularization.exec(); + water_advection_step_setup.exec(); + Real advection_dt = fluid_advection_time_step.exec(); + fluid_viscous_force.exec(); + viscous_force_on_structure.exec(); + + Real relaxation_time = 0.0; + Real acoustic_dt = 0.0; + while (relaxation_time < advection_dt) + { + acoustic_dt = fluid_acoustic_time_step.exec(); + fluid_acoustic_step_1st_half.exec(acoustic_dt); + pressure_force_on_structure.exec(); + if (total_time >= relax_time) // coupled rigid body dynamics. + { + SimTK::State &state_for_update = integ.updAdvancedState(); + force_on_bodies.clearAllBodyForces(state_for_update); + force_on_bodies.setOneBodyForce(state_for_update, structure_mob, force_on_structure.exec()); + integ.stepBy(acoustic_dt); + constraint_on_structure.exec(); + } + fluid_acoustic_step_2nd_half.exec(acoustic_dt); + + relaxation_time += acoustic_dt; + integral_time += acoustic_dt; + total_time += acoustic_dt; + if (total_time >= relax_time) + sv_physical_time->incrementValue(acoustic_dt); + } + water_advection_step_close.exec(); + + if (number_of_iterations % screen_output_interval == 0) + { + std::cout << std::fixed << std::setprecision(9) << "N=" << number_of_iterations + << " Total Time = " << total_time + << " Physical Time = " << sv_physical_time->getValue() + << " advection_dt = " << advection_dt << " acoustic_dt = " << acoustic_dt << "\n"; + } + number_of_iterations++; + if (number_of_iterations % 100 == 0 && number_of_iterations != 1) + { + particle_sort.exec(); + } + water_cell_linked_list.exec(); + structure_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); + structure_update_contact_relation.exec(); + + if (total_time >= relax_time) + { + write_structure_position.writeToFile(number_of_iterations); + wave_gauge.writeToFile(number_of_iterations); + } + } + + TickCount t2 = TickCount::now(); + if (total_time >= relax_time) + write_real_body_states.writeToFile(); + TickCount t3 = TickCount::now(); + interval += t3 - t2; + } + + TickCount t4 = TickCount::now(); + + TimeInterval tt; + tt = t4 - t1 - interval; + std::cout << "Total wall time for computation: " << tt.seconds() << " seconds." << std::endl; + + if (sph_system.GenerateRegressionData()) + { + write_structure_position.generateDataBase(1e-3); + wave_gauge.generateDataBase(1e-3); + } + else + { + write_structure_position.testResult(); + wave_gauge.testResult(); + } + + return 0; +} From 869c9019de6ee34d813c60642ce66bab4f3dab77 Mon Sep 17 00:00:00 2001 From: xiangyu_hu Date: Fri, 7 Feb 2025 19:51:10 +0100 Subject: [PATCH 13/33] to test cpu sycl --- tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 2 +- tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index 0102d472f9..1faee2ba34 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -390,7 +390,7 @@ int main(int ac, char *av[]) TickCount t2 = TickCount::now(); if (total_time >= relax_time) - write_real_body_states.writeToFile(); + write_real_body_states.writeToFile(MainExecutionPolicy{}); TickCount t3 = TickCount::now(); interval += t3 - t2; } diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp index 08978d3637..045564f72a 100644 --- a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp @@ -390,7 +390,7 @@ int main(int ac, char *av[]) TickCount t2 = TickCount::now(); if (total_time >= relax_time) - write_real_body_states.writeToFile(); + write_real_body_states.writeToFile(MainExecutionPolicy{}); TickCount t3 = TickCount::now(); interval += t3 - t2; } From becf394606436420f6f8d7f67f097f97f1060a7a Mon Sep 17 00:00:00 2001 From: xiangyu_hu Date: Fri, 7 Feb 2025 22:33:34 +0100 Subject: [PATCH 14/33] no mixing shared and device memory in single expression. --- .../particle_dynamics/solid_dynamics/solid_constraint.h | 4 ++-- .../particle_dynamics/solid_dynamics/solid_constraint.hpp | 6 +++--- src/shared/simbody_sphinxsys/all_simbody.h | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h index faa9247332..1d83052727 100644 --- a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h @@ -97,7 +97,7 @@ class TotalForceForSimBodyCK protected: Vecd *force_, *force_prior_, *pos_; - Vecd *current_origin_location_; + Vec3d *current_origin_location_; }; protected: @@ -105,7 +105,7 @@ class TotalForceForSimBodyCK SimTK::MobilizedBody &mobod_; SimTK::RungeKuttaMersonIntegrator &integ_; DiscreteVariable *dv_force_, *dv_force_prior_, *dv_pos_; - SingularVariable *sv_current_origin_location_; + SingularVariable *sv_current_origin_location_; }; using TotalForceOnBodyForSimBodyCK = TotalForceForSimBodyCK; using TotalForceOnBodyPartForSimBodyCK = TotalForceForSimBodyCK; diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp index 282f0fbbd1..8e43d52c30 100644 --- a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp @@ -89,7 +89,7 @@ TotalForceForSimBodyCK:: dv_force_prior_(this->particles_->template getVariableByName("ForcePrior")), dv_pos_(this->particles_->template getVariableByName("Position")), sv_current_origin_location_( - this->particles_->template addUniqueSingularVariableOnly( + this->particles_->template addUniqueSingularVariableOnly( identifier.getName() + "OriginLocation")) { this->quantity_name_ = "TotalForceForSimBody"; @@ -100,7 +100,7 @@ void TotalForceForSimBodyCK::setupDynamics(Real dt) { const SimTK::State *state = &integ_.getState(); MBsystem_.realize(*state, SimTK::Stage::Acceleration); - sv_current_origin_location_->setValue(degradeToVecd(SimTKToEigen(mobod_.getBodyOriginLocation(*state)))); + sv_current_origin_location_->setValue(SimTKToEigen(mobod_.getBodyOriginLocation(*state))); } //=================================================================================================// template @@ -118,7 +118,7 @@ SimTK::SpatialVec TotalForceForSimBodyCK:: { Vecd force = force_[index_i] + force_prior_[index_i]; Vec3d force_from_particle = upgradeToVec3d(force); - Vecd displacement = pos_[index_i] - *current_origin_location_; + Vecd displacement = pos_[index_i] - degradeToVecd(*current_origin_location_); Vec3d torque_from_particle = upgradeToVec3d(displacement).cross(force_from_particle); return SimTK::SpatialVec(EigenToSimTK(torque_from_particle), EigenToSimTK(force_from_particle)); } diff --git a/src/shared/simbody_sphinxsys/all_simbody.h b/src/shared/simbody_sphinxsys/all_simbody.h index a97668c90d..b96a74cd02 100644 --- a/src/shared/simbody_sphinxsys/all_simbody.h +++ b/src/shared/simbody_sphinxsys/all_simbody.h @@ -41,13 +41,13 @@ namespace SPH template <> struct ZeroData { - static inline SimTK::SpatialVec value = SimTK::SpatialVec(SimTKVec3(0), SimTKVec3(0)); + static inline const SimTK::SpatialVec value = SimTK::SpatialVec(SimTKVec3(0), SimTKVec3(0)); }; template <> struct ZeroData { - static inline SimTKVec3 value = SimTKVec3(0); + static inline const SimTKVec3 value = SimTKVec3(0); }; struct SimbodyState @@ -90,7 +90,7 @@ struct SimbodyState template <> struct ZeroData { - static inline SimbodyState value = SimbodyState(); + static inline const SimbodyState value = SimbodyState(); }; } // namespace SPH #endif // ALL_SIMBODY_H \ No newline at end of file From 51341f073d6a742709ef65f9bd37990e54a2e71f Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Sat, 8 Feb 2025 22:16:52 +0000 Subject: [PATCH 15/33] I see strange behavior on Nvidia GPU (first run, ok, second run crash but third run ok again) for the stfb_sycl case. This does not happen for sycl using intel CPU as device, or the tbb using computing kernel. --- src/shared/io_system/io_base.cpp | 18 ++++++---- src/shared/io_system/io_base.h | 29 +++++++--------- src/shared/io_system/io_observation.h | 4 +-- src/shared/io_system/io_vtk.hpp | 10 ------ src/shared/particles/base_particles.cpp | 1 + .../shared_ck/io_system/io_observation_ck.h | 4 +-- .../update_body_relation.hpp | 6 +--- .../solid_dynamics/solid_constraint.h | 4 +-- .../solid_dynamics/solid_constraint.hpp | 33 ++++++------------- src/shared/simbody_sphinxsys/all_simbody.h | 20 +++++++---- .../shared/common/sphinxsys_variable_sycl.hpp | 2 +- 11 files changed, 55 insertions(+), 76 deletions(-) diff --git a/src/shared/io_system/io_base.cpp b/src/shared/io_system/io_base.cpp index 9a6504f25d..4fcfd87af5 100644 --- a/src/shared/io_system/io_base.cpp +++ b/src/shared/io_system/io_base.cpp @@ -7,11 +7,11 @@ namespace SPH //=============================================================================================// BaseIO::BaseIO(SPHSystem &sph_system) : sph_system_(sph_system), io_environment_(sph_system.getIOEnvironment()), - sv_physical_time_(*sph_system_.getSystemVariableByName("PhysicalTime")) {} + sv_physical_time_(sph_system_.getSystemVariableByName("PhysicalTime")) {} //=============================================================================================// std::string BaseIO::convertPhysicalTimeToString(Real convertPhysicalTimeToStream) { - int i_time = int(sv_physical_time_.getValue() * 1.0e6); + int i_time = int(sv_physical_time_->getValue() * 1.0e6); return padValueWithZeros(i_time); } //=============================================================================================/ @@ -25,7 +25,6 @@ bool BaseIO::isBodyIncluded(const SPHBodyVector &bodies, SPHBody *sph_body) //=============================================================================================// BodyStatesRecording::BodyStatesRecording(SPHSystem &sph_system) : BaseIO(sph_system), bodies_(sph_system.getRealBodies()), - prepare_variable_to_write_(), state_recording_(sph_system_.StateRecording()) { for (size_t i = 0; i < bodies_.size(); ++i) @@ -37,7 +36,14 @@ BodyStatesRecording::BodyStatesRecording(SPHSystem &sph_system) //=============================================================================================// BodyStatesRecording::BodyStatesRecording(SPHBody &body) : BaseIO(body.getSPHSystem()), bodies_({&body}), - state_recording_(sph_system_.StateRecording()) {} + state_recording_(sph_system_.StateRecording()) +{ + for (size_t i = 0; i < bodies_.size(); ++i) + { + BaseParticles &particles = bodies_[i]->getBaseParticles(); + dv_all_pos_.push_back(particles.getVariableByName("Position")); + } +} //=============================================================================================// void BodyStatesRecording::writeToFile() { @@ -45,7 +51,7 @@ void BodyStatesRecording::writeToFile() { derived_variable->exec(); } - writeWithFileName(convertPhysicalTimeToString(sv_physical_time_.getValue())); + writeWithFileName(convertPhysicalTimeToString(sv_physical_time_->getValue())); } //=============================================================================================// void BodyStatesRecording::writeToFile(size_t iteration_step) @@ -76,7 +82,7 @@ void RestartIO::writeToFile(size_t iteration_step) fs::remove(overall_filefullpath); } std::ofstream out_file(overall_filefullpath.c_str(), std::ios::app); - out_file << std::fixed << std::setprecision(9) << sv_physical_time_.getValue() << " \n"; + out_file << std::fixed << std::setprecision(9) << sv_physical_time_->getValue() << " \n"; out_file.close(); for (size_t i = 0; i < bodies_.size(); ++i) diff --git a/src/shared/io_system/io_base.h b/src/shared/io_system/io_base.h index c75a17490c..8cb788ff3c 100644 --- a/src/shared/io_system/io_base.h +++ b/src/shared/io_system/io_base.h @@ -62,7 +62,7 @@ class BaseIO protected: SPHSystem &sph_system_; IOEnvironment &io_environment_; - SingularVariable &sv_physical_time_; + SingularVariable *sv_physical_time_; std::string convertPhysicalTimeToString(Real physical_time); @@ -78,8 +78,6 @@ class BaseIO struct prepareVariablesToWrite { - prepareVariablesToWrite() {}; - template void operator()(DataContainerAddressKeeper> &variables, const ExecutionPolicy &ex_policy) @@ -105,29 +103,24 @@ class BodyStatesRecording : public BaseIO virtual ~BodyStatesRecording() {}; /** write with filename indicated by physical time */ void writeToFile(); - + void writeToFile(const ParallelDevicePolicy &ex_policy) { for (size_t i = 0; i < bodies_.size(); ++i) { - dv_all_pos_[i]->prepareForOutput(ex_policy); - BaseParticles &base_particles = bodies_[i]->getBaseParticles(); - prepare_variable_to_write_(base_particles.VariablesToWrite(), ex_policy); + if (bodies_[i]->checkNewlyUpdated()) + { + dv_all_pos_[i]->prepareForOutput(ex_policy); + BaseParticles &base_particles = bodies_[i]->getBaseParticles(); + prepare_variable_to_write_(base_particles.VariablesToWrite(), ex_policy); + } } writeToFile(); }; - - void writeToFile(const ParallelPolicy &ex_policy) - { - writeToFile(); - }; - - void writeToFile(const SequencedPolicy &ex_policy) - { - writeToFile(); - }; - + + void writeToFile(const ParallelPolicy &ex_policy) { writeToFile(); }; + void writeToFile(const SequencedPolicy &ex_policy) { writeToFile(); }; virtual void writeToFile(size_t iteration_step) override; template diff --git a/src/shared/io_system/io_observation.h b/src/shared/io_system/io_observation.h index 3b756f0aa8..b51948e3b6 100644 --- a/src/shared/io_system/io_observation.h +++ b/src/shared/io_system/io_observation.h @@ -82,7 +82,7 @@ class ObservedQuantityRecording : public BodyStatesRecording, { this->exec(); std::ofstream out_file(filefullpath_output_.c_str(), std::ios::app); - out_file << sv_physical_time_.getValue() << " "; + out_file << sv_physical_time_->getValue() << " "; for (size_t i = 0; i != base_particles_.TotalRealParticles(); ++i) { plt_engine_.writeAQuantity(out_file, this->interpolated_quantities_[i]); @@ -140,7 +140,7 @@ class ReducedQuantityRecording : public BaseIO virtual void writeToFile(size_t iteration_step = 0) override { std::ofstream out_file(filefullpath_output_.c_str(), std::ios::app); - out_file << sv_physical_time_.getValue() << " "; + out_file << sv_physical_time_->getValue() << " "; plt_engine_.writeAQuantity(out_file, reduce_method_.exec()); out_file << "\n"; out_file.close(); diff --git a/src/shared/io_system/io_vtk.hpp b/src/shared/io_system/io_vtk.hpp index 7be9f487d3..33f341bd49 100644 --- a/src/shared/io_system/io_vtk.hpp +++ b/src/shared/io_system/io_vtk.hpp @@ -23,16 +23,6 @@ void BodyStatesRecordingToVtp::writeParticlesToVtk(OutStreamType &output_stream, output_stream << std::endl; output_stream << " \n"; - // write original particles ID - output_stream << " \n"; - output_stream << " "; - for (size_t i = 0; i != total_real_particles; ++i) - { - output_stream << particles.ParticleOriginalIds()[i] << " "; - } - output_stream << std::endl; - output_stream << " \n"; - // write particle IDs constexpr int type_index_UnsignedInt = DataTypeIndex::value; for (DiscreteVariable *variable : std::get(variables_to_write)) diff --git a/src/shared/particles/base_particles.cpp b/src/shared/particles/base_particles.cpp index b10cd1bf43..832266b500 100644 --- a/src/shared/particles/base_particles.cpp +++ b/src/shared/particles/base_particles.cpp @@ -39,6 +39,7 @@ void BaseParticles::initializeBasicParticleVariables() // unregistered variables and data //---------------------------------------------------------------------- original_id_ = registerDiscreteVariable("OriginalID", particles_bound_, getAssignIndex()); + addVariableToWrite("OriginalID"); sorted_id_ = registerDiscreteVariable("SortedID", particles_bound_, getAssignIndex()); } //=================================================================================================// diff --git a/src/shared/shared_ck/io_system/io_observation_ck.h b/src/shared/shared_ck/io_system/io_observation_ck.h index 7cfd8e13bd..0a2308ee1d 100644 --- a/src/shared/shared_ck/io_system/io_observation_ck.h +++ b/src/shared/shared_ck/io_system/io_observation_ck.h @@ -85,7 +85,7 @@ class ObservedQuantityRecording this->dv_interpolated_quantities_->prepareForOutput(ExecutionPolicy{}); DataType *interpolated_quantities = this->dv_interpolated_quantities_->Data(); std::ofstream out_file(filefullpath_output_.c_str(), std::ios::app); - out_file << sv_physical_time_.getValue() << " "; + out_file << sv_physical_time_->getValue() << " "; for (size_t i = 0; i != base_particles_.TotalRealParticles(); ++i) { plt_engine_.writeAQuantity(out_file, interpolated_quantities[i]); @@ -137,7 +137,7 @@ class ReducedQuantityRecording : public virtual void writeToFile(size_t iteration_step = 0) override { std::ofstream out_file(filefullpath_output_.c_str(), std::ios::app); - out_file << sv_physical_time_.getValue() << " "; + out_file << sv_physical_time_->getValue() << " "; plt_engine_.writeAQuantity(out_file, reduce_method_.exec()); out_file << "\n"; out_file.close(); diff --git a/src/shared/shared_ck/particle_dynamics/configuration_dynamics/update_body_relation.hpp b/src/shared/shared_ck/particle_dynamics/configuration_dynamics/update_body_relation.hpp index 11e72303cb..93e2c87fda 100644 --- a/src/shared/shared_ck/particle_dynamics/configuration_dynamics/update_body_relation.hpp +++ b/src/shared/shared_ck/particle_dynamics/configuration_dynamics/update_body_relation.hpp @@ -15,10 +15,7 @@ UpdateRelation>:: : Interaction>(inner_relation), BaseDynamics(), ex_policy_(ExecutionPolicy{}), cell_linked_list_(inner_relation.getCellLinkedList()), - kernel_implementation_(*this) -{ - this->particles_->addVariableToWrite(this->dv_particle_offset_); -} + kernel_implementation_(*this){} //=================================================================================================// template template @@ -101,7 +98,6 @@ UpdateRelation>:: { for (size_t k = 0; k != this->contact_bodies_.size(); ++k) { - this->particles_->addVariableToWrite(this->dv_contact_particle_offset_[k]); contact_kernel_implementation_.push_back( contact_kernel_implementation_ptrs_.template createPtr(*this)); } diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h index 1d83052727..01583c75f9 100644 --- a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.h @@ -69,9 +69,7 @@ class ConstraintBySimBodyCK : public BaseLocalDynamics DiscreteVariable *dv_pos_, *dv_pos0_, *dv_vel_; DiscreteVariable *dv_n_, *dv_n0_, *dv_acc_; SingularVariable *sv_simbody_state_; - - void initializeSimbodyState(const SimTK::State &state); - void updateSimbodyState(const SimTK::State &state); + SimTKVec3 sim_tk_initial_origin_location_; }; using ConstraintBodyBySimBodyCK = ConstraintBySimBodyCK; using ConstraintBodyPartBySimBodyCK = ConstraintBySimBodyCK; diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp index 8e43d52c30..3549ed1fc6 100644 --- a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp @@ -19,12 +19,19 @@ ConstraintBySimBodyCK:: dv_vel_(this->particles_->template getVariableByName("Velocity")), dv_n_(this->particles_->template getVariableByName("NormalDirection")), dv_n0_(this->particles_->template registerStateVariableOnlyFrom("InitialNormalDirection", "NormalDirection")), - dv_acc_(this->particles_->template getVariableByName("Acceleration")), + dv_acc_(this->particles_->template registerStateVariableOnly("Acceleration")), sv_simbody_state_(this->particles_->template addUniqueSingularVariableOnly("SimbodyState")) { + this->particles_->template addVariableToWrite("Velocity"); const SimTK::State *state = &integ_.getState(); MBsystem_.realize(*state, SimTK::Stage::Acceleration); - initializeSimbodyState(*state); + sim_tk_initial_origin_location_ = mobod_.getBodyOriginLocation(*state); + sv_simbody_state_->setValue(SimbodyState(sim_tk_initial_origin_location_, mobod_, *state)); + Vec3d angular_acceleration = SimTKToEigen(mobod_.getBodyAngularAcceleration(*state)); + std::cout << std::fixed << std::setprecision(9) + << " angular_acceleration[0] = " << angular_acceleration[0] + << " angular_acceleration[1] = " << angular_acceleration[1] + << " angular_acceleration[2] = " << angular_acceleration[2] << "\n"; } //=================================================================================================// template @@ -32,30 +39,10 @@ void ConstraintBySimBodyCK::setupDynamics(Real dt) { const SimTK::State *state = &integ_.getState(); MBsystem_.realize(*state, SimTK::Stage::Acceleration); - updateSimbodyState(*state); + sv_simbody_state_->setValue(SimbodyState(sim_tk_initial_origin_location_, mobod_, *state)); }; //=================================================================================================// template -void ConstraintBySimBodyCK::initializeSimbodyState(const SimTK::State &state) -{ - updateSimbodyState(state); - SimbodyState *simbody_state = sv_simbody_state_->Data(); - simbody_state->initial_origin_location_ = simbody_state->origin_location_; -} -//=================================================================================================// -template -void ConstraintBySimBodyCK::updateSimbodyState(const SimTK::State &state) -{ - SimbodyState *simbody_state = sv_simbody_state_->Data(); - simbody_state->origin_location_ = SimTKToEigen(mobod_.getBodyOriginLocation(state)); - simbody_state->origin_velocity_ = SimTKToEigen(mobod_.getBodyOriginVelocity(state)); - simbody_state->origin_acceleration_ = SimTKToEigen(mobod_.getBodyOriginAcceleration(state)); - simbody_state->angular_velocity_ = SimTKToEigen(mobod_.getBodyAngularVelocity(state)); - simbody_state->angular_acceleration_ = SimTKToEigen(mobod_.getBodyAngularAcceleration(state)); - simbody_state->rotation_ = SimTKToEigen(mobod_.getBodyRotation(state)); -} -//=================================================================================================// -template template ConstraintBySimBodyCK::UpdateKernel:: UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) diff --git a/src/shared/simbody_sphinxsys/all_simbody.h b/src/shared/simbody_sphinxsys/all_simbody.h index b96a74cd02..ccb978d451 100644 --- a/src/shared/simbody_sphinxsys/all_simbody.h +++ b/src/shared/simbody_sphinxsys/all_simbody.h @@ -58,13 +58,21 @@ struct SimbodyState Mat3d rotation_; SimbodyState() - : initial_origin_location_(ZeroData::value), - origin_location_(ZeroData::value), - origin_velocity_(ZeroData::value), - origin_acceleration_(ZeroData::value), - angular_velocity_(ZeroData::value), - angular_acceleration_(ZeroData::value), + : initial_origin_location_(Vec3d::Zero()), + origin_location_(Vec3d::Zero()), + origin_velocity_(Vec3d::Zero()), + origin_acceleration_(Vec3d::Zero()), + angular_velocity_(Vec3d::Zero()), + angular_acceleration_(Vec3d::Zero()), rotation_(Mat3d::Identity()) {} + SimbodyState(const SimTKVec3 &sim_tk_initial_origin_location, SimTK::MobilizedBody &mobod, const SimTK::State &state) + : initial_origin_location_(SimTKToEigen(sim_tk_initial_origin_location)), + origin_location_(SimTKToEigen(mobod.getBodyOriginLocation(state))), + origin_velocity_(SimTKToEigen(mobod.getBodyOriginVelocity(state))), + origin_acceleration_(SimTKToEigen(mobod.getBodyOriginAcceleration(state))), + angular_velocity_(SimTKToEigen(mobod.getBodyAngularVelocity(state))), + angular_acceleration_(SimTKToEigen(mobod.getBodyAngularAcceleration(state))), + rotation_(SimTKToEigen(mobod.getBodyRotation(state))) {}; // implemented according to the Simbody API function with the same name void findStationLocationVelocityAndAccelerationInGround( diff --git a/src/src_sycl/shared/common/sphinxsys_variable_sycl.hpp b/src/src_sycl/shared/common/sphinxsys_variable_sycl.hpp index eca27da17f..7fe4a2389d 100644 --- a/src/src_sycl/shared/common/sphinxsys_variable_sycl.hpp +++ b/src/src_sycl/shared/common/sphinxsys_variable_sycl.hpp @@ -13,7 +13,7 @@ DeviceSharedSingularVariable:: : Entity(host_variable->Name()), device_shared_data_(allocateDeviceShared(1)) { - *device_shared_data_ = *host_variable->Data(); + copyToDevice(host_variable->Data(), device_shared_data_, 1); host_variable->setDelegateData(device_shared_data_); } //=================================================================================================// From 86988cfe61462bba482734d10ab0b9f0bcba9a37 Mon Sep 17 00:00:00 2001 From: xiangyu_hu Date: Sun, 9 Feb 2025 00:27:57 +0100 Subject: [PATCH 16/33] the strange issue seems due to simbody library --- .../particle_dynamics/solid_dynamics/solid_constraint.hpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp index 3549ed1fc6..58cd96423e 100644 --- a/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/solid_constraint.hpp @@ -27,11 +27,6 @@ ConstraintBySimBodyCK:: MBsystem_.realize(*state, SimTK::Stage::Acceleration); sim_tk_initial_origin_location_ = mobod_.getBodyOriginLocation(*state); sv_simbody_state_->setValue(SimbodyState(sim_tk_initial_origin_location_, mobod_, *state)); - Vec3d angular_acceleration = SimTKToEigen(mobod_.getBodyAngularAcceleration(*state)); - std::cout << std::fixed << std::setprecision(9) - << " angular_acceleration[0] = " << angular_acceleration[0] - << " angular_acceleration[1] = " << angular_acceleration[1] - << " angular_acceleration[2] = " << angular_acceleration[2] << "\n"; } //=================================================================================================// template From e748576a80699272492e5e46d69212a5e7d8645c Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Sun, 9 Feb 2025 00:42:29 +0000 Subject: [PATCH 17/33] small change --- src/shared/io_system/io_observation.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/io_system/io_observation.h b/src/shared/io_system/io_observation.h index 70a1d463da..0f2330c8aa 100644 --- a/src/shared/io_system/io_observation.h +++ b/src/shared/io_system/io_observation.h @@ -171,7 +171,7 @@ class SingularVariableRecording : public BaseQuantityRecording virtual void writeToFile(size_t iteration_step = 0) override { std::ofstream out_file(filefullpath_output_.c_str(), std::ios::app); - out_file << sv_physical_time_.getValue() << " "; + out_file << sv_physical_time_->getValue() << " "; plt_engine_.writeAQuantity(out_file, variable_->getValue()); out_file << "\n"; out_file.close(); From 09f32fe7ffa11e99aa99e7745c845bec95bb93d1 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Sun, 9 Feb 2025 11:42:41 +0000 Subject: [PATCH 18/33] update the regression test date for 3d dambreak_sycl --- src/shared/io_system/io_base.h | 20 +-- .../FluidObserver_Pressure_Run_0_result.xml | 14 +- .../FluidObserver_Pressure_Run_10_result.xml | 14 ++ .../FluidObserver_Pressure_Run_18_result.xml | 14 -- .../FluidObserver_Pressure_Run_20_result.xml | 14 ++ .../FluidObserver_Pressure_Run_9_result.xml | 14 -- .../FluidObserver_Pressure_dtwdistance.xml | 2 +- .../FluidObserver_Pressure_runtimes.dat | 2 +- ...ody_TotalMechanicalEnergy_Run_0_result.xml | 2 +- ...dy_TotalMechanicalEnergy_Run_10_result.xml | 9 ++ ...ody_TotalMechanicalEnergy_Run_3_result.xml | 9 -- ...ody_TotalMechanicalEnergy_Run_5_result.xml | 9 ++ ...ody_TotalMechanicalEnergy_Run_6_result.xml | 9 -- ...Body_TotalMechanicalEnergy_dtwdistance.xml | 2 +- ...terBody_TotalMechanicalEnergy_runtimes.dat | 2 +- .../regression_test_base_tool.py | 138 ++++++++++++++++++ .../regression_test_tool.py | 66 ++++++++- .../FluidObserver_Pressure_Run_0_result.xml | 14 +- .../FluidObserver_Pressure_Run_10_result.xml | 14 ++ .../FluidObserver_Pressure_Run_18_result.xml | 14 -- .../FluidObserver_Pressure_Run_20_result.xml | 14 ++ .../FluidObserver_Pressure_Run_9_result.xml | 14 -- .../FluidObserver_Pressure_dtwdistance.xml | 2 +- .../FluidObserver_Pressure_runtimes.dat | 2 +- ...ody_TotalMechanicalEnergy_Run_0_result.xml | 2 +- ...dy_TotalMechanicalEnergy_Run_10_result.xml | 9 ++ ...ody_TotalMechanicalEnergy_Run_3_result.xml | 9 -- ...ody_TotalMechanicalEnergy_Run_5_result.xml | 9 ++ ...ody_TotalMechanicalEnergy_Run_6_result.xml | 9 -- ...Body_TotalMechanicalEnergy_dtwdistance.xml | 2 +- ...terBody_TotalMechanicalEnergy_runtimes.dat | 2 +- .../regression_test_base_tool.py | 138 ++++++++++++++++++ .../regression_test_tool.py | 66 ++++++++- 33 files changed, 523 insertions(+), 137 deletions(-) create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml delete mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml delete mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml delete mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml delete mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml create mode 100644 tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_base_tool.py create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml delete mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml delete mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml delete mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml delete mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml create mode 100644 tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_base_tool.py diff --git a/src/shared/io_system/io_base.h b/src/shared/io_system/io_base.h index 8cb788ff3c..9dcf016fa8 100644 --- a/src/shared/io_system/io_base.h +++ b/src/shared/io_system/io_base.h @@ -103,22 +103,24 @@ class BodyStatesRecording : public BaseIO virtual ~BodyStatesRecording() {}; /** write with filename indicated by physical time */ void writeToFile(); - + void writeToFile(const ParallelDevicePolicy &ex_policy) { - for (size_t i = 0; i < bodies_.size(); ++i) + if (state_recording_) { - if (bodies_[i]->checkNewlyUpdated()) + for (size_t i = 0; i < bodies_.size(); ++i) { - dv_all_pos_[i]->prepareForOutput(ex_policy); - BaseParticles &base_particles = bodies_[i]->getBaseParticles(); - prepare_variable_to_write_(base_particles.VariablesToWrite(), ex_policy); + if (bodies_[i]->checkNewlyUpdated()) + { + dv_all_pos_[i]->prepareForOutput(ex_policy); + BaseParticles &base_particles = bodies_[i]->getBaseParticles(); + prepare_variable_to_write_(base_particles.VariablesToWrite(), ex_policy); + } } + writeToFile(); } - - writeToFile(); }; - + void writeToFile(const ParallelPolicy &ex_policy) { writeToFile(); }; void writeToFile(const SequencedPolicy &ex_policy) { writeToFile(); }; virtual void writeToFile(size_t iteration_step) override; diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml index c99bab799b..e05cae4176 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml @@ -1,14 +1,14 @@ - + - - - - - - + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml new file mode 100644 index 0000000000..b5f6d09f9f --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml deleted file mode 100644 index 2837d6f823..0000000000 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml new file mode 100644 index 0000000000..203455cea0 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml deleted file mode 100644 index a52e5d1ce1..0000000000 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml index c2bf017a34..8565f6e849 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml @@ -1,4 +1,4 @@ - + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_runtimes.dat index 57574ea953..fd8ad08880 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_runtimes.dat +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/FluidObserver_Pressure_runtimes.dat @@ -1,3 +1,3 @@ true -19 +21 4 \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml index b126d034a0..4cb24a50c1 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml @@ -4,6 +4,6 @@ - + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml new file mode 100644 index 0000000000..f8474bca87 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml deleted file mode 100644 index 4a3668c2f3..0000000000 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml new file mode 100644 index 0000000000..3b970a220f --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml deleted file mode 100644 index 135dcf035b..0000000000 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml index adaed6dbb5..b327acdcbd 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml @@ -1,4 +1,4 @@ - + diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat index 34de7daedb..b33a499cce 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat @@ -1,3 +1,3 @@ true -7 +11 4 \ No newline at end of file diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_base_tool.py b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_base_tool.py new file mode 100644 index 0000000000..98313572b5 --- /dev/null +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_base_tool.py @@ -0,0 +1,138 @@ +# !/usr/bin/env python3 +import os + +# This is the regression test base module used for all test cases. +# There are two different schemes that differ from the executable path. +# The first one is calling Python script by CTest, such as test_0d_regression_test. +# The other one is calling Python script directly manually. +# They have different relative paths, and correspond to different modules. + + +class SphinxsysRegressionTestByCTest: + + def __init__(self, casename, bodyname, parametername): + self.sphinxsys_exec_path = os.path.abspath(os.path.join(os.getcwd())) + self.sphinxsys_case_path = os.path.abspath(os.path.join(self.sphinxsys_exec_path)) + self.sphinxsys_case_name = casename + self.sphinxsys_body_name = bodyname + self.sphinxsys_parameter_name = parametername + self.enter_sphinxsys_exec_folder = f"cd {self.sphinxsys_exec_path};" + self.enter_sphinxsys_case_folder = f"cd {self.sphinxsys_case_path};" + self.input_file_path = os.path.join(self.sphinxsys_exec_path, "input") + self.condition_file_path = os.path.join(self.input_file_path, f"{bodyname}_{parametername}_runtimes.dat") + + def compile_case(self) -> None: + print('Start compiling test case....') + command = "make -j8" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Compiling test case is finished...') + + def run_particle_relaxation(self) -> None: + print('Start particle relaxation for the simulation...') + command = f".{os.sep}{self.sphinxsys_case_name} --relax=true" + os.system(self.enter_sphinxsys_exec_folder) + os.system(command) + print('Simulating case is finished...') + + def run_case(self) -> None: + print('Start case simulation...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --state_recording=false --regression=true" + os.system(self.enter_sphinxsys_exec_folder) + os.system(command) + print('Simulating case is finished...') + + def run_case_with_reload(self) -> None: + print('Start case simulation with particle reload...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --reload=true --state_recording=false --regression=true" + os.system(self.enter_sphinxsys_exec_folder) + os.system(command) + print('Simulating case is finished...') + + def read_dat_file(self): + file = open(self.condition_file_path) + ifconverged = file.readline(4) + file.close() + return ifconverged + + def clean_input_folder(folder_path, keep_file="regression_test_tool.py"): + for filename in os.listdir(folder_path): + file_path = os.path.join(folder_path, filename) + if filename != keep_file and os.path.isfile(file_path): + os.remove(file_path) + print(f"Deleted: {file_path}") + + +class SphinxsysRegressionTest: + + def __init__(self, casename, bodyname, parametername): + self.sphinxsys_exec_path = os.path.abspath(os.path.join(os.getcwd(), "..")) + self.sphinxsys_case_path = os.path.abspath(os.path.join(self.sphinxsys_exec_path, "..")) + self.sphinxsys_src_path = os.path.join(self.sphinxsys_case_path, "src") + self.sphinxsys_rld_path = os.path.join(self.sphinxsys_src_path, "reload") + self.sphinxsys_case_name = casename + self.sphinxsys_body_name = bodyname + self.sphinxsys_parameter_name = parametername + self.enter_sphinxsys_exec_folder = f"cd {self.sphinxsys_exec_path};" + self.enter_sphinxsys_case_folder = f"cd {self.sphinxsys_case_path};" + self.input_file_path = os.path.join(self.sphinxsys_exec_path, "input") + self.condition_file_path = os.path.join(self.input_file_path, f"{bodyname}_{parametername}_runtimes.dat") + + def compile_case(self) -> None: + print('Start compiling test case....') + command = "make -j8" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Compiling test case is finished...') + + def test_case(self) -> None: + print('Start test case...') + command = "make test" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Testing case is finished...') + + def copy_reload(self) -> None: + print('Start copy the reload file...') + command = "cp -r reload bin" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Copying the reload file is finished...') + + def run_particle_relaxation(self) -> None: + print('Start particle relaxation for the simulation...') + command = f".{os.sep}{self.sphinxsys_case_name} --relax=true" + os.chdir(self.sphinxsys_exec_path) + os.system(command) + print('Simulating case is finished...') + + def run_case(self) -> None: + print('Start case simulation...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --state_recording=false --regression=true" + os.chdir(self.sphinxsys_exec_path) + os.system(command) + print('Simulating case is finished...') + + def run_case_with_reload(self) -> None: + print('Start case simulation with particle reload...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --reload=true --state_recording=false --regression=true" + os.chdir(self.sphinxsys_exec_path) + os.system(command) + print('Simulating case is finished...') + + def clean_input_folder(folder_path, keep_file="regression_test_tool.py"): + for filename in os.listdir(folder_path): + file_path = os.path.join(folder_path, filename) + if filename != keep_file and os.path.isfile(file_path): + os.remove(file_path) + print(f"Deleted: {file_path}") + + def read_dat_file(self): + file = open(self.condition_file_path) + ifconverged = file.readline(4) + file.close() + return ifconverged diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_tool.py b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_tool.py index 8edaf9970c..89c17d9989 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_tool.py +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/regression_test_tool/regression_test_tool.py @@ -2,16 +2,71 @@ import os import sys -path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') -sys.path.append(path) -from regression_test_base_tool import SphinxsysRegressionTest +def find_upper_folder(folder_name, start_path=None): + """ + Search for an upper-level folder by name, starting from a given directory and traversing upwards. + """ + if start_path is None: + start_path = os.getcwd() + current_path = start_path + while True: + potential_path = os.path.join(current_path, folder_name) + if os.path.isdir(potential_path): + return potential_path + parent_path = os.path.dirname(current_path) + if parent_path == current_path: # Reached the root directory + break + current_path = parent_path + + return None + +def find_nested_folder(folder_chain, start_path=None): + """ + Find a nested folder by traversing upward and then descending into a specified folder chain. + """ + if not folder_chain: + return None + + # Step 1: Find the first folder in the chain + first_folder = folder_chain[0] + first_folder_path = find_upper_folder(first_folder, start_path) + if not first_folder_path: + return None + + # Step 2: Traverse the rest of the folder chain + current_path = first_folder_path + for folder in folder_chain[1:]: + current_path = os.path.join(current_path, folder) + if not os.path.isdir(current_path): + return None + + return current_path + +# Step 1: Find the RegressionTest folder +folder_chain = ["build", "PythonScriptStore", "RegressionTest"] +regression_test_folder = find_nested_folder(folder_chain) + +if not regression_test_folder: + print("'RegressionTest' folder not found.") + exit(1) + +# Step 2: Add the RegressionTest folder to sys.path +if regression_test_folder not in sys.path: + sys.path.insert(0, regression_test_folder) + +# Step 3: Import the module +try: + from regression_test_base_tool import SphinxsysRegressionTest + print("Module imported successfully!") +except ImportError as e: + print(f"Failed to import module: {e}") """ -case name: test_3d_dambreak +case name: test_3d_dambreak_sycl """ -case_name = "test_3d_dambreak" +case_name = "test_3d_dambreak_sycl" body_name = "WaterBody" parameter_name = "TotalMechanicalEnergy" body_name_1 = "FluidObserver" @@ -21,7 +76,6 @@ converged = 0 sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) -clean_input_folder(sphinxsys.input_file_path) while True: diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml index c99bab799b..e05cae4176 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_0_result.xml @@ -1,14 +1,14 @@ - + - - - - - - + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml new file mode 100644 index 0000000000..b5f6d09f9f --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_10_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml deleted file mode 100644 index 2837d6f823..0000000000 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_18_result.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml new file mode 100644 index 0000000000..203455cea0 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_20_result.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml deleted file mode 100644 index a52e5d1ce1..0000000000 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_Run_9_result.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml index c2bf017a34..8565f6e849 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_dtwdistance.xml @@ -1,4 +1,4 @@ - + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat index 57574ea953..fd8ad08880 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/FluidObserver_Pressure_runtimes.dat @@ -1,3 +1,3 @@ true -19 +21 4 \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml index b126d034a0..4cb24a50c1 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_0_result.xml @@ -4,6 +4,6 @@ - + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml new file mode 100644 index 0000000000..f8474bca87 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_10_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml deleted file mode 100644 index 4a3668c2f3..0000000000 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_3_result.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml new file mode 100644 index 0000000000..3b970a220f --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_5_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml deleted file mode 100644 index 135dcf035b..0000000000 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_Run_6_result.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml index adaed6dbb5..b327acdcbd 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_dtwdistance.xml @@ -1,4 +1,4 @@ - + diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat index 34de7daedb..b33a499cce 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/WaterBody_TotalMechanicalEnergy_runtimes.dat @@ -1,3 +1,3 @@ true -7 +11 4 \ No newline at end of file diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_base_tool.py b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_base_tool.py new file mode 100644 index 0000000000..98313572b5 --- /dev/null +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_base_tool.py @@ -0,0 +1,138 @@ +# !/usr/bin/env python3 +import os + +# This is the regression test base module used for all test cases. +# There are two different schemes that differ from the executable path. +# The first one is calling Python script by CTest, such as test_0d_regression_test. +# The other one is calling Python script directly manually. +# They have different relative paths, and correspond to different modules. + + +class SphinxsysRegressionTestByCTest: + + def __init__(self, casename, bodyname, parametername): + self.sphinxsys_exec_path = os.path.abspath(os.path.join(os.getcwd())) + self.sphinxsys_case_path = os.path.abspath(os.path.join(self.sphinxsys_exec_path)) + self.sphinxsys_case_name = casename + self.sphinxsys_body_name = bodyname + self.sphinxsys_parameter_name = parametername + self.enter_sphinxsys_exec_folder = f"cd {self.sphinxsys_exec_path};" + self.enter_sphinxsys_case_folder = f"cd {self.sphinxsys_case_path};" + self.input_file_path = os.path.join(self.sphinxsys_exec_path, "input") + self.condition_file_path = os.path.join(self.input_file_path, f"{bodyname}_{parametername}_runtimes.dat") + + def compile_case(self) -> None: + print('Start compiling test case....') + command = "make -j8" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Compiling test case is finished...') + + def run_particle_relaxation(self) -> None: + print('Start particle relaxation for the simulation...') + command = f".{os.sep}{self.sphinxsys_case_name} --relax=true" + os.system(self.enter_sphinxsys_exec_folder) + os.system(command) + print('Simulating case is finished...') + + def run_case(self) -> None: + print('Start case simulation...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --state_recording=false --regression=true" + os.system(self.enter_sphinxsys_exec_folder) + os.system(command) + print('Simulating case is finished...') + + def run_case_with_reload(self) -> None: + print('Start case simulation with particle reload...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --reload=true --state_recording=false --regression=true" + os.system(self.enter_sphinxsys_exec_folder) + os.system(command) + print('Simulating case is finished...') + + def read_dat_file(self): + file = open(self.condition_file_path) + ifconverged = file.readline(4) + file.close() + return ifconverged + + def clean_input_folder(folder_path, keep_file="regression_test_tool.py"): + for filename in os.listdir(folder_path): + file_path = os.path.join(folder_path, filename) + if filename != keep_file and os.path.isfile(file_path): + os.remove(file_path) + print(f"Deleted: {file_path}") + + +class SphinxsysRegressionTest: + + def __init__(self, casename, bodyname, parametername): + self.sphinxsys_exec_path = os.path.abspath(os.path.join(os.getcwd(), "..")) + self.sphinxsys_case_path = os.path.abspath(os.path.join(self.sphinxsys_exec_path, "..")) + self.sphinxsys_src_path = os.path.join(self.sphinxsys_case_path, "src") + self.sphinxsys_rld_path = os.path.join(self.sphinxsys_src_path, "reload") + self.sphinxsys_case_name = casename + self.sphinxsys_body_name = bodyname + self.sphinxsys_parameter_name = parametername + self.enter_sphinxsys_exec_folder = f"cd {self.sphinxsys_exec_path};" + self.enter_sphinxsys_case_folder = f"cd {self.sphinxsys_case_path};" + self.input_file_path = os.path.join(self.sphinxsys_exec_path, "input") + self.condition_file_path = os.path.join(self.input_file_path, f"{bodyname}_{parametername}_runtimes.dat") + + def compile_case(self) -> None: + print('Start compiling test case....') + command = "make -j8" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Compiling test case is finished...') + + def test_case(self) -> None: + print('Start test case...') + command = "make test" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Testing case is finished...') + + def copy_reload(self) -> None: + print('Start copy the reload file...') + command = "cp -r reload bin" + os.system(self.enter_sphinxsys_case_folder) + os.system(command) + print('Copying the reload file is finished...') + + def run_particle_relaxation(self) -> None: + print('Start particle relaxation for the simulation...') + command = f".{os.sep}{self.sphinxsys_case_name} --relax=true" + os.chdir(self.sphinxsys_exec_path) + os.system(command) + print('Simulating case is finished...') + + def run_case(self) -> None: + print('Start case simulation...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --state_recording=false --regression=true" + os.chdir(self.sphinxsys_exec_path) + os.system(command) + print('Simulating case is finished...') + + def run_case_with_reload(self) -> None: + print('Start case simulation with particle reload...') + print(self.enter_sphinxsys_exec_folder) + command = f".{os.sep}{self.sphinxsys_case_name} --reload=true --state_recording=false --regression=true" + os.chdir(self.sphinxsys_exec_path) + os.system(command) + print('Simulating case is finished...') + + def clean_input_folder(folder_path, keep_file="regression_test_tool.py"): + for filename in os.listdir(folder_path): + file_path = os.path.join(folder_path, filename) + if filename != keep_file and os.path.isfile(file_path): + os.remove(file_path) + print(f"Deleted: {file_path}") + + def read_dat_file(self): + file = open(self.condition_file_path) + ifconverged = file.readline(4) + file.close() + return ifconverged diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py index 8edaf9970c..89c17d9989 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/regression_test_tool/regression_test_tool.py @@ -2,16 +2,71 @@ import os import sys -path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') -sys.path.append(path) -from regression_test_base_tool import SphinxsysRegressionTest +def find_upper_folder(folder_name, start_path=None): + """ + Search for an upper-level folder by name, starting from a given directory and traversing upwards. + """ + if start_path is None: + start_path = os.getcwd() + current_path = start_path + while True: + potential_path = os.path.join(current_path, folder_name) + if os.path.isdir(potential_path): + return potential_path + parent_path = os.path.dirname(current_path) + if parent_path == current_path: # Reached the root directory + break + current_path = parent_path + + return None + +def find_nested_folder(folder_chain, start_path=None): + """ + Find a nested folder by traversing upward and then descending into a specified folder chain. + """ + if not folder_chain: + return None + + # Step 1: Find the first folder in the chain + first_folder = folder_chain[0] + first_folder_path = find_upper_folder(first_folder, start_path) + if not first_folder_path: + return None + + # Step 2: Traverse the rest of the folder chain + current_path = first_folder_path + for folder in folder_chain[1:]: + current_path = os.path.join(current_path, folder) + if not os.path.isdir(current_path): + return None + + return current_path + +# Step 1: Find the RegressionTest folder +folder_chain = ["build", "PythonScriptStore", "RegressionTest"] +regression_test_folder = find_nested_folder(folder_chain) + +if not regression_test_folder: + print("'RegressionTest' folder not found.") + exit(1) + +# Step 2: Add the RegressionTest folder to sys.path +if regression_test_folder not in sys.path: + sys.path.insert(0, regression_test_folder) + +# Step 3: Import the module +try: + from regression_test_base_tool import SphinxsysRegressionTest + print("Module imported successfully!") +except ImportError as e: + print(f"Failed to import module: {e}") """ -case name: test_3d_dambreak +case name: test_3d_dambreak_sycl """ -case_name = "test_3d_dambreak" +case_name = "test_3d_dambreak_sycl" body_name = "WaterBody" parameter_name = "TotalMechanicalEnergy" body_name_1 = "FluidObserver" @@ -21,7 +76,6 @@ converged = 0 sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) -clean_input_folder(sphinxsys.input_file_path) while True: From 0e204ab6dbb1385b9f31a85fd21c47b360d6e2b9 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Sun, 9 Feb 2025 17:46:46 +0000 Subject: [PATCH 19/33] revise triangle mesh shape --- .../geometries/triangle_mesh_shape.cpp | 145 ++++++------------ .../geometries/triangle_mesh_shape.h | 44 ++---- .../bodies/complex_bodies/unstructured_mesh.h | 2 +- 3 files changed, 68 insertions(+), 123 deletions(-) diff --git a/src/for_3D_build/geometries/triangle_mesh_shape.cpp b/src/for_3D_build/geometries/triangle_mesh_shape.cpp index 51c9329b19..8e6eca0998 100644 --- a/src/for_3D_build/geometries/triangle_mesh_shape.cpp +++ b/src/for_3D_build/geometries/triangle_mesh_shape.cpp @@ -3,22 +3,43 @@ namespace SPH { //=================================================================================================// -SimTK::ContactGeometry::TriangleMesh *TriangleMeshShape::generateTriangleMesh(const SimTK::PolygonalMesh &poly_mesh) +TriangleMeshShape::TriangleMeshShape(const std::string &shape_name) + : Shape(shape_name), triangle_mesh_(nullptr) {} +//=================================================================================================// +void TriangleMeshShape::initializeFromPolygonalMesh(const SimTK::PolygonalMesh &poly_mesh) { - SimTK::ContactGeometry::TriangleMesh *triangle_mesh; - triangle_mesh = triangle_mesh_ptr_keeper_.createPtr(poly_mesh); - if (!SimTK::ContactGeometry::TriangleMesh::isInstance(*triangle_mesh)) + triangle_mesh_ = triangle_mesh_ptr_keeper_.createPtr(poly_mesh); + if (!TriangleMesh::isInstance(*triangle_mesh_)) { std::cout << "\n Error the triangle mesh is not valid" << std::endl; std::cout << __FILE__ << ':' << __LINE__ << std::endl; throw; } - std::cout << "num of faces:" << triangle_mesh->getNumFaces() << std::endl; + std::cout << "TriangleMesh:" << name_ << std::endl; + std::cout << "num of vertices:" << triangle_mesh_->getNumVertices() << std::endl; + std::cout << "num of faces:" << triangle_mesh_->getNumFaces() << std::endl; + + std::vector> vertices; + vertices.reserve(triangle_mesh_->getNumVertices()); + for (int i = 0; i < triangle_mesh_->getNumVertices(); i++) + { + const auto &p = triangle_mesh_->getVertexPosition(i); + vertices.push_back({Real(p[0]), Real(p[1]), Real(p[2])}); + } - return triangle_mesh; + std::vector> faces; + faces.reserve(triangle_mesh_->getNumFaces()); + for (int i = 0; i < triangle_mesh_->getNumFaces(); i++) + { + auto f1 = triangle_mesh_->getFaceVertex(i, 0); + auto f2 = triangle_mesh_->getFaceVertex(i, 1); + auto f3 = triangle_mesh_->getFaceVertex(i, 2); + faces.push_back({f1, f2, f3}); + } + triangle_mesh_distance_.construct(vertices, faces); } //=================================================================================================// -SimTK::ContactGeometry::TriangleMesh *TriangleMeshShape::getTriangleMesh() +TriangleMesh *TriangleMeshShape::getTriangleMesh() { if (triangle_mesh_ == nullptr) { @@ -31,51 +52,14 @@ SimTK::ContactGeometry::TriangleMesh *TriangleMeshShape::getTriangleMesh() //=================================================================================================// bool TriangleMeshShape::checkContain(const Vec3d &probe_point, bool BOUNDARY_INCLUDED) { - SimTKVec2 uv_coordinate; - bool inside = false; // note that direct prediction is not reliable sometime. - int face_id; - - SimTKVec3 closest_pnt = triangle_mesh_->findNearestPoint(EigenToSimTK(probe_point), inside, face_id, uv_coordinate); - Vec3d from_face_to_pnt = probe_point - SimTKToEigen(closest_pnt); - Real distance_to_pnt = from_face_to_pnt.norm(); - Vec3d direction_to_pnt = from_face_to_pnt / (distance_to_pnt + TinyReal); - Vec3d face_normal = SimTKToEigen(triangle_mesh_->getFaceNormal(face_id)); - Real cosine_angle = face_normal.dot(direction_to_pnt); - - int ite = 0; - while (fabs(cosine_angle) < Eps) - { - Vec3d jittered = probe_point; // jittering - for (int l = 0; l != probe_point.size(); ++l) - jittered[l] = probe_point[l] + rand_uniform(-0.5, 0.5) * (SqrtEps + distance_to_pnt * 0.1); - Vec3d from_face_to_jittered = jittered - SimTKToEigen(closest_pnt); - Vec3d direction_to_jittered = from_face_to_jittered / (from_face_to_jittered.norm() + TinyReal); - cosine_angle = face_normal.dot(direction_to_jittered); - - ite++; - if (ite > 100) - { - std::cout << "\n Error: TriangleMeshShape::checkContain not able to achieve! " << std::endl; - std::cout << __FILE__ << ':' << __LINE__ << std::endl; - exit(1); - } - } + Real distance = triangle_mesh_distance_.signed_distance(probe_point).distance; - return cosine_angle < 0.0 ? true : false; + return distance < 0.0 ? true : false; } //=================================================================================================// Vecd TriangleMeshShape::findClosestPoint(const Vecd &probe_point) { - bool inside = false; - int face_id; - SimTKVec2 norm; - SimTKVec3 closest_pnt = triangle_mesh_->findNearestPoint(SimTKVec3(probe_point[0], probe_point[1], probe_point[2]), inside, face_id, norm); - if (face_id < 0 && face_id > triangle_mesh_->getNumFaces()) - { - std::cout << "\n Error the nearest point is not valid" << std::endl; - std::cout << __FILE__ << ':' << __LINE__ << std::endl; - throw; - } + auto closest_pnt = triangle_mesh_distance_.signed_distance(probe_point).nearest_point; return Vecd(closest_pnt[0], closest_pnt[1], closest_pnt[2]); } //=================================================================================================// @@ -101,12 +85,14 @@ TriangleMeshShapeBrick::TriangleMeshShapeBrick(Vecd halfsize, int resolution, Ve const std::string &shape_name) : TriangleMeshShape(shape_name) { - SimTK::PolygonalMesh polymesh = SimTK::PolygonalMesh::createBrickMesh(SimTKVec3(halfsize[0], halfsize[1], halfsize[2]), resolution); - triangle_mesh_ = generateTriangleMesh(polymesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2]))); + SimTK::PolygonalMesh poly_mesh = SimTK::PolygonalMesh::createBrickMesh( + SimTKVec3(halfsize[0], halfsize[1], halfsize[2]), resolution); + initializeFromPolygonalMesh( + poly_mesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2]))); } //=================================================================================================// -TriangleMeshShapeBrick::TriangleMeshShapeBrick(const TriangleMeshShapeBrick::ShapeParameters &shape_parameters, - const std::string &shape_name) +TriangleMeshShapeBrick::TriangleMeshShapeBrick( + const TriangleMeshShapeBrick::ShapeParameters &shape_parameters, const std::string &shape_name) : TriangleMeshShapeBrick(shape_parameters.halfsize_, shape_parameters.resolution_, shape_parameters.translation_, shape_name) {} //=================================================================================================// @@ -114,17 +100,20 @@ TriangleMeshShapeSphere::TriangleMeshShapeSphere(Real radius, int resolution, Ve const std::string &shape_name) : TriangleMeshShape(shape_name) { - SimTK::PolygonalMesh polymesh = SimTK::PolygonalMesh::createSphereMesh(radius, resolution); - triangle_mesh_ = generateTriangleMesh(polymesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2]))); + SimTK::PolygonalMesh poly_mesh = SimTK::PolygonalMesh::createSphereMesh(radius, resolution); + initializeFromPolygonalMesh( + poly_mesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2]))); } //=================================================================================================// -TriangleMeshShapeCylinder::TriangleMeshShapeCylinder(SimTK::UnitVec3 axis, Real radius, Real halflength, int resolution, - Vecd translation, const std::string &shape_name) +TriangleMeshShapeCylinder::TriangleMeshShapeCylinder( + SimTK::UnitVec3 axis, Real radius, Real halflength, int resolution, + Vecd translation, const std::string &shape_name) : TriangleMeshShape(shape_name) { - SimTK::PolygonalMesh polymesh = + SimTK::PolygonalMesh poly_mesh = SimTK::PolygonalMesh::createCylinderMesh(axis, radius, halflength, resolution); - triangle_mesh_ = generateTriangleMesh(polymesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2]))); + initializeFromPolygonalMesh( + poly_mesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2]))); } //=================================================================================================// TriangleMeshShapeSTL::TriangleMeshShapeSTL(const std::string &filepathname, Vec3d translation, @@ -137,43 +126,11 @@ TriangleMeshShapeSTL::TriangleMeshShapeSTL(const std::string &filepathname, Vec3 std::cout << __FILE__ << ':' << __LINE__ << std::endl; throw; } - SimTK::PolygonalMesh polymesh; - polymesh.loadStlFile(filepathname); - polymesh.scaleMesh(scale_factor); - polymesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2])); - triangle_mesh_ = generateTriangleMesh(polymesh); - - std::vector> vertices; - vertices.reserve(polymesh.getNumVertices()); - for (int i = 0; i < polymesh.getNumVertices(); i++) - { - const auto &p = polymesh.getVertexPosition(i); - vertices.push_back({Real(p[0]), Real(p[1]), Real(p[2])}); - } - - std::vector> faces; - faces.reserve(polymesh.getNumFaces()); - for (int i = 0; i < polymesh.getNumFaces(); i++) - { - auto f1 = polymesh.getFaceVertex(i, 0); - auto f2 = polymesh.getFaceVertex(i, 1); - auto f3 = polymesh.getFaceVertex(i, 2); - faces.push_back({f1, f2, f3}); - } - triangle_mesh_distance_.construct(vertices, faces); -} -//=================================================================================================// -bool TriangleMeshShapeSTL::checkContain(const Vec3d &probe_point, bool BOUNDARY_INCLUDED) -{ - Real distance = triangle_mesh_distance_.signed_distance(probe_point).distance; - - return distance < 0.0 ? true : false; -} -//=================================================================================================// -Vecd TriangleMeshShapeSTL::findClosestPoint(const Vecd &probe_point) -{ - auto closest_pnt = triangle_mesh_distance_.signed_distance(probe_point).nearest_point; - return Vecd(closest_pnt[0], closest_pnt[1], closest_pnt[2]); + SimTK::PolygonalMesh poly_mesh; + poly_mesh.loadStlFile(filepathname); + poly_mesh.scaleMesh(scale_factor); + poly_mesh.transformMesh(SimTKVec3(translation[0], translation[1], translation[2])); + initializeFromPolygonalMesh(poly_mesh); } //=================================================================================================// } // namespace SPH diff --git a/src/for_3D_build/geometries/triangle_mesh_shape.h b/src/for_3D_build/geometries/triangle_mesh_shape.h index e7f265ed97..8333f22779 100644 --- a/src/for_3D_build/geometries/triangle_mesh_shape.h +++ b/src/for_3D_build/geometries/triangle_mesh_shape.h @@ -22,8 +22,8 @@ * ------------------------------------------------------------------------- */ /** * @file triangle_mesh_shape.h - * @brief Here, we define the 3D geometries based on the polymesh. - * @details The idea is to define complex geometry by passing stl, obj or other polymesh files. + * @brief Here, we define the 3D geometries based on the poly mesh. + * @details The idea is to define complex geometry by passing stl, obj or other poly mesh files. * @author Chi Zhang and Xiangyu Hu */ @@ -42,6 +42,7 @@ namespace fs = std::filesystem; namespace SPH { +using TriangleMesh = SimTK::ContactGeometry::TriangleMesh; /** * @class TriangleMeshShape * @brief Derived class for triangle shape processing. @@ -49,28 +50,22 @@ namespace SPH class TriangleMeshShape : public Shape { private: - UniquePtrKeeper triangle_mesh_ptr_keeper_; + UniquePtrKeeper triangle_mesh_ptr_keeper_; public: - explicit TriangleMeshShape(const std::string &shape_name, const SimTK::PolygonalMesh *mesh = nullptr) - : Shape(shape_name), triangle_mesh_(nullptr) - { - if (mesh) - triangle_mesh_ = generateTriangleMesh(*mesh); - }; + explicit TriangleMeshShape(const std::string &shape_name); /** Only reliable when the probe point is close to the shape surface. * Need to be combined with level set shape and sign correction to avoid artifacts * when probe distance is far from the surface. */ virtual bool checkContain(const Vec3d &probe_point, bool BOUNDARY_INCLUDED = true) override; virtual Vec3d findClosestPoint(const Vec3d &probe_point) override; - - SimTK::ContactGeometry::TriangleMesh *getTriangleMesh(); + TriangleMesh *getTriangleMesh(); protected: - SimTK::ContactGeometry::TriangleMesh *triangle_mesh_; - + TriangleMesh *triangle_mesh_; + tmd::TriangleMeshDistance triangle_mesh_distance_; /** generate triangle mesh from polygon mesh */ - SimTK::ContactGeometry::TriangleMesh *generateTriangleMesh(const SimTK::PolygonalMesh &poly_mesh); + void initializeFromPolygonalMesh(const SimTK::PolygonalMesh &poly_mesh); virtual BoundingBox findBounds() override; }; @@ -84,7 +79,7 @@ class TriangleMeshShapeBrick : public TriangleMeshShape class ShapeParameters { public: - ShapeParameters() : halfsize_(Vec3d::Zero()), translation_(Vec3d::Zero()), resolution_(0){}; + ShapeParameters() : halfsize_(Vec3d::Zero()), translation_(Vec3d::Zero()), resolution_(0) {}; Vec3d halfsize_; Vec3d translation_; int resolution_; @@ -93,7 +88,7 @@ class TriangleMeshShapeBrick : public TriangleMeshShape const std::string &shape_name = "TriangleMeshShapeBrick"); explicit TriangleMeshShapeBrick(const TriangleMeshShapeBrick::ShapeParameters &shape_parameters, const std::string &shape_name = "TriangleMeshShapeBrick"); - virtual ~TriangleMeshShapeBrick(){}; + virtual ~TriangleMeshShapeBrick() {}; }; /** @@ -105,7 +100,7 @@ class TriangleMeshShapeSphere : public TriangleMeshShape public: explicit TriangleMeshShapeSphere(Real radius, int resolution, Vec3d translation, const std::string &shape_name = "TriangleMeshShapeSphere"); - virtual ~TriangleMeshShapeSphere(){}; + virtual ~TriangleMeshShapeSphere() {}; }; /** @@ -115,9 +110,10 @@ class TriangleMeshShapeSphere : public TriangleMeshShape class TriangleMeshShapeCylinder : public TriangleMeshShape { public: - explicit TriangleMeshShapeCylinder(SimTK::UnitVec3 axis, Real radius, Real halflength, int resolution, Vec3d translation, + explicit TriangleMeshShapeCylinder(SimTK::UnitVec3 axis, Real radius, + Real halflength, int resolution, Vec3d translation, const std::string &shape_name = "TriangleMeshShapeCylinder"); - virtual ~TriangleMeshShapeCylinder(){}; + virtual ~TriangleMeshShapeCylinder() {}; }; /** @@ -129,15 +125,7 @@ class TriangleMeshShapeSTL : public TriangleMeshShape public: explicit TriangleMeshShapeSTL(const std::string &file_path_name, Vec3d translation, Real scale_factor, const std::string &shape_name = "TriangleMeshShapeSTL"); - virtual ~TriangleMeshShapeSTL(){}; - - /** Here, we use the open source method TriangleMeshDistance library. - * https://github.com/InteractiveComputerGraphics/TriangleMeshDistance/tree/main */ - virtual bool checkContain(const Vec3d &probe_point, bool BOUNDARY_INCLUDED = true) override; - virtual Vec3d findClosestPoint(const Vec3d &probe_point) override; - - protected: - tmd::TriangleMeshDistance triangle_mesh_distance_; + virtual ~TriangleMeshShapeSTL() {}; }; } // namespace SPH diff --git a/src/shared/bodies/complex_bodies/unstructured_mesh.h b/src/shared/bodies/complex_bodies/unstructured_mesh.h index 5ba92073ef..81da1cb141 100644 --- a/src/shared/bodies/complex_bodies/unstructured_mesh.h +++ b/src/shared/bodies/complex_bodies/unstructured_mesh.h @@ -145,4 +145,4 @@ class InnerRelationInFVM : public BaseInnerRelationInFVM }; } // namespace SPH -#endif // UNSTRUCTURED_MESH_H \ No newline at end of file +#endif // UNSTRUCTURED_MESH_H From 8e722f3a1c927e7dc5f0cd5de7da2eec3d82b8ba Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Sun, 9 Feb 2025 20:30:44 +0000 Subject: [PATCH 20/33] to test locally --- src/for_3D_build/io_system/io_vtk_mesh_3d.cpp | 107 ++++++++++++++++++ src/for_3D_build/io_system/io_vtk_mesh_3d.hpp | 97 ++++++++++++++++ .../base_particle_generator_3d.cpp | 19 ++++ src/shared/io_system/io_vtk_mesh.cpp | 83 -------------- src/shared/io_system/io_vtk_mesh.h | 15 ++- .../base_particle_generator.cpp | 4 + .../base_particle_generator.h | 5 +- .../particle_generator_mesh.h | 5 +- .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 17 ++- 9 files changed, 253 insertions(+), 99 deletions(-) create mode 100644 src/for_3D_build/io_system/io_vtk_mesh_3d.cpp create mode 100644 src/for_3D_build/io_system/io_vtk_mesh_3d.hpp create mode 100644 src/for_3D_build/particle_generator/base_particle_generator_3d.cpp diff --git a/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp new file mode 100644 index 0000000000..0d5beccf66 --- /dev/null +++ b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp @@ -0,0 +1,107 @@ +#include "io_vtk_mesh_3d.hpp" +#include "io_vtk.hpp" + +#include "triangle_mesh_shape.h" + +namespace SPH +{ +//=================================================================================================// +BodyStatesRecordingToTriangleMeshVtp::BodyStatesRecordingToTriangleMeshVtp( + SPHBody &body, TriangleMeshShape &triangle_mesh_shape) + : BodyStatesRecordingToVtp(body) +{ + TriangleMesh &triangle_mesh = *triangle_mesh_shape.getTriangleMesh(); + for (int i = 0; i != triangle_mesh.getNumFaces(); ++i) + { + faces_.reserve(triangle_mesh.getNumFaces()); + for (int i = 0; i < triangle_mesh.getNumFaces(); i++) + { + auto f1 = triangle_mesh.getFaceVertex(i, 0); + auto f2 = triangle_mesh.getFaceVertex(i, 1); + auto f3 = triangle_mesh.getFaceVertex(i, 2); + faces_.push_back({f1, f2, f3}); + } + } +} +//=================================================================================================// +void BodyStatesRecordingToTriangleMeshVtp::writeWithFileName(const std::string &sequence) +{ + for (SPHBody *body : bodies_) + { + if (body->checkNewlyUpdated() && state_recording_) + { + std::string filefullpath = io_environment_.output_folder_ + "/" + body->getName() + "_" + sequence + ".vtp"; + if (fs::exists(filefullpath)) + { + fs::remove(filefullpath); + } + std::ofstream out_file(filefullpath.c_str(), std::ios::trunc); + + BaseParticles &particles = body->getBaseParticles(); + + // begin of the XML file + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + + // Write point data + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + + Vec3d *pos = particles.ParticlePositions(); + for (size_t i = 0; i != particles.TotalRealParticles(); ++i) + { + out_file << pos[i][0] << " " << pos[i][1] << " " << pos[i][2] << "\n"; + } + + out_file << "\n"; + out_file << "\n"; + + // Write face data + out_file << "\n"; + out_file << "\n"; + + for (const auto &face : faces_) + { + for (const auto &vertex : face) + { + out_file << vertex << " "; + } + out_file << "\n"; + } + + out_file << "\n"; + out_file << "\n"; + + size_t offset = 0; + for (const auto &face : faces_) + { + offset += face.size(); + out_file << offset << " "; + } + + out_file << "\n\n"; + out_file << "\n"; + + // Write face attribute data + out_file << "\n"; + + writeCellsToVtk(out_file, particles); + + out_file << "\n"; + + // Write file footer + out_file << "\n"; + out_file << "\n"; + out_file << "\n"; + + out_file.close(); + } + body->setNotNewlyUpdated(); + } +} +//=================================================================================================// +} // namespace SPH diff --git a/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp b/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp new file mode 100644 index 0000000000..23ce2c99c3 --- /dev/null +++ b/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp @@ -0,0 +1,97 @@ +#ifndef IO_VTK_MESH_3D_HPP +#define IO_VTK_MESH_3D_HPP + +#include "io_vtk_mesh.h" + +namespace SPH +{ +//=============================================================================================// +template +void BodyStatesRecordingToTriangleMeshVtp::writeCellsToVtk(OutStreamType &output_stream, BaseParticles &particles) +{ + ParticleVariables &variables_to_write = particles.VariablesToWrite(); + + // write cell IDs + output_stream + << " \n"; + output_stream << " "; + for (size_t i = 0; i != faces_.size(); ++i) + { + output_stream << i << " "; + } + output_stream << std::endl; + output_stream << " \n"; + + // write scalars + constexpr int type_index_Real = DataTypeIndex::value; + for (DiscreteVariable *variable : std::get(variables_to_write)) + { + Real *data_field = variable->Data(); + output_stream << " Name() << "\" type=\"Float32\" Format=\"ascii\">\n"; + output_stream << " "; + for (size_t i = 0; i != faces_.size(); ++i) + { + std::array &face = faces_[i]; + Real sum = 0.0; + for (size_t j = 0; j != face.size(); ++j) + { + sum += data_field[face[j]]; + } + output_stream << std::fixed << std::setprecision(9) << sum / Real(face.size()) << " "; + } + output_stream << std::endl; + output_stream << " \n"; + } + + // write vectors + constexpr int type_index_Vecd = DataTypeIndex::value; + for (DiscreteVariable *variable : std::get(variables_to_write)) + { + Vecd *data_field = variable->Data(); + output_stream << " Name() << "\" type=\"Float32\" NumberOfComponents=\"3\" Format=\"ascii\">\n"; + output_stream << " "; + for (size_t i = 0; i != faces_.size(); ++i) + { + std::array &face = faces_[i]; + Vec3d sum = ZeroData::value; + for (size_t j = 0; j != face.size(); ++j) + { + sum += data_field[face[j]]; + } + Vec3d vector_value = sum / Real(face.size()); + output_stream << std::fixed << std::setprecision(9) << vector_value[0] << " " << vector_value[1] << " " << vector_value[2] << " "; + } + output_stream << std::endl; + output_stream << " \n"; + } + + // write matrices + constexpr int type_index_Matd = DataTypeIndex::value; + for (DiscreteVariable *variable : std::get(variables_to_write)) + { + Matd *data_field = variable->Data(); + output_stream << " Name() << "\" type= \"Float32\" NumberOfComponents=\"9\" Format=\"ascii\">\n"; + output_stream << " "; + for (size_t i = 0; i != faces_.size(); ++i) + { + std::array &face = faces_[i]; + Mat3d sum = ZeroData::value; + for (size_t j = 0; j != face.size(); ++j) + { + sum += data_field[face[j]]; + } + Mat3d matrix_value = sum / Real(face.size()); + + for (int k = 0; k != 3; ++k) + { + Vec3d col_vector = matrix_value.col(k); + output_stream << std::fixed << std::setprecision(9) << col_vector[0] << " " << col_vector[1] << " " << col_vector[2] << " "; + } + } + output_stream << std::endl; + output_stream << " \n"; + } +} +//=============================================================================================// +} // namespace SPH +#endif // IO_VTK_MESH_3D_HPP \ No newline at end of file diff --git a/src/for_3D_build/particle_generator/base_particle_generator_3d.cpp b/src/for_3D_build/particle_generator/base_particle_generator_3d.cpp new file mode 100644 index 0000000000..68745e3d7b --- /dev/null +++ b/src/for_3D_build/particle_generator/base_particle_generator_3d.cpp @@ -0,0 +1,19 @@ +#include "base_particle_generator.h" + +#include "triangle_mesh_shape.h" + +namespace SPH +{ +//=================================================================================================// +ParticleGenerator::ParticleGenerator( + SPHBody &sph_body, BaseParticles &base_particles, TriangleMeshShape &triangle_mesh_shape) + : ParticleGenerator(sph_body, base_particles) +{ + TriangleMesh &triangle_mesh = *triangle_mesh_shape.getTriangleMesh(); + for (int i = 0; i != triangle_mesh.getNumVertices(); ++i) + { + positions_.push_back(SimTKToEigen(triangle_mesh.getVertexPosition(i))); + } +} +//=================================================================================================// +} // namespace SPH diff --git a/src/shared/io_system/io_vtk_mesh.cpp b/src/shared/io_system/io_vtk_mesh.cpp index 2804b8a5c7..cd0474060e 100644 --- a/src/shared/io_system/io_vtk_mesh.cpp +++ b/src/shared/io_system/io_vtk_mesh.cpp @@ -4,89 +4,6 @@ namespace SPH { //=================================================================================================// -BodyStatesRecordingToMeshVtp::BodyStatesRecordingToMeshVtp(SPHBody &body, ANSYSMesh &ansys_mesh) - : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), - elements_nodes_connection_(ansys_mesh.elements_nodes_connection_) {} -//=================================================================================================// -void BodyStatesRecordingToMeshVtp::writeWithFileName(const std::string &sequence) -{ - for (SPHBody *body : bodies_) - { - if (body->checkNewlyUpdated() && state_recording_) - { - std::string filefullpath = io_environment_.output_folder_ + "/" + body->getName() + "_" + sequence + ".vtp"; - if (fs::exists(filefullpath)) - { - fs::remove(filefullpath); - } - std::ofstream out_file(filefullpath.c_str(), std::ios::trunc); - // begin of the XML file - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - - // Write point data - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - - size_t total_nodes = node_coordinates_.size(); - for (size_t node = 0; node != total_nodes; ++node) - { - Vec3d particle_position = upgradeToVec3d(node_coordinates_[node]); - out_file << particle_position[0] << " " << particle_position[1] << " " << particle_position[2] << "\n"; - } - - out_file << "\n"; - out_file << "\n"; - - // Write face data - out_file << "\n"; - out_file << "\n"; - - for (const auto &element : elements_nodes_connection_) - { - for (const auto &vertex : element) - { - out_file << vertex << " "; - } - out_file << "\n"; - } - - out_file << "\n"; - out_file << "\n"; - - size_t offset = 0; - for (const auto &face : elements_nodes_connection_) - { - offset += face.size(); - out_file << offset << " "; - } - - out_file << "\n\n"; - out_file << "\n"; - - // Write face attribute data - out_file << "\n"; - - BaseParticles &particles = body->getBaseParticles(); - writeParticlesToVtk(out_file, particles); - - out_file << "\n"; - - // Write file footer - out_file << "\n"; - out_file << "\n"; - out_file << "\n"; - - out_file.close(); - } - body->setNotNewlyUpdated(); - } -} -//=================================================================================================// BodyStatesRecordingToMeshVtu::BodyStatesRecordingToMeshVtu(SPHBody &body, ANSYSMesh &ansys_mesh) : BodyStatesRecordingToVtp(body), node_coordinates_(ansys_mesh.node_coordinates_), elements_nodes_connection_(ansys_mesh.elements_nodes_connection_), bounds_(body) {}; diff --git a/src/shared/io_system/io_vtk_mesh.h b/src/shared/io_system/io_vtk_mesh.h index bf42583224..d757563f76 100644 --- a/src/shared/io_system/io_vtk_mesh.h +++ b/src/shared/io_system/io_vtk_mesh.h @@ -35,21 +35,24 @@ namespace SPH { /** - * @class BodyStatesRecordingToMeshVtp + * @class BodyStatesRecordingToTriangleMeshVtp * @brief Write files for bodies * the output file is VTK XML format can be visualized by ParaView * with the data type vtkPolyData */ -class BodyStatesRecordingToMeshVtp : public BodyStatesRecordingToVtp +class TriangleMeshShape; +class BodyStatesRecordingToTriangleMeshVtp : public BodyStatesRecordingToVtp { public: - BodyStatesRecordingToMeshVtp(SPHBody &body, ANSYSMesh &ansys_mesh); - virtual ~BodyStatesRecordingToMeshVtp() {}; + BodyStatesRecordingToTriangleMeshVtp(SPHBody &body, TriangleMeshShape &triangle_mesh_shape); + virtual ~BodyStatesRecordingToTriangleMeshVtp() {}; protected: virtual void writeWithFileName(const std::string &sequence) override; - StdLargeVec &node_coordinates_; - StdLargeVec> &elements_nodes_connection_; + StdLargeVec> faces_; + + template + void writeCellsToVtk(OutStreamType &output_stream, BaseParticles &particles); }; class BodyStatesRecordingToMeshVtu : public BodyStatesRecordingToVtp diff --git a/src/shared/particle_generator/base_particle_generator.cpp b/src/shared/particle_generator/base_particle_generator.cpp index e2f8e7cf0c..264045aaac 100644 --- a/src/shared/particle_generator/base_particle_generator.cpp +++ b/src/shared/particle_generator/base_particle_generator.cpp @@ -69,6 +69,10 @@ void ParticleGenerator::initializeParticleVariablesFromReload( surface_particles_.registerSurfacePropertiesFromReload(); } //=================================================================================================// +ParticleGenerator::ParticleGenerator( + SPHBody &sph_body, BaseParticles &base_particles, const StdVec &positions) + : ParticleGenerator(sph_body, base_particles), positions_(positions) {} +//=================================================================================================// void ParticleGenerator::prepareGeometricData() { for (size_t i = 0; i < positions_.size(); ++i) diff --git a/src/shared/particle_generator/base_particle_generator.h b/src/shared/particle_generator/base_particle_generator.h index 46cfa2084d..372b0c7834 100644 --- a/src/shared/particle_generator/base_particle_generator.h +++ b/src/shared/particle_generator/base_particle_generator.h @@ -89,12 +89,13 @@ class ParticleGenerator : public ParticleGenerator // generate observer particles class ParticleGenerator : public ParticleGenerator { public: - explicit ParticleGenerator(SPHBody &sph_body, BaseParticles &base_particles, const StdVec &positions) - : ParticleGenerator(sph_body, base_particles), positions_(positions){}; + ParticleGenerator(SPHBody &sph_body, BaseParticles &base_particles, const StdVec &positions); + ParticleGenerator(SPHBody &sph_body, BaseParticles &base_particles, TriangleMeshShape &triangle_mesh_shape); virtual ~ParticleGenerator(){}; virtual void prepareGeometricData() override; diff --git a/src/shared/particle_generator/particle_generator_mesh.h b/src/shared/particle_generator/particle_generator_mesh.h index ab80908324..eaec7b2646 100644 --- a/src/shared/particle_generator/particle_generator_mesh.h +++ b/src/shared/particle_generator/particle_generator_mesh.h @@ -40,7 +40,7 @@ class GeneratingMethod { public: explicit GeneratingMethod(ANSYSMesh &ansys_mesh); - virtual ~GeneratingMethod(){}; + virtual ~GeneratingMethod() {}; protected: StdLargeVec &elements_centroids_; @@ -53,9 +53,8 @@ class ParticleGenerator { public: explicit ParticleGenerator(SPHBody &sph_body, BaseParticles &base_particles, ANSYSMesh &ansys_mesh); - virtual ~ParticleGenerator(){}; + virtual ~ParticleGenerator() {}; virtual void prepareGeometricData() override; }; - } // namespace SPH #endif // PARTICLE_GENERATOR_MESH_H diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index 1faee2ba34..00bc2c3b0b 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -148,10 +148,15 @@ int main(int ac, char *av[]) ObserverBody observer(sph_system, "Observer"); observer.defineAdaptationRatios(1.15, 2.0); observer.generateParticles(StdVec{obs}); + + TriangleMeshShapeBrick structure_mesh(halfsize_structure, 10, structure_pos); + ObserverBody structure_observer(sph_system, "StructureObserver"); + structure_observer.generateParticles(structure_mesh); //---------------------------------------------------------------------- // Creating body parts. //---------------------------------------------------------------------- - TransformShape wave_probe_buffer_shape(Transform(translation_FS_gauge), FS_gauge); + TransformShape + wave_probe_buffer_shape(Transform(translation_FS_gauge), FS_gauge); BodyRegionByCell wave_probe_buffer(water_block, wave_probe_buffer_shape); //---------------------------------------------------------------------- // Define body relation map. @@ -286,6 +291,7 @@ int main(int ac, char *av[]) // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- BodyStatesRecordingToVtp write_real_body_states(sph_system); + BodyStatesRecordingToTriangleMeshVtp write_structure_surface(structure, structure_mesh); RegressionTestDynamicTimeWarping>> wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); @@ -325,10 +331,11 @@ int main(int ac, char *av[]) write_real_body_states.writeToFile(MainExecutionPolicy{}); write_structure_position.writeToFile(number_of_iterations); wave_gauge.writeToFile(number_of_iterations); - //---------------------------------------------------------------------- - // Main loop of time stepping starts here. - //---------------------------------------------------------------------- - while (sv_physical_time->getValue() < end_time) + write_structure_surface.writeToFile(); + //---------------------------------------------------------------------- + // Main loop of time stepping starts here. + //---------------------------------------------------------------------- + while (sv_physical_time->getValue() < end_time) { Real integral_time = 0.0; while (integral_time < output_interval) From d49b984f3a09a1612c2b1eda224c32d9439aba0f Mon Sep 17 00:00:00 2001 From: xiangyu_hu Date: Mon, 10 Feb 2025 00:31:45 +0100 Subject: [PATCH 21/33] add vtk out for triangle mesh observer --- src/for_3D_build/io_system/io_vtk_mesh_3d.hpp | 11 ----------- .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 2 +- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp b/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp index 23ce2c99c3..7ab743f887 100644 --- a/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp +++ b/src/for_3D_build/io_system/io_vtk_mesh_3d.hpp @@ -11,17 +11,6 @@ void BodyStatesRecordingToTriangleMeshVtp::writeCellsToVtk(OutStreamType &output { ParticleVariables &variables_to_write = particles.VariablesToWrite(); - // write cell IDs - output_stream - << " \n"; - output_stream << " "; - for (size_t i = 0; i != faces_.size(); ++i) - { - output_stream << i << " "; - } - output_stream << std::endl; - output_stream << " \n"; - // write scalars constexpr int type_index_Real = DataTypeIndex::value; for (DiscreteVariable *variable : std::get(variables_to_write)) diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index 00bc2c3b0b..b7bf29fd1d 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -291,7 +291,7 @@ int main(int ac, char *av[]) // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- BodyStatesRecordingToVtp write_real_body_states(sph_system); - BodyStatesRecordingToTriangleMeshVtp write_structure_surface(structure, structure_mesh); + BodyStatesRecordingToTriangleMeshVtp write_structure_surface(structure_observer, structure_mesh); RegressionTestDynamicTimeWarping>> wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); From 03ce1e0d72578be1ae3e2c50a811718924b8d6bb Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Mon, 10 Feb 2025 20:20:08 +0000 Subject: [PATCH 22/33] to test locally --- .../particle_dynamics/complex_algorithms_ck.h | 31 ++++++ .../general_dynamics/interpolation_dynamics.h | 7 +- .../solid_dynamics/all_solid_dynamics_ck.h | 1 + .../solid_dynamics/derived_solid_state.cpp | 21 ++++ .../solid_dynamics/derived_solid_state.h | 100 ++++++++++++++++++ .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 27 ++++- 6 files changed, 180 insertions(+), 7 deletions(-) create mode 100644 src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.cpp create mode 100644 src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.h diff --git a/src/shared/shared_ck/particle_dynamics/complex_algorithms_ck.h b/src/shared/shared_ck/particle_dynamics/complex_algorithms_ck.h index d3d3acf94d..2a80ecface 100644 --- a/src/shared/shared_ck/particle_dynamics/complex_algorithms_ck.h +++ b/src/shared/shared_ck/particle_dynamics/complex_algorithms_ck.h @@ -46,6 +46,7 @@ class DynamicsSequence> : public BaseDynamics() {}; virtual void exec(Real dt = 0.0) override {}; }; + template class DynamicsType, class FirstLocalDynamics, class... OtherLocalDynamics> @@ -67,5 +68,35 @@ class DynamicsSequence +class ArbitraryDynamicsSequence; + +template <> +class ArbitraryDynamicsSequence<> : public BaseDynamics +{ + public: + ArbitraryDynamicsSequence() : BaseDynamics() {}; + virtual void exec(Real dt = 0.0) override {}; +}; + +template +class ArbitraryDynamicsSequence : public FistDynamicsType +{ + protected: + ArbitraryDynamicsSequence other_dynamics_; + + public: + template + explicit ArbitraryDynamicsSequence(FirstParameterSet &&first_parameter_set, OtherParameterSets &&...other_parameter_sets) + : FistDynamicsType(first_parameter_set), + other_dynamics_(std::forward(other_parameter_sets)...){}; + + virtual void exec(Real dt = 0.0) override + { + FistDynamicsType::exec(dt); + other_dynamics_.exec(dt); + }; +}; } // namespace SPH #endif // COMPLEX_ALGORITHMS_CK_H diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h b/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h index 112e84b379..d6f0cdfadd 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h @@ -71,9 +71,12 @@ template class ObservingAQuantityCK : public InteractionDynamicsCK>> { public: - explicit ObservingAQuantityCK(Relation> &pair_contact_relation, const std::string &variable_name) + ObservingAQuantityCK(Relation> &pair_contact_relation, const std::string &variable_name) : InteractionDynamicsCK>>(pair_contact_relation, variable_name){}; - virtual ~ObservingAQuantityCK(){}; + template + explicit ObservingAQuantityCK(InteractArgs parameters) + : ObservingAQuantityCK(parameters.body_relation_, std::get<0>(parameters.others_)){}; + virtual ~ObservingAQuantityCK(){}; }; } // namespace SPH #endif // INTERPOLATION_DYNAMICS_H diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/all_solid_dynamics_ck.h b/src/shared/shared_ck/particle_dynamics/solid_dynamics/all_solid_dynamics_ck.h index 1d8e0fb560..27ed71e037 100644 --- a/src/shared/shared_ck/particle_dynamics/solid_dynamics/all_solid_dynamics_ck.h +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/all_solid_dynamics_ck.h @@ -26,4 +26,5 @@ #pragma once +#include "derived_solid_state.h" #include "solid_constraint.hpp" diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.cpp b/src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.cpp new file mode 100644 index 0000000000..757ca65484 --- /dev/null +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.cpp @@ -0,0 +1,21 @@ +#include "derived_solid_state.h" + +namespace SPH +{ +namespace solid_dynamics +{ +//=================================================================================================// +DisplacementAndPosition::DisplacementAndPosition(SPHBody &sph_body) + : LocalDynamics(sph_body), + dv_pos_(particles_->getVariableByName("Position")), + dv_pos0_(particles_->registerStateVariableOnlyFrom("InitialPosition", "Position")), + dv_displacement_(particles_->registerStateVariableOnly("Displacement")) {} +//=============================================================================================// +UpdateDisplacementFromPosition::UpdateDisplacementFromPosition(SPHBody &sph_body) + : DisplacementAndPosition(sph_body) {} +//=============================================================================================// +UpdatePositionFromDisplacement::UpdatePositionFromDisplacement(SPHBody &sph_body) + : DisplacementAndPosition(sph_body) {} +//=================================================================================================// +} // namespace solid_dynamics +} // namespace SPH diff --git a/src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.h b/src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.h new file mode 100644 index 0000000000..a00464c415 --- /dev/null +++ b/src/shared/shared_ck/particle_dynamics/solid_dynamics/derived_solid_state.h @@ -0,0 +1,100 @@ +/* ------------------------------------------------------------------------- * + * SPHinXsys * + * ------------------------------------------------------------------------- * + * SPHinXsys (pronunciation: s'finksis) is an acronym from Smoothed Particle * + * Hydrodynamics for industrial compleX systems. It provides C++ APIs for * + * physical accurate simulation and aims to model coupled industrial dynamic * + * systems including fluid, solid, multi-body dynamics and beyond with SPH * + * (smoothed particle hydrodynamics), a meshless computational method using * + * particle discretization. * + * * + * SPHinXsys is partially funded by German Research Foundation * + * (Deutsche Forschungsgemeinschaft) DFG HU1527/6-1, HU1527/10-1, * + * HU1527/12-1 and HU1527/12-4. * + * * + * Portions copyright (c) 2017-2023 Technical University of Munich and * + * the authors' affiliations. * + * * + * Licensed under the Apache License, Version 2.0 (the "License"); you may * + * not use this file except in compliance with the License. You may obtain a * + * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * + * * + * ------------------------------------------------------------------------- */ +/** + * @file derived_solid_state.h + * @brief tbd. + * @author Xiangyu Hu + */ + +#ifndef DERIVED_SOLID_STATE_H +#define DERIVED_SOLID_STATE_H + +#include "base_general_dynamics.h" + +namespace SPH +{ +namespace solid_dynamics +{ +class DisplacementAndPosition : public LocalDynamics +{ + public: + explicit DisplacementAndPosition(SPHBody &sph_body); + virtual ~DisplacementAndPosition() {}; + + class UpdateKernel + { + public: + template + UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + : pos_(encloser.dv_pos_->DelegatedData(ex_policy)), + pos0_(encloser.dv_pos0_->DelegatedData(ex_policy)), + displacement_(encloser.dv_displacement_->DelegatedData(ex_policy)){}; + + protected: + Vecd *pos_, *pos0_, *displacement_; + }; + + protected: + DiscreteVariable *dv_pos_, *dv_pos0_, *dv_displacement_; +}; + +class UpdateDisplacementFromPosition : public DisplacementAndPosition +{ + public: + explicit UpdateDisplacementFromPosition(SPHBody &sph_body); + virtual ~UpdateDisplacementFromPosition() {}; + + class UpdateKernel : public DisplacementAndPosition::UpdateKernel + { + public: + template + UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + : DisplacementAndPosition::UpdateKernel(ex_policy, encloser){}; + void update(size_t index_i, Real dt = 0.0) + { + displacement_[index_i] = pos_[index_i] - pos0_[index_i]; + }; + }; +}; + +class UpdatePositionFromDisplacement : public DisplacementAndPosition +{ + public: + explicit UpdatePositionFromDisplacement(SPHBody &sph_body); + virtual ~UpdatePositionFromDisplacement() {}; + + class UpdateKernel : public DisplacementAndPosition::UpdateKernel + { + public: + template + UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + : DisplacementAndPosition::UpdateKernel(ex_policy, encloser){}; + void update(size_t index_i, Real dt = 0.0) + { + pos_[index_i] = pos0_[index_i] + displacement_[index_i]; + }; + }; +}; +} // namespace solid_dynamics +} // namespace SPH +#endif // DERIVED_SOLID_STATE_H diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index b7bf29fd1d..48c7b59bc7 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -170,6 +170,7 @@ int main(int ac, char *av[]) Relation> water_block_contact(water_block, {&wall_boundary, &structure}); Relation> structure_contact(structure, {&water_block}); Relation> observer_contact(observer, {&structure}); + Relation> structure_observer_contact(structure_observer, {&structure}); //---------------------------------------------------------------------- // Define the main execution policy for this case. //---------------------------------------------------------------------- @@ -195,6 +196,8 @@ int main(int ac, char *av[]) structure_update_contact_relation(structure_contact); UpdateRelation> observer_update_contact_relation(observer_contact); + UpdateRelation> + structure_observer_update_contact_relation(structure_observer_contact); ParticleSortCK particle_sort(water_block); Gravity gravity(Vec3d(0.0, 0.0, -gravity_g)); @@ -219,6 +222,15 @@ int main(int ac, char *av[]) ReduceDynamicsCK fluid_advection_time_step(water_block, U_f); ReduceDynamicsCK fluid_acoustic_time_step(water_block); + + ArbitraryDynamicsSequence< + StateDynamics, + ObservingAQuantityCK, + StateDynamics> + structure_observer_follow_structure( + structure, + InteractArgs(structure_observer_contact, std::string("Displacement")), + structure_observer); //---------------------------------------------------------------------- // Define the multi-body system //---------------------------------------------------------------------- @@ -312,6 +324,7 @@ int main(int ac, char *av[]) water_block_update_complex_relation.exec(); structure_update_contact_relation.exec(); observer_update_contact_relation.exec(); + structure_observer_update_contact_relation.exec(); //---------------------------------------------------------------------- // Basic control parameters for time stepping. //---------------------------------------------------------------------- @@ -331,11 +344,11 @@ int main(int ac, char *av[]) write_real_body_states.writeToFile(MainExecutionPolicy{}); write_structure_position.writeToFile(number_of_iterations); wave_gauge.writeToFile(number_of_iterations); - write_structure_surface.writeToFile(); - //---------------------------------------------------------------------- - // Main loop of time stepping starts here. - //---------------------------------------------------------------------- - while (sv_physical_time->getValue() < end_time) + write_structure_surface.writeToFile(MainExecutionPolicy{}); + //---------------------------------------------------------------------- + // Main loop of time stepping starts here. + //---------------------------------------------------------------------- + while (sv_physical_time->getValue() < end_time) { Real integral_time = 0.0; while (integral_time < output_interval) @@ -397,7 +410,11 @@ int main(int ac, char *av[]) TickCount t2 = TickCount::now(); if (total_time >= relax_time) + { write_real_body_states.writeToFile(MainExecutionPolicy{}); + structure_observer_follow_structure.exec(); + write_structure_surface.writeToFile(MainExecutionPolicy{}); + } TickCount t3 = TickCount::now(); interval += t3 - t2; } From 47d1908189e210a5c7f3f72fb8a1259528dde940 Mon Sep 17 00:00:00 2001 From: xiangyu_hu Date: Mon, 10 Feb 2025 23:21:45 +0100 Subject: [PATCH 23/33] a bug in compuitng the number of faces --- src/for_3D_build/io_system/io_vtk_mesh_3d.cpp | 15 ++++++--------- .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 5 ++++- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp index 0d5beccf66..570ebd57cd 100644 --- a/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp +++ b/src/for_3D_build/io_system/io_vtk_mesh_3d.cpp @@ -11,16 +11,13 @@ BodyStatesRecordingToTriangleMeshVtp::BodyStatesRecordingToTriangleMeshVtp( : BodyStatesRecordingToVtp(body) { TriangleMesh &triangle_mesh = *triangle_mesh_shape.getTriangleMesh(); - for (int i = 0; i != triangle_mesh.getNumFaces(); ++i) + faces_.reserve(triangle_mesh.getNumFaces()); + for (int i = 0; i < triangle_mesh.getNumFaces(); i++) { - faces_.reserve(triangle_mesh.getNumFaces()); - for (int i = 0; i < triangle_mesh.getNumFaces(); i++) - { - auto f1 = triangle_mesh.getFaceVertex(i, 0); - auto f2 = triangle_mesh.getFaceVertex(i, 1); - auto f3 = triangle_mesh.getFaceVertex(i, 2); - faces_.push_back({f1, f2, f3}); - } + auto f1 = triangle_mesh.getFaceVertex(i, 0); + auto f2 = triangle_mesh.getFaceVertex(i, 1); + auto f3 = triangle_mesh.getFaceVertex(i, 2); + faces_.push_back({f1, f2, f3}); } } //=================================================================================================// diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index 48c7b59bc7..06260d0f76 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -149,7 +149,7 @@ int main(int ac, char *av[]) observer.defineAdaptationRatios(1.15, 2.0); observer.generateParticles(StdVec{obs}); - TriangleMeshShapeBrick structure_mesh(halfsize_structure, 10, structure_pos); + TriangleMeshShapeBrick structure_mesh(halfsize_structure, 1, structure_pos); ObserverBody structure_observer(sph_system, "StructureObserver"); structure_observer.generateParticles(structure_mesh); //---------------------------------------------------------------------- @@ -226,9 +226,11 @@ int main(int ac, char *av[]) ArbitraryDynamicsSequence< StateDynamics, ObservingAQuantityCK, + ObservingAQuantityCK, StateDynamics> structure_observer_follow_structure( structure, + InteractArgs(structure_observer_contact, std::string("Velocity")), InteractArgs(structure_observer_contact, std::string("Displacement")), structure_observer); //---------------------------------------------------------------------- @@ -304,6 +306,7 @@ int main(int ac, char *av[]) //---------------------------------------------------------------------- BodyStatesRecordingToVtp write_real_body_states(sph_system); BodyStatesRecordingToTriangleMeshVtp write_structure_surface(structure_observer, structure_mesh); + write_structure_surface.addToWrite(structure_observer, "Velocity"); RegressionTestDynamicTimeWarping>> wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); From b7f4faa5fbadff7f8c4392438a6d38745bf8fcf7 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Tue, 11 Feb 2025 07:55:22 +0000 Subject: [PATCH 24/33] rename InteractArgs to DynamicsArgs for generalization in complex dynamics setting --- .../particle_dynamics/base_local_dynamics.h | 14 +-- .../particle_dynamics_dissipation.h | 24 +++--- .../eulerian_fluid_integration.h | 26 +++--- .../transport_velocity_correction.h | 12 +-- .../general_dynamics/kernel_correction.h | 18 ++-- .../relax_dynamics/relax_stepping.h | 20 ++--- .../general_dynamics/interpolation_dynamics.h | 10 +-- .../general_dynamics/kernel_correction_ck.h | 16 ++-- .../test_2d_dambreak_ck/dambreak_ck.cpp | 2 +- .../lid_driven_cavity_ck.cpp | 37 ++++---- .../test_2d_collision/collision.cpp | 2 +- .../2d_eulerian_flow_around_cylinder_LG.cpp | 4 +- .../mr_free_stream_around_cylinder.cpp | 2 +- .../test_2d_hydrostatic_fluid_shell.cpp | 6 +- .../hydrostatic_fsi.cpp | 2 +- .../nonlinear_wave_fsi.cpp | 2 +- .../droplet_conservation.cpp | 4 +- .../test_2d_standing_wave/standing_wave.cpp | 2 +- tests/2d_examples/test_2d_throat/throat.cpp | 2 +- .../test_3d_dambreak_ck/dambreak.cpp | 2 +- .../3d_examples_ck/test_3d_stfb_ck/stfb.cpp | 8 +- .../nonlinear_wave_fsi.cpp | 2 +- .../for_2D_build/k-epsilon_turbulent_model.h | 86 +++++++++---------- .../lid_driven_cavity.cpp | 4 +- .../test_2d_dambreak_sycl/dambreak_sycl.cpp | 4 +- .../lid_driven_cavity_sycl.cpp | 38 ++++---- .../test_3d_dambreak_sycl/dambreak.cpp | 2 +- 27 files changed, 175 insertions(+), 176 deletions(-) diff --git a/src/shared/particle_dynamics/base_local_dynamics.h b/src/shared/particle_dynamics/base_local_dynamics.h index 0920c0c4c9..ec672fe2a0 100644 --- a/src/shared/particle_dynamics/base_local_dynamics.h +++ b/src/shared/particle_dynamics/base_local_dynamics.h @@ -143,19 +143,19 @@ class Average : public ReduceSumType }; /** - * @class InteractArgs + * @class DynamicsArgs * @brief Class template argument deduction (CTAD) for constructing interaction dynamics. * @details Note that the form "XXX" is not std::string type, so we need to use * std::string("XXX") to convert it to std::string type. */ -template -struct InteractArgs +template +struct DynamicsArgs { - BodyRelationType &body_relation_; + DynamicsIdentifier &identifier_; std::tuple others_; - SPHBody &getSPHBody() { return body_relation_.getSPHBody(); }; - InteractArgs(BodyRelationType &body_relation, OtherArgs... other_args) - : body_relation_(body_relation), others_(other_args...) {}; + SPHBody &getSPHBody() { return identifier_.getSPHBody(); }; + DynamicsArgs(DynamicsIdentifier &identifier, OtherArgs... other_args) + : identifier_(identifier), others_(other_args...) {}; }; /** diff --git a/src/shared/particle_dynamics/dissipation_dynamics/particle_dynamics_dissipation.h b/src/shared/particle_dynamics/dissipation_dynamics/particle_dynamics_dissipation.h index 8e0545cf80..8cc94c2cfe 100644 --- a/src/shared/particle_dynamics/dissipation_dynamics/particle_dynamics_dissipation.h +++ b/src/shared/particle_dynamics/dissipation_dynamics/particle_dynamics_dissipation.h @@ -50,7 +50,7 @@ struct ErrorAndParameters Real a_, c_; ErrorAndParameters() : error_(ZeroData::value), - a_(0), c_(0){}; + a_(0), c_(0) {}; }; class FixedDampingRate @@ -59,8 +59,8 @@ class FixedDampingRate FixedDampingRate(BaseParticles *particles, Real eta, Real c = 1.0) : damping_rate_(particles->registerSingularVariable("DampingRate", eta)->Data()), specific_capacity_(particles->registerSingularVariable("SpecificCapacity", c)->Data()), - mass_(particles->getVariableDataByName("Mass")){}; - virtual ~FixedDampingRate(){}; + mass_(particles->getVariableDataByName("Mass")) {}; + virtual ~FixedDampingRate() {}; Real DampingRate(size_t i, size_t j) { return *damping_rate_; }; Real DampingRate(size_t i) { return *damping_rate_; }; @@ -83,12 +83,12 @@ class Damping template explicit Damping(BaseRelationType &base_relation, const std::string &name, Args &&...args); template - Damping(InteractArgs parameters, std::index_sequence) - : Damping(parameters.body_relation_, std::get(parameters.others_)...){}; + Damping(DynamicsArgs parameters, std::index_sequence) + : Damping(parameters.identifier_, std::get(parameters.others_)...){}; template - explicit Damping(InteractArgs parameters) + explicit Damping(DynamicsArgs parameters) : Damping(parameters, std::make_index_sequence>{}){}; - virtual ~Damping(){}; + virtual ~Damping() {}; protected: typedef DataType DampingVariable; @@ -114,7 +114,7 @@ class Damping, DataType, DampingRateType> template Damping(Args &&...args) : Damping(std::forward(args)...){}; - virtual ~Damping(){}; + virtual ~Damping() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -137,7 +137,7 @@ class Damping, DataType, DampingRateType> template Damping(Args &&...args) : Damping(std::forward(args)...){}; - virtual ~Damping(){}; + virtual ~Damping() {}; void interaction(size_t index_i, Real dt = 0.0); }; template @@ -150,7 +150,7 @@ class Damping, DataType, DampingRateType> public: template Damping(Args &&...args); - virtual ~Damping(){}; + virtual ~Damping() {}; protected: StdVec contact_Vol_; @@ -164,7 +164,7 @@ class Damping, DataType, DampingRateType> template Damping(Args &&...args) : Damping, DataType, DampingRateType>(std::forward(args)...){}; - virtual ~Damping(){}; + virtual ~Damping() {}; void interaction(size_t index_i, Real dt = 0.0); }; template @@ -191,7 +191,7 @@ class DampingWithRandomChoice : public DampingAlgorithmType public: template DampingWithRandomChoice(Real random_ratio, Args &&...args); - virtual ~DampingWithRandomChoice(){}; + virtual ~DampingWithRandomChoice() {}; virtual void exec(Real dt = 0.0) override; }; diff --git a/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_fluid_integration.h b/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_fluid_integration.h index f48477380a..8414ea2ad9 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_fluid_integration.h +++ b/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_fluid_integration.h @@ -41,7 +41,7 @@ class EulerianIntegration : public BaseIntegration public: template explicit EulerianIntegration(BaseRelationType &base_relation); - virtual ~EulerianIntegration(){}; + virtual ~EulerianIntegration() {}; protected: Vecd *mom_, *dmom_dt_; @@ -58,9 +58,9 @@ class EulerianIntegration1stHalf, RiemannSolverType> public: explicit EulerianIntegration1stHalf(BaseInnerRelation &inner_relation, Real limiter_parameter = 15.0); template - explicit EulerianIntegration1stHalf(InteractArgs parameters) - : EulerianIntegration1stHalf(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~EulerianIntegration1stHalf(){}; + explicit EulerianIntegration1stHalf(DynamicsArgs parameters) + : EulerianIntegration1stHalf(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~EulerianIntegration1stHalf() {}; void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); @@ -77,9 +77,9 @@ class EulerianIntegration1stHalf, RiemannSolverType> public: EulerianIntegration1stHalf(BaseContactRelation &wall_contact_relation, Real limiter_parameter = 15.0); template - explicit EulerianIntegration1stHalf(InteractArgs parameters) - : EulerianIntegration1stHalf(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~EulerianIntegration1stHalf(){}; + explicit EulerianIntegration1stHalf(DynamicsArgs parameters) + : EulerianIntegration1stHalf(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~EulerianIntegration1stHalf() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -100,9 +100,9 @@ class EulerianIntegration2ndHalf, RiemannSolverType> explicit EulerianIntegration2ndHalf(BaseInnerRelation &inner_relation, Real limiter_parameter = 15.0); template - explicit EulerianIntegration2ndHalf(InteractArgs parameters) - : EulerianIntegration2ndHalf(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~EulerianIntegration2ndHalf(){}; + explicit EulerianIntegration2ndHalf(DynamicsArgs parameters) + : EulerianIntegration2ndHalf(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~EulerianIntegration2ndHalf() {}; void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); @@ -122,9 +122,9 @@ class EulerianIntegration2ndHalf, RiemannSolverType> public: EulerianIntegration2ndHalf(BaseContactRelation &wall_contact_relation, Real limiter_parameter = 15.0); template - explicit EulerianIntegration2ndHalf(InteractArgs parameters) - : EulerianIntegration2ndHalf(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~EulerianIntegration2ndHalf(){}; + explicit EulerianIntegration2ndHalf(DynamicsArgs parameters) + : EulerianIntegration2ndHalf(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~EulerianIntegration2ndHalf() {}; void interaction(size_t index_i, Real dt = 0.0); protected: diff --git a/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.h b/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.h index 918d465c1d..e88c2b8efd 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.h +++ b/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.h @@ -52,7 +52,7 @@ class TransportVelocityCorrection explicit TransportVelocityCorrection(BaseRelationType &base_relation); - virtual ~TransportVelocityCorrection(){}; + virtual ~TransportVelocityCorrection() {}; protected: Vecd *zero_gradient_residue_; @@ -67,9 +67,9 @@ class TransportVelocityCorrection, CommonCont public: explicit TransportVelocityCorrection(BaseInnerRelation &inner_relation, Real coefficient = 0.2); template - explicit TransportVelocityCorrection(InteractArgs parameters) - : TransportVelocityCorrection(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~TransportVelocityCorrection(){}; + explicit TransportVelocityCorrection(DynamicsArgs parameters) + : TransportVelocityCorrection(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~TransportVelocityCorrection() {}; void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); @@ -90,7 +90,7 @@ class TransportVelocityCorrection, CommonControlTypes...> { public: explicit TransportVelocityCorrection(BaseContactRelation &contact_relation); - virtual ~TransportVelocityCorrection(){}; + virtual ~TransportVelocityCorrection() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -103,7 +103,7 @@ class TransportVelocityCorrection, KernelCorrectionType, CommonControl { public: explicit TransportVelocityCorrection(BaseContactRelation &contact_relation); - virtual ~TransportVelocityCorrection(){}; + virtual ~TransportVelocityCorrection() {}; void interaction(size_t index_i, Real dt = 0.0); protected: diff --git a/src/shared/particle_dynamics/general_dynamics/kernel_correction.h b/src/shared/particle_dynamics/general_dynamics/kernel_correction.h index 9b6c3461c1..bc1d9758e8 100644 --- a/src/shared/particle_dynamics/general_dynamics/kernel_correction.h +++ b/src/shared/particle_dynamics/general_dynamics/kernel_correction.h @@ -48,7 +48,7 @@ class LinearGradientCorrectionMatrix public: template explicit LinearGradientCorrectionMatrix(BaseRelationType &base_relation); - virtual ~LinearGradientCorrectionMatrix(){}; + virtual ~LinearGradientCorrectionMatrix() {}; protected: Real *Vol_; @@ -63,11 +63,11 @@ class LinearGradientCorrectionMatrix> public: explicit LinearGradientCorrectionMatrix(BaseInnerRelation &inner_relation, Real alpha = Real(0)) - : LinearGradientCorrectionMatrix(inner_relation), alpha_(alpha){}; + : LinearGradientCorrectionMatrix(inner_relation), alpha_(alpha) {}; template - explicit LinearGradientCorrectionMatrix(InteractArgs parameters) - : LinearGradientCorrectionMatrix(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~LinearGradientCorrectionMatrix(){}; + explicit LinearGradientCorrectionMatrix(DynamicsArgs parameters) + : LinearGradientCorrectionMatrix(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~LinearGradientCorrectionMatrix() {}; void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); }; @@ -79,7 +79,7 @@ class LinearGradientCorrectionMatrix> { public: explicit LinearGradientCorrectionMatrix(BaseContactRelation &contact_relation); - virtual ~LinearGradientCorrectionMatrix(){}; + virtual ~LinearGradientCorrectionMatrix() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -99,7 +99,7 @@ class KernelGradientCorrection public: template explicit KernelGradientCorrection(BaseRelationType &base_relation); - virtual ~KernelGradientCorrection(){}; + virtual ~KernelGradientCorrection() {}; protected: template @@ -114,7 +114,7 @@ class KernelGradientCorrection> public: explicit KernelGradientCorrection(BaseInnerRelation &inner_relation); - virtual ~KernelGradientCorrection(){}; + virtual ~KernelGradientCorrection() {}; void interaction(size_t index_i, Real dt = 0.0); }; using KernelGradientCorrectionInner = KernelGradientCorrection>; @@ -127,7 +127,7 @@ class KernelGradientCorrection> public: KernelGradientCorrection(BaseContactRelation &contact_relation); - virtual ~KernelGradientCorrection(){}; + virtual ~KernelGradientCorrection() {}; void interaction(size_t index_i, Real dt = 0.0); }; diff --git a/src/shared/particle_dynamics/relax_dynamics/relax_stepping.h b/src/shared/particle_dynamics/relax_dynamics/relax_stepping.h index 678bd48b1f..abe7b5f7db 100644 --- a/src/shared/particle_dynamics/relax_dynamics/relax_stepping.h +++ b/src/shared/particle_dynamics/relax_dynamics/relax_stepping.h @@ -50,7 +50,7 @@ class RelaxationResidue public: template explicit RelaxationResidue(BaseRelationType &base_relation); - virtual ~RelaxationResidue(){}; + virtual ~RelaxationResidue() {}; protected: SPHAdaptation *sph_adaptation_; @@ -65,7 +65,7 @@ class RelaxationResidue> public: explicit RelaxationResidue(BaseInnerRelation &inner_relation); RelaxationResidue(BaseInnerRelation &inner_relation, const std::string &sub_shape_name); - virtual ~RelaxationResidue(){}; + virtual ~RelaxationResidue() {}; Shape &getRelaxShape() { return relax_shape_; }; void interaction(size_t index_i, Real dt = 0.0); @@ -80,9 +80,9 @@ class RelaxationResidue> : public RelaxationResidue RelaxationResidue(Args &&...args); template - explicit RelaxationResidue(InteractArgs parameters) - : RelaxationResidue(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~RelaxationResidue(){}; + explicit RelaxationResidue(DynamicsArgs parameters) + : RelaxationResidue(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~RelaxationResidue() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -103,7 +103,7 @@ class RelaxationResidue> contact_Vol_.push_back(this->contact_particles_[k]->template registerStateVariable("VolumetricMeasure")); } }; - virtual ~RelaxationResidue(){}; + virtual ~RelaxationResidue() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -118,7 +118,7 @@ class RelaxationScaling : public LocalDynamicsReduce { public: explicit RelaxationScaling(SPHBody &sph_body); - virtual ~RelaxationScaling(){}; + virtual ~RelaxationScaling() {}; Real reduce(size_t index_i, Real dt = 0.0); virtual Real outputResult(Real reduced_value); @@ -139,7 +139,7 @@ class PositionRelaxation : public LocalDynamics public: explicit PositionRelaxation(SPHBody &sph_body); - virtual ~PositionRelaxation(){}; + virtual ~PositionRelaxation() {}; void update(size_t index_i, Real scaling); }; @@ -155,7 +155,7 @@ class UpdateSmoothingLengthRatioByShape : public LocalDynamics public: UpdateSmoothingLengthRatioByShape(SPHBody &sph_body, Shape &target_shape); explicit UpdateSmoothingLengthRatioByShape(SPHBody &sph_body); - virtual ~UpdateSmoothingLengthRatioByShape(){}; + virtual ~UpdateSmoothingLengthRatioByShape() {}; void update(size_t index_i, Real dt = 0.0); }; @@ -165,7 +165,7 @@ class RelaxationStep : public BaseDynamics public: template explicit RelaxationStep(FirstArg &&first_arg, OtherArgs &&...other_args); - virtual ~RelaxationStep(){}; + virtual ~RelaxationStep() {}; SimpleDynamics &SurfaceBounding() { return surface_bounding_; }; virtual void exec(Real dt = 0.0) override; diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h b/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h index d6f0cdfadd..c350276e5a 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/interpolation_dynamics.h @@ -45,7 +45,7 @@ class Interpolation> : public Interaction> { public: Interpolation(Relation> &pair_contact_relation, const std::string &variable_name); - virtual ~Interpolation(){}; + virtual ~Interpolation() {}; class InteractKernel : public Interaction>::InteractKernel { @@ -72,11 +72,11 @@ class ObservingAQuantityCK : public InteractionDynamicsCK> &pair_contact_relation, const std::string &variable_name) - : InteractionDynamicsCK>>(pair_contact_relation, variable_name){}; + : InteractionDynamicsCK>>(pair_contact_relation, variable_name) {}; template - explicit ObservingAQuantityCK(InteractArgs parameters) - : ObservingAQuantityCK(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~ObservingAQuantityCK(){}; + explicit ObservingAQuantityCK(DynamicsArgs parameters) + : ObservingAQuantityCK(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~ObservingAQuantityCK() {}; }; } // namespace SPH #endif // INTERPOLATION_DYNAMICS_H diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/kernel_correction_ck.h b/src/shared/shared_ck/particle_dynamics/general_dynamics/kernel_correction_ck.h index f2f0cd4ae9..0a761bdb27 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/kernel_correction_ck.h +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/kernel_correction_ck.h @@ -46,7 +46,7 @@ class LinearCorrectionMatrix> public: template explicit LinearCorrectionMatrix(DynamicsIdentifier &identifier); - virtual ~LinearCorrectionMatrix(){}; + virtual ~LinearCorrectionMatrix() {}; class InteractKernel : public Interaction>::InteractKernel @@ -74,11 +74,11 @@ class LinearCorrectionMatrix> public: explicit LinearCorrectionMatrix(Relation> &inner_relation, Real alpha = Real(0)) - : LinearCorrectionMatrix>(inner_relation), alpha_(alpha){}; + : LinearCorrectionMatrix>(inner_relation), alpha_(alpha) {}; template - explicit LinearCorrectionMatrix(InteractArgs parameters) - : LinearCorrectionMatrix(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~LinearCorrectionMatrix(){}; + explicit LinearCorrectionMatrix(DynamicsArgs parameters) + : LinearCorrectionMatrix(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~LinearCorrectionMatrix() {}; class InteractKernel : public LinearCorrectionMatrix>::InteractKernel @@ -114,7 +114,7 @@ class LinearCorrectionMatrix> { public: explicit LinearCorrectionMatrix(Relation> &contact_relation); - virtual ~LinearCorrectionMatrix(){}; + virtual ~LinearCorrectionMatrix() {}; class InteractKernel : public LinearCorrectionMatrix>::InteractKernel @@ -139,7 +139,7 @@ using LinearCorrectionMatrixComplex = LinearCorrectionMatrix, class NoKernelCorrectionCK : public KernelCorrection { public: - NoKernelCorrectionCK(BaseParticles *particles) : KernelCorrection(){}; + NoKernelCorrectionCK(BaseParticles *particles) : KernelCorrection() {}; class ComputingKernel : public ParameterFixed { @@ -156,7 +156,7 @@ class LinearCorrectionCK : public KernelCorrection public: LinearCorrectionCK(BaseParticles *particles) : KernelCorrection(), - dv_B_(particles->getVariableByName("LinearCorrectionMatrix")){}; + dv_B_(particles->getVariableByName("LinearCorrectionMatrix")) {}; class ComputingKernel : public ParameterVariable { diff --git a/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp b/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp index 11c1f3281e..d2e4abd130 100644 --- a/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp +++ b/tests/2d_examples/2d_examples_ck/test_2d_dambreak_ck/dambreak_ck.cpp @@ -106,7 +106,7 @@ int main(int ac, char *av[]) StateDynamics water_advection_step_close(water_block); InteractionDynamicsCK - fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + fluid_linear_correction_matrix(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); InteractionDynamicsCK fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); InteractionDynamicsCK diff --git a/tests/2d_examples/2d_examples_ck/test_2d_lid_driven_cavity_corrected_ck/lid_driven_cavity_ck.cpp b/tests/2d_examples/2d_examples_ck/test_2d_lid_driven_cavity_corrected_ck/lid_driven_cavity_ck.cpp index 7067a81111..e9944ede21 100644 --- a/tests/2d_examples/2d_examples_ck/test_2d_lid_driven_cavity_corrected_ck/lid_driven_cavity_ck.cpp +++ b/tests/2d_examples/2d_examples_ck/test_2d_lid_driven_cavity_corrected_ck/lid_driven_cavity_ck.cpp @@ -5,7 +5,7 @@ * @author Bo Zhang, Xiangyu Hu */ #include "sphinxsys_ck.h" // SPHinXsys Library. -using namespace SPH; // Namespace cite here. +using namespace SPH; // Namespace cite here. //---------------------------------------------------------------------- // Basic geometry parameters and numerical setup. //---------------------------------------------------------------------- @@ -137,7 +137,7 @@ int main(int ac, char *av[]) // Creating body, materials and particles. //---------------------------------------------------------------------- FluidBody water_body(sph_system, makeShared("WaterBody")); - water_body.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); + water_body.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); water_body.generateParticles(); SolidBody wall_boundary(sph_system, makeShared("Wall")); @@ -154,7 +154,7 @@ int main(int ac, char *av[]) // Define body relation map. // The contact map gives the topological connections between the bodies. // Basically the the range of bodies to build neighbor particle lists. - //---------------------------------------------------------------------- + //---------------------------------------------------------------------- Relation> water_block_inner(water_body); Relation> water_wall_contact(water_body, {&wall_boundary}); Relation> horizontal_observer_contact(horizontal_observer, {&water_body}); @@ -185,7 +185,7 @@ int main(int ac, char *av[]) //---------------------------------------------------------------------- StateDynamics wall_boundary_normal_direction(wall_boundary); // run on CPU - /** Time step size with considering sound wave speed. */ + /** Time step size with considering sound wave speed. */ StateDynamics water_advection_step_setup(water_body); StateDynamics water_advection_step_close(water_body); @@ -193,29 +193,29 @@ int main(int ac, char *av[]) SimpleDynamics solid_initial_condition(wall_boundary); /** Kernel correction matrix and transport velocity formulation. */ InteractionDynamicsCK - fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + fluid_linear_correction_matrix(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); /** Evaluation of density by summation approach. */ InteractionDynamicsCK - fluid_density_regularization(water_block_inner, water_wall_contact); /** Pressure and density relaxation algorithm by using Verlet time stepping. */ + fluid_density_regularization(water_block_inner, water_wall_contact); /** Pressure and density relaxation algorithm by using Verlet time stepping. */ InteractionDynamicsCK fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); InteractionDynamicsCK fluid_acoustic_step_2nd_half(water_block_inner, water_wall_contact); - /** + /** * Free Surface Indicator and BulkParticles for Transport Velocity Correction are not required for this simulation. - * They are included here solely for testing and verification purposes, + * They are included here solely for testing and verification purposes, * and do not contribute to the primary objectives of the current case. */ InteractionDynamicsCK - fluid_boundary_indicator(water_block_inner,water_wall_contact); + fluid_boundary_indicator(water_block_inner, water_wall_contact); InteractionDynamicsCK - transport_correction_ck(water_block_inner, water_wall_contact); + transport_correction_ck(water_block_inner, water_wall_contact); ReduceDynamicsCK fluid_advection_time_step(water_body, U_f); ReduceDynamicsCK fluid_acoustic_time_step(water_body); /** Computing viscous acceleration with wall. */ InteractionDynamicsCK - fluid_viscous_force(water_block_inner, water_wall_contact); + fluid_viscous_force(water_block_inner, water_wall_contact); //---------------------------------------------------------------------- // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- @@ -228,9 +228,8 @@ int main(int ac, char *av[]) RestartIO restart_io(sph_system); - - RegressionTestDynamicTimeWarping> write_horizontal_velocity("Velocity", horizontal_observer_contact); - RegressionTestDynamicTimeWarping> write_vertical_velocity("Velocity", vertical_observer_contact); + RegressionTestDynamicTimeWarping> write_horizontal_velocity("Velocity", horizontal_observer_contact); + RegressionTestDynamicTimeWarping> write_vertical_velocity("Velocity", vertical_observer_contact); //---------------------------------------------------------------------- // Prepare the simulation with cell linked list, configuration // and case specified initial condition if necessary. @@ -248,7 +247,7 @@ int main(int ac, char *av[]) wall_cell_linked_list.exec(); water_block_update_complex_relation.exec(); horizontal_observer_contact_relation.exec(); - vertical_observer_contact_relation.exec(); + vertical_observer_contact_relation.exec(); solid_initial_condition.exec(); fluid_linear_correction_matrix.exec(); //---------------------------------------------------------------------- @@ -292,7 +291,7 @@ int main(int ac, char *av[]) fluid_linear_correction_matrix.exec(); fluid_boundary_indicator.exec(); transport_correction_ck.exec(); - + Real advection_dt = fluid_advection_time_step.exec(); interval_computing_time_step += TickCount::now() - time_instance; @@ -302,7 +301,7 @@ int main(int ac, char *av[]) while (relaxation_time < advection_dt) { /** inner loop for dual-time criteria time-stepping. */ - acoustic_dt = SMIN(fluid_acoustic_time_step.exec(),advection_dt); + acoustic_dt = SMIN(fluid_acoustic_time_step.exec(), advection_dt); fluid_acoustic_step_1st_half.exec(acoustic_dt); fluid_acoustic_step_2nd_half.exec(acoustic_dt); relaxation_time += acoustic_dt; @@ -330,8 +329,8 @@ int main(int ac, char *av[]) { particle_sort.exec(); } - water_cell_linked_list.exec(); - water_block_update_complex_relation.exec(); + water_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); interval_updating_configuration += TickCount::now() - time_instance; } diff --git a/tests/2d_examples/test_2d_collision/collision.cpp b/tests/2d_examples/test_2d_collision/collision.cpp index c0ecd7561c..49c7158047 100644 --- a/tests/2d_examples/test_2d_collision/collision.cpp +++ b/tests/2d_examples/test_2d_collision/collision.cpp @@ -200,7 +200,7 @@ int main(int ac, char *av[]) InteractionWithUpdate damping_ball_compute_solid_contact_forces(damping_ball_contact); /** Damping for one ball */ DampingWithRandomChoice>> - damping(0.5, InteractArgs(damping_ball_inner, "Velocity", physical_viscosity)); + damping(0.5, DynamicsArgs(damping_ball_inner, "Velocity", physical_viscosity)); ReduceDynamics free_ball_get_time_step_size(free_ball); ReduceDynamics damping_ball_get_time_step_size(damping_ball); diff --git a/tests/2d_examples/test_2d_eulerian_flow_around_cylinder_LG/2d_eulerian_flow_around_cylinder_LG.cpp b/tests/2d_examples/test_2d_eulerian_flow_around_cylinder_LG/2d_eulerian_flow_around_cylinder_LG.cpp index f1be223041..3de0726985 100644 --- a/tests/2d_examples/test_2d_eulerian_flow_around_cylinder_LG/2d_eulerian_flow_around_cylinder_LG.cpp +++ b/tests/2d_examples/test_2d_eulerian_flow_around_cylinder_LG/2d_eulerian_flow_around_cylinder_LG.cpp @@ -69,7 +69,7 @@ class FarFieldBoundary : public fluid_dynamics::NonReflectiveBoundaryCorrection sound_speed_ = c_f; vel_farfield_ = Vecd(U_f, 0.0); }; - virtual ~FarFieldBoundary(){}; + virtual ~FarFieldBoundary() {}; }; //---------------------------------------------------------------------- // Main program starts here. @@ -137,7 +137,7 @@ int main(int ac, char *av[]) ReloadParticleIO write_real_body_particle_reload_files({&cylinder, &water_block}); RelaxationStepLevelSetCorrectionInner relaxation_step_inner(cylinder_inner); RelaxationStepLevelSetCorrectionComplex relaxation_step_complex( - InteractArgs(water_block_inner, std::string("OuterBoundary")), water_block_contact); + DynamicsArgs(water_block_inner, std::string("OuterBoundary")), water_block_contact); //---------------------------------------------------------------------- // Particle relaxation starts here. //---------------------------------------------------------------------- diff --git a/tests/2d_examples/test_2d_free_stream_around_cylinder_mr/mr_free_stream_around_cylinder.cpp b/tests/2d_examples/test_2d_free_stream_around_cylinder_mr/mr_free_stream_around_cylinder.cpp index 1e48a80b6a..9c2aa5cca9 100644 --- a/tests/2d_examples/test_2d_free_stream_around_cylinder_mr/mr_free_stream_around_cylinder.cpp +++ b/tests/2d_examples/test_2d_free_stream_around_cylinder_mr/mr_free_stream_around_cylinder.cpp @@ -79,7 +79,7 @@ int main(int ac, char *av[]) /** A Physics relaxation step. */ RelaxationStepLevelSetCorrectionInner relaxation_step_inner(cylinder_inner); RelaxationStepLevelSetCorrectionComplex relaxation_step_complex( - InteractArgs(water_block_inner, std::string("OuterBoundary")), water_contact); + DynamicsArgs(water_block_inner, std::string("OuterBoundary")), water_contact); SimpleDynamics update_smoothing_length_ratio(water_block, refinement_region); //---------------------------------------------------------------------- // Particle relaxation starts here. diff --git a/tests/2d_examples/test_2d_hydrostatic_fluid_shell/test_2d_hydrostatic_fluid_shell.cpp b/tests/2d_examples/test_2d_hydrostatic_fluid_shell/test_2d_hydrostatic_fluid_shell.cpp index 1fabe8fcee..0129ad3cd0 100644 --- a/tests/2d_examples/test_2d_hydrostatic_fluid_shell/test_2d_hydrostatic_fluid_shell.cpp +++ b/tests/2d_examples/test_2d_hydrostatic_fluid_shell/test_2d_hydrostatic_fluid_shell.cpp @@ -34,7 +34,7 @@ class ParticleGenerator : public ParticleGenerat explicit ParticleGenerator(SPHBody &sph_body, SurfaceParticles &surface_particles, Real DH, Real DL, Real particle_spacing_gate) : ParticleGenerator(sph_body, surface_particles), - DH(DH), DL(DL), particle_spacing_gate(particle_spacing_gate){}; + DH(DH), DL(DL), particle_spacing_gate(particle_spacing_gate) {}; void prepareGeometricData() override { const auto particle_number_wall = int(DH / particle_spacing_gate); @@ -68,7 +68,7 @@ class ParticleGenerator : public ParticleGenerator(sph_body, surface_particles), - DL(DL), BW(BW), particle_spacing_gate(particle_spacing_gate), Gate_thickness(Gate_thickness){}; + DL(DL), BW(BW), particle_spacing_gate(particle_spacing_gate), Gate_thickness(Gate_thickness) {}; void prepareGeometricData() override { const auto particle_number_gate = int((DL + 2 * BW) / particle_spacing_gate); @@ -261,7 +261,7 @@ void hydrostatic_fsi(const Real particle_spacing_gate, const Real particle_spaci /** Compute time step size with considering sound wave speed. */ ReduceDynamics get_fluid_time_step_size(water_block); DampingWithRandomChoice>> - fluid_damping(0.2, InteractArgs(water_block_inner, "Velocity", mu_f), InteractArgs(water_block_contact, "Velocity", mu_f)); + fluid_damping(0.2, DynamicsArgs(water_block_inner, "Velocity", mu_f), DynamicsArgs(water_block_contact, "Velocity", mu_f)); //---------------------------------------------------------------------- // Define fsi methods which are used in this case. //---------------------------------------------------------------------- diff --git a/tests/2d_examples/test_2d_hydrostatic_fsi/hydrostatic_fsi.cpp b/tests/2d_examples/test_2d_hydrostatic_fsi/hydrostatic_fsi.cpp index a0606bee0a..b0e5414c82 100644 --- a/tests/2d_examples/test_2d_hydrostatic_fsi/hydrostatic_fsi.cpp +++ b/tests/2d_examples/test_2d_hydrostatic_fsi/hydrostatic_fsi.cpp @@ -265,7 +265,7 @@ int main(int ac, char *av[]) Dynamics1Level density_relaxation(water_block_inner, water_block_contact); InteractionWithUpdate update_fluid_density(water_block_inner, water_block_contact); DampingWithRandomChoice>> - fluid_damping(0.2, InteractArgs(water_block_inner, "Velocity", mu_f), InteractArgs(water_block_contact, "Velocity", mu_f)); + fluid_damping(0.2, DynamicsArgs(water_block_inner, "Velocity", mu_f), DynamicsArgs(water_block_contact, "Velocity", mu_f)); ReduceDynamics get_fluid_advection_time_step_size(water_block, U_ref); ReduceDynamics get_fluid_time_step_size(water_block); diff --git a/tests/2d_examples/test_2d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp b/tests/2d_examples/test_2d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp index 05a119eb84..87ba4229a8 100644 --- a/tests/2d_examples/test_2d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp +++ b/tests/2d_examples/test_2d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp @@ -82,7 +82,7 @@ int main(int ac, char *av[]) Gravity gravity(Vecd(0.0, -gravity_g)); SimpleDynamics> constant_gravity(water_block, gravity); - InteractionWithUpdate corrected_configuration_fluid(InteractArgs(water_block_inner, 0.1), water_block_contact); + InteractionWithUpdate corrected_configuration_fluid(DynamicsArgs(water_block_inner, 0.1), water_block_contact); Dynamics1Level pressure_relaxation(water_block_inner, water_block_contact); Dynamics1Level density_relaxation(water_block_inner, water_block_contact); diff --git a/tests/2d_examples/test_2d_square_droplet/droplet_conservation.cpp b/tests/2d_examples/test_2d_square_droplet/droplet_conservation.cpp index 3d65d681ab..150f887ef4 100644 --- a/tests/2d_examples/test_2d_square_droplet/droplet_conservation.cpp +++ b/tests/2d_examples/test_2d_square_droplet/droplet_conservation.cpp @@ -134,9 +134,9 @@ int main(int ac, char *av[]) InteractionWithUpdate, Contact<>, Contact<>>> update_water_density_by_summation(water_inner, water_air_contact, water_wall_contact); InteractionWithUpdate> - air_transport_correction(InteractArgs(air_inner, 0.02), air_water_contact, air_wall_contact); + air_transport_correction(DynamicsArgs(air_inner, 0.02), air_water_contact, air_wall_contact); InteractionWithUpdate> - water_transport_correction(InteractArgs(water_inner, 0.02), water_air_contact, water_wall_contact); + water_transport_correction(DynamicsArgs(water_inner, 0.02), water_air_contact, water_wall_contact); InteractionWithUpdate water_viscous_force(water_inner, water_air_contact, water_wall_contact); InteractionWithUpdate air_viscous_force(air_inner, air_water_contact, air_wall_contact); diff --git a/tests/2d_examples/test_2d_standing_wave/standing_wave.cpp b/tests/2d_examples/test_2d_standing_wave/standing_wave.cpp index d5dc6bd7a0..dd410029f2 100644 --- a/tests/2d_examples/test_2d_standing_wave/standing_wave.cpp +++ b/tests/2d_examples/test_2d_standing_wave/standing_wave.cpp @@ -147,7 +147,7 @@ int main(int ac, char *av[]) Gravity gravity(Vecd(0.0, -gravity_g)); SimpleDynamics> constant_gravity(water_block, gravity); SimpleDynamics wall_boundary_normal_direction(wall_boundary); - InteractionWithUpdate corrected_configuration_fluid(InteractArgs(water_block_inner, 0.5), water_wall_contact); + InteractionWithUpdate corrected_configuration_fluid(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); Dynamics1Level fluid_pressure_relaxation_correct(water_block_inner, water_wall_contact); Dynamics1Level fluid_density_relaxation(water_block_inner, water_wall_contact); InteractionWithUpdate fluid_density_by_summation(water_block_inner, water_wall_contact); diff --git a/tests/2d_examples/test_2d_throat/throat.cpp b/tests/2d_examples/test_2d_throat/throat.cpp index 2f30591c81..49d9993e17 100644 --- a/tests/2d_examples/test_2d_throat/throat.cpp +++ b/tests/2d_examples/test_2d_throat/throat.cpp @@ -173,7 +173,7 @@ int main(int ac, char *av[]) Dynamics1Level density_relaxation(fluid_block_inner, fluid_block_contact); InteractionWithUpdate update_density_by_summation(fluid_block_inner, fluid_block_contact); InteractionSplit> implicit_viscous_damping( - InteractArgs(fluid_block_inner, "Velocity", mu_f), InteractArgs(fluid_block_contact, "Velocity", mu_f)); + DynamicsArgs(fluid_block_inner, "Velocity", mu_f), DynamicsArgs(fluid_block_contact, "Velocity", mu_f)); InteractionWithUpdate> transport_velocity_correction(fluid_block_inner, fluid_block_contact); ReduceDynamics get_fluid_advection_time_step_size(fluid_block, U_f); diff --git a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp index d15bb06855..443aa78c49 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_dambreak_ck/dambreak.cpp @@ -125,7 +125,7 @@ int main(int ac, char *av[]) StateDynamics water_advection_step_close(water_block); InteractionDynamicsCK - fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + fluid_linear_correction_matrix(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); InteractionDynamicsCK fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); InteractionDynamicsCK diff --git a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp index 06260d0f76..0b17dfbac8 100644 --- a/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp +++ b/tests/3d_examples/3d_examples_ck/test_3d_stfb_ck/stfb.cpp @@ -228,10 +228,10 @@ int main(int ac, char *av[]) ObservingAQuantityCK, ObservingAQuantityCK, StateDynamics> - structure_observer_follow_structure( + update_structure_observer_states( structure, - InteractArgs(structure_observer_contact, std::string("Velocity")), - InteractArgs(structure_observer_contact, std::string("Displacement")), + DynamicsArgs(structure_observer_contact, std::string("Velocity")), + DynamicsArgs(structure_observer_contact, std::string("Displacement")), structure_observer); //---------------------------------------------------------------------- // Define the multi-body system @@ -415,7 +415,7 @@ int main(int ac, char *av[]) if (total_time >= relax_time) { write_real_body_states.writeToFile(MainExecutionPolicy{}); - structure_observer_follow_structure.exec(); + update_structure_observer_states.exec(); write_structure_surface.writeToFile(MainExecutionPolicy{}); } TickCount t3 = TickCount::now(); diff --git a/tests/3d_examples/test_3d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp b/tests/3d_examples/test_3d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp index 9f1ea687f7..7f9509b59d 100644 --- a/tests/3d_examples/test_3d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp +++ b/tests/3d_examples/test_3d_nonlinear_wave_fsi/nonlinear_wave_fsi.cpp @@ -149,7 +149,7 @@ int main(int ac, char *av[]) SimpleDynamics structure_normal_direction(structure); InteractionWithUpdate structure_corrected_configuration(structure_inner); - InteractionWithUpdate corrected_configuration_fluid(InteractArgs(water_block_inner, 0.1), water_block_contact); + InteractionWithUpdate corrected_configuration_fluid(DynamicsArgs(water_block_inner, 0.1), water_block_contact); Dynamics1Level pressure_relaxation(water_block_inner, water_block_contact); Dynamics1Level density_relaxation(water_block_inner, water_block_contact); InteractionWithUpdate update_density_by_summation(water_block_inner, water_block_contact); diff --git a/tests/extra_source_and_tests/extra_src/for_2D_build/k-epsilon_turbulent_model.h b/tests/extra_source_and_tests/extra_src/for_2D_build/k-epsilon_turbulent_model.h index b08aac1173..0527987985 100644 --- a/tests/extra_source_and_tests/extra_src/for_2D_build/k-epsilon_turbulent_model.h +++ b/tests/extra_source_and_tests/extra_src/for_2D_build/k-epsilon_turbulent_model.h @@ -22,8 +22,8 @@ * ------------------------------------------------------------------------*/ /** * @file k-epsilon_turbulent_model.h - * @brief - * @details + * @brief + * @details * @author Xiangyu Hu */ @@ -41,7 +41,7 @@ class BaseTurbuClosureCoeff { public: explicit BaseTurbuClosureCoeff(); - virtual ~BaseTurbuClosureCoeff(){}; + virtual ~BaseTurbuClosureCoeff() {}; protected: Real Karman_; @@ -62,8 +62,8 @@ class BaseTurbuClosureCoeff class WallFunction : public BaseTurbuClosureCoeff { public: - explicit WallFunction(){}; - virtual ~WallFunction(){}; + explicit WallFunction() {}; + virtual ~WallFunction() {}; Real get_dimensionless_velocity(Real y_star, Real time); Real get_near_wall_velocity_gradient_magnitude(Real y_star, Real vel_fric_mag, Real denominator_log_law, Real dynamic_viscosity); @@ -85,7 +85,7 @@ class GetVelocityGradient public: template explicit GetVelocityGradient(BaseRelationType &base_relation); - virtual ~GetVelocityGradient(){}; + virtual ~GetVelocityGradient() {}; protected: Real *Vol_; @@ -103,7 +103,7 @@ class GetVelocityGradient> : public GetVelocityGradient> : public InteractionWithWall public: template explicit BaseTurbulentModel(BaseRelationType &base_relation); - virtual ~BaseTurbulentModel(){}; + virtual ~BaseTurbulentModel() {}; protected: Matd *turbu_strain_rate_; @@ -151,14 +151,14 @@ class BaseTurbulentModel }; //=================================================================================================// /** - * @class K_TurbulentModelInner - * @brief K_TurbulentModelInner - */ + * @class K_TurbulentModelInner + * @brief K_TurbulentModelInner + */ class K_TurbulentModelInner : public BaseTurbulentModel { public: explicit K_TurbulentModelInner(BaseInnerRelation &inner_relation, const StdVec &initial_values, int is_extr_visc_dissipa, bool is_STL); - virtual ~K_TurbulentModelInner(){}; + virtual ~K_TurbulentModelInner() {}; inline void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); @@ -182,14 +182,14 @@ class K_TurbulentModelInner : public BaseTurbulentModel }; //=================================================================================================// /** - * @class E_TurbulentModelInner - * @brief E_TurbulentModelInner - */ + * @class E_TurbulentModelInner + * @brief E_TurbulentModelInner + */ class E_TurbulentModelInner : public BaseTurbulentModel { public: explicit E_TurbulentModelInner(BaseInnerRelation &inner_relation, bool is_STL); - virtual ~E_TurbulentModelInner(){}; + virtual ~E_TurbulentModelInner() {}; inline void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); @@ -220,7 +220,7 @@ class TKEnergyForce public: template explicit TKEnergyForce(BaseRelationType &base_relation); - virtual ~TKEnergyForce(){}; + virtual ~TKEnergyForce() {}; protected: Vecd *force_; @@ -236,7 +236,7 @@ class TKEnergyForce> : public TKEnergyForce { public: explicit TKEnergyForce(BaseInnerRelation &inner_relation); - virtual ~TKEnergyForce(){}; + virtual ~TKEnergyForce() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -249,7 +249,7 @@ class TKEnergyForce> : public TKEnergyForce { public: explicit TKEnergyForce(BaseContactRelation &contact_relation); - virtual ~TKEnergyForce(){}; + virtual ~TKEnergyForce() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -271,7 +271,7 @@ class TurbuViscousForce : public ViscousForce explicit TurbuViscousForce(BaseRelationType &base_relation); - virtual ~TurbuViscousForce(){}; + virtual ~TurbuViscousForce() {}; protected: Real *turbu_k_; @@ -291,7 +291,7 @@ class TurbuViscousForce> : public TurbuViscousForce { public: explicit TurbuViscousForce(BaseInnerRelation &inner_relation); - virtual ~TurbuViscousForce(){}; + virtual ~TurbuViscousForce() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -306,7 +306,7 @@ class TurbuViscousForce> : public BaseTurbuViscousForceWithWall, p { public: explicit TurbuViscousForce(BaseContactRelation &wall_contact_relation); - virtual ~TurbuViscousForce(){}; + virtual ~TurbuViscousForce() {}; void interaction(size_t index_i, Real dt = 0.0); protected: @@ -321,7 +321,7 @@ class TurbulentEddyViscosity : public LocalDynamics, public BaseTurbuClosureCoef { public: explicit TurbulentEddyViscosity(SPHBody &sph_body); - virtual ~TurbulentEddyViscosity(){}; + virtual ~TurbulentEddyViscosity() {}; void update(size_t index_i, Real dt = 0.0); @@ -336,14 +336,14 @@ class TurbulentEddyViscosity : public LocalDynamics, public BaseTurbuClosureCoef }; //=================================================================================================// /** - * @class TurbulentAdvectionTimeStepSize - * @brief Computing the turbulent advection time step size - */ + * @class TurbulentAdvectionTimeStepSize + * @brief Computing the turbulent advection time step size + */ class TurbulentAdvectionTimeStepSize : public LocalDynamicsReduce { public: explicit TurbulentAdvectionTimeStepSize(SPHBody &sph_body, Real U_max, Real advectionCFL = 0.25); - virtual ~TurbulentAdvectionTimeStepSize(){}; + virtual ~TurbulentAdvectionTimeStepSize() {}; Real reduce(size_t index_i, Real dt = 0.0); virtual Real outputResult(Real reduced_value) override; @@ -357,17 +357,17 @@ class TurbulentAdvectionTimeStepSize : public LocalDynamicsReduce }; //=================================================================================================// /** - * @class InflowTurbulentCondition - * @brief Inflow boundary condition which imposes directly to a given velocity profile. - * TargetVelocity gives the velocity profile along the inflow direction, - * i.e. x direction in local frame. - */ + * @class InflowTurbulentCondition + * @brief Inflow boundary condition which imposes directly to a given velocity profile. + * TargetVelocity gives the velocity profile along the inflow direction, + * i.e. x direction in local frame. + */ class InflowTurbulentCondition : public BaseFlowBoundaryCondition, public BaseTurbuClosureCoeff { public: explicit InflowTurbulentCondition(BodyPartByCell &body_part, Real CharacteristicLength, Real relaxation_rate, int type_turbu_inlet); - virtual ~InflowTurbulentCondition(){}; + virtual ~InflowTurbulentCondition() {}; void update(size_t index_i, Real dt = 0.0); protected: @@ -387,7 +387,7 @@ class JudgeIsNearWall : public LocalDynamics, public DataDelegateContact, public public: JudgeIsNearWall(BaseInnerRelation &inner_relation, BaseContactRelation &contact_relation); - virtual ~JudgeIsNearWall(){}; + virtual ~JudgeIsNearWall() {}; inline void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); @@ -412,7 +412,7 @@ class StandardWallFunctionCorrection : public LocalDynamics, public DataDelegate public: StandardWallFunctionCorrection(BaseInnerRelation &inner_relation, BaseContactRelation &contact_relation, Real y_p_constant); - virtual ~StandardWallFunctionCorrection(){}; + virtual ~StandardWallFunctionCorrection() {}; inline void interaction(size_t index_i, Real dt = 0.0); protected: @@ -446,7 +446,7 @@ class ConstrainNormalVelocityInRegionP : public LocalDynamics { public: explicit ConstrainNormalVelocityInRegionP(SPHBody &sph_body); - virtual ~ConstrainNormalVelocityInRegionP(){}; + virtual ~ConstrainNormalVelocityInRegionP() {}; void update(size_t index_i, Real dt = 0.0); @@ -466,7 +466,7 @@ class TurbulentLinearGradientCorrectionMatrix public: template explicit TurbulentLinearGradientCorrectionMatrix(BaseRelationType &base_relation); - virtual ~TurbulentLinearGradientCorrectionMatrix(){}; + virtual ~TurbulentLinearGradientCorrectionMatrix() {}; protected: Real *Vol_; @@ -482,11 +482,11 @@ class TurbulentLinearGradientCorrectionMatrix> public: explicit TurbulentLinearGradientCorrectionMatrix(BaseInnerRelation &inner_relation, Real alpha = Real(0)) - : TurbulentLinearGradientCorrectionMatrix(inner_relation), turbu_alpha_(alpha){}; + : TurbulentLinearGradientCorrectionMatrix(inner_relation), turbu_alpha_(alpha) {}; template - explicit TurbulentLinearGradientCorrectionMatrix(InteractArgs parameters) - : TurbulentLinearGradientCorrectionMatrix(parameters.body_relation_, std::get<0>(parameters.others_)){}; - virtual ~TurbulentLinearGradientCorrectionMatrix(){}; + explicit TurbulentLinearGradientCorrectionMatrix(DynamicsArgs parameters) + : TurbulentLinearGradientCorrectionMatrix(parameters.identifier_, std::get<0>(parameters.others_)){}; + virtual ~TurbulentLinearGradientCorrectionMatrix() {}; void interaction(size_t index_i, Real dt = 0.0); void update(size_t index_i, Real dt = 0.0); }; @@ -505,7 +505,7 @@ class ModifiedTruncatedLinear : public Limiter public: ModifiedTruncatedLinear(Real ref, Real slope = 1000.0) - : Limiter(), ref_(ref), slope_(slope){}; + : Limiter(), ref_(ref), slope_(slope) {}; Real operator()(Real measure) { Real measure_scale = measure * ref_; diff --git a/tests/extra_source_and_tests/test_2d_lid_driven_cavity/lid_driven_cavity.cpp b/tests/extra_source_and_tests/test_2d_lid_driven_cavity/lid_driven_cavity.cpp index 1fa59fc863..4669b16234 100644 --- a/tests/extra_source_and_tests/test_2d_lid_driven_cavity/lid_driven_cavity.cpp +++ b/tests/extra_source_and_tests/test_2d_lid_driven_cavity/lid_driven_cavity.cpp @@ -88,7 +88,7 @@ class ChangingBoundaryVelocity : public fluid_dynamics::FluidInitialCondition { public: ChangingBoundaryVelocity(SPHBody &sph_body) - : fluid_dynamics::FluidInitialCondition(sph_body){}; + : fluid_dynamics::FluidInitialCondition(sph_body) {}; void update(size_t index_i, Real dt) { if (vel_[index_i][0] < 1) @@ -152,7 +152,7 @@ int main(int ac, char *av[]) // Define the numerical methods used in the simulation SimpleDynamics wall_boundary_normal_direction(no_slip_boundary); - InteractionWithUpdate corrected_configuration_fluid(InteractArgs(fluid_inner, 0.3), fluid_all_walls); + InteractionWithUpdate corrected_configuration_fluid(DynamicsArgs(fluid_inner, 0.3), fluid_all_walls); Dynamics1Level> pressure_relaxation(fluid_inner, fluid_all_walls); Dynamics1Level> density_relaxation(fluid_inner, fluid_all_walls); InteractionWithUpdate update_density_by_summation(fluid_inner, fluid_all_walls); diff --git a/tests/tests_sycl/2d_examples/test_2d_dambreak_sycl/dambreak_sycl.cpp b/tests/tests_sycl/2d_examples/test_2d_dambreak_sycl/dambreak_sycl.cpp index 0403fcb30d..77f57749b5 100644 --- a/tests/tests_sycl/2d_examples/test_2d_dambreak_sycl/dambreak_sycl.cpp +++ b/tests/tests_sycl/2d_examples/test_2d_dambreak_sycl/dambreak_sycl.cpp @@ -106,7 +106,7 @@ int main(int ac, char *av[]) StateDynamics water_advection_step_close(water_block); InteractionDynamicsCK - fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + fluid_linear_correction_matrix(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); InteractionDynamicsCK fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); InteractionDynamicsCK @@ -114,7 +114,7 @@ int main(int ac, char *av[]) InteractionDynamicsCK fluid_density_regularization(water_block_inner, water_wall_contact); InteractionDynamicsCK - fluid_boundary_indicator(water_block_inner,water_wall_contact); + fluid_boundary_indicator(water_block_inner, water_wall_contact); ReduceDynamicsCK fluid_advection_time_step(water_block, U_ref); ReduceDynamicsCK fluid_acoustic_time_step(water_block); diff --git a/tests/tests_sycl/2d_examples/test_2d_lid_driven_cavity_corrected_sycl/lid_driven_cavity_sycl.cpp b/tests/tests_sycl/2d_examples/test_2d_lid_driven_cavity_corrected_sycl/lid_driven_cavity_sycl.cpp index fc6c47717a..b0a2590ac9 100644 --- a/tests/tests_sycl/2d_examples/test_2d_lid_driven_cavity_corrected_sycl/lid_driven_cavity_sycl.cpp +++ b/tests/tests_sycl/2d_examples/test_2d_lid_driven_cavity_corrected_sycl/lid_driven_cavity_sycl.cpp @@ -5,7 +5,7 @@ * @author Bo Zhang, Xiangyu Hu */ #include "sphinxsys_sycl.h" // SPHinXsys Library. -using namespace SPH; // Namespace cite here. +using namespace SPH; // Namespace cite here. //---------------------------------------------------------------------- // Basic geometry parameters and numerical setup. //---------------------------------------------------------------------- @@ -137,7 +137,7 @@ int main(int ac, char *av[]) // Creating body, materials and particles. //---------------------------------------------------------------------- FluidBody water_body(sph_system, makeShared("WaterBody")); - water_body.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); + water_body.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); water_body.generateParticles(); SolidBody wall_boundary(sph_system, makeShared("Wall")); @@ -154,7 +154,7 @@ int main(int ac, char *av[]) // Define body relation map. // The contact map gives the topological connections between the bodies. // Basically the the range of bodies to build neighbor particle lists. - //---------------------------------------------------------------------- + //---------------------------------------------------------------------- Relation> water_block_inner(water_body); Relation> water_wall_contact(water_body, {&wall_boundary}); Relation> horizontal_observer_contact(horizontal_observer, {&water_body}); @@ -185,7 +185,7 @@ int main(int ac, char *av[]) //---------------------------------------------------------------------- StateDynamics wall_boundary_normal_direction(wall_boundary); // run on CPU - /** Time step size with considering sound wave speed. */ + /** Time step size with considering sound wave speed. */ StateDynamics water_advection_step_setup(water_body); StateDynamics water_advection_step_close(water_body); @@ -193,29 +193,29 @@ int main(int ac, char *av[]) SimpleDynamics solid_initial_condition(wall_boundary); /** Kernel correction matrix and transport velocity formulation. */ InteractionDynamicsCK - fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + fluid_linear_correction_matrix(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); /** Evaluation of density by summation approach. */ InteractionDynamicsCK - fluid_density_regularization(water_block_inner, water_wall_contact); /** Pressure and density relaxation algorithm by using Verlet time stepping. */ + fluid_density_regularization(water_block_inner, water_wall_contact); /** Pressure and density relaxation algorithm by using Verlet time stepping. */ InteractionDynamicsCK fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); InteractionDynamicsCK fluid_acoustic_step_2nd_half(water_block_inner, water_wall_contact); - /** + /** * Free Surface Indicator and BulkParticles for Transport Velocity Correction are not required for this simulation. - * They are included here solely for testing and verification purposes, + * They are included here solely for testing and verification purposes, * and do not contribute to the primary objectives of the current case. */ InteractionDynamicsCK - fluid_boundary_indicator(water_block_inner,water_wall_contact); + fluid_boundary_indicator(water_block_inner, water_wall_contact); InteractionDynamicsCK - transport_correction_ck(water_block_inner, water_wall_contact); - + transport_correction_ck(water_block_inner, water_wall_contact); + ReduceDynamicsCK fluid_advection_time_step(water_body, U_f); ReduceDynamicsCK fluid_acoustic_time_step(water_body); /** Computing viscous acceleration with wall. */ InteractionDynamicsCK - fluid_viscous_force(water_block_inner, water_wall_contact); + fluid_viscous_force(water_block_inner, water_wall_contact); //---------------------------------------------------------------------- // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- @@ -228,8 +228,8 @@ int main(int ac, char *av[]) RestartIO restart_io(sph_system); - RegressionTestDynamicTimeWarping> write_horizontal_velocity("Velocity", horizontal_observer_contact); - RegressionTestDynamicTimeWarping> write_vertical_velocity("Velocity", vertical_observer_contact); + RegressionTestDynamicTimeWarping> write_horizontal_velocity("Velocity", horizontal_observer_contact); + RegressionTestDynamicTimeWarping> write_vertical_velocity("Velocity", vertical_observer_contact); //---------------------------------------------------------------------- // Prepare the simulation with cell linked list, configuration // and case specified initial condition if necessary. @@ -285,14 +285,14 @@ int main(int ac, char *av[]) /** outer loop for dual-time criteria time-stepping. */ time_instance = TickCount::now(); - fluid_density_regularization.exec(); + fluid_density_regularization.exec(); water_advection_step_setup.exec(); fluid_viscous_force.exec(); fluid_linear_correction_matrix.exec(); fluid_boundary_indicator.exec(); transport_correction_ck.exec(); - + Real advection_dt = fluid_advection_time_step.exec(); interval_computing_time_step += TickCount::now() - time_instance; @@ -302,7 +302,7 @@ int main(int ac, char *av[]) while (relaxation_time < advection_dt) { /** inner loop for dual-time criteria time-stepping. */ - acoustic_dt = SMIN(fluid_acoustic_time_step.exec(),advection_dt); + acoustic_dt = SMIN(fluid_acoustic_time_step.exec(), advection_dt); fluid_acoustic_step_1st_half.exec(acoustic_dt); fluid_acoustic_step_2nd_half.exec(acoustic_dt); relaxation_time += acoustic_dt; @@ -330,8 +330,8 @@ int main(int ac, char *av[]) { particle_sort.exec(); } - water_cell_linked_list.exec(); - water_block_update_complex_relation.exec(); + water_cell_linked_list.exec(); + water_block_update_complex_relation.exec(); interval_updating_configuration += TickCount::now() - time_instance; } diff --git a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp index 5270194aec..3dad52e649 100644 --- a/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp +++ b/tests/tests_sycl/3d_examples/test_3d_dambreak_sycl/dambreak.cpp @@ -125,7 +125,7 @@ int main(int ac, char *av[]) StateDynamics water_advection_step_close(water_block); InteractionDynamicsCK - fluid_linear_correction_matrix(InteractArgs(water_block_inner, 0.5), water_wall_contact); + fluid_linear_correction_matrix(DynamicsArgs(water_block_inner, 0.5), water_wall_contact); InteractionDynamicsCK fluid_acoustic_step_1st_half(water_block_inner, water_wall_contact); InteractionDynamicsCK From cd345d30e33ded71ec14283d54327c4169351a54 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Tue, 11 Feb 2025 08:12:32 +0000 Subject: [PATCH 25/33] add to sycl case --- .../3d_examples/test_3d_stfb_sycl/stfb.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp index 045564f72a..2c2afad1c0 100644 --- a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp @@ -148,6 +148,10 @@ int main(int ac, char *av[]) ObserverBody observer(sph_system, "Observer"); observer.defineAdaptationRatios(1.15, 2.0); observer.generateParticles(StdVec{obs}); + + TriangleMeshShapeBrick structure_mesh(halfsize_structure, 1, structure_pos); + ObserverBody structure_observer(sph_system, "StructureObserver"); + structure_observer.generateParticles(structure_mesh); //---------------------------------------------------------------------- // Creating body parts. //---------------------------------------------------------------------- @@ -165,6 +169,7 @@ int main(int ac, char *av[]) Relation> water_block_contact(water_block, {&wall_boundary, &structure}); Relation> structure_contact(structure, {&water_block}); Relation> observer_contact(observer, {&structure}); + Relation> structure_observer_contact(structure_observer, {&structure}); //---------------------------------------------------------------------- // Define the main execution policy for this case. //---------------------------------------------------------------------- @@ -214,6 +219,17 @@ int main(int ac, char *av[]) ReduceDynamicsCK fluid_advection_time_step(water_block, U_f); ReduceDynamicsCK fluid_acoustic_time_step(water_block); + + ArbitraryDynamicsSequence< + StateDynamics, + ObservingAQuantityCK, + ObservingAQuantityCK, + StateDynamics> + update_structure_observer_states( + structure, + DynamicsArgs(structure_observer_contact, std::string("Velocity")), + DynamicsArgs(structure_observer_contact, std::string("Displacement")), + structure_observer); //---------------------------------------------------------------------- // Define the multi-body system //---------------------------------------------------------------------- @@ -286,6 +302,8 @@ int main(int ac, char *av[]) // Define the methods for I/O operations and observations of the simulation. //---------------------------------------------------------------------- BodyStatesRecordingToVtp write_real_body_states(sph_system); + BodyStatesRecordingToTriangleMeshVtp write_structure_surface(structure_observer, structure_mesh); + write_structure_surface.addToWrite(structure_observer, "Velocity"); RegressionTestDynamicTimeWarping>> wave_gauge(wave_probe_buffer, "FreeSurfaceHeight"); @@ -306,6 +324,7 @@ int main(int ac, char *av[]) water_block_update_complex_relation.exec(); structure_update_contact_relation.exec(); observer_update_contact_relation.exec(); + structure_observer_update_contact_relation.exec(); //---------------------------------------------------------------------- // Basic control parameters for time stepping. //---------------------------------------------------------------------- @@ -325,6 +344,7 @@ int main(int ac, char *av[]) write_real_body_states.writeToFile(MainExecutionPolicy{}); write_structure_position.writeToFile(number_of_iterations); wave_gauge.writeToFile(number_of_iterations); + write_structure_surface.writeToFile(MainExecutionPolicy{}); //---------------------------------------------------------------------- // Main loop of time stepping starts here. //---------------------------------------------------------------------- @@ -390,7 +410,11 @@ int main(int ac, char *av[]) TickCount t2 = TickCount::now(); if (total_time >= relax_time) + { write_real_body_states.writeToFile(MainExecutionPolicy{}); + update_structure_observer_states.exec(); + write_structure_surface.writeToFile(MainExecutionPolicy{}); + } TickCount t3 = TickCount::now(); interval += t3 - t2; } From 7ae7f239529fcaaae8adedaa6fcf4468a0492def Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Tue, 11 Feb 2025 09:22:21 +0000 Subject: [PATCH 26/33] all compiled --- tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp index 2c2afad1c0..08024538c4 100644 --- a/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp +++ b/tests/tests_sycl/3d_examples/test_3d_stfb_sycl/stfb.cpp @@ -195,6 +195,8 @@ int main(int ac, char *av[]) structure_update_contact_relation(structure_contact); UpdateRelation> observer_update_contact_relation(observer_contact); + UpdateRelation> + structure_observer_update_contact_relation(structure_observer_contact); ParticleSortCK particle_sort(water_block); Gravity gravity(Vec3d(0.0, 0.0, -gravity_g)); From f82d281b0c7a20a6db26be99e7a1616be2d19238 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Tue, 11 Feb 2025 21:13:41 +0000 Subject: [PATCH 27/33] use discrete variable for position in base particles --- src/shared/io_system/io_base.cpp | 18 ++-------- src/shared/io_system/io_base.h | 3 +- src/shared/particles/base_particles.cpp | 6 ++-- src/shared/particles/base_particles.h | 9 +++-- src/shared/particles/base_particles.hpp | 46 +++++++++++++++++++------ 5 files changed, 48 insertions(+), 34 deletions(-) diff --git a/src/shared/io_system/io_base.cpp b/src/shared/io_system/io_base.cpp index 4fcfd87af5..83ee33e9f6 100644 --- a/src/shared/io_system/io_base.cpp +++ b/src/shared/io_system/io_base.cpp @@ -25,25 +25,11 @@ bool BaseIO::isBodyIncluded(const SPHBodyVector &bodies, SPHBody *sph_body) //=============================================================================================// BodyStatesRecording::BodyStatesRecording(SPHSystem &sph_system) : BaseIO(sph_system), bodies_(sph_system.getRealBodies()), - state_recording_(sph_system_.StateRecording()) -{ - for (size_t i = 0; i < bodies_.size(); ++i) - { - BaseParticles &particles = bodies_[i]->getBaseParticles(); - dv_all_pos_.push_back(particles.getVariableByName("Position")); - } -} + state_recording_(sph_system_.StateRecording()) {} //=============================================================================================// BodyStatesRecording::BodyStatesRecording(SPHBody &body) : BaseIO(body.getSPHSystem()), bodies_({&body}), - state_recording_(sph_system_.StateRecording()) -{ - for (size_t i = 0; i < bodies_.size(); ++i) - { - BaseParticles &particles = bodies_[i]->getBaseParticles(); - dv_all_pos_.push_back(particles.getVariableByName("Position")); - } -} + state_recording_(sph_system_.StateRecording()) {} //=============================================================================================// void BodyStatesRecording::writeToFile() { diff --git a/src/shared/io_system/io_base.h b/src/shared/io_system/io_base.h index 9dcf016fa8..d2534df014 100644 --- a/src/shared/io_system/io_base.h +++ b/src/shared/io_system/io_base.h @@ -112,8 +112,8 @@ class BodyStatesRecording : public BaseIO { if (bodies_[i]->checkNewlyUpdated()) { - dv_all_pos_[i]->prepareForOutput(ex_policy); BaseParticles &base_particles = bodies_[i]->getBaseParticles(); + base_particles.dvParticlePosition()->prepareForOutput(ex_policy); prepare_variable_to_write_(base_particles.VariablesToWrite(), ex_policy); } } @@ -166,7 +166,6 @@ class BodyStatesRecording : public BaseIO StdVec *> derived_variables_; OperationOnDataAssemble prepare_variable_to_write_; bool state_recording_; - StdVec *> dv_all_pos_; virtual void writeWithFileName(const std::string &sequence) = 0; private: diff --git a/src/shared/particles/base_particles.cpp b/src/shared/particles/base_particles.cpp index 832266b500..e75f082d92 100644 --- a/src/shared/particles/base_particles.cpp +++ b/src/shared/particles/base_particles.cpp @@ -12,7 +12,7 @@ namespace SPH BaseParticles::BaseParticles(SPHBody &sph_body, BaseMaterial *base_material) : sv_total_real_particles_(nullptr), real_particles_bound_(0), particles_bound_(0), original_id_(nullptr), sorted_id_(nullptr), - pos_(nullptr), Vol_(nullptr), rho_(nullptr), mass_(nullptr), + dv_pos_(nullptr), Vol_(nullptr), rho_(nullptr), mass_(nullptr), sph_body_(sph_body), body_name_(sph_body.getName()), base_material_(*base_material), restart_xml_parser_("xml_restart", "particles"), @@ -45,7 +45,7 @@ void BaseParticles::initializeBasicParticleVariables() //=================================================================================================// void BaseParticles::registerPositionAndVolumetricMeasure(StdLargeVec &pos, StdLargeVec &Vol) { - pos_ = registerStateVariableFrom("Position", pos); + dv_pos_ = registerStateVariableOnlyFrom("Position", pos); Vol_ = registerStateVariableFrom("VolumetricMeasure", Vol); addVariableToReload("Position"); addVariableToReload("VolumetricMeasure"); @@ -53,7 +53,7 @@ void BaseParticles::registerPositionAndVolumetricMeasure(StdLargeVec &pos, //=================================================================================================// void BaseParticles::registerPositionAndVolumetricMeasureFromReload() { - pos_ = registerStateVariableFromReload("Position"); + dv_pos_ = registerStateVariableOnlyFromReload("Position"); Vol_ = registerStateVariableFromReload("VolumetricMeasure"); } //=================================================================================================// diff --git a/src/shared/particles/base_particles.h b/src/shared/particles/base_particles.h index 3b3f24ee53..250b722d9d 100644 --- a/src/shared/particles/base_particles.h +++ b/src/shared/particles/base_particles.h @@ -166,6 +166,10 @@ class BaseParticles DiscreteVariable *registerStateVariableOnly(const std::string &name, Args &&...args); template DiscreteVariable *registerStateVariableOnlyFrom(const std::string &new_name, const std::string &old_name); + template + DiscreteVariable *registerStateVariableOnlyFrom(const std::string &name, const StdLargeVec &geometric_data); + template + DiscreteVariable *registerStateVariableOnlyFromReload(const std::string &name); template SingularVariable *addUniqueSingularVariableOnly(const std::string &name, DataType initial_value = ZeroData::value); @@ -225,13 +229,14 @@ class BaseParticles //---------------------------------------------------------------------- void registerPositionAndVolumetricMeasure(StdLargeVec &pos, StdLargeVec &Vol); void registerPositionAndVolumetricMeasureFromReload(); - Vecd *ParticlePositions() { return pos_; } + DiscreteVariable *dvParticlePosition() { return dv_pos_; } + Vecd *ParticlePositions() { return dv_pos_->Data(); } Real *VolumetricMeasures() { return Vol_; } virtual Real ParticleVolume(size_t index) { return Vol_[index]; } virtual Real ParticleSpacing(size_t index) { return std::pow(Vol_[index], 1.0 / Real(Dimensions)); } protected: - Vecd *pos_; /**< Position */ + DiscreteVariable *dv_pos_; /**< Discrete variable position */ Real *Vol_; /**< Volumetric measure, also area and length of surface and linear particle */ Real *rho_; /**< Density as a fundamental property of phyiscal matter */ Real *mass_; /**< Mass as another fundamental property of physical matter */ diff --git a/src/shared/particles/base_particles.hpp b/src/shared/particles/base_particles.hpp index 1e3f94700d..ececc4a3ec 100644 --- a/src/shared/particles/base_particles.hpp +++ b/src/shared/particles/base_particles.hpp @@ -164,6 +164,34 @@ DataType *BaseParticles::registerStateVariableFrom( } //=================================================================================================// template +DataType *BaseParticles::registerStateVariableFrom( + const std::string &name, const StdLargeVec &geometric_data) +{ + DataType *data_field = registerStateVariable(name); + + for (size_t i = 0; i != geometric_data.size(); ++i) + { + data_field[i] = geometric_data[i]; + } + return data_field; +} +//=================================================================================================// +template +DataType *BaseParticles::registerStateVariableFromReload(const std::string &name) +{ + DataType *data_field = registerStateVariable(name); + + size_t index = 0; + for (auto child = reload_xml_parser_.first_element_->FirstChildElement(); child; child = child->NextSiblingElement()) + { + reload_xml_parser_.queryAttributeValue(child, name, data_field[index]); + index++; + } + + return data_field; +} +//=================================================================================================// +template DiscreteVariable *BaseParticles::registerStateVariableOnlyFrom( const std::string &new_name, const std::string &old_name) { @@ -182,22 +210,18 @@ DiscreteVariable *BaseParticles::registerStateVariableOnlyFrom( } //=================================================================================================// template -DataType *BaseParticles::registerStateVariableFrom( +DiscreteVariable *BaseParticles::registerStateVariableOnlyFrom( const std::string &name, const StdLargeVec &geometric_data) { - DataType *data_field = registerStateVariable(name); - - for (size_t i = 0; i != geometric_data.size(); ++i) - { - data_field[i] = geometric_data[i]; - } - return data_field; + return registerStateVariableOnly(name, [&](size_t index) + { return geometric_data[index]; }); } //=================================================================================================// template -DataType *BaseParticles::registerStateVariableFromReload(const std::string &name) +DiscreteVariable *BaseParticles::registerStateVariableOnlyFromReload(const std::string &name) { - DataType *data_field = registerStateVariable(name); + DiscreteVariable *new_variable = registerStateVariableOnly(name); + DataType *data_field = new_variable->Data(); size_t index = 0; for (auto child = reload_xml_parser_.first_element_->FirstChildElement(); child; child = child->NextSiblingElement()) @@ -206,7 +230,7 @@ DataType *BaseParticles::registerStateVariableFromReload(const std::string &name index++; } - return data_field; + return new_variable; } //=================================================================================================// template From fe1fa5c0340084e8c5c0388185c85ab6cb0ed694 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu <37415154+Xiangyu-Hu@users.noreply.github.com> Date: Wed, 12 Feb 2025 08:18:35 +0100 Subject: [PATCH 28/33] Update base_local_dynamics.h --- src/shared/particle_dynamics/base_local_dynamics.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/shared/particle_dynamics/base_local_dynamics.h b/src/shared/particle_dynamics/base_local_dynamics.h index ec672fe2a0..d3f6ea2471 100644 --- a/src/shared/particle_dynamics/base_local_dynamics.h +++ b/src/shared/particle_dynamics/base_local_dynamics.h @@ -147,6 +147,9 @@ class Average : public ReduceSumType * @brief Class template argument deduction (CTAD) for constructing interaction dynamics. * @details Note that the form "XXX" is not std::string type, so we need to use * std::string("XXX") to convert it to std::string type. + * Only the DynamicsIdentifier parameter is reference, + * the other parameters should not use it, use pointer + * instead. */ template struct DynamicsArgs From a2cb9f717053bb2beec71b3c4b271404f8adf222 Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Wed, 12 Feb 2025 13:07:33 +0000 Subject: [PATCH 29/33] revise 0d regression test case --- .../diffusion_dynamics.cpp | 10 +- .../diffusion_dynamics.h | 51 +- .../diffusion_dynamics_ck.h | 75 ++- .../diffusion_dynamics_ck.hpp | 34 +- .../general_initial_condition.h | 42 +- .../regression_test.cpp | 36 +- .../CMakeLists.txt | 28 + ...CylinderObserver_Position_Run_0_result.xml | 9 + ...ylinderObserver_Position_Run_15_result.xml | 9 + ...CylinderObserver_Position_Run_7_result.xml | 9 + .../CylinderObserver_Position_dtwdistance.xml | 4 + .../CylinderObserver_Position_runtimes.dat | 3 + .../WettingObserver_Phi_Run_0_result.xml | 9 + .../WettingObserver_Phi_Run_11_result.xml | 9 + .../WettingObserver_Phi_Run_5_result.xml | 9 + .../WettingObserver_Phi_dtwdistance.xml | 4 + .../WettingObserver_Phi_runtimes.dat | 3 + .../regression_test_tool.py | 45 ++ .../test_2d_water_entry_exit.cpp | 525 ++++++++++++++++++ 19 files changed, 830 insertions(+), 84 deletions(-) create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/CMakeLists.txt create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_0_result.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_15_result.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_7_result.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_dtwdistance.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_runtimes.dat create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_0_result.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_11_result.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_5_result.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_dtwdistance.xml create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_runtimes.dat create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/regression_test_tool.py create mode 100644 tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/test_2d_water_entry_exit.cpp diff --git a/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp b/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp index f88ad64e9f..f508fb8a5b 100644 --- a/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp +++ b/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp @@ -3,12 +3,16 @@ namespace SPH { //=================================================================================================// -GetDiffusionTimeStepSize::GetDiffusionTimeStepSize(SPHBody &sph_body) +GetDiffusionTimeStepSize::GetDiffusionTimeStepSize( + SPHBody &sph_body, AbstractDiffusion &abstract_diffusion) : BaseDynamics() { - AbstractDiffusion &diffusion = DynamicCast(this, sph_body.getBaseMaterial()); Real smoothing_length = sph_body.sph_adaptation_->ReferenceSmoothingLength(); - diff_time_step_ = diffusion.getDiffusionTimeStepSize(smoothing_length); + diff_time_step_ = abstract_diffusion.getDiffusionTimeStepSize(smoothing_length); } //=================================================================================================// +GetDiffusionTimeStepSize::GetDiffusionTimeStepSize(SPHBody &sph_body) + : GetDiffusionTimeStepSize( + sph_body, DynamicCast(this, sph_body.getBaseMaterial())) {} +//=================================================================================================// } // namespace SPH diff --git a/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.h b/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.h index a3e4fb07ae..6a78774116 100644 --- a/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.h +++ b/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.h @@ -40,8 +40,9 @@ namespace SPH class GetDiffusionTimeStepSize : public BaseDynamics { public: + GetDiffusionTimeStepSize(SPHBody &sph_body, AbstractDiffusion &abstract_diffusion); explicit GetDiffusionTimeStepSize(SPHBody &sph_body); - virtual ~GetDiffusionTimeStepSize(){}; + virtual ~GetDiffusionTimeStepSize() {}; virtual Real exec(Real dt = 0.0) override { return diff_time_step_; }; @@ -77,7 +78,7 @@ class DiffusionRelaxation class KernelGradientInner { public: - explicit KernelGradientInner(BaseParticles *inner_particles){}; + explicit KernelGradientInner(BaseParticles *inner_particles) {}; Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) { return dW_ijV_j * e_ij; @@ -90,7 +91,7 @@ class CorrectedKernelGradientInner public: explicit CorrectedKernelGradientInner(BaseParticles *inner_particles) - : B_(inner_particles->getVariableDataByName("LinearGradientCorrectionMatrix")){}; + : B_(inner_particles->getVariableDataByName("LinearGradientCorrectionMatrix")) {}; Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) { return 0.5 * dW_ijV_j * (B_[index_i] + B_[index_j]) * e_ij; @@ -110,16 +111,16 @@ class DiffusionRelaxation, DiffusionType> public: template - explicit DiffusionRelaxation(Args &&... args); + explicit DiffusionRelaxation(Args &&...args); - virtual ~DiffusionRelaxation(){}; + virtual ~DiffusionRelaxation() {}; inline void interaction(size_t index_i, Real dt = 0.0); }; class KernelGradientContact { public: - KernelGradientContact(BaseParticles *inner_particles, BaseParticles *contact_particles){}; + KernelGradientContact(BaseParticles *inner_particles, BaseParticles *contact_particles) {}; Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) { return dW_ijV_j * e_ij; @@ -134,7 +135,7 @@ class CorrectedKernelGradientContact public: CorrectedKernelGradientContact(BaseParticles *inner_particles, BaseParticles *contact_particles) : B_(inner_particles->getVariableDataByName("LinearGradientCorrectionMatrix")), - contact_B_(contact_particles->getVariableDataByName("LinearGradientCorrectionMatrix")){}; + contact_B_(contact_particles->getVariableDataByName("LinearGradientCorrectionMatrix")) {}; Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) { return 0.5 * dW_ijV_j * (B_[index_i] + contact_B_[index_j]) * e_ij; @@ -155,8 +156,8 @@ class DiffusionRelaxation, DiffusionType> public: template - explicit DiffusionRelaxation(Args &&... args); - virtual ~DiffusionRelaxation(){}; + explicit DiffusionRelaxation(Args &&...args); + virtual ~DiffusionRelaxation() {}; }; template @@ -175,8 +176,8 @@ class DiffusionRelaxation, DiffusionType> public: template - explicit DiffusionRelaxation(Args &&... args); - virtual ~DiffusionRelaxation(){}; + explicit DiffusionRelaxation(Args &&...args); + virtual ~DiffusionRelaxation() {}; inline void interaction(size_t index_i, Real dt = 0.0); }; @@ -198,8 +199,8 @@ class DiffusionRelaxation, DiffusionType> public: template - explicit DiffusionRelaxation(Args &&... args); - virtual ~DiffusionRelaxation(){}; + explicit DiffusionRelaxation(Args &&...args); + virtual ~DiffusionRelaxation() {}; void interaction(size_t index_i, Real dt = 0.0); }; @@ -224,9 +225,9 @@ class DiffusionRelaxation, DiffusionType> public: template - explicit DiffusionRelaxation(Args &&... args); + explicit DiffusionRelaxation(Args &&...args); - virtual ~DiffusionRelaxation(){}; + virtual ~DiffusionRelaxation() {}; void interaction(size_t index_i, Real dt = 0.0); }; @@ -244,9 +245,9 @@ class RungeKuttaStep : public DiffusionRelaxationType public: template - RungeKuttaStep(Args &&... args); + RungeKuttaStep(Args &&...args); - virtual ~RungeKuttaStep(){}; + virtual ~RungeKuttaStep() {}; }; /** @@ -259,9 +260,9 @@ class FirstStageRK2 : public RungeKuttaStep { public: template - FirstStageRK2(Args &&... args); + FirstStageRK2(Args &&...args); - virtual ~FirstStageRK2(){}; + virtual ~FirstStageRK2() {}; void initialization(size_t index_i, Real dt = 0.0); }; @@ -274,9 +275,9 @@ class SecondStageRK2 : public RungeKuttaStep { public: template - SecondStageRK2(Args &&... args); + SecondStageRK2(Args &&...args); - virtual ~SecondStageRK2(){}; + virtual ~SecondStageRK2() {}; void update(size_t index_i, Real dt = 0.0); }; @@ -293,9 +294,9 @@ class DiffusionRelaxationRK2 : public BaseDynamics public: template - explicit DiffusionRelaxationRK2(FirstArg &first_arg, OtherArgs &&... other_args); + explicit DiffusionRelaxationRK2(FirstArg &first_arg, OtherArgs &&...other_args); - virtual ~DiffusionRelaxationRK2(){}; + virtual ~DiffusionRelaxationRK2() {}; virtual void exec(Real dt = 0.0) override; }; @@ -310,12 +311,12 @@ class DiffusionBodyRelaxationComplex { public: template - explicit DiffusionBodyRelaxationComplex(FirstArg &&first_arg, OtherArgs &&... other_args) + explicit DiffusionBodyRelaxationComplex(FirstArg &&first_arg, OtherArgs &&...other_args) : DiffusionRelaxationRK2< ComplexInteraction, ContactInteractionTypes...>, DiffusionType>>(first_arg, std::forward(other_args)...){}; - virtual ~DiffusionBodyRelaxationComplex(){}; + virtual ~DiffusionBodyRelaxationComplex() {}; }; } // namespace SPH #endif // DIFFUSION_DYNAMICS_H diff --git a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h index e260c5f444..b478dc2a40 100644 --- a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h +++ b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h @@ -36,6 +36,22 @@ namespace SPH { +class KernelGradientInnerCK +{ + public: + explicit KernelGradientInnerCK(BaseParticles *inner_particles) {}; + class ComputingKernel + { + public: + template + ComputingKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser){}; + Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) + { + return dW_ijV_j * e_ij; + }; + }; +}; + class CorrectedKernelGradientInnerCK { DiscreteVariable *dv_B_; @@ -60,6 +76,50 @@ class CorrectedKernelGradientInnerCK }; }; +class KernelGradientContactCK +{ + public: + KernelGradientContactCK(BaseParticles *inner_particles, BaseParticles *contact_particles) {}; + class ComputingKernel + { + public: + template + ComputingKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser){}; + Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) + { + return dW_ijV_j * e_ij; + }; + }; +}; + +class CorrectedKernelGradientContactCK +{ + DiscreteVariable *dv_B_; + DiscreteVariable *dv_contact_B_; + + public: + CorrectedKernelGradientContactCK(BaseParticles *inner_particles, BaseParticles *contact_particles) + : dv_B_(inner_particles->getVariableByName("LinearCorrectionMatrix")), + dv_contact_B_(contact_particles->getVariableByName("LinearCorrectionMatrix")) {}; + + class ComputingKernel + { + Matd *B_; + Matd *contact_B_; + + public: + template + ComputingKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + : B_(encloser.dv_B_->DelegatedData(ex_policy)), + contact_B_(encloser.dv_contact_B_->DelegatedData(ex_policy)){}; + + Vecd operator()(size_t index_i, size_t index_j, Real dW_ijV_j, const Vecd &e_ij) + { + return 0.5 * dW_ijV_j * (B_[index_i] + contact_B_[index_j]) * e_ij; + }; + }; +}; + template class DiffusionRelaxationCK; @@ -68,6 +128,8 @@ class DiffusionRelaxationCK : public BaseInteractionType { public: + template + DiffusionRelaxationCK(DynamicsIdentifier &identifier, AbstractDiffusion &abstract_diffusion); template explicit DiffusionRelaxationCK(DynamicsIdentifier &identifier); virtual ~DiffusionRelaxationCK() {}; @@ -104,7 +166,7 @@ class DiffusionRelaxationCK Real smoothing_length_sq_; private: - StdVec getConcreteDiffusions(BaseMaterial &base_material); + StdVec getConcreteDiffusions(AbstractDiffusion &abstract_diffusion); StdVec *> getDiffusionSpecies(StdVec diffusions); StdVec *> getGradientSpecies(StdVec diffusions); StdVec *> getSpeciesChangeRates(StdVec diffusions); @@ -175,16 +237,17 @@ class DiffusionRelaxationCK -class DiffusionRelaxationCK> - : public DiffusionRelaxationCK>> +template class RelationType, typename... Parameters> +class DiffusionRelaxationCK> + : public DiffusionRelaxationCK>> { - using BaseInteraction = DiffusionRelaxationCK>>; + using BaseInteraction = DiffusionRelaxationCK>>; using GradientKernel = typename KernelGradientType::ComputingKernel; using InterParticleDiffusionCoeff = typename DiffusionType::InterParticleDiffusionCoeff; public: - explicit DiffusionRelaxationCK(Relation> &inner_relation); + explicit DiffusionRelaxationCK(Relation> &relation); virtual ~DiffusionRelaxationCK() {}; class InteractKernel : public BaseInteraction::InteractKernel diff --git a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp index cdd93f9129..0278255f92 100644 --- a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp +++ b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp @@ -15,19 +15,25 @@ namespace SPH template template DiffusionRelaxationCK:: - DiffusionRelaxationCK(DynamicsIdentifier &identifier) + DiffusionRelaxationCK(DynamicsIdentifier &identifier, AbstractDiffusion &abstract_diffusion) : BaseInteractionType(identifier), - diffusions_(this->getConcreteDiffusions(this->sph_body_.getBaseMaterial())), + diffusions_(this->getConcreteDiffusions(abstract_diffusion)), dv_diffusion_species_array_(this->getDiffusionSpecies(diffusions_)), dv_gradient_species_array_(this->getGradientSpecies(diffusions_)), dv_diffusion_dt_array_(this->getSpeciesChangeRates(diffusions_)), smoothing_length_sq_(pow(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength(), 2)) {} //=================================================================================================// template +template +DiffusionRelaxationCK:: + DiffusionRelaxationCK(DynamicsIdentifier &identifier) + : DiffusionRelaxationCK( + identifier, DynamicCast(this, identifier.getSPHBody().getBaseMaterial())) {} +//=================================================================================================// +template StdVec DiffusionRelaxationCK:: - getConcreteDiffusions(BaseMaterial &base_material) + getConcreteDiffusions(AbstractDiffusion &abstract_diffusion) { - AbstractDiffusion &abstract_diffusion = DynamicCast(this, base_material); StdVec all_diffusions = abstract_diffusion.AllDiffusions(); StdVec diffusions; for (auto &diffusion : all_diffusions) @@ -190,17 +196,18 @@ void DiffusionRelaxationCK -DiffusionRelaxationCK>:: - DiffusionRelaxationCK(Relation> &inner_relation) - : BaseInteraction(inner_relation), - kernel_gradient_(this->particles_), +template class RelationType, typename... Parameters> +DiffusionRelaxationCK>:: + DiffusionRelaxationCK(Relation> &relation) + : BaseInteraction(relation), kernel_gradient_(this->particles_), ca_inter_particle_diffusion_coeff_(this->diffusions_), dv_Vol_(this->particles_->template getVariableByName("VolumetricMeasure")) {} //=================================================================================================// -template +template class RelationType, typename... Parameters> template -DiffusionRelaxationCK>:: +DiffusionRelaxationCK>:: InteractKernel::InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : BaseInteraction::InteractKernel(ex_policy, encloser), inter_particle_diffusion_coeff_(encloser.ca_inter_particle_diffusion_coeff_.DelegatedData(ex_policy)), @@ -212,8 +219,9 @@ DiffusionRelaxationCKDelegatedData(ex_policy)), smoothing_length_sq_(encloser.smoothing_length_sq_) {} //=================================================================================================// -template -void DiffusionRelaxationCK>:: +template class RelationType, typename... Parameters> +void DiffusionRelaxationCK>:: InteractKernel::interact(size_t index_i, Real dt) { for (size_t m = 0; m < number_of_species_; ++m) diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/general_initial_condition.h b/src/shared/shared_ck/particle_dynamics/general_dynamics/general_initial_condition.h index 2cff84d180..ccc1a8013a 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/general_initial_condition.h +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/general_initial_condition.h @@ -33,16 +33,19 @@ namespace SPH { -template +template class InitialCondition : public BaseLocalDynamics { - using DataType = typename ReturnFunctionType::ReturnType; + using DataType = typename InitializeFunctionType::ReturnType; + using Initialize = typename InitializeFunctionType::ComputingKernel; public: - InitialCondition(DynamicsIdentifier &identifier, const std::string &variable_name) + template + InitialCondition(DynamicsIdentifier &identifier, const std::string &variable_name, Args &...args) : BaseLocalDynamics(identifier), dv_pos_(this->particles_->template getVariableByName("Position")), - dv_variable_(this->particles_->template registerStateVariableOnly(variable_name)) {}; + dv_variable_(this->particles_->template registerStateVariableOnly(variable_name)), + initialize_method_(this->particles_, std::forward(args)...){}; virtual ~InitialCondition() {}; class UpdateKernel @@ -52,22 +55,47 @@ class InitialCondition : public BaseLocalDynamics UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : pos_(encloser.dv_pos_->DelegatedData(ex_policy)), variable_(encloser.dv_variable_->DelegatedData(ex_policy)), - function_(ex_policy, encloser){}; + initialize_(ex_policy, encloser.initialize_method_){}; void update(size_t index_i, Real dt = 0.0) { - variable_[index_i] = function_(pos_[index_i]); + variable_[index_i] = initialize_(pos_[index_i]); }; protected: Vecd *pos_; DataType *variable_; - ReturnFunctionType function_; + Initialize initialize_; }; protected: DiscreteVariable *dv_pos_; DiscreteVariable *dv_variable_; + InitializeFunctionType initialize_method_; +}; + +template +class UniformDistribution : public ReturnFunction +{ + public: + UniformDistribution(BaseParticles *particles, DataType constant_value) + : constant_value_(constant_value) {}; + + class ComputingKernel + { + public: + template + ComputingKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + : constant_value_(encloser.constant_value_){}; + + DataType operator()(const Vecd &position) { return constant_value_; }; + + protected: + DataType constant_value_; + }; + + protected: + DataType constant_value_; }; } // namespace SPH #endif // GENERAL_INITIAL_CONDITION_H diff --git a/tests/2d_examples/2d_examples_ck/test_0d_regression_test_ck/regression_test.cpp b/tests/2d_examples/2d_examples_ck/test_0d_regression_test_ck/regression_test.cpp index 5f648c7eee..5822944462 100644 --- a/tests/2d_examples/2d_examples_ck/test_0d_regression_test_ck/regression_test.cpp +++ b/tests/2d_examples/2d_examples_ck/test_0d_regression_test_ck/regression_test.cpp @@ -95,28 +95,7 @@ MultiPolygon createOtherSideBoundary() return multi_polygon; } -//---------------------------------------------------------------------- -// Define extra classes which are used in the main program. -// These classes are defined under the namespace of SPH. -//---------------------------------------------------------------------- -namespace SPH -{ -//---------------------------------------------------------------------- -// Case-dependent initial condition function. -//---------------------------------------------------------------------- -struct UniformTemperature : ReturnFunction -{ - Real initial_temperature_; - template - UniformTemperature(const ExecutionPolicy &ex_policy, EncloserType &encloser) - : ReturnFunction(), initial_temperature_(initial_temperature){}; - - Real operator()(const Vecd &position) - { - return initial_temperature_; - } -}; StdVec createObservationPoints() { /** A line of measuring points at the middle line. */ @@ -132,8 +111,6 @@ StdVec createObservationPoints() } return observation_points; }; - -} // namespace SPH //---------------------------------------------------------------------- // Main program starts here. //---------------------------------------------------------------------- @@ -180,20 +157,19 @@ int main(int ac, char *av[]) // boundary condition and other constraints should be defined. //---------------------------------------------------------------------- UpdateCellLinkedList diffusion_body_cell_linked_list(diffusion_body); - UpdateRelation> water_block_update_complex_relation(diffusion_body_inner); UpdateRelation> observer_update_contact_relation(observer_contact); InteractionDynamicsCK correct_configuration(diffusion_body_inner); - StateDynamics> - diffusion_initial_condition(diffusion_body, diffusion_species_name); + StateDynamics>> + diffusion_initial_condition(diffusion_body, diffusion_species_name, initial_temperature); GetDiffusionTimeStepSize get_time_step_size(diffusion_body); DynamicsSequence>, - DiffusionRelaxationCK>>> - diffusion_relaxation_rk2(diffusion_body_inner, diffusion_body_inner); + MainExecutionPolicy, + DiffusionRelaxationCK>, + DiffusionRelaxationCK>>> + diffusion_relaxation_rk2(diffusion_body_inner, diffusion_body_inner); BodyRegionByParticle left_boundary(diffusion_body, makeShared(createLeftSideBoundary())); StateDynamics> diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/CMakeLists.txt b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/CMakeLists.txt new file mode 100644 index 0000000000..507ee8bf40 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/CMakeLists.txt @@ -0,0 +1,28 @@ +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${SPHINXSYS_PROJECT_DIR}/cmake) # main (top) cmake dir + +set(CMAKE_VERBOSE_MAKEFILE on) + +STRING(REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}) +PROJECT("${CURRENT_FOLDER}") + +SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib) +SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin/") +SET(BUILD_INPUT_PATH "${EXECUTABLE_OUTPUT_PATH}/input") +SET(BUILD_RELOAD_PATH "${EXECUTABLE_OUTPUT_PATH}/reload") + +file(MAKE_DIRECTORY ${BUILD_INPUT_PATH}) +execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${BUILD_INPUT_PATH}) +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/regression_test_tool/ DESTINATION ${BUILD_INPUT_PATH}) + +aux_source_directory(. DIR_SRCS) +ADD_EXECUTABLE(${PROJECT_NAME} ${EXECUTABLE_OUTPUT_PATH} ${DIR_SRCS}) +set_target_properties(${PROJECT_NAME} PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${EXECUTABLE_OUTPUT_PATH}") +target_link_libraries(${PROJECT_NAME} sphinxsys_2d) + +add_test(NAME ${PROJECT_NAME}_particle_relaxation COMMAND ${PROJECT_NAME} --relax=true --state_recording=${TEST_STATE_RECORDING} + WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) +add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME} --reload=true --state_recording=${TEST_STATE_RECORDING} + WORKING_DIRECTORY ${EXECUTABLE_OUTPUT_PATH}) + +set_tests_properties(${PROJECT_NAME} PROPERTIES LABELS "spatial_temporal_identification diffusion reaction") +set_tests_properties(${PROJECT_NAME} PROPERTIES DEPENDS "${PROJECT_NAME}_particle_relaxation") \ No newline at end of file diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_0_result.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_0_result.xml new file mode 100644 index 0000000000..556607eaf0 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_15_result.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_15_result.xml new file mode 100644 index 0000000000..0257615594 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_15_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_7_result.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_7_result.xml new file mode 100644 index 0000000000..b1ce83eb16 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_Run_7_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_dtwdistance.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_dtwdistance.xml new file mode 100644 index 0000000000..ead45a7e4c --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_runtimes.dat b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_runtimes.dat new file mode 100644 index 0000000000..452899ced3 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/CylinderObserver_Position_runtimes.dat @@ -0,0 +1,3 @@ +true +16 +4 \ No newline at end of file diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_0_result.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_0_result.xml new file mode 100644 index 0000000000..52ecd39a2d --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_0_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_11_result.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_11_result.xml new file mode 100644 index 0000000000..052cb39f9b --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_11_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_5_result.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_5_result.xml new file mode 100644 index 0000000000..b4c7a3e6fe --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_Run_5_result.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_dtwdistance.xml b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_dtwdistance.xml new file mode 100644 index 0000000000..318e85025f --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_dtwdistance.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_runtimes.dat b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_runtimes.dat new file mode 100644 index 0000000000..5cc2fa0e29 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/WettingObserver_Phi_runtimes.dat @@ -0,0 +1,3 @@ +true +12 +4 \ No newline at end of file diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/regression_test_tool.py b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/regression_test_tool.py new file mode 100644 index 0000000000..4672379302 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/regression_test_tool/regression_test_tool.py @@ -0,0 +1,45 @@ +# !/usr/bin/env python3 +import os +import sys + +path = os.path.abspath('../../../../../PythonScriptStore/RegressionTest') +sys.path.append(path) +from regression_test_base_tool import SphinxsysRegressionTest + +""" +case name: test_2d_water_entry_exit +""" + +case_name = "test_2d_water_entry_exit" +body_name = "CylinderObserver" +parameter_name = "Position" +body_name_1 = "WettingObserver" +parameter_name_1 = "Phi" + +number_of_run_times = 0 +converged = 0 +sphinxsys = SphinxsysRegressionTest(case_name, body_name, parameter_name) +sphinxsys_1 = SphinxsysRegressionTest(case_name, body_name_1, parameter_name_1) +clean_input_folder(sphinxsys.input_file_path) + +while True: + print("Now start a new run......") + sphinxsys.run_particle_relaxation() + sphinxsys.run_case_with_reload() + number_of_run_times += 1 + converged = sphinxsys.read_dat_file() + converged_1 = sphinxsys_1.read_dat_file() + print("Please note: This is the", number_of_run_times, "run!") + if number_of_run_times <= 200: + if (converged == "true") and (converged_1 == "true"): + print("The tested parameters of all variables are converged, and the run will stop here!") + break + elif converged != "true": + print("The tested parameters of", sphinxsys.sphinxsys_parameter_name, "are not converged!") + continue + elif converged_1 != "true": + print("The tested parameters of", sphinxsys_1.sphinxsys_parameter_name, "are not converged!") + continue + else: + print("It's too many runs but still not converged, please try again!") + break diff --git a/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/test_2d_water_entry_exit.cpp b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/test_2d_water_entry_exit.cpp new file mode 100644 index 0000000000..747fb90668 --- /dev/null +++ b/tests/2d_examples/2d_examples_ck/test_2d_water_entry_exit_ck/test_2d_water_entry_exit.cpp @@ -0,0 +1,525 @@ +/** + * @file water entry and exit.cpp + * @brief 2D water entry and exit example with surface wetting considered. + * @details This is the one of FSI test cases, also one case for + * understanding spatial temporal identification approach, + * especially when coupled with the wetting. + * @author Shuoguo Zhang and Xiangyu Hu + */ +#include "sphinxsys_ck.h" //SPHinXsys Library. +using namespace SPH; // Namespace cite here. +//---------------------------------------------------------------------- +// Basic geometry parameters and numerical setup. +//---------------------------------------------------------------------- +Real cylinder_radius = 0.055; /**< Cylinder radius. */ +Real DL = 8.0 * cylinder_radius; /**< Water tank length. */ +Real DH = 7.0 * cylinder_radius; /**< Water tank height. */ +Real LL = DL; /**< Water column length. */ +Real LH = 3.0 * cylinder_radius; /**< Water column height. */ +Real particle_spacing_ref = 2.0 * cylinder_radius / 40.0; /**< Initial reference particle spacing. */ +Real BW = particle_spacing_ref * 4; /**< Thickness of tank wall. */ +Vec2d cylinder_center(0.5 * DL, LH + 0.15); /**< Location of the cylinder center. */ +Vecd tethering_point(0.5 * DL, DH); /**< The tethering point. */ +StdVec observer_location = {cylinder_center}; /**< Displacement observation point. */ +StdVec wetting_observer_location = + {cylinder_center - Vecd(0.0, cylinder_radius)}; /**< wetting observation point. */ +//---------------------------------------------------------------------- +// Material parameters. +//---------------------------------------------------------------------- +Real rho0_f = 1.0; /**< Fluid density. */ +Real rho0_s = 0.5; /**< Cylinder density. */ +Real gravity_g = 9.81; /**< Gravity. */ +Real U_max = 2.0 * sqrt(gravity_g * LH); /**< Characteristic velocity. */ +Real c_f = 10.0 * U_max; /**< Reference sound speed. */ +Real mu_f = 8.9e-7; /**< Water dynamics viscosity. */ +//---------------------------------------------------------------------- +// Wetting parameters +//---------------------------------------------------------------------- +std::string diffusion_species_name = "Phi"; +Real diffusion_coeff = 100.0 * pow(particle_spacing_ref, 2); /**< Wetting coefficient. */ +Real fluid_moisture = 1.0; /**< fluid moisture. */ +Real cylinder_moisture = 0.0; /**< cylinder moisture. */ +Real wall_moisture = 1.0; /**< wall moisture. */ +//---------------------------------------------------------------------- +// Definition for water body +//---------------------------------------------------------------------- +std::vector createWaterBlockShape() +{ + std::vector water_block; + water_block.push_back(Vecd(0.0, 0.0)); + water_block.push_back(Vecd(0.0, LH)); + water_block.push_back(Vecd(LL, LH)); + water_block.push_back(Vecd(LL, 0.0)); + water_block.push_back(Vecd(0.0, 0.0)); + + return water_block; +} +class WettingFluidBody : public MultiPolygonShape +{ + public: + explicit WettingFluidBody(const std::string &shape_name) : MultiPolygonShape(shape_name) + { + multi_polygon_.addAPolygon(createWaterBlockShape(), ShapeBooleanOps::add); + } +}; + +class WettingFluidBodyInitialCondition : public LocalDynamics +{ + public: + explicit WettingFluidBodyInitialCondition(SPHBody &sph_body) + : LocalDynamics(sph_body), + pos_(particles_->getVariableDataByName("Position")), + phi_(particles_->registerStateVariable(diffusion_species_name)) {}; + + void update(size_t index_i, Real dt) + { + phi_[index_i] = fluid_moisture; + }; + + protected: + Vecd *pos_; + Real *phi_; +}; +//---------------------------------------------------------------------- +// Definition for wall body +//---------------------------------------------------------------------- +std::vector createOuterWallShape() +{ + std::vector outer_wall; + outer_wall.push_back(Vecd(-BW, -BW)); + outer_wall.push_back(Vecd(-BW, DH + BW)); + outer_wall.push_back(Vecd(DL + BW, DH + BW)); + outer_wall.push_back(Vecd(DL + BW, -BW)); + outer_wall.push_back(Vecd(-BW, -BW)); + + return outer_wall; +} +std::vector createInnerWallShape() +{ + std::vector inner_wall; + inner_wall.push_back(Vecd(0.0, 0.0)); + inner_wall.push_back(Vecd(0.0, DH)); + inner_wall.push_back(Vecd(DL, DH)); + inner_wall.push_back(Vecd(DL, 0.0)); + inner_wall.push_back(Vecd(0.0, 0.0)); + + return inner_wall; +} +class WettingWallBody : public MultiPolygonShape +{ + public: + explicit WettingWallBody(const std::string &shape_name) : MultiPolygonShape(shape_name) + { + multi_polygon_.addAPolygon(createOuterWallShape(), ShapeBooleanOps::add); + multi_polygon_.addAPolygon(createInnerWallShape(), ShapeBooleanOps::sub); + } +}; +class WettingWallBodyInitialCondition : public LocalDynamics +{ + public: + explicit WettingWallBodyInitialCondition(SPHBody &sph_body) + : LocalDynamics(sph_body), + pos_(particles_->getVariableDataByName("Position")), + phi_(particles_->registerStateVariable(diffusion_species_name)) {}; + + void update(size_t index_i, Real dt) + { + phi_[index_i] = wall_moisture; + }; + + protected: + Vecd *pos_; + Real *phi_; +}; +//---------------------------------------------------------------------- +// Definition for cylinder body +//---------------------------------------------------------------------- +class WettingCylinderBody : public MultiPolygonShape +{ + public: + explicit WettingCylinderBody(const std::string &shape_name) : MultiPolygonShape(shape_name) + { + multi_polygon_.addACircle(cylinder_center, cylinder_radius, 100, ShapeBooleanOps::add); + } +}; +class WettingCylinderBodyInitialCondition : public LocalDynamics +{ + public: + explicit WettingCylinderBodyInitialCondition(SPHBody &sph_body) + : LocalDynamics(sph_body), + pos_(particles_->getVariableDataByName("Position")), + phi_(particles_->registerStateVariable(diffusion_species_name)) {}; + + void update(size_t index_i, Real dt) + { + phi_[index_i] = cylinder_moisture; + }; + + protected: + Vecd *pos_; + Real *phi_; +}; +//------------------------------------------------------------------------------ +// Constrained part for Simbody +//------------------------------------------------------------------------------ +MultiPolygon createSimbodyConstrainShape(SPHBody &sph_body) +{ + MultiPolygon multi_polygon; + multi_polygon.addACircle(cylinder_center, cylinder_radius, 100, ShapeBooleanOps::add); + return multi_polygon; +}; +//---------------------------------------------------------------------- +// Main program starts here. +//---------------------------------------------------------------------- +int main(int ac, char *av[]) +{ + //---------------------------------------------------------------------- + // Build up an SPHSystem. + //---------------------------------------------------------------------- + BoundingBox system_domain_bounds(Vec2d(-BW, -BW), Vec2d(DL + BW, DH + BW)); + SPHSystem sph_system(system_domain_bounds, particle_spacing_ref); + sph_system.setRunParticleRelaxation(false); + sph_system.setReloadParticles(true); + sph_system.handleCommandlineOptions(ac, av)->setIOEnvironment(); + //---------------------------------------------------------------------- + // Creating bodies with corresponding materials and particles. + //---------------------------------------------------------------------- + FluidBody water_block(sph_system, makeShared("WaterBody")); + water_block.defineClosure(ConstructArgs(rho0_f, c_f), mu_f); + water_block.generateParticles(); + + SolidBody wall_boundary(sph_system, makeShared("WallBoundary")); + wall_boundary.defineMaterial(); + wall_boundary.generateParticles(); + + SolidBody cylinder(sph_system, makeShared("Cylinder")); + cylinder.defineAdaptationRatios(1.15, 1.0); + cylinder.defineBodyLevelSetShape(); + cylinder.defineMaterial(rho0_s); + (!sph_system.RunParticleRelaxation() && sph_system.ReloadParticles()) + ? cylinder.generateParticles(cylinder.getName()) + : cylinder.generateParticles(); + + ObserverBody cylinder_observer(sph_system, "CylinderObserver"); + cylinder_observer.generateParticles(observer_location); + + ObserverBody wetting_observer(sph_system, "WettingObserver"); + wetting_observer.generateParticles(wetting_observer_location); + //---------------------------------------------------------------------- + // Run particle relaxation for body-fitted distribution if chosen. + //---------------------------------------------------------------------- + if (sph_system.RunParticleRelaxation()) + { + /** body topology only for particle relaxation */ + InnerRelation cylinder_inner(cylinder); + //---------------------------------------------------------------------- + // Methods used for particle relaxation. + //---------------------------------------------------------------------- + using namespace relax_dynamics; + SimpleDynamics random_inserted_body_particles(cylinder); + /** Write the body state to Vtp file. */ + BodyStatesRecordingToVtp write_inserted_body_to_vtp(cylinder); + /** Write the particle reload files. */ + ReloadParticleIO write_particle_reload_files(cylinder); + /** A Physics relaxation step. */ + RelaxationStepInner relaxation_step_inner(cylinder_inner); + //---------------------------------------------------------------------- + // Particle relaxation starts here. + //---------------------------------------------------------------------- + random_inserted_body_particles.exec(0.25); + relaxation_step_inner.SurfaceBounding().exec(); + write_inserted_body_to_vtp.writeToFile(0); + //---------------------------------------------------------------------- + // Relax particles of the insert body. + //---------------------------------------------------------------------- + int ite_p = 0; + while (ite_p < 1000) + { + relaxation_step_inner.exec(); + ite_p += 1; + if (ite_p % 200 == 0) + { + std::cout << std::fixed << std::setprecision(9) << "Relaxation steps for the inserted body N = " << ite_p << "\n"; + write_inserted_body_to_vtp.writeToFile(ite_p); + } + } + std::cout << "The physics relaxation process of inserted body finish !" << std::endl; + /** Output results. */ + write_particle_reload_files.writeToFile(0); + return 0; + } + //---------------------------------------------------------------------- + // Define body relation map. + // The contact map gives the topological connections between the bodies. + // Basically the the range of bodies to build neighbor particle lists. + // Generally, we first define all the inner relations, then the contact relations. + //---------------------------------------------------------------------- + Relation> water_block_inner(water_block); + Relation> water_block_contact(water_block, {&wall_boundary, &cylinder}); + Relation> cylinder_contact(cylinder, {&water_block}); + Relation> cylinder_observer_contact(cylinder_observer, {&cylinder}); + Relation> wetting_observer_contact(wetting_observer, {&cylinder}); + //---------------------------------------------------------------------- + // Define the main execution policy for this case. + //---------------------------------------------------------------------- + using MainExecutionPolicy = execution::ParallelPolicy; + //---------------------------------------------------------------------- + // Define the numerical methods used in the simulation. + // Note that there may be data dependence on the sequence of constructions. + // Generally, the configuration dynamics, such as update cell linked list, + // update body relations, are defiend first. + // Then the geometric models or simple objects without data dependencies, + // such as gravity, initialized normal direction. + // After that, the major physical particle dynamics model should be introduced. + // Finally, the auxiliary models such as time step estimator, initial condition, + // boundary condition and other constraints should be defined. + //---------------------------------------------------------------------- + UpdateCellLinkedList water_cell_linked_list(water_block); + UpdateCellLinkedList wall_cell_linked_list(wall_boundary); + UpdateCellLinkedList cylinder_cell_linked_list(cylinder); + + UpdateRelation, Contact<>> + water_block_update_complex_relation(water_block_inner, water_block_contact); + UpdateRelation> + cylinder_update_contact_relation(cylinder_contact); + UpdateRelation> + cylinder_observer_update_contact_relation(cylinder_observer_contact); + UpdateRelation> + wetting_observer_update_contact_relation(wetting_observer_contact); + ParticleSortCK particle_sort(water_block); + + IsotropicDiffusion diffusion(diffusion_species_name, diffusion_species_name, diffusion_coeff); + GetDiffusionTimeStepSize get_thermal_time_step(cylinder, diffusion); + StateDynamics>> + cylinder_initial_condition(cylinder, diffusion_species_name, wall_moisture); + StateDynamics>> + water_block_initial_condition(water_block, diffusion_species_name, fluid_moisture); + + CylinderFluidDiffusionDirichlet cylinder_wetting(cylinder_contact); + SimpleDynamics wetting_water_initial_condition(water_block); + SimpleDynamics wetting_wall_initial_condition(wall_boundary); + SimpleDynamics wetting_cylinder_initial_condition(cylinder); + + Gravity gravity(Vecd(0.0, -gravity_g)); + SimpleDynamics> constant_gravity(water_block, gravity); + InteractionWithUpdate free_stream_surface_indicator(water_block_inner, water_block_contact); + SimpleDynamics wall_boundary_normal_direction(wall_boundary); + SimpleDynamics cylinder_normal_direction(cylinder); + + Dynamics1Level fluid_pressure_relaxation(water_block_inner, water_block_contact); + Dynamics1Level fluid_density_relaxation(water_block_inner, water_block_contact); + InteractionWithUpdate fluid_density_by_summation(water_block_inner, water_block_contact); + InteractionWithUpdate viscous_force(water_block_inner, water_block_contact); + InteractionWithUpdate> transport_velocity_correction(water_block_inner, water_block_contact); + + ReduceDynamics fluid_advection_time_step(water_block, U_max); + ReduceDynamics fluid_acoustic_time_step(water_block); + //---------------------------------------------------------------------- + // Algorithms of FSI. + //---------------------------------------------------------------------- + InteractionWithUpdate viscous_force_from_fluid(cylinder_contact); + InteractionWithUpdate> pressure_force_from_fluid(cylinder_contact); + //---------------------------------------------------------------------- + // Define the configuration related particles dynamics. + //---------------------------------------------------------------------- + ParticleSorting particle_sorting(water_block); + //---------------------------------------------------------------------- + // Building Simbody. + //---------------------------------------------------------------------- + SimTK::MultibodySystem MBsystem; + /** The bodies or matter of the MBsystem. */ + SimTK::SimbodyMatterSubsystem matter(MBsystem); + /** The forces of the MBsystem.*/ + SimTK::GeneralForceSubsystem forces(MBsystem); + /** Mass properties of the fixed spot. */ + SimTK::Body::Rigid fixed_spot_info(SimTK::MassProperties(1.0, SimTKVec3(0), SimTK::UnitInertia(1))); + SolidBodyPartForSimbody cylinder_constraint_area(cylinder, makeShared(createSimbodyConstrainShape(cylinder), "cylinder")); + /** Mass properties of the constrained spot. */ + SimTK::Body::Rigid tethered_spot_info(*cylinder_constraint_area.body_part_mass_properties_); + /** Mobility of the fixed spot. */ + SimTK::MobilizedBody::Weld fixed_spot(matter.Ground(), SimTK::Transform(SimTKVec3(tethering_point[0], tethering_point[1], 0.0)), + fixed_spot_info, SimTK::Transform(SimTKVec3(0))); + /** Mobility of the tethered spot. + * Set the mass center as the origin location of the planar mobilizer + */ + Vecd displacement0 = cylinder_constraint_area.initial_mass_center_ - tethering_point; + SimTK::MobilizedBody::Planar tethered_spot(fixed_spot, + SimTK::Transform(SimTKVec3(displacement0[0], displacement0[1], 0.0)), + tethered_spot_info, SimTK::Transform(SimTKVec3(0))); + // discrete forces acting on the bodies + SimTK::Force::UniformGravity sim_gravity(forces, matter, SimTK::Vec3(0.0, Real(-9.81), 0.0), 0.0); + SimTK::Force::DiscreteForces force_on_bodies(forces, matter); + fixed_spot_info.addDecoration(SimTK::Transform(), SimTK::DecorativeSphere(0.02)); + tethered_spot_info.addDecoration(SimTK::Transform(), SimTK::DecorativeSphere(0.4)); + SimTK::State state = MBsystem.realizeTopology(); + + /** Time stepping method for multibody system.*/ + SimTK::RungeKuttaMersonIntegrator integ(MBsystem); + integ.setAccuracy(1e-3); + integ.setAllowInterpolation(false); + integ.initialize(state); + //---------------------------------------------------------------------- + // Coupling between SimBody and SPH.. + //---------------------------------------------------------------------- + ReduceDynamics + force_on_tethered_spot(cylinder_constraint_area, MBsystem, tethered_spot, integ); + SimpleDynamics + constraint_tethered_spot(cylinder_constraint_area, MBsystem, tethered_spot, integ); + //---------------------------------------------------------------------- + // Define the methods for I/O operations, observations + // and regression tests of the simulation. + //---------------------------------------------------------------------- + BodyStatesRecordingToVtp body_states_recording(sph_system); + body_states_recording.addToWrite(water_block, "Pressure"); // output for debug + body_states_recording.addToWrite(water_block, "Density"); // output for debug + body_states_recording.addToWrite(water_block, "Indicator"); // output for debug + body_states_recording.addToWrite(wall_boundary, "NormalDirection"); // output for debug + RestartIO restart_io(sph_system); + RegressionTestDynamicTimeWarping> write_cylinder_displacement("Position", cylinder_observer_contact); + RegressionTestDynamicTimeWarping> write_cylinder_wetting("Phi", wetting_observer_contact); + //---------------------------------------------------------------------- + // Prepare the simulation with cell linked list, configuration + // and case specified initial condition if necessary. + //---------------------------------------------------------------------- + sph_system.initializeSystemCellLinkedLists(); + sph_system.initializeSystemConfigurations(); + wall_boundary_normal_direction.exec(); + cylinder_normal_direction.exec(); + wetting_water_initial_condition.exec(); + wetting_wall_initial_condition.exec(); + wetting_cylinder_initial_condition.exec(); + Real dt_thermal = get_thermal_time_step.exec(); + free_stream_surface_indicator.exec(); + constant_gravity.exec(); + //---------------------------------------------------------------------- + // Setup for time-stepping control + //---------------------------------------------------------------------- + Real &physical_time = *sph_system.getSystemVariableDataByName("PhysicalTime"); + size_t number_of_iterations = 0; + int screen_output_interval = 100; + int observation_sample_interval = screen_output_interval * 2; + int restart_output_interval = screen_output_interval * 10; + Real end_time = 1.0; + Real output_interval = end_time / 70.0; + //---------------------------------------------------------------------- + // Statistics for CPU time + //---------------------------------------------------------------------- + TickCount t1 = TickCount::now(); + TimeInterval interval; + TimeInterval interval_computing_time_step; + TimeInterval interval_computing_fluid_pressure_relaxation; + TimeInterval interval_updating_configuration; + TickCount time_instance; + //---------------------------------------------------------------------- + // First output before the main loop. + //---------------------------------------------------------------------- + body_states_recording.writeToFile(); + write_cylinder_displacement.writeToFile(number_of_iterations); + write_cylinder_wetting.writeToFile(number_of_iterations); + //---------------------------------------------------------------------- + // Main loop starts here. + //---------------------------------------------------------------------- + while (physical_time < end_time) + { + Real integration_time = 0.0; + /** Integrate time (loop) until the next output time. */ + while (integration_time < output_interval) + { + /** outer loop for dual-time criteria time-stepping. */ + time_instance = TickCount::now(); + Real Dt = fluid_advection_time_step.exec(); + + fluid_density_by_summation.exec(); + viscous_force.exec(); + transport_velocity_correction.exec(); + interval_computing_time_step += TickCount::now() - time_instance; + + time_instance = TickCount::now(); + Real relaxation_time = 0.0; + Real dt = 0.0; + viscous_force_from_fluid.exec(); + while (relaxation_time < Dt) + { + /** inner loop for dual-time criteria time-stepping. */ + dt = SMIN(SMIN(dt_thermal, fluid_acoustic_time_step.exec()), Dt); + fluid_pressure_relaxation.exec(dt); + pressure_force_from_fluid.exec(); + fluid_density_relaxation.exec(dt); + cylinder_wetting.exec(dt); + + integ.stepBy(dt); + SimTK::State &state_for_update = integ.updAdvancedState(); + force_on_bodies.clearAllBodyForces(state_for_update); + force_on_bodies.setOneBodyForce(state_for_update, tethered_spot, force_on_tethered_spot.exec()); + constraint_tethered_spot.exec(); + + relaxation_time += dt; + integration_time += dt; + physical_time += dt; + } + interval_computing_fluid_pressure_relaxation += TickCount::now() - time_instance; + + /** screen output, write body reduced values and restart files */ + if (number_of_iterations % screen_output_interval == 0) + { + std::cout << std::fixed << std::setprecision(9) << "N=" << number_of_iterations << " Time = " + << physical_time + << " Dt = " << Dt << " dt = " << dt << "\n"; + + if (number_of_iterations % observation_sample_interval == 0 && number_of_iterations != sph_system.RestartStep()) + { + write_cylinder_displacement.writeToFile(number_of_iterations); + write_cylinder_wetting.writeToFile(number_of_iterations); + } + if (number_of_iterations % restart_output_interval == 0) + restart_io.writeToFile(number_of_iterations); + } + number_of_iterations++; + + /** Update cell linked list and configuration. */ + time_instance = TickCount::now(); + if (number_of_iterations % 100 == 0 && number_of_iterations != 1) + { + particle_sorting.exec(); + } + water_block.updateCellLinkedList(); + cylinder.updateCellLinkedList(); + water_block_inner.updateConfiguration(); + cylinder_inner.updateConfiguration(); + cylinder_contact.updateConfiguration(); + water_block_complex.updateConfiguration(); + free_stream_surface_indicator.exec(); + interval_updating_configuration += TickCount::now() - time_instance; + } + + body_states_recording.writeToFile(); + TickCount t2 = TickCount::now(); + TickCount t3 = TickCount::now(); + interval += t3 - t2; + } + TickCount t4 = TickCount::now(); + + TimeInterval tt; + tt = t4 - t1 - interval; + std::cout << "Total wall time for computation: " << tt.seconds() + << " seconds." << std::endl; + std::cout << std::fixed << std::setprecision(9) << "interval_computing_time_step =" + << interval_computing_time_step.seconds() << "\n"; + std::cout << std::fixed << std::setprecision(9) << "interval_computing_fluid_pressure_relaxation = " + << interval_computing_fluid_pressure_relaxation.seconds() << "\n"; + std::cout << std::fixed << std::setprecision(9) << "interval_updating_configuration = " + << interval_updating_configuration.seconds() << "\n"; + + if (sph_system.GenerateRegressionData()) + { + write_cylinder_displacement.generateDataBase(1.0e-3); + write_cylinder_wetting.generateDataBase(1.0e-3); + } + else + { + write_cylinder_displacement.testResult(); + write_cylinder_wetting.testResult(); + } + + return 0; +}; From 23627e64e556479bda42585bcd9624f3cdc1036f Mon Sep 17 00:00:00 2001 From: Xiangyu Hu Date: Wed, 12 Feb 2025 17:19:41 +0000 Subject: [PATCH 30/33] 1. move three members in base particles into protected, 2. revamp the sycl diffusion dynamics --- .../slender_structure_dynamics.cpp | 4 +- .../slender_structure_dynamics.h | 20 +- .../particle_generator_network.cpp | 2 +- src/shared/bodies/base_body.h | 18 +- src/shared/bodies/base_body_part.cpp | 4 +- src/shared/bodies/solid_body.cpp | 2 +- .../body_relations/base_body_relation.cpp | 2 +- .../body_relations/base_body_relation.h | 20 +- src/shared/geometries/level_set_shape.cpp | 2 +- .../continuum_integration.cpp | 6 +- .../diffusion_dynamics.cpp | 2 +- .../boundary_condition/near_wall_boundary.cpp | 2 +- .../fluid_dynamics/density_summation.cpp | 6 +- .../fluid_dynamics/density_summation.hpp | 10 +- ...ulerian_compressible_fluid_integration.cpp | 4 +- .../fluid_dynamics/fluid_time_step.cpp | 4 +- .../non_newtonian_dynamics.cpp | 2 +- .../fluid_dynamics/shape_confinement.cpp | 4 +- .../fluid_dynamics/surface_tension.cpp | 8 +- .../transport_velocity_correction.hpp | 2 +- .../fluid_dynamics/viscous_dynamics.hpp | 2 +- .../eulerian_ghost_boundary.cpp | 4 +- .../domian_bouding/domain_bounding.h | 14 +- .../general_dynamics/general_constraint.cpp | 2 +- .../general_dynamics/particle_smoothing.hpp | 2 +- .../surface_indication/surface_indication.cpp | 2 +- .../relax_dynamics/base_relax_dynamics.cpp | 2 +- .../relax_dynamics/relax_stepping.cpp | 6 +- .../relax_dynamics/relax_stepping.hpp | 2 +- .../relax_dynamics/relax_thick_shell.cpp | 6 +- .../repulsion_factor_summation.cpp | 10 +- .../solid_dynamics/elastic_dynamics.cpp | 8 +- .../solid_dynamics/elastic_dynamics.h | 30 +-- .../fluid_structure_interaction.cpp | 2 +- .../solid_dynamics/general_solid_dynamics.cpp | 4 +- .../solid_dynamics_variable.cpp | 2 +- .../thin_structure_dynamics.cpp | 10 +- .../solid_dynamics/thin_structure_dynamics.h | 22 +- .../base_particle_generator.cpp | 2 +- .../particle_generator_lattice.cpp | 6 +- .../particle_neighborhood/neighborhood.cpp | 36 +-- src/shared/particles/surface_particles.cpp | 2 +- .../shared_ck/body_relation/relation_ck.cpp | 2 +- .../diffusion_dynamics_ck.h | 91 ++++--- .../diffusion_dynamics_ck.hpp | 190 ++++++++------- .../fluid_dynamics/fluid_time_step_ck.cpp | 4 +- .../transport_velocity_correction_ck.hpp | 69 +++--- .../fluid_dynamics/viscous_force.hpp | 8 +- .../force_on_structure.hpp | 2 +- .../general_dynamics/geometric_dynamics.cpp | 2 +- .../surface_indication_ck.hpp | 36 +-- .../particle_dynamics/interaction_ck.hpp | 4 +- src/shared/sphinxsys_system/sph_system.cpp | 5 +- .../test_2d_water_entry_exit.cpp | 226 ------------------ .../test_2d_anisotropic_beam.cpp | 12 +- .../2d_eulerian_flow_around_cylinder_LG.cpp | 4 +- ...lerian_supersonic_flow_around_cylinder.cpp | 2 +- .../2d_eulerian_taylor_green_LG.cpp | 6 +- .../test_2d_filling_tank/filling_tank.cpp | 2 +- .../test_2d_mr_cantilever_beam.cpp | 4 +- .../oscillating_beam_UL.cpp | 4 +- .../src/tethered_dead_fish_in_flow.cpp | 2 +- ..._bending_circular_plate_parametric_cvt.cpp | 10 +- .../excitation-contraction.cpp | 4 +- .../excitation_contraction.h | 14 +- .../heart_volume_change.cpp | 4 +- .../test_3d_mr_cantilever_beam.cpp | 4 +- .../pkj_lv_electrocontraction.h | 16 +- .../test_3d_roof_parametric_cvt.cpp | 14 +- .../test_3d_slender_beam.cpp | 6 +- .../test_3d_taylor_bar/taylor_bar.h | 8 +- .../test_3d_taylor_bar_UL/taylor_bar_UL.h | 16 +- .../k-epsilon_turbulent_model.cpp | 10 +- .../k-epsilon_turbulent_model.hpp | 4 +- .../shared/porous_media_dynamics.cpp | 4 +- .../extra_src/shared/porous_media_dynamics.h | 22 +- .../pressure_boundary/density_correciton.cpp | 2 +- .../pressure_boundary/density_correciton.hpp | 6 +- .../shared/rans_turbulence_dynamics.hpp | 133 ++++++----- .../cohesive_soil_failure.h | 16 +- .../passive_cantilever_LG.cpp | 4 +- 81 files changed, 538 insertions(+), 734 deletions(-) diff --git a/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.cpp b/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.cpp index f24e11bde5..f54f7886b2 100644 --- a/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.cpp +++ b/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.cpp @@ -20,7 +20,7 @@ BarAcousticTimeStepSize::BarAcousticTimeStepSize(SPHBody &sph_body, Real CFL) E0_(elastic_solid_.YoungsModulus()), nu_(elastic_solid_.PoissonRatio()), c0_(elastic_solid_.ReferenceSoundSpeed()), - smoothing_length_(sph_body.sph_adaptation_->ReferenceSmoothingLength()), + smoothing_length_(sph_body.getSPHAdaptation().ReferenceSmoothingLength()), angular_b_vel_(particles_->getVariableDataByName("BinormalAngularVelocity")), dangular_b_vel_dt_(particles_->getVariableDataByName("BinormalAngularAcceleration")), width_(particles_->getVariableDataByName("Width")) {} @@ -100,7 +100,7 @@ BarStressRelaxationFirstHalf:: : BaseBarRelaxation(inner_relation), elastic_solid_(DynamicCast(this, sph_body_.getBaseMaterial())), rho0_(elastic_solid_.ReferenceDensity()), inv_rho0_(1.0 / rho0_), - smoothing_length_(sph_body_.sph_adaptation_->ReferenceSmoothingLength()), + smoothing_length_(sph_body_.getSPHAdaptation().ReferenceSmoothingLength()), numerical_damping_scaling_matrix_(Matd::Identity() * smoothing_length_), rho_(particles_->getVariableDataByName("Density")), mass_(particles_->getVariableDataByName("Mass")), diff --git a/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.h b/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.h index cdf03b2e6a..eda6a6f355 100644 --- a/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.h +++ b/src/for_3D_build/particle_dynamics/solid_dynamics/slender_structure_dynamics.h @@ -60,7 +60,7 @@ class BarAcousticTimeStepSize : public LocalDynamicsReduce public: explicit BarAcousticTimeStepSize(SPHBody &sph_body, Real CFL = 0.6); - virtual ~BarAcousticTimeStepSize(){}; + virtual ~BarAcousticTimeStepSize() {}; Real reduce(size_t index_i, Real dt = 0.0); }; @@ -73,7 +73,7 @@ class BarCorrectConfiguration : public LocalDynamics, public DataDelegateInner { public: explicit BarCorrectConfiguration(BaseInnerRelation &inner_relation); - virtual ~BarCorrectConfiguration(){}; + virtual ~BarCorrectConfiguration() {}; inline void interaction(size_t index_i, Real dt = 0.0) { @@ -109,7 +109,7 @@ class BarDeformationGradientTensor : public LocalDynamics, public DataDelegateIn { public: explicit BarDeformationGradientTensor(BaseInnerRelation &inner_relation); - virtual ~BarDeformationGradientTensor(){}; + virtual ~BarDeformationGradientTensor() {}; inline void interaction(size_t index_i, Real dt = 0.0) { @@ -154,7 +154,7 @@ class BaseBarRelaxation : public LocalDynamics, public DataDelegateInner { public: explicit BaseBarRelaxation(BaseInnerRelation &inner_relation); - virtual ~BaseBarRelaxation(){}; + virtual ~BaseBarRelaxation() {}; protected: Real *Vol_, *thickness_, *width_; @@ -179,7 +179,7 @@ class BarStressRelaxationFirstHalf : public BaseBarRelaxation public: explicit BarStressRelaxationFirstHalf(BaseInnerRelation &inner_relation, int number_of_gaussian_points = 4, bool hourglass_control = false); - virtual ~BarStressRelaxationFirstHalf(){}; + virtual ~BarStressRelaxationFirstHalf() {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) @@ -232,7 +232,7 @@ class BarStressRelaxationFirstHalf : public BaseBarRelaxation Real E0_, G0_, nu_, hourglass_control_factor_; bool hourglass_control_; - const Real inv_W0_ = 1.0 / sph_body_.sph_adaptation_->getKernel()->W0(ZeroVecd); + const Real inv_W0_ = 1.0 / sph_body_.getSPHAdaptation().getKernel()->W0(ZeroVecd); const Real shear_correction_factor_ = 5.0 / 6.0; Real gpt = sqrt(3.0 / 5.0); @@ -267,8 +267,8 @@ class BarStressRelaxationSecondHalf : public BaseBarRelaxation { public: explicit BarStressRelaxationSecondHalf(BaseInnerRelation &inner_relation) - : BaseBarRelaxation(inner_relation){}; - virtual ~BarStressRelaxationSecondHalf(){}; + : BaseBarRelaxation(inner_relation) {}; + virtual ~BarStressRelaxationSecondHalf() {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) @@ -311,7 +311,7 @@ class ConstrainBarBodyRegion : public BaseLocalDynamics { public: ConstrainBarBodyRegion(BodyPartByParticle &body_part); - virtual ~ConstrainBarBodyRegion(){}; + virtual ~ConstrainBarBodyRegion() {}; void update(size_t index_i, Real dt = 0.0); protected: @@ -327,7 +327,7 @@ class ConstrainBarBodyRegionAlongAxis : public BaseLocalDynamics:: : ParticleGenerator(sph_body, base_particles), starting_pnt_(starting_pnt), second_pnt_(second_pnt), n_it_(iterator), fascicles_(true), segments_in_branch_(10), - segment_length_(sph_body.sph_adaptation_->ReferenceSpacing()), + segment_length_(sph_body.getSPHAdaptation().ReferenceSpacing()), grad_factor_(grad_factor), sph_body_(sph_body), initial_shape_(sph_body.getInitialShape()), cell_linked_list_(DynamicCast(this, sph_body).getCellLinkedList()), tree_(DynamicCast(this, &sph_body)) diff --git a/src/shared/bodies/base_body.h b/src/shared/bodies/base_body.h index 71c13bfb3f..72dc5603b7 100644 --- a/src/shared/bodies/base_body.h +++ b/src/shared/bodies/base_body.h @@ -80,13 +80,12 @@ class SPHBody Shape *initial_shape_; /**< initial volumetric geometry enclosing the body */ int total_body_parts_; /**< total number of body parts */ StdVec body_parts_by_particle_; /**< all body parts by particle */ + SPHAdaptation *sph_adaptation_; /**< numerical adaptation policy */ + BaseMaterial *base_material_; /**< base material for dynamic cast in DataDelegate */ + StdVec body_relations_; /**< all contact relations centered from this body **/ public: typedef SPHBody BaseIdentifier; - SPHAdaptation *sph_adaptation_; /**< numerical adaptation policy */ - BaseMaterial *base_material_; /**< base material for dynamic cast in DataDelegate */ - StdVec body_relations_; /**< all contact relations centered from this body **/ - SPHBody(SPHSystem &sph_system, Shape &shape, const std::string &name); SPHBody(SPHSystem &sph_system, Shape &shape); SPHBody(SPHSystem &sph_system, const std::string &name); @@ -99,6 +98,7 @@ class SPHBody SPHBody &getSPHBody() { return *this; }; Shape &getInitialShape() { return *initial_shape_; }; void assignBaseParticles(BaseParticles *base_particles) { base_particles_ = base_particles; }; + SPHAdaptation &getSPHAdaptation() { return *sph_adaptation_; }; BaseParticles &getBaseParticles(); BaseMaterial &getBaseMaterial(); StdVec &getBodyRelations() { return body_relations_; }; @@ -115,11 +115,11 @@ class SPHBody int getTotalBodyParts() { return total_body_parts_; }; void addBodyPartByParticle(BodyPartByParticle *body_part) { body_parts_by_particle_.push_back(body_part); }; StdVec getBodyPartsByParticle() { return body_parts_by_particle_; }; - //---------------------------------------------------------------------- - // Object factory template functions - //---------------------------------------------------------------------- - virtual void - defineAdaptationRatios(Real h_spacing_ratio, Real new_system_refinement_ratio = 1.0); + //---------------------------------------------------------------------- + // Object factory template functions + //---------------------------------------------------------------------- + virtual void + defineAdaptationRatios(Real h_spacing_ratio, Real new_system_refinement_ratio = 1.0); template void defineAdaptation(Args &&...args) diff --git a/src/shared/bodies/base_body_part.cpp b/src/shared/bodies/base_body_part.cpp index c2a61ba688..9c010d4750 100644 --- a/src/shared/bodies/base_body_part.cpp +++ b/src/shared/bodies/base_body_part.cpp @@ -82,7 +82,7 @@ void BodyRegionByParticle::tagByContain(size_t particle_index) //=================================================================================================// BodySurface::BodySurface(SPHBody &sph_body) : BodyPartByParticle(sph_body, "BodySurface"), - particle_spacing_min_(sph_body.sph_adaptation_->MinimumSpacing()) + particle_spacing_min_(sph_body.getSPHAdaptation().MinimumSpacing()) { TaggingParticleMethod tagging_particle_method = std::bind(&BodySurface::tagNearSurface, this, _1); tagParticles(tagging_particle_method); @@ -98,7 +98,7 @@ void BodySurface::tagNearSurface(size_t particle_index) //=================================================================================================// BodySurfaceLayer::BodySurfaceLayer(SPHBody &sph_body, Real layer_thickness) : BodyPartByParticle(sph_body, "InnerLayers"), - thickness_threshold_(sph_body.sph_adaptation_->ReferenceSpacing() * layer_thickness) + thickness_threshold_(sph_body.getSPHAdaptation().ReferenceSpacing() * layer_thickness) { TaggingParticleMethod tagging_particle_method = std::bind(&BodySurfaceLayer::tagSurfaceLayer, this, _1); tagParticles(tagging_particle_method); diff --git a/src/shared/bodies/solid_body.cpp b/src/shared/bodies/solid_body.cpp index 77119253de..9d078f1d8c 100644 --- a/src/shared/bodies/solid_body.cpp +++ b/src/shared/bodies/solid_body.cpp @@ -10,7 +10,7 @@ namespace SPH SolidBodyPartForSimbody:: SolidBodyPartForSimbody(SPHBody &body, Shape &body_part_shape) : BodyRegionByParticle(body, body_part_shape), - rho0_(DynamicCast(this, body.base_material_)->ReferenceDensity()), + rho0_(DynamicCast(this, body.getBaseMaterial()).ReferenceDensity()), Vol_(base_particles_.getVariableDataByName("VolumetricMeasure")), pos_(base_particles_.getVariableDataByName("Position")) { diff --git a/src/shared/body_relations/base_body_relation.cpp b/src/shared/body_relations/base_body_relation.cpp index bde91d2bde..60a4d23285 100644 --- a/src/shared/body_relations/base_body_relation.cpp +++ b/src/shared/body_relations/base_body_relation.cpp @@ -50,7 +50,7 @@ BaseContactRelation::BaseContactRelation(SPHBody &sph_body, RealBodyVector conta { const std::string name = contact_bodies_[k]->getName(); contact_particles_.push_back(&contact_bodies_[k]->getBaseParticles()); - contact_adaptations_.push_back(contact_bodies_[k]->sph_adaptation_); + contact_adaptations_.push_back(&contact_bodies_[k]->getSPHAdaptation()); contact_configuration_[k].resize(base_particles_.RealParticlesBound(), Neighborhood()); } } diff --git a/src/shared/body_relations/base_body_relation.h b/src/shared/body_relations/base_body_relation.h index b732a92a18..1f9a313311 100644 --- a/src/shared/body_relations/base_body_relation.h +++ b/src/shared/body_relations/base_body_relation.h @@ -32,9 +32,9 @@ #include "base_body.h" #include "base_body_part.h" #include "base_geometry.h" +#include "base_implementation.h" #include "base_particles.h" #include "cell_linked_list.h" -#include "base_implementation.h" #include "neighborhood.h" namespace SPH @@ -55,7 +55,7 @@ struct SearchDepthContact : search_depth_(1) { Real inv_grid_spacing_ = 1.0 / target_mesh.GridSpacing(); - Kernel *kernel_ = sph_body.sph_adaptation_->getKernel(); + Kernel *kernel_ = sph_body.getSPHAdaptation().getKernel(); search_depth_ = 1 + (int)floor(kernel_->CutOffRadius() * inv_grid_spacing_); }; int operator()(size_t particle_index) const { return search_depth_; }; @@ -71,7 +71,7 @@ struct SearchDepthAdaptive Real *h_ratio_; SearchDepthAdaptive(SPHBody &sph_body, Mesh &target_mesh) : inv_grid_spacing_(1.0 / target_mesh.GridSpacing()), - kernel_(sph_body.sph_adaptation_->getKernel()), + kernel_(sph_body.getSPHAdaptation().getKernel()), h_ratio_(sph_body.getBaseParticles().getVariableDataByName("SmoothingLengthRatio")) {}; int operator()(size_t particle_index) const { @@ -89,8 +89,8 @@ struct SearchDepthAdaptiveContact Kernel &kernel_; SearchDepthAdaptiveContact(SPHBody &sph_body, Mesh &target_mesh) : inv_grid_spacing_(1.0 / target_mesh.GridSpacing()), - sph_adaptation_(*sph_body.sph_adaptation_), - kernel_(*sph_body.sph_adaptation_->getKernel()) {}; + sph_adaptation_(sph_body.getSPHAdaptation()), + kernel_(*sph_body.getSPHAdaptation().getKernel()) {}; int operator()(size_t particle_index) const { return 1 + (int)floor(kernel_.CutOffRadius(sph_adaptation_.SmoothingLengthRatio(particle_index)) * inv_grid_spacing_); @@ -109,9 +109,9 @@ class SPHRelation public: SPHBody &getSPHBody() { return sph_body_; }; explicit SPHRelation(SPHBody &sph_body); - virtual ~SPHRelation(){}; + virtual ~SPHRelation() {}; - void subscribeToBody() { sph_body_.body_relations_.push_back(this); }; + void subscribeToBody() { sph_body_.getBodyRelations().push_back(this); }; virtual void updateConfiguration() = 0; protected: @@ -129,7 +129,7 @@ class BaseInnerRelation : public SPHRelation RealBody *real_body_; ParticleConfiguration inner_configuration_; /**< inner configuration for the neighbor relations. */ explicit BaseInnerRelation(RealBody &real_body); - virtual ~BaseInnerRelation(){}; + virtual ~BaseInnerRelation() {}; BaseInnerRelation &getRelation() { return *this; }; protected: @@ -153,8 +153,8 @@ class BaseContactRelation : public SPHRelation BaseContactRelation(SPHBody &sph_body, RealBodyVector contact_bodies); BaseContactRelation(SPHBody &sph_body, BodyPartVector contact_body_parts) - : BaseContactRelation(sph_body, BodyPartsToRealBodies(contact_body_parts)){}; - virtual ~BaseContactRelation(){}; + : BaseContactRelation(sph_body, BodyPartsToRealBodies(contact_body_parts)) {}; + virtual ~BaseContactRelation() {}; BaseContactRelation &getRelation() { return *this; }; RealBodyVector getContactBodies() { return contact_bodies_; }; StdVec getContactParticles() { return contact_particles_; }; diff --git a/src/shared/geometries/level_set_shape.cpp b/src/shared/geometries/level_set_shape.cpp index c3317519eb..181e09d30f 100644 --- a/src/shared/geometries/level_set_shape.cpp +++ b/src/shared/geometries/level_set_shape.cpp @@ -19,7 +19,7 @@ LevelSetShape:: LevelSetShape::LevelSetShape(SPHBody &sph_body, Shape &shape, Real refinement_ratio) : Shape(shape.getName()), level_set_(*level_set_keeper_.movePtr( - sph_body.sph_adaptation_->createLevelSet(shape, refinement_ratio))) + sph_body.getSPHAdaptation().createLevelSet(shape, refinement_ratio))) { bounding_box_ = shape.getBounds(); is_bounds_found_ = true; diff --git a/src/shared/particle_dynamics/continuum_dynamics/continuum_integration.cpp b/src/shared/particle_dynamics/continuum_dynamics/continuum_integration.cpp index aac2151fde..4fb3106c28 100644 --- a/src/shared/particle_dynamics/continuum_dynamics/continuum_integration.cpp +++ b/src/shared/particle_dynamics/continuum_dynamics/continuum_integration.cpp @@ -17,7 +17,7 @@ AcousticTimeStep::AcousticTimeStep(SPHBody &sph_body, Real acousticCFL) rho_(particles_->getVariableDataByName("Density")), p_(particles_->getVariableDataByName("Pressure")), vel_(particles_->getVariableDataByName("Velocity")), - smoothing_length_min_(sph_body.sph_adaptation_->MinimumSmoothingLength()), + smoothing_length_min_(sph_body.getSPHAdaptation().MinimumSmoothingLength()), acousticCFL_(acousticCFL) {} //=================================================================================================// Real AcousticTimeStep::reduce(size_t index_i, Real dt) @@ -33,7 +33,7 @@ Real AcousticTimeStep::outputResult(Real reduced_value) StressDiffusion::StressDiffusion(BaseInnerRelation &inner_relation) : BasePlasticIntegration(inner_relation), phi_(DynamicCast(this, plastic_continuum_).getFrictionAngle()), - smoothing_length_(sph_body_.sph_adaptation_->ReferenceSmoothingLength()), + smoothing_length_(sph_body_.getSPHAdaptation().ReferenceSmoothingLength()), sound_speed_(plastic_continuum_.ReferenceSoundSpeed()) {} //====================================================================================// void StressDiffusion::interaction(size_t index_i, Real dt) @@ -55,7 +55,7 @@ void StressDiffusion::interaction(size_t index_i, Real dt) diffusion_stress(1, 1) -= density * gravity * y_ij; diffusion_stress(2, 2) -= (1 - sin(phi_)) * density * gravity * y_ij; diffusion_stress_rate += 2 * zeta_ * smoothing_length_ * sound_speed_ * - diffusion_stress * r_ij * dW_ijV_j / (r_ij * r_ij + 0.01 * smoothing_length_); + diffusion_stress * r_ij * dW_ijV_j / (r_ij * r_ij + 0.01 * smoothing_length_); } stress_rate_3D_[index_i] = diffusion_stress_rate; } diff --git a/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp b/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp index f508fb8a5b..98c49e1937 100644 --- a/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp +++ b/src/shared/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics.cpp @@ -7,7 +7,7 @@ GetDiffusionTimeStepSize::GetDiffusionTimeStepSize( SPHBody &sph_body, AbstractDiffusion &abstract_diffusion) : BaseDynamics() { - Real smoothing_length = sph_body.sph_adaptation_->ReferenceSmoothingLength(); + Real smoothing_length = sph_body.getSPHAdaptation().ReferenceSmoothingLength(); diff_time_step_ = abstract_diffusion.getDiffusionTimeStepSize(smoothing_length); } //=================================================================================================// diff --git a/src/shared/particle_dynamics/fluid_dynamics/boundary_condition/near_wall_boundary.cpp b/src/shared/particle_dynamics/fluid_dynamics/boundary_condition/near_wall_boundary.cpp index b2c36662b6..e3e0c3ac20 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/boundary_condition/near_wall_boundary.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/boundary_condition/near_wall_boundary.cpp @@ -7,7 +7,7 @@ namespace fluid_dynamics //=================================================================================================// NearWallDistance::NearWallDistance(BaseContactRelation &wall_contact_relation) : LocalDynamics(wall_contact_relation.getSPHBody()), DataDelegateContact(wall_contact_relation), - spacing_ref_(sph_body_.sph_adaptation_->ReferenceSpacing()), + spacing_ref_(sph_body_.getSPHAdaptation().ReferenceSpacing()), distance_default_(100.0 * spacing_ref_), pos_(particles_->getVariableDataByName("Position")) { diff --git a/src/shared/particle_dynamics/fluid_dynamics/density_summation.cpp b/src/shared/particle_dynamics/fluid_dynamics/density_summation.cpp index 6e74b1af4d..7b5c01ac94 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/density_summation.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/density_summation.cpp @@ -23,7 +23,7 @@ void DensitySummation>::update(size_t index_i, Real dt) //=================================================================================================// DensitySummation>::DensitySummation(BaseInnerRelation &inner_relation) : DensitySummation>(inner_relation), - sph_adaptation_(*sph_body_.sph_adaptation_), + sph_adaptation_(sph_body_.getSPHAdaptation()), kernel_(*sph_adaptation_.getKernel()), h_ratio_(particles_->getVariableDataByName("SmoothingLengthRatio")) {} //=================================================================================================// @@ -49,7 +49,7 @@ DensitySummation>::DensitySummation(BaseContactRelation &contact_r { for (size_t k = 0; k != this->contact_particles_.size(); ++k) { - Real rho0_k = this->contact_bodies_[k]->base_material_->ReferenceDensity(); + Real rho0_k = this->contact_bodies_[k]->getBaseMaterial().ReferenceDensity(); contact_inv_rho0_.push_back(1.0 / rho0_k); contact_mass_.push_back(contact_particles_[k]->getVariableDataByName("Mass")); } @@ -80,7 +80,7 @@ void DensitySummation>::interaction(size_t index_i, Real dt) DensitySummation>:: DensitySummation(BaseContactRelation &contact_relation) : DensitySummation>(contact_relation), - sph_adaptation_(*sph_body_.sph_adaptation_), + sph_adaptation_(sph_body_.getSPHAdaptation()), h_ratio_(particles_->getVariableDataByName("SmoothingLengthRatio")) {} //=================================================================================================// void DensitySummation>::interaction(size_t index_i, Real dt) diff --git a/src/shared/particle_dynamics/fluid_dynamics/density_summation.hpp b/src/shared/particle_dynamics/fluid_dynamics/density_summation.hpp index 1f091f7cb2..ed51d58a88 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/density_summation.hpp +++ b/src/shared/particle_dynamics/fluid_dynamics/density_summation.hpp @@ -15,13 +15,13 @@ DensitySummation::DensitySummation(BaseRelationType &b mass_(this->particles_->template getVariableDataByName("Mass")), rho_sum_(this->particles_->template registerStateVariable("DensitySummation")), Vol_(this->particles_->template getVariableDataByName("VolumetricMeasure")), - rho0_(this->sph_body_.base_material_->ReferenceDensity()), - inv_sigma0_(1.0 / this->sph_body_.sph_adaptation_->LatticeNumberDensity()), - W0_(this->sph_body_.sph_adaptation_->getKernel()->W0(ZeroVecd)) {} + rho0_(this->sph_body_.getBaseMaterial().ReferenceDensity()), + inv_sigma0_(1.0 / this->sph_body_.getSPHAdaptation().LatticeNumberDensity()), + W0_(this->sph_body_.getSPHAdaptation().getKernel()->W0(ZeroVecd)) {} //=================================================================================================// template template -DensitySummation>::DensitySummation(Args &&... args) +DensitySummation>::DensitySummation(Args &&...args) : DensitySummation>(std::forward(args)...) {} //=================================================================================================// template @@ -32,7 +32,7 @@ void DensitySummation>::update(size_t index //=================================================================================================// template template -DensitySummation>::DensitySummation(Args &&... args) +DensitySummation>::DensitySummation(Args &&...args) : DensitySummation>(std::forward(args)...), indicator_(this->particles_->template getVariableDataByName("Indicator")){}; //=================================================================================================// diff --git a/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_compressible_fluid_integration.cpp b/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_compressible_fluid_integration.cpp index c2fae13d0e..8a8ebb5199 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_compressible_fluid_integration.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/eulerian_fluid_dynamics/eulerian_compressible_fluid_integration.cpp @@ -14,7 +14,7 @@ BaseIntegrationInCompressible::BaseIntegrationInCompressible(BaseInnerRelation & dmass_dt_(particles_->registerStateVariable("MassChangeRate")), mom_(particles_->registerStateVariable("Momentum")), force_(particles_->registerStateVariable("Force")), - force_prior_(particles_->registerStateVariable("ForcePrior")){}; + force_prior_(particles_->registerStateVariable("ForcePrior")) {}; //=================================================================================================// CompressibleFluidInitialCondition::CompressibleFluidInitialCondition(SPHBody &sph_body) : FluidInitialCondition(sph_body), @@ -31,7 +31,7 @@ EulerianCompressibleAcousticTimeStepSize:: rho_(particles_->getVariableDataByName("Density")), p_(particles_->getVariableDataByName("Pressure")), vel_(particles_->getVariableDataByName("Velocity")), - smoothing_length_(sph_body.sph_adaptation_->ReferenceSmoothingLength()), + smoothing_length_(sph_body.getSPHAdaptation().ReferenceSmoothingLength()), compressible_fluid_(CompressibleFluid(1.0, 1.4)) { acousticCFL_ = acousticCFL; diff --git a/src/shared/particle_dynamics/fluid_dynamics/fluid_time_step.cpp b/src/shared/particle_dynamics/fluid_dynamics/fluid_time_step.cpp index 2e7ae5610a..d0e4ed8753 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/fluid_time_step.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/fluid_time_step.cpp @@ -16,7 +16,7 @@ AcousticTimeStep::AcousticTimeStep(SPHBody &sph_body, Real acousticCFL) vel_(particles_->getVariableDataByName("Velocity")), force_(particles_->getVariableDataByName("Force")), force_prior_(particles_->getVariableDataByName("ForcePrior")), - h_min_(sph_body.sph_adaptation_->MinimumSmoothingLength()), + h_min_(sph_body.getSPHAdaptation().MinimumSmoothingLength()), acousticCFL_(acousticCFL) {} //=================================================================================================// Real AcousticTimeStep::reduce(size_t index_i, Real dt) @@ -40,7 +40,7 @@ AdvectionTimeStep:: vel_(particles_->getVariableDataByName("Velocity")), force_(particles_->getVariableDataByName("Force")), force_prior_(particles_->getVariableDataByName("ForcePrior")), - h_min_(sph_body.sph_adaptation_->MinimumSmoothingLength()), + h_min_(sph_body.getSPHAdaptation().MinimumSmoothingLength()), speed_ref_(U_ref), advectionCFL_(advectionCFL) {} //=================================================================================================// Real AdvectionTimeStep::reduce(size_t index_i, Real dt) diff --git a/src/shared/particle_dynamics/fluid_dynamics/non_newtonian_dynamics/non_newtonian_dynamics.cpp b/src/shared/particle_dynamics/fluid_dynamics/non_newtonian_dynamics/non_newtonian_dynamics.cpp index a92041fc76..e7d51f1baf 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/non_newtonian_dynamics/non_newtonian_dynamics.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/non_newtonian_dynamics/non_newtonian_dynamics.cpp @@ -94,7 +94,7 @@ void Oldroyd_BIntegration2ndHalf>::update(size_t index_i, Real dt) //=================================================================================================// SRDViscousTimeStepSize::SRDViscousTimeStepSize(SPHBody &sph_body, Real diffusionCFL) : LocalDynamicsReduce(sph_body), - smoothing_length_(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength()), + smoothing_length_(this->sph_body_.getSPHAdaptation().ReferenceSmoothingLength()), rho_(this->particles_->template getVariableDataByName("Density")), mu_srd_(this->particles_->getVariableDataByName("VariableViscosity")), diffusionCFL(diffusionCFL) {} diff --git a/src/shared/particle_dynamics/fluid_dynamics/shape_confinement.cpp b/src/shared/particle_dynamics/fluid_dynamics/shape_confinement.cpp index e02e306f3c..d1593c4cd6 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/shape_confinement.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/shape_confinement.cpp @@ -7,8 +7,8 @@ namespace fluid_dynamics //=================================================================================================// StaticConfinementDensity::StaticConfinementDensity(NearShapeSurface &near_surface) : BaseLocalDynamics(near_surface), - rho0_(sph_body_.base_material_->ReferenceDensity()), - inv_sigma0_(1.0 / sph_body_.sph_adaptation_->LatticeNumberDensity()), + rho0_(sph_body_.getBaseMaterial().ReferenceDensity()), + inv_sigma0_(1.0 / sph_body_.getSPHAdaptation().LatticeNumberDensity()), mass_(particles_->getVariableDataByName("Mass")), rho_sum_(particles_->getVariableDataByName("DensitySummation")), pos_(particles_->getVariableDataByName("Position")), diff --git a/src/shared/particle_dynamics/fluid_dynamics/surface_tension.cpp b/src/shared/particle_dynamics/fluid_dynamics/surface_tension.cpp index 9000e6956a..8ac4670065 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/surface_tension.cpp +++ b/src/shared/particle_dynamics/fluid_dynamics/surface_tension.cpp @@ -16,12 +16,12 @@ SurfaceTensionStress:: particles_->addVariableToWrite("ColorGradient"); particles_->addVariableToSort("SurfaceTensionStress"); particles_->addVariableToWrite("SurfaceTensionStress"); - Real rho0 = getSPHBody().base_material_->ReferenceDensity(); + Real rho0 = getSPHBody().getBaseMaterial().ReferenceDensity(); for (size_t k = 0; k != contact_particles_.size(); ++k) { contact_Vol_.push_back(contact_particles_[k]->getVariableDataByName("VolumetricMeasure")); contact_surface_tension_.push_back(contact_surface_tension[k]); - Real rho0_k = contact_bodies_[k]->base_material_->ReferenceDensity(); + Real rho0_k = contact_bodies_[k]->getBaseMaterial().ReferenceDensity(); contact_fraction_.push_back(rho0 / (rho0 + rho0_k)); } } @@ -71,10 +71,10 @@ void SurfaceStressForce>::interaction(size_t index_i, Real dt) SurfaceStressForce>::SurfaceStressForce(BaseContactRelation &contact_relation) : SurfaceStressForce(contact_relation) { - Real rho0 = getSPHBody().base_material_->ReferenceDensity(); + Real rho0 = getSPHBody().getBaseMaterial().ReferenceDensity(); for (size_t k = 0; k != contact_particles_.size(); ++k) { - Real rho0_k = contact_bodies_[k]->base_material_->ReferenceDensity(); + Real rho0_k = contact_bodies_[k]->getBaseMaterial().ReferenceDensity(); contact_fraction_.push_back(rho0 / (rho0 + rho0_k)); contact_Vol_.push_back(contact_particles_[k]->getVariableDataByName("VolumetricMeasure")); contact_color_gradient_.push_back( diff --git a/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.hpp b/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.hpp index 79485a0297..b531052f93 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.hpp +++ b/src/shared/particle_dynamics/fluid_dynamics/transport_velocity_correction.hpp @@ -23,7 +23,7 @@ template , CommonControlTypes...>:: TransportVelocityCorrection(BaseInnerRelation &inner_relation, Real coefficient) : TransportVelocityCorrection(inner_relation), - h_ref_(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength()), + h_ref_(this->sph_body_.getSPHAdaptation().ReferenceSmoothingLength()), correction_scaling_(coefficient * h_ref_ * h_ref_), Vol_(this->particles_->template getVariableDataByName("VolumetricMeasure")), pos_(this->particles_->template getVariableDataByName("Position")), diff --git a/src/shared/particle_dynamics/fluid_dynamics/viscous_dynamics.hpp b/src/shared/particle_dynamics/fluid_dynamics/viscous_dynamics.hpp index a5a04ec205..445d4266bd 100644 --- a/src/shared/particle_dynamics/fluid_dynamics/viscous_dynamics.hpp +++ b/src/shared/particle_dynamics/fluid_dynamics/viscous_dynamics.hpp @@ -17,7 +17,7 @@ ViscousForce::ViscousForce(BaseRelationType &base_relation) Vol_(this->particles_->template getVariableDataByName("VolumetricMeasure")), vel_(this->particles_->template getVariableDataByName("Velocity")), viscous_force_(this->particles_->template registerStateVariable("ViscousForce")), - smoothing_length_(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength()) {} + smoothing_length_(this->sph_body_.getSPHAdaptation().ReferenceSmoothingLength()) {} //=================================================================================================// template ViscousForce, ViscosityType, KernelCorrectionType>:: diff --git a/src/shared/particle_dynamics/general_dynamics/boundary_condition/eulerian_ghost_boundary.cpp b/src/shared/particle_dynamics/general_dynamics/boundary_condition/eulerian_ghost_boundary.cpp index 6b9688455a..51c207f5cc 100644 --- a/src/shared/particle_dynamics/general_dynamics/boundary_condition/eulerian_ghost_boundary.cpp +++ b/src/shared/particle_dynamics/general_dynamics/boundary_condition/eulerian_ghost_boundary.cpp @@ -71,7 +71,7 @@ GhostBoundaryConditionSetupInESPH:: ghost_bound_(ghost_creation.ghost_bound_), real_and_ghost_particle_data_(ghost_creation.real_and_ghost_particle_data_), boundary_type_(particles_->registerStateVariable("BoundaryType")), - W0_(sph_body_.sph_adaptation_->getKernel()->W0(ZeroVecd)) + W0_(sph_body_.getSPHAdaptation().getKernel()->W0(ZeroVecd)) { setupBoundaryTypes(); } @@ -119,7 +119,7 @@ GhostKernelGradientUpdate::GhostKernelGradientUpdate(BaseInnerRelation &inner_re Vol_(particles_->getVariableDataByName("VolumetricMeasure")), kernel_gradient_original_summation_( particles_->registerStateVariable("KernelGradientOriginalSummation")), - indicator_(particles_->getVariableDataByName("Indicator")){}; + indicator_(particles_->getVariableDataByName("Indicator")) {}; //=================================================================================================// void GhostKernelGradientUpdate::interaction(size_t index_i, Real dt) { diff --git a/src/shared/particle_dynamics/general_dynamics/domian_bouding/domain_bounding.h b/src/shared/particle_dynamics/general_dynamics/domian_bouding/domain_bounding.h index 4b74c470c6..572bb18a72 100644 --- a/src/shared/particle_dynamics/general_dynamics/domian_bouding/domain_bounding.h +++ b/src/shared/particle_dynamics/general_dynamics/domian_bouding/domain_bounding.h @@ -48,7 +48,7 @@ struct PeriodicAlongAxis periodic_translation_[axis] = bounding_bounds.second_[axis] - bounding_bounds.first_[axis]; }; - virtual ~PeriodicAlongAxis(){}; + virtual ~PeriodicAlongAxis() {}; BoundingBox getBoundingBox() { return bounding_bounds_; }; int getAxis() { return axis_; }; Vecd getPeriodicTranslation() { return periodic_translation_; }; @@ -74,7 +74,7 @@ class BasePeriodicCondition cell_linked_list.tagBoundingCells(bound_cells_data_, periodic_box.getBoundingBox(), periodic_box.getAxis()); }; - virtual ~BasePeriodicCondition(){}; + virtual ~BasePeriodicCondition() {}; protected: StdVec bound_cells_data_; @@ -111,10 +111,10 @@ class BasePeriodicCondition : LocalDynamics(real_body), BaseDynamics(), bounding_bounds_(periodic_box.getBoundingBox()), axis_(periodic_box.getAxis()), periodic_translation_(periodic_box.getPeriodicTranslation()), - cut_off_radius_max_(real_body.sph_adaptation_->getKernel()->CutOffRadius()), + cut_off_radius_max_(real_body.getSPHAdaptation().getKernel()->CutOffRadius()), bound_cells_data_(bound_cells_data), - pos_(particles_->getVariableDataByName("Position")){}; - virtual ~PeriodicBounding(){}; + pos_(particles_->getVariableDataByName("Position")) {}; + virtual ~PeriodicBounding() {}; virtual void exec(Real dt = 0.0) override { @@ -154,7 +154,7 @@ class PeriodicConditionUsingCellLinkedList : public BasePeriodicCondition &bound_cells_data, RealBody &real_body, PeriodicAlongAxis &periodic_box); - virtual ~PeriodicCellLinkedList(){}; + virtual ~PeriodicCellLinkedList() {}; virtual void exec(Real dt = 0.0) override; }; @@ -164,7 +164,7 @@ class PeriodicConditionUsingCellLinkedList : public BasePeriodicCondition(near_shape_surface), pos_(particles_->getVariableDataByName("Position")), - constrained_distance_(0.5 * sph_body_.sph_adaptation_->MinimumSpacing()) + constrained_distance_(0.5 * sph_body_.getSPHAdaptation().MinimumSpacing()) { level_set_shape_ = &near_shape_surface.getLevelSetShape(); } diff --git a/src/shared/particle_dynamics/general_dynamics/particle_smoothing.hpp b/src/shared/particle_dynamics/general_dynamics/particle_smoothing.hpp index 60416d74dd..7d215a303b 100644 --- a/src/shared/particle_dynamics/general_dynamics/particle_smoothing.hpp +++ b/src/shared/particle_dynamics/general_dynamics/particle_smoothing.hpp @@ -10,7 +10,7 @@ template ParticleSmoothing:: ParticleSmoothing(BaseInnerRelation &inner_relation, const std::string &variable_name) : LocalDynamics(inner_relation.getSPHBody()), DataDelegateInner(inner_relation), - W0_(sph_body_.sph_adaptation_->getKernel()->W0(ZeroVecd)), + W0_(sph_body_.getSPHAdaptation().getKernel()->W0(ZeroVecd)), smoothed_(particles_->template getVariableDataByName(variable_name)), temp_(particles_->registerStateVariable(variable_name + "_temp")) {} //=================================================================================================// diff --git a/src/shared/particle_dynamics/general_dynamics/surface_indication/surface_indication.cpp b/src/shared/particle_dynamics/general_dynamics/surface_indication/surface_indication.cpp index df7de2fd72..ab1d7535fe 100644 --- a/src/shared/particle_dynamics/general_dynamics/surface_indication/surface_indication.cpp +++ b/src/shared/particle_dynamics/general_dynamics/surface_indication/surface_indication.cpp @@ -6,7 +6,7 @@ namespace SPH FreeSurfaceIndication>:: FreeSurfaceIndication(BaseInnerRelation &inner_relation) : FreeSurfaceIndication(inner_relation), - smoothing_length_(inner_relation.getSPHBody().sph_adaptation_->ReferenceSmoothingLength()) {} + smoothing_length_(inner_relation.getSPHBody().getSPHAdaptation().ReferenceSmoothingLength()) {} //=================================================================================================// void FreeSurfaceIndication>::interaction(size_t index_i, Real dt) { diff --git a/src/shared/particle_dynamics/relax_dynamics/base_relax_dynamics.cpp b/src/shared/particle_dynamics/relax_dynamics/base_relax_dynamics.cpp index 46f9d04d7a..c088ab1036 100644 --- a/src/shared/particle_dynamics/relax_dynamics/base_relax_dynamics.cpp +++ b/src/shared/particle_dynamics/relax_dynamics/base_relax_dynamics.cpp @@ -8,7 +8,7 @@ namespace relax_dynamics RandomizeParticlePosition::RandomizeParticlePosition(SPHBody &sph_body) : LocalDynamics(sph_body), pos_(particles_->getVariableDataByName("Position")), - randomize_scale_(sph_body.sph_adaptation_->MinimumSpacing()) {} + randomize_scale_(sph_body.getSPHAdaptation().MinimumSpacing()) {} //=================================================================================================// void RandomizeParticlePosition::update(size_t index_i, Real dt) { diff --git a/src/shared/particle_dynamics/relax_dynamics/relax_stepping.cpp b/src/shared/particle_dynamics/relax_dynamics/relax_stepping.cpp index efcb34eda4..0101e137a4 100644 --- a/src/shared/particle_dynamics/relax_dynamics/relax_stepping.cpp +++ b/src/shared/particle_dynamics/relax_dynamics/relax_stepping.cpp @@ -53,7 +53,7 @@ void RelaxationResidue>::interaction(size_t index_i, Real dt) RelaxationScaling::RelaxationScaling(SPHBody &sph_body) : LocalDynamicsReduce(sph_body), residue_(particles_->getVariableDataByName("ZeroOrderResidue")), - h_ref_(sph_body.sph_adaptation_->ReferenceSmoothingLength()) {} + h_ref_(sph_body.getSPHAdaptation().ReferenceSmoothingLength()) {} //=================================================================================================// Real RelaxationScaling::reduce(size_t index_i, Real dt) { @@ -67,7 +67,7 @@ Real RelaxationScaling::outputResult(Real reduced_value) //=================================================================================================// PositionRelaxation::PositionRelaxation(SPHBody &sph_body) : LocalDynamics(sph_body), - sph_adaptation_(sph_body.sph_adaptation_), + sph_adaptation_(&sph_body.getSPHAdaptation()), pos_(particles_->getVariableDataByName("Position")), residue_(particles_->getVariableDataByName("ZeroOrderResidue")) {} //=================================================================================================// @@ -83,7 +83,7 @@ UpdateSmoothingLengthRatioByShape:: Vol_(particles_->getVariableDataByName("VolumetricMeasure")), pos_(particles_->getVariableDataByName("Position")), target_shape_(target_shape), - particle_adaptation_(DynamicCast(this, sph_body.sph_adaptation_)), + particle_adaptation_(DynamicCast(this, &sph_body.getSPHAdaptation())), reference_spacing_(particle_adaptation_->ReferenceSpacing()) {} //=================================================================================================// UpdateSmoothingLengthRatioByShape::UpdateSmoothingLengthRatioByShape(SPHBody &sph_body) diff --git a/src/shared/particle_dynamics/relax_dynamics/relax_stepping.hpp b/src/shared/particle_dynamics/relax_dynamics/relax_stepping.hpp index 51c9761532..0ccc627651 100644 --- a/src/shared/particle_dynamics/relax_dynamics/relax_stepping.hpp +++ b/src/shared/particle_dynamics/relax_dynamics/relax_stepping.hpp @@ -12,7 +12,7 @@ template template RelaxationResidue::RelaxationResidue(BaseRelationType &base_relation) : LocalDynamics(base_relation.getSPHBody()), DataDelegationType(base_relation), - sph_adaptation_(this->sph_body_.sph_adaptation_), + sph_adaptation_(&this->sph_body_.getSPHAdaptation()), Vol_(this->particles_->template getVariableDataByName("VolumetricMeasure")), residue_(this->particles_->template registerStateVariable("ZeroOrderResidue")) {} //=================================================================================================// diff --git a/src/shared/particle_dynamics/relax_dynamics/relax_thick_shell.cpp b/src/shared/particle_dynamics/relax_dynamics/relax_thick_shell.cpp index 6892467244..18ed6d12e8 100644 --- a/src/shared/particle_dynamics/relax_dynamics/relax_thick_shell.cpp +++ b/src/shared/particle_dynamics/relax_dynamics/relax_thick_shell.cpp @@ -8,8 +8,8 @@ namespace relax_dynamics ShellMidSurfaceBounding::ShellMidSurfaceBounding(NearShapeSurface &body_part) : BaseLocalDynamics(body_part), pos_(particles_->getVariableDataByName("Position")), - constrained_distance_(0.5 * sph_body_.sph_adaptation_->MinimumSpacing()), - particle_spacing_ref_(sph_body_.sph_adaptation_->MinimumSpacing()), + constrained_distance_(0.5 * sph_body_.getSPHAdaptation().MinimumSpacing()), + particle_spacing_ref_(sph_body_.getSPHAdaptation().MinimumSpacing()), level_set_shape_(DynamicCast(this, &sph_body_.getInitialShape())) {} //=================================================================================================// void ShellMidSurfaceBounding::update(size_t index_i, Real dt) @@ -160,7 +160,7 @@ bool ShellNormalDirectionPrediction::ConsistencyUpdatedCheck::reduce(size_t inde //=================================================================================================// ShellNormalDirectionPrediction::SmoothingNormal:: SmoothingNormal(BaseInnerRelation &inner_relation) - : ParticleSmoothing(inner_relation, "NormalDirection"){}; + : ParticleSmoothing(inner_relation, "NormalDirection") {}; //=================================================================================================// void ShellNormalDirectionPrediction::SmoothingNormal::update(size_t index_i, Real dt) { diff --git a/src/shared/particle_dynamics/solid_dynamics/contact_dynamics/repulsion_factor_summation.cpp b/src/shared/particle_dynamics/solid_dynamics/contact_dynamics/repulsion_factor_summation.cpp index 2830a73564..2b5bfb5c0a 100644 --- a/src/shared/particle_dynamics/solid_dynamics/contact_dynamics/repulsion_factor_summation.cpp +++ b/src/shared/particle_dynamics/solid_dynamics/contact_dynamics/repulsion_factor_summation.cpp @@ -9,8 +9,8 @@ RepulsionFactorSummation>:: RepulsionFactorSummation(SelfSurfaceContactRelation &self_contact_relation) : RepulsionFactorSummation(self_contact_relation, "SelfRepulsionFactor") { - Real dp_1 = self_contact_relation.getSPHBody().sph_adaptation_->ReferenceSpacing(); - offset_W_ij_ = self_contact_relation.getSPHBody().sph_adaptation_->getKernel()->W(dp_1, ZeroVecd); + Real dp_1 = self_contact_relation.getSPHBody().getSPHAdaptation().ReferenceSpacing(); + offset_W_ij_ = self_contact_relation.getSPHBody().getSPHAdaptation().getKernel()->W(dp_1, ZeroVecd); } //=================================================================================================// void RepulsionFactorSummation>::interaction(size_t index_i, Real dt) @@ -48,12 +48,12 @@ void RepulsionFactorSummation>::interaction(size_t index_i, Real dt) ShellContactFactor::ShellContactFactor(ShellSurfaceContactRelation &solid_body_contact_relation) : RepulsionFactorSummation(solid_body_contact_relation, "RepulsionFactor"), solid_(DynamicCast(this, sph_body_.getBaseMaterial())), - kernel_(solid_body_contact_relation.getSPHBody().sph_adaptation_->getKernel()), - particle_spacing_(solid_body_contact_relation.getSPHBody().sph_adaptation_->ReferenceSpacing()) + kernel_(solid_body_contact_relation.getSPHBody().getSPHAdaptation().getKernel()), + particle_spacing_(solid_body_contact_relation.getSPHBody().getSPHAdaptation().ReferenceSpacing()) { for (size_t k = 0; k != contact_particles_.size(); ++k) { - Real dp_k = solid_body_contact_relation.contact_bodies_[k]->sph_adaptation_->ReferenceSpacing(); + Real dp_k = solid_body_contact_relation.contact_bodies_[k]->getSPHAdaptation().ReferenceSpacing(); Real average_spacing_k = 0.5 * particle_spacing_ + 0.5 * dp_k; Real h_ratio_k = particle_spacing_ / average_spacing_k; offset_W_ij_.push_back(kernel_->W(h_ratio_k, average_spacing_k, ZeroVecd)); diff --git a/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.cpp b/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.cpp index eec0502816..49c654c963 100644 --- a/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.cpp +++ b/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.cpp @@ -15,7 +15,7 @@ AcousticTimeStep::AcousticTimeStep(SPHBody &sph_body, Real CFL) force_(particles_->getVariableDataByName("Force")), force_prior_(particles_->getVariableDataByName("ForcePrior")), mass_(particles_->getVariableDataByName("Mass")), - smoothing_length_min_(sph_body.sph_adaptation_->MinimumSmoothingLength()), + smoothing_length_min_(sph_body.getSPHAdaptation().MinimumSmoothingLength()), c0_(elastic_solid_.ReferenceSoundSpeed()) {} //=================================================================================================// Real AcousticTimeStep::reduce(size_t index_i, Real dt) @@ -76,7 +76,7 @@ BaseIntegration1stHalf:: rho_(particles_->getVariableDataByName("Density")), mass_(particles_->getVariableDataByName("Mass")), force_prior_(particles_->registerStateVariable("ForcePrior")), - smoothing_length_(sph_body_.sph_adaptation_->ReferenceSmoothingLength()) {} + smoothing_length_(sph_body_.getSPHAdaptation().ReferenceSmoothingLength()) {} //=================================================================================================// void BaseIntegration1stHalf::update(size_t index_i, Real dt) { @@ -89,7 +89,7 @@ Integration1stHalf::Integration1stHalf(BaseInnerRelation &inner_relation) numerical_dissipation_factor_(0.25) {} //=================================================================================================// Integration1stHalfPK2::Integration1stHalfPK2(BaseInnerRelation &inner_relation) - : Integration1stHalf(inner_relation){}; + : Integration1stHalf(inner_relation) {}; //=================================================================================================// void Integration1stHalfPK2::initialization(size_t index_i, Real dt) { @@ -103,7 +103,7 @@ void Integration1stHalfPK2::initialization(size_t index_i, Real dt) //=================================================================================================// Integration1stHalfKirchhoff:: Integration1stHalfKirchhoff(BaseInnerRelation &inner_relation) - : Integration1stHalf(inner_relation){}; + : Integration1stHalf(inner_relation) {}; //=================================================================================================// void Integration1stHalfKirchhoff::initialization(size_t index_i, Real dt) { diff --git a/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.h b/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.h index 8d2a9ff31a..bd5cd5d2d9 100644 --- a/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.h +++ b/src/shared/particle_dynamics/solid_dynamics/elastic_dynamics.h @@ -50,7 +50,7 @@ class ElasticDynamicsInitialCondition : public LocalDynamics { public: explicit ElasticDynamicsInitialCondition(SPHBody &sph_body); - virtual ~ElasticDynamicsInitialCondition(){}; + virtual ~ElasticDynamicsInitialCondition() {}; protected: Vecd *pos_, *vel_; @@ -70,7 +70,7 @@ class UpdateElasticNormalDirection : public LocalDynamics public: explicit UpdateElasticNormalDirection(SPHBody &sph_body); - virtual ~UpdateElasticNormalDirection(){}; + virtual ~UpdateElasticNormalDirection() {}; void update(size_t index_i, Real dt = 0.0); }; @@ -91,7 +91,7 @@ class AcousticTimeStep : public LocalDynamicsReduce public: explicit AcousticTimeStep(SPHBody &sph_body, Real CFL = 0.6); - virtual ~AcousticTimeStep(){}; + virtual ~AcousticTimeStep() {}; Real reduce(size_t index_i, Real dt = 0.0); }; @@ -104,7 +104,7 @@ class DeformationGradientBySummation : public LocalDynamics, public DataDelegate { public: explicit DeformationGradientBySummation(BaseInnerRelation &inner_relation); - virtual ~DeformationGradientBySummation(){}; + virtual ~DeformationGradientBySummation() {}; inline void interaction(size_t index_i, Real dt = 0.0) { @@ -137,7 +137,7 @@ class BaseElasticIntegration : public LocalDynamics, public DataDelegateInner { public: explicit BaseElasticIntegration(BaseInnerRelation &inner_relation); - virtual ~BaseElasticIntegration(){}; + virtual ~BaseElasticIntegration() {}; protected: Real *Vol_; @@ -154,7 +154,7 @@ class BaseIntegration1stHalf : public BaseElasticIntegration { public: explicit BaseIntegration1stHalf(BaseInnerRelation &inner_relation); - virtual ~BaseIntegration1stHalf(){}; + virtual ~BaseIntegration1stHalf() {}; void update(size_t index_i, Real dt = 0.0); protected: @@ -174,7 +174,7 @@ class Integration1stHalf : public BaseIntegration1stHalf { public: explicit Integration1stHalf(BaseInnerRelation &inner_relation); - virtual ~Integration1stHalf(){}; + virtual ~Integration1stHalf() {}; inline void interaction(size_t index_i, Real dt = 0.0) { @@ -205,7 +205,7 @@ class Integration1stHalf : public BaseIntegration1stHalf protected: Matd *stress_PK1_B_; Real numerical_dissipation_factor_; - Real inv_W0_ = 1.0 / sph_body_.sph_adaptation_->getKernel()->W0(ZeroVecd); + Real inv_W0_ = 1.0 / sph_body_.getSPHAdaptation().getKernel()->W0(ZeroVecd); }; /** @@ -216,7 +216,7 @@ class Integration1stHalfPK2 : public Integration1stHalf { public: explicit Integration1stHalfPK2(BaseInnerRelation &inner_relation); - virtual ~Integration1stHalfPK2(){}; + virtual ~Integration1stHalfPK2() {}; void initialization(size_t index_i, Real dt = 0.0); }; @@ -227,7 +227,7 @@ class Integration1stHalfCauchy : public Integration1stHalf { public: explicit Integration1stHalfCauchy(BaseInnerRelation &inner_relation); - virtual ~Integration1stHalfCauchy(){}; + virtual ~Integration1stHalfCauchy() {}; void initialization(size_t index_i, Real dt = 0.0); }; @@ -239,7 +239,7 @@ class Integration1stHalfKirchhoff : public Integration1stHalf { public: explicit Integration1stHalfKirchhoff(BaseInnerRelation &inner_relation); - virtual ~Integration1stHalfKirchhoff(){}; + virtual ~Integration1stHalfKirchhoff() {}; void initialization(size_t index_i, Real dt = 0.0); }; @@ -262,7 +262,7 @@ class DecomposedIntegration1stHalf : public BaseIntegration1stHalf { public: explicit DecomposedIntegration1stHalf(BaseInnerRelation &inner_relation); - virtual ~DecomposedIntegration1stHalf(){}; + virtual ~DecomposedIntegration1stHalf() {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) @@ -297,7 +297,7 @@ class Integration1stHalfPK2RightCauchy : public Integration1stHalfPK2 public: explicit Integration1stHalfPK2RightCauchy(BaseInnerRelation &inner_relation) : Integration1stHalfPK2(inner_relation), - h_ratio_(particles_->registerStateVariable("SmoothingLengthRatio", Real(1.0))){}; + h_ratio_(particles_->registerStateVariable("SmoothingLengthRatio", Real(1.0))) {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) { @@ -328,8 +328,8 @@ class Integration2ndHalf : public BaseElasticIntegration { public: explicit Integration2ndHalf(BaseInnerRelation &inner_relation) - : BaseElasticIntegration(inner_relation){}; - virtual ~Integration2ndHalf(){}; + : BaseElasticIntegration(inner_relation) {}; + virtual ~Integration2ndHalf() {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) diff --git a/src/shared/particle_dynamics/solid_dynamics/fluid_structure_interaction.cpp b/src/shared/particle_dynamics/solid_dynamics/fluid_structure_interaction.cpp index 0c14ad6447..2563effa04 100644 --- a/src/shared/particle_dynamics/solid_dynamics/fluid_structure_interaction.cpp +++ b/src/shared/particle_dynamics/solid_dynamics/fluid_structure_interaction.cpp @@ -30,7 +30,7 @@ ViscousForceFromFluid::ViscousForceFromFluid(BaseContactRelation &contact_relati contact_Vol_.push_back(contact_particles_[k]->getVariableDataByName("VolumetricMeasure")); Viscosity &viscosity_k = DynamicCast(this, contact_particles_[k]->getBaseMaterial()); mu_.push_back(viscosity_k.ReferenceViscosity()); - smoothing_length_.push_back(contact_bodies_[k]->sph_adaptation_->ReferenceSmoothingLength()); + smoothing_length_.push_back(contact_bodies_[k]->getSPHAdaptation().ReferenceSmoothingLength()); } } //=================================================================================================// diff --git a/src/shared/particle_dynamics/solid_dynamics/general_solid_dynamics.cpp b/src/shared/particle_dynamics/solid_dynamics/general_solid_dynamics.cpp index b8d6e6a8ea..87ce10f0fb 100644 --- a/src/shared/particle_dynamics/solid_dynamics/general_solid_dynamics.cpp +++ b/src/shared/particle_dynamics/solid_dynamics/general_solid_dynamics.cpp @@ -31,8 +31,8 @@ DistributingPointForces:: //=================================================================================================// void DistributingPointForces::getWeight() { - Kernel *kernel_ = sph_body_.sph_adaptation_->getKernel(); - Real reference_smoothing_length = sph_body_.sph_adaptation_->ReferenceSmoothingLength(); + Kernel *kernel_ = sph_body_.getSPHAdaptation().getKernel(); + Real reference_smoothing_length = sph_body_.getSPHAdaptation().ReferenceSmoothingLength(); Real smoothing_length = h_spacing_ratio_ * particle_spacing_ref_; Real h_ratio = reference_smoothing_length / smoothing_length; Real cutoff_radius_sqr = pow(2.0 * smoothing_length, 2); diff --git a/src/shared/particle_dynamics/solid_dynamics/solid_dynamics_variable.cpp b/src/shared/particle_dynamics/solid_dynamics/solid_dynamics_variable.cpp index b4516f229c..0320be1d06 100644 --- a/src/shared/particle_dynamics/solid_dynamics/solid_dynamics_variable.cpp +++ b/src/shared/particle_dynamics/solid_dynamics/solid_dynamics_variable.cpp @@ -48,7 +48,7 @@ void GreenLagrangeStrain::update(size_t index_i, Real dt) //=============================================================================================// VonMisesStress::VonMisesStress(SPHBody &sph_body) : BaseDerivedVariable(sph_body, "VonMisesStress"), - rho0_(sph_body_.base_material_->ReferenceDensity()), + rho0_(sph_body_.getBaseMaterial().ReferenceDensity()), rho_(particles_->getVariableDataByName("Density")), F_(particles_->getVariableDataByName("DeformationGradient")), elastic_solid_(DynamicCast(this, sph_body_.getBaseMaterial())) {} diff --git a/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.cpp b/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.cpp index fd3d49664c..6e880e3368 100644 --- a/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.cpp +++ b/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.cpp @@ -34,7 +34,7 @@ ShellAcousticTimeStepSize::ShellAcousticTimeStepSize(SPHBody &sph_body, Real CFL E0_(elastic_solid_.YoungsModulus()), nu_(elastic_solid_.PoissonRatio()), c0_(elastic_solid_.ReferenceSoundSpeed()), - smoothing_length_(sph_body.sph_adaptation_->ReferenceSmoothingLength()) {} + smoothing_length_(sph_body.getSPHAdaptation().ReferenceSmoothingLength()) {} //=================================================================================================// Real ShellAcousticTimeStepSize::reduce(size_t index_i, Real dt) { @@ -100,7 +100,7 @@ ShellStressRelaxationFirstHalf:: elastic_solid_(DynamicCast(this, sph_body_.getBaseMaterial())), rho0_(elastic_solid_.ReferenceDensity()), inv_rho0_(1.0 / rho0_), - smoothing_length_(sph_body_.sph_adaptation_->ReferenceSmoothingLength()), + smoothing_length_(sph_body_.getSPHAdaptation().ReferenceSmoothingLength()), numerical_damping_scaling_matrix_(Matd::Identity() * smoothing_length_), rho_(particles_->getVariableDataByName("Density")), mass_(particles_->getVariableDataByName("Mass")), @@ -278,7 +278,7 @@ InitialShellCurvature::InitialShellCurvature(BaseInnerRelation &inner_relation) F_bending_(particles_->getVariableDataByName("BendingDeformationGradient")), k1_(particles_->registerStateVariable("1stPrincipleCurvature")), k2_(particles_->registerStateVariable("2ndPrincipleCurvature")), - dn_0_(particles_->registerStateVariable("InitialNormalGradient")){}; + dn_0_(particles_->registerStateVariable("InitialNormalGradient")) {}; //=================================================================================================// void InitialShellCurvature::update(size_t index_i, Real) { @@ -306,7 +306,7 @@ ShellCurvatureUpdate::ShellCurvatureUpdate(SPHBody &sph_body) F_bending_(particles_->getVariableDataByName("BendingDeformationGradient")), k1_(particles_->registerStateVariable("1stPrincipleCurvature")), k2_(particles_->registerStateVariable("2ndPrincipleCurvature")), - dn_0_(particles_->registerStateVariable("InitialNormalGradient")){}; + dn_0_(particles_->registerStateVariable("InitialNormalGradient")) {}; //=================================================================================================// void ShellCurvatureUpdate::update(size_t index_i, Real) { @@ -324,7 +324,7 @@ AverageShellCurvature::AverageShellCurvature(BaseInnerRelation &inner_relation) Vol_(particles_->getVariableDataByName("VolumetricMeasure")), n_(particles_->getVariableDataByName("NormalDirection")), k1_ave_(particles_->registerStateVariable("Average1stPrincipleCurvature")), - k2_ave_(particles_->registerStateVariable("Average2ndPrincipleCurvature")){}; + k2_ave_(particles_->registerStateVariable("Average2ndPrincipleCurvature")) {}; //=================================================================================================// void AverageShellCurvature::update(size_t index_i, Real) { diff --git a/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.h b/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.h index a8f0f4faa0..c41dfd9693 100644 --- a/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.h +++ b/src/shared/particle_dynamics/solid_dynamics/thin_structure_dynamics.h @@ -54,7 +54,7 @@ class UpdateShellNormalDirection : public LocalDynamics public: explicit UpdateShellNormalDirection(SPHBody &sph_body); - virtual ~UpdateShellNormalDirection(){}; + virtual ~UpdateShellNormalDirection() {}; void update(size_t index_i, Real dt = 0.0); }; @@ -75,7 +75,7 @@ class ShellAcousticTimeStepSize : public LocalDynamicsReduce public: explicit ShellAcousticTimeStepSize(SPHBody &sph_body, Real CFL = 0.6); - virtual ~ShellAcousticTimeStepSize(){}; + virtual ~ShellAcousticTimeStepSize() {}; Real reduce(size_t index_i, Real dt = 0.0); }; @@ -88,7 +88,7 @@ class ShellCorrectConfiguration : public LocalDynamics, public DataDelegateInner { public: explicit ShellCorrectConfiguration(BaseInnerRelation &inner_relation); - virtual ~ShellCorrectConfiguration(){}; + virtual ~ShellCorrectConfiguration() {}; inline void interaction(size_t index_i, Real dt = 0.0) { @@ -124,7 +124,7 @@ class ShellDeformationGradientTensor : public LocalDynamics, public DataDelegate { public: explicit ShellDeformationGradientTensor(BaseInnerRelation &inner_relation); - virtual ~ShellDeformationGradientTensor(){}; + virtual ~ShellDeformationGradientTensor() {}; inline void interaction(size_t index_i, Real dt = 0.0) { @@ -162,7 +162,7 @@ class BaseShellRelaxation : public LocalDynamics, public DataDelegateInner { public: explicit BaseShellRelaxation(BaseInnerRelation &inner_relation); - virtual ~BaseShellRelaxation(){}; + virtual ~BaseShellRelaxation() {}; protected: Real *thickness_, *Vol_; @@ -183,7 +183,7 @@ class ShellStressRelaxationFirstHalf : public BaseShellRelaxation public: explicit ShellStressRelaxationFirstHalf(BaseInnerRelation &inner_relation, int number_of_gaussian_points = 3, bool hourglass_control = false, Real hourglass_control_factor = 0.002); - virtual ~ShellStressRelaxationFirstHalf(){}; + virtual ~ShellStressRelaxationFirstHalf() {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) @@ -243,7 +243,7 @@ class ShellStressRelaxationFirstHalf : public BaseShellRelaxation Matd *global_F_, *global_F_bending_; Real E0_, G0_, nu_, hourglass_control_factor_; bool hourglass_control_; - const Real inv_W0_ = 1.0 / sph_body_.sph_adaptation_->getKernel()->W0(ZeroVecd); + const Real inv_W0_ = 1.0 / sph_body_.getSPHAdaptation().getKernel()->W0(ZeroVecd); const Real shear_correction_factor_ = 5.0 / 6.0; const StdVec one_gaussian_point_ = {0.0}; @@ -266,8 +266,8 @@ class ShellStressRelaxationSecondHalf : public BaseShellRelaxation { public: explicit ShellStressRelaxationSecondHalf(BaseInnerRelation &inner_relation) - : BaseShellRelaxation(inner_relation){}; - virtual ~ShellStressRelaxationSecondHalf(){}; + : BaseShellRelaxation(inner_relation) {}; + virtual ~ShellStressRelaxationSecondHalf() {}; void initialization(size_t index_i, Real dt = 0.0); inline void interaction(size_t index_i, Real dt = 0.0) @@ -302,7 +302,7 @@ class ConstrainShellBodyRegion : public BaseLocalDynamics { public: ConstrainShellBodyRegion(BodyPartByParticle &body_part); - virtual ~ConstrainShellBodyRegion(){}; + virtual ~ConstrainShellBodyRegion() {}; void update(size_t index_i, Real dt = 0.0); protected: @@ -318,7 +318,7 @@ class ConstrainShellBodyRegionAlongAxis : public BaseLocalDynamics:: ParticleGenerator(SPHBody &sph_body, BaseParticles &base_particles) : base_particles_(base_particles), - particle_spacing_ref_(sph_body.sph_adaptation_->ReferenceSpacing()) {} + particle_spacing_ref_(sph_body.getSPHAdaptation().ReferenceSpacing()) {} //=================================================================================================// void ParticleGenerator::addParticlePosition(const Vecd &position) { diff --git a/src/shared/particle_generator/particle_generator_lattice.cpp b/src/shared/particle_generator/particle_generator_lattice.cpp index 945ddf6e63..9fd2edcb4d 100644 --- a/src/shared/particle_generator/particle_generator_lattice.cpp +++ b/src/shared/particle_generator/particle_generator_lattice.cpp @@ -8,7 +8,7 @@ namespace SPH { //=================================================================================================// GeneratingMethod::GeneratingMethod(SPHBody &sph_body) - : lattice_spacing_(sph_body.sph_adaptation_->ReferenceSpacing()), + : lattice_spacing_(sph_body.getSPHAdaptation().ReferenceSpacing()), domain_bounds_(sph_body.getSPHSystemBounds()), initial_shape_(sph_body.getInitialShape()) { @@ -29,7 +29,7 @@ ParticleGenerator:: ParticleGenerator(SPHBody &sph_body, BaseParticles &base_particles, Shape &target_shape) : ParticleGenerator(sph_body, base_particles), target_shape_(target_shape), - particle_adaptation_(DynamicCast(this, sph_body.sph_adaptation_)) + particle_adaptation_(DynamicCast(this, &sph_body.getSPHAdaptation())) { lattice_spacing_ = particle_adaptation_->MinimumSpacing(); } @@ -55,7 +55,7 @@ ParticleGenerator:: ParticleGenerator(SPHBody &sph_body, SurfaceParticles &surface_particles, Real thickness) : ParticleGenerator(sph_body, surface_particles), GeneratingMethod(sph_body), total_volume_(0), thickness_(thickness), - particle_spacing_(sph_body.sph_adaptation_->ReferenceSpacing()), + particle_spacing_(sph_body.getSPHAdaptation().ReferenceSpacing()), avg_particle_volume_(pow(particle_spacing_, Dimensions - 1) * thickness_), all_cells_(0), planned_number_of_particles_(0) { diff --git a/src/shared/particle_neighborhood/neighborhood.cpp b/src/shared/particle_neighborhood/neighborhood.cpp index 0e584c7a61..9d94ebcd29 100644 --- a/src/shared/particle_neighborhood/neighborhood.cpp +++ b/src/shared/particle_neighborhood/neighborhood.cpp @@ -73,13 +73,13 @@ void NeighborBuilder::initializeNeighbor(Neighborhood &neighborhood, const Real //=================================================================================================// Kernel *NeighborBuilder::chooseKernel(SPHBody &body, SPHBody &target_body) { - Kernel *kernel = body.sph_adaptation_->getKernel(); - Kernel *target_kernel = target_body.sph_adaptation_->getKernel(); + Kernel *kernel = body.getSPHAdaptation().getKernel(); + Kernel *target_kernel = target_body.getSPHAdaptation().getKernel(); return kernel->SmoothingLength() > target_kernel->SmoothingLength() ? kernel : target_kernel; } //=================================================================================================// NeighborBuilderInner::NeighborBuilderInner(SPHBody &body) - : NeighborBuilder(body.sph_adaptation_->getKernel()) {} + : NeighborBuilder(body.getSPHAdaptation().getKernel()) {} //=================================================================================================// void NeighborBuilderInner::operator()(Neighborhood &neighborhood, const Vecd &pos_i, size_t index_i, const ListData &list_data_j) @@ -98,7 +98,7 @@ void NeighborBuilderInner::operator()(Neighborhood &neighborhood, //=================================================================================================// NeighborBuilderInnerAdaptive:: NeighborBuilderInnerAdaptive(SPHBody &body) - : NeighborBuilder(body.sph_adaptation_->getKernel()), + : NeighborBuilder(body.getSPHAdaptation().getKernel()), h_ratio_(body.getBaseParticles().getVariableDataByName("SmoothingLengthRatio")) {} //=================================================================================================// void NeighborBuilderInnerAdaptive:: @@ -121,7 +121,7 @@ operator()(Neighborhood &neighborhood, const Vecd &pos_i, size_t index_i, const //=================================================================================================// NeighborBuilderSelfContact:: NeighborBuilderSelfContact(SPHBody &body) - : NeighborBuilder(body.sph_adaptation_->getKernel()), + : NeighborBuilder(body.getSPHAdaptation().getKernel()), pos0_(body.getBaseParticles().registerStateVariableFrom("InitialPosition", "Position")) {} //=================================================================================================// void NeighborBuilderSelfContact::operator()(Neighborhood &neighborhood, @@ -161,8 +161,8 @@ void NeighborBuilderContact::operator()(Neighborhood &neighborhood, NeighborBuilderSurfaceContact::NeighborBuilderSurfaceContact(SPHBody &body, SPHBody &contact_body) : NeighborBuilderContact(body, contact_body) { - Real source_smoothing_length = body.sph_adaptation_->ReferenceSmoothingLength(); - Real target_smoothing_length = contact_body.sph_adaptation_->ReferenceSmoothingLength(); + Real source_smoothing_length = body.getSPHAdaptation().ReferenceSmoothingLength(); + Real target_smoothing_length = contact_body.getSPHAdaptation().ReferenceSmoothingLength(); kernel_ = kernel_keeper_.createPtr(0.5 * (source_smoothing_length + target_smoothing_length)); } //=================================================================================================// @@ -195,8 +195,8 @@ void NeighborBuilderContactBodyPart::operator()(Neighborhood &neighborhood, } //=================================================================================================// NeighborBuilderContactAdaptive::NeighborBuilderContactAdaptive(SPHBody &body, SPHBody &contact_body) - : NeighborBuilder(body.sph_adaptation_->getKernel()), adaptation_(*body.sph_adaptation_), - contact_adaptation_(*contact_body.sph_adaptation_), + : NeighborBuilder(body.getSPHAdaptation().getKernel()), adaptation_(body.getSPHAdaptation()), + contact_adaptation_(contact_body.getSPHAdaptation()), relative_h_ref_(adaptation_.ReferenceSmoothingLength() / contact_adaptation_.ReferenceSmoothingLength()) {} //=================================================================================================// @@ -220,7 +220,7 @@ void NeighborBuilderContactAdaptive::operator()(Neighborhood &neighborhood, } //=================================================================================================// BaseNeighborBuilderContactShell::BaseNeighborBuilderContactShell(SPHBody &shell_body) - : NeighborBuilder(shell_body.sph_adaptation_->getKernel()), + : NeighborBuilder(shell_body.getSPHAdaptation().getKernel()), n_(shell_body.getBaseParticles().getVariableDataByName("NormalDirection")), thickness_(shell_body.getBaseParticles().getVariableDataByName("Thickness")), k1_ave_(shell_body.getBaseParticles().registerStateVariable("Average1stPrincipleCurvature")), @@ -317,11 +317,11 @@ void BaseNeighborBuilderContactFromShell::update_neighbors(Neighborhood &neighbo NeighborBuilderContactFromShellToFluid::NeighborBuilderContactFromShellToFluid(SPHBody &body, SPHBody &contact_body, bool normal_correction) : BaseNeighborBuilderContactFromShell(body, contact_body, normal_correction) { - Real fluid_reference_spacing = body.sph_adaptation_->ReferenceSpacing(); - Real shell_reference_spacing = contact_body.sph_adaptation_->ReferenceSpacing(); + Real fluid_reference_spacing = body.getSPHAdaptation().ReferenceSpacing(); + Real shell_reference_spacing = contact_body.getSPHAdaptation().ReferenceSpacing(); if (fluid_reference_spacing < shell_reference_spacing) throw std::runtime_error("NeighborBuilderContactToShell: fluid spacing should be larger or equal than shell spacing..."); - kernel_ = body.sph_adaptation_->getKernel(); + kernel_ = body.getSPHAdaptation().getKernel(); } //=================================================================================================// NeighborBuilderContactFromFluidToShell::NeighborBuilderContactFromFluidToShell(SPHBody &body, SPHBody &contact_body, bool normal_correction) @@ -394,7 +394,7 @@ void NeighborBuilderContactFromFluidToShell::operator()(Neighborhood &neighborho ShellNeighborBuilderInnerWithContactKernel::ShellNeighborBuilderInnerWithContactKernel(SPHBody &body, SPHBody &contact_body) : NeighborBuilderInner(body) { // create a reduced kernel with refined smoothing length for shell - Real smoothing_length = contact_body.sph_adaptation_->ReferenceSmoothingLength(); + Real smoothing_length = contact_body.getSPHAdaptation().ReferenceSmoothingLength(); kernel_ = kernel_keeper_.createPtr(smoothing_length); kernel_->reduceOnce(); } @@ -407,7 +407,7 @@ NeighborBuilderShellSelfContact:: pos0_(body.getBaseParticles().registerStateVariableFrom("InitialPosition", "Position")) { // create a unreduced kernel for shell self contact - Real smoothing_length = body.sph_adaptation_->ReferenceSmoothingLength(); + Real smoothing_length = body.getSPHAdaptation().ReferenceSmoothingLength(); kernel_ = kernel_keeper_.createPtr(smoothing_length); } //=================================================================================================// @@ -477,8 +477,8 @@ void NeighborBuilderShellSelfContact::operator()(Neighborhood &neighborhood, NeighborBuilderSurfaceContactFromShell::NeighborBuilderSurfaceContactFromShell(SPHBody &body, SPHBody &contact_body, bool normal_correction) : BaseNeighborBuilderContactFromShell(body, contact_body, normal_correction) { - Real source_smoothing_length = body.sph_adaptation_->ReferenceSmoothingLength(); - Real target_smoothing_length = contact_body.sph_adaptation_->ReferenceSmoothingLength(); + Real source_smoothing_length = body.getSPHAdaptation().ReferenceSmoothingLength(); + Real target_smoothing_length = contact_body.getSPHAdaptation().ReferenceSmoothingLength(); kernel_ = kernel_keeper_.createPtr(0.5 * (source_smoothing_length + target_smoothing_length)); } //=================================================================================================// @@ -529,7 +529,7 @@ void NeighborBuilderSurfaceContactFromSolid::operator()(Neighborhood &neighborho //=================================================================================================// NeighborBuilderSplitInnerAdaptive:: NeighborBuilderSplitInnerAdaptive(SPHBody &body) - : NeighborBuilder(body.sph_adaptation_->getKernel()), + : NeighborBuilder(body.getSPHAdaptation().getKernel()), h_ratio_(body.getBaseParticles().getVariableDataByName("SmoothingLengthRatio")), level_(body.getBaseParticles().getVariableDataByName("ParticleMeshLevel")) {} //=================================================================================================// diff --git a/src/shared/particles/surface_particles.cpp b/src/shared/particles/surface_particles.cpp index c69f78a60f..50bf4d9c9e 100644 --- a/src/shared/particles/surface_particles.cpp +++ b/src/shared/particles/surface_particles.cpp @@ -12,7 +12,7 @@ SurfaceParticles::SurfaceParticles(SPHBody &sph_body, BaseMaterial *base_materia //---------------------------------------------------------------------- // modify kernel function for surface particles //---------------------------------------------------------------------- - sph_body.sph_adaptation_->getKernel()->reduceOnce(); + sph_body.getSPHAdaptation().getKernel()->reduceOnce(); } //=================================================================================================// void SurfaceParticles::initializeBasicParticleVariables() diff --git a/src/shared/shared_ck/body_relation/relation_ck.cpp b/src/shared/shared_ck/body_relation/relation_ck.cpp index a286c7a53b..e07909bdc5 100644 --- a/src/shared/shared_ck/body_relation/relation_ck.cpp +++ b/src/shared/shared_ck/body_relation/relation_ck.cpp @@ -34,7 +34,7 @@ Relation>::Relation(SPHBody &sph_body, RealBodyVector contact_sph_bodi { const std::string name = contact_bodies_[k]->getName(); contact_particles_.push_back(&contact_bodies_[k]->getBaseParticles()); - contact_adaptations_.push_back(contact_bodies_[k]->sph_adaptation_); + contact_adaptations_.push_back(&contact_bodies_[k]->getSPHAdaptation()); CellLinkedList *target_cell_linked_list = DynamicCast(this, &contact_bodies_[k]->getCellLinkedList()); diff --git a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h index b478dc2a40..f462e7c738 100644 --- a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h +++ b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.h @@ -123,15 +123,17 @@ class CorrectedKernelGradientContactCK template class DiffusionRelaxationCK; -template -class DiffusionRelaxationCK - : public BaseInteractionType +template +class DiffusionRelaxationCK { + StdVec getConcreteDiffusions(AbstractDiffusion &abstract_diffusion); + StdVec *> getDiffusionSpecies(BaseParticles &particles); + StdVec *> getGradientSpecies(BaseParticles &particles); + StdVec *> getSpeciesChangeRates(BaseParticles &particles); + public: - template - DiffusionRelaxationCK(DynamicsIdentifier &identifier, AbstractDiffusion &abstract_diffusion); - template - explicit DiffusionRelaxationCK(DynamicsIdentifier &identifier); + DiffusionRelaxationCK(SPHBody &sph_body, AbstractDiffusion &abstract_diffusion); + explicit DiffusionRelaxationCK(SPHBody &sph_body); virtual ~DiffusionRelaxationCK() {}; class InitializeKernel @@ -164,41 +166,35 @@ class DiffusionRelaxationCK DiscreteVariableArray dv_gradient_species_array_; DiscreteVariableArray dv_diffusion_dt_array_; Real smoothing_length_sq_; - - private: - StdVec getConcreteDiffusions(AbstractDiffusion &abstract_diffusion); - StdVec *> getDiffusionSpecies(StdVec diffusions); - StdVec *> getGradientSpecies(StdVec diffusions); - StdVec *> getSpeciesChangeRates(StdVec diffusions); }; -template -class DiffusionRelaxationCK - : public DiffusionRelaxationCK +template +class DiffusionRelaxationCK + : public DiffusionRelaxationCK { - using BaseDynamicsType = DiffusionRelaxationCK; + using BaseDynamicsType = DiffusionRelaxationCK; public: template - DiffusionRelaxationCK(Args &&...args); + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args); virtual ~DiffusionRelaxationCK() {}; protected: DiscreteVariableArray dv_diffusion_species_array_s_; private: - StdVec *> getIntermediateSpecies(StdVec diffusions); + StdVec *> getIntermediateSpecies(BaseParticles &particles); }; -template -class DiffusionRelaxationCK - : public DiffusionRelaxationCK +template +class DiffusionRelaxationCK + : public DiffusionRelaxationCK { - using BaseDynamicsType = DiffusionRelaxationCK; + using BaseDynamicsType = DiffusionRelaxationCK; public: template - DiffusionRelaxationCK(Args &&...args); + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args); virtual ~DiffusionRelaxationCK() {}; class InitializeKernel : public BaseDynamicsType::InitializeKernel @@ -214,15 +210,15 @@ class DiffusionRelaxationCK -class DiffusionRelaxationCK - : public DiffusionRelaxationCK +template +class DiffusionRelaxationCK + : public DiffusionRelaxationCK { - using BaseDynamicsType = DiffusionRelaxationCK; + using BaseDynamicsType = DiffusionRelaxationCK; public: template - DiffusionRelaxationCK(Args &&...args); + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args); virtual ~DiffusionRelaxationCK() {}; class UpdateKernel : public BaseDynamicsType::UpdateKernel @@ -237,25 +233,24 @@ class DiffusionRelaxationCK class RelationType, typename... Parameters> -class DiffusionRelaxationCK> - : public DiffusionRelaxationCK>> +template +class DiffusionRelaxationCK + : public DiffusionRelaxationCK { - using BaseInteraction = DiffusionRelaxationCK>>; + using BaseRelaxation = DiffusionRelaxationCK; using GradientKernel = typename KernelGradientType::ComputingKernel; using InterParticleDiffusionCoeff = typename DiffusionType::InterParticleDiffusionCoeff; public: - explicit DiffusionRelaxationCK(Relation> &relation); + template + explicit DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args); virtual ~DiffusionRelaxationCK() {}; - class InteractKernel : public BaseInteraction::InteractKernel + class InteractKernel { public: template InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser); - void interact(size_t index_i, Real dt = 0.0); protected: InterParticleDiffusionCoeff *inter_particle_diffusion_coeff_; @@ -271,5 +266,27 @@ class DiffusionRelaxationCK ca_inter_particle_diffusion_coeff_; DiscreteVariable *dv_Vol_; }; + +template +class DiffusionRelaxationCK> + : public DiffusionRelaxationCK, + public Interaction> +{ + using BaseRelaxation = DiffusionRelaxationCK; + using BaseInteraction = Interaction>; + + public: + template + explicit DiffusionRelaxationCK(Relation> &relation, Args &&...args); + virtual ~DiffusionRelaxationCK() {}; + + class InteractKernel : public BaseRelaxation::InteractKernel, public BaseInteraction::InteractKernel + { + public: + template + InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser); + void interact(size_t index_i, Real dt = 0.0); + }; +}; } // namespace SPH #endif // DIFFUSION_DYNAMICS_CK_H diff --git a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp index 0278255f92..96072d111f 100644 --- a/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp +++ b/src/shared/shared_ck/particle_dynamics/diffusion_reaction_dynamics/diffusion_dynamics_ck.hpp @@ -12,26 +12,22 @@ namespace SPH { //=================================================================================================// -template -template -DiffusionRelaxationCK:: - DiffusionRelaxationCK(DynamicsIdentifier &identifier, AbstractDiffusion &abstract_diffusion) - : BaseInteractionType(identifier), - diffusions_(this->getConcreteDiffusions(abstract_diffusion)), - dv_diffusion_species_array_(this->getDiffusionSpecies(diffusions_)), - dv_gradient_species_array_(this->getGradientSpecies(diffusions_)), - dv_diffusion_dt_array_(this->getSpeciesChangeRates(diffusions_)), - smoothing_length_sq_(pow(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength(), 2)) {} -//=================================================================================================// -template -template -DiffusionRelaxationCK:: - DiffusionRelaxationCK(DynamicsIdentifier &identifier) +template +DiffusionRelaxationCK:: + DiffusionRelaxationCK(SPHBody &sph_body, AbstractDiffusion &abstract_diffusion) + : diffusions_(this->getConcreteDiffusions(abstract_diffusion)), + dv_diffusion_species_array_(this->getDiffusionSpecies(sph_body.getBaseParticles())), + dv_gradient_species_array_(this->getGradientSpecies(sph_body.getBaseParticles())), + dv_diffusion_dt_array_(this->getSpeciesChangeRates(sph_body.getBaseParticles())), + smoothing_length_sq_(pow(sph_body.getSPHAdaptation().ReferenceSmoothingLength(), 2)) {} +//=================================================================================================// +template +DiffusionRelaxationCK::DiffusionRelaxationCK(SPHBody &sph_body) : DiffusionRelaxationCK( - identifier, DynamicCast(this, identifier.getSPHBody().getBaseMaterial())) {} + sph_body, DynamicCast(this, sph_body.getBaseMaterial())) {} //=================================================================================================// -template -StdVec DiffusionRelaxationCK:: +template +StdVec DiffusionRelaxationCK:: getConcreteDiffusions(AbstractDiffusion &abstract_diffusion) { StdVec all_diffusions = abstract_diffusion.AllDiffusions(); @@ -43,61 +39,61 @@ StdVec DiffusionRelaxationCK -StdVec *> DiffusionRelaxationCK:: - getDiffusionSpecies(StdVec diffusions) +template +StdVec *> DiffusionRelaxationCK:: + getDiffusionSpecies(BaseParticles &particles) { StdVec *> diffusion_species; - for (auto &diffusion : diffusions) + for (auto &diffusion : diffusions_) { std::string species_name = diffusion->DiffusionSpeciesName(); diffusion_species.push_back( - this->particles_->template registerStateVariableOnly(species_name)); - this->particles_->template addVariableToSort(species_name); - this->particles_->template addVariableToWrite(species_name); + particles.template registerStateVariableOnly(species_name)); + particles.template addVariableToSort(species_name); + particles.template addVariableToWrite(species_name); } return diffusion_species; } //=================================================================================================// -template -StdVec *> DiffusionRelaxationCK:: - getGradientSpecies(StdVec diffusions) +template +StdVec *> DiffusionRelaxationCK:: + getGradientSpecies(BaseParticles &particles) { StdVec *> gradient_species; for (auto &diffusion : diffusions_) { std::string species_name = diffusion->GradientSpeciesName(); gradient_species.push_back( - this->particles_->template registerStateVariableOnly(species_name)); - this->particles_->template addVariableToSort(species_name); - this->particles_->template addVariableToWrite(species_name); + particles.template registerStateVariableOnly(species_name)); + particles.template addVariableToSort(species_name); + particles.template addVariableToWrite(species_name); } return gradient_species; } //=================================================================================================// -template -StdVec *> DiffusionRelaxationCK:: - getSpeciesChangeRates(StdVec diffusions) +template +StdVec *> DiffusionRelaxationCK:: + getSpeciesChangeRates(BaseParticles &particles) { StdVec *> diffusion_dt; for (auto &diffusion : diffusions_) { std::string species_name = diffusion->DiffusionSpeciesName(); diffusion_dt.push_back( - this->particles_->template registerStateVariableOnly(species_name + "ChangeRate")); + particles.template registerStateVariableOnly(species_name + "ChangeRate")); } return diffusion_dt; } //=================================================================================================// -template +template template -DiffusionRelaxationCK:: +DiffusionRelaxationCK:: InitializeKernel::InitializeKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : diffusion_dt_(encloser.dv_diffusion_dt_array_.DelegatedDataArray(ex_policy)), number_of_species_(encloser.diffusions_.size()) {} //=================================================================================================// -template -void DiffusionRelaxationCK:: +template +void DiffusionRelaxationCK:: InitializeKernel::initialize(size_t index_i, Real dt) { for (size_t m = 0; m < number_of_species_; ++m) @@ -106,16 +102,16 @@ void DiffusionRelaxationCK:: } } //=================================================================================================// -template +template template -DiffusionRelaxationCK:: +DiffusionRelaxationCK:: UpdateKernel::UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : diffusion_species_(encloser.dv_diffusion_species_array_.DelegatedDataArray(ex_policy)), diffusion_dt_(encloser.dv_diffusion_dt_array_.DelegatedDataArray(ex_policy)), number_of_species_(encloser.diffusions_.size()) {} //=================================================================================================// -template -void DiffusionRelaxationCK:: +template +void DiffusionRelaxationCK:: UpdateKernel::update(size_t index_i, Real dt) { for (size_t m = 0; m < number_of_species_; ++m) @@ -124,43 +120,43 @@ void DiffusionRelaxationCK:: } } //=================================================================================================// -template +template template -DiffusionRelaxationCK:: - DiffusionRelaxationCK(Args &&...args) - : BaseDynamicsType(std::forward(args)...), - dv_diffusion_species_array_s_(this->getIntermediateSpecies(this->diffusions_)) {} -//=================================================================================================// -template -StdVec *> DiffusionRelaxationCK:: - getIntermediateSpecies(StdVec diffusions) +DiffusionRelaxationCK:: + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args) + : BaseDynamicsType(sph_body, std::forward(args)...), + dv_diffusion_species_array_s_(this->getIntermediateSpecies(sph_body.getBaseParticles())) {} +//=================================================================================================// +template +StdVec *> DiffusionRelaxationCK:: + getIntermediateSpecies(BaseParticles &particles) { StdVec *> diffusion_species_s; - for (auto &diffusion : diffusions) + for (auto &diffusion : this->diffusions_) { std::string species_name = diffusion->DiffusionSpeciesName(); diffusion_species_s.push_back( - this->particles_->template registerStateVariableOnly(species_name + "Intermediate")); + particles.template registerStateVariableOnly(species_name + "Intermediate")); } return diffusion_species_s; } //=================================================================================================// -template +template template -DiffusionRelaxationCK:: - DiffusionRelaxationCK(Args &&...args) - : BaseDynamicsType(std::forward(args)...) {} +DiffusionRelaxationCK:: + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args) + : BaseDynamicsType(sph_body, std::forward(args)...) {} //=================================================================================================// -template +template template -DiffusionRelaxationCK:: +DiffusionRelaxationCK:: InitializeKernel::InitializeKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : BaseDynamicsType::InitializeKernel(ex_policy, encloser), diffusion_species_(encloser.dv_diffusion_species_array_.DelegatedDataArray(ex_policy)), diffusion_species_s_(encloser.dv_diffusion_species_array_s_.DelegatedDataArray(ex_policy)) {} //=================================================================================================// -template -void DiffusionRelaxationCK:: +template +void DiffusionRelaxationCK:: InitializeKernel::initialize(size_t index_i, Real dt) { BaseDynamicsType::InitializeKernel::initialize(index_i, dt); @@ -171,21 +167,21 @@ void DiffusionRelaxationCK +template template -DiffusionRelaxationCK:: - DiffusionRelaxationCK(Args &&...args) - : BaseDynamicsType(std::forward(args)...) {} +DiffusionRelaxationCK:: + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args) + : BaseDynamicsType(sph_body, std::forward(args)...) {} //=================================================================================================// -template +template template -DiffusionRelaxationCK:: +DiffusionRelaxationCK:: UpdateKernel::UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : BaseDynamicsType::UpdateKernel(ex_policy, encloser), diffusion_species_s_(encloser.dv_diffusion_species_array_s_.DelegatedDataArray(ex_policy)) {} //=================================================================================================// -template -void DiffusionRelaxationCK:: +template +void DiffusionRelaxationCK:: UpdateKernel::update(size_t index_i, Real dt) { BaseDynamicsType::UpdateKernel::update(index_i, dt); @@ -196,21 +192,20 @@ void DiffusionRelaxationCK class RelationType, typename... Parameters> -DiffusionRelaxationCK>:: - DiffusionRelaxationCK(Relation> &relation) - : BaseInteraction(relation), kernel_gradient_(this->particles_), +template +template +DiffusionRelaxationCK:: + DiffusionRelaxationCK(SPHBody &sph_body, Args &&...args) + : BaseRelaxation(sph_body, std::forward(args)...), + kernel_gradient_(&sph_body.getBaseParticles()), ca_inter_particle_diffusion_coeff_(this->diffusions_), - dv_Vol_(this->particles_->template getVariableByName("VolumetricMeasure")) {} + dv_Vol_(sph_body.getBaseParticles().template getVariableByName("VolumetricMeasure")) {} //=================================================================================================// -template class RelationType, typename... Parameters> +template template -DiffusionRelaxationCK>:: +DiffusionRelaxationCK:: InteractKernel::InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) - : BaseInteraction::InteractKernel(ex_policy, encloser), - inter_particle_diffusion_coeff_(encloser.ca_inter_particle_diffusion_coeff_.DelegatedData(ex_policy)), + : inter_particle_diffusion_coeff_(encloser.ca_inter_particle_diffusion_coeff_.DelegatedData(ex_policy)), diffusion_species_(encloser.dv_diffusion_species_array_.DelegatedDataArray(ex_policy)), gradient_species_(encloser.dv_gradient_species_array_.DelegatedDataArray(ex_policy)), diffusion_dt_(encloser.dv_diffusion_dt_array_.DelegatedDataArray(ex_policy)), @@ -219,27 +214,40 @@ DiffusionRelaxationCKDelegatedData(ex_policy)), smoothing_length_sq_(encloser.smoothing_length_sq_) {} //=================================================================================================// -template class RelationType, typename... Parameters> -void DiffusionRelaxationCK>:: +template +template +DiffusionRelaxationCK>:: + DiffusionRelaxationCK(Relation> &relation, Args &&...args) + : BaseRelaxation(relation.getSPHBody(), std::forward(args)...), + Interaction>(relation) {} +//=================================================================================================// +template +template +DiffusionRelaxationCK>:: + InteractKernel::InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + : BaseRelaxation::InteractKernel(ex_policy, encloser), + BaseInteraction::InteractKernel(ex_policy, encloser) {} +//=================================================================================================// +template +void DiffusionRelaxationCK>:: InteractKernel::interact(size_t index_i, Real dt) { - for (size_t m = 0; m < number_of_species_; ++m) + for (size_t m = 0; m < this->number_of_species_; ++m) { Real d_species = 0.0; for (UnsignedInt n = this->FirstNeighbor(index_i); n != this->LastNeighbor(index_i); ++n) { UnsignedInt index_j = this->neighbor_index_[n]; - Real dW_ijV_j = this->dW_ij(index_i, index_j) * Vol_[index_j]; + Real dW_ijV_j = this->dW_ij(index_i, index_j) * this->Vol_[index_j]; Vecd e_ij = this->e_ij(index_i, index_j); Vecd vec_r_ij = this->vec_r_ij(index_i, index_j); - Real surface_area_ij = 2.0 * gradient_(index_i, index_j, dW_ijV_j, e_ij).dot(vec_r_ij) / - (vec_r_ij.squaredNorm() + 0.01 * smoothing_length_sq_); - Real phi_ij = gradient_species_[m][index_i] - gradient_species_[m][index_j]; - d_species += inter_particle_diffusion_coeff_[m](index_i, index_j, e_ij) * phi_ij * surface_area_ij; + Real surface_area_ij = 2.0 * this->gradient_(index_i, index_j, dW_ijV_j, e_ij).dot(vec_r_ij) / + (vec_r_ij.squaredNorm() + 0.01 * this->smoothing_length_sq_); + Real phi_ij = this->gradient_species_[m][index_i] - this->gradient_species_[m][index_j]; + d_species += this->inter_particle_diffusion_coeff_[m](index_i, index_j, e_ij) * phi_ij * surface_area_ij; } - diffusion_dt_[m][index_i] += d_species; + this->diffusion_dt_[m][index_i] += d_species; } } //=================================================================================================// diff --git a/src/shared/shared_ck/particle_dynamics/fluid_dynamics/fluid_time_step_ck.cpp b/src/shared/shared_ck/particle_dynamics/fluid_dynamics/fluid_time_step_ck.cpp index f305559be9..ae92da67ac 100644 --- a/src/shared/shared_ck/particle_dynamics/fluid_dynamics/fluid_time_step_ck.cpp +++ b/src/shared/shared_ck/particle_dynamics/fluid_dynamics/fluid_time_step_ck.cpp @@ -16,7 +16,7 @@ AcousticTimeStepCK::AcousticTimeStepCK(SPHBody &sph_body, Real acousticCFL) dv_vel_(particles_->getVariableByName("Velocity")), dv_force_(particles_->getVariableByName("Force")), dv_force_prior_(particles_->getVariableByName("ForcePrior")), - h_min_(sph_body.sph_adaptation_->MinimumSmoothingLength()), + h_min_(sph_body.getSPHAdaptation().MinimumSmoothingLength()), acousticCFL_(acousticCFL) {} //=================================================================================================// AcousticTimeStepCK::FinishDynamics::FinishDynamics(AcousticTimeStepCK &encloser) @@ -32,7 +32,7 @@ Real AcousticTimeStepCK::FinishDynamics::Result(Real reduced_value) AdvectionTimeStepCK:: AdvectionTimeStepCK(SPHBody &sph_body, Real U_ref, Real advectionCFL) : LocalDynamicsReduce(sph_body), - h_min_(sph_body.sph_adaptation_->MinimumSmoothingLength()), + h_min_(sph_body.getSPHAdaptation().MinimumSmoothingLength()), speed_ref_(U_ref), advectionCFL_(advectionCFL), dv_mass_(particles_->getVariableByName("Mass")), dv_vel_(particles_->getVariableByName("Velocity")), diff --git a/src/shared/shared_ck/particle_dynamics/fluid_dynamics/transport_velocity_correction_ck.hpp b/src/shared/shared_ck/particle_dynamics/fluid_dynamics/transport_velocity_correction_ck.hpp index a834a53e91..24ae0b746f 100644 --- a/src/shared/shared_ck/particle_dynamics/fluid_dynamics/transport_velocity_correction_ck.hpp +++ b/src/shared/shared_ck/particle_dynamics/fluid_dynamics/transport_velocity_correction_ck.hpp @@ -19,10 +19,11 @@ TransportVelocityCorrectionCKBase:: dv_dpos_(this->particles_->template getVariableByName("Displacement")), dv_zero_gradient_residue_( this->particles_->template registerStateVariableOnly("ZeroGradientResidue")) -{} +{ +} //======================================================================================== -// 2) Partial Specialization: +// 2) Partial Specialization: // //======================================================================================== template @@ -30,7 +31,7 @@ TransportVelocityCorrectionCK> &inner_relation, Real coefficient) : TransportVelocityCorrectionCKBase>>(inner_relation), kernel_correction_(this->particles_), - h_ref_(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength()), + h_ref_(this->sph_body_.getSPHAdaptation().ReferenceSmoothingLength()), correction_scaling_(coefficient * h_ref_ * h_ref_), h_ratio_(this->particles_), limiter_(h_ref_ * h_ref_), @@ -47,22 +48,23 @@ TransportVelocityCorrectionCK +template template TransportVelocityCorrectionCK>::InteractKernel:: -InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) + InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : BaseInteraction::InteractKernel(ex_policy, encloser), correction_(ex_policy, encloser.kernel_correction_), Vol_(encloser.dv_Vol_->DelegatedData(ex_policy)), dpos_(encloser.dv_dpos_->DelegatedData(ex_policy)), zero_gradient_residue_(encloser.dv_zero_gradient_residue_->DelegatedData(ex_policy)), within_scope_(ex_policy, encloser.within_scope_method_, *this) -{} +{ +} -template +template void TransportVelocityCorrectionCK>::InteractKernel:: -interact(size_t index_i, Real dt) -{ + interact(size_t index_i, Real dt) +{ if (this->within_scope_(index_i)) { Vecd inconsistency = Vecd::Zero(); @@ -90,17 +92,16 @@ template < class ParticleScopeType, typename... Parameters> template -TransportVelocityCorrectionCK< Inner ->::UpdateKernel:: -UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) +TransportVelocityCorrectionCK>::UpdateKernel:: + UpdateKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser) : correction_(ex_policy, encloser.kernel_correction_), correction_scaling_(encloser.correction_scaling_), h_ratio_(encloser.h_ratio_), limiter_(encloser.limiter_), dpos_(encloser.dv_dpos_->DelegatedData(ex_policy)), - zero_gradient_residue_(encloser.dv_zero_gradient_residue_->DelegatedData(ex_policy)) - , within_scope_(ex_policy, encloser.within_scope_method_, *this) -{} + zero_gradient_residue_(encloser.dv_zero_gradient_residue_->DelegatedData(ex_policy)), within_scope_(ex_policy, encloser.within_scope_method_, *this) +{ +} template < class KernelCorrectionType, @@ -109,21 +110,20 @@ template < class ParticleScopeType, typename... ExtraParams> void TransportVelocityCorrectionCK< - Inner ->::UpdateKernel:: -update(size_t index_i, Real dt) + Inner>::UpdateKernel:: + update(size_t index_i, Real dt) { if (this->within_scope_(index_i)) { Real inv_h_ratio = 1.0 / h_ratio_(index_i); Real squared_norm = this->zero_gradient_residue_[index_i].squaredNorm(); dpos_[index_i] += correction_scaling_ * limiter_(squared_norm) * - this->zero_gradient_residue_[index_i] * inv_h_ratio * inv_h_ratio; + this->zero_gradient_residue_[index_i] * inv_h_ratio * inv_h_ratio; } } //======================================================================================== -// Partial Specialization: +// Partial Specialization: // > //======================================================================================== @@ -131,12 +131,12 @@ template >:: TransportVelocityCorrectionCK(Relation> &contact_relation) : TransportVelocityCorrectionCKBase>>(contact_relation), - kernel_correction_(this->particles_) + kernel_correction_(this->particles_) { for (size_t k = 0; k != this->contact_particles_.size(); ++k) - { + { dv_contact_wall_Vol_.push_back(this->contact_particles_[k]->template getVariableByName("VolumetricMeasure")); - } + } } //------------------------------------------------------------------------------ // InteractKernel Implementation @@ -144,31 +144,32 @@ TransportVelocityCorrectionCK template TransportVelocityCorrectionCK>:: -InteractKernel::InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser, UnsignedInt contact_index) + InteractKernel::InteractKernel(const ExecutionPolicy &ex_policy, EncloserType &encloser, UnsignedInt contact_index) : BaseInteraction::InteractKernel(ex_policy, encloser, contact_index), correction_(ex_policy, encloser.kernel_correction_), - zero_gradient_residue_(encloser.dv_zero_gradient_residue_->DelegatedData(ex_policy)), + zero_gradient_residue_(encloser.dv_zero_gradient_residue_->DelegatedData(ex_policy)), contact_wall_Vol_(encloser.dv_contact_wall_Vol_[contact_index]->DelegatedData(ex_policy)) -{} +{ +} template void TransportVelocityCorrectionCK>:: -InteractKernel::interact(size_t index_i, Real dt) + InteractKernel::interact(size_t index_i, Real dt) { Vecd inconsistency = Vecd::Zero(); for (UnsignedInt n = this->FirstNeighbor(index_i); n != this->LastNeighbor(index_i); ++n) { - UnsignedInt index_j = this->neighbor_index_[n]; - const Real dW_ijV_j = this->dW_ij(index_i, index_j) * contact_wall_Vol_[index_j]; - const Vecd e_ij = this->e_ij(index_i, index_j); + UnsignedInt index_j = this->neighbor_index_[n]; + const Real dW_ijV_j = this->dW_ij(index_i, index_j) * contact_wall_Vol_[index_j]; + const Vecd e_ij = this->e_ij(index_i, index_j); - // acceleration for transport velocity - inconsistency -= 2.0*this->correction_(index_i) * - dW_ijV_j * e_ij; + // acceleration for transport velocity + inconsistency -= 2.0 * this->correction_(index_i) * + dW_ijV_j * e_ij; } this->zero_gradient_residue_[index_i] += inconsistency; } } // end namespace fluid_dynamics } // end namespace SPH -#endif // TRANSPORT_VELOCITY_CORRECTION_CK_HPP +#endif // TRANSPORT_VELOCITY_CORRECTION_CK_HPP diff --git a/src/shared/shared_ck/particle_dynamics/fluid_dynamics/viscous_force.hpp b/src/shared/shared_ck/particle_dynamics/fluid_dynamics/viscous_force.hpp index d73208177c..d3da7721ab 100644 --- a/src/shared/shared_ck/particle_dynamics/fluid_dynamics/viscous_force.hpp +++ b/src/shared/shared_ck/particle_dynamics/fluid_dynamics/viscous_force.hpp @@ -14,12 +14,12 @@ ViscousForceCK>(base_relation), ForcePriorCK(this->particles_, "ViscousForce"), - viscosity_model_(DynamicCast(this, this->particles_->getBaseMaterial())), + viscosity_model_(DynamicCast(this, this->particles_->getBaseMaterial())), kernel_correction_(this->particles_), dv_Vol_(this->particles_->template getVariableByName("VolumetricMeasure")), dv_vel_(this->particles_->template getVariableByName("Velocity")), dv_viscous_force_(this->dv_current_force_), - smoothing_length_sq_(pow(this->sph_body_.sph_adaptation_->ReferenceSmoothingLength(), 2)) {} + smoothing_length_sq_(pow(this->sph_body_.getSPHAdaptation().ReferenceSmoothingLength(), 2)) {} //=================================================================================================// template class RelationType, typename... Parameters> @@ -64,10 +64,10 @@ void ViscousForceCKneighbor_index_[n]; Vecd e_ij = this->e_ij(index_i, index_j); Vecd vec_r_ij = this->vec_r_ij(index_i, index_j); - Vecd vel_derivative = 2.0*(this->vel_[index_i] - this->wall_vel_ave_[index_j]) / + Vecd vel_derivative = 2.0 * (this->vel_[index_i] - this->wall_vel_ave_[index_j]) / (vec_r_ij.squaredNorm() + 0.01 * this->smoothing_length_sq_); - force += 2.0*vec_r_ij.dot(this->correction_(index_i) * e_ij) * + force += 2.0 * vec_r_ij.dot(this->correction_(index_i) * e_ij) * this->viscosity_(index_i) * vel_derivative * this->dW_ij(index_i, index_j) * this->wall_Vol_[index_j]; } diff --git a/src/shared/shared_ck/particle_dynamics/fluid_structure_interaction/force_on_structure.hpp b/src/shared/shared_ck/particle_dynamics/fluid_structure_interaction/force_on_structure.hpp index 9abf6140a9..3de3d55ca1 100644 --- a/src/shared/shared_ck/particle_dynamics/fluid_structure_interaction/force_on_structure.hpp +++ b/src/shared/shared_ck/particle_dynamics/fluid_structure_interaction/force_on_structure.hpp @@ -49,7 +49,7 @@ ViscousForceFromFluid>:: { ViscosityType *viscosity_model_k = DynamicCast(this, &this->contact_particles_[k]->getBaseMaterial()); contact_viscosity_model_.push_back(viscosity_model_k); - contact_smoothing_length_sq_.push_back(pow(this->contact_bodies_[k]->sph_adaptation_->ReferenceSmoothingLength(), 2)); + contact_smoothing_length_sq_.push_back(pow(this->contact_bodies_[k]->getSPHAdaptation().ReferenceSmoothingLength(), 2)); } } //=================================================================================================// diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp index b2939fb3ce..a8e885148c 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/geometric_dynamics.cpp @@ -25,7 +25,7 @@ void NormalFromBodyShapeCK::UpdateKernel::update(size_t index_i, Real dt) SurfaceIndicationFromBodyShape::SurfaceIndicationFromBodyShape(SPHBody &sph_body) : LocalDynamics(sph_body), initial_shape_(&sph_body.getInitialShape()), - spacing_ref_(sph_body.sph_adaptation_->ReferenceSpacing()), + spacing_ref_(sph_body.getSPHAdaptation().ReferenceSpacing()), dv_indicator_(particles_->registerStateVariableOnly("SurfaceIndicator")), dv_pos_(particles_->getVariableByName("Position")) {} //=============================================================================================// diff --git a/src/shared/shared_ck/particle_dynamics/general_dynamics/surface_indication/surface_indication_ck.hpp b/src/shared/shared_ck/particle_dynamics/general_dynamics/surface_indication/surface_indication_ck.hpp index b92e310a9e..5183c5a50a 100644 --- a/src/shared/shared_ck/particle_dynamics/general_dynamics/surface_indication/surface_indication_ck.hpp +++ b/src/shared/shared_ck/particle_dynamics/general_dynamics/surface_indication/surface_indication_ck.hpp @@ -1,8 +1,8 @@ #ifndef SURFACE_INDICATION_CK_HPP #define SURFACE_INDICATION_CK_HPP -#include "surface_indication_ck.h" #include "base_particles.hpp" +#include "surface_indication_ck.h" namespace SPH { @@ -14,22 +14,22 @@ namespace fluid_dynamics template