PolyFEM
Loading...
Searching...
No Matches
GrowthElasticVarForm.cpp
Go to the documentation of this file.
2
9
13
16
18
27
33
34#include <igl/Timer.h>
35
36#include <polysolve/linear/Solver.hpp>
37#include <polysolve/nonlinear/Solver.hpp>
38
39#include <algorithm>
40#include <array>
41#include <cassert>
42#include <fstream>
43#include <limits>
44#include <iomanip>
45#include <vector>
46
47namespace polyfem::varform
48{
49 namespace
50 {
51 json first_material(const json &materials)
52 {
53 return materials.is_array() ? materials.front() : materials;
54 }
55
56 void disable_newton_psd_projection(json &solver_params)
57 {
58 const auto disable_for_newton = [](json &params) {
59 if (!params.contains("Newton") || params["Newton"].is_null())
60 params["Newton"] = json::object();
61 params["Newton"]["use_psd_projection"] = false;
62 };
63
64 if (solver_params.contains("solver") && solver_params["solver"].is_array())
65 {
66 for (json &strategy : solver_params["solver"])
67 {
68 const std::string type = strategy.value("type", "");
69 if (type == "Newton" || type == "SparseNewton" || type == "sparse_newton"
70 || type == "DenseNewton" || type == "dense_newton")
71 disable_for_newton(strategy);
72 }
73 }
74 else
75 {
76 disable_for_newton(solver_params);
77 }
78 }
79
80 json solver_params_for_residual_mode(const json &solver_params, const bool is_residual)
81 {
82 json params = solver_params;
83 if (is_residual)
84 disable_newton_psd_projection(params);
85 return params;
86 }
87
88 void assert_same_space_ids(
89 const json &materials,
90 const int displacement_space_id,
91 const int growth_space_id)
92 {
93 for (const json &material : utils::json_as_array(materials))
94 {
95 if (material.at("displacement_space_id").get<int>() != displacement_space_id
96 || material.at("growth_space_id").get<int>() != growth_space_id)
97 {
98 log_and_throw_error("All GrowthElasticity materials must use the same FE space ids.");
99 }
100 }
101 }
102
103 json elastic_material_from_growth_material(const json &material)
104 {
105 if (!material.contains("elastic_material") || !material["elastic_material"].is_object())
106 log_and_throw_error("GrowthElasticity requires elastic_material to be an elastic material object.");
107
108 json elastic_material = material["elastic_material"];
109 const std::string type = elastic_material.value("type", "");
111 log_and_throw_error("GrowthElasticity elastic_material must be an elastic material, got '{}'.", type);
112
113 if (material.contains("id"))
114 elastic_material["id"] = material["id"];
115 if (material.contains("rho"))
116 elastic_material["rho"] = material["rho"];
117
118 return elastic_material;
119 }
120
121 std::string elastic_formulation_from_growth_materials(const json &materials)
122 {
123 std::string formulation;
124 for (const json &material : utils::json_as_array(materials))
125 {
126 const json elastic_material = elastic_material_from_growth_material(material);
127 const std::string type = elastic_material["type"];
128 if (formulation.empty())
129 formulation = type;
130 else if (formulation != type)
131 formulation = "MultiModels";
132 }
133
134 return formulation;
135 }
136
137 StiffnessMatrix block_diag(const StiffnessMatrix &a, const StiffnessMatrix &b)
138 {
139 std::vector<Eigen::Triplet<double>> entries;
140 entries.reserve(a.nonZeros() + b.nonZeros());
141
142 for (int k = 0; k < a.outerSize(); ++k)
143 for (StiffnessMatrix::InnerIterator it(a, k); it; ++it)
144 entries.emplace_back(it.row(), it.col(), it.value());
145
146 for (int k = 0; k < b.outerSize(); ++k)
147 for (StiffnessMatrix::InnerIterator it(b, k); it; ++it)
148 entries.emplace_back(a.rows() + it.row(), a.cols() + it.col(), it.value());
149
150 StiffnessMatrix out(a.rows() + b.rows(), a.cols() + b.cols());
151 out.setFromTriplets(entries.begin(), entries.end());
152 out.makeCompressed();
153 return out;
154 }
155
156 StiffnessMatrix identity_mass(const int size)
157 {
158 return utils::sparse_identity(size, size);
159 }
160 } // namespace
161
163 {
167 growth_problem_ = nullptr;
170 growth_assembler_ = nullptr;
171 growthelastic_assembler_ = nullptr;
172 growth_mass_assembler_ = nullptr;
173 growth_rhs_assembler_ = nullptr;
174 growth_rhs_density_ = std::make_shared<assembler::NoDensity>();
175 growth_mass_.resize(0, 0);
176 stacked_lumped_mass_.resize(0, 0);
177 growth_rhs_.resize(0, 0);
178 growth_coupling_form_ = nullptr;
179 stacked_form_ = nullptr;
180 converged_solution_.resize(0, 0);
181 prescribed_growth_.resize(0, 0);
183 growth_space_id_ = -1;
184 elastic_formulation_ = "MaterialSum";
186 threshold_per_element_.resize(0);
187 threshold_parallel_.resize(0);
188 shear_supply_.resize(0);
189 setup_logged_ = false;
190 threshold_clamped_.resize(0);
191 lag_residual_.resize(0);
192 attainment_.resize(0);
193 dissipation_.resize(0);
194 shear_work_.resize(0);
195 element_volume_.resize(0);
197 growth_node_volume_.resize(0);
198 growth_node_weights_.resize(0);
199 theta_n_.resize(0);
200 pinned_growth_nodes_.clear();
201 growth_pinned_mask_.clear();
202 growth_activation_step_.resize(0);
203 dissipation_form_ = nullptr;
204 }
205
207 {
209 const json material = first_material(args["materials"]);
210 if (!material.contains("growth_law") || material["growth_law"].is_null())
211 return;
212
213 // jse always injects the block with its defaults, so "off" is the
214 // threshold sentinel "none" (the default), not an absent block. A block
215 // whose other settings were changed but whose threshold was left out is
216 // refused rather than silently ignored.
217 const json &gl = material["growth_law"];
218 const bool from_state = gl.contains("threshold") && gl["threshold"].is_string() && gl["threshold"] == "from_state";
219 const bool has_threshold = from_state || (gl.contains("threshold") && (gl["threshold"].is_number() || gl["threshold"].is_object()));
220 if (!has_threshold)
221 {
222 const GrowthLawSettings d;
223 if (gl.value("n_steps", d.n_steps) != d.n_steps || gl.value("t_end", d.t_end) != d.t_end
224 || gl.value("max_active_set_iterations", d.max_active_set_iterations) != d.max_active_set_iterations
225 || gl.value("active_set_tol", d.active_set_tol) != d.active_set_tol
226 || gl.value("feasibility_tol", d.feasibility_tol) != d.feasibility_tol
227 || gl.value("theta_floor_fraction", d.theta_floor_fraction) != d.theta_floor_fraction
228 || gl.value("save_increments", d.save_increments) != d.save_increments
229 || gl.value("theta_crit", d.theta_crit) != d.theta_crit
230 || gl.value("relag_tol", d.relag_tol) != d.relag_tol
231 || gl.value("relag_max_updates", d.relag_max_updates) != d.relag_max_updates
232 || gl.value("final_tol_factor", d.final_tol_factor) != d.final_tol_factor
233 || gl.value("max_increment_splits", d.max_increment_splits) != d.max_increment_splits)
234 log_and_throw_error("GrowthElasticity growth_law settings are given but no threshold "
235 "(a number in Pa, a per_element_file, or \"from_state\"); set one to enable the law.");
236 return;
237 }
238
239 growth_law_.enabled = true;
240 growth_law_.from_state = from_state;
241 growth_law_.n_steps = gl.value("n_steps", growth_law_.n_steps);
242 growth_law_.t_end = gl.value("t_end", growth_law_.t_end);
243 growth_law_.max_active_set_iterations = gl.value("max_active_set_iterations", growth_law_.max_active_set_iterations);
244 growth_law_.active_set_tol = gl.value("active_set_tol", growth_law_.active_set_tol);
245 growth_law_.feasibility_tol = gl.value("feasibility_tol", growth_law_.feasibility_tol);
246 growth_law_.theta_floor_fraction = gl.value("theta_floor_fraction", growth_law_.theta_floor_fraction);
247 growth_law_.save_increments = gl.value("save_increments", growth_law_.save_increments);
248 growth_law_.theta_crit = gl.value("theta_crit", growth_law_.theta_crit);
249 growth_law_.relag_tol = gl.value("relag_tol", growth_law_.relag_tol);
250 growth_law_.relag_max_updates = gl.value("relag_max_updates", growth_law_.relag_max_updates);
251 growth_law_.final_tol_factor = gl.value("final_tol_factor", growth_law_.final_tol_factor);
252 growth_law_.max_increment_splits = gl.value("max_increment_splits", growth_law_.max_increment_splits);
254 log_and_throw_error("growth_law max_increment_splits must be >= 0.");
256 log_and_throw_error("growth_law relag_max_updates must be >= 0 (0 = no cap).");
257 if (!(growth_law_.relag_tol > 0))
258 log_and_throw_error("growth_law relag_tol must be positive.");
260 log_and_throw_error("growth_law final_tol_factor must be in (0, 1], got {}.", growth_law_.final_tol_factor);
262 log_and_throw_error("growth_law threshold \"from_state\" needs theta_crit > 0 (the C_check construction).");
263 if (growth_law_.theta_crit < 0)
264 log_and_throw_error("growth_law theta_crit must be >= 0.");
265
266 if (growth_law_.n_steps < 1)
267 log_and_throw_error("growth_law n_steps must be >= 1, got {}.", growth_law_.n_steps);
268 if (!(growth_law_.t_end > 0))
269 log_and_throw_error("growth_law t_end must be positive, got {}.", growth_law_.t_end);
271 log_and_throw_error("growth_law max_active_set_iterations must be >= 1.");
272
273 // Solved and prescribed growth are different modes of the same field;
274 // the formulation allows partial prescription, but not through this
275 // switch, so refuse the ambiguous combination rather than pick one.
276 const std::string nodal = args["boundary_conditions"].value("growth_nodal_field", "");
277 if (!nodal.empty())
278 log_and_throw_error("growth_law (solved growth) cannot be combined with growth_nodal_field (prescribed growth).");
279
280 for (const json &m : utils::json_as_array(args["materials"]))
281 if (m.contains("growth_law") && m["growth_law"] != gl)
282 log_and_throw_error("All GrowthElasticity materials must share one growth_law block "
283 "(per-element thresholds go in the threshold file).");
284 }
285
287 io::CheckpointWriter &writer,
288 const Eigen::MatrixXd &solution,
289 const io::CheckpointMetadata &metadata) const
290 {
291 VarForm::serialize_checkpoint(writer, solution, metadata);
292 write_checkpoint_ordering(writer, "primary", space_);
293 write_checkpoint_ordering(writer, "growth", growth_space_);
294 }
295
297 const io::CheckpointReader &reader,
298 Eigen::MatrixXd &solution)
299 {
300 VarForm::deserialize_checkpoint(reader, solution);
303 reader, "primary", space_,
304 mesh_->dimension(), 0, solution);
306 reader, "growth", growth_space_,
307 1, displacement_ndof(), solution);
308 }
309
316
318 const std::string &formulation,
319 const Units &units,
320 const json &args,
321 const std::string &out_path)
322 {
323 for (const std::string field : {"pressure_boundary", "pressure_cavity"})
324 {
325 const json::json_pointer path("/boundary_conditions/" + field);
326 if (args.contains(path) && !args.at(path).empty())
327 log_and_throw_error("{} does not support boundary_conditions.{}.", formulation, field);
328 }
329
330 VarForm::init(formulation, units, args, out_path);
333
334 // No dynamics: prescribed growth is a single static solve, and solved
335 // growth (growth_law) steps its own quasi-static pseudo-time through
336 // growth_law.n_steps / t_end, evaluating the displacement Dirichlet
337 // expressions at each increment's t. PolyFEM's "time" block (inertia,
338 // integrators) is not used.
339 if (args.contains("time") && !args["time"].is_null())
340 log_and_throw_error("GrowthElasticity has no dynamics: use growth_law.n_steps / t_end for pseudo-time, not \"time\".");
341
342 // Contact is inherited u-block machinery and structurally functional here
343 // (collision mesh, barrier stiffness update), but the growth+contact
344 // combination is untested; decline loudly until it has its own validation.
345 if (args["contact"]["enabled"].get<bool>())
346 log_and_throw_error("GrowthElasticity does not yet support contact (untested combination).");
347
349 if (args["solver"]["advanced"]["check_inversion"] == "Conservative")
350 {
351 if (auto elastic_assembler = std::dynamic_pointer_cast<assembler::ElasticityAssembler>(primary_assembler_))
352 elastic_assembler->set_use_robust_jacobian();
353 }
354
355 // The growth space carries no PDE of its own: this Laplacian is used
356 // purely structurally (FE-space construction and Dirichlet-value
357 // plumbing through the RhsAssembler); it is never registered as a form.
358 // Its material parameter is therefore optional and unused; the name
359 // reserves the slot a gradient regularizer of theta would occupy.
360 growth_assembler_ = std::make_shared<assembler::Laplacian>("growth_diffusivity");
362 mass_assembler_ = std::make_shared<assembler::Mass>();
363 pure_mass_assembler_ = std::make_shared<assembler::HRZMass>();
364 // Unit-density mass on the growth space: a well-conditioned Gram
365 // matrix for the augmented-Lagrangian BC form (the growth material has
366 // no physical density).
367 growth_mass_assembler_ = std::make_shared<assembler::Mass>(std::make_shared<assembler::NoDensity>());
368
369 problem = std::make_shared<assembler::GenericTensorProblem>("GrowthDisplacement");
370 problem->clear();
371 growth_problem_ = std::make_shared<assembler::GenericScalarProblem>("GrowthField");
372 growth_problem_->clear();
373
374 json tmp;
375 tmp["is_time_dependent"] = false;
376 problem->set_parameters(tmp, resources_);
377 growth_problem_->set_parameters(tmp, resources_);
378 // Solved growth evaluates the displacement Dirichlet expressions at each
379 // pseudo-time increment (the Dirichlet ramp), so they are not constant
380 // in time. The growth problem stays static: its only Dirichlet data are
381 // the active-set pins, which carry tabulated targets.
383 {
384 json td;
385 td["is_time_dependent"] = true;
386 problem->set_parameters(td, resources_);
387 }
388
389 auto bc = args["boundary_conditions"];
390 problem->set_parameters(bc, resources_);
391 growth_problem_->set_parameters(bc, resources_);
392 problem->set_parameters(args["initial_conditions"], resources_);
393 growth_problem_->set_parameters(args["initial_conditions"], resources_);
394 problem->set_parameters(args["output"], resources_);
395 growth_problem_->set_parameters(args["output"], resources_);
396
397 problem->set_units(*primary_assembler_, units);
399
400 t0 = 0.0;
401 time_steps = 0;
402 dt = 0.0;
403 contact_dhat_was_explicit_ = args["contact"].value("_dhat_was_explicit", false);
404 this->args["contact"].erase("_dhat_was_explicit");
405 }
406
408 {
409 const json material = first_material(args.at("materials"));
410 displacement_space_id_ = material.at("displacement_space_id").get<int>();
411 growth_space_id_ = material.at("growth_space_id").get<int>();
413 log_and_throw_error("GrowthElasticity requires distinct displacement and growth FE spaces.");
414
415 elastic_formulation_ = elastic_formulation_from_growth_materials(args.at("materials"));
416 assert_same_space_ids(args.at("materials"), displacement_space_id_, growth_space_id_);
417 }
418
420 {
421 if (args["materials"].is_array())
422 {
423 json materials = json::array();
424 for (const json &material : args["materials"])
425 materials.push_back(elastic_material_from_growth_material(material));
426 return materials;
427 }
428
429 return elastic_material_from_growth_material(args["materials"]);
430 }
431
432 void GrowthElasticVarForm::load_mesh(const mesh::Mesh &mesh, const json &args)
433 {
434 assert(mesh_);
435 std::vector<int> body_ids(mesh.n_elements());
436 for (int i = 0; i < mesh.n_elements(); ++i)
437 body_ids[i] = mesh.get_body_id(i);
438
439 const json elastic_materials = elastic_material_args();
440
441 primary_assembler_->set_size(mesh.dimension());
442 primary_assembler_->set_materials(body_ids, elastic_materials, units, resources_);
443 growthelastic_assembler_->set_size(mesh.dimension());
444 growthelastic_assembler_->set_materials(body_ids, args["materials"], units, resources_);
445 mass_assembler_->set_size(mesh.dimension());
446 mass_assembler_->set_materials(body_ids, elastic_materials, units, resources_);
447 pure_mass_assembler_->set_size(mass_assembler_->size());
448
449 growth_assembler_->set_size(1);
450 growth_assembler_->set_materials(body_ids, args["materials"], units, resources_);
451 growth_mass_assembler_->set_size(1);
452 // no set_materials: the growth mass uses NoDensity (unit density), which
453 // throws on add_multimaterial by design -- it needs no material setup
454
455 problem->init(mesh);
456 growth_problem_->init(mesh);
457 }
458
459 void GrowthElasticVarForm::build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args_in)
460 {
461 // Solved growth needs more than the centroid rule. At P1 the default
462 // quadrature is one point per tet, so the coupling energy and the
463 // dissipation see theta only through element averages, and nodal
464 // patterns with zero average on every element are exact null modes
465 // (hourglass modes of the growth field; on a Kuhn-split cube every tet
466 // holds one node of each class (i+j+k) mod 4, and the solve converged to
467 // such a pattern). With order >= 2 (four points on a tet) the nodal values map
468 // invertibly onto the point values, and the energy, convex in theta
469 // pointwise, fixes them. Prescribed growth is unaffected (theta is
470 // data), so only the solved mode raises it. Both spaces share the order
471 // (MixedAssemblerForm requires matching quadrature). Done here, on a
472 // local copy, because State re-injects its args after init().
473 json args = args_in;
474 if (growth_law_.enabled && args["space"]["advanced"]["quadrature_order"].get<int>() < 2)
475 {
476 logger().info("growth_law: quadrature_order raised to 2 "
477 "(the centroid rule leaves the P1 growth field with null modes).");
478 args["space"]["advanced"]["quadrature_order"] = 2;
479 }
480
481 assert(problem);
482 assert(growth_problem_);
483 assert(primary_assembler_);
484 assert(growth_assembler_);
485
486 Eigen::VectorXi displacement_orders, displacement_ordersq;
487 assign_discr_orders(args["space"], displacement_space_id_, mesh, displacement_orders, displacement_ordersq);
488
489 if (args["space"]["use_p_ref"])
490 {
492 mesh,
493 args["space"]["advanced"]["B"],
494 args["space"]["advanced"]["h1_formula"],
495 args["space"]["discr_order"],
496 args["space"]["advanced"]["discr_order_max"],
497 stats,
498 displacement_orders);
499
500 logger().info("min p: {} max p: {}", displacement_orders.minCoeff(), displacement_orders.maxCoeff());
501 }
502
504 mesh,
505 iso_parametric,
506 displacement_orders,
507 displacement_ordersq,
508 args["space"]["basis_type"],
509 args["space"]["poly_basis_type"],
511 mesh.dimension(),
512 args["space"]["advanced"]["quadrature_order"],
513 args["space"]["advanced"]["mass_quadrature_order"],
514 args["space"]["advanced"]["use_corner_quadrature"],
515 args["space"]["advanced"]["n_harmonic_samples"],
516 args["space"]["advanced"]["integral_constraints"],
517 space_,
518 boundary_);
519
520 problem->update_nodes(space_.space_in_node_to_node);
522
523 const int n_fe_bases = space_.n_bases;
525
526 logger().info("Building collision mesh...");
529 logger().info("Done!");
530
531 for (int i = n_fe_bases; i < space_.n_bases; ++i)
532 {
533 for (int d = 0; d < mesh.dimension(); ++d)
534 boundary_.boundary_nodes.push_back(i * mesh.dimension() + d);
535 }
537
538 build_growth_basis(mesh, iso_parametric, args);
540
541 const auto &current_bases = space_.geometry_basis_list();
542 if (args["space"]["advanced"]["count_flipped_els"])
543 stats.count_flipped_elements(mesh, current_bases);
544
545 const int n_samples = 10;
546 stats.compute_mesh_size(mesh, current_bases, n_samples, args["output"]["advanced"]["curved_mesh_size"]);
547 logger().info("flipped elements {}", stats.n_flipped);
548 logger().info("h: {}", stats.mesh_size);
549
550 if (std::max(space_.n_bases, growth_space_.n_bases) <= args["solver"]["advanced"]["cache_size"])
551 {
552 igl::Timer timer;
553 timer.start();
554 logger().info("Building cache...");
555 ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases);
556 mass_ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases, true);
557 pure_mass_ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases, true);
560 logger().info(" took {}s", timer.getElapsedTime());
561 }
562 else
563 {
569 }
570 }
571
573 {
575
576 problem->setup_bc(
577 mesh,
584 mesh.dimension());
585 std::vector<int> unused_neumann_boundary_nodes;
586 problem->setup_bc(
587 mesh,
593 unused_neumann_boundary_nodes,
594 mesh.dimension());
595
596 problem->setup_nodal_bc(
597 space_.mesh_nodes.get(),
602 problem->setup_nodal_bc(
603 space_.mesh_nodes.get(),
608
609 for (const int n_id : boundary_.dirichlet_nodes)
610 {
611 const int tag = space_.node_tag(n_id);
612 for (int d = 0; d < mesh.dimension(); ++d)
613 if (problem->is_nodal_dimension_dirichlet(n_id, tag, d, displacement_space_id_))
614 boundary_.boundary_nodes.push_back(n_id * mesh.dimension() + d);
615 }
616
620 }
621
622 void GrowthElasticVarForm::build_growth_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args)
623 {
624 Eigen::VectorXi growth_orders, growth_ordersq;
625 assign_discr_orders(args["space"], growth_space_id_, mesh, growth_orders, growth_ordersq);
626
628 mesh,
629 iso_parametric,
630 growth_orders,
631 growth_ordersq,
632 args["space"]["basis_type"],
633 args["space"]["poly_basis_type"],
635 /*value_dim=*/1,
636 args["space"]["advanced"]["quadrature_order"],
637 args["space"]["advanced"]["mass_quadrature_order"],
638 args["space"]["advanced"]["use_corner_quadrature"],
639 args["space"]["advanced"]["n_harmonic_samples"],
640 args["space"]["advanced"]["integral_constraints"],
644
645 // build_fe_space builds the input->internal node map only for spaces that
646 // own their geometry; the growth space shares the displacement geometry,
647 // so it must build its own (else growth_nodal_field values would be placed
648 // in internal order).
649 build_node_mapping(mesh, args["space"]["basis_type"], growth_space_,
652
653 // PolyFEM computes no input orderings for this mesh path, so the call
654 // above returns an empty map. For P1 each growth node lies on one mesh
655 // vertex, and the loader keeps mesh vertices in file order, so the
656 // vertex -> node table of the growth space IS the input -> node map.
658 && growth_space_.disc_orders.size() > 0
659 && growth_space_.disc_orders.minCoeff() == 1 && growth_space_.disc_orders.maxCoeff() == 1)
660 {
661 const auto &p2n = growth_space_.mesh_nodes->primitive_to_node();
662 const int nv = mesh.n_vertices();
663 Eigen::VectorXi vmap(nv);
664 for (int v = 0; v < nv; ++v)
665 {
666 const int n = p2n[growth_space_.mesh_nodes->primitive_from_vertex(v)];
667 if (n < 0 || n >= growth_space_.n_bases)
668 log_and_throw_error("GrowthElasticity: mesh vertex {} has no P1 growth node ({}).", v, n);
669 vmap(v) = n;
670 }
672 logger().info("GrowthElasticity: growth node map built from mesh vertices ({} nodes).", nv);
673 }
674
675 logger().info("n growth bases: {}", growth_space_.n_bases);
676 }
677
679 {
681
683
684 growth_problem_->setup_bc(
685 mesh,
692 /*value_dim=*/1);
693 std::vector<int> unused_neumann_boundary_nodes;
694 growth_problem_->setup_bc(
695 mesh,
701 unused_neumann_boundary_nodes,
702 /*value_dim=*/1);
703
704 growth_problem_->setup_nodal_bc(
710 growth_problem_->setup_nodal_bc(
716
717 for (const int n_id : growth_boundary_.dirichlet_nodes)
718 growth_boundary_.boundary_nodes.push_back(n_id);
719
723 }
724
726 {
727 json rhs_solver_params = args["solver"]["linear"];
728 if (!rhs_solver_params.contains("Pardiso"))
729 rhs_solver_params["Pardiso"] = {};
730 rhs_solver_params["Pardiso"]["mtype"] = -2;
731
732 solve_data_.rhs_assembler = std::make_shared<assembler::RhsAssembler>(
738 args["space"]["advanced"]["bc_method"],
739 rhs_solver_params,
742
743 growth_rhs_assembler_ = std::make_shared<assembler::RhsAssembler>(
747 growth_space_.n_bases, /*size=*/1,
750 args["space"]["advanced"]["bc_method"],
751 rhs_solver_params,
753 }
754
756 {
757 igl::Timer timer;
758 json p_params = {};
759 p_params["formulation"] = primary_assembler_->name();
760 {
761 RowVectorNd min, max, delta;
762 mesh.bounding_box(min, max);
763 delta = (max - min) / 2. + min;
764 if (mesh.is_volume())
765 p_params["bbox_center"] = {delta(0), delta(1), delta(2)};
766 else
767 p_params["bbox_center"] = {delta(0), delta(1)};
768 }
769 problem->set_parameters(p_params, resources_);
770 growth_problem_->set_parameters(p_params, resources_);
771
772 rhs_.resize(0, 0);
773 growth_rhs_.resize(0, 0);
774
775 timer.start();
776 logger().info("Assigning rhs...");
777
779 assert(rhs_assembler_ != nullptr);
780 assert(growth_rhs_assembler_ != nullptr);
781 assert(growth_rhs_density_ != nullptr);
782 rhs_assembler_->assemble(mass_assembler_->density(), rhs_);
783 rhs_ *= -1;
785 growth_rhs_ *= -1;
786
787 timings.assigning_rhs_time = timer.getElapsedTime();
788 logger().info(" took {}s", timings.assigning_rhs_time);
789 }
790
792 {
793 mass_.resize(0, 0);
794 pure_mass_.resize(0, 0);
795 growth_mass_.resize(0, 0);
796
797 igl::Timer timer;
798 timer.start();
799 logger().info("Assembling mass mat...");
800
804
805 assert(mass_.size() > 0);
806 avg_mass_ = 0;
807 for (int k = 0; k < mass_.outerSize(); ++k)
808 for (StiffnessMatrix::InnerIterator it(mass_, k); it; ++it)
809 avg_mass_ += it.value();
810 avg_mass_ /= mass_.rows();
811 logger().info("average mass {}", avg_mass_);
812
813 if (args["solver"]["advanced"]["lump_mass_matrix"])
814 {
817 }
818
819 // Static problem: the stacked lumped mass only feeds the nonlinear
820 // problem's scaling. Identity on the growth block (no physical mass).
821 stacked_lumped_mass_ = block_diag(
822 pure_mass_.size() > 0 ? pure_mass_ : identity_mass(displacement_ndof()),
823 identity_mass(growth_ndof()));
824
825 timer.stop();
826 timings.assembling_mass_mat_time = timer.getElapsedTime();
827 logger().info(" took {}s", timings.assembling_mass_mat_time);
828
831 stats.mat_size = (long long)stacked_lumped_mass_.rows() * (long long)stacked_lumped_mass_.cols();
832 logger().info("sparsity: {}/{}", stats.nn_zero, stats.mat_size);
833 }
834
836 {
837 if (prescribed_growth_.size() > 0)
838 return prescribed_growth_;
839
840 const std::string path = args["boundary_conditions"]["growth_nodal_field"];
841 if (path.empty())
842 return prescribed_growth_; // empty: no whole-field prescription
843
844 auto input = resources_.open(path, false);
845 if (!input || !*input)
846 log_and_throw_error("GrowthElasticity: cannot open growth_nodal_field '{}'.", resources_.describe(path));
847 std::istream &in = *input;
848
849 std::vector<double> values;
850 values.reserve(growth_ndof());
851 double v;
852 while (in >> v)
853 values.push_back(v);
854
855 if (int(values.size()) != growth_ndof())
857 "GrowthElasticity: growth_nodal_field '{}' has {} values, expected {} (one per growth node, mesh-vertex order).",
858 path, values.size(), growth_ndof());
859
860 Eigen::MatrixXd field = Eigen::Map<Eigen::VectorXd>(values.data(), values.size());
861
862 // Mesh-vertex (input) -> internal node order. The internal order is NOT
863 // the file order in general, and no augmented-Lagrangian diagnostic can
864 // catch a wrong map here: initial and target both come from this function.
865 const auto &map = growth_space_.space_in_node_to_node;
866 if (map.size() != field.rows())
868 "GrowthElasticity: growth-space node map has {} entries for {} values; "
869 "growth_nodal_field cannot be placed on the right nodes.",
870 map.size(), field.rows());
871 Eigen::MatrixXd remapped(field.rows(), 1);
872 for (int i = 0; i < map.size(); ++i)
873 remapped(map(i)) = field(i);
874 field = remapped;
875
876 if ((field.array() <= 0).any())
878 "GrowthElasticity: growth_nodal_field '{}' contains non-positive theta (min {}).",
879 path, field.minCoeff());
880
881 prescribed_growth_ = field;
882 return prescribed_growth_;
883 }
884
885 void GrowthElasticVarForm::initial_growth_solution(Eigen::MatrixXd &solution) const
886 {
887 // A whole-field prescription is also the initial solution: initial ==
888 // target makes the AL start error ~0 and the first iterate consistent.
889 const Eigen::MatrixXd &prescribed = prescribed_growth_field();
890 if (prescribed.size() > 0)
891 {
892 solution = prescribed;
893 return;
894 }
895
896 assert(growth_rhs_assembler_ != nullptr);
897 growth_rhs_assembler_->initial_solution(solution);
898
899 // theta = 0 is singular (Fg not invertible); the harmless zero default
900 // of the temperature precedent is fatal here, so an all-zero initial
901 // growth field -- i.e. no initial_conditions entry for the growth
902 // space -- is replaced by the identity, theta = 1, making the
903 // first iterate pure elasticity per the formulation's initialization
904 // convention. A user-prescribed nonzero field is left untouched.
905 if (solution.size() > 0 && (solution.array() == 0.0).all())
906 {
907 logger().info("Growth field initialized to theta = 1 (identity growth).");
908 solution.setOnes();
909 }
910 }
911
913 const Eigen::MatrixXd &displacement,
914 const Eigen::MatrixXd &growth) const
915 {
916 assert(displacement.rows() == displacement_ndof());
917 assert(growth.rows() == growth_ndof());
918 assert(displacement.cols() == growth.cols());
919
920 Eigen::MatrixXd solution(displacement.rows() + growth.rows(), displacement.cols());
921 solution << displacement, growth;
922 return solution;
923 }
924
926 const Eigen::MatrixXd &solution,
927 Eigen::MatrixXd &displacement,
928 Eigen::MatrixXd &growth) const
929 {
930 assert(solution.rows() == total_ndof());
931 displacement = solution.topRows(displacement_ndof());
932 growth = solution.bottomRows(growth_ndof());
933 }
934
935 void GrowthElasticVarForm::build_forms(Eigen::MatrixXd &solution, const double t)
936 {
937 assert(solution.cols() == 1);
938 assert(solution.rows() == total_ndof());
939
940 stacked_form_ = std::make_shared<solver::StackedForm>();
941 const auto displacement_block = stacked_form_->add_block(displacement_ndof());
942 const auto growth_block = stacked_form_->add_block(growth_ndof());
943
944 Eigen::MatrixXd displacement, growth;
945 split_solution(solution, displacement, growth);
946
948
949 init_forms(args, mesh_->dimension(), displacement, t);
950 for (const auto &form : forms)
951 {
952 assert(form);
953 stacked_form_->add(displacement_block, form);
954 }
955 solve_data_.al_form.clear();
956
957 // No growth-block form: theta has no PDE of its own. The growth block's
958 // stiffness is the K_gg quadrant of the coupling form below plus the
959 // augmented-Lagrangian boundary form; with every growth DOF prescribed
960 // the reduced problem contains only displacements.
961
963 growth_coupling_form_ = std::make_shared<solver::MixedAssemblerForm>(
967 t, /*dt=*/0.0, mesh_->is_volume());
968 stacked_form_->add(displacement_block, growth_block, growth_coupling_form_);
969
970 // Solved growth: the rate-independent dissipation on the growth block.
971 // It sits inside stacked_form_, so the stacked gradient's growth rows
972 // are dPi_inc/dtheta (the KKT residual of the active-set loop).
973 dissipation_form_ = nullptr;
975 {
976 assert(growth_node_weights_.size() == growth_ndof());
977 assert(theta_n_.size() == growth_ndof());
978 dissipation_form_ = std::make_shared<solver::GrowthDissipationForm>(
980 stacked_form_->add(growth_block, dissipation_form_);
981 }
982
983 forms.clear();
984 forms.push_back(stacked_form_);
985 for (const auto &form : forms)
986 form->set_output_dir(output_path);
987
988 solve_data_.al_form.clear();
989 const bool has_growth_pins = growth_law_.enabled && !pinned_growth_nodes_.empty();
991 || prescribed_growth_field().size() > 0 || has_growth_pins)
992 {
993 auto stacked_al = std::make_shared<solver::StackedAugmentedLagrangianForm>();
994 const auto displacement_al_block = stacked_al->add_block(displacement_block.size());
995 const auto growth_al_block = stacked_al->add_block(growth_block.size());
996
997 if (!boundary_.boundary_nodes.empty())
998 {
999 // Prescribed growth is one static solve; solved growth steps the
1000 // displacement Dirichlet data through pseudo-time.
1001 stacked_al->add(
1002 displacement_al_block,
1003 std::make_shared<solver::BCLagrangianForm>(
1004 displacement_block.size(),
1007 obstacle.n_vertices() * mesh_->dimension(),
1008 /*is_time_dependent=*/growth_law_.enabled, t));
1009 }
1010
1011 const Eigen::MatrixXd &prescribed = prescribed_growth_field();
1012 if (growth_law_.enabled)
1013 {
1014 // Active-set pins: every pinned growth DOF is Dirichlet at
1015 // theta_n (tabulated targets). The node list is a member because
1016 // BCLagrangianForm keeps a reference to it.
1017 if (!growth_boundary_.boundary_nodes.empty())
1018 log_and_throw_error("growth_law: growth-space dirichlet_boundary entries are not supported "
1019 "(the growth law owns the growth DOFs; tag displacement BCs with fe_space).");
1020 if (has_growth_pins)
1021 stacked_al->add(
1022 growth_al_block,
1023 std::make_shared<solver::BCLagrangianForm>(
1024 growth_block.size(), pinned_growth_nodes_, growth_mass_,
1025 /*obstacle_ndof=*/0, Eigen::MatrixXd(theta_n_)));
1026 }
1027 else if (prescribed.size() > 0)
1028 {
1029 // Whole-field prescription: every growth DOF is Dirichlet with
1030 // tabulated targets (BCLagrangianForm's target constructor; no
1031 // RhsAssembler involved). Supersedes any growth-space surface
1032 // Dirichlet entries.
1033 if (!growth_boundary_.boundary_nodes.empty())
1034 logger().warn("growth_nodal_field supersedes {} growth-space dirichlet_boundary node(s).", growth_boundary_.boundary_nodes.size());
1035
1036 std::vector<int> all_growth_nodes(growth_ndof());
1037 for (int i = 0; i < growth_ndof(); ++i)
1038 all_growth_nodes[i] = i;
1039
1040 stacked_al->add(
1041 growth_al_block,
1042 std::make_shared<solver::BCLagrangianForm>(
1043 growth_block.size(), all_growth_nodes, growth_mass_,
1044 /*obstacle_ndof=*/0, prescribed));
1045 }
1046 else if (!growth_boundary_.boundary_nodes.empty())
1047 {
1048 assert(growth_space_.disc_orders.size() > 0 && "Growth boundary quadrature requires initialized FE orders");
1049 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
1050 const QuadratureOrders growth_boundary_samples =
1051 n_boundary_samples(growth_space_.disc_orders.maxCoeff(), growth_space_.disc_ordersq.maxCoeff(), gdiscr_order);
1052
1053 stacked_al->add(
1054 growth_al_block,
1055 std::make_shared<solver::BCLagrangianForm>(
1056 growth_block.size(),
1058 growth_boundary_.local_neumann_boundary, growth_boundary_samples,
1060 /*obstacle_ndof=*/0, /*is_time_dependent=*/false, t));
1061 }
1062
1063 solve_data_.al_form.push_back(stacked_al);
1064 }
1065 }
1066
1067 void GrowthElasticVarForm::solve_nonlinear_step(const int step, Eigen::MatrixXd &solution, const double grad_tol_factor)
1068 {
1069 assert(solve_data_.nl_problem != nullptr && "Growth forms must initialize the nonlinear problem before solving");
1071
1072 json nonlinear_params = solver_params_for_residual_mode(args["solver"]["nonlinear"], nl_problem.is_residual());
1073 if (grad_tol_factor != 1.0 && nonlinear_params.contains("grad_norm_tol"))
1074 nonlinear_params["grad_norm_tol"] = nonlinear_params["grad_norm_tol"].get<double>() * grad_tol_factor;
1075 json al_nonlinear_params = solver_params_for_residual_mode(args["solver"]["augmented_lagrangian"]["nonlinear"], nl_problem.is_residual());
1076 // The AL subsolves run on the AL settings (as in the plain elastic VarForm);
1077 // the main Newton residual tolerance is carried over when it is looser, since
1078 // the penalty phase is where the gradient is largest (absolute test).
1079 if (nonlinear_params.contains("Newton") && nonlinear_params["Newton"].contains("residual_tolerance"))
1080 {
1081 const double main_tol = nonlinear_params["Newton"]["residual_tolerance"];
1082 const double al_tol = al_nonlinear_params.value("Newton", json::object()).value("residual_tolerance", 0.0);
1083 if (main_tol > al_tol)
1084 al_nonlinear_params["Newton"]["residual_tolerance"] = main_tol;
1085 }
1086
1087 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver =
1088 polysolve::nonlinear::Solver::create(
1089 nonlinear_params, args["solver"]["linear"],
1091
1092 if (nl_problem.uses_lagging())
1093 nl_problem.init_lagging(solution);
1094
1095 const auto update_displacement_barrier_stiffness = [&](const Eigen::VectorXd &x) {
1096 const Eigen::VectorXd displacement = x.head(displacement_ndof());
1098 };
1099
1100 if (!solve_data_.al_form.empty())
1101 {
1102 solver::ALSolver al_solver(
1104 args["solver"]["augmented_lagrangian"]["initial_weight"],
1105 args["solver"]["augmented_lagrangian"]["scaling"],
1106 args["solver"]["augmented_lagrangian"]["max_weight"],
1107 args["solver"]["augmented_lagrangian"]["eta"],
1108 update_displacement_barrier_stiffness);
1109
1110 al_solver.post_subsolve = [&](const double al_weight) {
1111 stats.solver_info.push_back(
1112 {{"type", al_weight > 0 ? "al" : "rc"},
1113 {"t", step},
1114 {"info", nl_solver->info()}});
1115 if (al_weight > 0)
1116 stats.solver_info.back()["weight"] = al_weight;
1117 save_subsolve(stats.solver_info.size(), step, solution);
1118 };
1119
1120 al_solver.solve_al(
1121 nl_problem, solution, al_nonlinear_params,
1122 args["solver"]["linear"], units.characteristic_length());
1123 al_solver.solve_reduced(
1124 nl_problem, solution, nonlinear_params,
1125 args["solver"]["linear"], units.characteristic_length(), nl_solver);
1126 return;
1127 }
1128
1129 Eigen::VectorXd x = solution;
1130 nl_problem.init(x);
1131 update_displacement_barrier_stiffness(x);
1132 nl_problem.normalize_forms();
1133 nl_solver->minimize(nl_problem, x);
1134 nl_problem.finish();
1135 solution = x;
1136 stats.solver_info.push_back({{"type", "rc"}, {"t", step}, {"info", nl_solver->info()}});
1137 save_subsolve(stats.solver_info.size(), step, solution);
1138 }
1139
1141 Eigen::MatrixXd &sol,
1142 const InitialConditionOverride *initial_condition_override,
1143 const ForwardStepCallback &post_step)
1144 {
1145 assert(!initial_condition_override && "GrowthElasticity does not support initial-condition overrides");
1146 assert(!post_step && "GrowthElasticity does not support post-step callbacks");
1147
1148 stats.spectrum.setZero();
1149
1150 igl::Timer timer;
1151 timer.start();
1152 logger().info("Solving GrowthElasticity");
1153
1154 {
1155 POLYFEM_SCOPED_TIMER("Setup RHS");
1156
1157 if (sol.size() <= 0)
1158 {
1159 Eigen::MatrixXd displacement, growth;
1160 initial_solution(displacement);
1162 const int cols = std::max(displacement.cols(), growth.cols());
1163 if (displacement.cols() != cols)
1164 displacement.conservativeResize(Eigen::NoChange, cols);
1165 if (growth.cols() != cols)
1166 growth.conservativeResize(Eigen::NoChange, cols);
1167 sol = stacked_solution(displacement, growth);
1168 }
1169
1170 if (sol.cols() > 1)
1171 sol.conservativeResize(Eigen::NoChange, 1);
1172 }
1173
1174 stats.solver_info = json::array();
1175
1176 if (growth_law_.enabled)
1177 {
1178 solve_growth_law(sol);
1179 }
1180 else
1181 {
1182 build_forms(sol, /*t=*/1.0);
1183 make_nl_problem(sol, /*t=*/1.0);
1184 solve_nonlinear_step(0, sol);
1185 }
1186 converged_solution_ = sol;
1187
1188 timer.stop();
1189 timings.solving_time = timer.getElapsedTime();
1190 logger().info(" took {}s", timings.solving_time);
1191 }
1192
1193 void GrowthElasticVarForm::make_nl_problem(const Eigen::MatrixXd &sol, const double t)
1194 {
1195 double characteristic_length = 0;
1196 if (args["solver"]["advanced"]["characteristic_length"] > 0)
1197 characteristic_length = args["solver"]["advanced"]["characteristic_length"];
1198 else
1199 {
1200 RowVectorNd min, max;
1201 mesh_->bounding_box(min, max);
1202 characteristic_length = (max - min).norm();
1203 }
1204
1205 double characteristic_force_density = 0;
1206 if (args["solver"]["advanced"]["characteristic_force_density"] <= 0)
1207 {
1208 logger().warn("No user-specified force density was provided, defaulting to 10000.");
1209 characteristic_force_density = 10000;
1210 }
1211 else
1212 characteristic_force_density = args["solver"]["advanced"]["characteristic_force_density"];
1213
1214 solve_data_.nl_problem = std::make_shared<solver::NLProblem>(
1215 total_ndof(), t,
1217 polysolve::linear::Solver::create(args["solver"]["linear"], logger()),
1218 characteristic_length, characteristic_force_density,
1219 stacked_lumped_mass_.size() > 0 ? stacked_lumped_mass_ : identity_mass(total_ndof()),
1220 mesh_->dimension(),
1221 /*is_time_dependent=*/false);
1222 solve_data_.nl_problem->init(sol);
1223 solve_data_.nl_problem->update_quantities(t, sol);
1224 }
1225
1226 // ======================================================================
1227 // Solved growth (growth_law)
1228 // ======================================================================
1229
1231 {
1232 const int n_el = mesh_->n_elements();
1233 const json material = first_material(args["materials"]);
1234 const json &gl = material["growth_law"];
1235
1236 const auto read_scalar_field = [&](const json &spec, const std::string &what,
1237 const std::string &default_field, Eigen::VectorXd &out) {
1238 if (spec.is_number())
1239 {
1240 out.setConstant(n_el, spec.get<double>());
1241 return;
1242 }
1243 if (!spec.is_object() || spec.value("type", "") != "per_element_file")
1244 log_and_throw_error("growth_law: {} must be a number or {{type: per_element_file, path, field}}.", what);
1245 const Eigen::MatrixXd values = assembler::read_growth_cell_array(
1246 resources_, spec.at("path").get<std::string>(), spec.value("field", default_field), 1);
1247 if (values.rows() != n_el)
1248 log_and_throw_error("growth_law: {} file has {} cells, mesh has {} elements.", what, values.rows(), n_el);
1249 out = values.col(0);
1250 };
1251
1253 {
1254 // set from the state on the elastic predictor, before any growth DOF is
1255 // released (the predictor does not depend on the threshold: every growth
1256 // DOF is pinned in pass 1)
1257 threshold_parallel_.setZero(n_el);
1258 shear_supply_.setZero(n_el);
1259 threshold_clamped_.setZero(n_el);
1260 threshold_per_element_.setZero(n_el);
1261 }
1262 else
1263 {
1264 read_scalar_field(gl.at("threshold"), "threshold", "PHI", threshold_per_element_);
1265 if (!threshold_per_element_.allFinite())
1266 log_and_throw_error("growth_law: threshold contains non-finite values.");
1267 }
1268
1269 normal_growth_per_element_.setOnes(n_el);
1270 if (material.contains("normal_growth"))
1271 read_scalar_field(material["normal_growth"], "normal_growth", "VN", normal_growth_per_element_);
1272 if (!(normal_growth_per_element_.array() > 0).all())
1273 log_and_throw_error("growth_law: normal_growth must be positive.");
1274
1276 }
1277
1278 double GrowthElasticVarForm::median_of(const Eigen::VectorXd &v)
1279 {
1280 if (v.size() == 0)
1281 return std::nan("");
1282 std::vector<double> s(v.data(), v.data() + v.size());
1283 std::nth_element(s.begin(), s.begin() + s.size() / 2, s.end());
1284 return s[s.size() / 2];
1285 }
1286
1288 {
1289 const int n_el = mesh_->n_elements();
1290
1291 // w_a = sum_e vn_e phi_e int_e N_a dV (growth basis, the element's own
1292 // quadrature), and the plain nodal volume int N_a dV for tolerances.
1297 for (int e = 0; e < n_el; ++e)
1298 {
1301 const Eigen::ArrayXd da = vals.det.array() * vals.quadrature.weights.array();
1302 const double coeff = normal_growth_per_element_(e) * threshold_per_element_(e);
1303 for (const auto &bv : vals.basis_values)
1304 {
1305 const double integral = (bv.val.array() * da).sum();
1306 for (const auto &g : bv.global)
1307 {
1308 growth_node_volume_(g.index) += g.val * integral;
1309 growth_node_vn_volume_(g.index) += g.val * integral * normal_growth_per_element_(e);
1310 growth_node_weights_(g.index) += g.val * integral * coeff;
1311 }
1312 }
1313 }
1314
1315 if (!setup_logged_)
1316 {
1317 const std::string source = growth_law_.from_state
1318 ? fmt::format("from the state (theta_crit {:g}, relag cap {})", growth_law_.theta_crit,
1319 growth_law_.relag_max_updates > 0 ? std::to_string(growth_law_.relag_max_updates) : "none")
1320 : fmt::format("given, in [{:g}, {:g}] Pa", threshold_per_element_.minCoeff(),
1321 threshold_per_element_.maxCoeff());
1322 logger().info("growth_law: threshold {} over {} elements; {} increments to t = {:g}; "
1323 "{} growth quadrature points on element 0.",
1324 source, n_el, growth_law_.n_steps, growth_law_.t_end, vals.quadrature.weights.size());
1325 setup_logged_ = true;
1326 }
1327 }
1328
1330 const Eigen::VectorXd &u, const double t,
1331 Eigen::VectorXd &phi_full, Eigen::VectorXd &phi_no_shear, Eigen::VectorXd &theta_tot_out)
1332 {
1333 const auto ge = std::dynamic_pointer_cast<assembler::GrowthElasticity>(growthelastic_assembler_);
1334 if (!ge)
1335 log_and_throw_error("growth_law: the C_check threshold needs the GrowthElasticity assembler.");
1336 const int n_el = mesh_->n_elements();
1337 const int dim = mesh_->dimension();
1338 if (dim != 3)
1339 log_and_throw_error("growth_law: the C_check threshold is 3D only.");
1340 if (!(growth_law_.theta_crit > 0))
1341 log_and_throw_error("growth_law: the C_check threshold needs theta_crit > 0.");
1342 const double crit = growth_law_.theta_crit;
1343 phi_full.resize(n_el);
1344 phi_no_shear.resize(n_el);
1345 theta_tot_out.resize(n_el);
1346
1348 for (int e = 0; e < n_el; ++e)
1349 {
1351 const Eigen::ArrayXd da = vals.det.array() * vals.quadrature.weights.array();
1352 Eigen::Matrix3d F = Eigen::Matrix3d::Zero();
1353 RowVectorNd pos = RowVectorNd::Zero(dim);
1354 for (int p = 0; p < da.size(); ++p)
1355 {
1356 Eigen::Matrix3d Fp = Eigen::Matrix3d::Identity();
1357 for (const auto &bv : vals.basis_values)
1358 for (const auto &g : bv.global)
1359 for (int d = 0; d < dim; ++d)
1360 Fp.row(d) += g.val * u(g.index * dim + d) * bv.grad_t_m.row(p);
1361 F += da(p) * Fp;
1362 pos += da(p) * vals.val.row(p);
1363 }
1364 F /= da.sum();
1365 pos /= da.sum();
1366 const Eigen::Matrix3d C = F.transpose() * F;
1367
1368 // wall frame: n0 and any orthonormal in-plane pair
1369 const Eigen::Vector3d n = ge->wall_normal(e).normalized();
1370 const Eigen::Vector3d trial = std::abs(n(0)) < 0.9 ? Eigen::Vector3d::UnitX() : Eigen::Vector3d::UnitY();
1371 const Eigen::Vector3d e1 = (trial - trial.dot(n) * n).normalized();
1372 const Eigen::Vector3d e2 = n.cross(e1);
1373 const double c11 = e1.dot(C * e1), c22 = e2.dot(C * e2), c12 = e1.dot(C * e2);
1374 const double theta_tot = std::sqrt(std::max(c11 * c22 - c12 * c12, 0.0));
1375 if (!(theta_tot > 0))
1376 log_and_throw_error("growth_law: degenerate in-plane stretch on element {}.", e);
1377 theta_tot_out(e) = theta_tot;
1378
1379 // C_check: Fg at theta = theta_tot / theta_crit (so vartheta^e = theta_crit), vn_e
1380 const double th = theta_tot / crit;
1381 const double vn = normal_growth_per_element_(e);
1382 const Eigen::Matrix3d nn = n * n.transpose();
1383 const Eigen::Matrix3d P = Eigen::Matrix3d::Identity() - nn;
1384 const Eigen::Matrix3d Fgi = P / std::sqrt(th) + nn / vn;
1385 const Eigen::Matrix3d Ce = Fgi.transpose() * C * Fgi;
1386
1387 // shear-free state: transverse shears removed, Ce_nn at the layer value
1388 const double layer = 1.0 / n.dot(Ce.inverse() * n);
1389 const Eigen::Matrix3d Ce_ns = P * Ce * P + layer * nn;
1390
1391 phi_full(e) = ge->driving_force(e, pos, t, Ce);
1392 phi_no_shear(e) = ge->driving_force(e, pos, t, Ce_ns);
1393 }
1394 if (!phi_full.allFinite() || !phi_no_shear.allFinite())
1395 log_and_throw_error("growth_law: non-finite C_check threshold.");
1396 }
1397
1398 void GrowthElasticVarForm::threshold_target(const Eigen::MatrixXd &solution, const double t,
1399 Eigen::VectorXd &par, Eigen::VectorXd &gam, Eigen::VectorXd &clamped)
1400 {
1401 Eigen::VectorXd full, ns, tt;
1402 evaluate_threshold_state(solution.col(0).head(displacement_ndof()), t, full, ns, tt);
1403 gam = full - ns;
1404 par = ns.cwiseMax(0.0);
1405 clamped = (ns.array() < 0).cast<double>().matrix();
1406 }
1407
1408 void GrowthElasticVarForm::set_threshold(const Eigen::VectorXd &par, const Eigen::VectorXd &gam,
1409 const Eigen::VectorXd &clamped, const double t, const double omega)
1410 {
1411 const int n_el = mesh_->n_elements();
1412 threshold_parallel_ = par;
1413 shear_supply_ = gam;
1414 if (clamped.size() == n_el)
1415 threshold_clamped_ = clamped;
1418
1419 // round-off of f_gamma on zero-floored PHI_PAR is not a negative threshold
1420 const double neg_tol = 1e-6 * std::max(1.0, threshold_parallel_.cwiseAbs().maxCoeff());
1421 const int n_neg = int((threshold_per_element_.array() < -neg_tol).count());
1422 const std::string om = omega != 1.0 ? fmt::format("; relaxation omega {:.3g}", omega) : std::string();
1423 logger().info("growth_law: threshold from the state at t = {:g}: PHI_PAR median {:.4g} Pa, clamped on {:.1f}%; "
1424 "f_gamma median {:.4g} Pa, in [{:.4g}, {:.4g}]; threshold in [{:.4g}, {:.4g}] Pa, negative on {:.1f}% of elements{}",
1426 median_of(shear_supply_), shear_supply_.minCoeff(), shear_supply_.maxCoeff(),
1427 threshold_per_element_.minCoeff(), threshold_per_element_.maxCoeff(), 100.0 * n_neg / n_el, om);
1428 }
1429
1430 Eigen::VectorXd GrowthElasticVarForm::element_mean_growth(const Eigen::VectorXd &theta)
1431 {
1432 const int n_el = mesh_->n_elements();
1433 Eigen::VectorXd out(n_el);
1435 for (int e = 0; e < n_el; ++e)
1436 {
1439 const Eigen::ArrayXd da = vals.det.array() * vals.quadrature.weights.array();
1440 Eigen::ArrayXd th = Eigen::ArrayXd::Zero(da.size());
1441 for (const auto &bv : vals.basis_values)
1442 for (const auto &g : bv.global)
1443 th += g.val * theta(g.index) * bv.val.array();
1444 out(e) = (th * da).sum() / da.sum();
1445 }
1446 return out;
1447 }
1448
1449 void GrowthElasticVarForm::log_kkt_residual(const int step, const double t, const Eigen::MatrixXd &solution,
1450 const Eigen::VectorXd &mult, const std::vector<char> &pinned)
1451 {
1452 // dPi/dtheta per v_n-weighted nodal volume is phi - f_I in Pa (nodal average):
1453 // ~0 on free DOFs (the law holds), >= 0 on pinned ones (the slack).
1454 std::vector<double> free_res;
1455 double min_slack = std::numeric_limits<double>::infinity();
1456 int n_pinned = 0;
1457 for (int a = 0; a < int(pinned.size()); ++a)
1458 {
1459 const double v = growth_node_vn_volume_(a) > 0 ? growth_node_vn_volume_(a) : 1.0;
1460 const double r = mult(a) / v;
1461 if (pinned[a])
1462 {
1463 min_slack = std::min(min_slack, r);
1464 ++n_pinned;
1465 }
1466 else
1467 free_res.push_back(std::abs(r));
1468 }
1469 double med = 0, mx = 0;
1470 if (!free_res.empty())
1471 {
1472 mx = *std::max_element(free_res.begin(), free_res.end());
1473 std::nth_element(free_res.begin(), free_res.begin() + free_res.size() / 2, free_res.end());
1474 med = free_res[free_res.size() / 2];
1475 }
1476 logger().info("growth step {} (t = {:g}) KKT: free DOFs |phi - f_I| median {:.3g} Pa, max {:.3g} Pa ({}); "
1477 "pinned min slack {:.3g} Pa ({})",
1478 step, t, med, mx, free_res.size(), n_pinned > 0 ? min_slack : 0.0, n_pinned);
1479 stats.solver_info.push_back(
1480 {{"type", "growth_kkt"}, {"t", t}, {"step", step}, {"free_median_pa", med}, {"free_max_pa", mx}, {"pinned_min_slack_pa", n_pinned > 0 ? min_slack : 0.0}});
1481 }
1482
1483 void GrowthElasticVarForm::accumulate_dissipation(const int step, const double t, const Eigen::VectorXd &dtheta)
1484 {
1485 // Split of the increment's dissipation term v_n phi dtheta (per reference
1486 // volume, Pa) for the from_state threshold: D = v_n max(f_par, 0) dtheta >= 0,
1487 // the dissipation, and S = v_n f_gamma dtheta, the shear supply. A
1488 // shear supply comparable to D means the shear credit carries the growth.
1489 const int n_el = mesh_->n_elements();
1490 if (threshold_parallel_.size() != n_el || shear_supply_.size() != n_el)
1491 return;
1492 if (element_volume_.size() != n_el)
1493 {
1494 element_volume_.resize(n_el);
1496 for (int e = 0; e < n_el; ++e)
1497 {
1500 element_volume_(e) = (vals.det.array() * vals.quadrature.weights.array()).sum();
1501 }
1502 dissipation_.setZero(n_el);
1503 shear_work_.setZero(n_el);
1504 }
1505 const Eigen::VectorXd dth = element_mean_growth(dtheta.cwiseMax(0.0));
1506 const Eigen::VectorXd D = normal_growth_per_element_.cwiseProduct(threshold_parallel_).cwiseProduct(dth);
1507 const Eigen::VectorXd S = normal_growth_per_element_.cwiseProduct(shear_supply_).cwiseProduct(dth);
1508 dissipation_ += D;
1509 shear_work_ += S;
1510 const double iD = D.dot(element_volume_), iS = S.dot(element_volume_);
1511 const double cD = dissipation_.dot(element_volume_), cS = shear_work_.dot(element_volume_);
1512 int n_grow = 0, n_neg = 0, n_dneg = 0;
1513 for (int e = 0; e < n_el; ++e)
1514 if (dth(e) > 0)
1515 {
1516 ++n_grow;
1517 n_neg += (threshold_per_element_(e) < 0);
1518 n_dneg += (D(e) < 0);
1519 }
1520 logger().info("growth step {} (t = {:g}): dissipation int D dV {:.4g} (cumulative {:.4g}), shear supply int S dV "
1521 "{:.4g} (cumulative {:.4g}) [Pa x mesh volume]; S/D {:.3f}; growing elements {}, with phi < 0: {}, with D < 0: {}",
1522 step, t, iD, cD, iS, cS, iD != 0 ? iS / iD : 0.0, n_grow, n_neg, n_dneg);
1523 stats.solver_info.push_back(
1524 {{"type", "growth_dissipation"}, {"t", t}, {"step", step}, {"D", iD}, {"S", iS}, {"D_cumulative", cD}, {"S_cumulative", cS}, {"n_phi_negative", n_neg}, {"n_D_negative", n_dneg}});
1525 }
1526
1527 void GrowthElasticVarForm::report_lag_residual(const int step, const double t, const Eigen::MatrixXd &solution)
1528 {
1529 // The threshold the converged state itself implies (the from_state
1530 // construction at its own C_check) against the one the increment used:
1531 // the lag left by capping or converging the threshold iteration.
1532 Eigen::VectorXd full, ns, tt;
1533 evaluate_threshold_state(solution.col(0).head(displacement_ndof()), t, full, ns, tt);
1534 const Eigen::VectorXd phi_state = ns.cwiseMax(0.0) + (full - ns);
1536 const Eigen::VectorXd th_e = element_mean_growth(solution.col(0).tail(growth_ndof()));
1537 attainment_ = tt.cwiseQuotient(th_e) / growth_law_.theta_crit;
1538
1539 std::vector<double> res, att;
1540 for (int e = 0; e < th_e.size(); ++e)
1541 if (th_e(e) > 1.0 + 1e-9 && ns(e) >= 0) // grown, not clamped at this state's C_check
1542 {
1543 res.push_back(std::abs(lag_residual_(e)));
1544 att.push_back(attainment_(e));
1545 }
1546 if (res.empty())
1547 {
1548 logger().info("growth step {} (t = {:g}): lag residual: no grown unclamped elements yet", step, t);
1549 return;
1550 }
1551 const auto q = [](std::vector<double> v, const double f) {
1552 const size_t k = std::min(v.size() - 1, size_t(f * double(v.size() - 1) + 0.5));
1553 std::nth_element(v.begin(), v.begin() + k, v.end());
1554 return v[k];
1555 };
1556 logger().info("growth step {} (t = {:g}): lag residual |phi(state) - phi used| median {:.4g} Pa (p95 {:.4g}); "
1557 "attainment median {:.4f} (p5 {:.4f}, p95 {:.4f}) over {} grown unclamped elements",
1558 step, t, q(res, 0.5), q(res, 0.95), q(att, 0.5), q(att, 0.05), q(att, 0.95), res.size());
1559 stats.solver_info.push_back(
1560 {{"type", "growth_lag_residual"}, {"t", t}, {"step", step}, {"abs_median", q(res, 0.5)}, {"abs_p95", q(res, 0.95)}, {"attainment_median", q(att, 0.5)}});
1561 }
1562
1563 Eigen::VectorXd GrowthElasticVarForm::growth_multiplier(const Eigen::MatrixXd &solution) const
1564 {
1565 assert(stacked_form_);
1566 Eigen::VectorXd full_grad;
1567 stacked_form_->first_derivative(solution.col(0), full_grad);
1568 return full_grad.tail(growth_ndof());
1569 }
1570
1571 void GrowthElasticVarForm::solve_with_current_pins(const int step, const double t, Eigen::MatrixXd &solution, const double grad_tol_factor)
1572 {
1573 build_forms(solution, t);
1574 make_nl_problem(solution, t);
1575 solve_nonlinear_step(step, solution, grad_tol_factor);
1576 }
1577
1578 int GrowthElasticVarForm::solve_growth_increment(const int step, const double t, Eigen::MatrixXd &solution)
1579 {
1580 const int nu = displacement_ndof();
1581 const int ng = growth_ndof();
1582
1583 // Release tolerance per DOF: the multiplier is an energy per unit growth
1584 // (Pa x volume), so it is scaled by the nodal volume and the threshold
1585 // magnitude (at least 1 Pa, so a zero threshold still has a scale).
1586
1587 // Pass 1 is the elastic predictor: every growth DOF pinned at theta_n.
1588 // Once the set settles, one confirmation pass re-solves with the gradient
1589 // tolerance scaled by final_tol_factor (when < 1), so the multipliers the
1590 // set was decided on, and the reported state, are converged tighter than
1591 // the release tolerance they are compared with.
1592 std::vector<char> pinned(ng, 1);
1593 bool tight = false;
1594
1595 // from_state: the threshold is re-evaluated on every pass's state, with Aitken
1596 // dynamic relaxation of the iteration: x_{k+1} = x_k + omega_k (G(x_k) - x_k),
1597 // x = (PHI_PAR, f_gamma) per element,
1598 // omega_k = -omega_{k-1} r_{k-1}.(r_k - r_{k-1}) / |r_k - r_{k-1}|^2, clamped.
1599 // Restarted (omega = 1) whenever the active set changed in between, since the
1600 // map G then changes too. The fixed point is the same as without relaxation.
1601 constexpr double omega_min = 0.05, omega_max = 5.0;
1602 Eigen::VectorXd r_prev;
1603 double omega_prev = 1.0;
1604 bool set_changed_last_pass = true;
1605 int n_threshold_updates = 0;
1606 for (int pass = 1; pass <= growth_law_.max_active_set_iterations; ++pass)
1607 {
1608 pinned_growth_nodes_.clear();
1609 for (int a = 0; a < ng; ++a)
1610 {
1611 if (pinned[a])
1612 {
1613 pinned_growth_nodes_.push_back(a);
1614 solution(nu + a, 0) = theta_n_(a); // pinned values exact: AL start error 0
1615 }
1616 }
1617
1618 solve_with_current_pins(step, t, solution, tight ? growth_law_.final_tol_factor : 1.0);
1619
1620 Eigen::VectorXd mult = growth_multiplier(solution);
1621
1622 // from_state: threshold re-evaluated on this pass's state. The dissipation
1623 // is linear in theta with gradient w, so the multiplier for the updated
1624 // threshold is mult + (w_new - w_old), exactly, without another solve.
1625 bool threshold_moved = false;
1626 const bool update_capped = growth_law_.relag_max_updates > 0
1627 && n_threshold_updates >= growth_law_.relag_max_updates;
1628 if (growth_law_.from_state && !update_capped)
1629 {
1630 ++n_threshold_updates;
1631 const Eigen::VectorXd w_old = growth_node_weights_;
1632 const Eigen::VectorXd phi_old = threshold_per_element_;
1633 Eigen::VectorXd par_g, gam_g, clamped_g;
1634 threshold_target(solution, t, par_g, gam_g, clamped_g);
1635 const int n_el = int(par_g.size());
1636 Eigen::VectorXd r(2 * n_el);
1637 r << par_g - threshold_parallel_, gam_g - shear_supply_;
1638 const double dphi = ((par_g + gam_g) - phi_old).cwiseAbs().maxCoeff(); // |G(x) - x|, the lag
1639 double omega = 1.0;
1640 if (!set_changed_last_pass && r_prev.size() == r.size())
1641 {
1642 const Eigen::VectorXd dr = r - r_prev;
1643 const double den = dr.squaredNorm();
1644 if (den > 0)
1645 omega = std::clamp(-omega_prev * r_prev.dot(dr) / den, omega_min, omega_max);
1646 }
1647 r_prev = r;
1648 omega_prev = omega;
1649 set_threshold((threshold_parallel_ + omega * r.head(n_el)).cwiseMax(0.0),
1650 shear_supply_ + omega * r.tail(n_el), clamped_g, t, omega);
1651 mult += growth_node_weights_ - w_old;
1652 // a changed threshold only moves the solution where theta is free
1653 const bool any_free = std::find(pinned.begin(), pinned.end(), 0) != pinned.end();
1654 threshold_moved = any_free && dphi > growth_law_.relag_tol;
1655 const bool cap_now = growth_law_.relag_max_updates > 0
1656 && n_threshold_updates >= growth_law_.relag_max_updates;
1657 logger().info("growth step {} (t = {:g}) pass {}: threshold updated, max |d phi| {:.4g} Pa{}{}",
1658 step, t, pass, dphi, threshold_moved ? " (re-solving)" : "",
1659 cap_now ? fmt::format("; update cap {} reached, threshold held from here", growth_law_.relag_max_updates)
1660 : std::string());
1661 }
1662
1663 // scale from the threshold in use (it may have just been updated)
1664 const double force_scale = std::max(1.0, threshold_per_element_.cwiseAbs().maxCoeff());
1665 const Eigen::VectorXd release_tol = growth_law_.active_set_tol * force_scale * growth_node_volume_;
1666 int n_released = 0, n_pinned = 0, n_pinned_total = 0;
1667 std::vector<char> next = pinned;
1668 for (int a = 0; a < ng; ++a)
1669 {
1670 const double theta = solution(nu + a, 0);
1671 if (pinned[a])
1672 {
1673 // at the bound: the law wants growth when dPi/dtheta < 0
1674 if (mult(a) < -release_tol(a))
1675 {
1676 next[a] = 0;
1677 ++n_released;
1678 }
1679 }
1680 else if (theta < theta_n_(a) - growth_law_.feasibility_tol)
1681 {
1682 next[a] = 1; // free DOF crossed the bound: irreversibility violated
1683 ++n_pinned;
1684 }
1685 n_pinned_total += next[a];
1686 }
1687
1688 growth_pinned_mask_ = pinned;
1689 logger().info("growth step {} (t = {:g}) active-set pass {}: {} released, {} pinned, {}/{} at theta_n",
1690 step, t, pass, n_released, n_pinned, n_pinned_total, ng);
1691 stats.solver_info.push_back(
1692 {{"type", "growth_active_set"}, {"t", t}, {"step", step}, {"pass", pass}, {"released", n_released}, {"pinned", n_pinned}, {"n_at_bound", n_pinned_total}});
1693
1694 set_changed_last_pass = n_released != 0 || n_pinned != 0;
1695 if (n_released == 0 && n_pinned == 0 && !threshold_moved)
1696 {
1697 if (growth_law_.final_tol_factor < 1.0 && !tight)
1698 {
1699 tight = true;
1700 logger().info("growth step {} (t = {:g}): active set settled; confirmation pass with the gradient "
1701 "tolerance x {:g}",
1702 step, t, growth_law_.final_tol_factor);
1703 continue;
1704 }
1705 log_kkt_residual(step, t, solution, mult, pinned);
1706 return pass;
1707 }
1708 pinned = next;
1709 }
1710
1711 log_and_throw_error("growth step {} (t = {:g}): active set did not settle in {} passes "
1712 "(raise growth_law.max_active_set_iterations, or reduce the increment).",
1714 return -1;
1715 }
1716
1717 void GrowthElasticVarForm::solve_growth_law(Eigen::MatrixXd &solution)
1718 {
1720
1721 const int ng = growth_ndof();
1722 theta_n_ = solution.col(0).tail(ng);
1723 if (!(theta_n_.array() > 0).all())
1724 log_and_throw_error("growth_law: initial growth must be positive (min {}).", theta_n_.minCoeff());
1725 growth_activation_step_ = Eigen::VectorXi::Zero(ng);
1726
1727 for (int step = 1; step <= growth_law_.n_steps; ++step)
1728 {
1729 const double t_from = growth_law_.t_end * double(step - 1) / double(growth_law_.n_steps);
1730 const double t = growth_law_.t_end * double(step) / double(growth_law_.n_steps);
1731 const Eigen::VectorXd theta_start = theta_n_;
1732 const int passes = advance_increment(step, t_from, t, solution, 0);
1733
1734 const Eigen::VectorXd theta = solution.col(0).tail(ng);
1735 const Eigen::VectorXd dtheta = theta - theta_start;
1736 const int n_active = int(std::count(growth_pinned_mask_.begin(), growth_pinned_mask_.end(), 0));
1737 logger().info("growth step {}/{} (t = {:g}): {} pass(es), {}/{} DOFs growing, "
1738 "theta in [{:.6g}, {:.6g}], max increment {:.3e}, min increment {:.3e}",
1739 step, growth_law_.n_steps, t, passes, n_active, ng,
1740 theta.minCoeff(), theta.maxCoeff(), dtheta.maxCoeff(), dtheta.minCoeff());
1741 stats.solver_info.push_back(
1742 {{"type", "growth_step"}, {"t", t}, {"step", step}, {"passes", passes}, {"n_growing", n_active}, {"theta_min", theta.minCoeff()}, {"theta_max", theta.maxCoeff()}});
1743
1744 if (growth_law_.theta_crit > 0)
1745 report_lag_residual(step, t, solution);
1746
1748 save_growth_increment(step, t, solution);
1749 }
1750 }
1751
1752 int GrowthElasticVarForm::advance_increment(const int step, const double t_from, const double t_to,
1753 Eigen::MatrixXd &solution, const int depth)
1754 {
1755 // Everything an attempt may change, so a failed one can be undone exactly.
1756 const Eigen::MatrixXd solution0 = solution;
1757 const Eigen::VectorXd threshold0 = threshold_per_element_, parallel0 = threshold_parallel_,
1758 shear0 = shear_supply_, clamped0 = threshold_clamped_, weights0 = growth_node_weights_;
1759 const std::vector<char> mask0 = growth_pinned_mask_;
1760 try
1761 {
1762 const int passes = solve_growth_increment(step, t_to, solution);
1763 commit_increment(step, t_to, solution);
1764 return passes;
1765 }
1766 catch (const std::runtime_error &e)
1767 {
1768 if (depth >= growth_law_.max_increment_splits)
1769 throw;
1770 solution = solution0;
1771 threshold_per_element_ = threshold0;
1772 threshold_parallel_ = parallel0;
1773 shear_supply_ = shear0;
1774 threshold_clamped_ = clamped0;
1775 growth_node_weights_ = weights0;
1776 growth_pinned_mask_ = mask0;
1777 const double t_mid = 0.5 * (t_from + t_to);
1778 logger().warn("growth step {}: the increment to t = {:g} failed ({}); retrying from t = {:g} as two "
1779 "half increments, to t = {:g} and t = {:g} (split level {} of {})",
1780 step, t_to, e.what(), t_from, t_mid, t_to, depth + 1, growth_law_.max_increment_splits);
1781 stats.solver_info.push_back(
1782 {{"type", "growth_split"}, {"step", step}, {"t_from", t_from}, {"t_to", t_to}, {"level", depth + 1}});
1783 const int p1 = advance_increment(step, t_from, t_mid, solution, depth + 1);
1784 const int p2 = advance_increment(step, t_mid, t_to, solution, depth + 1);
1785 return p1 + p2;
1786 }
1787 }
1788
1789 void GrowthElasticVarForm::commit_increment(const int step, const double t, Eigen::MatrixXd &solution)
1790 {
1791 const int nu = displacement_ndof();
1792 const int ng = growth_ndof();
1793 const Eigen::VectorXd theta = solution.col(0).tail(ng);
1794 const Eigen::VectorXd dtheta = theta - theta_n_;
1795
1796 accumulate_dissipation(step, t, dtheta);
1797
1798 // Irreversibility holds by construction: pinned DOFs equal theta_n and
1799 // free DOFs passed the feasibility test. Clamp round-off only.
1800 theta_n_ = theta.cwiseMax(theta_n_);
1801 solution.col(0).segment(nu, ng) = theta_n_;
1802
1803 // Activation increment: the first increment in which a DOF
1804 // was free in the settled active set AND grew. Free-but-unmoved
1805 // DOFs (exactly at threshold) do not count.
1806 for (int a = 0; a < ng; ++a)
1807 if (growth_activation_step_(a) == 0 && !growth_pinned_mask_[a] && dtheta(a) > 0)
1808 growth_activation_step_(a) = step;
1809 }
1810
1811 void GrowthElasticVarForm::save_growth_increment(const int step, const double t, const Eigen::MatrixXd &solution)
1812 {
1813 const io::OutputSpace space = output_space();
1814 if (!space.mesh)
1815 return;
1816
1817 // output_fields falls back to converged_solution_ for non-stacked
1818 // inputs; keep it current so every export path sees this increment.
1819 converged_solution_ = solution;
1820
1822 const auto opts = export_options(space);
1823 const double dt = growth_law_.t_end / double(growth_law_.n_steps);
1824 const std::string name = fmt::format("growth_step_{:d}.vtu", step);
1826 output_field_function(solution, opts), t, dt, opts);
1827
1828 // The PVD is rewritten each increment, so an aborted ramp still leaves
1829 // a readable series of the increments that converged.
1830 std::ofstream pvd(resolve_output_path("growth_steps.pvd"));
1831 pvd << "<?xml version=\"1.0\"?>\n"
1832 << "<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\"LittleEndian\">\n"
1833 << " <Collection>\n";
1834 for (int k = 1; k <= step; ++k)
1835 pvd << fmt::format(" <DataSet timestep=\"{:.17g}\" group=\"\" part=\"0\" file=\"growth_step_{:d}.vtu\"/>\n",
1836 growth_law_.t_end * double(k) / double(growth_law_.n_steps), k);
1837 pvd << " </Collection>\n</VTKFile>\n";
1838 logger().info("growth step {}: wrote {}", step, resolve_output_path(name));
1839 }
1840
1841 void GrowthElasticVarForm::export_data(const Eigen::MatrixXd &solution) const
1842 {
1843 Eigen::MatrixXd displacement, growth;
1844 split_solution(solution, displacement, growth);
1845
1846 // The inherited exporter expects a pure-displacement solution; the
1847 // growth block is in the VTU output (field "growth").
1849 if (!args["output"]["data"]["stress_mat"].get<std::string>().empty()
1850 || !args["output"]["data"]["mises"].get<std::string>().empty())
1851 logger().warn(
1852 "GrowthElastic: output.data.stress_mat / mises are evaluated with the ungrown "
1853 "material at the total F; the grown-material stresses are the VTU fields "
1854 "(cauchy_stess_*, pk1_stess_*, pk2_stess_*, von_mises).");
1855 }
1856
1858 {
1859 if (!args["output"]["advanced"]["compute_error"])
1860 return stats;
1861
1862 Eigen::MatrixXd displacement, growth;
1863 split_solution(solution, displacement, growth);
1864
1866 return stats;
1867 }
1868
1870 const int e, const Eigen::MatrixXd &local_pts, const double t,
1871 const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &growth,
1872 Eigen::MatrixXd &cauchy, Eigen::MatrixXd &pk1, Eigen::MatrixXd &pk2,
1873 Eigen::MatrixXd &von_mises, Eigen::MatrixXd &energy) const
1874 {
1875 const auto ge = std::dynamic_pointer_cast<assembler::GrowthElasticity>(growthelastic_assembler_);
1876 if (!ge)
1877 log_and_throw_error("GrowthElastic: grown stresses need the GrowthElasticity assembler.");
1878
1879 const int dim = mesh_->dimension();
1880 const basis::ElementBases &bs = space_.basis_list()[e];
1883 vals.compute(e, mesh_->is_volume(), local_pts, bs, gbs);
1884
1885 Eigen::MatrixXd theta, theta_grad;
1888 e, local_pts, growth, theta, theta_grad);
1889
1890 const int n = local_pts.rows();
1891 cauchy.resize(n, 9);
1892 pk1.resize(n, 9);
1893 pk2.resize(n, 9);
1894 von_mises.resize(n, 1);
1895 energy.resize(n, 1);
1896
1897 Eigen::MatrixXd grad_u(dim, dim);
1898 Eigen::Matrix3d s, P, S;
1899 for (int p = 0; p < n; ++p)
1900 {
1901 compute_diplacement_grad(dim, bs, vals, local_pts, p, displacement, grad_u);
1902 const Eigen::Matrix3d F = Eigen::Matrix3d::Identity() + grad_u;
1903 double w;
1904 ge->grown_stresses(e, vals.val.row(p), t, F, theta(p, 0), s, P, S, w);
1905
1906 // column-major, as the base flattening (field "<name>_k" = column k)
1907 cauchy.row(p) = Eigen::Map<const Eigen::Matrix<double, 1, 9>>(s.data());
1908 pk1.row(p) = Eigen::Map<const Eigen::Matrix<double, 1, 9>>(P.data());
1909 pk2.row(p) = Eigen::Map<const Eigen::Matrix<double, 1, 9>>(S.data());
1910 von_mises(p, 0) = von_mises_stress_for_stress_tensor(s);
1911 energy(p, 0) = w;
1912 }
1913 }
1914
1916 const io::OutputSample &sample,
1917 const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &growth,
1918 std::vector<io::OutputField> &fields) const
1919 {
1920 if (!mesh_ || mesh_->dimension() != 3 || displacement.size() <= 0 || growth.size() <= 0)
1921 return;
1922 if (!std::dynamic_pointer_cast<assembler::GrowthElasticity>(growthelastic_assembler_))
1923 return;
1924
1925 // Base names: "von_mises" and "<tensor>_k" (k = 1..3, column k of the
1926 // column-major tensor); the nodal averages carry "_avg" before "_k".
1927 // Only fields the base emitted are touched, so the export options keep
1928 // deciding what is written.
1929 static const std::array<std::string, 3> tensor_names = {{"cauchy_stess", "pk1_stess", "pk2_stess"}};
1930 struct Targets
1931 {
1932 io::OutputField *von_mises = nullptr;
1933 std::array<std::array<io::OutputField *, 3>, 3> tensor{};
1934 bool any = false;
1935 };
1936 const auto collect = [&](const std::string &suffix) {
1937 Targets tg;
1938 for (io::OutputField &field : fields)
1939 {
1940 if (field.name == "von_mises" + suffix)
1941 {
1942 tg.von_mises = &field;
1943 tg.any = true;
1944 continue;
1945 }
1946 for (int a = 0; a < 3; ++a)
1947 for (int k = 0; k < 3; ++k)
1948 if (field.name == fmt::format("{}{}_{}", tensor_names[a], suffix, k + 1))
1949 {
1950 tg.tensor[a][k] = &field;
1951 tg.any = true;
1952 }
1953 }
1954 return tg;
1955 };
1956 const Targets point = collect("");
1957 const Targets avg = collect("_avg");
1958 const bool has_element_samples = sample.local_points.rows() > 0 && sample.local_points.rows() == sample.element_ids.size();
1959 Eigen::MatrixXd cauchy, pk1, pk2, vm, w;
1960
1961 // ---- energy density at the output samples; "energy_avg" is the
1962 // per-element mean of the sample values, as in the elastic base
1963 io::OutputField *energy = nullptr, *energy_avg = nullptr;
1964 for (io::OutputField &field : fields)
1965 {
1966 if (field.name == "energy")
1967 energy = &field;
1968 else if (field.name == "energy_avg")
1969 energy_avg = &field;
1970 }
1971 if ((energy || energy_avg) && has_element_samples)
1972 {
1973 const int ns = sample.local_points.rows();
1974 Eigen::VectorXd values = Eigen::VectorXd::Zero(ns);
1975 Eigen::VectorXd sum = Eigen::VectorXd::Zero(mesh_->n_elements());
1976 Eigen::VectorXi count = Eigen::VectorXi::Zero(mesh_->n_elements());
1977 for (int i = 0; i < ns; ++i)
1978 {
1979 const int e = sample.element_ids(i);
1980 if (e < 0)
1981 continue;
1982 grown_stress_at(e, sample.local_points.row(i), sample.time, displacement, growth, cauchy, pk1, pk2, vm, w);
1983 values(i) = w(0, 0);
1984 sum(e) += values(i);
1985 count(e)++;
1986 }
1987 for (int i = 0; i < ns; ++i)
1988 {
1989 const int e = sample.element_ids(i);
1990 if (e < 0)
1991 continue;
1992 if (energy && i < energy->values.rows())
1993 energy->values(i, 0) = values(i);
1994 if (energy_avg && i < energy_avg->values.rows())
1995 energy_avg->values(i, 0) = sum(e) / count(e);
1996 }
1997 }
1998
1999 if (!point.any && !avg.any)
2000 return;
2001
2002 // row `row` of the targets from row `src` of (cauchy, pk1, pk2, von_mises)
2003 const auto write_row = [](const Targets &tg, const int row,
2004 const std::array<const Eigen::MatrixXd *, 3> &tensors,
2005 const Eigen::MatrixXd &vm, const int src) {
2006 if (tg.von_mises && row < tg.von_mises->values.rows())
2007 tg.von_mises->values(row, 0) = vm(src, 0);
2008 for (int a = 0; a < 3; ++a)
2009 for (int k = 0; k < 3; ++k)
2010 if (tg.tensor[a][k] && row < tg.tensor[a][k]->values.rows())
2011 tg.tensor[a][k]->values.row(row) = tensors[a]->block(src, 3 * k, 1, 3);
2012 };
2013
2014 // ---- point values at the output samples
2015 if (point.any && has_element_samples)
2016 {
2017 for (int i = 0; i < sample.local_points.rows(); ++i)
2018 {
2019 const int e = sample.element_ids(i);
2020 if (e < 0)
2021 continue;
2022 grown_stress_at(e, sample.local_points.row(i), sample.time, displacement, growth, cauchy, pk1, pk2, vm, w);
2023 write_row(point, i, {{&cauchy, &pk1, &pk2}}, vm, 0);
2024 }
2025 }
2026
2027 if (!avg.any)
2028 return;
2029
2030 // ---- nodal averages: same rule as the elastic base (element values at
2031 // the element's Lagrange nodes, weighted by element volume, interface
2032 // nodes only), then sampled at the output points
2033 const int nb = space_.n_bases;
2034 Eigen::VectorXd areas = Eigen::VectorXd::Zero(nb);
2035 std::array<Eigen::MatrixXd, 3> avg_tensor;
2036 for (auto &m : avg_tensor)
2037 m.setZero(nb, 9);
2038 Eigen::MatrixXd avg_vm = Eigen::MatrixXd::Zero(nb, 1);
2039
2040 for (int e = 0; e < int(space_.basis_list().size()); ++e)
2041 {
2042 Eigen::MatrixXd local_pts;
2043 if (mesh_->is_simplex(e))
2044 autogen::p_nodes_3d(space_.disc_orders(e), local_pts);
2045 else if (mesh_->is_cube(e))
2046 autogen::q_nodes_3d(space_.disc_orders(e), local_pts);
2047 else if (mesh_->is_prism(e))
2049 else
2050 continue;
2051
2052 const basis::ElementBases &bs = space_.basis_list()[e];
2054 vals.compute(e, mesh_->is_volume(), bs, space_.geometry_basis_list()[e]);
2055 const double area = (vals.det.array() * vals.quadrature.weights.array()).sum();
2056
2057 grown_stress_at(e, local_pts, sample.time, displacement, growth, cauchy, pk1, pk2, vm, w);
2058
2059 for (size_t j = 0; j < bs.bases.size(); ++j)
2060 {
2061 const basis::Basis &b = bs.bases[j];
2062 if (b.global().size() > 1)
2063 continue;
2064 const int index = b.global().front().index;
2065 areas(index) += area;
2066 avg_tensor[0].row(index) += cauchy.row(j) * area;
2067 avg_tensor[1].row(index) += pk1.row(j) * area;
2068 avg_tensor[2].row(index) += pk2.row(j) * area;
2069 avg_vm(index) += vm(j) * area;
2070 }
2071 }
2072
2073 for (int i = 0; i < nb; ++i)
2074 {
2075 if (!(areas(i) > 0))
2076 continue;
2077 for (auto &m : avg_tensor)
2078 m.row(i) /= areas(i);
2079 avg_vm(i) /= areas(i);
2080 }
2081
2082 // stack (cauchy | pk1 | pk2 | vm) per node so one interpolation serves all
2083 Eigen::MatrixXd nodal(nb, 28);
2084 nodal << avg_tensor[0], avg_tensor[1], avg_tensor[2], avg_vm;
2085 const Eigen::VectorXd nodal_flat = utils::flatten(nodal);
2086
2087 const auto write_sampled = [&](const int row, const Eigen::MatrixXd &v) {
2088 cauchy = v.middleCols(0, 9);
2089 pk1 = v.middleCols(9, 9);
2090 pk2 = v.middleCols(18, 9);
2091 write_row(avg, row, {{&cauchy, &pk1, &pk2}}, v.middleCols(27, 1), 0);
2092 };
2093
2094 if (has_element_samples)
2095 {
2096 for (int i = 0; i < sample.local_points.rows(); ++i)
2097 {
2098 const int e = sample.element_ids(i);
2099 if (e < 0)
2100 continue;
2101 Eigen::MatrixXd local_sol, local_grad;
2104 e, sample.local_points.row(i), nodal_flat, local_sol, local_grad);
2105 write_sampled(i, local_sol);
2106 }
2107 }
2108 else if (sample.node_ids.size() > 0)
2109 {
2110 for (int i = 0; i < sample.node_ids.size(); ++i)
2111 {
2112 const int node = sample.node_ids(i);
2113 if (node >= 0 && node < nb)
2114 write_sampled(i, nodal.row(node));
2115 }
2116 }
2117 }
2118
2119 std::vector<io::OutputField> GrowthElasticVarForm::output_fields(
2120 const io::OutputSample &sample,
2121 const Eigen::MatrixXd &solution,
2122 const io::OutputFieldOptions &options) const
2123 {
2124 // See converged_solution_: prefer the cached stacked solution when the
2125 // passed one is not stacked-sized (export paths differ in what they
2126 // hand this function; slicing a wrong-sized vector fed garbage theta
2127 // into the reaction evaluation and tripped the positivity guard).
2128 const bool passed_is_stacked = solution.rows() == total_ndof();
2129 const Eigen::MatrixXd &stacked =
2130 passed_is_stacked ? solution : converged_solution_;
2131 if (stacked.rows() != total_ndof())
2132 return NonlinearElasticVarForm::output_fields(sample, solution, options);
2133
2134 Eigen::MatrixXd displacement, growth;
2135 split_solution(stacked, displacement, growth);
2136
2137 std::vector<io::OutputField> fields =
2138 NonlinearElasticVarForm::output_fields(sample, displacement, options);
2139 // The base fields carry the displacement block under the name
2140 // "solution", which would be misleading beside the growth fields;
2141 // rename rather than drop, so the vtu is self-contained (points and
2142 // displacement in one consistent order -- what verification tooling
2143 // pairs against).
2144 for (io::OutputField &field : fields)
2145 {
2146 if (field.name == "solution")
2147 field.name = "displacement";
2148 else if (field.name == "solution_gradient")
2149 field.name = "displacement_gradient";
2150 }
2151
2152 if (!mesh_ || growth.size() <= 0)
2153 return fields;
2155 return fields;
2156
2157 replace_stress_fields(sample, displacement, growth, fields);
2158
2159 const bool has_element_samples = sample.local_points.rows() > 0 && sample.local_points.rows() == sample.element_ids.size();
2160 const int output_rows = sample.points.rows() > 0 ? sample.points.rows() : std::max<int>(sample.local_points.rows(), sample.node_ids.size());
2161
2162 const auto has_field = [&](const std::string &name) {
2163 return std::any_of(fields.begin(), fields.end(), [&](const io::OutputField &field) {
2164 return field.name == name;
2165 });
2166 };
2167
2168 const auto append_material_fields = [&](const assembler::Assembler &assembler) {
2169 const auto &paraview_options = args["output"]["paraview"]["options"];
2170 if (!paraview_options["material"] || !has_element_samples)
2171 return;
2172
2173 const auto params = assembler.parameters();
2174 std::map<std::string, Eigen::MatrixXd> param_values;
2175 for (const auto &[p, _] : params)
2176 param_values[p].setZero(output_rows, 1);
2177
2178 for (int i = 0; i < sample.local_points.rows(); ++i)
2179 {
2180 const int element_id = sample.element_ids(i);
2181 if (element_id < 0)
2182 continue;
2183
2184 for (const auto &[p, func] : params)
2185 param_values.at(p)(i) = func(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
2186 }
2187
2188 for (const auto &[name, values] : param_values)
2189 if (options.export_field(name) && !has_field(name))
2190 fields.push_back({name, values, io::OutputField::Association::Point});
2191 };
2192
2193 // Sample a nodal scalar field of the growth space at the requested
2194 // output locations (same pattern as the temperature sampling in the
2195 // thermo precedent).
2196 const auto sample_growth_scalar = [&](const Eigen::MatrixXd &nodal, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients = nullptr) -> bool {
2197 if (has_element_samples)
2198 {
2199 values.resize(sample.local_points.rows(), 1);
2200 if (gradients)
2201 gradients->resize(sample.local_points.rows(), mesh_->dimension());
2202 for (int i = 0; i < sample.local_points.rows(); ++i)
2203 {
2204 const int element_id = sample.element_ids(i);
2205 if (element_id < 0)
2206 {
2207 values(i) = 0;
2208 if (gradients)
2209 gradients->row(i).setZero();
2210 continue;
2211 }
2212
2213 Eigen::MatrixXd local_sol, local_grad;
2215 *mesh_, 1, growth_space_.basis_list(), growth_space_.geometry_basis_list(),
2216 element_id, sample.local_points.row(i), nodal, local_sol, local_grad);
2217 values(i) = local_sol(0);
2218 if (gradients)
2219 gradients->row(i) = local_grad;
2220 }
2221
2222 if (output_rows > values.rows())
2223 {
2224 const int previous_rows = values.rows();
2225 values.conservativeResize(output_rows, Eigen::NoChange);
2226 values.bottomRows(output_rows - previous_rows).setZero();
2227 if (gradients)
2228 {
2229 gradients->conservativeResize(output_rows, Eigen::NoChange);
2230 gradients->bottomRows(output_rows - previous_rows).setZero();
2231 }
2232 }
2233 return true;
2234 }
2235
2236 if (sample.node_ids.size() > 0)
2237 {
2238 values.resize(sample.node_ids.size(), 1);
2239 for (int i = 0; i < sample.node_ids.size(); ++i)
2240 {
2241 const int node_id = sample.node_ids(i);
2242 if (node_id < 0 || node_id >= nodal.rows())
2243 return false;
2244 values(i) = nodal(node_id);
2245 }
2246 return sample.points.rows() == 0 || sample.points.rows() == values.rows();
2247 }
2248
2249 return false;
2250 };
2251
2252 const bool export_growth_gradient =
2253 !options.fields.empty() && options.export_field("growth_gradient");
2254 if (options.export_field("growth") || export_growth_gradient)
2255 {
2256 Eigen::MatrixXd values, gradients;
2257 if (sample_growth_scalar(growth, values, export_growth_gradient ? &gradients : nullptr))
2258 {
2259 if (options.export_field("growth"))
2260 fields.push_back({"growth", values, io::OutputField::Association::Point});
2261 if (export_growth_gradient)
2262 fields.push_back({"growth_gradient", gradients, io::OutputField::Association::Point});
2263 }
2264 }
2265
2266 // Conjugate reaction on the growth block: the growth rows of the
2267 // stacked energy gradient at the converged full solution. With theta
2268 // prescribed everywhere this is the driving-force/reaction field of the
2269 // prescribed growth; the augmented-Lagrangian
2270 // boundary forms are NOT part of stacked_form_, so this is the pure
2271 // energy gradient.
2272 if (stacked_form_ && options.export_field("growth_reaction"))
2273 {
2274 Eigen::VectorXd full_grad;
2275 stacked_form_->first_derivative(stacked.col(0), full_grad);
2276 Eigen::MatrixXd reaction_nodal = full_grad.tail(growth_ndof());
2277 // Solved growth adds the dissipation to stacked_form_; growth_reaction
2278 // stays the pure energy gradient (assembled -vn f_I).
2279 if (dissipation_form_)
2280 reaction_nodal -= dissipation_form_->weights();
2281
2282 Eigen::MatrixXd values;
2283 if (sample_growth_scalar(reaction_nodal, values))
2284 fields.push_back({"growth_reaction", values, io::OutputField::Association::Point});
2285
2286 // The KKT residual of the active set, dPi_inc/dtheta: ~0 where theta
2287 // grows, >= 0 where pinned at theta_n (the multiplier of the bound).
2288 if (dissipation_form_ && options.export_field("growth_multiplier"))
2289 {
2290 const Eigen::MatrixXd mult = full_grad.tail(growth_ndof());
2291 if (sample_growth_scalar(mult, values))
2292 fields.push_back({"growth_multiplier", values, io::OutputField::Association::Point});
2293 }
2294 }
2295
2296 if (growth_law_.enabled && int(growth_pinned_mask_.size()) == growth_ndof()
2297 && options.export_field("growth_pinned"))
2298 {
2299 Eigen::MatrixXd mask(growth_ndof(), 1);
2300 for (int a = 0; a < growth_ndof(); ++a)
2301 mask(a) = growth_pinned_mask_[a] ? 1.0 : 0.0;
2302 Eigen::MatrixXd values;
2303 if (sample_growth_scalar(mask, values))
2304 fields.push_back({"growth_pinned", values, io::OutputField::Association::Point});
2305 }
2306
2307 if (growth_law_.enabled && has_element_samples && threshold_per_element_.size() == mesh_->n_elements())
2308 {
2309 const auto per_element = [&](const Eigen::VectorXd &data, const std::string &name) {
2310 if (!options.export_field(name))
2311 return;
2312 Eigen::MatrixXd values = Eigen::MatrixXd::Zero(output_rows, 1);
2313 for (int i = 0; i < sample.element_ids.size() && i < output_rows; ++i)
2314 if (sample.element_ids(i) >= 0)
2315 values(i) = data(sample.element_ids(i));
2316 fields.push_back({name, values, io::OutputField::Association::Point});
2317 };
2318 per_element(threshold_per_element_, "growth_threshold");
2319 if (shear_supply_.size() == mesh_->n_elements())
2320 per_element(shear_supply_, "growth_shear_supply");
2321 if (threshold_parallel_.size() == mesh_->n_elements())
2322 per_element(threshold_parallel_, "growth_threshold_parallel");
2323 if (threshold_clamped_.size() == mesh_->n_elements())
2324 per_element(threshold_clamped_, "growth_clamped");
2325 if (lag_residual_.size() == mesh_->n_elements())
2326 per_element(lag_residual_, "growth_lag_residual");
2327 if (attainment_.size() == mesh_->n_elements())
2328 per_element(attainment_, "growth_attainment");
2329 if (dissipation_.size() == mesh_->n_elements())
2330 per_element(dissipation_, "growth_dissipation");
2331 if (shear_work_.size() == mesh_->n_elements())
2332 per_element(shear_work_, "growth_shear_supply_work");
2333 }
2334
2335 if (growth_law_.enabled && growth_activation_step_.size() == growth_ndof()
2336 && options.export_field("growth_activation_step"))
2337 {
2338 const Eigen::MatrixXd steps = growth_activation_step_.cast<double>();
2339 Eigen::MatrixXd values;
2340 if (sample_growth_scalar(steps, values))
2341 fields.push_back({"growth_activation_step", values, io::OutputField::Association::Point});
2342 }
2343
2344 if (growthelastic_assembler_)
2345 append_material_fields(*growthelastic_assembler_);
2346
2347 return fields;
2348 }
2349} // namespace polyfem::varform
QuadratureVector da
ElementAssemblyValues vals
std::vector< Eigen::Triplet< double > > entries
Eigen::RowVectorXd point
StiffnessMatrix source
int x
#define POLYFEM_SCOPED_TIMER(...)
Definition Timer.hpp:10
double characteristic_length() const
Definition Units.hpp:22
static std::shared_ptr< MixedNLAssembler > make_mixed_nl_assembler(const std::string &formulation)
static bool is_elastic_material(const std::string &material)
utility to check if material is one of the elastic materials
static std::shared_ptr< Assembler > make_assembler(const std::string &formulation)
void init(const bool is_volume, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const bool is_mass=false)
computes the basis evaluation and geometric mapping for each of the given ElementBases in bases initi...
void init_empty(const bool is_mass=false)
initialize an empty cache.
void compute(const int el_index, const bool is_volume, const basis::ElementBases &basis, const basis::ElementBases &gbasis, ElementAssemblyValues &vals) const
Copies cached values into vals, or computes into vals when the cache is empty.
stores per element basis values at given quadrature points and geometric mapping
void compute(const int el_index, const bool is_volume, const Eigen::MatrixXd &pts, const basis::ElementBases &basis, const basis::ElementBases &gbasis)
computes the per element values at the local (ref el) points (pts) sets basis_values,...
Represents one basis function and its gradient.
Definition Basis.hpp:44
Stores the basis functions for a given element in a mesh (facet in 2d, cell in 3d).
std::vector< Basis > bases
one basis function per node in the element
static void interpolate_at_local_vals(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const int el_index, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &fun, Eigen::MatrixXd &result, Eigen::MatrixXd &result_grad)
interpolate solution and gradient at element (calls interpolate_at_local_vals with sol)
void save_vtu(const std::string &path, const OutputSpace &space, const OutputFieldFunction &output_fields, const double t, const double dt, const ExportOptions &opts) const
saves the vtu file for time t
Definition OutData.cpp:2351
double assigning_rhs_time
time to computing the rhs
double assembling_mass_mat_time
time to assembly mass
double solving_time
time to solve
all stats from polyfem
int n_flipped
number of flipped elements, compute only when using count_flipped_els (false by default)
json solver_info
information of the solver, eg num iteration, time, errors, etc the informations varies depending on t...
Eigen::Vector4d spectrum
spectrum of the stiffness matrix, enable only if POLYSOLVE_WITH_SPECTRA is ON (off by default)
void count_flipped_elements(const polyfem::mesh::Mesh &mesh, const std::vector< polyfem::basis::ElementBases > &gbases)
counts the number of flipped elements
Definition OutData.cpp:3021
void compute_errors(const int n_bases, const std::vector< polyfem::basis::ElementBases > &bases, const std::vector< polyfem::basis::ElementBases > &gbases, const polyfem::mesh::Mesh &mesh, const assembler::Problem &problem, const double tend, const Eigen::MatrixXd &sol)
compute errors
Definition OutData.cpp:3066
void compute_mesh_size(const polyfem::mesh::Mesh &mesh_in, const std::vector< polyfem::basis::ElementBases > &bases_in, const int n_samples, const bool use_curved_mesh_size)
computes the mesh size, it samples every edges n_samples times uses curved_mesh_size (false by defaul...
Definition OutData.cpp:2938
long long nn_zero
non zeros and sytem matrix size num dof is the total dof in the system
double mesh_size
max edge lenght
virtual std::string describe(const std::string &path) const =0
virtual std::unique_ptr< std::istream > open(const std::string &path, bool binary) const =0
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:77
int n_elements() const
utitlity to return the number of elements, cells or faces in 3d and 2d
Definition Mesh.hpp:181
virtual int n_vertices() const =0
number of vertices
virtual int get_body_id(const int primitive) const
Get the volume selection of an element (cell in 3d, face in 2d)
Definition Mesh.hpp:521
virtual void bounding_box(RowVectorNd &min, RowVectorNd &max) const =0
computes the bbox of the mesh
virtual bool is_volume() const =0
checks if mesh is volume
int dimension() const
utily for dimension
Definition Mesh.hpp:171
static void p_refine(const mesh::Mesh &mesh, const double B, const bool h1_formula, const int base_p, const int discr_order_max, io::OutStatsData &stats, Eigen::VectorXi &disc_orders)
compute a priori prefinement
Definition APriori.cpp:242
void solve_reduced(NLProblem &nl_problem, Eigen::MatrixXd &sol, std::shared_ptr< polysolve::nonlinear::Solver > nl_solver)
Definition ALSolver.hpp:41
std::function< void(const double)> post_subsolve
Definition ALSolver.hpp:53
void solve_al(NLProblem &nl_problem, Eigen::MatrixXd &sol, std::shared_ptr< polysolve::nonlinear::Solver > nl_solver)
Definition ALSolver.hpp:29
bool is_residual() const override
virtual void init(const TVector &x0) override
double normalize_forms() override
void init_lagging(const TVector &x) override
std::shared_ptr< solver::NLProblem > nl_problem
std::vector< std::shared_ptr< solver::AugmentedLagrangianForm > > al_form
std::shared_ptr< time_integrator::ImplicitTimeIntegrator > time_integrator
void update_barrier_stiffness(const Eigen::VectorXd &x)
update the barrier stiffness for the forms
std::shared_ptr< assembler::RhsAssembler > rhs_assembler
assembler::AssemblyValsCache pure_mass_ass_vals_cache_
std::shared_ptr< assembler::Assembler > primary_assembler_
QuadratureOrders elastic_boundary_samples() const
assembler::AssemblyValsCache ass_vals_cache_
std::shared_ptr< assembler::HRZMass > pure_mass_assembler_
std::shared_ptr< assembler::Mass > mass_assembler_
std::shared_ptr< assembler::RhsAssembler > rhs_assembler_
assembler::AssemblyValsCache mass_ass_vals_cache_
void initial_solution(Eigen::MatrixXd &solution, const InitialConditionOverride *override=nullptr, const std::string &state_prefix="") const
void export_data(const Eigen::MatrixXd &solution) const override
const std::vector< basis::ElementBases > & geometry_basis_list() const
Definition FESpace.hpp:119
std::shared_ptr< GeometryMapping > geometry
Geometric mapping used to integrate this FE space.
Definition FESpace.hpp:93
Eigen::VectorXi disc_orders
Primary polynomial degree for each mesh element.
Definition FESpace.hpp:71
Eigen::VectorXi disc_ordersq
Secondary polynomial degree for anisotropic bases, e.g. prisms.
Definition FESpace.hpp:74
int n_bases
Number of globally indexed scalar basis functions in the space.
Definition FESpace.hpp:65
Eigen::VectorXi space_in_node_to_node
Definition FESpace.hpp:95
const std::vector< basis::ElementBases > & basis_list() const
Definition FESpace.hpp:113
Eigen::VectorXi space_in_primitive_to_primitive
Definition FESpace.hpp:96
std::shared_ptr< mesh::MeshNodes > mesh_nodes
Optional primitive-to-node mapping for this FE space.
Definition FESpace.hpp:86
int node_tag(const int node) const
Point-selection id of a node of this space (see MeshNodes::node_tag); -1 without mesh nodes (e....
Definition FESpace.hpp:90
bool setup_logged_
the setup line is logged once, not per update
std::shared_ptr< assembler::MixedNLAssembler > growthelastic_assembler_
void solve_problem(Eigen::MatrixXd &sol, const InitialConditionOverride *initial_condition_override, const ForwardStepCallback &post_step) override
void threshold_target(const Eigen::MatrixXd &solution, double t, Eigen::VectorXd &par, Eigen::VectorXd &gam, Eigen::VectorXd &clamped)
the threshold the state implies (from_state): G(x) = (PHI_PAR, f_gamma) at C_check of the state; f_ga...
Eigen::VectorXd lag_residual_
phi(converged state) - phi used, last increment [Pa]
void solve_nonlinear_step(const int step, Eigen::MatrixXd &solution, double grad_tol_factor=1.0)
std::shared_ptr< assembler::Problem > growth_problem_
std::shared_ptr< assembler::Density > growth_rhs_density_
std::vector< io::OutputField > output_fields(const io::OutputSample &sample, const Eigen::MatrixXd &solution, const io::OutputFieldOptions &options) const override
Get the output fields of the variational formulation, for output purposes.
Eigen::VectorXd element_volume_
reference element volumes (growth quadrature)
Eigen::MatrixXd stacked_solution(const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &growth) const
Eigen::VectorXi growth_activation_step_
first increment in which a growth DOF grew (0 = never)
void set_threshold(const Eigen::VectorXd &par, const Eigen::VectorXd &gam, const Eigen::VectorXd &clamped, double t, double omega)
install a threshold (parts), rebuild the node weights, log
Eigen::VectorXd threshold_per_element_
phi_e [Pa] in use (from_state: phi_par + f_gamma)
Eigen::VectorXd growth_node_weights_
int vn phi N_a dV
void save_growth_increment(int step, double t, const Eigen::MatrixXd &solution)
growth_law.save_increments: the converged stacked state of increment step (pseudo-time t) as growth_s...
std::vector< char > growth_pinned_mask_
last solved pass: 1 = pinned at theta_n
int advance_increment(int step, double t_from, double t_to, Eigen::MatrixXd &solution, int depth)
one increment (t_from, t_to], split recursively on failure; returns passes
std::shared_ptr< solver::StackedForm > stacked_form_
void build_forms(Eigen::MatrixXd &solution, const double t)
Eigen::VectorXd attainment_
vartheta^e / theta_crit at the last converged increment
Eigen::VectorXd normal_growth_per_element_
vn_e (1 when not given)
void make_nl_problem(const Eigen::MatrixXd &sol, const double t)
NLProblem over the current forms and AL forms, initialized at sol, t.
void assemble_rhs(const mesh::Mesh &mesh) override
void report_lag_residual(int step, double t, const Eigen::MatrixXd &solution)
lag residual phi(converged state) - phi used, and attainment, logged per increment
void export_data(const Eigen::MatrixXd &solution) const override
std::shared_ptr< assembler::RhsAssembler > growth_rhs_assembler_
void deserialize_checkpoint(const io::CheckpointReader &reader, Eigen::MatrixXd &solution) override
void solve_growth_law(Eigen::MatrixXd &solution)
Eigen::MatrixXd prescribed_growth_
Whole-field growth prescription (boundary_conditions.growth_nodal_field): nodal theta values loaded l...
void replace_stress_fields(const io::OutputSample &sample, const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &growth, std::vector< io::OutputField > &fields) const
The elastic base evaluates von_mises, cauchy_stess_*, pk1_stess_*, pk2_stess_* (and the *_avg variant...
Eigen::MatrixXd converged_solution_
Converged stacked (u, growth) solution cached at the end of solve_problem.
int solve_growth_increment(const int step, const double t, Eigen::MatrixXd &solution)
One increment: primal-dual active-set loop on theta >= theta_n.
std::shared_ptr< solver::MixedAssemblerForm > growth_coupling_form_
Eigen::VectorXd threshold_clamped_
1 where f_par(C_check) < 0 (zero floor), when computed here
void log_kkt_residual(int step, double t, const Eigen::MatrixXd &solution, const Eigen::VectorXd &mult, const std::vector< char > &pinned)
phi - f_I per v_n-weighted nodal volume on the settled set: free and pinned
const Eigen::MatrixXd & prescribed_growth_field() const
void grown_stress_at(const int e, const Eigen::MatrixXd &local_pts, const double t, const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &growth, Eigen::MatrixXd &cauchy, Eigen::MatrixXd &pk1, Eigen::MatrixXd &pk2, Eigen::MatrixXd &von_mises, Eigen::MatrixXd &energy) const
Grown-material stresses and energy density (GrowthElasticity::grown_stresses) at local points of elem...
Eigen::VectorXd threshold_parallel_
from_state: phi_par,e of the last update [Pa]
Eigen::VectorXd element_mean_growth(const Eigen::VectorXd &theta)
element mean of a nodal growth field (growth quadrature)
Eigen::VectorXd dissipation_
cumulative D = sum v_n max(f_par,0) dtheta per element [Pa]
void split_solution(const Eigen::MatrixXd &solution, Eigen::MatrixXd &displacement, Eigen::MatrixXd &growth) const
void build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args) override
void evaluate_threshold_state(const Eigen::VectorXd &u, double t, Eigen::VectorXd &phi_full, Eigen::VectorXd &phi_no_shear, Eigen::VectorXd &theta_tot)
The state-built threshold at C_check of displacement u, per element: f_I(Ce) (phi_full),...
std::shared_ptr< solver::GrowthDissipationForm > dissipation_form_
void validate_time_dependence() const override
Solved growth steps its own pseudo-time (growth_law.n_steps, t_end), so its displacement problem is t...
Eigen::VectorXd shear_work_
cumulative S = sum v_n f_gamma dtheta per element [Pa]
Eigen::VectorXd growth_multiplier(const Eigen::MatrixXd &solution) const
d Pi_inc / d theta at the solution: stacked energy gradient plus the dissipation weights (the KKT res...
Eigen::VectorXd shear_supply_
from_state: f_gamma,e of the last update [Pa]
Eigen::VectorXd theta_n_
converged growth of the previous increment
void solve_with_current_pins(const int step, const double t, Eigen::MatrixXd &solution, double grad_tol_factor=1.0)
struct polyfem::varform::GrowthElasticVarForm::GrowthLawSettings growth_law_
std::vector< int > pinned_growth_nodes_
member: BCLagrangianForm keeps a reference
void build_growth_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args)
assembler::AssemblyValsCache growth_ass_vals_cache_
void assemble_growth_node_weights()
w_a = sum_e vn_e phi_e int_e N_a dV from threshold_per_element_ (and the nodal volumes); called once ...
void load_mesh(const mesh::Mesh &mesh, const json &args) override
void serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const override
both blocks of the stacked (displacement, growth) solution, each with its node ordering,...
std::shared_ptr< assembler::Assembler > growth_assembler_
static double median_of(const Eigen::VectorXd &v)
assembler::AssemblyValsCache growth_mass_ass_vals_cache_
void init(const std::string &formulation, const Units &units, const json &args, const std::string &out_path) override
Initialize the variational formulation with the given parameters.
std::string name() const override
Get the name of the variational formulation.
io::OutStatsData compute_errors(const Eigen::MatrixXd &solution) override
Get the error statistics of the variational formulation, for output purposes.
Eigen::VectorXd growth_node_vn_volume_
int vn N_a dV (KKT residual in Pa)
void assemble_mass_mat(const mesh::Mesh &mesh, const json &args) override
std::shared_ptr< assembler::Mass > growth_mass_assembler_
void initial_growth_solution(Eigen::MatrixXd &solution) const
void commit_increment(int step, double t, Eigen::MatrixXd &solution)
D/S accumulation, theta_n update and activation marking after a converged (sub)increment.
void accumulate_dissipation(int step, double t, const Eigen::VectorXd &dtheta)
split of the increment's dissipation term (D, S), accumulated and logged
virtual void init_forms(const json &args, int dim, Eigen::MatrixXd &sol, double t)
std::vector< io::OutputField > output_fields(const io::OutputSample &sample, const Eigen::MatrixXd &solution, const io::OutputFieldOptions &options) const override
Get the output fields of the variational formulation, for output purposes.
io::OutputSpace output_space() const override
Get the output space of the variational formulation, for output purposes.
static void build_collision_mesh(const mesh::Mesh &mesh, const int n_bases, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &geom_bases, const std::vector< mesh::LocalBoundary > &total_local_boundary, const mesh::Obstacle &obstacle, const json &args, const io::ResourceIO &resources, const Eigen::VectorXi &in_node_to_node, ipc::CollisionMesh &collision_mesh)
std::vector< std::shared_ptr< solver::Form > > forms
void reorder_checkpoint_block(const io::CheckpointReader &reader, const std::string &name, const FESpace &space, int block_size, int row_offset, Eigen::MatrixXd &value) const
Definition VarForm.cpp:1023
static void rebuild_node_positions(const std::vector< basis::ElementBases > &bases, const std::vector< int > &node_ids, std::vector< RowVectorNd > &positions)
Definition VarForm.cpp:1219
std::shared_ptr< assembler::Problem > problem
current problem, it contains rhs and bc
Definition VarForm.hpp:282
void write_checkpoint_ordering(io::CheckpointWriter &writer, const std::string &name, const FESpace &space) const
Definition VarForm.cpp:980
virtual void deserialize_checkpoint(const io::CheckpointReader &reader, Eigen::MatrixXd &solution)
Definition VarForm.cpp:947
std::unique_ptr< mesh::Mesh > mesh_
Definition VarForm.hpp:294
void assign_discr_orders(const json &space_args, const mesh::Mesh &mesh, Eigen::VectorXi &disc_orders, Eigen::VectorXi &disc_ordersq)
Definition VarForm.cpp:726
io::OutStatsData stats
Definition VarForm.hpp:286
io::OutGeometryData::ExportOptions export_options(const io::OutputSpace &space) const
Definition VarForm.cpp:877
io::OutGeometryData output_geometry_
Definition VarForm.hpp:298
void save_subsolve(const int i, const int t, const Eigen::MatrixXd &solution) const
Definition VarForm.cpp:1180
io::OutputFieldFunction output_field_function(const Eigen::MatrixXd &solution, const io::OutGeometryData::ExportOptions &opts) const
Definition VarForm.cpp:886
virtual void serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const
Definition VarForm.cpp:939
QuadratureOrders n_boundary_samples(const int discr_order, const int discr_orderq, const int gdiscr_order) const
Definition VarForm.cpp:187
void build_fe_space(mesh::Mesh &mesh, const bool iso_parametric, const Eigen::VectorXi &disc_orders, const Eigen::VectorXi &disc_ordersq, const std::string &basis_type, const std::string &poly_basis_type, const assembler::Assembler &space_assembler, const int value_dim, const int quadrature_order, const int mass_quadrature_order, const bool use_corner_quadrature, const int n_harmonic_samples, const int integral_constraints, FESpace &space, VarFormBoundaryState &boundary, std::shared_ptr< GeometryMapping > geometry=nullptr)
Definition VarForm.cpp:286
std::string resolve_output_path(const std::string &path) const
Definition VarForm.cpp:1210
virtual void validate_time_dependence() const
Check time configuration after the derived formulation initializes its problem.
Definition VarForm.cpp:226
void ensure_output_sampler() const
Definition VarForm.cpp:863
virtual void init(const std::string &formulation, const Units &units, const json &args, const std::string &out_path)
Initialize the variational formulation with the given parameters.
Definition VarForm.cpp:210
void validate_checkpoint_solution(const Eigen::MatrixXd &solution, int expected_rows) const
Definition VarForm.cpp:1079
io::OutRuntimeData timings
runtime statistics
Definition VarForm.hpp:289
const io::ResourceIO & resources_
Definition VarForm.hpp:305
void build_node_mapping(const mesh::Mesh &mesh, const std::string &basis_type, const FESpace &space, Eigen::VectorXi &space_in_node_to_node, Eigen::VectorXi &space_in_primitive_to_primitive) const
Input-order -> internal node map of an FE space.
Definition VarForm.cpp:646
Eigen::MatrixXd read_growth_cell_array(const io::ResourceIO &resources, const std::string &path, const std::string &field, const int ncomp_expected)
Mixed (displacement, growth) assembler implementing the correction energy of finite areal growth of a...
void prism_nodes_3d(const int p, const int q, Eigen::MatrixXd &val)
void p_nodes_3d(const int p, Eigen::MatrixXd &val)
void q_nodes_3d(const int q, Eigen::MatrixXd &val)
Eigen::SparseMatrix< double > lump_matrix(const Eigen::SparseMatrix< double > &M)
Lump each row of a matrix into the diagonal.
Eigen::SparseMatrix< double > sparse_identity(int rows, int cols)
std::vector< T > json_as_array(const json &j)
Return the value of a json object as an array.
Definition JSONUtils.hpp:49
Eigen::VectorXd flatten(const Eigen::MatrixXd &X)
Flatten rowwises.
std::function< void(int step, const Eigen::MatrixXd &solution)> ForwardStepCallback
Definition VarForm.hpp:59
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:44
std::array< int, 2 > QuadratureOrders
Definition Types.hpp:19
nlohmann::json json
Definition Common.hpp:9
double von_mises_stress_for_stress_tensor(const Eigen::MatrixXd &stress)
void compute_diplacement_grad(const int size, const ElementAssemblyValues &vals, const Eigen::MatrixXd &local_pts, const int p, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &displacement_grad)
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
Definition Types.hpp:13
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix
Definition Types.hpp:24
bool export_field(const std::string &field) const
Definition OutData.cpp:82
Eigen::VectorXi node_ids
Eigen::VectorXi element_ids
Eigen::MatrixXd local_points
const mesh::Mesh * mesh
Growth law (material "growth_law"): rate-independent, per-element threshold (given,...
double t_end
pseudo-time at which DBC expressions reach their end state
int max_increment_splits
a failed increment is retried from its start as two half increments, recursively, up to this many lev...
double relag_tol
from_state: per-pass threshold iteration tolerance [Pa]
double theta_crit
C_check in-plane elastic area stretch (from_state; else optional, lag report)
bool from_state
threshold "from_state": phi_e = max(f_par, 0) + f_gamma at C_check of the current displacement,...
double final_tol_factor
< 1: after the active set settles, one confirmation pass with the nonlinear gradient tolerance multip...
double feasibility_tol
pin a free DOF if theta < theta_n - tol
double active_set_tol
release a pin if dPi/dtheta < -tol * scale_a (Pa)
double theta_floor_fraction
positivity filter: theta >= fraction * theta_n
bool save_increments
write growth_step_<k>.vtu + growth_steps.pvd per increment
std::vector< RowVectorNd > neumann_nodes_position
Definition FESpace.hpp:167
std::vector< mesh::LocalBoundary > local_boundary
Definition FESpace.hpp:159
std::vector< mesh::LocalBoundary > local_neumann_boundary
Definition FESpace.hpp:160
std::vector< mesh::LocalBoundary > total_local_boundary
Definition FESpace.hpp:158
std::vector< RowVectorNd > dirichlet_nodes_position
Definition FESpace.hpp:165