PolyFEM
Loading...
Searching...
No Matches
NavierStokesFSIVarForm.cpp
Go to the documentation of this file.
2
4
28
29#include <igl/Timer.h>
30#include <polysolve/linear/FEMSolver.hpp>
31#include <polysolve/nonlinear/Solver.hpp>
32#include <paraviewo/VTMWriter.hpp>
33#include <spdlog/fmt/fmt.h>
34
35#include <optional>
36#include <map>
37#include <set>
38
39namespace polyfem::varform
40{
43 const Eigen::MatrixXd &solution,
44 const io::CheckpointMetadata &metadata) const
45 {
46 VarForm::serialize_checkpoint(writer, solution, metadata);
47 write_checkpoint_ordering(writer, "primary", space_);
48 write_checkpoint_ordering(writer, "pressure", pressure_space_);
51 log_and_throw_error("Cannot checkpoint NavierStokesFSI without its mesh-motion integrator.");
52 mesh_displacement_time_integrator_->serialize_checkpoint(writer, "/checkpoint/state/mesh_motion_integrator");
53 if (has_solid_)
54 {
55 if (!solid_varform_ || !solid_varform_->embedding_time_integrator())
56 log_and_throw_error("Cannot checkpoint two-mesh NavierStokesFSI without its solid integrator.");
57 const io::OutputSpace solid_output = solid_varform_->output_space();
58 if (solid_output.mesh == nullptr)
59 log_and_throw_error("Cannot checkpoint NavierStokesFSI without its solid mesh.");
60 writer.write_mesh("/checkpoint/meshes/solid", *solid_output.mesh);
61 write_checkpoint_ordering(writer, "solid", solid_varform_->space_);
62 solid_varform_->embedding_time_integrator()->serialize_checkpoint(writer, "/checkpoint/state/solid_integrator");
63 }
64 }
65
67 const io::CheckpointReader &reader,
68 Eigen::MatrixXd &solution)
69 {
70 VarForm::deserialize_checkpoint(reader, solution);
72 const int dim = mesh_->dimension();
73 reorder_checkpoint_block(reader, "primary", space_, dim, 0, solution);
75 reader, "pressure", pressure_space_,
76 1, pressure_offset(), solution);
78 reader, "mesh_motion", mesh_displacement_space_,
79 dim, mesh_displacement_offset(), solution);
80 if (has_solid_)
82 reader, "solid", solid_varform_->space_,
83 dim, solid_displacement_offset(), solution);
84 }
85
86 namespace
87 {
88 json first_material(const json &materials)
89 {
90 return materials.is_array() ? materials.at(0) : materials;
91 }
92
93 json mesh_material(const json &material)
94 {
95 json result = material.at("mesh_material");
96 if (material.contains("id"))
97 result["id"] = material["id"];
98 return result;
99 }
100
101 json filter_fe_space_entries(const json &entries, const int fe_space_id)
102 {
103 if (!entries.is_array())
104 return entries;
105
106 json result = json::array();
107 for (const json &entry : entries)
108 {
109 if (!entry.is_object())
110 {
111 result.push_back(entry);
112 continue;
113 }
114 if (entry.contains("fe_space") && entry["fe_space"].get<int>() != fe_space_id)
115 continue;
116 json filtered = entry;
117 filtered.erase("fe_space");
118 result.push_back(std::move(filtered));
119 }
120 return result;
121 }
122
123 json residual_solver_params(const json &input)
124 {
125 json params = input;
126 params["solver"] = "Newton";
127 params["line_search"]["method"] = "ResidualBacktracking";
128 if (!params.contains("Newton") || params["Newton"].is_null())
129 params["Newton"] = json::object();
130 params["Newton"]["force_psd_projection"] = false;
131 params["Newton"]["use_psd_projection"] = true;
132 return params;
133 }
134
135 StiffnessMatrix residual_mass(
136 const StiffnessMatrix &velocity_mass,
137 const int pressure_size,
138 const StiffnessMatrix &mesh_mass,
139 const StiffnessMatrix &solid_mass,
140 const StiffnessMatrix &fluid_interface_mass,
141 const StiffnessMatrix &mesh_interface_mass,
142 const bool add_average)
143 {
144 const int mesh_offset = velocity_mass.rows() + pressure_size;
145 const int solid_offset = mesh_offset + mesh_mass.rows();
146 const int fluid_interface_offset = solid_offset + solid_mass.rows();
147 const int mesh_interface_offset = fluid_interface_offset + fluid_interface_mass.rows();
148 const int total = mesh_interface_offset + mesh_interface_mass.rows() + (add_average ? 1 : 0);
149 std::vector<Eigen::Triplet<double>> entries;
150 entries.reserve(velocity_mass.nonZeros() + pressure_size + mesh_mass.nonZeros()
151 + solid_mass.nonZeros() + fluid_interface_mass.nonZeros()
152 + mesh_interface_mass.nonZeros() + (add_average ? 1 : 0));
153 for (int k = 0; k < velocity_mass.outerSize(); ++k)
154 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
155 entries.emplace_back(it.row(), it.col(), it.value());
156 for (int i = 0; i < pressure_size; ++i)
157 entries.emplace_back(velocity_mass.rows() + i, velocity_mass.rows() + i, 1);
158 for (int k = 0; k < mesh_mass.outerSize(); ++k)
159 for (StiffnessMatrix::InnerIterator it(mesh_mass, k); it; ++it)
160 entries.emplace_back(mesh_offset + it.row(), mesh_offset + it.col(), it.value());
161 for (int k = 0; k < solid_mass.outerSize(); ++k)
162 for (StiffnessMatrix::InnerIterator it(solid_mass, k); it; ++it)
163 entries.emplace_back(solid_offset + it.row(), solid_offset + it.col(), it.value());
164 for (int k = 0; k < fluid_interface_mass.outerSize(); ++k)
165 for (StiffnessMatrix::InnerIterator it(fluid_interface_mass, k); it; ++it)
166 entries.emplace_back(fluid_interface_offset + it.row(), fluid_interface_offset + it.col(), it.value());
167 for (int k = 0; k < mesh_interface_mass.outerSize(); ++k)
168 for (StiffnessMatrix::InnerIterator it(mesh_interface_mass, k); it; ++it)
169 entries.emplace_back(mesh_interface_offset + it.row(), mesh_interface_offset + it.col(), it.value());
170 if (add_average)
171 entries.emplace_back(total - 1, total - 1, 1);
172 StiffnessMatrix result(total, total);
173 result.setFromTriplets(entries.begin(), entries.end());
174 result.makeCompressed();
175 return result;
176 }
177
178 bool same_point(const RowVectorNd &a, const RowVectorNd &b)
179 {
180 return a.size() == b.size() && (a - b).norm() <= 1e-10;
181 }
182
183 int local_edge(const mesh::Mesh2D &mesh, const mesh::Navigation::Index &index)
184 {
185 for (int le = 0; le < mesh.n_face_vertices(index.face); ++le)
186 if (mesh.get_index_from_face(index.face, le).edge == index.edge)
187 return le;
188 log_and_throw_error("Unable to locate interface edge {} in element {}.", index.edge, index.face);
189 }
190
191 std::map<int, Eigen::VectorXd> global_basis_values(
192 const basis::ElementBases &bases, const Eigen::MatrixXd &points)
193 {
194 std::vector<assembler::AssemblyValues> values;
195 bases.evaluate_bases(points, values);
196 std::map<int, Eigen::VectorXd> result;
197 for (int i = 0; i < int(values.size()); ++i)
198 for (const auto &global : bases.bases[i].global())
199 {
200 auto it = result.try_emplace(
201 global.index, Eigen::VectorXd::Zero(points.rows()))
202 .first;
203 it->second += global.val * values[i].val.col(0);
204 }
205 return result;
206 }
207
208 struct ScalarTraceOperators
209 {
212 std::vector<int> multiplier_source_ids;
213 };
214
215 struct VectorTraceOperators
216 {
219 };
220
221 ScalarTraceOperators assemble_2d_trace_operators(
222 const mesh::Mesh2D &fluid_mesh,
223 const mesh::Mesh2D &solid_mesh,
224 const std::vector<std::pair<mesh::Navigation::Index, mesh::Navigation::Index>> &interface_pairs,
225 const std::vector<basis::ElementBases> &source_bases,
226 const int source_n_bases,
227 const std::vector<basis::ElementBases> &solid_bases,
228 const int solid_n_bases,
229 const int quadrature_order)
230 {
231 ScalarTraceOperators result;
232 std::map<int, int> multiplier_index;
233 std::vector<Eigen::Triplet<double>> source_entries, solid_entries;
234 for (const auto &[fluid_index, solid_index] : interface_pairs)
235 {
236 const int fluid_edge = local_edge(fluid_mesh, fluid_index);
237 const int solid_edge = local_edge(solid_mesh, solid_index);
238 const int fluid_vertices = fluid_mesh.n_face_vertices(fluid_index.face);
239 const int solid_vertices = solid_mesh.n_face_vertices(solid_index.face);
240 if ((fluid_vertices != 3 && fluid_vertices != 4)
241 || (solid_vertices != 3 && solid_vertices != 4))
242 log_and_throw_error("FSI interface coupling currently supports triangular and quadrilateral 2D elements.");
243
244 const RowVectorNd fluid_from = fluid_mesh.point(fluid_mesh.face_vertex(fluid_index.face, fluid_edge));
245 const RowVectorNd fluid_to = fluid_mesh.point(fluid_mesh.face_vertex(fluid_index.face, (fluid_edge + 1) % fluid_vertices));
246 const RowVectorNd solid_from = solid_mesh.point(solid_mesh.face_vertex(solid_index.face, solid_edge));
247 const RowVectorNd solid_to = solid_mesh.point(solid_mesh.face_vertex(solid_index.face, (solid_edge + 1) % solid_vertices));
248 const bool same_orientation = same_point(fluid_from, solid_from) && same_point(fluid_to, solid_to);
249 const bool opposite_orientation = same_point(fluid_from, solid_to) && same_point(fluid_to, solid_from);
250 if (!same_orientation && !opposite_orientation)
252 "FSI interface edge pair ({}, {}) is only partially overlapping; conforming facets are required.",
253 fluid_index.edge, solid_index.edge);
254
255 Eigen::MatrixXd uv, fluid_points;
256 Eigen::VectorXd weights;
257 if (fluid_vertices == 3)
259 fluid_edge, quadrature_order, fluid_index.edge, fluid_mesh, uv, fluid_points, weights);
260 else
262 fluid_edge, quadrature_order, fluid_index.edge, fluid_mesh, uv, fluid_points, weights);
263
264 const Eigen::Matrix2d solid_endpoints = solid_vertices == 3
266 : utils::BoundarySampler::quad_local_node_coordinates_from_edge(solid_edge);
267 Eigen::MatrixXd solid_points(fluid_points.rows(), 2);
268 for (int q = 0; q < solid_points.rows(); ++q)
269 {
270 const double t = uv(q, 1);
271 if (same_orientation)
272 solid_points.row(q) = (1 - t) * solid_endpoints.row(0) + t * solid_endpoints.row(1);
273 else
274 solid_points.row(q) = (1 - t) * solid_endpoints.row(1) + t * solid_endpoints.row(0);
275 }
276
277 const auto source_values = global_basis_values(source_bases.at(fluid_index.face), fluid_points);
278 const auto solid_values = global_basis_values(solid_bases.at(solid_index.face), solid_points);
279 for (const auto &[source_id, multiplier_values] : source_values)
280 {
281 if (multiplier_values.cwiseAbs().maxCoeff() < 1e-12)
282 continue;
283 const auto [it, inserted] = multiplier_index.try_emplace(source_id, multiplier_index.size());
284 const int row = it->second;
285 if (inserted)
286 result.multiplier_source_ids.push_back(source_id);
287 for (const auto &[trial_id, trial_values] : source_values)
288 {
289 const double value = (weights.array() * multiplier_values.array() * trial_values.array()).sum();
290 if (std::abs(value) > 1e-14)
291 source_entries.emplace_back(row, trial_id, value);
292 }
293 for (const auto &[trial_id, trial_values] : solid_values)
294 {
295 const double value = (weights.array() * multiplier_values.array() * trial_values.array()).sum();
296 if (std::abs(value) > 1e-14)
297 solid_entries.emplace_back(row, trial_id, value);
298 }
299 }
300 }
301 result.source.resize(multiplier_index.size(), source_n_bases);
302 result.source.setFromTriplets(source_entries.begin(), source_entries.end());
303 result.solid.resize(multiplier_index.size(), solid_n_bases);
304 result.solid.setFromTriplets(solid_entries.begin(), solid_entries.end());
305 return result;
306 }
307
308 VectorTraceOperators vector_trace(
309 const ScalarTraceOperators &scalar,
310 const int dim,
311 const std::vector<int> &source_dirichlet_dofs)
312 {
313 assert(scalar.source.rows() == scalar.solid.rows());
314 assert(scalar.source.rows() == int(scalar.multiplier_source_ids.size()));
315
316 std::vector<bool> is_dirichlet(scalar.source.cols() * dim, false);
317 for (const int dof : source_dirichlet_dofs)
318 if (dof >= 0 && dof < int(is_dirichlet.size()))
319 is_dirichlet[dof] = true;
320
321 std::vector<int> vector_rows(scalar.source.rows() * dim, -1);
322 int n_rows = 0;
323 for (int row = 0; row < scalar.source.rows(); ++row)
324 for (int d = 0; d < dim; ++d)
325 if (!is_dirichlet[scalar.multiplier_source_ids[row] * dim + d])
326 vector_rows[row * dim + d] = n_rows++;
327
328 const auto expand = [&](const StiffnessMatrix &matrix) {
329 std::vector<Eigen::Triplet<double>> entries;
330 entries.reserve(matrix.nonZeros() * dim);
331 for (int k = 0; k < matrix.outerSize(); ++k)
332 for (StiffnessMatrix::InnerIterator it(matrix, k); it; ++it)
333 for (int d = 0; d < dim; ++d)
334 {
335 const int row = vector_rows[it.row() * dim + d];
336 if (row >= 0)
337 entries.emplace_back(row, it.col() * dim + d, it.value());
338 }
339 StiffnessMatrix result(n_rows, matrix.cols() * dim);
340 result.setFromTriplets(entries.begin(), entries.end());
341 return result;
342 };
343
344 VectorTraceOperators result;
345 result.source = expand(scalar.source);
346 result.solid = expand(scalar.solid);
347 return result;
348 }
349 } // namespace
350
352 {
358 has_solid_ = false;
359 mesh_elastic_formulation_ = "NeoHookean";
360 solid_elastic_formulation_ = "NeoHookean";
361 solid_args_ = json();
362 solid_varform_ = nullptr;
363 interface_2d_.clear();
364 interface_3d_.clear();
371 mesh_elastic_assembler_ = nullptr;
372 mesh_mass_assembler_ = nullptr;
374 mesh_rhs_assembler_ = nullptr;
375 mesh_rhs_.resize(0, 0);
376 fluid_zero_rhs_.resize(0, 0);
377 mesh_pure_mass_.resize(0, 0);
378 interface_velocity_trace_.resize(0, 0);
380 interface_mesh_trace_.resize(0, 0);
381 interface_solid_mesh_trace_.resize(0, 0);
382 ale_assemblers_.clear();
384 fsi_forms_.clear();
385 fsi_al_forms_.clear();
386 fsi_problem_ = nullptr;
387 ale_form_ = nullptr;
388 interface_form_ = nullptr;
389 auxiliary_form_ = nullptr;
390 mesh_elastic_form_ = nullptr;
391 fluid_neumann_form_ = nullptr;
392 mesh_body_form_ = nullptr;
393 average_pressure_form_ = nullptr;
394 }
395
397 const std::string &formulation,
398 const Units &units,
399 const json &args,
400 const std::string &out_path)
401 {
402 if (!args.contains("time") || args["time"].is_null())
403 log_and_throw_error("NavierStokesFSI is only available for time-dependent problems.");
404 FluidVarForm::init(formulation, units, args, out_path);
405
406 const json &materials = args.at("materials");
407 const json material = first_material(materials);
408 mesh_displacement_space_id_ = material.at("mesh_displacement_space_id").get<int>();
411 log_and_throw_error("NavierStokesFSI requires distinct velocity, pressure, and mesh-displacement FE spaces.");
412 mesh_elastic_formulation_ = material.at("mesh_material").at("type").get<std::string>();
414 log_and_throw_error("NavierStokesFSI mesh_material must be an elastic material, got {}.", mesh_elastic_formulation_);
415
416 const std::array<std::string, 4> solid_fields{{"fluid_geometry_id", "solid_geometry_id", "displacement_space_id", "solid_material"}};
417 int present_solid_fields = 0;
418 for (const std::string &field : solid_fields)
419 present_solid_fields += material.contains(field);
420 if (present_solid_fields != 0 && present_solid_fields != int(solid_fields.size()))
421 log_and_throw_error("Two-mesh NavierStokesFSI requires fluid_geometry_id, solid_geometry_id, displacement_space_id, and solid_material together.");
422 has_solid_ = present_solid_fields == int(solid_fields.size());
423 if (has_solid_)
424 {
425 fluid_geometry_id_ = material.at("fluid_geometry_id").get<int>();
426 solid_geometry_id_ = material.at("solid_geometry_id").get<int>();
427 displacement_space_id_ = material.at("displacement_space_id").get<int>();
428 solid_elastic_formulation_ = material.at("solid_material").at("type").get<std::string>();
430 log_and_throw_error("NavierStokesFSI solid_material must be an elastic material, got {}.", solid_elastic_formulation_);
431 const std::set<int> ids{
433 if (ids.size() != 4)
434 log_and_throw_error("Two-mesh NavierStokesFSI requires four distinct FE-space IDs.");
436 log_and_throw_error("Two-mesh NavierStokesFSI requires distinct fluid and solid geometry IDs.");
437 }
438
439 if (materials.is_array())
440 for (const json &entry : materials)
441 {
442 if (entry.at("mesh_displacement_space_id").get<int>() != mesh_displacement_space_id_)
443 log_and_throw_error("All NavierStokesFSI materials must use the same mesh-displacement FE space.");
444 if (entry.at("mesh_material").at("type").get<std::string>() != mesh_elastic_formulation_)
445 log_and_throw_error("All NavierStokesFSI regions must use the same mesh elastic formulation.");
446 for (const std::string &field : solid_fields)
447 if (entry.contains(field) != has_solid_)
448 log_and_throw_error("All NavierStokesFSI materials must consistently enable the two-mesh solid fields.");
449 if (has_solid_ && (entry.at("fluid_geometry_id") != fluid_geometry_id_ || entry.at("solid_geometry_id") != solid_geometry_id_ || entry.at("displacement_space_id") != displacement_space_id_ || entry.at("solid_material").at("type") != solid_elastic_formulation_))
450 log_and_throw_error("All NavierStokesFSI materials must use the same geometry IDs, solid FE space, and solid formulation.");
451 }
452
453 if (args.at("space").at("discr_order").is_array())
454 {
455 bool found = false;
456 for (const json &entry : args.at("space").at("discr_order"))
457 found |= entry.at("fe_space").get<int>() == mesh_displacement_space_id_;
458 if (!found)
459 log_and_throw_error("NavierStokesFSI discretization orders must name the mesh-displacement FE space.");
460 }
461
463 mesh_mass_assembler_ = std::make_shared<assembler::Mass>();
464 mesh_pure_mass_assembler_ = std::make_shared<assembler::HRZMass>();
466 std::make_shared<assembler::NavierStokesFSIVelocity>(),
467 std::make_shared<assembler::NavierStokesFSIMixed>(),
468 std::make_shared<assembler::NavierStokesFSIPressure>(),
469 std::make_shared<assembler::NavierStokesFSIInertia>()};
470
471 mesh_displacement_problem_ = std::make_shared<assembler::GenericTensorProblem>("NavierStokesFSIMeshDisplacement");
473 mesh_displacement_problem_->set_parameters({{"is_time_dependent", true}}, resources_);
474 auto boundary_conditions = args["boundary_conditions"];
475 mesh_displacement_problem_->set_parameters(boundary_conditions, resources_);
476 mesh_displacement_problem_->set_parameters(args["initial_conditions"], resources_);
477 mesh_displacement_problem_->set_parameters(args["output"], resources_);
479
480 if (has_solid_)
481 {
483 solid_varform_ = std::make_shared<NonlinearElasticTransientVarForm>(resources_);
485 }
486 }
487
489 {
490 if (args["materials"].is_array())
491 {
492 json result = json::array();
493 for (const json &material : args["materials"])
494 result.push_back(mesh_material(material));
495 return result;
496 }
497 return mesh_material(args["materials"]);
498 }
499
501 {
502 json result = args;
503 const json material = first_material(args.at("materials"));
504 result["materials"] = material.at("solid_material");
505 result.erase("preset_problem");
506
507 if (result["space"]["discr_order"].is_array())
508 result["space"]["discr_order"] = filter_fe_space_entries(
509 result["space"]["discr_order"], displacement_space_id_);
510
511 for (const char *key : {
512 "rhs", "dirichlet_boundary", "neumann_boundary",
513 "nodal_neumann_boundary", "normal_aligned_neumann_boundary"})
514 {
515 if (result["boundary_conditions"].contains(key))
516 result["boundary_conditions"][key] = filter_fe_space_entries(
517 result["boundary_conditions"][key], displacement_space_id_);
518 }
519 result["boundary_conditions"]["pressure_boundary"] = json::array();
520 result["boundary_conditions"]["pressure_cavity"] = json::array();
521
522 for (const char *key : {"solution", "velocity", "acceleration"})
523 if (result["initial_conditions"].contains(key))
524 result["initial_conditions"][key] = filter_fe_space_entries(
525 result["initial_conditions"][key], displacement_space_id_);
526
527 result["time"]["integrator"] = time_integrator_args(displacement_space_id_);
528 result["constraints"]["hard"] = json::array();
529 result["constraints"]["soft"] = json::array();
530 result["space"]["remesh"]["enabled"] = false;
531
532 result["output"]["advanced"]["timestep_prefix"] =
533 "solid_" + result["output"]["advanced"]["timestep_prefix"].get<std::string>();
534 return result;
535 }
536
538 {
539 const json &integrators = args["time"]["integrator"];
540 if (!integrators.is_array())
541 return integrators;
542 for (const json &integrator : integrators)
543 if (integrator.value("fe_space", -1) == fe_space_id)
544 {
545 json result = integrator;
546 result.erase("fe_space");
547 return result;
548 }
549 log_and_throw_error("Missing time integrator for FE space {}.", fe_space_id);
550 }
551
552 void NavierStokesFSIVarForm::load_mesh(const mesh::Mesh &mesh, const json &args)
553 {
554 if (has_solid_)
555 {
556 std::unique_ptr<mesh::Mesh> fluid_mesh, solid_mesh;
558 {
559 if (!checkpoint_reader_->get().exists("/checkpoint/meshes/solid"))
560 log_and_throw_error("Two-mesh NavierStokesFSI checkpoint is missing its solid mesh.");
561 fluid_mesh = mesh.copy();
562 solid_mesh = checkpoint_reader_->get().read_mesh(
563 "/checkpoint/meshes/solid", !mesh.is_conforming());
564 }
565 else
566 {
567 auto pieces = mesh.split();
568 if (pieces.size() != 2)
569 log_and_throw_error("Two-mesh NavierStokesFSI expected exactly two geometry partitions, got {}.", pieces.size());
570 for (auto &piece : pieces)
571 {
572 if (piece.id == fluid_geometry_id_)
573 fluid_mesh = std::move(piece.mesh);
574 else if (piece.id == solid_geometry_id_)
575 solid_mesh = std::move(piece.mesh);
576 else
577 log_and_throw_error("Unexpected geometry ID {} in two-mesh NavierStokesFSI.", piece.id);
578 }
579 }
580 if (!fluid_mesh || !solid_mesh)
582 "Unable to find configured fluid/solid geometry IDs {}/{}.",
584
585 if (fluid_mesh->dimension() == 2)
586 {
588 dynamic_cast<const mesh::Mesh2D &>(*fluid_mesh),
589 dynamic_cast<const mesh::Mesh2D &>(*solid_mesh));
590 if (interface_2d_.empty())
591 log_and_throw_error("Configured 2D fluid and solid geometries do not share an interface.");
592 }
593 else
594 {
596 dynamic_cast<const mesh::Mesh3D &>(*fluid_mesh),
597 dynamic_cast<const mesh::Mesh3D &>(*solid_mesh));
598 if (interface_3d_.empty())
599 log_and_throw_error("Configured 3D fluid and solid geometries do not share an interface.");
600 }
601
602 mesh_ = std::move(fluid_mesh);
603 solid_varform_->set_mesh(std::move(solid_mesh));
604 }
605
607 std::vector<int> body_ids(mesh_->n_elements());
608 for (int e = 0; e < mesh_->n_elements(); ++e)
609 body_ids[e] = mesh_->get_body_id(e);
610 for (const auto &assembler : ale_assemblers_)
611 {
612 assembler->set_size(mesh_->dimension());
613 assembler->set_materials(body_ids, this->args["materials"], units, resources_);
614 }
615 const json mesh_materials = mesh_material_args();
616 mesh_elastic_assembler_->set_size(mesh_->dimension());
617 mesh_elastic_assembler_->set_materials(body_ids, mesh_materials, units, resources_);
618 mesh_mass_assembler_->set_size(mesh_->dimension());
619 mesh_mass_assembler_->set_materials(body_ids, mesh_materials, units, resources_);
620 mesh_pure_mass_assembler_->set_size(mesh_->dimension());
622 }
623
624 void NavierStokesFSIVarForm::build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args)
625 {
626 FluidVarForm::build_basis(mesh, iso_parametric, args);
627 // The interface traction multiplier can exchange a constant normal
628 // traction with the fluid pressure. Keep an explicit physical-domain
629 // pressure reference in the coupled problem even when an outer boundary
630 // is marked Neumann.
631 if (has_solid_)
632 use_avg_pressure = true;
633 Eigen::VectorXi orders, ordersq;
634 assign_discr_orders(args["space"], mesh_displacement_space_id_, mesh, orders, ordersq);
636 mesh, iso_parametric, orders, ordersq,
637 args["space"]["basis_type"], args["space"]["poly_basis_type"],
639 args["space"]["advanced"]["quadrature_order"],
640 args["space"]["advanced"]["mass_quadrature_order"],
641 args["space"]["advanced"]["use_corner_quadrature"],
642 args["space"]["advanced"]["n_harmonic_samples"],
643 args["space"]["advanced"]["integral_constraints"],
646
648 <= args["solver"]["advanced"]["cache_size"])
649 {
653 }
654 else
655 {
659 }
661 logger().info("n mesh displacement bases: {}", mesh_displacement_space_.n_bases);
662 if (has_solid_)
663 {
664 solid_varform_->prepare_for_embedding();
666 logger().info("n solid displacement dofs: {}", solid_varform_->embedding_ndof());
667 logger().info(
668 "n FSI interface multiplier dofs: physical={}, mesh={}",
670 }
671 }
672
674 {
675 assert(has_solid_ && solid_varform_ && mesh_);
676 if (mesh_->dimension() != 2)
677 log_and_throw_error("Two-mesh FSI interface coupling currently supports 2D meshes.");
678 const io::OutputSpace solid_output = solid_varform_->output_space();
679 assert(solid_output.mesh);
680 const auto &fluid_mesh = dynamic_cast<const mesh::Mesh2D &>(*mesh_);
681 const auto &solid_mesh = dynamic_cast<const mesh::Mesh2D &>(*solid_output.mesh);
682 const FESpace &solid_space = solid_varform_->embedding_space();
683 const int order = 2 * std::max({space_.disc_orders.maxCoeff(), mesh_displacement_space_.disc_orders.maxCoeff(), solid_space.disc_orders.maxCoeff()}) + 2;
684
685 const ScalarTraceOperators physical = assemble_2d_trace_operators(
686 fluid_mesh, solid_mesh, interface_2d_,
688 solid_space.basis_list(), solid_space.n_bases, order);
689 const ScalarTraceOperators computational = assemble_2d_trace_operators(
690 fluid_mesh, solid_mesh, interface_2d_,
692 solid_space.basis_list(), solid_space.n_bases, order);
693 const VectorTraceOperators physical_vector =
694 vector_trace(physical, mesh_->dimension(), boundary_.boundary_nodes);
695 const VectorTraceOperators computational_vector =
696 vector_trace(computational, mesh_->dimension(), mesh_displacement_boundary_.boundary_nodes);
697 interface_velocity_trace_ = physical_vector.source;
698 interface_solid_velocity_trace_ = physical_vector.solid;
699 interface_mesh_trace_ = computational_vector.source;
700 interface_solid_mesh_trace_ = computational_vector.solid;
701 if (interface_velocity_trace_.rows() == 0 || interface_mesh_trace_.rows() == 0)
702 log_and_throw_error("The fluid-solid interface has no active FE trace degrees of freedom.");
703 }
704
706 {
713 mesh.dimension());
714 std::vector<int> unused;
721 for (const int node : mesh_displacement_boundary_.dirichlet_nodes)
722 {
723 const int tag = mesh_displacement_space_.node_tag(node);
724 for (int d = 0; d < mesh.dimension(); ++d)
725 if (mesh_displacement_problem_->is_nodal_dimension_dirichlet(node, tag, d, mesh_displacement_space_id_))
726 mesh_displacement_boundary_.boundary_nodes.push_back(node * mesh.dimension() + d);
727 }
731 }
732
734 {
737 return;
738 json solver_params = args["solver"]["linear"];
739 if (!solver_params.contains("Pardiso"))
740 solver_params["Pardiso"] = {};
741 solver_params["Pardiso"]["mtype"] = -2;
742 mesh_rhs_assembler_ = std::make_shared<assembler::RhsAssembler>(
749 args["space"]["advanced"]["bc_method"], solver_params,
751 }
752
754 {
756 assert(mesh_rhs_assembler_);
758 mesh_rhs_ *= -1;
759 const Eigen::MatrixXd velocity_rhs = rhs_.topRows(primary_ndof());
760 rhs_.setZero(total_ndof(), 1);
761 rhs_.topRows(primary_ndof()) = velocity_rhs;
763 }
764
773
775 {
776 return mesh_ ? mesh_displacement_space_.n_bases * mesh_->dimension() : 0;
777 }
778
780 {
781 return has_solid_ && solid_varform_ ? solid_varform_->embedding_ndof() : 0;
782 }
783
788
793
800
802 {
803 if (sol.size() == 0)
804 {
805 Eigen::MatrixXd velocity, mesh_displacement, solid_displacement;
806 rhs_assembler_->initial_solution(velocity);
807 mesh_rhs_assembler_->initial_solution(mesh_displacement);
808 if (has_solid_)
809 solid_varform_->initial_solution_for_embedding(solid_displacement, "solid_");
810 sol.setZero(total_ndof(), 1);
811 sol.topRows(primary_ndof()) = velocity.topRows(primary_ndof()).leftCols(1);
813 mesh_displacement.topRows(mesh_displacement_ndof()).leftCols(1);
814 if (has_solid_)
816 solid_displacement.topRows(solid_displacement_ndof()).leftCols(1);
817 }
818 else
819 {
820 if (sol.cols() > 1)
821 sol.conservativeResize(Eigen::NoChange, 1);
822 if (sol.rows() != total_ndof())
823 {
824 const Eigen::MatrixXd input = sol;
825 sol.setZero(total_ndof(), 1);
826 const int rows = std::min<int>(input.rows(), total_ndof());
827 if (rows > 0)
828 sol.topRows(rows) = input.topRows(rows);
829 }
830 }
831 }
832
833 void NavierStokesFSIVarForm::build_forms(Eigen::MatrixXd &sol, const double t)
834 {
835 const int dim = mesh_->dimension();
836 const Eigen::VectorXd velocity = sol.topRows(primary_ndof());
837 const Eigen::VectorXd mesh_displacement = sol.middleRows(mesh_displacement_offset(), mesh_displacement_ndof());
838 Eigen::MatrixXd solid_displacement;
839 if (has_solid_)
840 {
841 solid_displacement = sol.middleRows(solid_displacement_offset(), solid_displacement_ndof());
842 solid_varform_->init_forms_for_embedding(solid_displacement, t, "solid_");
843 }
844
849 Eigen::MatrixXd velocity_initial_velocity, mesh_initial_velocity;
850 rhs_assembler_->initial_velocity(velocity_initial_velocity);
851 mesh_rhs_assembler_->initial_velocity(mesh_initial_velocity);
852 Eigen::MatrixXd velocity_history = velocity;
853 Eigen::MatrixXd velocity_history_velocity = velocity_initial_velocity;
854 Eigen::MatrixXd velocity_history_acceleration = Eigen::MatrixXd::Zero(primary_ndof(), 1);
855 Eigen::MatrixXd mesh_history = mesh_displacement;
856 Eigen::MatrixXd mesh_history_velocity = mesh_initial_velocity;
857 Eigen::MatrixXd mesh_history_acceleration = Eigen::MatrixXd::Zero(mesh_displacement_ndof(), 1);
858 velocity_bdf->init(velocity_history, velocity_history_velocity, velocity_history_acceleration, dt);
859 mesh_bdf->init(mesh_history, mesh_history_velocity, mesh_history_acceleration, dt);
860 time_integrator = velocity_bdf;
863 time_integrator, "/checkpoint/state/primary_integrator", dt,
864 "primary", space_, dim);
866 mesh_displacement_time_integrator_, "/checkpoint/state/mesh_motion_integrator", dt,
867 "mesh_motion", mesh_displacement_space_, dim);
868 if (has_solid_ && solid_varform_->embedding_time_integrator())
870 solid_varform_->embedding_time_integrator(), "/checkpoint/state/solid_integrator", dt,
871 "solid", solid_varform_->space_, dim);
872
873 ale_form_ = std::make_shared<solver::NavierStokesFSIForm>(
878 t, dt, mesh_->is_volume(),
879 [this](const int element, const Eigen::MatrixXd &points, const double time, Eigen::MatrixXd &value) {
880 problem->rhs(*primary_assembler_, *mesh_, element, points, time, value, velocity_space_id_);
881 });
882 const int gorder = mesh_->orders().size() == 0 ? 1 : mesh_->orders().maxCoeff();
883 const QuadratureOrders velocity_samples = n_boundary_samples(
884 space_.disc_orders.maxCoeff(), space_.disc_ordersq.maxCoeff(), gorder);
885 ale_form_->set_velocity_tilde_updater(
886 [this, velocity_samples](const double time, const Eigen::VectorXd &, Eigen::VectorXd &target) {
887 Eigen::MatrixXd projected = target;
888 const std::vector<mesh::LocalBoundary> empty_neumann;
889 rhs_assembler_->set_bc(boundary_.local_boundary, boundary_.boundary_nodes, velocity_samples, empty_neumann, projected, Eigen::MatrixXd(), time);
890 target = projected.col(0);
891 });
892
893 auxiliary_form_ = std::make_shared<solver::StackedForm>();
894 const auto velocity_block = auxiliary_form_->add_block(primary_ndof());
896 const auto mesh_block = auxiliary_form_->add_block(mesh_displacement_ndof());
897 std::optional<solver::StackedForm::Block> solid_block;
898 if (has_solid_)
899 {
900 solid_block = auxiliary_form_->add_block(solid_displacement_ndof());
901 for (const auto &form : solid_varform_->embedding_forms())
902 auxiliary_form_->add(*solid_block, form);
905 }
906
907 const solver::ElementInversionCheck check = args["solver"]["advanced"]["check_inversion"];
908 mesh_elastic_form_ = std::make_shared<solver::ElasticForm>(
911 args["solver"]["advanced"]["jacobian_threshold"], check);
912 auxiliary_form_->add(mesh_block, mesh_elastic_form_);
913
914 fluid_zero_rhs_ = Eigen::MatrixXd::Zero(primary_ndof(), 1);
915 fluid_neumann_form_ = std::make_shared<solver::BodyForm>(
918 mass_assembler_->density(), false, true);
919 fluid_neumann_form_->update_quantities(t, velocity);
920 auxiliary_form_->add(velocity_block, fluid_neumann_form_);
921
922 const QuadratureOrders mesh_samples = n_boundary_samples(
924 mesh_displacement_space_.disc_ordersq.maxCoeff(), gorder);
925 mesh_body_form_ = std::make_shared<solver::BodyForm>(
929 mesh_rhs_, *mesh_rhs_assembler_, mesh_mass_assembler_->density(), false, true);
930 mesh_body_form_->update_quantities(t, mesh_displacement);
931 auxiliary_form_->add(mesh_block, mesh_body_form_);
932
934 {
935 auxiliary_form_->add_block(1);
936 average_pressure_form_ = std::make_shared<solver::NavierStokesFSIAveragePressureForm>(
942 }
943 else
944 average_pressure_form_ = nullptr;
945
946 if (has_solid_)
947 {
948 interface_form_ = std::make_shared<solver::FSIInterfaceForm>(
953 *time_integrator, *solid_varform_->embedding_time_integrator());
954 }
955 else
956 interface_form_ = nullptr;
957
959 if (interface_form_)
960 fsi_forms_.push_back(interface_form_);
963 for (const auto &form : fsi_forms_)
964 form->set_output_dir(output_path);
965 fsi_al_forms_.clear();
967 || (has_solid_ && !solid_varform_->embedding_al_forms().empty()))
968 {
969 auto stacked_al = std::make_shared<solver::StackedAugmentedLagrangianForm>();
970 const auto velocity_al = stacked_al->add_block(primary_ndof());
971 stacked_al->add_block(pressure_space_.n_bases);
972 const auto mesh_al = stacked_al->add_block(mesh_displacement_ndof());
973 std::optional<solver::StackedAugmentedLagrangianForm::Block> solid_al;
974 if (has_solid_)
975 {
976 solid_al = stacked_al->add_block(solid_displacement_ndof());
977 stacked_al->add_block(fluid_interface_multiplier_ndof());
978 stacked_al->add_block(mesh_interface_multiplier_ndof());
979 }
981 stacked_al->add_block(1);
982 if (!boundary_.boundary_nodes.empty())
983 stacked_al->add(velocity_al, std::make_shared<solver::BCLagrangianForm>(
985 velocity_samples, pure_mass_, *rhs_assembler_, 0, true, t));
987 stacked_al->add(mesh_al, std::make_shared<solver::BCLagrangianForm>(
990 mesh_samples, mesh_pure_mass_, *mesh_rhs_assembler_, 0, true, t));
991 if (has_solid_)
992 for (const auto &form : solid_varform_->embedding_al_forms())
993 stacked_al->add(*solid_al, form);
994 fsi_al_forms_.push_back(stacked_al);
995 }
996
997 fsi_problem_ = std::make_shared<solver::NLProblem>(
999 polysolve::linear::Solver::create(args["solver"]["linear"], logger()),
1001 residual_mass(
1003 has_solid_ ? solid_varform_->embedding_norm_matrix() : StiffnessMatrix(),
1004 has_solid_ ? interface_form_->fluid_multiplier_mass() : StiffnessMatrix(),
1005 has_solid_ ? interface_form_->mesh_multiplier_mass() : StiffnessMatrix(),
1007 dim, true);
1008 fsi_problem_->init(sol);
1009 fsi_problem_->update_quantities(t, sol);
1011 stats.solver_info = json::array();
1012 }
1013
1015 {
1016 const double scale = time_integrator->acceleration_scaling();
1018 fluid_neumann_form_->set_weight(scale);
1020 average_pressure_form_->set_weight(scale);
1021 }
1022
1023 void NavierStokesFSIVarForm::solve_nonlinear_step(const int step, Eigen::MatrixXd &sol)
1024 {
1025 const json nonlinear_params = residual_solver_params(args["solver"]["nonlinear"]);
1026 const json al_params = residual_solver_params(args["solver"]["augmented_lagrangian"]["nonlinear"]);
1027 std::shared_ptr<polysolve::nonlinear::Solver> nonlinear_solver = polysolve::nonlinear::Solver::create(
1028 nonlinear_params, args["solver"]["linear"], units.characteristic_length(), logger());
1029 solver::ALSolver al_solver(
1030 fsi_al_forms_, args["solver"]["augmented_lagrangian"]["initial_weight"],
1031 args["solver"]["augmented_lagrangian"]["scaling"],
1032 args["solver"]["augmented_lagrangian"]["max_weight"],
1033 args["solver"]["augmented_lagrangian"]["eta"],
1034 [this](const Eigen::VectorXd &x) {
1035 if (has_solid_)
1036 solid_varform_->update_barrier_stiffness_for_embedding(
1038 });
1039 al_solver.post_subsolve = [&](const double weight) {
1040 stats.solver_info.push_back({{"type", weight > 0 ? "al" : "rc"}, {"t", step}, {"info", nonlinear_solver->info()}});
1041 if (weight > 0)
1042 stats.solver_info.back()["weight"] = weight;
1043 save_subsolve(stats.solver_info.size(), step, sol);
1044 };
1045 if (!fsi_al_forms_.empty())
1046 al_solver.solve_al(*fsi_problem_, sol, al_params, args["solver"]["linear"], units.characteristic_length(), nonlinear_solver);
1047 al_solver.solve_reduced(*fsi_problem_, sol, nonlinear_params, args["solver"]["linear"], units.characteristic_length(), nonlinear_solver);
1048 }
1049
1051 Eigen::MatrixXd &sol,
1052 const InitialConditionOverride *initial_condition_override,
1053 const ForwardStepCallback &post_step)
1054 {
1055 assert(!initial_condition_override && "Navier-Stokes FSI does not support initial-condition overrides");
1056 assert(!post_step && "Navier-Stokes FSI does not support post-step callbacks");
1057
1058 igl::Timer timer;
1059 timer.start();
1061 build_forms(sol, t0 + dt);
1062 save_fsi_timestep(t0, 0, sol);
1063 for (int step = 1; step <= time_steps; ++step)
1064 {
1065 const double time = t0 + step * dt;
1066 logger().info("{}/{} steps, dt={}s t={}s", step, time_steps, dt, time);
1067 solve_nonlinear_step(step, sol);
1068 time_integrator->update_quantities(sol.topRows(primary_ndof()));
1069 mesh_displacement_time_integrator_->update_quantities(
1071 if (has_solid_)
1072 solid_varform_->advance_for_embedding(
1075 fsi_problem_->update_quantities(t0 + (step + 1) * dt, sol);
1076 save_fsi_timestep(time, step, sol);
1077 save_step_state(t0, dt, step, sol, time_integrator.get());
1079 }
1080 timer.stop();
1081 timings.solving_time = timer.getElapsedTime();
1082 }
1083
1085 const double time, const int step, const Eigen::MatrixXd &solution) const
1086 {
1087 if (!has_solid_)
1088 {
1089 save_timestep(time, step, t0, dt, solution);
1090 return;
1091 }
1092 if (!should_save_timestep(step) && !solid_varform_->should_save_timestep(step))
1093 return;
1095 {
1096 const int global_t = output_file_index(step);
1097 const std::string step_name = args["output"]["advanced"]["timestep_prefix"];
1098 const std::string vtm_path = resolve_output_path(fmt::format(step_name + "{:d}.vtm", global_t));
1099 const std::string pvd_path = resolve_output_path(args["output"]["paraview"]["file_name"]);
1100 const int skip_frame = args["output"]["paraview"]["skip_frame"];
1101 output_writer_->enqueue([&] {
1102 auto vtm = std::make_shared<paraviewo::VTMWriter>(time);
1104 save_timestep_to_vtm(time, step, dt, solution, *vtm, "Fluid", &writes);
1105 solid_varform_->save_timestep_for_embedding(time, step, dt,
1106 solution.middleRows(solid_displacement_offset(), solid_displacement_ndof()), *vtm, "Solid", &writes);
1107 return [this, vtm, writes = std::move(writes), global_t, step_name, vtm_path, pvd_path, skip_frame, t0 = t0, dt = dt] {
1108 for (const auto &write : writes)
1109 write();
1110 vtm->save(vtm_path);
1111 if (!pvd_path.empty())
1112 output_geometry_.save_pvd(pvd_path, [step_name](int i) { return fmt::format(step_name + "{:d}.vtm", i); }, global_t, t0, dt, skip_frame);
1113 };
1114 });
1115 return;
1116 }
1117
1118 paraviewo::VTMWriter vtm(time);
1119 const bool fluid_saved = save_timestep_to_vtm(time, step, dt, solution, vtm, "Fluid");
1120 const bool solid_saved = solid_varform_->save_timestep_for_embedding(
1121 time, step, dt,
1122 solution.middleRows(solid_displacement_offset(), solid_displacement_ndof()),
1123 vtm, "Solid");
1124 if (!fluid_saved && !solid_saved)
1125 return;
1126
1127 const int global_t = output_file_index(step);
1128 const std::string step_name = args["output"]["advanced"]["timestep_prefix"];
1129 vtm.save(resolve_output_path(fmt::format(step_name + "{:d}.vtm", global_t)));
1131 resolve_output_path(args["output"]["paraview"]["file_name"]),
1132 [step_name](int i) { return fmt::format(step_name + "{:d}.vtm", i); },
1133 global_t, t0, dt, args["output"]["paraview"]["skip_frame"].get<int>());
1134 }
1135
1136 std::vector<io::OutputField> NavierStokesFSIVarForm::output_fields(
1137 const io::OutputSample &sample,
1138 const Eigen::MatrixXd &solution,
1139 const io::OutputFieldOptions &options) const
1140 {
1141 std::vector<io::OutputField> fields = FluidVarForm::output_fields(sample, solution, options);
1142 if (!mesh_ || solution.rows() < mesh_displacement_offset() + mesh_displacement_ndof()
1143 || !options.export_field("mesh_displacement"))
1144 return fields;
1145
1146 const int dim = mesh_->dimension();
1147 const Eigen::MatrixXd mesh_displacement =
1148 solution.middleRows(mesh_displacement_offset(), mesh_displacement_ndof());
1149 const bool has_element_samples =
1150 sample.local_points.rows() > 0 && sample.local_points.rows() == sample.element_ids.size();
1151 const int output_rows = sample.points.rows() > 0
1152 ? sample.points.rows()
1153 : std::max<int>(sample.local_points.rows(), sample.node_ids.size());
1154 Eigen::MatrixXd values;
1155
1156 if (has_element_samples)
1157 {
1158 values.setZero(output_rows, dim);
1159 for (int i = 0; i < sample.local_points.rows(); ++i)
1160 {
1161 const int element = sample.element_ids(i);
1162 if (element < 0)
1163 continue;
1164 Eigen::MatrixXd local_value, local_gradient;
1166 *mesh_, dim,
1168 element, sample.local_points.row(i), mesh_displacement,
1169 local_value, local_gradient);
1170 for (int d = 0; d < dim; ++d)
1171 values(i, d) = local_value(d);
1172 }
1173 }
1174 else if (sample.node_ids.size() > 0)
1175 {
1176 values.resize(sample.node_ids.size(), dim);
1177 for (int i = 0; i < sample.node_ids.size(); ++i)
1178 {
1179 const int node = sample.node_ids(i);
1180 if (node < 0 || node * dim + dim > mesh_displacement.rows())
1181 return fields;
1182 values.row(i) = mesh_displacement.block(node * dim, 0, dim, 1).transpose();
1183 }
1184 }
1185 else
1186 {
1187 return fields;
1188 }
1189
1190 fields.push_back({"mesh_displacement", values, io::OutputField::Association::Point});
1191 return fields;
1192 }
1193} // namespace polyfem::varform
std::vector< Eigen::Triplet< double > > entries
StiffnessMatrix source
std::vector< int > multiplier_source_ids
StiffnessMatrix solid
std::vector< std::pair< int, double > > weights
int x
double characteristic_length() const
Definition Units.hpp:22
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 write_mesh(const std::string &group, const mesh::Mesh &mesh)
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_pvd(const std::string &name, const std::function< std::string(int)> &vtu_names, int time_steps, double t0, double dt, int skip_frame=1) const
save a PVD of a time dependent simulation
Definition OutData.cpp:2827
std::vector< std::function< void()> > WriteJobs
Definition OutData.hpp:31
double solving_time
time to solve
json solver_info
information of the solver, eg num iteration, time, errors, etc the informations varies depending on t...
void enqueue(const Prepare &prepare)
Wait for the pending slot, then prepare its owned frame on the caller.
2D mesh interface: the elements are the faces (polygons) and the boundary elements are the edges.
Definition Mesh2D.hpp:18
3D mesh interface: the elements are the cells (tetrahedra, hexahedra, prisms, pyramids or general pol...
Definition Mesh3D.hpp:22
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:77
virtual bool is_conforming() const =0
if the mesh is conforming
virtual bool is_volume() const =0
checks if mesh is volume
virtual std::unique_ptr< Mesh > copy() const =0
Create a copy of the mesh.
std::vector< MeshWithID > split() const
Split the mesh according to its per-element geometry IDs.
Definition Mesh.cpp:29
int dimension() const
utily for dimension
Definition Mesh.hpp:171
std::function< void(const double)> post_subsolve
Definition ALSolver.hpp:53
static std::shared_ptr< BDF > construct_bdf_integrator(const json &params, DynamicOrder dynamic_order=DynamicOrder::Second)
Construct a BDF integrator for algorithms using BDF-specific operations.
static void quadrature_for_quad_edge(int index, int order, const int gid, const mesh::Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights)
static void quadrature_for_tri_edge(int index, int order, const int gid, const mesh::Mesh &mesh, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights)
static Eigen::Matrix2d tri_local_node_coordinates_from_edge(int le)
A finite-element space for one scalar- or vector-valued field.
Definition FESpace.hpp:59
const std::vector< basis::ElementBases > & geometry_basis_list() const
Definition FESpace.hpp:119
std::shared_ptr< std::vector< basis::ElementBases > > bases
Per-element basis data.
Definition FESpace.hpp:68
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
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
void assemble_rhs(const mesh::Mesh &mesh) override
assembler::AssemblyValsCache pressure_ass_vals_cache_
void assemble_mass_mat(const mesh::Mesh &mesh, const json &args) override
void build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args) override
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::shared_ptr< time_integrator::ImplicitTimeIntegrator > time_integrator
assembler::AssemblyValsCache ass_vals_cache_
std::shared_ptr< assembler::RhsAssembler > rhs_assembler_
VarFormBoundaryState boundary_
std::shared_ptr< assembler::Mass > mass_assembler_
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.
void load_mesh(const mesh::Mesh &mesh, const json &args) override
std::shared_ptr< NonlinearElasticTransientVarForm > solid_varform_
void prepare_fsi_initial_solution(Eigen::MatrixXd &sol) const
std::shared_ptr< time_integrator::ImplicitTimeIntegrator > mesh_displacement_time_integrator_
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.
std::shared_ptr< solver::NLProblem > fsi_problem_
std::shared_ptr< assembler::Assembler > mesh_elastic_assembler_
std::shared_ptr< assembler::Problem > mesh_displacement_problem_
std::shared_ptr< assembler::HRZMass > mesh_pure_mass_assembler_
std::vector< std::shared_ptr< solver::Form > > fsi_forms_
void serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const override
std::vector< std::shared_ptr< assembler::MultiSpacesNLAssembler > > ale_assemblers_
void assemble_mass_mat(const mesh::Mesh &mesh, const json &args) override
void load_mesh(const mesh::Mesh &mesh, const json &args) override
std::shared_ptr< solver::NavierStokesFSIForm > ale_form_
std::shared_ptr< solver::FSIInterfaceForm > interface_form_
void solve_problem(Eigen::MatrixXd &sol, const InitialConditionOverride *initial_condition_override, const ForwardStepCallback &post_step) override
void build_forms(Eigen::MatrixXd &sol, double t)
std::shared_ptr< solver::BodyForm > mesh_body_form_
std::shared_ptr< assembler::RhsAssembler > mesh_rhs_assembler_
void save_fsi_timestep(double time, int step, const Eigen::MatrixXd &solution) const
std::shared_ptr< solver::ElasticForm > mesh_elastic_form_
std::vector< std::pair< mesh::Navigation::Index, mesh::Navigation::Index > > interface_2d_
std::vector< std::pair< mesh::Navigation3D::Index, mesh::Navigation3D::Index > > interface_3d_
void build_basis(mesh::Mesh &mesh, bool iso_parametric, const json &args) override
std::shared_ptr< solver::BodyForm > fluid_neumann_form_
void deserialize_checkpoint(const io::CheckpointReader &reader, Eigen::MatrixXd &solution) override
std::vector< std::shared_ptr< solver::AugmentedLagrangianForm > > fsi_al_forms_
assembler::AssemblyValsCache mesh_displacement_mass_ass_vals_cache_
void solve_nonlinear_step(int step, Eigen::MatrixXd &sol)
std::shared_ptr< assembler::Mass > mesh_mass_assembler_
std::shared_ptr< solver::StackedForm > auxiliary_form_
void assemble_rhs(const mesh::Mesh &mesh) override
assembler::AssemblyValsCache mesh_displacement_pure_mass_ass_vals_cache_
std::shared_ptr< solver::NavierStokesFSIAveragePressureForm > average_pressure_form_
assembler::AssemblyValsCache mesh_displacement_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.
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
int output_file_index(const int t) const
Definition VarForm.cpp:1205
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
void save_step_state(const double t0, const double dt, const int t, const Eigen::MatrixXd &solution, const time_integrator::ImplicitTimeIntegrator *time_integrator) const
Definition VarForm.cpp:905
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::OutputWriter * output_writer_
Definition VarForm.hpp:300
void notify_time_step(const int t, const int time_steps, const double t0, const double dt) const
Definition VarForm.cpp:1199
io::OutGeometryData output_geometry_
Definition VarForm.hpp:298
void init_child_varform(VarForm &child, const std::string &formulation, const Units &units, const json &args, const std::string &out_path) const
Definition VarForm.cpp:261
bool should_save_timestep(int step) const
Whether the output index and frame selection include this timestep.
Definition VarForm.cpp:1152
void save_subsolve(const int i, const int t, const Eigen::MatrixXd &solution) const
Definition VarForm.cpp:1180
void restore_checkpoint_integrator(const std::shared_ptr< time_integrator::ImplicitTimeIntegrator > &integrator, const std::string &group, double dt, const std::string &ordering, const FESpace &space, int block_size) const
Definition VarForm.cpp:959
virtual void serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const
Definition VarForm.cpp:939
bool save_timestep_to_vtm(const double time, const int t, const double dt, const Eigen::MatrixXd &solution, paraviewo::VTMWriter &vtm, const std::string &block_prefix, io::OutGeometryData::WriteJobs *writes=nullptr) const
Definition VarForm.cpp:1159
QuadratureOrders n_boundary_samples(const int discr_order, const int discr_orderq, const int gdiscr_order) const
Definition VarForm.cpp:187
std::optional< std::reference_wrapper< const io::CheckpointReader > > checkpoint_reader_
Definition VarForm.hpp:292
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
void save_timestep(const double time, const int t, const double t0, const double dt, const Eigen::MatrixXd &solution) const
Definition VarForm.cpp:1089
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
int norm
Definition p_bases.py:265
std::vector< std::pair< Navigation::Index, Navigation::Index > > compute_mesh_interface(const Mesh2D &first, const Mesh2D &second)
Pair coincident boundary edges, including nonconforming leader/follower edges.
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
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
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