29#include <polysolve/linear/FEMSolver.hpp>
30#include <polysolve/nonlinear/Solver.hpp>
34 using namespace varform::internal;
38 const Eigen::MatrixXd &solution,
48 Eigen::MatrixXd &solution)
54 mesh_->dimension(), 0, solution);
92 for (
const std::string field : {
"pressure_boundary",
"pressure_cavity"})
94 const json::json_pointer path(
"/boundary_conditions/" + field);
95 if (
args.contains(path) && !
args.at(path).empty())
100 const bool is_time_dependent =
args.contains(
"time") && !
args[
"time"].is_null();
101 const json &discr_orders =
args.at(
"space").at(
"discr_order");
103 const json &materials =
args.at(
"materials");
104 if (materials.is_array() && materials.empty())
106 const json &first_material = materials.is_array() ? materials.at(0) : materials;
112 if (discr_orders.is_array())
114 bool has_velocity_space =
false;
115 bool has_pressure_space =
false;
116 for (
const json &entry : discr_orders)
118 const int fe_space_id = entry.at(
"fe_space").get<
int>();
122 if (!has_velocity_space || !has_pressure_space)
123 log_and_throw_error(
"Fluid discretization-order lists must explicitly name the velocity and pressure FE spaces.");
126 if (materials.is_array())
128 for (
const json &material : materials)
132 log_and_throw_error(
"All fluid materials must use the same velocity and pressure FE space IDs.");
142 if (!
args.contains(
"preset_problem"))
144 problem = std::make_shared<assembler::GenericTensorProblem>(
"GenericTensor");
148 tmp[
"is_time_dependent"] = is_time_dependent;
151 auto bc =
args[
"boundary_conditions"];
158 if (
args[
"preset_problem"][
"type"] ==
"Kernel")
173 t0 = is_time_dependent ?
args[
"time"][
"t0"].get<
double>() : 0.0;
174 time_steps = is_time_dependent ?
args[
"time"][
"time_steps"].get<
int>() : 0;
175 dt = is_time_dependent ?
args[
"time"][
"dt"].get<
double>() : 0.0;
184 logger().error(
"Load the mesh first!");
187 if (solution.size() <= 0)
189 logger().error(
"Solve the problem first!");
193 logger().info(
"Saving json...");
195 const Eigen::MatrixXd stats_solution =
196 solution.rows() >= primary_size
197 ? solution.topRows(primary_size).eval()
205 args[
"output"][
"advanced"][
"sol_at_node"], j);
206 out << j.dump(4) << std::endl;
214 for (
int e = 0; e < output_orders.size(); ++e)
216 if (
mesh_->is_prism(e))
237 if (!
args[
"output"][
"advanced"][
"compute_error"])
241 if (!
args[
"time"].is_null())
242 tend =
args[
"time"][
"tend"];
244 Eigen::MatrixXd velocity, pressure;
255 logger().error(
"Load the mesh first!");
258 if (solution.size() <= 0)
260 logger().error(
"Solve the problem first!");
267 const bool has_time =
args.contains(
"time") && !
args[
"time"].is_null();
268 double tend = has_time ?
args[
"time"][
"tend"].get<
double>() : 1.0;
282 Eigen::MatrixXd velocity, pressure;
286 if (!solution_path.empty())
288 const int primary_rows = std::min<int>(velocity.rows(),
primary_ndof());
289 const Eigen::MatrixXd primary_solution = velocity.topRows(primary_rows);
293 Eigen::MatrixXd reordered = Eigen::MatrixXd::Zero(nodal_solution.rows(), nodal_solution.cols());
297 if (node >= 0 && node < nodal_solution.rows() && input_node < reordered.rows())
298 reordered.row(input_node) = nodal_solution.row(node);
309 if (!nodes_path.empty())
314 for (
const auto &global : basis.global())
315 nodes.row(global.index) = global.node;
323 Eigen::MatrixXd stress;
324 Eigen::VectorXd mises;
329 if (!stress_path.empty())
331 if (!mises_path.empty())
366 json rhs_solver_params =
args[
"solver"][
"linear"];
367 if (!rhs_solver_params.contains(
"Pardiso"))
368 rhs_solver_params[
"Pardiso"] = {};
369 rhs_solver_params[
"Pardiso"][
"mtype"] = -2;
376 args[
"space"][
"advanced"][
"bc_method"],
388 Eigen::VectorXi space_disc_orders, space_disc_ordersq;
391 if (
args[
"space"][
"use_p_ref"])
395 args[
"space"][
"advanced"][
"B"],
396 args[
"space"][
"advanced"][
"h1_formula"],
397 args[
"space"][
"discr_order"],
398 args[
"space"][
"advanced"][
"discr_order_max"],
402 logger().info(
"min p: {} max p: {}", space_disc_orders.minCoeff(), space_disc_orders.maxCoeff());
410 args[
"space"][
"basis_type"],
411 args[
"space"][
"poly_basis_type"],
414 args[
"space"][
"advanced"][
"quadrature_order"],
415 args[
"space"][
"advanced"][
"mass_quadrature_order"],
416 args[
"space"][
"advanced"][
"use_corner_quadrature"],
417 args[
"space"][
"advanced"][
"n_harmonic_samples"],
418 args[
"space"][
"advanced"][
"integral_constraints"],
425 if (
args[
"space"][
"advanced"][
"count_flipped_els"])
428 const int n_samples = 10;
441 igl::Timer cache_timer;
443 logger().info(
"Building cache...");
447 logger().info(
" took {}s", cache_timer.getElapsedTime());
458 const int prev_b_size = int(all_boundary.size());
459 const bool use_corner_quadrature =
args[
"space"][
"advanced"][
"use_corner_quadrature"];
460 const int quadrature_order =
args[
"space"][
"advanced"][
"quadrature_order"].get<
int>();
461 const int mass_quadrature_order =
args[
"space"][
"advanced"][
"mass_quadrature_order"].get<
int>();
462 Eigen::VectorXi pressure_disc_orders, pressure_disc_ordersq;
465 const std::string pressure_basis_type =
args[
"space"][
"basis_type"].get<std::string>() ==
"Bernstein" ?
"Bernstein" :
"Lagrange";
469 pressure_disc_orders,
470 pressure_disc_ordersq,
472 args[
"space"][
"poly_basis_type"],
476 mass_quadrature_order,
477 use_corner_quadrature,
478 args[
"space"][
"advanced"][
"n_harmonic_samples"],
479 args[
"space"][
"advanced"][
"integral_constraints"],
509 for (
int d = 0; d < mesh.
dimension(); ++d)
521 for (
int d = 0; d < mesh.
dimension(); ++d)
546 delta = (max - min) / 2. + min;
548 p_params[
"bbox_center"] = {delta(0), delta(1), delta(2)};
550 p_params[
"bbox_center"] = {delta(0), delta(1)};
557 logger().info(
"Assigning rhs...");
566 const int prev_size =
rhs_.rows();
573 if (!
problem->is_time_dependent())
585 logger().info(
"Assembling mass mat...");
592 std::vector<Eigen::Triplet<double>> blocks;
593 blocks.reserve(velocity_mass.nonZeros());
594 for (
int k = 0; k < velocity_mass.outerSize(); ++k)
595 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
596 blocks.emplace_back(it.row(), it.col(), it.value());
599 mass_.setFromTriplets(blocks.begin(), blocks.end());
600 mass_.makeCompressed();
603 for (
int k = 0; k < velocity_mass.outerSize(); ++k)
604 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
606 assert(it.col() == k);
609 avg_mass_ /= std::max(1,
int(velocity_mass.rows()));
612 if (
args[
"solver"][
"advanced"][
"lump_mass_matrix"])
630 if (
problem->is_time_dependent())
634 sol.resize(
rhs_.size(), 1);
639 sol.conservativeResize(Eigen::NoChange, 1);
646 const int cols = std::max(1,
int(stacked.cols()));
650 const int primary_rows = std::min(
primary_ndof(),
int(stacked.rows()));
651 if (primary_rows > 0)
652 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
657 if (pressure_rows > 0)
658 pressure.topRows(pressure_rows) = stacked.middleRows(
primary_ndof(), pressure_rows);
666 logger().info(
"Assembling stiffness mat...");
668 StiffnessMatrix velocity_stiffness, mixed_stiffness, pressure_stiffness;
675 velocity_stiffness, mixed_stiffness, pressure_stiffness, stiffness);
683 stats.
mat_size = (
long long)stiffness.rows() * (
long long)stiffness.cols();
690 const std::unique_ptr<polysolve::linear::Solver> &solver,
693 const bool compute_spectrum,
694 Eigen::MatrixXd &sol)
704 args[
"output"][
"data"][
"stiffness_mat"],
712 const double error = (A *
x - b).norm();
714 logger().error(
"Solver error: {}", error);
716 logger().debug(
"Solver error: {}", error);
723 auto saved_solution = std::make_shared<Eigen::MatrixXd>(solution);
726 {sample.requested_fields.empty() ? fields : sample.requested_fields});
732 const Eigen::MatrixXd &solution,
735 std::vector<io::OutputField> fields;
739 Eigen::MatrixXd velocity, pressure;
742 const int field_dim =
mesh_->dimension();
745 const bool export_solution_gradient =
747 const bool export_pressure_gradient =
750 const auto resize_to_output_rows = [&](Eigen::MatrixXd &values) {
751 if (output_rows <= values.rows())
754 const int previous_rows = values.rows();
755 values.conservativeResize(output_rows, values.cols());
756 values.bottomRows(output_rows - previous_rows).setZero();
759 const auto sample_vector_field = [&](
const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients =
nullptr) ->
bool {
760 if (dof_values.size() <= 0 || field_dim <= 0)
763 if (has_element_samples)
773 values.row(i).setZero();
775 gradients->row(i).setZero();
779 Eigen::MatrixXd local_sol, local_grad;
782 element_id, sample.
local_points.row(i), dof_values, local_sol, local_grad);
784 for (
int d = 0; d < field_dim; ++d)
785 values(i, d) = local_sol(d);
787 gradients->row(i) = local_grad;
790 resize_to_output_rows(values);
792 resize_to_output_rows(*gradients);
798 values.resize(sample.
node_ids.size(), field_dim);
799 for (
int i = 0; i < sample.
node_ids.size(); ++i)
801 const int node_id = sample.
node_ids(i);
802 for (
int d = 0; d < field_dim; ++d)
804 const int dof = node_id * field_dim + d;
805 if (dof < 0 || dof >= dof_values.rows())
807 values(i, d) = dof_values(dof);
810 return sample.
points.rows() == 0 || sample.
points.rows() == values.rows();
816 Eigen::MatrixXd velocity_values, velocity_gradients;
817 const bool sampled_velocity = sample_vector_field(
818 velocity, velocity_values,
819 export_solution_gradient ? &velocity_gradients :
nullptr);
820 if (sampled_velocity && options.
export_field(
"velocity"))
824 if (sampled_velocity && export_solution_gradient)
827 if (mesh_ && (options.export_field(
"pressure") || export_pressure_gradient))
829 Eigen::MatrixXd values, gradients;
831 *mesh_, pressure_space_.basis_list(),
space_.geometry_basis_list(), sample, pressure, values,
832 export_pressure_gradient ? &gradients : nullptr))
834 if (options.export_field(
"pressure"))
836 if (export_pressure_gradient)
841 const auto ¶view_options =
args[
"output"][
"paraview"][
"options"];
842 if (paraview_options[
"material"] && has_element_samples)
844 const auto ¶ms = primary_assembler_->parameters();
845 std::map<std::string, Eigen::MatrixXd> param_values;
846 for (
const auto &[p, _] : params)
847 param_values[p].setZero(output_rows, 1);
849 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
850 const auto &density = mass_assembler_->density();
851 for (
int i = 0; i < sample.local_points.rows(); ++i)
853 const int element_id = sample.element_ids(i);
857 for (
const auto &[p, func] : params)
858 param_values.at(p)(i) =
func(sample.local_points.row(i), sample.
points.row(i), sample.time, element_id);
859 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
862 for (
const auto &[name, values] : param_values)
863 if (options.export_field(name))
865 if (options.export_field(
"rho"))
869 if (paraview_options[
"body_ids"] && options.export_field(
"body_ids") && has_element_samples)
871 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
872 for (
int i = 0; i < sample.element_ids.size(); ++i)
874 const int element_id = sample.element_ids(i);
876 ids(i) = mesh_->get_body_id(element_id);
884 void StokesVarForm::solve_static_linear(Eigen::MatrixXd &sol)
886 auto solver = polysolve::linear::Solver::create(args[
"solver"][
"linear"],
logger());
887 logger().info(
"{}...", solver->name());
889 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
890 const QuadratureOrders boundary_samples = n_boundary_samples(
space_.disc_orders.maxCoeff(),
space_.disc_ordersq.maxCoeff(), gdiscr_order);
891 rhs_assembler_->set_bc(
892 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples,
893 boundary_.local_neumann_boundary, rhs_);
896 build_stiffness_mat(A);
897 Eigen::VectorXd b = rhs_;
898 solve_linear_system(solver, A, b, args[
"output"][
"advanced"][
"spectrum"], sol);
901 void StokesVarForm::solve_transient_linear(Eigen::MatrixXd &sol)
903 auto solver = polysolve::linear::Solver::create(args[
"solver"][
"linear"],
logger());
904 logger().info(
"{}...", solver->name());
906 Eigen::MatrixXd velocity, pressure;
907 split_solution(sol, velocity, pressure);
910 args[
"time"][
"integrator"]);
913 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
914 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
916 time_integrator = bdf;
917 restore_checkpoint_integrator(
918 time_integrator,
"/checkpoint/state/primary_integrator", dt,
919 "primary",
space_, mesh_->dimension());
921 save_timestep(t0, 0, t0, dt, sol);
923 Eigen::MatrixXd current_rhs = rhs_;
925 build_stiffness_mat(stiffness);
927 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
928 const QuadratureOrders boundary_samples = n_boundary_samples(
space_.disc_orders.maxCoeff(),
space_.disc_ordersq.maxCoeff(), gdiscr_order);
930 for (
int t = 1; t <= time_steps; ++t)
932 const double time = t0 + t * dt;
933 rhs_assembler_->compute_energy_grad(
934 boundary_.local_boundary, boundary_.boundary_nodes, mass_assembler_->density(), boundary_samples, boundary_.local_neumann_boundary, rhs_, time,
936 rhs_assembler_->set_bc(
937 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, current_rhs, velocity, time);
939 if (current_rhs.rows() != stacked_ndof())
941 const int old_rows = current_rhs.rows();
942 current_rhs.conservativeResize(stacked_ndof(), current_rhs.cols());
943 if (stacked_ndof() > old_rows)
944 current_rhs.bottomRows(stacked_ndof() - old_rows).setZero();
946 current_rhs.bottomRows(pressure_block_size()).setZero();
949 Eigen::VectorXd b = Eigen::VectorXd::Zero(stacked_ndof());
950 b.head(primary_ndof()) = (mass_ * bdf->weighted_sum_x_prevs()) / bdf->beta_dt();
951 for (
int i : boundary_.boundary_nodes)
955 solve_linear_system(solver, A, b, args[
"output"][
"advanced"][
"spectrum"].get<bool>() && t == time_steps, sol);
956 split_solution(sol, velocity, pressure);
957 bdf->update_quantities(velocity.col(0));
959 save_timestep(time, t, t0, dt, sol);
960 save_step_state(t0, dt, t, sol, time_integrator.get());
961 logger().info(
"{}/{} t={}", t, time_steps, time);
962 notify_time_step(t, time_steps, t0, dt);
966 void StokesVarForm::solve_problem(
967 Eigen::MatrixXd &sol,
971 assert(!initial_condition_override &&
"Stokes does not support initial-condition overrides");
972 assert(!post_step &&
"Stokes does not support post-step callbacks");
974 stats.spectrum.setZero();
977 logger().info(
"Solving {}", primary_assembler_->name());
979 prepare_initial_solution(sol);
980 if (problem->is_time_dependent())
981 solve_transient_linear(sol);
984 time_integrator =
nullptr;
985 solve_static_linear(sol);
989 timings.solving_time = timer.getElapsedTime();
990 logger().info(
" took {}s", timings.solving_time);
995 json residual_solver_params(
const json &input)
998 params[
"solver"] =
"Newton";
999 params[
"line_search"][
"method"] =
"ResidualBacktracking";
1001 if (!params.contains(
"Newton") || params[
"Newton"].is_null())
1002 params[
"Newton"] = json::object();
1003 params[
"Newton"][
"force_psd_projection"] =
false;
1004 params[
"Newton"][
"use_psd_projection"] =
true;
1010 std::vector<Eigen::Triplet<double>>
entries;
1011 entries.reserve(velocity_mass.nonZeros() + extra_size);
1012 for (
int k = 0; k < velocity_mass.outerSize(); ++k)
1013 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
1014 entries.emplace_back(it.row(), it.col(), it.value());
1015 for (
int i = 0; i < extra_size; ++i)
1016 entries.emplace_back(velocity_mass.rows() + i, velocity_mass.cols() + i, 1.0);
1019 velocity_mass.rows() + extra_size,
1020 velocity_mass.cols() + extra_size);
1022 result.makeCompressed();
1027 void NavierStokesVarForm::build_forms(Eigen::MatrixXd &sol,
const double t)
1029 assert(sol.rows() == stacked_ndof());
1030 assert(sol.cols() == 1);
1032 auto stokes_assembler = std::make_shared<assembler::StokesVelocity>();
1033 set_materials(*stokes_assembler, mesh_->dimension());
1035 assert(navier_stokes_assembler);
1037 stacked_form_ = std::make_shared<solver::StackedForm>();
1038 const auto velocity_block = stacked_form_->add_block(primary_ndof());
1039 const auto pressure_block = stacked_form_->add_block(pressure_space_.n_bases);
1041 navier_stokes_form_ = std::make_shared<solver::NavierStokesForm>(
1043 stokes_assembler, *navier_stokes_assembler, ass_vals_cache_, t, mesh_->is_volume());
1044 stacked_form_->add(velocity_block, navier_stokes_form_);
1046 velocity_rhs_ = rhs_.topRows(primary_ndof());
1047 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
1048 const QuadratureOrders boundary_samples = n_boundary_samples(
space_.disc_orders.maxCoeff(),
space_.disc_ordersq.maxCoeff(), gdiscr_order);
1049 body_form_ = std::make_shared<solver::BodyForm>(
1051 boundary_.boundary_nodes, boundary_.local_boundary,
1052 boundary_.local_neumann_boundary, boundary_samples,
1053 velocity_rhs_, *rhs_assembler_, mass_assembler_->density(),
1054 false, problem->is_time_dependent());
1055 body_form_->update_quantities(t, sol.topRows(primary_ndof()));
1056 stacked_form_->add(velocity_block, body_form_);
1058 mixed_form_ = std::make_shared<solver::MixedLinearForm>(
1059 space_.n_bases, pressure_space_.n_bases,
1060 space_.basis_list(), pressure_space_.basis_list(),
space_.geometry_basis_list(),
1061 *mixed_assembler_, ass_vals_cache_, pressure_ass_vals_cache_, t, mesh_->is_volume());
1062 stacked_form_->add(velocity_block, pressure_block, mixed_form_);
1064 if (use_avg_pressure)
1066 const auto average_block = stacked_form_->add_block(1);
1067 average_pressure_form_ = std::make_shared<solver::AveragePressureForm>(pressure_space_.n_bases);
1068 stacked_form_->add(pressure_block, average_block, average_pressure_form_);
1071 average_pressure_form_ =
nullptr;
1073 inertia_form_ =
nullptr;
1074 if (problem->is_time_dependent())
1076 assert(time_integrator);
1077 inertia_form_ = std::make_shared<solver::InertiaForm>(mass_, *time_integrator);
1078 if (!boundary_.boundary_nodes.empty())
1080 inertia_form_->set_x_tilde_updater(
1081 [
this, boundary_samples](
1083 const Eigen::VectorXd &,
1084 Eigen::VectorXd &target) {
1085 Eigen::MatrixXd projected_target = target;
1086 const std::vector<mesh::LocalBoundary> empty_neumann_boundary;
1087 rhs_assembler_->set_bc(
1088 boundary_.local_boundary, boundary_.boundary_nodes,
1089 boundary_samples, empty_neumann_boundary,
1090 projected_target, Eigen::MatrixXd(), time);
1091 assert(projected_target.cols() == 1);
1092 target = projected_target.col(0);
1095 stacked_form_->add(velocity_block, inertia_form_);
1096 update_transient_form_weights();
1099 forms_ = {stacked_form_};
1100 for (
const auto &form : forms_)
1101 form->set_output_dir(output_path);
1104 if (!boundary_.boundary_nodes.empty())
1106 auto stacked_al = std::make_shared<solver::StackedAugmentedLagrangianForm>();
1107 const auto velocity_al_block = stacked_al->add_block(primary_ndof());
1108 stacked_al->add_block(pressure_space_.n_bases);
1109 if (use_avg_pressure)
1110 stacked_al->add_block(1);
1113 std::make_shared<solver::BCLagrangianForm>(
1114 primary_ndof(), boundary_.boundary_nodes,
1115 boundary_.local_boundary, boundary_.local_neumann_boundary,
1116 boundary_samples, pure_mass_, *rhs_assembler_,
1117 0, problem->is_time_dependent(), t));
1118 al_forms_.push_back(stacked_al);
1121 const StiffnessMatrix residual_mass = append_identity_mass(pure_mass_, pressure_block_size());
1122 nl_problem_ = std::make_shared<solver::NLProblem>(
1123 stacked_ndof(), t, forms_, al_forms_,
1124 polysolve::linear::Solver::create(args[
"solver"][
"linear"],
logger()),
1125 units.characteristic_length(), 1,
1126 residual_mass, mesh_->dimension(),
true);
1127 nl_problem_->init(sol);
1128 nl_problem_->update_quantities(t, sol);
1129 stats.solver_info = json::array();
1132 void NavierStokesVarForm::update_transient_form_weights()
1134 assert(time_integrator);
1135 const double scaling = time_integrator->acceleration_scaling();
1136 navier_stokes_form_->set_weight(scaling);
1137 body_form_->set_weight(scaling);
1138 mixed_form_->set_row_weights(scaling, scaling);
1139 if (average_pressure_form_)
1140 average_pressure_form_->set_weight(scaling);
1143 void NavierStokesVarForm::solve_nonlinear_step(
const int step, Eigen::MatrixXd &sol)
1145 assert(nl_problem_);
1146 const json nonlinear_params = residual_solver_params(args[
"solver"][
"nonlinear"]);
1147 const json al_nonlinear_params = residual_solver_params(args[
"solver"][
"augmented_lagrangian"][
"nonlinear"]);
1148 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver =
1149 polysolve::nonlinear::Solver::create(
1150 nonlinear_params, args[
"solver"][
"linear"], units.characteristic_length(),
logger());
1153 al_forms_, args[
"solver"][
"augmented_lagrangian"][
"initial_weight"],
1154 args[
"solver"][
"augmented_lagrangian"][
"scaling"],
1155 args[
"solver"][
"augmented_lagrangian"][
"max_weight"],
1156 args[
"solver"][
"augmented_lagrangian"][
"eta"],
1157 [](
const Eigen::VectorXd &) {});
1160 stats.solver_info.push_back(
1161 {{
"type", al_weight > 0 ?
"al" :
"rc"},
1163 {
"info", nl_solver->info()}});
1165 stats.solver_info.back()[
"weight"] = al_weight;
1166 save_subsolve(stats.solver_info.size(), step, sol);
1169 if (!al_forms_.empty())
1171 *nl_problem_, sol, al_nonlinear_params,
1172 args[
"solver"][
"linear"], units.characteristic_length(), nl_solver);
1173 al_solver.solve_reduced(
1174 *nl_problem_, sol, nonlinear_params,
1175 args[
"solver"][
"linear"], units.characteristic_length(), nl_solver);
1178 void NavierStokesVarForm::solve_problem(
1179 Eigen::MatrixXd &sol,
1183 assert(!initial_condition_override &&
"Navier-Stokes does not support initial-condition overrides");
1184 assert(!post_step &&
"Navier-Stokes does not support post-step callbacks");
1186 stats.spectrum.setZero();
1189 logger().info(
"Solving {}", primary_assembler_->name());
1191 prepare_initial_solution(sol);
1192 if (!problem->is_time_dependent())
1194 time_integrator =
nullptr;
1195 build_forms(sol, 1.0);
1196 solve_nonlinear_step(0, sol);
1200 Eigen::MatrixXd velocity, pressure;
1201 split_solution(sol, velocity, pressure);
1203 args[
"time"][
"integrator"],
1207 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
1208 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()), dt);
1209 time_integrator = bdf;
1210 restore_checkpoint_integrator(
1211 time_integrator,
"/checkpoint/state/primary_integrator", dt,
1212 "primary",
space_, mesh_->dimension());
1214 build_forms(sol, t0 + dt);
1215 save_timestep(t0, 0, t0, dt, sol);
1216 for (
int step = 1; step <= time_steps; ++step)
1218 const double time = t0 + step * dt;
1219 logger().info(
"{}/{} steps, dt={}s t={}s", step, time_steps, dt, time);
1220 solve_nonlinear_step(step, sol);
1222 split_solution(sol, velocity, pressure);
1223 time_integrator->update_quantities(velocity.col(0));
1224 update_transient_form_weights();
1225 nl_problem_->update_quantities(t0 + (step + 1) * dt, sol);
1227 save_timestep(time, step, t0, dt, sol);
1228 save_step_state(t0, dt, step, sol, time_integrator.get());
1229 notify_time_step(step, time_steps, t0, dt);
1234 timings.solving_time = timer.getElapsedTime();
1235 logger().info(
" took {}s", timings.solving_time);
std::vector< Eigen::Triplet< double > > entries
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.
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
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
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
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
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...
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
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
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
int dimension() const
utily for dimension
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
std::function< void(const double)> post_subsolve
static std::shared_ptr< BDF > construct_bdf_integrator(const json ¶ms, DynamicOrder dynamic_order=DynamicOrder::Second)
Construct a BDF integrator for algorithms using BDF-specific operations.
std::function< std::vector< OutputField >(const OutputSample &)> OutputFieldFunction
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.
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.
spdlog::logger & logger()
Retrieves the current logger.
std::array< int, 2 > QuadratureOrders
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
void log_and_throw_error(const std::string &msg)
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix
std::vector< std::string > fields
bool export_field(const std::string &field) const
std::vector< std::string > fields
Eigen::VectorXi element_ids
Eigen::MatrixXd local_points