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