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 * Two-particle circle test with fully in-process setup:
11 * - No input file on disk (deck built in C++ only).
12 * - Particle meshes from in-process Gmsh (CreateMesh.Info = gmsh_builtin_mesh).
13 *
14 * Default layout under the current working directory:
15 * ./out/ — VTU results and log.txt (Output.Path must end with a separator)
16 * ./inp/ — input.json (full deck) and mesh_cir_1.msh, mesh_cir_2.msh
17 *
18 * With PVD_Collection enabled (default here), ./out/output.pvd lists all particle
19 * VTU timesteps — open output.pvd in ParaView for a single time animation (not one
20 * monolithic VTU; VTK uses one VTU per snapshot plus this index file).
21 *
22 * -outputDir <path> sets the output directory (absolute or relative to cwd).
23 * Input files go to a sibling ./inp next to that directory's parent
24 * if -outputDir points at .../out; otherwise use -inputDir.
25 * -inputDir <path> optional; defaults to cwd/inp, or <parent of outputDir>/inp when
26 * -outputDir is used.
27 * -finalTime <t> integration end time (default 0.002; example_twop_circ_contact uses 0.012).
28 * -numSteps <n> number of steps (default 6000; example uses 36000). dt = finalTime/numSteps.
29 * -requireContact fail if max Damage_Z is 0 (particles never damaged / no contact).
30 * -jha2021Table2 Jha et al. JMPS 2021 Table 2 test 1 (ε_n = 1, CR = 1).
31 * -jha2021Table2Test <n> Table 2 test n = 1..5 (sets time, IC, ε_n, CR, damping).
32 * -inbuiltMesh with -jha2021Table2*: Gmsh in-process mesh (Mesh_Size=R/5)
33 * instead of the frozen v0.1.0 .msh. Same dt, IC, horizon, μ.
34 * -epsN <ε> contact Epsilon (paper ε̄_n). ε < 1 turns damping on (C̄ = 100).
35 * -betaNFactor <C> contact Beta_n_Factor (paper C̄, default 100).
36 * -zeroIC drop from rest (paper Fig. 5); default is a free-fall velocity IC.
37 * -assertCR <ref> fail unless sqrt(H1/H0) is within -crTol of <ref>.
38 * -crTol <tol> absolute CR tolerance (default 0.1).
39 */
40
41#include "inp/deckIncludes.h"
42#include "util/io.h"
43#include "util/function.h"
44#include "util/parallelUtil.h"
47#include "periDEMModel.h"
51#include <mpi.h>
52#include <algorithm>
53#include <cmath>
54#include <cstdlib>
55#include <cstring>
56#include <filesystem>
57#include <format>
58#include <fstream>
59#include <memory>
60#include <stdexcept>
61#include <thread>
62#include <utility>
63#include <vector>
64
65// Jha et al. JMPS 2021 Table 2: same R, M1, H0; CR vs ε̄_n (paper Epsilon).
67 double eps;
68 double cr;
69};
70
72 static const Jha2021Table2 k[] = {
73 {1.0, 1.0}, {0.95, 0.946}, {0.9, 0.893}, {0.85, 0.845}, {0.8, 0.796}};
74 if (test_id < 1 || test_id > 5)
75 throw std::runtime_error("jha2021Table2Test must be 1..5");
76 return k[test_id - 1];
77}
78
79namespace {
80
82std::string directoryPathWithTrailingSep(const std::filesystem::path &dir) {
83 namespace fs = std::filesystem;
84 fs::path n = fs::absolute(dir).lexically_normal();
85 std::string s = n.string();
86 if (!s.empty() && s.back() != '/' && s.back() != '\\')
87 s += fs::path::preferred_separator;
88 return s;
89}
90
91json buildInputJson(const std::string &output_path_for_deck,
92 const std::filesystem::path &mesh_file_1,
93 const std::filesystem::path &mesh_file_2,
94 double final_time, size_t num_steps, bool zero_ic,
95 double mesh_size_in, double horizon_in, bool damping_on,
96 double eps_n, bool two_particle_test, bool file_mesh,
97 double beta_n_factor,
98 const std::string &damping_law = "com_and_node",
99 const std::string &friction_law = "coulomb_simple",
100 bool friction_on = false,
101 double friction_mu = -1.,
102 double ic_vx = 0.,
103 bool bottom_patch_bc = false,
104 const std::string &mpi_strategy = "auto") {
105
106 const std::vector<double> center = {0.0, 0.0, 0.0};
107 const double R1 = 0.001;
108 const double R2 = 0.001;
109 const double mesh_size =
110 mesh_size_in > 0. ? mesh_size_in : std::min(R1, R2) / 5.0;
111 const double horizon = horizon_in > 0. ? horizon_in : 3.0 * mesh_size;
112 const double particle_dist = 0.001;
113
114 const double poisson1 = 0.25;
115 const double rho1 = 1200.0;
116 const double K1 = 2.16e+7;
117 const double E1 = material::toE(K1, poisson1);
118 const double G1 = material::toGE(E1, poisson1);
119 const double Gc1 = 50.0;
120
121 const double poisson2 = 0.25;
122 const double rho2 = 1200.0;
123 const double K2 = 2.16e+7;
124 const double E2 = material::toE(K2, poisson2);
125 const double G2 = material::toGE(E2, poisson2);
126 const double Gc2 = 50.0;
127
128 const double R_contact_factor = 0.95;
129 const double Kn_11 = 18.0 * util::harmonicMean(K1, K1) / (M_PI * std::pow(horizon, 5));
130 const double Kn_22 = 18.0 * util::harmonicMean(K2, K2) / (M_PI * std::pow(horizon, 5));
131 const double Kn_12 = 18.0 * util::harmonicMean(K1, K2) / (M_PI * std::pow(horizon, 5));
132 const double friction_coeff = 0.5;
133
134 std::vector<double> p1_center = center;
135 std::vector<double> p2_center = center;
136
137 const double H0_drop = particle_dist; // paper drop height, 1 mm
138 // Table 2 energy: remaining gap = horizon, rest of H0 already in IC velocity.
139 const double top_gap = two_particle_test ? horizon : particle_dist;
140
141 const size_t dt_out_n = num_steps / 10;
142 auto modelDeckJson = inp::ModelDeck::getExampleJson(2, final_time, num_steps,
143 "finite_difference", "central_difference",
144 true, 2, "Multi_Particle", 0);
145 modelDeckJson["MPI_Strategy"] = mpi_strategy;
146
147 auto outputDeckJson = inp::OutputDeck::getExampleJson("vtu", output_path_for_deck,
148 std::vector<std::string>({"Displacement", "Velocity", "Force", "Damage_Z", "Damage", "Particle_ID"}),
149 dt_out_n, 2, true, "zlib", true, 1, "", true);
150
151 auto bcDeckJson = inp::BCDeck::getExampleJson(0, 1, 1, true, util::Point(0, -10, 0));
152
153 if (bottom_patch_bc) {
154 // Particle 0 centered at (R1,R1); fix only a bottom strip (not the whole grain).
155 geom::GeomData patch;
156 patch.d_geomName = "rectangle";
157 patch.d_geomParams = {R1 - 1.1 * R1, -0.1 * R1, 0., R1 + 1.1 * R1, 0.35 * R1,
158 0.};
159 json j_geom;
160 geom::writeGeometry(j_geom, patch);
161 bcDeckJson["Displacement_BC"]["Set_1"] = json{
162 {"Particle_List", json::array({0})},
163 {"Region", {{"Geometry", j_geom}}},
164 {"Direction", json::array({1, 2})},
165 {"Zero_Displacement", true}};
166 } else {
167 bcDeckJson["Displacement_BC"]["Set_1"] =
168 inp::BCBaseDeck::getExampleJson("Displacement_BC", false, geom::GeomData(),
169 {0}, {}, "", {}, "", {}, {1, 2}, true, "",
170 {});
171 }
172
173 std::vector<double> ic_vel = {0.0, 0.0, 0.0};
174 if (!zero_ic) {
175 const double fallen =
176 two_particle_test ? (H0_drop - top_gap) : (particle_dist - horizon);
177 if (fallen > 0.)
178 ic_vel[1] = -std::sqrt(2.0 * std::abs(-10.0) * fallen);
179 }
180 ic_vel[0] = ic_vx;
181 bcDeckJson["IC"]["Set_1"] = inp::BCBaseDeck::getExampleJson("IC", false, geom::GeomData(),
182 {1}, {}, "", {}, "", {},
183 {}, false, "Constant_Velocity", ic_vel);
184
185 auto pDeckJson = json({});
186
187 std::vector<geom::GeomData> pGeomVec(2);
188 pGeomVec[0].d_geomName = "circle";
189 pGeomVec[0].d_geomParams = {R1, p1_center[0], p1_center[1], p1_center[2]};
190 pGeomVec[1].d_geomName = "circle";
191 pGeomVec[1].d_geomParams = {R2, p2_center[0], p2_center[1], p2_center[2]};
192
193 pDeckJson["Particle"] = inp::ParticleDeck::getParticleGeomExampleJson(pGeomVec);
194
195 const std::string f1 = mesh_file_1.string();
196 const std::string f2 = mesh_file_2.string();
197 json meshSet1, meshSet2;
198 if (file_mesh) {
199 meshSet1 = json({{"File", f1}});
200 meshSet2 = json({{"File", f2}});
201 } else {
202 meshSet1 = json({{"File", f1},
203 {"CreateMesh",
204 {{"Flag", true},
205 {"Info", "gmsh_builtin_mesh"},
206 {"Mesh_Size", mesh_size},
207 {"Write_Mesh_File", true}}}});
208 meshSet2 = json({{"File", f2},
209 {"CreateMesh",
210 {{"Flag", true},
211 {"Info", "gmsh_builtin_mesh"},
212 {"Mesh_Size", mesh_size},
213 {"Write_Mesh_File", true}}}});
214 }
215 pDeckJson["Mesh"] = json({{"Sets", 2}, {"Set_1", meshSet1}, {"Set_2", meshSet2}});
216
218 pMatJson["Set_1"] = inp::MaterialDeck::getExampleJson("PDState", false, horizon,
219 0, rho1, K1, G1, Gc1, true, 1);
220 pMatJson["Set_2"] = inp::MaterialDeck::getExampleJson("PDState", false, horizon,
221 0, rho2, K2, G2, Gc2, true, 1);
222 pDeckJson["Material"] = pMatJson;
223
225 // v0.1.0 circ_damp: Friction_On: false leaves μ = 0 (coeff is not read).
226 // Nonzero μ with the flag off still applies a tangential force in PairForce
227 // and walks the falling particle sideways (Table 2 test 4).
228 const double mu =
229 (friction_mu >= 0.) ? friction_mu
230 : (two_particle_test ? 0. : friction_coeff);
232 R_contact_factor, true, damping_on, friction_on, Kn_11, eps_n, mu,
233 1.0, beta_n_factor, 1.0, 0.0, K1);
234
235 pContactJson["Set_1_1"] = contact_base;
236 pContactJson["Set_1_1"]["Kn"] = Kn_11;
237 pContactJson["Set_1_1"]["K"] = K1;
238 pContactJson["Set_1_2"] = contact_base;
239 pContactJson["Set_1_2"]["Kn"] = Kn_12;
240 pContactJson["Set_1_2"]["K"] = util::harmonicMean(K1, K2);
241 pContactJson["Set_2_2"] = contact_base;
242 pContactJson["Set_2_2"]["Kn"] = Kn_22;
243 pContactJson["Set_2_2"]["K"] = K2;
244 pContactJson["Damping_Law"] = damping_law;
245 pContactJson["Friction_Law"] = friction_law;
246 pDeckJson["Contact"] = pContactJson;
247
248 pDeckJson["Neighbor"] = two_particle_test
249 ? inp::PNeighborDeck::getExampleJson("simple_all", 5.0, 1, 0.5)
250 : inp::PNeighborDeck::getExampleJson("simple_all", 10.0, 40, 0.5);
251
252 auto pGenJson = inp::PGenDeck::getExampleJson("From_File");
253 pGenJson["Random_Rotation"] = false;
254 pGenJson["Data"]["N"] = 2;
255 pGenJson["Data"]["0"] = {
256 {"x", R1}, {"y", R1}, {"z", 0.0},
257 {"theta", 0.0}, {"s", 1.0},
258 {"geom_id", 0}, {"mat_id", 0}, {"contact_id", 0}
259 };
260 pGenJson["Data"]["1"] = {
261 {"x", R1}, {"y", 2.0 * R1 + R2 + top_gap}, {"z", 0.0},
262 {"theta", two_particle_test ? M_PI / 2.0 : M_PI}, {"s", 1.0},
263 {"geom_id", 1}, {"mat_id", 1}, {"contact_id", 1}
264 };
265 pDeckJson["Particle_Generation"] = pGenJson;
266
267 auto j = json({{"Model", modelDeckJson},
268 {"Output", outputDeckJson},
269 {"Force_BC", bcDeckJson["Force_BC"]},
270 {"Displacement_BC", bcDeckJson["Displacement_BC"]},
271 {"IC", bcDeckJson["IC"]},
272 {"Particle", pDeckJson["Particle"]},
273 {"Mesh", pDeckJson["Mesh"]},
274 {"Material", pDeckJson["Material"]},
275 {"Contact", pDeckJson["Contact"]},
276 {"Neighbor", pDeckJson["Neighbor"]},
277 {"Particle_Generation", pDeckJson["Particle_Generation"]}});
278 if (two_particle_test)
279 j["Test"] = json{{"Test_Name", "two_particle"}};
280 // bottom_patch_bc keeps PD force on particle 0 (deformable base).
281 return j;
282}
283
284} // namespace
285
287public:
288 explicit RestitutionProbe(double H0) : d_H0(H0) {}
289
292 if (data.d_particlesListTypeAll.size() < 2)
293 return;
294 const auto *p0 = data.d_particlesListTypeAll[0];
295 const auto *p1 = data.d_particlesListTypeAll[1];
296 const double gap = p0->getXCenter().dist(p1->getXCenter()) -
297 p0->d_geom_p->boundingRadius() -
298 p1->d_geom_p->boundingRadius();
299 if (data.currentStep() % 50 == 0)
300 d_samples.push_back({data.d_time, gap});
301 if (d_done)
302 return;
303 const double leave = 1.0e-5;
304 const double significant = 0.05 * d_H0;
305 if (!d_contacted) {
306 if (gap < d_minGap) {
307 d_minGap = gap;
308 d_tMin = data.d_time;
309 } else if (d_minGap < 0.3 * d_H0 && gap > d_minGap + leave) {
310 d_contacted = true;
311 d_H1 = gap;
312 d_tH1 = data.d_time;
313 }
314 } else if (gap > d_H1) {
315 d_H1 = gap;
316 d_tH1 = data.d_time;
317 } else if (d_H1 > d_minGap + significant && gap < d_H1 - leave) {
318 d_done = true;
319 }
320 }
321
322 bool contacted() const { return d_contacted; }
323 double H1() const { return d_H1; }
324 double minGap() const { return d_minGap; }
325 double tMin() const { return d_tMin; }
326 double tH1() const { return d_tH1; }
327 const std::vector<std::pair<double, double>> &samples() const {
328 return d_samples;
329 }
330 double CR() const {
331 if (d_H0 <= 0. || d_H1 <= 0.)
332 return 0.;
333 return std::sqrt(d_H1 / d_H0);
334 }
335
336private:
337 double d_H0;
338 double d_H1 = 0.;
339 double d_minGap = 1.0e9;
340 double d_tMin = 0.;
341 double d_tH1 = 0.;
342 bool d_contacted = false;
343 bool d_done = false;
344 std::vector<std::pair<double, double>> d_samples;
345};
346
350public:
351 explicit LateralProbe(double ic_abs_vx) : d_icAbsVx(std::abs(ic_abs_vx)) {}
352
355 if (data.d_particlesListTypeAll.size() < 2)
356 return;
357 const auto *p0 = data.d_particlesListTypeAll[0];
358 const auto *p1 = data.d_particlesListTypeAll[1];
359 const double gap = p0->getXCenter().dist(p1->getXCenter()) -
360 p0->d_geom_p->boundingRadius() -
361 p1->d_geom_p->boundingRadius();
362 if (gap < 0.5 * 0.001)
363 d_contacted = true;
364 const double vx = std::abs(p1->getVCenter().d_x);
365 if (vx > d_maxAbsVx)
366 d_maxAbsVx = vx;
369 }
370 bool contacted() const { return d_contacted; }
371 double maxAbsVx() const { return d_maxAbsVx; }
375 double icAbsVx() const { return d_icAbsVx; }
376
377private:
378 double d_icAbsVx = 0.;
379 double d_maxAbsVx = 0.;
380 double d_minAbsVxAfterContact = 1.0e300;
381 bool d_contacted = false;
382};
383
386public:
387 MpiMetricTsProbe(std::filesystem::path out_dir, size_t interval)
388 : d_outDir(std::move(out_dir)),
389 d_interval(std::max<size_t>(1, interval)) {
390 if (util::parallel::mpiRank() == 0) {
391 std::filesystem::create_directories(d_outDir / "nodal");
392 d_os.open(d_outDir / "mpi_metric_ts.csv");
393 d_os << "step,t,max_u,com1x,com1y\n";
394 }
395 }
396
399 const size_t nstep = data.currentStep();
400 if (nstep % d_interval != 0 && nstep < data.numTimeSteps())
401 return;
402
403 double max_u = 0.;
404 for (const auto &u : data.d_u)
405 max_u = std::max(max_u, u.length());
406 if (util::parallel::mpiSize() > 1)
407 MPI_Allreduce(MPI_IN_PLACE, &max_u, 1, MPI_DOUBLE, MPI_MAX,
409 double com1x = 0., com1y = 0.;
410 if (data.d_particlesListTypeParticle.size() > 1) {
411 const auto c = data.d_particlesListTypeParticle[1]->getXCenter();
412 com1x = c.d_x;
413 com1y = c.d_y;
414 }
415 if (util::parallel::mpiRank() == 0) {
416 d_os << std::format("{},{:.12e},{:.12e},{:.12e},{:.12e}\n", nstep,
417 data.d_time, max_u, com1x, com1y);
418 d_os.flush();
419 }
420 dumpNodalUV(data, nstep);
421 }
422
423private:
424 static bool ownsNode(const data::ModelData &data, size_t i) {
425 const int rank = util::parallel::mpiRank();
426 if (data.d_pdDofMpi) {
427 if (i >= data.d_pdNodePartition.size())
428 return false;
429 return static_cast<int>(data.d_pdNodePartition[i]) == rank;
430 }
431 // Particle-MPI / serial: owned grains; walls only from rank 0 (replicated).
432 for (const auto *p : data.d_particlesListTypeAll) {
433 const size_t i0 = p->d_globStart;
434 const size_t i1 = i0 + p->getNumNodes();
435 if (i < i0 || i >= i1)
436 continue;
437 if (p->isWall())
438 return rank == 0;
439 return particle::isLocallyOwned(*p);
440 }
441 return rank == 0;
442 }
443
444 void dumpNodalUV(data::ModelData &data, size_t nstep) {
445 const size_t n = data.d_u.size();
446 std::vector<double> buf(6 * n, 0.);
447 for (size_t i = 0; i < n; ++i) {
448 if (!ownsNode(data, i))
449 continue;
450 buf[6 * i + 0] = data.d_u[i].d_x;
451 buf[6 * i + 1] = data.d_u[i].d_y;
452 buf[6 * i + 2] = data.d_u[i].d_z;
453 buf[6 * i + 3] = data.d_v[i].d_x;
454 buf[6 * i + 4] = data.d_v[i].d_y;
455 buf[6 * i + 5] = data.d_v[i].d_z;
456 }
457 if (util::parallel::mpiSize() > 1)
458 MPI_Allreduce(MPI_IN_PLACE, buf.data(), static_cast<int>(buf.size()),
459 MPI_DOUBLE, MPI_SUM, util::parallel::mpiComm());
460 if (util::parallel::mpiRank() != 0)
461 return;
462 if (!d_wroteXref) {
463 std::ofstream xr(d_outDir / "nodal" / "x_ref.bin", std::ios::binary);
464 const uint32_t nn = static_cast<uint32_t>(n);
465 xr.write(reinterpret_cast<const char *>(&nn), sizeof(nn));
466 for (size_t i = 0; i < n; ++i) {
467 const double p[3] = {data.d_xRef[i].d_x, data.d_xRef[i].d_y,
468 data.d_xRef[i].d_z};
469 xr.write(reinterpret_cast<const char *>(p), sizeof(p));
470 }
471 d_wroteXref = true;
472 }
473 const auto path =
474 d_outDir / "nodal" / std::format("uv_{:06d}.bin", nstep);
475 std::ofstream os(path, std::ios::binary);
476 const char magic[4] = {'P', 'D', 'U', 'V'};
477 const uint32_t step32 = static_cast<uint32_t>(nstep);
478 const uint32_t nn = static_cast<uint32_t>(n);
479 os.write(magic, 4);
480 os.write(reinterpret_cast<const char *>(&step32), sizeof(step32));
481 os.write(reinterpret_cast<const char *>(&nn), sizeof(nn));
482 os.write(reinterpret_cast<const char *>(buf.data()),
483 static_cast<std::streamsize>(buf.size() * sizeof(double)));
484 }
485
486 std::filesystem::path d_outDir;
488 std::ofstream d_os;
489 bool d_wroteXref = false;
490};
491
492int main(int argc, char *argv[]) {
493
494 util::parallel::initMpi(argc, argv);
495 int mpiSize = util::parallel::mpiSize(), mpiRank = util::parallel::mpiRank();
496 util::io::print(std::format("Initialized MPI. MPI size = {}, MPI rank = {}\n", mpiSize, mpiRank));
498
499 util::io::InputParser input(argc, argv);
500
501 unsigned int nThreads;
502 if (input.cmdOptionExists("-nThreads"))
503 nThreads = std::stoi(input.getCmdOption("-nThreads"));
504 else {
505 nThreads = std::thread::hardware_concurrency();
506 util::io::print(std::format("Running test with default number of threads = {}\n", nThreads));
507 }
509 util::io::print(std::format("Number of threads = {}\n", util::parallel::getNThreads()));
510
511#ifndef TWOP_CONTACT_EXAMPLE
512 double final_time = 0.002;
513 size_t num_steps = 6000;
514#else
515 double final_time = 0.012;
516 size_t num_steps = 36000;
517#endif
518 bool zero_ic = false;
519 double mesh_size_in = -1.;
520 double horizon_in = -1.;
521 bool assert_cr = false;
522 double cr_ref = 1.;
523 double cr_tol = 0.1;
524 bool damping_on = false;
525 double eps_n = 0.9;
526 double beta_n_factor = 100.0;
527 std::string damping_law = "com_and_node";
528 std::string friction_law = "coulomb_simple";
529 bool friction_on = false;
530 double friction_mu = -1.;
531 double ic_vx = 0.;
532 bool assert_lat = false;
533 double lat_min = 0.;
534 bool bottom_patch_bc = false;
535 std::string mpi_strategy = "auto";
536 bool write_mpi_metric = false;
537 int jha_test = 0;
538 if (input.cmdOptionExists("-jha2021Table2Test"))
539 jha_test = std::stoi(input.getCmdOption("-jha2021Table2Test"));
540 else if (input.cmdOptionExists("-jha2021Table2"))
541 jha_test = 1;
542 if (jha_test > 0) {
543 const auto c = jha2021Table2(jha_test);
544 // Paper §4.1 / v0.1.0 circ_damp: T=0.04 s, Δt=0.2 μs, horizon 0.6 mm.
545 // Mesh is the frozen v0.1.0 .msh (hmin = 0.1423 mm), not in-process Gmsh.
546 final_time = 0.04;
547 num_steps = 200000;
548 horizon_in = 0.0006;
549 // v0.1.0 circ_damp: not drop-from-rest. Gap is shortened to the horizon
550 // and the leftover 0.4 mm of the 1 mm drop is an impact velocity.
551 zero_ic = false;
552 assert_cr = true;
553 cr_ref = c.cr;
554 cr_tol = 0.05;
555 eps_n = c.eps;
556 damping_on = c.eps < 1.0 - 1.0e-12;
557 }
558 if (input.cmdOptionExists("-finalTime"))
559 final_time = std::stod(input.getCmdOption("-finalTime"));
560 if (input.cmdOptionExists("-numSteps"))
561 num_steps = std::stoul(input.getCmdOption("-numSteps"));
562 if (input.cmdOptionExists("-zeroIC"))
563 zero_ic = true;
564 if (input.cmdOptionExists("-meshSize"))
565 mesh_size_in = std::stod(input.getCmdOption("-meshSize"));
566 if (input.cmdOptionExists("-horizon"))
567 horizon_in = std::stod(input.getCmdOption("-horizon"));
568 if (input.cmdOptionExists("-epsN")) {
569 eps_n = std::stod(input.getCmdOption("-epsN"));
570 damping_on = eps_n < 1.0 - 1.0e-12;
571 }
572 if (input.cmdOptionExists("-betaNFactor"))
573 beta_n_factor = std::stod(input.getCmdOption("-betaNFactor"));
574 if (input.cmdOptionExists("-dampingLaw"))
575 damping_law = input.getCmdOption("-dampingLaw");
576 if (input.cmdOptionExists("-frictionLaw"))
577 friction_law = input.getCmdOption("-frictionLaw");
578 if (input.cmdOptionExists("-enableFriction"))
579 friction_on = true;
580 if (input.cmdOptionExists("-mu"))
581 friction_mu = std::stod(input.getCmdOption("-mu"));
582 if (input.cmdOptionExists("-icVx"))
583 ic_vx = std::stod(input.getCmdOption("-icVx"));
584 if (input.cmdOptionExists("-assertLateralVx")) {
585 assert_lat = true;
586 lat_min = std::stod(input.getCmdOption("-assertLateralVx"));
587 assert_cr = false; // skip CR gate from table2 defaults for this lateral check
588 }
589 if (input.cmdOptionExists("-assertCR")) {
590 assert_cr = true;
591 cr_ref = std::stod(input.getCmdOption("-assertCR"));
592 }
593 if (input.cmdOptionExists("-crTol"))
594 cr_tol = std::stod(input.getCmdOption("-crTol"));
595 if (input.cmdOptionExists("-bottomPatchBC"))
596 bottom_patch_bc = true;
597 if (input.cmdOptionExists("-mpiStrategy"))
598 mpi_strategy = input.getCmdOption("-mpiStrategy");
599 if (input.cmdOptionExists("-writeMpiMetric"))
600 write_mpi_metric = true;
601 util::io::print(std::format(
602 "final_time = {}, num_steps = {}, zero_ic = {}, eps_n = {}, C_bar = {}, "
603 "damping = {}, Damping_Law = {}, Friction_Law = {}, bottomPatchBC = {}, "
604 "MPI_Strategy = {}\n",
605 final_time, num_steps, zero_ic, eps_n, beta_n_factor, damping_on,
606 damping_law, friction_law, bottom_patch_bc, mpi_strategy));
607
608 namespace fs = std::filesystem;
609 const fs::path cwd = fs::current_path();
610
611 fs::path out_dir = cwd / "out";
612 fs::path inp_dir = cwd / "inp";
613
614 if (input.cmdOptionExists("-outputDir")) {
615 fs::path p = input.getCmdOption("-outputDir");
616 out_dir = p.is_absolute() ? std::move(p) : cwd / p;
617 }
618 if (input.cmdOptionExists("-inputDir")) {
619 fs::path p = input.getCmdOption("-inputDir");
620 inp_dir = p.is_absolute() ? std::move(p) : cwd / p;
621 } else if (input.cmdOptionExists("-outputDir")) {
622 // Place inp next to out: .../run/out -> .../run/inp
623 inp_dir = out_dir.parent_path() / "inp";
624 }
625
626 fs::create_directories(out_dir);
627 fs::create_directories(inp_dir);
628
629 const std::string output_path_for_deck = directoryPathWithTrailingSep(out_dir);
630 const fs::path mesh1 = inp_dir / "mesh_cir_1.msh";
631 const fs::path mesh2 = inp_dir / "mesh_cir_2.msh";
632 const bool inbuilt_mesh = input.cmdOptionExists("-inbuiltMesh");
633 const bool file_mesh = jha_test > 0 && !inbuilt_mesh;
634 if (file_mesh) {
635#ifndef JHA2021_MESH_DIR
636 throw std::runtime_error("JHA2021_MESH_DIR is not set (v0.1.0 circ_damp meshes).");
637#else
638 const fs::path src(JHA2021_MESH_DIR);
639 fs::copy_file(src / "mesh_cir_1.msh", mesh1, fs::copy_options::overwrite_existing);
640 fs::copy_file(src / "mesh_cir_2.msh", mesh2, fs::copy_options::overwrite_existing);
641 util::io::print(std::format("Using v0.1.0 circ_damp meshes from {}\n", src.string()));
642#endif
643 } else if (jha_test > 0)
644 util::io::print("Using in-process Gmsh (gmsh_builtin_mesh) instead of frozen v0.1.0 .msh\n");
645
646 util::io::print(std::format("Output directory (VTU, log.txt): {}\n", fs::absolute(out_dir).string()));
647 util::io::print(std::format("Input directory (input.json, meshes): {}\n", fs::absolute(inp_dir).string()));
648
649 auto inputJson = buildInputJson(output_path_for_deck, mesh1, mesh2, final_time,
650 num_steps, zero_ic, mesh_size_in, horizon_in,
651 damping_on, eps_n, jha_test > 0, file_mesh,
652 beta_n_factor, damping_law,
653 friction_law, friction_on, friction_mu,
654 ic_vx, bottom_patch_bc, mpi_strategy);
655
656 const fs::path input_json_path = inp_dir / "input.json";
657 {
658 std::ofstream os(input_json_path);
659 if (!os)
660 throw std::runtime_error("Failed to open " + input_json_path.string() + " for writing.");
661 os << inputJson.dump(2);
662 }
663 util::io::print(std::format("Wrote deck to {}\n", fs::absolute(input_json_path).string()));
664 if (jha_test > 0) {
665 const auto &p1 = inputJson["Particle_Generation"]["Data"]["1"];
666 const auto &v = inputJson["IC"]["Set_1"]["Constant_Velocity"]["Velocity_Vector"];
667 const double y1 = p1.at("y").get<double>();
668 const double gap0 = y1 - 0.001 - 0.001 - 0.001; // y_top - R_bottom_center - R_bot - R_top
669 util::io::print(std::format(
670 "Table 2 kinematics: top y = {}, surface gap = {}, v_y = {}\n",
671 y1, gap0, v.at(1).get<double>()));
672 }
673
674 auto deck = std::make_shared<inp::Input>(inputJson);
675
676 PeriDEMModel dem(deck);
677 RestitutionProbe *probe = nullptr;
678 LateralProbe *lat_probe = nullptr;
679 if (assert_cr) {
680 auto p = std::make_unique<RestitutionProbe>(0.001);
681 probe = p.get();
682 dem.setPostprocess(std::move(p));
683 } else if (assert_lat) {
684 auto p = std::make_unique<LateralProbe>(ic_vx);
685 lat_probe = p.get();
686 dem.setPostprocess(std::move(p));
687 } else if (write_mpi_metric) {
688 const size_t ts_every = std::max<size_t>(1, num_steps / 100);
689 dem.setPostprocess(
690 std::make_unique<MpiMetricTsProbe>(out_dir, ts_every));
691 }
692 dem.run(deck);
693
694 if (input.cmdOptionExists("-requireContact")) {
695 const float zmax =
696 dem.d_Z.empty() ? 0.f : *std::max_element(dem.d_Z.begin(), dem.d_Z.end());
697 util::io::print(std::format("requireContact: max Damage_Z = {}\n", zmax));
698 if (zmax <= 0.f) {
699 util::io::print("requireContact: no damage; particles did not contact.\n");
700 return EXIT_FAILURE;
701 }
702 }
703
704 if (assert_cr) {
705 {
706 const fs::path gap_csv = out_dir / "gap.csv";
707 std::ofstream gs(gap_csv);
708 gs << "t,gap\n";
709 for (const auto &s : probe->samples())
710 gs << s.first << "," << s.second << "\n";
711 util::io::print(std::format("Wrote {}\n", fs::absolute(gap_csv).string()));
712 }
713 const double cr = probe->CR();
714 util::io::print(std::format(
715 "assertCR: contacted={}, min_gap={} (t={}), H1={} (t={}), CR={}, ref={}, tol={}\n",
716 probe->contacted(), probe->minGap(), probe->tMin(), probe->H1(),
717 probe->tH1(), cr, cr_ref, cr_tol));
718 if (cr > 1.02) {
720 "assertCR: CR > 1.02 on the 1 mm energy-equivalent drop "
721 "(surface gap = horizon, leftover height already in v_y). "
722 "Unphysical energy gain.\n");
723 return EXIT_FAILURE;
724 }
725 if (!probe->contacted() || std::abs(cr - cr_ref) > cr_tol) {
726 util::io::print("assertCR: coefficient of restitution out of range.\n");
727 return EXIT_FAILURE;
728 }
729 }
730
731 if (assert_lat) {
732 const double vmin = lat_probe->minAbsVxAfterContact();
733 const double vmax = lat_probe->maxAbsVx();
734 const double ic = lat_probe->icAbsVx();
735 util::io::print(std::format(
736 "assertLateralVx: contacted={}, max|vx|={}, min|vx|_after_contact={}, "
737 "ic|vx|={}, slow_factor_max={}\n",
738 lat_probe->contacted(), vmax, vmin, ic, lat_min));
739 if (!lat_probe->contacted()) {
740 util::io::print("assertLateralVx: particles never contacted.\n");
741 return EXIT_FAILURE;
742 }
743 // lat_min is the maximum allowed ratio min_vx/ic_vx after contact (e.g. 0.95).
744 if (!(ic > 0.) || !(vmin < lat_min * ic)) {
746 "assertLateralVx: friction did not slow lateral speed enough "
747 "(or kinematics missed).\n");
748 return EXIT_FAILURE;
749 }
750 }
751
752 if (write_mpi_metric) {
753 double max_u = 0.;
754 for (const auto &u : dem.d_u)
755 max_u = std::max(max_u, u.length());
756 double com1x = 0., com1y = 0.;
757 if (dem.d_particlesListTypeParticle.size() > 1) {
758 const auto c = dem.d_particlesListTypeParticle[1]->getXCenter();
759 com1x = c.d_x;
760 com1y = c.d_y;
761 }
763 MPI_Allreduce(MPI_IN_PLACE, &max_u, 1, MPI_DOUBLE, MPI_MAX,
765 // Center node is unique; take from owning rank via MAX of abs then
766 // broadcast of values — simpler: Allreduce SUM after zeroing non-owners
767 // is wrong for COM. After DOF sync every rank has the same center x.
768 }
769 if (util::parallel::mpiRank() == 0) {
770 std::ofstream os(out_dir / "mpi_metric.txt");
771 os << std::format("{:.12e} {:.12e} {:.12e}\n", max_u, com1x, com1y);
772 util::io::print(std::format(
773 "mpi_metric: max|u|={:.12e} grain1_com=({:.12e},{:.12e})\n", max_u,
774 com1x, com1y));
775 }
776 }
777
779 return EXIT_SUCCESS;
780}
double icAbsVx() const
Definition main.cpp:375
double minAbsVxAfterContact() const
Definition main.cpp:372
double d_icAbsVx
Definition main.cpp:378
bool d_contacted
Definition main.cpp:381
LateralProbe(double ic_abs_vx)
Definition main.cpp:351
bool contacted() const
Definition main.cpp:370
double d_minAbsVxAfterContact
Definition main.cpp:380
double d_maxAbsVx
Definition main.cpp:379
void checkStop(data::ModelData &data) override
Definition main.cpp:353
double maxAbsVx() const
Definition main.cpp:371
void checkStop(data::ModelData &data) override
Definition main.cpp:397
MpiMetricTsProbe(std::filesystem::path out_dir, size_t interval)
Definition main.cpp:387
static bool ownsNode(const data::ModelData &data, size_t i)
Definition main.cpp:424
std::ofstream d_os
Definition main.cpp:488
std::filesystem::path d_outDir
Definition main.cpp:486
size_t d_interval
Definition main.cpp:487
void dumpNodalUV(data::ModelData &data, size_t nstep)
Definition main.cpp:444
void setPostprocess(std::unique_ptr< postprocess::Postprocess > p)
void run(std::shared_ptr< inp::Input > &deck)
bool contacted() const
Definition main.cpp:322
double H1() const
Definition main.cpp:323
double CR() const
Definition main.cpp:330
RestitutionProbe(double H0)
Definition main.cpp:288
std::vector< std::pair< double, double > > d_samples
Definition main.cpp:344
const std::vector< std::pair< double, double > > & samples() const
Definition main.cpp:327
double tH1() const
Definition main.cpp:326
double d_minGap
Definition main.cpp:339
void checkStop(data::ModelData &data) override
Definition main.cpp:290
double tMin() const
Definition main.cpp:325
double minGap() const
Definition main.cpp:324
double d_tMin
Definition main.cpp:340
A class to store model data.
Definition modelData.h:50
std::vector< float > d_Z
Damage at nodes.
Definition modelData.h:818
std::vector< util::Point > d_u
Displacement of the nodes.
Definition modelData.h:748
std::vector< particle::BaseParticle * > d_particlesListTypeParticle
List of particles.
Definition modelData.h:707
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
json buildInputJson(const std::string &output_path_for_deck, const std::filesystem::path &mesh_file_1, const std::filesystem::path &mesh_file_2, double final_time, size_t num_steps, bool zero_ic, double mesh_size_in, double horizon_in, bool damping_on, double eps_n, bool two_particle_test, bool file_mesh, double beta_n_factor, const std::string &damping_law="com_and_node", const std::string &friction_law="coulomb_simple", bool friction_on=false, double friction_mu=-1., double ic_vx=0., bool bottom_patch_bc=false, const std::string &mpi_strategy="auto")
Definition main.cpp:91
Definition contact.h:20
void writeGeometry(json &j, const geom::GeomData &geomData)
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.
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
bool isMpiEnabled()
Function to check if MPI is enabled.
unsigned int getNThreads()
Get number of threads to be used by taskflow.
void initNThreads(unsigned int nThreads=std::thread::hardware_concurrency())
Initializes MpiStatus struct.
const MpiStatus * getMpiStatus()
Returns pointer to 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
double cr
Definition main.cpp:68
double eps
Definition main.cpp:67
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
Jha2021Table2 jha2021Table2(int test_id)
Definition main.cpp:71
int main()
Definition main.cpp:31