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{
24 const Eigen::MatrixXd &solution,
25 const io::CheckpointMetadata &metadata) const
26 {
27 VarForm::serialize_checkpoint(writer, solution, metadata);
28 write_checkpoint_ordering(writer, "primary", space_);
29 write_checkpoint_ordering(writer, "pressure", pressure_space_);
30 Eigen::MatrixXd velocity, pressure;
31 split_solution(solution, velocity, pressure);
32 writer.write_matrix("/checkpoint/state/velocity", velocity);
33 writer.write_matrix("/checkpoint/state/pressure", pressure);
34 }
35
37 const io::CheckpointReader &reader,
38 Eigen::MatrixXd &solution)
39 {
40 VarForm::deserialize_checkpoint(reader, solution);
42 for (const std::string &path : {
43 "/checkpoint/state/velocity", "/checkpoint/state/pressure"})
44 if (!reader.exists(path))
45 log_and_throw_error("Operator-splitting checkpoint is missing {}.", path);
46
47 Eigen::MatrixXd velocity = reader.read_matrix("/checkpoint/state/velocity");
48 Eigen::MatrixXd pressure = reader.read_matrix("/checkpoint/state/pressure");
49 if (velocity.rows() != primary_ndof() || velocity.cols() != 1)
50 log_and_throw_error("Operator-splitting checkpoint velocity has invalid dimensions.");
51 if (pressure.rows() != pressure_space_.n_bases || pressure.cols() != 1)
52 log_and_throw_error("Operator-splitting checkpoint pressure has invalid dimensions.");
53 if (!solution.topRows(primary_ndof()).isApprox(velocity)
54 || !solution.middleRows(primary_ndof(), pressure_space_.n_bases).isApprox(pressure))
55 log_and_throw_error("Operator-splitting checkpoint contains inconsistent solution blocks.");
56
57 reorder_checkpoint_block(reader, "primary", space_, mesh_->dimension(), 0, velocity);
58 reorder_checkpoint_block(reader, "pressure", pressure_space_, 1, 0, pressure);
59 solution.topRows(primary_ndof()) = velocity;
60 solution.middleRows(primary_ndof(), pressure_space_.n_bases) = pressure;
61 }
62
63 using namespace varform::internal;
64
66 {
68 space_.reset();
75 rhs_assembler_ = nullptr;
76 mass_.resize(0, 0);
77 rhs_.resize(0, 0);
78 primary_assembler_ = nullptr;
79 mass_assembler_ = nullptr;
80 mixed_assembler_ = nullptr;
81 pressure_assembler_ = nullptr;
82 use_avg_pressure = true;
83 avg_mass_ = 0;
84 t0 = 0;
85 time_steps = 0;
86 dt = 0;
87 }
88
89 void OperatorSplittingVarForm::init(const std::string &formulation, const Units &units, const json &args, const std::string &out_path)
90 {
91 VarForm::init(formulation, units, args, out_path);
92 const bool is_time_dependent = args.contains("time") && !args["time"].is_null();
93
95 mass_assembler_ = std::make_shared<assembler::Mass>();
98
99 if (!args.contains("preset_problem"))
100 {
101 problem = std::make_shared<assembler::GenericTensorProblem>("GenericTensor");
102 problem->clear();
103
104 json tmp;
105 tmp["is_time_dependent"] = is_time_dependent;
106 problem->set_parameters(tmp, resources_);
107
108 auto bc = args["boundary_conditions"];
109 problem->set_parameters(bc, resources_);
110 problem->set_parameters(args["initial_conditions"], resources_);
111 problem->set_parameters(args["output"], resources_);
112 }
113 else
114 {
115 if (args["preset_problem"]["type"] == "Kernel")
116 {
117 problem = std::make_shared<problem::KernelProblem>("Kernel", *primary_assembler_);
118 problem->clear();
119 }
120 else
121 {
122 problem = problem::ProblemFactory::factory().get_problem(args["preset_problem"]["type"]);
123 problem->clear();
124 }
125 problem->set_parameters(args["preset_problem"], resources_);
126 }
127
128 problem->set_units(*primary_assembler_, units);
129
130 t0 = is_time_dependent ? args["time"]["t0"].get<double>() : 0.0;
131 time_steps = is_time_dependent ? args["time"]["time_steps"].get<int>() : 0;
132 dt = is_time_dependent ? args["time"]["dt"].get<double>() : 0.0;
133
134 assert(primary_assembler_);
135 assert(primary_assembler_->name() == "OperatorSplitting");
136 }
137
138 void OperatorSplittingVarForm::save_json(const Eigen::MatrixXd &solution, std::ostream &out) const
139 {
140 if (!mesh_)
141 {
142 logger().error("Load the mesh first!");
143 return;
144 }
145 if (solution.size() <= 0)
146 {
147 logger().error("Solve the problem first!");
148 return;
149 }
150
151 logger().info("Saving json...");
152 const int primary_size = primary_ndof();
153 const Eigen::MatrixXd stats_solution =
154 solution.rows() >= primary_size
155 ? solution.topRows(primary_size).eval()
156 : solution;
157
158 nlohmann::json j;
161 stats_solution, *mesh_, space_.disc_orders, space_.disc_ordersq, *problem,
163 args["output"]["advanced"]["sol_at_node"], j);
164 out << j.dump(4) << std::endl;
165 }
166
168 {
169 Eigen::VectorXi output_orders = space_.disc_orders;
170 if (mesh_ && space_.disc_ordersq.size() == space_.disc_orders.size())
171 {
172 for (int e = 0; e < output_orders.size(); ++e)
173 {
174 if (mesh_->is_prism(e))
175 output_orders(e) = std::max(space_.disc_orders(e), space_.disc_ordersq(e));
176 }
177 }
178
179 return {
180 mesh_.get(),
182 output_orders,
183 &space_.polys,
186 nullptr,
187 nullptr,
190 }
191
193 {
194 if (!args["output"]["advanced"]["compute_error"])
195 return stats;
196
197 double tend = 0;
198 if (args.contains("time") && !args["time"].is_null())
199 {
200 if (args["time"].contains("tend"))
201 tend = args["time"]["tend"].get<double>();
202 else
203 tend = t0 + dt * time_steps;
204 }
205
206 Eigen::MatrixXd velocity, pressure;
207 split_solution(solution, velocity, pressure);
209 return stats;
210 }
211
212 void OperatorSplittingVarForm::export_data(const Eigen::MatrixXd &solution) const
213 {
214 const io::OutputSpace space = output_space();
215 if (!space.mesh)
216 {
217 logger().error("Load the mesh first!");
218 return;
219 }
220 if (solution.size() <= 0)
221 {
222 logger().error("Solve the problem first!");
223 return;
224 }
225
227
228 const std::string vis_mesh_path = resolve_output_path(args["output"]["paraview"]["file_name"]);
229 const bool has_time = args.contains("time") && !args["time"].is_null();
230 double tend = 1.0;
231 if (has_time)
232 {
233 if (args["time"].contains("tend"))
234 tend = args["time"]["tend"].get<double>();
235 else
236 tend = t0 + dt * time_steps;
237 }
238 double local_dt = 1;
239 if (has_time)
240 local_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, local_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
306 {
307 (void)args;
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
327
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,
345 args["space"]["advanced"]["bc_method"],
346 rhs_solver_params,
347 /*fe_space_id=*/-1);
348 }
349
350 void OperatorSplittingVarForm::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
356 Eigen::VectorXi space_disc_orders, space_disc_ordersq;
357 assign_discr_orders(args["space"], mesh, space_disc_orders, space_disc_ordersq);
358
359 if (args["space"]["use_p_ref"])
360 {
362 mesh,
363 args["space"]["advanced"]["B"],
364 args["space"]["advanced"]["h1_formula"],
365 args["space"]["discr_order"],
366 args["space"]["advanced"]["discr_order_max"],
367 stats,
368 space_disc_orders);
369
370 logger().info("min p: {} max p: {}", space_disc_orders.minCoeff(), space_disc_orders.maxCoeff());
371 }
372
374 mesh,
375 iso_parametric,
376 space_disc_orders,
377 space_disc_ordersq,
378 args["space"]["basis_type"],
379 args["space"]["poly_basis_type"],
381 mesh.dimension(),
382 args["space"]["advanced"]["quadrature_order"],
383 args["space"]["advanced"]["mass_quadrature_order"],
384 args["space"]["advanced"]["use_corner_quadrature"],
385 args["space"]["advanced"]["n_harmonic_samples"],
386 args["space"]["advanced"]["integral_constraints"],
387 space_,
388 boundary_);
389
390 problem->update_nodes(space_.space_in_node_to_node);
392
393 const auto &current_bases = space_.geometry_basis_list();
394 if (args["space"]["advanced"]["count_flipped_els"])
395 stats.count_flipped_elements(mesh, current_bases);
396
397 const int n_samples = 10;
398 stats.compute_mesh_size(mesh, current_bases, n_samples, args["output"]["advanced"]["curved_mesh_size"]);
399
400 logger().info("flipped elements {}", stats.n_flipped);
401 logger().info("h: {}", stats.mesh_size);
402
403 if (space_.disc_orders.maxCoeff() != space_.disc_orders.minCoeff())
404 log_and_throw_error("p refinement not supported in operator splitting!");
405 if (!space_.poly_edge_to_data.empty())
406 log_and_throw_error("Polygonal bases are not supported in operator splitting!");
407
408 if (space_.n_bases <= args["solver"]["advanced"]["cache_size"])
409 {
410 igl::Timer cache_timer;
411 cache_timer.start();
412 logger().info("Building cache...");
413 ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases);
414 mass_ass_vals_cache_.init(mesh.is_volume(), space_.basis_list(), current_bases, true);
415 logger().info(" took {}s", cache_timer.getElapsedTime());
416 }
417 else
418 {
421 }
422
423 const auto &all_boundary = boundary_.total_local_boundary;
424 const int prev_bases = space_.n_bases;
425 const int prev_b_size = int(all_boundary.size());
426 const bool use_corner_quadrature = args["space"]["advanced"]["use_corner_quadrature"];
427 const int quadrature_order = args["space"]["advanced"]["quadrature_order"].get<int>();
428 const int mass_quadrature_order = args["space"]["advanced"]["mass_quadrature_order"].get<int>();
429 Eigen::VectorXi pressure_disc_orders, pressure_disc_ordersq;
430 assign_discr_orders(args["space"], mesh, pressure_disc_orders, pressure_disc_ordersq);
431 const std::string pressure_basis_type = args["space"]["basis_type"].get<std::string>() == "Bernstein" ? "Bernstein" : "Lagrange";
433 mesh,
434 /*iso_parametric=*/true,
435 pressure_disc_orders,
436 pressure_disc_ordersq,
437 pressure_basis_type,
438 args["space"]["poly_basis_type"],
440 /*value_dim=*/1,
441 quadrature_order,
442 mass_quadrature_order,
443 use_corner_quadrature,
444 args["space"]["advanced"]["n_harmonic_samples"],
445 args["space"]["advanced"]["integral_constraints"],
449
450 assert(space_.basis_list().size() == pressure_space_.basis_list().size());
451 for (int i = 0; i < int(pressure_space_.basis_list().size()); ++i)
452 {
454 space_.basis_list()[i].compute_quadrature(b_quad);
455 (*pressure_space_.bases)[i].set_quadrature([b_quad](quadrature::Quadrature &quad) { quad = b_quad; });
456 }
457
459 for (const auto &lb : all_boundary)
460 boundary_.local_boundary.emplace_back(lb);
462
463 problem->setup_bc(
464 mesh, space_.n_bases,
474
477
478 const bool has_neumann = !boundary_.local_neumann_boundary.empty() || int(boundary_.local_boundary.size()) < prev_b_size;
479 use_avg_pressure = !has_neumann;
480
481 for (int i = prev_bases; i < space_.n_bases; ++i)
482 for (int d = 0; d < mesh.dimension(); ++d)
483 boundary_.boundary_nodes.push_back(i * mesh.dimension() + d);
484
486
487 if (space_.n_bases <= args["solver"]["advanced"]["cache_size"])
489 else
491
493
494 logger().info("n pressure bases: {}", pressure_space_.n_bases);
495 }
496
498 {
500
501 igl::Timer timer;
502 json p_params = {};
503 p_params["formulation"] = primary_assembler_->name();
504 {
505 RowVectorNd min, max, delta;
506 mesh.bounding_box(min, max);
507 delta = (max - min) / 2. + min;
508 if (mesh.is_volume())
509 p_params["bbox_center"] = {delta(0), delta(1), delta(2)};
510 else
511 p_params["bbox_center"] = {delta(0), delta(1)};
512 }
513 problem->set_parameters(p_params, resources_);
514
515 rhs_.resize(0, 0);
516
517 timer.start();
518 logger().info("Assigning rhs...");
519
520 assert(rhs_assembler_ != nullptr);
521 rhs_assembler_->assemble(mass_assembler_->density(), rhs_);
522 rhs_ *= -1;
523
524 const int prev_size = rhs_.rows();
525 rhs_.conservativeResize(prev_size + pressure_block_size(), rhs_.cols());
526 rhs_.bottomRows(pressure_block_size()).setZero();
527
528 timer.stop();
529 timings.assigning_rhs_time = timer.getElapsedTime();
530 logger().info(" took {}s", timings.assigning_rhs_time);
531 }
532
534 {
535 (void)mesh;
536 (void)args;
537 mass_.resize(0, 0);
538 avg_mass_ = 1;
540 }
541
543 {
544 if (sol.size() <= 0)
545 {
546 assert(rhs_assembler_ != nullptr);
547 if (problem->is_time_dependent())
548 rhs_assembler_->initial_solution(sol);
549 else
550 {
551 sol.resize(rhs_.size(), 1);
552 sol.setZero();
553 }
554 }
555 if (sol.cols() > 1)
556 sol.conservativeResize(Eigen::NoChange, 1);
557 sol.conservativeResize(stacked_ndof(), sol.cols());
558 sol.bottomRows(pressure_block_size()).setZero();
559 }
560
561 void OperatorSplittingVarForm::split_solution(const Eigen::MatrixXd &stacked, Eigen::MatrixXd &primary, Eigen::MatrixXd &pressure) const
562 {
563 const int cols = std::max(1, int(stacked.cols()));
564 primary.setZero(primary_ndof(), cols);
565 pressure.setZero(pressure_space_.n_bases, cols);
566
567 const int primary_rows = std::min(primary_ndof(), int(stacked.rows()));
568 if (primary_rows > 0)
569 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
570
571 if (stacked.rows() > primary_ndof())
572 {
573 const int pressure_rows = std::min(pressure_space_.n_bases, int(stacked.rows()) - primary_ndof());
574 if (pressure_rows > 0)
575 pressure.topRows(pressure_rows) = stacked.middleRows(primary_ndof(), pressure_rows);
576 }
577 }
578
579 void OperatorSplittingVarForm::stack_solution(const Eigen::MatrixXd &primary, const Eigen::MatrixXd &pressure, Eigen::MatrixXd &stacked) const
580 {
581 const int cols = std::max(primary.cols(), pressure.cols());
582 stacked.resize(stacked_ndof(), cols);
583 stacked.setZero();
584
585 const int primary_rows = std::min(primary_ndof(), int(primary.rows()));
586 if (primary_rows > 0)
587 stacked.topRows(primary_rows) = primary.topRows(primary_rows);
588
589 const int pressure_rows = std::min(pressure_space_.n_bases, int(pressure.rows()));
590 if (pressure_rows > 0)
591 stacked.middleRows(primary_ndof(), pressure_rows) = pressure.topRows(pressure_rows);
592 }
593
594 std::vector<io::OutputField> OperatorSplittingVarForm::output_fields(
595 const io::OutputSample &sample,
596 const Eigen::MatrixXd &solution,
597 const io::OutputFieldOptions &options) const
598 {
599 std::vector<io::OutputField> fields;
600 if (!mesh_ || !problem || solution.size() <= 0)
601 return fields;
602
603 Eigen::MatrixXd velocity, pressure;
604 split_solution(solution, velocity, pressure);
605
606 const int field_dim = mesh_->dimension();
607 const bool has_element_samples = sample.local_points.rows() > 0 && sample.local_points.rows() == sample.element_ids.size();
608 const int output_rows = sample.points.rows() > 0 ? sample.points.rows() : std::max<int>(sample.local_points.rows(), sample.node_ids.size());
609 const bool export_solution_gradient =
610 !options.fields.empty() && options.export_field("solution_gradient");
611 const bool export_pressure_gradient =
612 !options.fields.empty() && options.export_field("pressure_gradient");
613
614 const auto resize_to_output_rows = [&](Eigen::MatrixXd &values) {
615 if (output_rows <= values.rows())
616 return;
617
618 const int previous_rows = values.rows();
619 values.conservativeResize(output_rows, values.cols());
620 values.bottomRows(output_rows - previous_rows).setZero();
621 };
622
623 const auto sample_vector_field = [&](const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients = nullptr) -> bool {
624 if (dof_values.size() <= 0 || field_dim <= 0)
625 return false;
626
627 if (has_element_samples)
628 {
629 values.resize(sample.local_points.rows(), field_dim);
630 if (gradients)
631 gradients->resize(sample.local_points.rows(), field_dim * mesh_->dimension());
632 for (int i = 0; i < sample.local_points.rows(); ++i)
633 {
634 const int element_id = sample.element_ids(i);
635 if (element_id < 0)
636 {
637 values.row(i).setZero();
638 if (gradients)
639 gradients->row(i).setZero();
640 continue;
641 }
642
643 Eigen::MatrixXd local_sol, local_grad;
646 element_id, sample.local_points.row(i), dof_values, local_sol, local_grad);
647
648 for (int d = 0; d < field_dim; ++d)
649 values(i, d) = local_sol(d);
650 if (gradients)
651 gradients->row(i) = local_grad;
652 }
653
654 resize_to_output_rows(values);
655 if (gradients)
656 resize_to_output_rows(*gradients);
657 return true;
658 }
659
660 if (sample.node_ids.size() > 0)
661 {
662 values.resize(sample.node_ids.size(), field_dim);
663 for (int i = 0; i < sample.node_ids.size(); ++i)
664 {
665 const int node_id = sample.node_ids(i);
666 for (int d = 0; d < field_dim; ++d)
667 {
668 const int dof = node_id * field_dim + d;
669 if (dof < 0 || dof >= dof_values.rows())
670 return false;
671 values(i, d) = dof_values(dof);
672 }
673 }
674 return sample.points.rows() == 0 || sample.points.rows() == values.rows();
675 }
676
677 return false;
678 };
679
680 Eigen::MatrixXd velocity_values, velocity_gradients;
681 const bool sampled_velocity = sample_vector_field(
682 velocity, velocity_values,
683 export_solution_gradient ? &velocity_gradients : nullptr);
684 if (sampled_velocity && options.export_field("velocity"))
685 fields.push_back({"velocity", velocity_values, io::OutputField::Association::Point});
686 if (sampled_velocity && options.export_field("solution"))
687 fields.push_back({"solution", velocity_values, io::OutputField::Association::Point});
688 if (sampled_velocity && export_solution_gradient)
689 fields.push_back({"solution_gradient", velocity_gradients, io::OutputField::Association::Point});
690
691 if (mesh_ && (options.export_field("pressure") || export_pressure_gradient))
692 {
693 Eigen::MatrixXd values, gradients;
694 if (sample_scalar_field(
695 *mesh_, pressure_space_.basis_list(), space_.geometry_basis_list(), sample, pressure, values,
696 export_pressure_gradient ? &gradients : nullptr))
697 {
698 if (options.export_field("pressure"))
699 fields.push_back({"pressure", values, io::OutputField::Association::Point});
700 if (export_pressure_gradient)
701 fields.push_back({"pressure_gradient", gradients, io::OutputField::Association::Point});
702 }
703 }
704
705 const auto &paraview_options = args["output"]["paraview"]["options"];
706 if (paraview_options["material"] && has_element_samples)
707 {
708 const auto &params = primary_assembler_->parameters();
709 std::map<std::string, Eigen::MatrixXd> param_values;
710 for (const auto &[p, _] : params)
711 param_values[p].setZero(output_rows, 1);
712
713 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
714 const auto &density = mass_assembler_->density();
715 for (int i = 0; i < sample.local_points.rows(); ++i)
716 {
717 const int element_id = sample.element_ids(i);
718 if (element_id < 0)
719 continue;
720
721 for (const auto &[p, func] : params)
722 param_values.at(p)(i) = func(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
723 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
724 }
725
726 for (const auto &[field_name, values] : param_values)
727 if (options.export_field(field_name))
728 fields.push_back({field_name, values, io::OutputField::Association::Point});
729 if (options.export_field("rho"))
730 fields.push_back({"rho", rhos, io::OutputField::Association::Point});
731 }
732
733 if (paraview_options["body_ids"] && options.export_field("body_ids") && has_element_samples)
734 {
735 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
736 for (int i = 0; i < sample.element_ids.size(); ++i)
737 {
738 const int element_id = sample.element_ids(i);
739 if (element_id >= 0)
740 ids(i) = mesh_->get_body_id(element_id);
741 }
742 fields.push_back({"body_ids", ids, io::OutputField::Association::Point});
743 }
744
745 return fields;
746 }
747
748 void OperatorSplittingVarForm::solve_problem(
749 Eigen::MatrixXd &sol,
750 const InitialConditionOverride *initial_condition_override,
751 const ForwardStepCallback &post_step)
752 {
753 assert(!initial_condition_override && "Operator splitting does not support initial-condition overrides");
754 assert(!post_step && "Operator splitting does not support post-step callbacks");
755
756 stats.spectrum.setZero();
757
758 if (!problem->is_time_dependent())
759 log_and_throw_error("Operator splitting requires a transient problem.");
760
761 igl::Timer timer;
762 timer.start();
763 logger().info("Solving {}", primary_assembler_->name());
764
765 prepare_initial_solution(sol);
766
767 Eigen::MatrixXd velocity, pressure;
768 split_solution(sol, velocity, pressure);
769 stack_solution(velocity, pressure, sol);
770 save_timestep(t0, 0, t0, dt, sol);
771
772 Eigen::MatrixXd local_pts;
773 const auto &gbases = space_.geometry_basis_list();
774 assert(space_.disc_orders.size() > 0 && "Operator splitting requires initialized FE orders");
775 const int discr_order = space_.disc_orders.maxCoeff();
776 if (mesh_->dimension() == 2)
777 {
778 if (gbases[0].bases.size() == 3)
779 autogen::p_nodes_2d(discr_order, local_pts);
780 else
781 autogen::q_nodes_2d(discr_order, local_pts);
782 }
783 else
784 {
785 if (gbases[0].bases.size() == 4)
786 autogen::p_nodes_3d(discr_order, local_pts);
787 else
788 autogen::q_nodes_3d(discr_order, local_pts);
789 }
790
791 std::vector<int> bnd_nodes;
792 bnd_nodes.reserve(boundary_.boundary_nodes.size() / std::max(1, mesh_->dimension()));
793 for (auto it = boundary_.boundary_nodes.begin(); it != boundary_.boundary_nodes.end(); ++it)
794 {
795 if (!(*it % mesh_->dimension()))
796 continue;
797 bnd_nodes.push_back(*it / mesh_->dimension());
798 }
799
800 const int n_el = int(space_.basis_list().size());
801 const int shape = gbases[0].bases.size();
802
803 auto fluid_assembler = std::dynamic_pointer_cast<assembler::OperatorSplitting>(primary_assembler_);
804 if (!fluid_assembler)
805 log_and_throw_error("Invalid assembler {}!", primary_assembler_ ? primary_assembler_->name() : name());
806 const double viscosity = fluid_assembler->viscosity()(0, 0, 0, 0, 0);
807 assert(viscosity >= 0);
808
809 logger().info("Matrices assembly...");
810 StiffnessMatrix stiffness_viscosity, mixed_stiffness, velocity_mass, pressure_stiffness;
811
812 assembler::Laplacian lapl_assembler;
813 lapl_assembler.set_size(1);
814 lapl_assembler.assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), gbases, ass_vals_cache_, 0, stiffness_viscosity);
815 mass_assembler_->set_size(1);
816 mass_assembler_->assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), gbases, mass_ass_vals_cache_, 0, mass_, true);
817
818 lapl_assembler.assemble(mesh_->is_volume(), pressure_space_.n_bases, pressure_space_.basis_list(), gbases, pressure_ass_vals_cache_, 0, pressure_stiffness);
819
820 mixed_assembler_->assemble(mesh_->is_volume(), pressure_space_.n_bases, space_.n_bases, pressure_space_.basis_list(), space_.basis_list(), gbases,
821 pressure_ass_vals_cache_, ass_vals_cache_, 0, mixed_stiffness);
822 mass_assembler_->set_size(mesh_->dimension());
823 mass_assembler_->assemble(mesh_->is_volume(), space_.n_bases, space_.basis_list(), gbases, mass_ass_vals_cache_, 0, velocity_mass, true);
824 mixed_stiffness = mixed_stiffness.transpose();
825 logger().info("Matrices assembly ends!");
826
828 *mesh_, shape, n_el, boundary_.local_boundary, boundary_.boundary_nodes, pressure_boundary_.boundary_nodes, bnd_nodes, mass_,
829 stiffness_viscosity, pressure_stiffness, velocity_mass, dt, viscosity, args["solver"]["linear"]);
830
831 const QuadratureOrders boundary_samples = n_boundary_samples(space_.disc_orders.maxCoeff(), space_.disc_ordersq.maxCoeff(), discr_order);
832 for (int t = 1; t <= time_steps; ++t)
833 {
834 const double time = t0 + t * dt;
835 logger().info("{}/{} steps, t={}s", t, time_steps, time);
836
837 logger().info("Advection...");
838 if (args["space"]["advanced"]["use_particle_advection"])
839 solver.advection_FLIP(*mesh_, gbases, space_.basis_list(), velocity, dt, local_pts);
840 else
841 solver.advection(*mesh_, gbases, space_.basis_list(), velocity, dt, local_pts);
842 logger().info("Advection finished!");
843
844 rhs_assembler_->set_bc(
845 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, velocity, Eigen::MatrixXd(), time);
846
847 logger().info("Solving diffusion...");
848 if (viscosity > 0)
849 solver.solve_diffusion_1st(mass_, bnd_nodes, velocity);
850 logger().info("Diffusion solved!");
851
852 solver.external_force(*mesh_, *primary_assembler_, gbases, space_.basis_list(), dt, velocity, local_pts, problem, time);
853
854 logger().info("Pressure projection...");
855 solver.solve_pressure(mixed_stiffness, pressure_boundary_.boundary_nodes, velocity, pressure);
856 solver.projection(space_.n_bases, gbases, space_.basis_list(), pressure_space_.basis_list(), local_pts, pressure, velocity);
857 logger().info("Pressure projection finished!");
858
859 pressure = pressure / dt;
860
861 rhs_assembler_->set_bc(
862 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, velocity, Eigen::MatrixXd(), time);
863
864 stack_solution(velocity, pressure, sol);
865 save_timestep(time, t, t0, dt, sol);
866 save_step_state(t0, dt, t, sol, nullptr);
867 notify_time_step(t, time_steps, t0, dt);
868 }
869
870 timer.stop();
871 timings.solving_time = timer.getElapsedTime();
872 logger().info(" took {}s", timings.solving_time);
873 }
874} // namespace polyfem::varform
std::array< Matrix< int, 3, 3 >, 3 > space_
virtual void set_size(const int size)
Definition Assembler.hpp:67
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).
Eigen::MatrixXd read_matrix(const std::string &path) const
bool exists(const std::string &path) const
void write_matrix(const std::string &path, const Eigen::MatrixXd &value)
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 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: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
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
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_
void deserialize_checkpoint(const io::CheckpointReader &reader, Eigen::MatrixXd &solution) override
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
void serialize_checkpoint(io::CheckpointWriter &writer, const Eigen::MatrixXd &solution, const io::CheckpointMetadata &metadata) const override
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
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
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
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:43
Eigen::MatrixXd unflatten(const Eigen::VectorXd &x, int dim)
Unflatten rowwises, so every dim elements in x become a row.
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