PolyFEM
Loading...
Searching...
No Matches
OperatorSplittingVarForm.cpp
Go to the documentation of this file.
2
17
18#include <igl/Timer.h>
19
20namespace polyfem::varform
21{
22 using namespace varform::internal;
23
25 {
27 space_.reset();
34 rhs_assembler_ = nullptr;
35 mass_.resize(0, 0);
36 rhs_.resize(0, 0);
37 primary_assembler_ = nullptr;
38 mass_assembler_ = nullptr;
39 mixed_assembler_ = nullptr;
40 pressure_assembler_ = nullptr;
41 use_avg_pressure = true;
42 avg_mass_ = 0;
43 t0 = 0;
44 time_steps = 0;
45 dt = 0;
46 }
47
48 void OperatorSplittingVarForm::init(const std::string &formulation, const Units &units, const json &args, const std::string &out_path)
49 {
50 VarForm::init(formulation, units, args, out_path);
51 const bool is_time_dependent = args.contains("time") && !args["time"].is_null();
52
54 mass_assembler_ = std::make_shared<assembler::Mass>();
57
58 if (!args.contains("preset_problem"))
59 {
60 problem = std::make_shared<assembler::GenericTensorProblem>("GenericTensor");
61 problem->clear();
62
63 json tmp;
64 tmp["is_time_dependent"] = is_time_dependent;
65 problem->set_parameters(tmp, root_path);
66
67 auto bc = args["boundary_conditions"];
68 bc["root_path"] = root_path;
69 problem->set_parameters(bc, root_path);
70 problem->set_parameters(args["initial_conditions"], root_path);
71 problem->set_parameters(args["output"], root_path);
72 }
73 else
74 {
75 if (args["preset_problem"]["type"] == "Kernel")
76 {
77 problem = std::make_shared<problem::KernelProblem>("Kernel", *primary_assembler_);
78 problem->clear();
79 }
80 else
81 {
82 problem = problem::ProblemFactory::factory().get_problem(args["preset_problem"]["type"]);
83 problem->clear();
84 }
85 problem->set_parameters(args["preset_problem"], root_path);
86 }
87
88 problem->set_units(*primary_assembler_, units);
89
90 t0 = is_time_dependent ? args["time"]["t0"].get<double>() : 0.0;
91 time_steps = is_time_dependent ? args["time"]["time_steps"].get<int>() : 0;
92 dt = is_time_dependent ? args["time"]["dt"].get<double>() : 0.0;
93
94 assert(primary_assembler_);
95 assert(primary_assembler_->name() == "OperatorSplitting");
96 }
97
98 void OperatorSplittingVarForm::save_json(const Eigen::MatrixXd &solution, std::ostream &out) const
99 {
100 if (!mesh_)
101 {
102 logger().error("Load the mesh first!");
103 return;
104 }
105 if (solution.size() <= 0)
106 {
107 logger().error("Solve the problem first!");
108 return;
109 }
110
111 logger().info("Saving json...");
112 const int primary_size = primary_ndof();
113 const Eigen::MatrixXd stats_solution =
114 solution.rows() >= primary_size
115 ? solution.topRows(primary_size).eval()
116 : solution;
117
118 nlohmann::json j;
121 stats_solution, *mesh_, space_.disc_orders, space_.disc_ordersq, *problem,
123 args["output"]["advanced"]["sol_at_node"], j);
124 out << j.dump(4) << std::endl;
125 }
126
128 {
129 Eigen::VectorXi output_orders = space_.disc_orders;
130 if (mesh_ && space_.disc_ordersq.size() == space_.disc_orders.size())
131 {
132 for (int e = 0; e < output_orders.size(); ++e)
133 {
134 if (mesh_->is_prism(e))
135 output_orders(e) = std::max(space_.disc_orders(e), space_.disc_ordersq(e));
136 }
137 }
138
139 return {
140 mesh_.get(),
142 output_orders,
143 &space_.polys,
146 nullptr,
147 nullptr,
150 }
151
153 {
154 if (!args["output"]["advanced"]["compute_error"])
155 return stats;
156
157 double tend = 0;
158 if (args.contains("time") && !args["time"].is_null())
159 {
160 if (args["time"].contains("tend"))
161 tend = args["time"]["tend"].get<double>();
162 else
163 tend = t0 + dt * time_steps;
164 }
165
166 Eigen::MatrixXd velocity, pressure;
167 split_solution(solution, velocity, pressure);
169 return stats;
170 }
171
172 void OperatorSplittingVarForm::export_data(const Eigen::MatrixXd &solution) const
173 {
174 const io::OutputSpace space = output_space();
175 if (!space.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
187
188 const std::string vis_mesh_path = resolve_output_path(args["output"]["paraview"]["file_name"]);
189 const bool has_time = args.contains("time") && !args["time"].is_null();
190 double tend = 1.0;
191 if (has_time)
192 {
193 if (args["time"].contains("tend"))
194 tend = args["time"]["tend"].get<double>();
195 else
196 tend = t0 + dt * time_steps;
197 }
198 double local_dt = 1;
199 if (has_time)
200 local_dt = args["time"]["dt"];
201
202 const auto opts = export_options(space);
204 space,
205 output_field_function(solution, opts),
206 has_time,
207 tend, local_dt,
208 opts,
209 vis_mesh_path);
210
211 Eigen::MatrixXd velocity, pressure;
212 split_solution(solution, velocity, pressure);
213
214 const std::string solution_path = resolve_output_path(args["output"]["data"]["solution"]);
215 if (!solution_path.empty())
216 {
217 const int primary_rows = std::min<int>(velocity.rows(), primary_ndof());
218 const Eigen::MatrixXd primary_solution = velocity.topRows(primary_rows);
219 if (opts.reorder_output && space_.space_in_node_to_node.size() > 0)
220 {
221 const Eigen::MatrixXd nodal_solution = utils::unflatten(primary_solution, mesh_->dimension());
222 Eigen::MatrixXd reordered = Eigen::MatrixXd::Zero(nodal_solution.rows(), nodal_solution.cols());
223 for (int input_node = 0; input_node < space_.space_in_node_to_node.size(); ++input_node)
224 {
225 const int node = space_.space_in_node_to_node(input_node);
226 if (node >= 0 && node < nodal_solution.rows() && input_node < reordered.rows())
227 reordered.row(input_node) = nodal_solution.row(node);
228 }
229 io::write_matrix(solution_path, reordered);
230 }
231 else
232 {
233 io::write_matrix(solution_path, primary_solution);
234 }
235 }
236
237 const std::string nodes_path = resolve_output_path(args["output"]["data"]["nodes"]);
238 if (!nodes_path.empty())
239 {
240 Eigen::MatrixXd nodes = Eigen::MatrixXd::Zero(space_.n_bases, mesh_->dimension());
241 for (const basis::ElementBases &element_bases : space_.basis_list())
242 for (const basis::Basis &basis : element_bases.bases)
243 for (const auto &global : basis.global())
244 nodes.row(global.index) = global.node;
245 io::write_matrix(nodes_path, nodes);
246 }
247
248 const std::string stress_path = resolve_output_path(args["output"]["data"]["stress_mat"]);
249 const std::string mises_path = resolve_output_path(args["output"]["data"]["mises"]);
250 if ((!stress_path.empty() || !mises_path.empty()) && primary_assembler_)
251 {
252 Eigen::MatrixXd stress;
253 Eigen::VectorXd mises;
257 stress, mises);
258 if (!stress_path.empty())
259 io::write_matrix(stress_path, stress);
260 if (!mises_path.empty())
261 io::write_matrix(mises_path, mises);
262 }
263 }
264
266 {
267 (void)args;
270 problem->init(mesh);
271
273 mixed_assembler_->set_size(mesh.dimension());
276 }
277
279 {
280 return mesh_ ? space_.n_bases * mesh_->dimension() : 0;
281 }
282
287
292
294 {
295 json rhs_solver_params = args["solver"]["linear"];
296 if (!rhs_solver_params.contains("Pardiso"))
297 rhs_solver_params["Pardiso"] = {};
298 rhs_solver_params["Pardiso"]["mtype"] = -2;
299
300 rhs_assembler_ = std::make_shared<assembler::RhsAssembler>(
301 *primary_assembler_, *mesh_, nullptr,
305 args["space"]["advanced"]["bc_method"],
306 rhs_solver_params,
307 /*fe_space_id=*/-1);
308 }
309
310 void OperatorSplittingVarForm::build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args)
311 {
312 assert(problem);
313 assert(primary_assembler_);
314 assert(mass_assembler_);
315
316 Eigen::VectorXi space_disc_orders;
317 assign_discr_orders(args["space"]["discr_order"], mesh, space_disc_orders);
318
319 if (args["space"]["use_p_ref"])
320 {
322 mesh,
323 args["space"]["advanced"]["B"],
324 args["space"]["advanced"]["h1_formula"],
325 args["space"]["discr_order"],
326 args["space"]["advanced"]["discr_order_max"],
327 stats,
328 space_disc_orders);
329
330 logger().info("min p: {} max p: {}", space_disc_orders.minCoeff(), space_disc_orders.maxCoeff());
331 }
332
334 mesh,
335 iso_parametric,
336 space_disc_orders,
337 args["space"]["basis_type"],
338 args["space"]["poly_basis_type"],
340 mesh.dimension(),
341 args["space"]["advanced"]["quadrature_order"],
342 args["space"]["advanced"]["mass_quadrature_order"],
343 args["space"]["advanced"]["use_corner_quadrature"],
344 args["space"]["advanced"]["n_harmonic_samples"],
345 args["space"]["advanced"]["integral_constraints"],
346 space_,
347 boundary_);
348
349 problem->update_nodes(space_.space_in_node_to_node);
351
352 const auto &current_bases = space_.geometry_basis_list();
353 if (args["space"]["advanced"]["count_flipped_els"])
354 stats.count_flipped_elements(mesh, current_bases);
355
356 const int n_samples = 10;
357 stats.compute_mesh_size(mesh, current_bases, n_samples, args["output"]["advanced"]["curved_mesh_size"]);
358
359 logger().info("flipped elements {}", stats.n_flipped);
360 logger().info("h: {}", stats.mesh_size);
361
362 if (space_.disc_orders.maxCoeff() != space_.disc_orders.minCoeff())
363 log_and_throw_error("p refinement not supported in operator splitting!");
364 if (!space_.poly_edge_to_data.empty())
365 log_and_throw_error("Polygonal bases are not supported in operator splitting!");
366
367 if (space_.n_bases <= args["solver"]["advanced"]["cache_size"])
368 {
369 igl::Timer cache_timer;
370 cache_timer.start();
371 logger().info("Building cache...");
372 ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases);
373 mass_ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases, true);
374 logger().info(" took {}s", cache_timer.getElapsedTime());
375 }
376 else
377 {
380 }
381
382 const auto &all_boundary = boundary_.total_local_boundary;
383 const int prev_bases = space_.n_bases;
384 const int prev_b_size = int(all_boundary.size());
385 const bool use_corner_quadrature = args["space"]["advanced"]["use_corner_quadrature"];
386 const int quadrature_order = args["space"]["advanced"]["quadrature_order"].get<int>();
387 const int mass_quadrature_order = args["space"]["advanced"]["mass_quadrature_order"].get<int>();
388 Eigen::VectorXi pressure_disc_orders;
389 assign_discr_orders(args["space"]["discr_order"], mesh, pressure_disc_orders);
390 const std::string pressure_basis_type = args["space"]["basis_type"].get<std::string>() == "Bernstein" ? "Bernstein" : "Lagrange";
392 mesh,
393 /*iso_parametric=*/true,
394 pressure_disc_orders,
395 pressure_basis_type,
396 args["space"]["poly_basis_type"],
398 /*value_dim=*/1,
399 quadrature_order,
400 mass_quadrature_order,
401 use_corner_quadrature,
402 args["space"]["advanced"]["n_harmonic_samples"],
403 args["space"]["advanced"]["integral_constraints"],
407
408 assert(space_.basis_list().size() == pressure_space_.basis_list().size());
409 for (int i = 0; i < int(pressure_space_.basis_list().size()); ++i)
410 {
412 space_.basis_list()[i].compute_quadrature(b_quad);
413 (*pressure_space_.bases)[i].set_quadrature([b_quad](quadrature::Quadrature &quad) { quad = b_quad; });
414 }
415
417 for (const auto &lb : all_boundary)
418 boundary_.local_boundary.emplace_back(lb);
420
421 problem->setup_bc(
422 mesh, space_.n_bases,
432
435
436 const bool has_neumann = !boundary_.local_neumann_boundary.empty() || int(boundary_.local_boundary.size()) < prev_b_size;
437 use_avg_pressure = !has_neumann;
438
439 for (int i = prev_bases; i < space_.n_bases; ++i)
440 for (int d = 0; d < mesh.dimension(); ++d)
441 boundary_.boundary_nodes.push_back(i * mesh.dimension() + d);
442
444
445 if (space_.n_bases <= args["solver"]["advanced"]["cache_size"])
447 else
449
451
452 logger().info("n pressure bases: {}", pressure_space_.n_bases);
453 }
454
456 {
458
459 igl::Timer timer;
460 json p_params = {};
461 p_params["formulation"] = primary_assembler_->name();
462 p_params["root_path"] = root_path;
463 {
464 RowVectorNd min, max, delta;
465 mesh.bounding_box(min, max);
466 delta = (max - min) / 2. + min;
467 if (mesh.is_volume())
468 p_params["bbox_center"] = {delta(0), delta(1), delta(2)};
469 else
470 p_params["bbox_center"] = {delta(0), delta(1)};
471 }
472 problem->set_parameters(p_params, root_path);
473
474 rhs_.resize(0, 0);
475
476 timer.start();
477 logger().info("Assigning rhs...");
478
479 assert(rhs_assembler_ != nullptr);
480 rhs_assembler_->assemble(mass_assembler_->density(), rhs_);
481 rhs_ *= -1;
482
483 const int prev_size = rhs_.rows();
484 rhs_.conservativeResize(prev_size + pressure_block_size(), rhs_.cols());
485 rhs_.bottomRows(pressure_block_size()).setZero();
486
487 timer.stop();
488 timings.assigning_rhs_time = timer.getElapsedTime();
489 logger().info(" took {}s", timings.assigning_rhs_time);
490 }
491
493 {
494 (void)mesh;
495 (void)args;
496 mass_.resize(0, 0);
497 avg_mass_ = 1;
499 }
500
502 {
503 if (sol.size() <= 0)
504 {
505 assert(rhs_assembler_ != nullptr);
506 const bool was_solution_loaded = read_initial_x_from_file(
507 resolve_input_path(args["input"]["data"]["state"]), "u",
508 args["input"]["data"]["reorder"], space_.space_in_node_to_node,
509 mesh_->dimension(), sol);
510
511 if (!was_solution_loaded)
512 {
513 if (problem->is_time_dependent())
514 rhs_assembler_->initial_solution(sol);
515 else
516 {
517 sol.resize(rhs_.size(), 1);
518 sol.setZero();
519 }
520 }
521 }
522 if (sol.cols() > 1)
523 sol.conservativeResize(Eigen::NoChange, 1);
524 sol.conservativeResize(stacked_ndof(), sol.cols());
525 sol.bottomRows(pressure_block_size()).setZero();
526 }
527
528 void OperatorSplittingVarForm::split_solution(const Eigen::MatrixXd &stacked, Eigen::MatrixXd &primary, Eigen::MatrixXd &pressure) const
529 {
530 const int cols = std::max(1, int(stacked.cols()));
531 primary.setZero(primary_ndof(), cols);
532 pressure.setZero(pressure_space_.n_bases, cols);
533
534 const int primary_rows = std::min(primary_ndof(), int(stacked.rows()));
535 if (primary_rows > 0)
536 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
537
538 if (stacked.rows() > primary_ndof())
539 {
540 const int pressure_rows = std::min(pressure_space_.n_bases, int(stacked.rows()) - primary_ndof());
541 if (pressure_rows > 0)
542 pressure.topRows(pressure_rows) = stacked.middleRows(primary_ndof(), pressure_rows);
543 }
544 }
545
546 void OperatorSplittingVarForm::stack_solution(const Eigen::MatrixXd &primary, const Eigen::MatrixXd &pressure, Eigen::MatrixXd &stacked) const
547 {
548 const int cols = std::max(primary.cols(), pressure.cols());
549 stacked.resize(stacked_ndof(), cols);
550 stacked.setZero();
551
552 const int primary_rows = std::min(primary_ndof(), int(primary.rows()));
553 if (primary_rows > 0)
554 stacked.topRows(primary_rows) = primary.topRows(primary_rows);
555
556 const int pressure_rows = std::min(pressure_space_.n_bases, int(pressure.rows()));
557 if (pressure_rows > 0)
558 stacked.middleRows(primary_ndof(), pressure_rows) = pressure.topRows(pressure_rows);
559 }
560
561 std::vector<io::OutputField> OperatorSplittingVarForm::output_fields(
562 const io::OutputSample &sample,
563 const Eigen::MatrixXd &solution,
564 const io::OutputFieldOptions &options) const
565 {
566 std::vector<io::OutputField> fields;
567 if (!mesh_ || !problem || solution.size() <= 0)
568 return fields;
569
570 Eigen::MatrixXd velocity, pressure;
571 split_solution(solution, velocity, pressure);
572
573 const int field_dim = mesh_->dimension();
574 const bool has_element_samples = sample.local_points.rows() > 0 && sample.local_points.rows() == sample.element_ids.size();
575 const int output_rows = sample.points.rows() > 0 ? sample.points.rows() : std::max<int>(sample.local_points.rows(), sample.node_ids.size());
576 const bool export_solution_gradient =
577 !options.fields.empty() && options.export_field("solution_gradient");
578 const bool export_pressure_gradient =
579 !options.fields.empty() && options.export_field("pressure_gradient");
580
581 const auto resize_to_output_rows = [&](Eigen::MatrixXd &values) {
582 if (output_rows <= values.rows())
583 return;
584
585 const int previous_rows = values.rows();
586 values.conservativeResize(output_rows, values.cols());
587 values.bottomRows(output_rows - previous_rows).setZero();
588 };
589
590 const auto sample_vector_field = [&](const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients = nullptr) -> bool {
591 if (dof_values.size() <= 0 || field_dim <= 0)
592 return false;
593
594 if (has_element_samples)
595 {
596 values.resize(sample.local_points.rows(), field_dim);
597 if (gradients)
598 gradients->resize(sample.local_points.rows(), field_dim * mesh_->dimension());
599 for (int i = 0; i < sample.local_points.rows(); ++i)
600 {
601 const int element_id = sample.element_ids(i);
602 if (element_id < 0)
603 {
604 values.row(i).setZero();
605 if (gradients)
606 gradients->row(i).setZero();
607 continue;
608 }
609
610 Eigen::MatrixXd local_sol, local_grad;
613 element_id, sample.local_points.row(i), dof_values, local_sol, local_grad);
614
615 for (int d = 0; d < field_dim; ++d)
616 values(i, d) = local_sol(d);
617 if (gradients)
618 gradients->row(i) = local_grad;
619 }
620
621 resize_to_output_rows(values);
622 if (gradients)
623 resize_to_output_rows(*gradients);
624 return true;
625 }
626
627 if (sample.node_ids.size() > 0)
628 {
629 values.resize(sample.node_ids.size(), field_dim);
630 for (int i = 0; i < sample.node_ids.size(); ++i)
631 {
632 const int node_id = sample.node_ids(i);
633 for (int d = 0; d < field_dim; ++d)
634 {
635 const int dof = node_id * field_dim + d;
636 if (dof < 0 || dof >= dof_values.rows())
637 return false;
638 values(i, d) = dof_values(dof);
639 }
640 }
641 return sample.points.rows() == 0 || sample.points.rows() == values.rows();
642 }
643
644 return false;
645 };
646
647 Eigen::MatrixXd velocity_values, velocity_gradients;
648 const bool sampled_velocity = sample_vector_field(
649 velocity, velocity_values,
650 export_solution_gradient ? &velocity_gradients : nullptr);
651 if (sampled_velocity && options.export_field("velocity"))
652 fields.push_back({"velocity", velocity_values, io::OutputField::Association::Point});
653 if (sampled_velocity && options.export_field("solution"))
654 fields.push_back({"solution", velocity_values, io::OutputField::Association::Point});
655 if (sampled_velocity && export_solution_gradient)
656 fields.push_back({"solution_gradient", velocity_gradients, io::OutputField::Association::Point});
657
658 if (mesh_ && (options.export_field("pressure") || export_pressure_gradient))
659 {
660 Eigen::MatrixXd values, gradients;
661 if (sample_scalar_field(
662 *mesh_, pressure_space_.basis_list(), space_.geometry_basis_list(), sample, pressure, values,
663 export_pressure_gradient ? &gradients : nullptr))
664 {
665 if (options.export_field("pressure"))
666 fields.push_back({"pressure", values, io::OutputField::Association::Point});
667 if (export_pressure_gradient)
668 fields.push_back({"pressure_gradient", gradients, io::OutputField::Association::Point});
669 }
670 }
671
672 const auto &paraview_options = args["output"]["paraview"]["options"];
673 if (paraview_options["material"] && has_element_samples)
674 {
675 const auto &params = primary_assembler_->parameters();
676 std::map<std::string, Eigen::MatrixXd> param_values;
677 for (const auto &[p, _] : params)
678 param_values[p].setZero(output_rows, 1);
679
680 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
681 const auto &density = mass_assembler_->density();
682 for (int i = 0; i < sample.local_points.rows(); ++i)
683 {
684 const int element_id = sample.element_ids(i);
685 if (element_id < 0)
686 continue;
687
688 for (const auto &[p, func] : params)
689 param_values.at(p)(i) = func(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
690 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
691 }
692
693 for (const auto &[field_name, values] : param_values)
694 if (options.export_field(field_name))
695 fields.push_back({field_name, values, io::OutputField::Association::Point});
696 if (options.export_field("rho"))
697 fields.push_back({"rho", rhos, io::OutputField::Association::Point});
698 }
699
700 if (paraview_options["body_ids"] && options.export_field("body_ids") && has_element_samples)
701 {
702 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
703 for (int i = 0; i < sample.element_ids.size(); ++i)
704 {
705 const int element_id = sample.element_ids(i);
706 if (element_id >= 0)
707 ids(i) = mesh_->get_body_id(element_id);
708 }
709 fields.push_back({"body_ids", ids, io::OutputField::Association::Point});
710 }
711
712 return fields;
713 }
714
715 void OperatorSplittingVarForm::solve_problem(Eigen::MatrixXd &sol)
716 {
717 stats.spectrum.setZero();
718
719 if (!problem->is_time_dependent())
720 log_and_throw_error("Operator splitting requires a transient problem.");
721
722 igl::Timer timer;
723 timer.start();
724 logger().info("Solving {}", primary_assembler_->name());
725
726 prepare_initial_solution(sol);
727
728 Eigen::MatrixXd velocity, pressure;
729 split_solution(sol, velocity, pressure);
730 stack_solution(velocity, pressure, sol);
731 save_timestep(t0, 0, t0, dt, sol);
732
733 Eigen::MatrixXd local_pts;
734 const auto &gbases = space_.geometry_basis_list();
735 const int discr_order = space_.disc_orders.size() > 0 ? space_.disc_orders.maxCoeff() : 1;
736 if (mesh_->dimension() == 2)
737 {
738 if (gbases[0].bases.size() == 3)
739 autogen::p_nodes_2d(discr_order, local_pts);
740 else
741 autogen::q_nodes_2d(discr_order, local_pts);
742 }
743 else
744 {
745 if (gbases[0].bases.size() == 4)
746 autogen::p_nodes_3d(discr_order, local_pts);
747 else
748 autogen::q_nodes_3d(discr_order, local_pts);
749 }
750
751 std::vector<int> bnd_nodes;
752 bnd_nodes.reserve(boundary_.boundary_nodes.size() / std::max(1, mesh_->dimension()));
753 for (auto it = boundary_.boundary_nodes.begin(); it != boundary_.boundary_nodes.end(); ++it)
754 {
755 if (!(*it % mesh_->dimension()))
756 continue;
757 bnd_nodes.push_back(*it / mesh_->dimension());
758 }
759
760 const int n_el = int(space_.basis_list().size());
761 const int shape = gbases[0].bases.size();
762
763 auto fluid_assembler = std::dynamic_pointer_cast<assembler::OperatorSplitting>(primary_assembler_);
764 if (!fluid_assembler)
765 log_and_throw_error("Invalid assembler {}!", primary_assembler_ ? primary_assembler_->name() : name());
766 const double viscosity = fluid_assembler->viscosity()(0, 0, 0, 0, 0);
767 assert(viscosity >= 0);
768
769 logger().info("Matrices assembly...");
770 StiffnessMatrix stiffness_viscosity, mixed_stiffness, velocity_mass, pressure_stiffness;
771
772 assembler::Laplacian lapl_assembler;
773 lapl_assembler.set_size(1);
774 lapl_assembler.assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), gbases, ass_vals_cache_, 0, stiffness_viscosity);
775 mass_assembler_->set_size(1);
776 mass_assembler_->assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), gbases, mass_ass_vals_cache_, 0, mass_, true);
777
778 lapl_assembler.assemble(mesh_->is_volume(), pressure_space_.n_bases, pressure_space_.basis_list(), gbases, pressure_ass_vals_cache_, 0, pressure_stiffness);
779
780 mixed_assembler_->assemble(mesh_->is_volume(), pressure_space_.n_bases, space_.n_bases, pressure_space_.basis_list(), space_.basis_list(), gbases,
781 pressure_ass_vals_cache_, ass_vals_cache_, 0, mixed_stiffness);
782 mass_assembler_->set_size(mesh_->dimension());
783 mass_assembler_->assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), gbases, mass_ass_vals_cache_, 0, velocity_mass, true);
784 mixed_stiffness = mixed_stiffness.transpose();
785 logger().info("Matrices assembly ends!");
786
788 *mesh_, shape, n_el, boundary_.local_boundary, boundary_.boundary_nodes, pressure_boundary_.boundary_nodes, bnd_nodes, mass_,
789 stiffness_viscosity, pressure_stiffness, velocity_mass, dt, viscosity, args["solver"]["linear"]);
790
791 pressure = Eigen::MatrixXd::Zero(pressure_space_.n_bases, 1);
792
793 const QuadratureOrders boundary_samples = n_boundary_samples(space_.disc_orders.maxCoeff(), discr_order);
794 for (int t = 1; t <= time_steps; ++t)
795 {
796 const double time = t0 + t * dt;
797 logger().info("{}/{} steps, t={}s", t, time_steps, time);
798
799 logger().info("Advection...");
800 if (args["space"]["advanced"]["use_particle_advection"])
801 solver.advection_FLIP(*mesh_, gbases, space_.basis_list(), velocity, dt, local_pts);
802 else
803 solver.advection(*mesh_, gbases, space_.basis_list(), velocity, dt, local_pts);
804 logger().info("Advection finished!");
805
806 rhs_assembler_->set_bc(
807 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, velocity, Eigen::MatrixXd(), time);
808
809 logger().info("Solving diffusion...");
810 if (viscosity > 0)
811 solver.solve_diffusion_1st(mass_, bnd_nodes, velocity);
812 logger().info("Diffusion solved!");
813
814 solver.external_force(*mesh_, *primary_assembler_, gbases, space_.basis_list(), dt, velocity, local_pts, problem, time);
815
816 logger().info("Pressure projection...");
817 solver.solve_pressure(mixed_stiffness, pressure_boundary_.boundary_nodes, velocity, pressure);
818 solver.projection(space_.n_bases, gbases, space_.basis_list(), pressure_space_.basis_list(), local_pts, pressure, velocity);
819 logger().info("Pressure projection finished!");
820
821 pressure = pressure / dt;
822
823 rhs_assembler_->set_bc(
824 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, velocity, Eigen::MatrixXd(), time);
825
826 stack_solution(velocity, pressure, sol);
827 save_timestep(time, t, t0, dt, sol);
828 notify_time_step(t, time_steps, t0, dt);
829 }
830
831 timer.stop();
832 timings.solving_time = timer.getElapsedTime();
833 logger().info(" took {}s", timings.solving_time);
834 }
835} // namespace polyfem::varform
std::array< Matrix< int, 3, 3 >, 3 > space_
virtual void set_size(const int size)
Definition Assembler.hpp:66
static std::shared_ptr< MixedAssembler > make_mixed_assembler(const std::string &formulation)
static std::string other_assembler_name(const std::string &formulation)
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.
Eigen::Matrix< double, Eigen::Dynamic, 1, 0, 9, 1 > assemble(const LinearAssemblerData &data) const override
computes local stiffness matrix (1x1) for bases i,j where i,j is passed in through data ie integral o...
Definition Laplacian.cpp:62
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:1124
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)
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:1811
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:1856
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:1728
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:2099
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:41
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:401
int dimension() const
utily for dimension
Definition Mesh.hpp:153
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
void solve_pressure(const StiffnessMatrix &mixed_stiffness, const std::vector< int > &pressure_boundary_nodes, Eigen::MatrixXd &sol, Eigen::MatrixXd &pressure)
void projection(const StiffnessMatrix &velocity_mass, const StiffnessMatrix &mixed_stiffness, const std::vector< int > &boundary_nodes_, Eigen::MatrixXd &sol, const Eigen::MatrixXd &pressure)
void external_force(const mesh::Mesh &mesh, const assembler::Assembler &assembler, const std::vector< basis::ElementBases > &gbases, const std::vector< basis::ElementBases > &bases, const double dt, Eigen::MatrixXd &sol, const Eigen::MatrixXd &local_pts, const std::shared_ptr< assembler::Problem > problem, const double time)
void advection(const mesh::Mesh &mesh, const std::vector< basis::ElementBases > &gbases, const std::vector< basis::ElementBases > &bases, Eigen::MatrixXd &sol, const double dt, const Eigen::MatrixXd &local_pts, const int order=1, const int RK=1)
void advection_FLIP(const mesh::Mesh &mesh, const std::vector< basis::ElementBases > &gbases, const std::vector< basis::ElementBases > &bases, Eigen::MatrixXd &sol, const double dt, const Eigen::MatrixXd &local_pts, const int order=1)
void solve_diffusion_1st(const StiffnessMatrix &mass, const std::vector< int > &bnd_nodes, Eigen::MatrixXd &sol)
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
std::shared_ptr< assembler::Mass > mass_assembler_
void split_solution(const Eigen::MatrixXd &stacked, Eigen::MatrixXd &primary, Eigen::MatrixXd &pressure) const
void save_json(const Eigen::MatrixXd &solution, std::ostream &out) const override
Save the solution to a JSON file, for output purposes.
void prepare_initial_solution(Eigen::MatrixXd &sol) const
void export_data(const Eigen::MatrixXd &solution) const override
void build_basis(mesh::Mesh &mesh, const bool iso_parametric, const json &args) override
std::shared_ptr< assembler::MixedAssembler > mixed_assembler_
std::shared_ptr< assembler::Assembler > primary_assembler_
void assemble_rhs(const mesh::Mesh &mesh) override
std::shared_ptr< assembler::RhsAssembler > rhs_assembler_
std::shared_ptr< assembler::Assembler > pressure_assembler_
std::vector< io::OutputField > output_fields(const io::OutputSample &sample, const Eigen::MatrixXd &solution, const io::OutputFieldOptions &options) const override
Get the output fields of the variational formulation, for output purposes.
void stack_solution(const Eigen::MatrixXd &primary, const Eigen::MatrixXd &pressure, Eigen::MatrixXd &stacked) const
io::OutputSpace output_space() const override
Get the output space of the variational formulation, for output purposes.
void init(const std::string &formulation, const Units &units, const json &args, const std::string &out_path) override
Initialize the variational formulation with the given parameters.
std::string name() const override
Get the name of the variational formulation.
io::OutStatsData compute_errors(const Eigen::MatrixXd &solution) override
Get the error statistics of the variational formulation, for output purposes.
void load_mesh(const mesh::Mesh &mesh, const json &args) override
void assemble_mass_mat(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:1052
static void rebuild_node_positions(const std::vector< basis::ElementBases > &bases, const std::vector< int > &node_ids, std::vector< RowVectorNd > &positions)
Definition VarForm.cpp:1066
std::shared_ptr< assembler::Problem > problem
current problem, it contains rhs and bc
Definition VarForm.hpp:190
std::unique_ptr< mesh::Mesh > mesh_
Definition VarForm.hpp:202
io::OutStatsData stats
Definition VarForm.hpp:194
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:38
io::OutGeometryData::ExportOptions export_options(const io::OutputSpace &space) const
Definition VarForm.cpp:859
io::OutGeometryData output_geometry_
Definition VarForm.hpp:206
io::OutputFieldFunction output_field_function(const Eigen::MatrixXd &solution, const io::OutGeometryData::ExportOptions &opts) const
Definition VarForm.cpp:868
std::string resolve_output_path(const std::string &path) const
Definition VarForm.cpp:1057
void ensure_output_sampler() const
Definition VarForm.cpp:845
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:279
void build_fe_space(mesh::Mesh &mesh, const bool iso_parametric, const Eigen::VectorXi &disc_orders, 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:322
io::OutRuntimeData timings
runtime statistics
Definition VarForm.hpp:197
void set_materials(assembler::Assembler &assembler, const int size) const
Definition VarForm.cpp:830
virtual void reset()=0
Definition VarForm.cpp:267
void assign_discr_orders(const json &discr_order, const mesh::Mesh &mesh, Eigen::VectorXi &disc_orders)
Definition VarForm.cpp:744
str func
Definition p_bases.py:417
void q_nodes_2d(const int q, Eigen::MatrixXd &val)
void p_nodes_2d(const int p, Eigen::MatrixXd &val)
void p_nodes_3d(const int p, Eigen::MatrixXd &val)
void q_nodes_3d(const int q, Eigen::MatrixXd &val)
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::MatrixXd unflatten(const Eigen::VectorXd &x, int dim)
Unflatten rowwises, so every dim elements in x become a row.
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:51
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