PeriDEM 0.3.0
PeriDEM -- Peridynamics-based high-fidelity model for granular media
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1/*
2 * -------------------------------------------
3 * Copyright (c) 2021 - 2026 Prashant K. Jha
4 * -------------------------------------------
5 * PeriDEM https://github.com/prashjha/PeriDEM
6 *
7 * Distributed under the Boost Software License, Version 1.0. (See accompanying
8 * file LICENSE)
9 *
10 * Quick Multi_Particle MPI identity driver: two circles + one fixed floor wall.
11 * Exercises DispBC on the wall, grain–grain contact, and grain–wall contact.
12 * Dumps gathered final nodal u,v for serial / Particle-MPI / DOF-MPI compare.
13 *
14 * -mpiStrategy none|particle|dof
15 * -outputDir / -inputDir
16 * -nThreads
17 */
18
19#include "geom/geomIncludes.h"
20#include "inp/deckIncludes.h"
21#include "inp/input.h"
25#include "periDEMModel.h"
27#include "util/function.h"
28#include "util/io.h"
29#include "util/parallelUtil.h"
30#include "util/point.h"
31
32#include <mpi.h>
33#include <algorithm>
34#include <cmath>
35#include <cstdint>
36#include <filesystem>
37#include <format>
38#include <fstream>
39#include <stdexcept>
40#include <string>
41#include <thread>
42#include <vector>
43
44namespace {
45
46std::string directoryPathWithTrailingSep(const std::filesystem::path &dir) {
47 namespace fs = std::filesystem;
48 fs::path n = fs::absolute(dir).lexically_normal();
49 std::string s = n.string();
50 if (!s.empty() && s.back() != '/' && s.back() != '\\')
51 s += fs::path::preferred_separator;
52 return s;
53}
54
55bool ownsNode(const data::ModelData &data, size_t i) {
56 const int rank = util::parallel::mpiRank();
57 if (data.d_pdDofMpi) {
58 if (i >= data.d_pdNodePartition.size())
59 return false;
60 return static_cast<int>(data.d_pdNodePartition[i]) == rank;
61 }
62 for (const auto *p : data.d_particlesListTypeAll) {
63 const size_t i0 = p->d_globStart;
64 const size_t i1 = i0 + p->getNumNodes();
65 if (i < i0 || i >= i1)
66 continue;
67 if (p->isWall())
68 return rank == 0;
69 return particle::isLocallyOwned(*p);
70 }
71 return rank == 0;
72}
73
75 const std::filesystem::path &out_dir) {
76 const size_t n = data.d_u.size();
77 std::vector<double> buf(6 * n, 0.);
78 for (size_t i = 0; i < n; ++i) {
79 if (!ownsNode(data, i))
80 continue;
81 buf[6 * i + 0] = data.d_u[i].d_x;
82 buf[6 * i + 1] = data.d_u[i].d_y;
83 buf[6 * i + 2] = data.d_u[i].d_z;
84 buf[6 * i + 3] = data.d_v[i].d_x;
85 buf[6 * i + 4] = data.d_v[i].d_y;
86 buf[6 * i + 5] = data.d_v[i].d_z;
87 }
89 MPI_Allreduce(MPI_IN_PLACE, buf.data(), static_cast<int>(buf.size()),
90 MPI_DOUBLE, MPI_SUM, util::parallel::mpiComm());
91 if (util::parallel::mpiRank() != 0)
92 return;
93
94 std::filesystem::create_directories(out_dir / "nodal");
95 {
96 std::ofstream xr(out_dir / "nodal" / "x_ref.bin", std::ios::binary);
97 const uint32_t nn = static_cast<uint32_t>(n);
98 xr.write(reinterpret_cast<const char *>(&nn), sizeof(nn));
99 for (size_t i = 0; i < n; ++i) {
100 const double p[3] = {data.d_xRef[i].d_x, data.d_xRef[i].d_y,
101 data.d_xRef[i].d_z};
102 xr.write(reinterpret_cast<const char *>(p), sizeof(p));
103 }
104 }
105 {
106 std::ofstream os(out_dir / "nodal" / "final_uv.bin", std::ios::binary);
107 const char magic[4] = {'P', 'D', 'U', 'V'};
108 const uint32_t step32 = static_cast<uint32_t>(data.currentStep());
109 const uint32_t nn = static_cast<uint32_t>(n);
110 os.write(magic, 4);
111 os.write(reinterpret_cast<const char *>(&step32), sizeof(step32));
112 os.write(reinterpret_cast<const char *>(&nn), sizeof(nn));
113 os.write(reinterpret_cast<const char *>(buf.data()),
114 static_cast<std::streamsize>(buf.size() * sizeof(double)));
115 }
116}
117
120public:
123 if (data.d_particlesListTypeParticle.size() < 2)
124 return;
125 const auto *g0 = data.d_particlesListTypeParticle[0];
126 const auto *g1 = data.d_particlesListTypeParticle[1];
127 double Rc = 0.;
128 try {
129 Rc = data.d_particleDeck_p->d_contactDeck.getContact(0, 0).d_contactR;
130 } catch (...) {
131 return;
132 }
133 d_Rc = Rc;
134 const double gap = g0->getXCenter().dist(g1->getXCenter()) -
135 g0->d_geom_p->boundingRadius() -
136 g1->d_geom_p->boundingRadius();
137 d_minPpGap = std::min(d_minPpGap, gap);
138 if (gap < Rc)
139 d_sawPp = true;
140
141 double min_y = 1.e300;
142 for (size_t i = 0; i < data.d_x.size(); ++i) {
143 if (data.getParticleFromAllList(data.d_ptId[i])->isWall())
144 continue;
145 min_y = std::min(min_y, data.d_x[i].d_y);
146 }
147 if (util::parallel::mpiSize() > 1)
148 MPI_Allreduce(MPI_IN_PLACE, &min_y, 1, MPI_DOUBLE, MPI_MIN,
150 d_minGrainY = std::min(d_minGrainY, min_y);
151 if (min_y < Rc)
152 d_sawWall = true;
153 }
154
155 void assertOk() const {
156 int saw_pp = d_sawPp ? 1 : 0;
157 int saw_wall = d_sawWall ? 1 : 0;
158 double min_pp = d_minPpGap;
159 double min_y = d_minGrainY;
160 double rc = d_Rc;
161 if (util::parallel::mpiSize() > 1) {
162 int saw_pp_g = 0, saw_wall_g = 0;
163 double min_pp_g = 0., min_y_g = 0., rc_g = 0.;
164 MPI_Allreduce(&saw_pp, &saw_pp_g, 1, MPI_INT, MPI_MAX,
166 MPI_Allreduce(&saw_wall, &saw_wall_g, 1, MPI_INT, MPI_MAX,
168 MPI_Allreduce(&min_pp, &min_pp_g, 1, MPI_DOUBLE, MPI_MIN,
170 MPI_Allreduce(&min_y, &min_y_g, 1, MPI_DOUBLE, MPI_MIN,
172 MPI_Allreduce(&rc, &rc_g, 1, MPI_DOUBLE, MPI_MAX,
174 saw_pp = saw_pp_g;
175 saw_wall = saw_wall_g;
176 min_pp = min_pp_g;
177 min_y = min_y_g;
178 rc = rc_g;
179 }
180 if (!saw_pp)
181 throw std::runtime_error(std::format(
182 "particle-particle contact missing: min_gap={:.6e} Rc={:.6e}", min_pp,
183 rc));
184 if (!saw_wall)
185 throw std::runtime_error(std::format(
186 "particle-wall contact missing: min_grain_y={:.6e} Rc={:.6e}", min_y,
187 rc));
188 if (util::parallel::mpiRank() == 0)
189 util::io::print(std::format(
190 "contacts OK: min_pp_gap={:.6e} min_grain_y={:.6e} Rc={:.6e}\n",
191 min_pp, min_y, rc));
192 }
193
194private:
195 bool d_sawPp = false;
196 bool d_sawWall = false;
197 double d_minPpGap = 1.e300;
198 double d_minGrainY = 1.e300;
199 double d_Rc = 0.;
200};
201
202json buildInputJson(const std::string &output_path,
203 const std::filesystem::path &mesh_cir,
204 const std::filesystem::path &mesh_wall,
205 const std::string &mpi_strategy, double final_time,
206 size_t num_steps) {
207 const double R = 0.001;
208 const double mesh_size = R / 4.0;
209 const double horizon = 3.0 * mesh_size;
210 const double h_est = 0.7 * mesh_size;
211 const double Rc_est = 0.95 * h_est;
212
213 // Start inside PP Rc and near the floor; soft Kn (below) keeps contact stable.
214 const double gap_pp = 0.5 * Rc_est;
215 const double cy = R + 0.35 * Rc_est;
216 const double cx0 = -(R + 0.5 * gap_pp);
217 const double cx1 = +(R + 0.5 * gap_pp);
218
219 const double wall_half = 3.5 * R;
220 const double wall_thick = std::max(2.0 * mesh_size, horizon);
221
222 geom::GeomData grain;
223 grain.d_geomName = "circle";
224 grain.d_geomParams = {R, 0., 0., 0.};
225 geom::GeomData floor;
226 floor.d_geomName = "rectangle";
227 floor.d_geomParams = {-wall_half, -wall_thick, 0., wall_half, 0., 0.};
228
229 const double poisson = 0.25;
230 const double rho = 1200.0;
231 const double K = 2.16e7;
232 const double E = material::toE(K, poisson);
233 const double G = material::toGE(E, poisson);
234 const double Gc = 50.0;
235 const double Kn =
236 18.0 * util::harmonicMean(K, K) / (M_PI * std::pow(horizon, 5));
237
239 2, final_time, num_steps, "finite_difference", "central_difference", true,
240 2, "Multi_Particle", 0);
241 model["MPI_Strategy"] = mpi_strategy;
242 model["Wall_Contact"] = "meshed";
243
245 "vtu", output_path,
246 std::vector<std::string>({"Displacement", "Velocity", "Force",
247 "Particle_ID"}),
248 std::max<size_t>(1, num_steps), 1, false, "zlib", false, num_steps, "",
249 false);
250
251 // Wall (particle index 2) fully fixed; downward IC on both grains.
252 auto bc = inp::BCDeck::getExampleJson(0, 1, 1, true, util::Point(0, -10, 0));
253 bc["Displacement_BC"]["Set_1"] = json{
254 {"Particle_List", std::vector<size_t>{2}},
255 {"Direction", std::vector<size_t>{1, 2}},
256 {"Time_Function",
257 {{"Type", "constant"}, {"Parameters", std::vector<double>{0.}}}},
258 {"Spatial_Function", {{"Type", "constant"}}},
259 {"Zero_Displacement", true}};
260 bc["IC"]["Set_1"] = inp::BCBaseDeck::getExampleJson(
261 "IC", false, geom::GeomData(), {0, 1}, {}, "", {}, "", {}, {}, false,
262 "Constant_Velocity", {0., -0.02, 0.});
263
265 auto mesh_set = [&](const std::filesystem::path &f) {
266 return json{{"File", f.string()},
267 {"CreateMesh",
268 {{"Flag", true},
269 {"Info", "gmsh_builtin_mesh"},
270 {"Mesh_Size", mesh_size},
271 {"Write_Mesh_File", true}}}};
272 };
273 json mesh = {{"Sets", 2},
274 {"Set_1", mesh_set(mesh_cir)},
275 {"Set_2", mesh_set(mesh_wall)}};
276
279 "PDState", false, horizon, 0, rho, K, G, Gc, true, 1);
281 "PDState", false, horizon, 0, rho, K, G, Gc, true, 1);
282
284 0.95, true, /*damping*/ false, /*friction*/ false, Kn, 0.95, 0.0, 1.0,
285 100.0, 1.0, 0.0, K);
286 // Soften contact spring so short MPI identity runs stay stable and bit-reproducible.
287 contact_base["Kn_Factor"] = 1.0e-4;
289 contact["Set_1_1"] = contact_base;
290 contact["Set_1_2"] = contact_base;
291 contact["Set_2_2"] = contact_base;
292 contact["Damping_Law"] = "off";
293 contact["Friction_Law"] = "coulomb_simple";
294
295 auto pgen = inp::PGenDeck::getExampleJson("From_File");
296 pgen["Random_Rotation"] = false;
297 pgen["Data"]["N"] = 3;
298 pgen["Data"]["0"] = json{{"x", cx0},
299 {"y", cy},
300 {"z", 0.},
301 {"theta", 0.},
302 {"s", 1.},
303 {"geom_id", 0},
304 {"mat_id", 0},
305 {"contact_id", 0}};
306 pgen["Data"]["1"] = json{{"x", cx1},
307 {"y", cy},
308 {"z", 0.},
309 {"theta", 0.},
310 {"s", 1.},
311 {"geom_id", 0},
312 {"mat_id", 0},
313 {"contact_id", 0}};
314 pgen["Data"]["2"] = json{{"x", 0.},
315 {"y", -0.5 * wall_thick},
316 {"z", 0.},
317 {"theta", 0.},
318 {"s", 1.},
319 {"geom_id", 1},
320 {"mat_id", 1},
321 {"contact_id", 1},
322 {"is_wall", true}};
323
324 util::io::print(std::format(
325 "mpi_identity_twop_wall: R={:.4g} mesh={:.4g} Rc~{:.4g} gap_pp={:.4g} "
326 "cy={:.4g} T={:.3g} N={}\n",
327 R, mesh_size, Rc_est, gap_pp, cy, final_time, num_steps));
328
329 return json{{"Model", model},
330 {"Output", output},
331 {"Force_BC", bc["Force_BC"]},
332 {"Displacement_BC", bc["Displacement_BC"]},
333 {"IC", bc["IC"]},
334 {"Particle", particle},
335 {"Mesh", mesh},
336 {"Material", material},
337 {"Contact", contact},
338 {"Neighbor",
339 inp::PNeighborDeck::getExampleJson("simple_all", 5.0, 1, 0.5)},
340 {"Particle_Generation", pgen}};
341}
342
343} // namespace
344
345int main(int argc, char *argv[]) {
346 util::parallel::initMpi(argc, argv);
347 util::io::InputParser input(argc, argv);
348
349 unsigned n_threads = 1;
350 if (input.cmdOptionExists("-nThreads"))
351 n_threads = static_cast<unsigned>(std::stoi(input.getCmdOption("-nThreads")));
353
354 std::string mpi_strategy = "none";
355 if (input.cmdOptionExists("-mpiStrategy"))
356 mpi_strategy = input.getCmdOption("-mpiStrategy");
357
358 namespace fs = std::filesystem;
359 fs::path out_dir = fs::current_path() / "out";
360 fs::path inp_dir = fs::current_path() / "inp";
361 if (input.cmdOptionExists("-outputDir"))
362 out_dir = input.getCmdOption("-outputDir");
363 if (input.cmdOptionExists("-inputDir"))
364 inp_dir = input.getCmdOption("-inputDir");
365 fs::create_directories(out_dir);
366 fs::create_directories(inp_dir);
367
368 // Short stable window with soft contact.
369 const double final_time = 2.0e-4;
370 const size_t num_steps = 1000;
371
372 auto input_json =
373 buildInputJson(directoryPathWithTrailingSep(out_dir),
374 inp_dir / "mesh_cir.msh", inp_dir / "mesh_wall.msh",
375 mpi_strategy, final_time, num_steps);
376 {
377 std::ofstream os(inp_dir / "input.json");
378 os << input_json.dump(2);
379 }
380
381 auto deck = std::make_shared<inp::Input>(input_json);
382 PeriDEMModel dem(deck);
383 auto witness = std::make_unique<ContactWitness>();
384 ContactWitness *witness_p = witness.get();
385 dem.setPostprocess(std::move(witness));
386 dem.init();
387 dem.integrate();
388 witness_p->assertOk();
389 dumpFinalNodal(dem, out_dir);
390 dem.close();
391
392 if (util::parallel::mpiRank() == 0)
393 util::io::print(std::format("mpi_identity_twop_wall done (strategy={})\n",
394 mpi_strategy));
396 return 0;
397}
void setPostprocess(std::unique_ptr< postprocess::Postprocess > p)
void checkStop(data::ModelData &data) override
Definition main.cpp:121
A class to store model data.
Definition modelData.h:50
Extra postprocessing and stop criteria (VTU writing is in rw::).
Definition postprocess.h:24
virtual void checkStop(data::ModelData &data)
Input command line argument parser.
Definition inputParser.h:28
bool cmdOptionExists(const std::string &option) const
Check if argument exists.
Definition inputParser.h:60
const std::string & getCmdOption(const std::string &option) const
Get value of argument specified by key.
Definition inputParser.h:45
nlohmann::ordered_json json
std::string directoryPathWithTrailingSep(const std::filesystem::path &dir)
Definition main.cpp:34
bool ownsNode(const data::ModelData &data, size_t i)
Definition main.cpp:55
void dumpFinalNodal(const data::ModelData &data, const std::filesystem::path &out_dir)
Definition main.cpp:74
json buildInputJson(const std::string &output_path, const std::filesystem::path &mesh_cir, const std::filesystem::path &mesh_wall, const std::string &mpi_strategy, double final_time, size_t num_steps)
Definition main.cpp:202
Definition contact.h:20
double toGE(double E, double nu)
Compute shear modulus from Young's modulus E and Poisson's ratio nu.
double toE(double K, double nu)
Compute Young's modulus E from Bulk modulus K and Poisson's ratio nu.
Collection of methods and data related to finite element and mesh.
Definition mesh.cpp:28
Collection of methods and data related to particle object.
Definition modelData.h:36
bool isLocallyOwned(const BaseParticle &p)
True if this rank updates / assembles forces for the particle. Walls are replicated on every rank....
void print(const T &msg, int nt=print_default_tab, int printMpiRank=print_default_mpi_rank)
Prints formatted information.
Definition io.h:128
void initNThreads(unsigned int nThreads=std::thread::hardware_concurrency())
Initializes MpiStatus struct.
void initMpi(int argc=0, char *argv[]=nullptr)
Initializes MPI and also creates MpiStatus struct.
int mpiSize()
Get size (number) of processors.
int mpiRank()
get rank (id) of this processor
void finalizeMpi()
Call MPI_Finalize if this process initialized MPI.
MPI_Comm mpiComm()
Get MPI comm.
double harmonicMean(const double &m1, const double &m2)
Definition function.cpp:131
Input data for geometrical objects.
std::vector< double > d_geomParams
Zone parameters.
std::string d_geomName
Zone type.
static json getExampleJson(std::string type="Foce_BC", bool isRegionActive=false, geom::GeomData regionGeomData=geom::GeomData(), std::vector< size_t > pList=std::vector< size_t >(), std::vector< size_t > pNotList=std::vector< size_t >(), std::string timeFnType="", std::vector< double > timeFnParams=std::vector< double >(), std::string spatialFnType="", std::vector< double > spatialFnParams=std::vector< double >(), std::vector< size_t > direction=std::vector< size_t >(), bool isDisplacementZero=false, std::string icType="", std::vector< double > icVec=std::vector< double >())
Returns example JSON object for ModelDeck configuration.
Definition bcBaseDeck.h:157
static json getExampleJson(size_t nForceSets=0, size_t nDispSets=0, size_t nICSets=0, bool gravityActive=false, util::Point gravity=util::Point())
Returns example JSON object for ModelDeck configuration.
Definition bcDeck.h:69
static json getExampleJson(double contactR=0., bool computeContactR=true, bool dampingOn=true, bool frictionOn=true, double Kn=0., double eps=1., double mu=0., double KnFactor=1., double betanFactor=1., double deltaMax=1., double vMax=0., double K=0.)
Returns example JSON object for ModelDeck configuration.
static json getExampleJson(std::string materialType="PDState", bool isPlainStrain=false, double horizon=-1., double horizonMeshRatio=-1., double density=1., double K=0., double G=0., double Gc=0., bool computeParamsFromElastic=true, size_t influenceFnType=0, double E=-1.)
Returns example JSON object for ModelDeck configuration.
static json getExampleJson(size_t dim=2, double tFinal=1.0, size_t Nt=10, std::string spatialDiscretization="finite_difference", std::string timeDiscretization="central_difference", bool populateElementNodeConnectivity=true, size_t quadOrder=2, std::string particleSimType="Multi_Particle", int seed=0)
Returns example JSON object for ModelDeck configuration.
Definition modelDeck.h:164
static json getExampleJson(std::string outFormat="vtu", std::string path="./", std::vector< std::string > outTags={"Displacement"}, size_t outputInterval=1, size_t debug=2, bool performFEOut=true, std::string compressType="zlib", bool performOut=true, size_t dtTestOut=1, std::string tagPPFile="", bool pvdCollection=false)
Returns example JSON object for ModelDeck configuration.
Definition outputDeck.h:144
static json getExampleJson(std::string genMethod="From_File")
Returns example JSON object for ModelDeck configuration.
Definition pGenDeck.h:65
static json getExampleJson(std::string updateCriteria="simple_all", double sFactor=1., size_t neighUpdateInterval=1, double nearBdNodesTol=0.5)
Returns example JSON object for ModelDeck configuration.
static json getParticleContactExampleJson(size_t nSets=0)
Returns example JSON object for ModelDeck configuration.
static json getParticleGeomExampleJson(std::vector< geom::GeomData > pGeomVec=std::vector< geom::GeomData >())
Returns example JSON object for ModelDeck configuration.
static json getParticleMaterialExampleJson(size_t nSets=0)
Returns example JSON object for ModelDeck configuration.
A structure to represent 3d vectors.
Definition point.h:30
int main()
Definition main.cpp:31