PolyFEM
Loading...
Searching...
No Matches
FluidVarForm.cpp
Go to the documentation of this file.
1#include "FluidVarForm.hpp"
2
28
29#include <polysolve/linear/FEMSolver.hpp>
30#include <polysolve/nonlinear/Solver.hpp>
31
32namespace polyfem::varform
33{
34 using namespace varform::internal;
35
38 const Eigen::MatrixXd &solution,
39 const io::CheckpointMetadata &metadata) const
40 {
41 VarForm::serialize_checkpoint(writer, solution, metadata);
42 write_checkpoint_ordering(writer, "primary", space_);
43 write_checkpoint_ordering(writer, "pressure", pressure_space_);
44 }
45
47 const io::CheckpointReader &reader,
48 Eigen::MatrixXd &solution)
49 {
50 VarForm::deserialize_checkpoint(reader, solution);
53 reader, "primary", space_,
54 mesh_->dimension(), 0, solution);
56 reader, "pressure", pressure_space_,
57 1, primary_ndof(), solution);
58 }
59
61 {
63 space_.reset();
73 rhs_assembler_ = nullptr;
74 mass_.resize(0, 0);
75 pure_mass_.resize(0, 0);
76 avg_mass_ = 0;
77 rhs_.resize(0, 0);
78 primary_assembler_ = nullptr;
79 mass_assembler_ = nullptr;
80 pure_mass_assembler_ = nullptr;
81 mixed_assembler_ = nullptr;
82 pressure_assembler_ = nullptr;
83 use_avg_pressure = true;
84 t0 = 0;
85 time_steps = 0;
86 dt = 0;
87 time_integrator = nullptr;
88 }
89
90 void FluidVarForm::init(const std::string &formulation, const Units &units, const json &args, const std::string &out_path)
91 {
92 VarForm::init(formulation, units, args, out_path);
93 const bool is_time_dependent = args.contains("time") && !args["time"].is_null();
94 const json &discr_orders = args.at("space").at("discr_order");
95
96 const json &materials = args.at("materials");
97 if (materials.is_array() && materials.empty())
98 log_and_throw_error("Fluid formulations require at least one material.");
99 const json &first_material = materials.is_array() ? materials.at(0) : materials;
100 velocity_space_id_ = first_material.at("velocity_space_id").get<int>();
101 pressure_space_id_ = first_material.at("pressure_space_id").get<int>();
103 log_and_throw_error("Fluid velocity and pressure must use different FE space IDs.");
104
105 if (discr_orders.is_array())
106 {
107 bool has_velocity_space = false;
108 bool has_pressure_space = false;
109 for (const json &entry : discr_orders)
110 {
111 const int fe_space_id = entry.at("fe_space").get<int>();
112 has_velocity_space |= fe_space_id == velocity_space_id_;
113 has_pressure_space |= fe_space_id == pressure_space_id_;
114 }
115 if (!has_velocity_space || !has_pressure_space)
116 log_and_throw_error("Fluid discretization-order lists must explicitly name the velocity and pressure FE spaces.");
117 }
118
119 if (materials.is_array())
120 {
121 for (const json &material : materials)
122 {
123 if (material.at("velocity_space_id").get<int>() != velocity_space_id_
124 || material.at("pressure_space_id").get<int>() != pressure_space_id_)
125 log_and_throw_error("All fluid materials must use the same velocity and pressure FE space IDs.");
126 }
127 }
128
130 mass_assembler_ = std::make_shared<assembler::Mass>();
131 pure_mass_assembler_ = std::make_shared<assembler::HRZMass>();
134
135 if (!args.contains("preset_problem"))
136 {
137 problem = std::make_shared<assembler::GenericTensorProblem>("GenericTensor");
138 problem->clear();
139
140 json tmp;
141 tmp["is_time_dependent"] = is_time_dependent;
142 problem->set_parameters(tmp, resources_);
143
144 auto bc = args["boundary_conditions"];
145 problem->set_parameters(bc, resources_);
146 problem->set_parameters(args["initial_conditions"], resources_);
147 problem->set_parameters(args["output"], resources_);
148 }
149 else
150 {
151 if (args["preset_problem"]["type"] == "Kernel")
152 {
153 problem = std::make_shared<problem::KernelProblem>("Kernel", *primary_assembler_);
154 problem->clear();
155 }
156 else
157 {
158 problem = problem::ProblemFactory::factory().get_problem(args["preset_problem"]["type"]);
159 problem->clear();
160 }
161 problem->set_parameters(args["preset_problem"], resources_);
162 }
163
164 problem->set_units(*primary_assembler_, units);
165
166 t0 = is_time_dependent ? args["time"]["t0"].get<double>() : 0.0;
167 time_steps = is_time_dependent ? args["time"]["time_steps"].get<int>() : 0;
168 dt = is_time_dependent ? args["time"]["dt"].get<double>() : 0.0;
169
170 assert(primary_assembler_->is_fluid());
171 }
172
173 void FluidVarForm::save_json(const Eigen::MatrixXd &solution, std::ostream &out) const
174 {
175 if (!mesh_)
176 {
177 logger().error("Load the mesh first!");
178 return;
179 }
180 if (solution.size() <= 0)
181 {
182 logger().error("Solve the problem first!");
183 return;
184 }
185
186 logger().info("Saving json...");
187 const int primary_size = primary_ndof();
188 const Eigen::MatrixXd stats_solution =
189 solution.rows() >= primary_size
190 ? solution.topRows(primary_size).eval()
191 : solution;
192
193 nlohmann::json j;
196 stats_solution, *mesh_, space_.disc_orders, space_.disc_ordersq, *problem,
198 args["output"]["advanced"]["sol_at_node"], j);
199 out << j.dump(4) << std::endl;
200 }
201
203 {
204 Eigen::VectorXi output_orders = space_.disc_orders;
205 if (mesh_ && space_.disc_ordersq.size() == space_.disc_orders.size())
206 {
207 for (int e = 0; e < output_orders.size(); ++e)
208 {
209 if (mesh_->is_prism(e))
210 output_orders(e) = std::max(space_.disc_orders(e), space_.disc_ordersq(e));
211 }
212 }
213
214 return {
215 mesh_.get(),
217 output_orders,
218 &space_.polys,
221 nullptr,
222 nullptr,
225 }
226
227 io::OutStatsData FluidVarForm::compute_errors(const Eigen::MatrixXd &solution)
228 {
229 if (!args["output"]["advanced"]["compute_error"])
230 return stats;
231
232 double tend = 0;
233 if (!args["time"].is_null())
234 tend = args["time"]["tend"];
235
236 Eigen::MatrixXd velocity, pressure;
237 split_solution(solution, velocity, pressure);
239 return stats;
240 }
241
242 void FluidVarForm::export_data(const Eigen::MatrixXd &solution) const
243 {
244 const io::OutputSpace space = output_space();
245 if (!space.mesh)
246 {
247 logger().error("Load the mesh first!");
248 return;
249 }
250 if (solution.size() <= 0)
251 {
252 logger().error("Solve the problem first!");
253 return;
254 }
255
257
258 const std::string vis_mesh_path = resolve_output_path(args["output"]["paraview"]["file_name"]);
259 const bool has_time = args.contains("time") && !args["time"].is_null();
260 double tend = has_time ? args["time"]["tend"].get<double>() : 1.0;
261 double dt = 1;
262 if (has_time)
263 dt = args["time"]["dt"];
264
265 const auto opts = export_options(space);
267 space,
268 output_field_function(solution, opts),
269 has_time,
270 tend, dt,
271 opts,
272 vis_mesh_path);
273
274 Eigen::MatrixXd velocity, pressure;
275 split_solution(solution, velocity, pressure);
276
277 const std::string solution_path = resolve_output_path(args["output"]["data"]["solution"]);
278 if (!solution_path.empty())
279 {
280 const int primary_rows = std::min<int>(velocity.rows(), primary_ndof());
281 const Eigen::MatrixXd primary_solution = velocity.topRows(primary_rows);
282 if (opts.reorder_output && space_.space_in_node_to_node.size() > 0)
283 {
284 const Eigen::MatrixXd nodal_solution = utils::unflatten(primary_solution, mesh_->dimension());
285 Eigen::MatrixXd reordered = Eigen::MatrixXd::Zero(nodal_solution.rows(), nodal_solution.cols());
286 for (int input_node = 0; input_node < space_.space_in_node_to_node.size(); ++input_node)
287 {
288 const int node = space_.space_in_node_to_node(input_node);
289 if (node >= 0 && node < nodal_solution.rows() && input_node < reordered.rows())
290 reordered.row(input_node) = nodal_solution.row(node);
291 }
292 io::write_matrix(solution_path, reordered);
293 }
294 else
295 {
296 io::write_matrix(solution_path, primary_solution);
297 }
298 }
299
300 const std::string nodes_path = resolve_output_path(args["output"]["data"]["nodes"]);
301 if (!nodes_path.empty())
302 {
303 Eigen::MatrixXd nodes = Eigen::MatrixXd::Zero(space_.n_bases, mesh_->dimension());
304 for (const basis::ElementBases &element_bases : space_.basis_list())
305 for (const basis::Basis &basis : element_bases.bases)
306 for (const auto &global : basis.global())
307 nodes.row(global.index) = global.node;
308 io::write_matrix(nodes_path, nodes);
309 }
310
311 const std::string stress_path = resolve_output_path(args["output"]["data"]["stress_mat"]);
312 const std::string mises_path = resolve_output_path(args["output"]["data"]["mises"]);
313 if ((!stress_path.empty() || !mises_path.empty()) && primary_assembler_)
314 {
315 Eigen::MatrixXd stress;
316 Eigen::VectorXd mises;
320 stress, mises);
321 if (!stress_path.empty())
322 io::write_matrix(stress_path, stress);
323 if (!mises_path.empty())
324 io::write_matrix(mises_path, mises);
325 }
326 }
327
328 void FluidVarForm::load_mesh(const mesh::Mesh &mesh, const json &args)
329 {
332 pure_mass_assembler_->set_size(mass_assembler_->size());
333 problem->init(mesh);
334
336 mixed_assembler_->set_size(mesh.dimension());
339 }
340
342 {
343 return mesh_ ? space_.n_bases * mesh_->dimension() : 0;
344 }
345
347 {
349 }
350
352 {
354 }
355
357 {
358 json rhs_solver_params = args["solver"]["linear"];
359 if (!rhs_solver_params.contains("Pardiso"))
360 rhs_solver_params["Pardiso"] = {};
361 rhs_solver_params["Pardiso"]["mtype"] = -2;
362
363 rhs_assembler_ = std::make_shared<assembler::RhsAssembler>(
364 *primary_assembler_, *mesh_, nullptr, // no obstacle for the rhs assembler
368 args["space"]["advanced"]["bc_method"],
369 rhs_solver_params,
371 }
372
373 void FluidVarForm::build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args)
374 {
375 assert(problem);
376 assert(primary_assembler_);
377 assert(mass_assembler_);
378 assert(pure_mass_assembler_);
379
380 Eigen::VectorXi space_disc_orders, space_disc_ordersq;
381 assign_discr_orders(args["space"], velocity_space_id_, mesh, space_disc_orders, space_disc_ordersq);
382
383 if (args["space"]["use_p_ref"])
384 {
386 mesh,
387 args["space"]["advanced"]["B"],
388 args["space"]["advanced"]["h1_formula"],
389 args["space"]["discr_order"],
390 args["space"]["advanced"]["discr_order_max"],
391 stats,
392 space_disc_orders);
393
394 logger().info("min p: {} max p: {}", space_disc_orders.minCoeff(), space_disc_orders.maxCoeff());
395 }
396
398 mesh,
399 iso_parametric,
400 space_disc_orders,
401 space_disc_ordersq,
402 args["space"]["basis_type"],
403 args["space"]["poly_basis_type"],
405 mesh.dimension(),
406 args["space"]["advanced"]["quadrature_order"],
407 args["space"]["advanced"]["mass_quadrature_order"],
408 args["space"]["advanced"]["use_corner_quadrature"],
409 args["space"]["advanced"]["n_harmonic_samples"],
410 args["space"]["advanced"]["integral_constraints"],
411 space_,
412 boundary_);
413
414 problem->update_nodes(space_.space_in_node_to_node);
416
417 const auto &current_bases = space_.geometry_basis_list();
418 if (args["space"]["advanced"]["count_flipped_els"])
419 stats.count_flipped_elements(mesh, current_bases);
420
421 const int n_samples = 10;
422 stats.compute_mesh_size(mesh, current_bases, n_samples, args["output"]["advanced"]["curved_mesh_size"]);
423
424 logger().info("flipped elements {}", stats.n_flipped);
425 logger().info("h: {}", stats.mesh_size);
426
427 if (space_.disc_orders.maxCoeff() != space_.disc_orders.minCoeff())
428 log_and_throw_error("p refinement not supported in mixed formulation!");
429 if (!space_.poly_edge_to_data.empty())
430 log_and_throw_error("Polygonal bases are not supported in mixed formulations!");
431
432 if (space_.n_bases <= args["solver"]["advanced"]["cache_size"])
433 {
434 igl::Timer cache_timer;
435 cache_timer.start();
436 logger().info("Building cache...");
437 ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases);
438 mass_ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases, true);
439 pure_mass_ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases, true);
440 logger().info(" took {}s", cache_timer.getElapsedTime());
441 }
442 else
443 {
447 }
448
449 const auto &all_boundary = boundary_.total_local_boundary;
450 const int prev_bases = space_.n_bases;
451 const int prev_b_size = int(all_boundary.size());
452 const bool use_corner_quadrature = args["space"]["advanced"]["use_corner_quadrature"];
453 const int quadrature_order = args["space"]["advanced"]["quadrature_order"].get<int>();
454 const int mass_quadrature_order = args["space"]["advanced"]["mass_quadrature_order"].get<int>();
455 Eigen::VectorXi pressure_disc_orders, pressure_disc_ordersq;
456 assign_discr_orders(args["space"], pressure_space_id_, mesh, pressure_disc_orders, pressure_disc_ordersq);
457 // to avoid serendipity
458 const std::string pressure_basis_type = args["space"]["basis_type"].get<std::string>() == "Bernstein" ? "Bernstein" : "Lagrange";
460 mesh,
461 /*iso_parametric=*/true,
462 pressure_disc_orders,
463 pressure_disc_ordersq,
464 pressure_basis_type,
465 args["space"]["poly_basis_type"],
467 /*value_dim=*/1,
468 quadrature_order,
469 mass_quadrature_order,
470 use_corner_quadrature,
471 args["space"]["advanced"]["n_harmonic_samples"],
472 args["space"]["advanced"]["integral_constraints"],
476
477 assert(space_.basis_list().size() == pressure_space_.basis_list().size());
478 for (int i = 0; i < int(pressure_space_.basis_list().size()); ++i)
479 {
481 space_.basis_list()[i].compute_quadrature(b_quad);
482 (*pressure_space_.bases)[i].set_quadrature([b_quad](quadrature::Quadrature &quad) { quad = b_quad; });
483 }
484
486 for (const auto &lb : all_boundary)
487 boundary_.local_boundary.emplace_back(lb);
489
490 problem->setup_bc(
491 mesh, space_.n_bases,
501
504
505 const bool has_neumann = !boundary_.local_neumann_boundary.empty() || int(boundary_.local_boundary.size()) < prev_b_size;
506 use_avg_pressure = !has_neumann;
507
508 for (int i = prev_bases; i < space_.n_bases; ++i)
509 for (int d = 0; d < mesh.dimension(); ++d)
510 boundary_.boundary_nodes.push_back(i * mesh.dimension() + d);
511
513
514 if (space_.n_bases <= args["solver"]["advanced"]["cache_size"])
516 else
518
520
521 logger().info("n pressure bases: {}", pressure_space_.n_bases);
522 }
523
525 {
527
528 igl::Timer timer;
529 json p_params = {};
530 p_params["formulation"] = primary_assembler_->name();
531 {
532 RowVectorNd min, max, delta;
533 mesh.bounding_box(min, max);
534 delta = (max - min) / 2. + min;
535 if (mesh.is_volume())
536 p_params["bbox_center"] = {delta(0), delta(1), delta(2)};
537 else
538 p_params["bbox_center"] = {delta(0), delta(1)};
539 }
540 problem->set_parameters(p_params, resources_);
541
542 rhs_.resize(0, 0);
543
544 timer.start();
545 logger().info("Assigning rhs...");
546
547 assert(rhs_assembler_ != nullptr);
548 rhs_assembler_->assemble(mass_assembler_->density(), rhs_);
549 rhs_ *= -1;
550
551 timings.assigning_rhs_time = timer.getElapsedTime();
552 logger().info(" took {}s", timings.assigning_rhs_time);
553
554 const int prev_size = rhs_.rows();
555 rhs_.conservativeResize(prev_size + pressure_block_size(), rhs_.cols());
556 rhs_.bottomRows(pressure_block_size()).setZero();
557 }
558
559 void FluidVarForm::assemble_mass_mat(const mesh::Mesh &mesh, const json &args)
560 {
561 if (!problem->is_time_dependent())
562 {
563 avg_mass_ = 1;
565 if (!primary_assembler_->is_linear())
567 return;
568 }
569
570 mass_.resize(0, 0);
571 igl::Timer timer;
572 timer.start();
573 logger().info("Assembling mass mat...");
574
575 StiffnessMatrix velocity_mass;
577 if (!primary_assembler_->is_linear())
579
580 std::vector<Eigen::Triplet<double>> blocks;
581 blocks.reserve(velocity_mass.nonZeros());
582 for (int k = 0; k < velocity_mass.outerSize(); ++k)
583 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
584 blocks.emplace_back(it.row(), it.col(), it.value());
585
586 mass_.resize(primary_ndof(), primary_ndof());
587 mass_.setFromTriplets(blocks.begin(), blocks.end());
588 mass_.makeCompressed();
589
590 avg_mass_ = 0;
591 for (int k = 0; k < velocity_mass.outerSize(); ++k)
592 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
593 {
594 assert(it.col() == k);
595 avg_mass_ += it.value();
596 }
597 avg_mass_ /= std::max(1, int(velocity_mass.rows()));
598 logger().info("average mass {}", avg_mass_);
599
600 if (args["solver"]["advanced"]["lump_mass_matrix"])
602
603 timer.stop();
604 timings.assembling_mass_mat_time = timer.getElapsedTime();
605 logger().info(" took {}s", timings.assembling_mass_mat_time);
606
607 stats.nn_zero = mass_.nonZeros();
608 stats.num_dofs = mass_.rows();
609 stats.mat_size = (long long)mass_.rows() * (long long)mass_.cols();
610 logger().info("sparsity: {}/{}", stats.nn_zero, stats.mat_size);
611 }
612
613 void FluidVarForm::prepare_initial_solution(Eigen::MatrixXd &sol) const
614 {
615 if (sol.size() <= 0)
616 {
617 assert(rhs_assembler_ != nullptr);
618 if (problem->is_time_dependent())
619 rhs_assembler_->initial_solution(sol);
620 else
621 {
622 sol.resize(rhs_.size(), 1);
623 sol.setZero();
624 }
625 }
626 if (sol.cols() > 1)
627 sol.conservativeResize(Eigen::NoChange, 1);
628 sol.conservativeResize(stacked_ndof(), sol.cols());
629 sol.bottomRows(pressure_block_size()).setZero();
630 }
631
632 void FluidVarForm::split_solution(const Eigen::MatrixXd &stacked, Eigen::MatrixXd &primary, Eigen::MatrixXd &pressure) const
633 {
634 const int cols = std::max(1, int(stacked.cols()));
635 primary.setZero(primary_ndof(), cols);
636 pressure.setZero(pressure_space_.n_bases, cols);
637
638 const int primary_rows = std::min(primary_ndof(), int(stacked.rows()));
639 if (primary_rows > 0)
640 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
641
642 if (stacked.rows() > primary_ndof())
643 {
644 const int pressure_rows = std::min(pressure_space_.n_bases, int(stacked.rows()) - primary_ndof());
645 if (pressure_rows > 0)
646 pressure.topRows(pressure_rows) = stacked.middleRows(primary_ndof(), pressure_rows);
647 }
648 }
649
651 {
652 igl::Timer timer;
653 timer.start();
654 logger().info("Assembling stiffness mat...");
655
656 StiffnessMatrix velocity_stiffness, mixed_stiffness, pressure_stiffness;
657 primary_assembler_->assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), space_.geometry_basis_list(), ass_vals_cache_, 0, velocity_stiffness);
660
663 velocity_stiffness, mixed_stiffness, pressure_stiffness, stiffness);
664
665 timer.stop();
666 timings.assembling_stiffness_mat_time = timer.getElapsedTime();
667 logger().info(" took {}s", timings.assembling_stiffness_mat_time);
668
669 stats.nn_zero = stiffness.nonZeros();
670 stats.num_dofs = stiffness.rows();
671 stats.mat_size = (long long)stiffness.rows() * (long long)stiffness.cols();
672 logger().info("sparsity: {}/{}", stats.nn_zero, stats.mat_size);
673
674 write_matrix_market(args, stiffness);
675 }
676
678 const std::unique_ptr<polysolve::linear::Solver> &solver,
680 Eigen::VectorXd &b,
681 const bool compute_spectrum,
682 Eigen::MatrixXd &sol)
683 {
684 Eigen::VectorXd x;
685 stats.spectrum = dirichlet_solve(
686 *solver,
687 A,
688 b,
690 x,
691 primary_ndof(),
692 args["output"]["data"]["stiffness_mat"],
693 compute_spectrum,
694 /*is_fluid=*/true,
696
697 sol = x;
698 solver->get_info(stats.solver_info);
699
700 const double error = (A * x - b).norm();
701 if (error > 1e-4)
702 logger().error("Solver error: {}", error);
703 else
704 logger().debug("Solver error: {}", error);
705 }
706
707 std::vector<io::OutputField> FluidVarForm::output_fields(
708 const io::OutputSample &sample,
709 const Eigen::MatrixXd &solution,
710 const io::OutputFieldOptions &options) const
711 {
712 std::vector<io::OutputField> fields;
713 if (!mesh_ || !problem || solution.size() <= 0)
714 return fields;
715
716 Eigen::MatrixXd velocity, pressure;
717 split_solution(solution, velocity, pressure);
718
719 const int field_dim = mesh_->dimension();
720 const bool has_element_samples = sample.local_points.rows() > 0 && sample.local_points.rows() == sample.element_ids.size();
721 const int output_rows = sample.points.rows() > 0 ? sample.points.rows() : std::max<int>(sample.local_points.rows(), sample.node_ids.size());
722 const bool export_solution_gradient =
723 !options.fields.empty() && options.export_field("solution_gradient");
724 const bool export_pressure_gradient =
725 !options.fields.empty() && options.export_field("pressure_gradient");
726
727 const auto resize_to_output_rows = [&](Eigen::MatrixXd &values) {
728 if (output_rows <= values.rows())
729 return;
730
731 const int previous_rows = values.rows();
732 values.conservativeResize(output_rows, values.cols());
733 values.bottomRows(output_rows - previous_rows).setZero();
734 };
735
736 const auto sample_vector_field = [&](const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients = nullptr) -> bool {
737 if (dof_values.size() <= 0 || field_dim <= 0)
738 return false;
739
740 if (has_element_samples)
741 {
742 values.resize(sample.local_points.rows(), field_dim);
743 if (gradients)
744 gradients->resize(sample.local_points.rows(), field_dim * mesh_->dimension());
745 for (int i = 0; i < sample.local_points.rows(); ++i)
746 {
747 const int element_id = sample.element_ids(i);
748 if (element_id < 0)
749 {
750 values.row(i).setZero();
751 if (gradients)
752 gradients->row(i).setZero();
753 continue;
754 }
755
756 Eigen::MatrixXd local_sol, local_grad;
759 element_id, sample.local_points.row(i), dof_values, local_sol, local_grad);
760
761 for (int d = 0; d < field_dim; ++d)
762 values(i, d) = local_sol(d);
763 if (gradients)
764 gradients->row(i) = local_grad;
765 }
766
767 resize_to_output_rows(values);
768 if (gradients)
769 resize_to_output_rows(*gradients);
770 return true;
771 }
772
773 if (sample.node_ids.size() > 0)
774 {
775 values.resize(sample.node_ids.size(), field_dim);
776 for (int i = 0; i < sample.node_ids.size(); ++i)
777 {
778 const int node_id = sample.node_ids(i);
779 for (int d = 0; d < field_dim; ++d)
780 {
781 const int dof = node_id * field_dim + d;
782 if (dof < 0 || dof >= dof_values.rows())
783 return false;
784 values(i, d) = dof_values(dof);
785 }
786 }
787 return sample.points.rows() == 0 || sample.points.rows() == values.rows();
788 }
789
790 return false;
791 };
792
793 Eigen::MatrixXd velocity_values, velocity_gradients;
794 const bool sampled_velocity = sample_vector_field(
795 velocity, velocity_values,
796 export_solution_gradient ? &velocity_gradients : nullptr);
797 if (sampled_velocity && options.export_field("velocity"))
798 fields.push_back({"velocity", velocity_values, io::OutputField::Association::Point});
799 // if (sampled_velocity && options.export_field("solution"))
800 // fields.push_back({"solution", velocity_values, io::OutputField::Association::Point});
801 if (sampled_velocity && export_solution_gradient)
802 fields.push_back({"solution_gradient", velocity_gradients, io::OutputField::Association::Point});
803
804 if (mesh_ && (options.export_field("pressure") || export_pressure_gradient))
805 {
806 Eigen::MatrixXd values, gradients;
808 *mesh_, pressure_space_.basis_list(), space_.geometry_basis_list(), sample, pressure, values,
809 export_pressure_gradient ? &gradients : nullptr))
810 {
811 if (options.export_field("pressure"))
812 fields.push_back({"pressure", values, io::OutputField::Association::Point});
813 if (export_pressure_gradient)
814 fields.push_back({"pressure_gradient", gradients, io::OutputField::Association::Point});
815 }
816 }
817
818 const auto &paraview_options = args["output"]["paraview"]["options"];
819 if (paraview_options["material"] && has_element_samples)
820 {
821 const auto &params = primary_assembler_->parameters();
822 std::map<std::string, Eigen::MatrixXd> param_values;
823 for (const auto &[p, _] : params)
824 param_values[p].setZero(output_rows, 1);
825
826 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
827 const auto &density = mass_assembler_->density();
828 for (int i = 0; i < sample.local_points.rows(); ++i)
829 {
830 const int element_id = sample.element_ids(i);
831 if (element_id < 0)
832 continue;
833
834 for (const auto &[p, func] : params)
835 param_values.at(p)(i) = func(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
836 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
837 }
838
839 for (const auto &[name, values] : param_values)
840 if (options.export_field(name))
841 fields.push_back({name, values, io::OutputField::Association::Point});
842 if (options.export_field("rho"))
843 fields.push_back({"rho", rhos, io::OutputField::Association::Point});
844 }
845
846 if (paraview_options["body_ids"] && options.export_field("body_ids") && has_element_samples)
847 {
848 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
849 for (int i = 0; i < sample.element_ids.size(); ++i)
850 {
851 const int element_id = sample.element_ids(i);
852 if (element_id >= 0)
853 ids(i) = mesh_->get_body_id(element_id);
854 }
855 fields.push_back({"body_ids", ids, io::OutputField::Association::Point});
856 }
857
858 return fields;
859 }
860
861 void StokesVarForm::solve_static_linear(Eigen::MatrixXd &sol)
862 {
863 auto solver = polysolve::linear::Solver::create(args["solver"]["linear"], logger());
864 logger().info("{}...", solver->name());
865
866 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
867 const QuadratureOrders boundary_samples = n_boundary_samples(space_.disc_orders.maxCoeff(), space_.disc_ordersq.maxCoeff(), gdiscr_order);
868 rhs_assembler_->set_bc(
869 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples,
870 boundary_.local_neumann_boundary, rhs_);
871
873 build_stiffness_mat(A);
874 Eigen::VectorXd b = rhs_;
875 solve_linear_system(solver, A, b, args["output"]["advanced"]["spectrum"], sol);
876 }
877
878 void StokesVarForm::solve_transient_linear(Eigen::MatrixXd &sol)
879 {
880 auto solver = polysolve::linear::Solver::create(args["solver"]["linear"], logger());
881 logger().info("{}...", solver->name());
882
883 Eigen::MatrixXd velocity, pressure;
884 split_solution(sol, velocity, pressure);
885
887 args["time"]["integrator"]);
888 bdf->init(
889 velocity,
890 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
891 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
892 dt);
893 time_integrator = bdf;
894 restore_checkpoint_integrator(
895 time_integrator, "/checkpoint/state/primary_integrator", dt,
896 "primary", space_, mesh_->dimension());
897
898 save_timestep(t0, 0, t0, dt, sol);
899
900 Eigen::MatrixXd current_rhs = rhs_;
901 StiffnessMatrix stiffness, expanded_mass;
902 build_stiffness_mat(stiffness);
903 expand_primary_matrix(stacked_ndof(), mass_, expanded_mass);
904 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
905 const QuadratureOrders boundary_samples = n_boundary_samples(space_.disc_orders.maxCoeff(), space_.disc_ordersq.maxCoeff(), gdiscr_order);
906
907 for (int t = 1; t <= time_steps; ++t)
908 {
909 const double time = t0 + t * dt;
910 rhs_assembler_->compute_energy_grad(
911 boundary_.local_boundary, boundary_.boundary_nodes, mass_assembler_->density(), boundary_samples, boundary_.local_neumann_boundary, rhs_, time,
912 current_rhs);
913 rhs_assembler_->set_bc(
914 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, current_rhs, velocity, time);
915
916 if (current_rhs.rows() != stacked_ndof())
917 {
918 const int old_rows = current_rhs.rows();
919 current_rhs.conservativeResize(stacked_ndof(), current_rhs.cols());
920 if (stacked_ndof() > old_rows)
921 current_rhs.bottomRows(stacked_ndof() - old_rows).setZero();
922 }
923 current_rhs.bottomRows(pressure_block_size()).setZero();
924
925 StiffnessMatrix A = expanded_mass / bdf->beta_dt() + stiffness;
926 Eigen::VectorXd b = Eigen::VectorXd::Zero(stacked_ndof());
927 b.head(primary_ndof()) = (mass_ * bdf->weighted_sum_x_prevs()) / bdf->beta_dt();
928 for (int i : boundary_.boundary_nodes)
929 b[i] = 0;
930 b += current_rhs;
931
932 solve_linear_system(solver, A, b, args["output"]["advanced"]["spectrum"].get<bool>() && t == time_steps, sol);
933 split_solution(sol, velocity, pressure);
934 bdf->update_quantities(velocity.col(0));
935
936 save_timestep(time, t, t0, dt, sol);
937 save_step_state(t0, dt, t, sol, time_integrator.get());
938 logger().info("{}/{} t={}", t, time_steps, time);
939 notify_time_step(t, time_steps, t0, dt);
940 }
941 }
942
943 void StokesVarForm::solve_problem(
944 Eigen::MatrixXd &sol,
945 const InitialConditionOverride *initial_condition_override,
946 const ForwardStepCallback &post_step)
947 {
948 assert(!initial_condition_override && "Stokes does not support initial-condition overrides");
949 assert(!post_step && "Stokes does not support post-step callbacks");
950
951 stats.spectrum.setZero();
952 igl::Timer timer;
953 timer.start();
954 logger().info("Solving {}", primary_assembler_->name());
955
956 prepare_initial_solution(sol);
957 if (problem->is_time_dependent())
958 solve_transient_linear(sol);
959 else
960 {
961 time_integrator = nullptr;
962 solve_static_linear(sol);
963 }
964
965 timer.stop();
966 timings.solving_time = timer.getElapsedTime();
967 logger().info(" took {}s", timings.solving_time);
968 }
969
970 namespace
971 {
972 json residual_solver_params(const json &input)
973 {
974 json params = input;
975 params["solver"] = "Newton";
976 params["line_search"]["method"] = "ResidualBacktracking";
977
978 if (!params.contains("Newton") || params["Newton"].is_null())
979 params["Newton"] = json::object();
980 params["Newton"]["force_psd_projection"] = false;
981 params["Newton"]["use_psd_projection"] = true;
982 return params;
983 }
984
985 StiffnessMatrix append_identity_mass(const StiffnessMatrix &velocity_mass, const int extra_size)
986 {
987 std::vector<Eigen::Triplet<double>> entries;
988 entries.reserve(velocity_mass.nonZeros() + extra_size);
989 for (int k = 0; k < velocity_mass.outerSize(); ++k)
990 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
991 entries.emplace_back(it.row(), it.col(), it.value());
992 for (int i = 0; i < extra_size; ++i)
993 entries.emplace_back(velocity_mass.rows() + i, velocity_mass.cols() + i, 1.0);
994
995 StiffnessMatrix result(
996 velocity_mass.rows() + extra_size,
997 velocity_mass.cols() + extra_size);
998 result.setFromTriplets(entries.begin(), entries.end());
999 result.makeCompressed();
1000 return result;
1001 }
1002 } // namespace
1003
1004 void NavierStokesVarForm::build_forms(Eigen::MatrixXd &sol, const double t)
1005 {
1006 assert(sol.rows() == stacked_ndof());
1007 assert(sol.cols() == 1);
1008
1009 auto stokes_assembler = std::make_shared<assembler::StokesVelocity>();
1010 set_materials(*stokes_assembler, mesh_->dimension());
1011 auto *navier_stokes_assembler = dynamic_cast<assembler::NavierStokesVelocity *>(primary_assembler_.get());
1012 assert(navier_stokes_assembler);
1013
1014 stacked_form_ = std::make_shared<solver::StackedForm>();
1015 const auto velocity_block = stacked_form_->add_block(primary_ndof());
1016 const auto pressure_block = stacked_form_->add_block(pressure_space_.n_bases);
1017
1018 navier_stokes_form_ = std::make_shared<solver::NavierStokesForm>(
1019 space_.n_bases, space_.basis_list(), space_.geometry_basis_list(),
1020 stokes_assembler, *navier_stokes_assembler, ass_vals_cache_, t, mesh_->is_volume());
1021 stacked_form_->add(velocity_block, navier_stokes_form_);
1022
1023 velocity_rhs_ = rhs_.topRows(primary_ndof());
1024 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
1025 const QuadratureOrders boundary_samples = n_boundary_samples(space_.disc_orders.maxCoeff(), space_.disc_ordersq.maxCoeff(), gdiscr_order);
1026 body_form_ = std::make_shared<solver::BodyForm>(
1027 primary_ndof(), /*n_pressure_bases=*/0,
1028 boundary_.boundary_nodes, boundary_.local_boundary,
1029 boundary_.local_neumann_boundary, boundary_samples,
1030 velocity_rhs_, *rhs_assembler_, mass_assembler_->density(),
1031 /*is_formulation_mixed=*/false, problem->is_time_dependent());
1032 body_form_->update_quantities(t, sol.topRows(primary_ndof()));
1033 stacked_form_->add(velocity_block, body_form_);
1034
1035 mixed_form_ = std::make_shared<solver::MixedLinearForm>(
1036 space_.n_bases, pressure_space_.n_bases,
1037 space_.basis_list(), pressure_space_.basis_list(), space_.geometry_basis_list(),
1038 *mixed_assembler_, ass_vals_cache_, pressure_ass_vals_cache_, t, mesh_->is_volume());
1039 stacked_form_->add(velocity_block, pressure_block, mixed_form_);
1040
1041 if (use_avg_pressure)
1042 {
1043 const auto average_block = stacked_form_->add_block(1);
1044 average_pressure_form_ = std::make_shared<solver::AveragePressureForm>(pressure_space_.n_bases);
1045 stacked_form_->add(pressure_block, average_block, average_pressure_form_);
1046 }
1047 else
1048 average_pressure_form_ = nullptr;
1049
1050 inertia_form_ = nullptr;
1051 if (problem->is_time_dependent())
1052 {
1053 assert(time_integrator);
1054 inertia_form_ = std::make_shared<solver::InertiaForm>(mass_, *time_integrator);
1055 if (!boundary_.boundary_nodes.empty())
1056 {
1057 inertia_form_->set_x_tilde_updater(
1058 [this, boundary_samples](
1059 const double time,
1060 const Eigen::VectorXd &,
1061 Eigen::VectorXd &target) {
1062 Eigen::MatrixXd projected_target = target;
1063 const std::vector<mesh::LocalBoundary> empty_neumann_boundary;
1064 rhs_assembler_->set_bc(
1065 boundary_.local_boundary, boundary_.boundary_nodes,
1066 boundary_samples, empty_neumann_boundary,
1067 projected_target, Eigen::MatrixXd(), time);
1068 assert(projected_target.cols() == 1);
1069 target = projected_target.col(0);
1070 });
1071 }
1072 stacked_form_->add(velocity_block, inertia_form_);
1073 update_transient_form_weights();
1074 }
1075
1076 forms_ = {stacked_form_};
1077 for (const auto &form : forms_)
1078 form->set_output_dir(output_path);
1079
1080 al_forms_.clear();
1081 if (!boundary_.boundary_nodes.empty())
1082 {
1083 auto stacked_al = std::make_shared<solver::StackedAugmentedLagrangianForm>();
1084 const auto velocity_al_block = stacked_al->add_block(primary_ndof());
1085 stacked_al->add_block(pressure_space_.n_bases);
1086 if (use_avg_pressure)
1087 stacked_al->add_block(1);
1088 stacked_al->add(
1089 velocity_al_block,
1090 std::make_shared<solver::BCLagrangianForm>(
1091 primary_ndof(), boundary_.boundary_nodes,
1092 boundary_.local_boundary, boundary_.local_neumann_boundary,
1093 boundary_samples, pure_mass_, *rhs_assembler_,
1094 /*obstacle_ndof=*/0, problem->is_time_dependent(), t));
1095 al_forms_.push_back(stacked_al);
1096 }
1097
1098 const StiffnessMatrix residual_mass = append_identity_mass(pure_mass_, pressure_block_size());
1099 nl_problem_ = std::make_shared<solver::NLProblem>(
1100 stacked_ndof(), t, forms_, al_forms_,
1101 polysolve::linear::Solver::create(args["solver"]["linear"], logger()),
1102 units.characteristic_length(), /*characteristic_force=*/1,
1103 residual_mass, mesh_->dimension(), /*is_residual=*/true);
1104 nl_problem_->init(sol);
1105 nl_problem_->update_quantities(t, sol);
1106 stats.solver_info = json::array();
1107 }
1108
1109 void NavierStokesVarForm::update_transient_form_weights()
1110 {
1111 assert(time_integrator);
1112 const double scaling = time_integrator->acceleration_scaling();
1113 navier_stokes_form_->set_weight(scaling);
1114 body_form_->set_weight(scaling);
1115 mixed_form_->set_row_weights(scaling, scaling);
1116 if (average_pressure_form_)
1117 average_pressure_form_->set_weight(scaling);
1118 }
1119
1120 void NavierStokesVarForm::solve_nonlinear_step(const int step, Eigen::MatrixXd &sol)
1121 {
1122 assert(nl_problem_);
1123 const json nonlinear_params = residual_solver_params(args["solver"]["nonlinear"]);
1124 const json al_nonlinear_params = residual_solver_params(args["solver"]["augmented_lagrangian"]["nonlinear"]);
1125 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver =
1126 polysolve::nonlinear::Solver::create(
1127 nonlinear_params, args["solver"]["linear"], units.characteristic_length(), logger());
1128
1129 solver::ALSolver al_solver(
1130 al_forms_, args["solver"]["augmented_lagrangian"]["initial_weight"],
1131 args["solver"]["augmented_lagrangian"]["scaling"],
1132 args["solver"]["augmented_lagrangian"]["max_weight"],
1133 args["solver"]["augmented_lagrangian"]["eta"],
1134 [](const Eigen::VectorXd &) {});
1135
1136 al_solver.post_subsolve = [&](const double al_weight) {
1137 stats.solver_info.push_back(
1138 {{"type", al_weight > 0 ? "al" : "rc"},
1139 {"t", step},
1140 {"info", nl_solver->info()}});
1141 if (al_weight > 0)
1142 stats.solver_info.back()["weight"] = al_weight;
1143 save_subsolve(stats.solver_info.size(), step, sol);
1144 };
1145
1146 if (!al_forms_.empty())
1147 al_solver.solve_al(
1148 *nl_problem_, sol, al_nonlinear_params,
1149 args["solver"]["linear"], units.characteristic_length(), nl_solver);
1150 al_solver.solve_reduced(
1151 *nl_problem_, sol, nonlinear_params,
1152 args["solver"]["linear"], units.characteristic_length(), nl_solver);
1153 }
1154
1155 void NavierStokesVarForm::solve_problem(
1156 Eigen::MatrixXd &sol,
1157 const InitialConditionOverride *initial_condition_override,
1158 const ForwardStepCallback &post_step)
1159 {
1160 assert(!initial_condition_override && "Navier-Stokes does not support initial-condition overrides");
1161 assert(!post_step && "Navier-Stokes does not support post-step callbacks");
1162
1163 stats.spectrum.setZero();
1164 igl::Timer timer;
1165 timer.start();
1166 logger().info("Solving {}", primary_assembler_->name());
1167
1168 prepare_initial_solution(sol);
1169 if (!problem->is_time_dependent())
1170 {
1171 time_integrator = nullptr;
1172 build_forms(sol, 1.0);
1173 solve_nonlinear_step(0, sol);
1174 }
1175 else
1176 {
1177 Eigen::MatrixXd velocity, pressure;
1178 split_solution(sol, velocity, pressure);
1180 args["time"]["integrator"],
1182 bdf->init(
1183 velocity,
1184 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
1185 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()), dt);
1186 time_integrator = bdf;
1187 restore_checkpoint_integrator(
1188 time_integrator, "/checkpoint/state/primary_integrator", dt,
1189 "primary", space_, mesh_->dimension());
1190
1191 build_forms(sol, t0 + dt);
1192 save_timestep(t0, 0, t0, dt, sol);
1193 for (int step = 1; step <= time_steps; ++step)
1194 {
1195 const double time = t0 + step * dt;
1196 logger().info("{}/{} steps, dt={}s t={}s", step, time_steps, dt, time);
1197 solve_nonlinear_step(step, sol);
1198
1199 split_solution(sol, velocity, pressure);
1200 time_integrator->update_quantities(velocity.col(0));
1201 update_transient_form_weights();
1202 nl_problem_->update_quantities(t0 + (step + 1) * dt, sol);
1203
1204 save_timestep(time, step, t0, dt, sol);
1205 save_step_state(t0, dt, step, sol, time_integrator.get());
1206 notify_time_step(step, time_steps, t0, dt);
1207 }
1208 }
1209
1210 timer.stop();
1211 timings.solving_time = timer.getElapsedTime();
1212 logger().info(" took {}s", timings.solving_time);
1213 }
1214} // namespace polyfem::varform
std::vector< Eigen::Triplet< double > > entries
int x
std::array< Matrix< int, 3, 3 >, 3 > space_
static std::shared_ptr< MixedAssembler > make_mixed_assembler(const std::string &formulation)
static std::string other_assembler_name(const std::string &formulation)
static void merge_mixed_matrices(const int n_bases, const int n_pressure_bases, const int problem_dim, const bool add_average, const StiffnessMatrix &velocity_stiffness, const StiffnessMatrix &mixed_stiffness, const StiffnessMatrix &pressure_stiffness, StiffnessMatrix &stiffness)
utility to merge 3 blocks of mixed matrices, A=velocity_stiffness, B=mixed_stiffness,...
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.
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).
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)
static void compute_stress_at_quadrature_points(const mesh::Mesh &mesh, const bool is_problem_scalar, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::VectorXi &disc_orders, const Eigen::VectorXi &disc_ordersq, const assembler::Assembler &assembler, const Eigen::MatrixXd &fun, const double t, Eigen::MatrixXd &result, Eigen::VectorXd &von_mises)
compute von mises stress at quadrature points for the function fun, also compute the interpolated fun...
void export_data(const OutputSpace &space, const OutputFieldFunction &output_fields, const bool is_time_dependent, const double tend_in, const double dt, const ExportOptions &opts, const std::string &vis_mesh_path) const
exports everytihng, txt, vtu, etc
Definition OutData.cpp:2103
double assembling_stiffness_mat_time
time to assembly
double assigning_rhs_time
time to computing the rhs
double assembling_mass_mat_time
time to assembly mass
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:2815
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:2860
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:2732
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
void save_json(const nlohmann::json &args, const int n_bases, const int n_pressure_bases, const Eigen::MatrixXd &sol, const mesh::Mesh &mesh, const Eigen::VectorXi &disc_orders, const Eigen::VectorXi &disc_ordersq, const assembler::Problem &problem, const OutRuntimeData &runtime, const std::string &formulation, const bool isoparametric, const int sol_at_node_id, nlohmann::json &j) const
saves the output statistic to a json object
Definition OutData.cpp:3103
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:50
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
void update_nodes(const Eigen::VectorXi &in_node_to_node)
Update the node ids to reorder them.
Definition Mesh.cpp:346
int dimension() const
utily for dimension
Definition Mesh.hpp:138
static const ProblemFactory & factory()
std::shared_ptr< assembler::Problem > get_problem(const std::string &problem) const
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
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.
const std::vector< basis::ElementBases > & geometry_basis_list() const
Definition FESpace.hpp:115
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:89
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:91
std::map< int, std::pair< Eigen::MatrixXd, Eigen::MatrixXi > > polys_3d
Physical vertices and face connectivity for 3D polyhedral elements.
Definition FESpace.hpp:83
std::map< int, Eigen::MatrixXd > polys
Physical boundary samples for 2D polygonal elements.
Definition FESpace.hpp:80
std::map< int, basis::InterfaceData > poly_edge_to_data
Polygonal-basis construction data, indexed by element ID.
Definition FESpace.hpp:77
const std::vector< basis::ElementBases > & basis_list() const
Definition FESpace.hpp:109
bool is_iso_parametric() const
Definition FESpace.hpp:104
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 serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const override
std::shared_ptr< assembler::HRZMass > pure_mass_assembler_
io::OutputSpace output_space() const override
Get the output space of the variational formulation, for output purposes.
VarFormBoundaryState pressure_boundary_
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_
void split_solution(const Eigen::MatrixXd &stacked, Eigen::MatrixXd &primary, Eigen::MatrixXd &pressure) const
std::shared_ptr< assembler::Assembler > primary_assembler_
void deserialize_checkpoint(const io::CheckpointReader &reader, Eigen::MatrixXd &solution) override
assembler::AssemblyValsCache pure_mass_ass_vals_cache_
std::shared_ptr< assembler::RhsAssembler > rhs_assembler_
void export_data(const Eigen::MatrixXd &solution) const override
void prepare_initial_solution(Eigen::MatrixXd &sol) const
VarFormBoundaryState boundary_
void save_json(const Eigen::MatrixXd &solution, std::ostream &out) const override
Save the solution to a JSON file, for output purposes.
io::OutStatsData compute_errors(const Eigen::MatrixXd &solution) override
Get the error statistics of the variational formulation, for output purposes.
std::shared_ptr< assembler::Mass > mass_assembler_
void solve_linear_system(const std::unique_ptr< polysolve::linear::Solver > &solver, StiffnessMatrix &A, Eigen::VectorXd &b, const bool compute_spectrum, Eigen::MatrixXd &sol)
void build_stiffness_mat(StiffnessMatrix &stiffness)
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< assembler::Assembler > pressure_assembler_
assembler::AssemblyValsCache mass_ass_vals_cache_
std::shared_ptr< assembler::MixedAssembler > mixed_assembler_
void load_mesh(const mesh::Mesh &mesh, const json &args) override
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:981
static void rebuild_node_positions(const std::vector< basis::ElementBases > &bases, const std::vector< int > &node_ids, std::vector< RowVectorNd > &positions)
Definition VarForm.cpp:1125
std::shared_ptr< assembler::Problem > problem
current problem, it contains rhs and bc
Definition VarForm.hpp:261
virtual std::string name() const =0
Get the name of the variational formulation.
void write_checkpoint_ordering(io::CheckpointWriter &writer, const std::string &name, const FESpace &space) const
Definition VarForm.cpp:938
virtual void deserialize_checkpoint(const io::CheckpointReader &reader, Eigen::MatrixXd &solution)
Definition VarForm.cpp:905
std::unique_ptr< mesh::Mesh > mesh_
Definition VarForm.hpp:273
void assign_discr_orders(const json &space_args, const mesh::Mesh &mesh, Eigen::VectorXi &disc_orders, Eigen::VectorXi &disc_ordersq)
Definition VarForm.cpp:684
io::OutStatsData stats
Definition VarForm.hpp:265
io::OutGeometryData::ExportOptions export_options(const io::OutputSpace &space) const
Definition VarForm.cpp:835
io::OutGeometryData output_geometry_
Definition VarForm.hpp:277
io::OutputFieldFunction output_field_function(const Eigen::MatrixXd &solution, const io::OutGeometryData::ExportOptions &opts) const
Definition VarForm.cpp:844
virtual void serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const
Definition VarForm.cpp:897
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:274
std::string resolve_output_path(const std::string &path) const
Definition VarForm.cpp:1116
void ensure_output_sampler() const
Definition VarForm.cpp:821
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:208
void validate_checkpoint_solution(const Eigen::MatrixXd &solution, int expected_rows) const
Definition VarForm.cpp:1037
io::OutRuntimeData timings
runtime statistics
Definition VarForm.hpp:268
const io::ResourceIO & resources_
Definition VarForm.hpp:283
void set_materials(assembler::Assembler &assembler, const int size) const
Definition VarForm.cpp:806
virtual void reset()=0
Definition VarForm.cpp:194
str func
Definition p_bases.py:417
bool write_matrix(const std::string &path, const Mat &mat)
Writes a matrix to a file. Determines the file format based on the path's extension.
Definition MatrixIO.cpp:43
Eigen::SparseMatrix< double > lump_matrix(const Eigen::SparseMatrix< double > &M)
Lump each row of a matrix into the diagonal.
Eigen::MatrixXd unflatten(const Eigen::VectorXd &x, int dim)
Unflatten rowwises, so every dim elements in x become a row.
bool write_matrix_market(const json &args, const StiffnessMatrix &stiffness)
bool sample_scalar_field(const mesh::Mesh &mesh, const std::vector< basis::ElementBases > &field_bases, const std::vector< basis::ElementBases > &gbases, const io::OutputSample &sample, const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients=nullptr)
void expand_primary_matrix(const int full_size, const StiffnessMatrix &primary, StiffnessMatrix &expanded)
std::function< void(int step, const Eigen::MatrixXd &solution)> ForwardStepCallback
Definition VarForm.hpp:53
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:56
std::vector< std::string > fields
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:163
std::vector< mesh::LocalBoundary > local_boundary
Definition FESpace.hpp:155
std::vector< mesh::LocalBoundary > local_neumann_boundary
Definition FESpace.hpp:156
std::vector< mesh::LocalBoundary > total_local_boundary
Definition FESpace.hpp:154
std::vector< RowVectorNd > dirichlet_nodes_position
Definition FESpace.hpp:161
std::vector< mesh::LocalBoundary > local_pressure_boundary
Definition FESpace.hpp:157
std::unordered_map< int, std::vector< mesh::LocalBoundary > > local_pressure_cavity
Definition FESpace.hpp:158