29#include <polysolve/linear/FEMSolver.hpp>
30#include <polysolve/nonlinear/Solver.hpp>
34 using namespace varform::internal;
69 const bool is_time_dependent =
args.contains(
"time") && !
args[
"time"].is_null();
70 const json &discr_orders =
args.at(
"space").at(
"discr_order");
72 const json &materials =
args.at(
"materials");
73 if (materials.is_array() && materials.empty())
75 const json &first_material = materials.is_array() ? materials.at(0) : materials;
81 if (discr_orders.is_array())
83 bool has_velocity_space =
false;
84 bool has_pressure_space =
false;
85 for (
const json &entry : discr_orders)
87 const int fe_space_id = entry.at(
"fe_space").get<
int>();
91 if (!has_velocity_space || !has_pressure_space)
92 log_and_throw_error(
"Fluid discretization-order lists must explicitly name the velocity and pressure FE spaces.");
95 if (materials.is_array())
97 for (
const json &material : materials)
101 log_and_throw_error(
"All fluid materials must use the same velocity and pressure FE space IDs.");
111 if (!
args.contains(
"preset_problem"))
113 problem = std::make_shared<assembler::GenericTensorProblem>(
"GenericTensor");
117 tmp[
"is_time_dependent"] = is_time_dependent;
120 auto bc =
args[
"boundary_conditions"];
128 if (
args[
"preset_problem"][
"type"] ==
"Kernel")
143 t0 = is_time_dependent ?
args[
"time"][
"t0"].get<
double>() : 0.0;
144 time_steps = is_time_dependent ?
args[
"time"][
"time_steps"].get<
int>() : 0;
145 dt = is_time_dependent ?
args[
"time"][
"dt"].get<
double>() : 0.0;
154 logger().error(
"Load the mesh first!");
157 if (solution.size() <= 0)
159 logger().error(
"Solve the problem first!");
163 logger().info(
"Saving json...");
165 const Eigen::MatrixXd stats_solution =
166 solution.rows() >= primary_size
167 ? solution.topRows(primary_size).eval()
175 args[
"output"][
"advanced"][
"sol_at_node"], j);
176 out << j.dump(4) << std::endl;
184 for (
int e = 0; e < output_orders.size(); ++e)
186 if (
mesh_->is_prism(e))
206 if (!
args[
"output"][
"advanced"][
"compute_error"])
210 if (!
args[
"time"].is_null())
211 tend =
args[
"time"][
"tend"];
213 Eigen::MatrixXd velocity, pressure;
224 logger().error(
"Load the mesh first!");
227 if (solution.size() <= 0)
229 logger().error(
"Solve the problem first!");
236 const bool has_time =
args.contains(
"time") && !
args[
"time"].is_null();
237 double tend = has_time ?
args[
"time"][
"tend"].get<
double>() : 1.0;
251 Eigen::MatrixXd velocity, pressure;
255 if (!solution_path.empty())
257 const int primary_rows = std::min<int>(velocity.rows(),
primary_ndof());
258 const Eigen::MatrixXd primary_solution = velocity.topRows(primary_rows);
262 Eigen::MatrixXd reordered = Eigen::MatrixXd::Zero(nodal_solution.rows(), nodal_solution.cols());
266 if (node >= 0 && node < nodal_solution.rows() && input_node < reordered.rows())
267 reordered.row(input_node) = nodal_solution.row(node);
278 if (!nodes_path.empty())
283 for (
const auto &global : basis.global())
284 nodes.row(global.index) = global.node;
292 Eigen::MatrixXd stress;
293 Eigen::VectorXd mises;
298 if (!stress_path.empty())
300 if (!mises_path.empty())
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;
345 args[
"space"][
"advanced"][
"bc_method"],
357 Eigen::VectorXi space_disc_orders;
360 if (
args[
"space"][
"use_p_ref"])
364 args[
"space"][
"advanced"][
"B"],
365 args[
"space"][
"advanced"][
"h1_formula"],
366 args[
"space"][
"discr_order"],
367 args[
"space"][
"advanced"][
"discr_order_max"],
371 logger().info(
"min p: {} max p: {}", space_disc_orders.minCoeff(), space_disc_orders.maxCoeff());
378 args[
"space"][
"basis_type"],
379 args[
"space"][
"poly_basis_type"],
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"],
394 if (
args[
"space"][
"advanced"][
"count_flipped_els"])
397 const int n_samples = 10;
410 igl::Timer cache_timer;
412 logger().info(
"Building cache...");
416 logger().info(
" took {}s", cache_timer.getElapsedTime());
427 const int prev_b_size = int(all_boundary.size());
428 const bool use_corner_quadrature =
args[
"space"][
"advanced"][
"use_corner_quadrature"];
429 const int quadrature_order =
args[
"space"][
"advanced"][
"quadrature_order"].get<
int>();
430 const int mass_quadrature_order =
args[
"space"][
"advanced"][
"mass_quadrature_order"].get<
int>();
431 Eigen::VectorXi pressure_disc_orders;
434 const std::string pressure_basis_type =
args[
"space"][
"basis_type"].get<std::string>() ==
"Bernstein" ?
"Bernstein" :
"Lagrange";
438 pressure_disc_orders,
440 args[
"space"][
"poly_basis_type"],
444 mass_quadrature_order,
445 use_corner_quadrature,
446 args[
"space"][
"advanced"][
"n_harmonic_samples"],
447 args[
"space"][
"advanced"][
"integral_constraints"],
461 for (
const auto &lb : all_boundary)
484 for (
int d = 0; d < mesh.
dimension(); ++d)
510 delta = (max - min) / 2. + min;
512 p_params[
"bbox_center"] = {delta(0), delta(1), delta(2)};
514 p_params[
"bbox_center"] = {delta(0), delta(1)};
521 logger().info(
"Assigning rhs...");
530 const int prev_size =
rhs_.rows();
537 if (!
problem->is_time_dependent())
549 logger().info(
"Assembling mass mat...");
556 std::vector<Eigen::Triplet<double>> blocks;
557 blocks.reserve(velocity_mass.nonZeros());
558 for (
int k = 0; k < velocity_mass.outerSize(); ++k)
559 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
560 blocks.emplace_back(it.row(), it.col(), it.value());
563 mass_.setFromTriplets(blocks.begin(), blocks.end());
564 mass_.makeCompressed();
567 for (
int k = 0; k < velocity_mass.outerSize(); ++k)
568 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
570 assert(it.col() == k);
573 avg_mass_ /= std::max(1,
int(velocity_mass.rows()));
576 if (
args[
"solver"][
"advanced"][
"lump_mass_matrix"])
597 mesh_->dimension(), sol);
599 if (!was_solution_loaded)
601 if (
problem->is_time_dependent())
605 sol.resize(
rhs_.size(), 1);
611 sol.conservativeResize(Eigen::NoChange, 1);
618 const int cols = std::max(1,
int(stacked.cols()));
622 const int primary_rows = std::min(
primary_ndof(),
int(stacked.rows()));
623 if (primary_rows > 0)
624 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
629 if (pressure_rows > 0)
630 pressure.topRows(pressure_rows) = stacked.middleRows(
primary_ndof(), pressure_rows);
638 logger().info(
"Assembling stiffness mat...");
640 StiffnessMatrix velocity_stiffness, mixed_stiffness, pressure_stiffness;
647 velocity_stiffness, mixed_stiffness, pressure_stiffness, stiffness);
655 stats.
mat_size = (
long long)stiffness.rows() * (
long long)stiffness.cols();
662 const std::unique_ptr<polysolve::linear::Solver> &solver,
665 const bool compute_spectrum,
666 Eigen::MatrixXd &sol)
676 args[
"output"][
"data"][
"stiffness_mat"],
684 const double error = (A *
x - b).norm();
686 logger().error(
"Solver error: {}", error);
688 logger().debug(
"Solver error: {}", error);
693 const Eigen::MatrixXd &solution,
696 std::vector<io::OutputField> fields;
700 Eigen::MatrixXd velocity, pressure;
703 const int field_dim =
mesh_->dimension();
706 const bool export_solution_gradient =
708 const bool export_pressure_gradient =
711 const auto resize_to_output_rows = [&](Eigen::MatrixXd &values) {
712 if (output_rows <= values.rows())
715 const int previous_rows = values.rows();
716 values.conservativeResize(output_rows, values.cols());
717 values.bottomRows(output_rows - previous_rows).setZero();
720 const auto sample_vector_field = [&](
const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients =
nullptr) ->
bool {
721 if (dof_values.size() <= 0 || field_dim <= 0)
724 if (has_element_samples)
734 values.row(i).setZero();
736 gradients->row(i).setZero();
740 Eigen::MatrixXd local_sol, local_grad;
743 element_id, sample.
local_points.row(i), dof_values, local_sol, local_grad);
745 for (
int d = 0; d < field_dim; ++d)
746 values(i, d) = local_sol(d);
748 gradients->row(i) = local_grad;
751 resize_to_output_rows(values);
753 resize_to_output_rows(*gradients);
759 values.resize(sample.
node_ids.size(), field_dim);
760 for (
int i = 0; i < sample.
node_ids.size(); ++i)
762 const int node_id = sample.
node_ids(i);
763 for (
int d = 0; d < field_dim; ++d)
765 const int dof = node_id * field_dim + d;
766 if (dof < 0 || dof >= dof_values.rows())
768 values(i, d) = dof_values(dof);
771 return sample.
points.rows() == 0 || sample.
points.rows() == values.rows();
777 Eigen::MatrixXd velocity_values, velocity_gradients;
778 const bool sampled_velocity = sample_vector_field(
779 velocity, velocity_values,
780 export_solution_gradient ? &velocity_gradients :
nullptr);
781 if (sampled_velocity && options.
export_field(
"velocity"))
783 if (sampled_velocity && options.export_field(
"solution"))
785 if (sampled_velocity && export_solution_gradient)
788 if (mesh_ && (options.export_field(
"pressure") || export_pressure_gradient))
790 Eigen::MatrixXd values, gradients;
791 if (sample_scalar_field(
792 *mesh_, pressure_space_.basis_list(),
space_.geometry_basis_list(), sample, pressure, values,
793 export_pressure_gradient ? &gradients : nullptr))
795 if (options.export_field(
"pressure"))
797 if (export_pressure_gradient)
802 const auto ¶view_options =
args[
"output"][
"paraview"][
"options"];
803 if (paraview_options[
"material"] && has_element_samples)
805 const auto ¶ms = primary_assembler_->parameters();
806 std::map<std::string, Eigen::MatrixXd> param_values;
807 for (
const auto &[p, _] : params)
808 param_values[p].setZero(output_rows, 1);
810 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
811 const auto &density = mass_assembler_->density();
812 for (
int i = 0; i < sample.local_points.rows(); ++i)
814 const int element_id = sample.element_ids(i);
818 for (
const auto &[p, func] : params)
819 param_values.at(p)(i) =
func(sample.local_points.row(i), sample.
points.row(i), sample.time, element_id);
820 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
823 for (
const auto &[name, values] : param_values)
824 if (options.export_field(name))
826 if (options.export_field(
"rho"))
830 if (paraview_options[
"body_ids"] && options.export_field(
"body_ids") && has_element_samples)
832 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
833 for (
int i = 0; i < sample.element_ids.size(); ++i)
835 const int element_id = sample.element_ids(i);
837 ids(i) = mesh_->get_body_id(element_id);
845 void StokesVarForm::solve_static_linear(Eigen::MatrixXd &sol)
847 auto solver = polysolve::linear::Solver::create(args[
"solver"][
"linear"],
logger());
848 logger().info(
"{}...", solver->name());
850 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
851 const QuadratureOrders boundary_samples = n_boundary_samples(
space_.disc_orders.maxCoeff(), gdiscr_order);
852 rhs_assembler_->set_bc(
853 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples,
854 boundary_.local_neumann_boundary, rhs_);
857 build_stiffness_mat(A);
858 Eigen::VectorXd b = rhs_;
859 solve_linear_system(solver, A, b, args[
"output"][
"advanced"][
"spectrum"], sol);
862 void StokesVarForm::solve_transient_linear(Eigen::MatrixXd &sol)
864 auto solver = polysolve::linear::Solver::create(args[
"solver"][
"linear"],
logger());
865 logger().info(
"{}...", solver->name());
867 Eigen::MatrixXd velocity, pressure;
868 split_solution(sol, velocity, pressure);
871 args[
"time"][
"integrator"]);
874 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
875 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
877 time_integrator = bdf;
879 save_timestep(t0, 0, t0, dt, sol);
881 Eigen::MatrixXd current_rhs = rhs_;
883 build_stiffness_mat(stiffness);
885 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
886 const QuadratureOrders boundary_samples = n_boundary_samples(
space_.disc_orders.maxCoeff(), gdiscr_order);
888 for (
int t = 1; t <= time_steps; ++t)
890 const double time = t0 + t * dt;
891 rhs_assembler_->compute_energy_grad(
892 boundary_.local_boundary, boundary_.boundary_nodes, mass_assembler_->density(), boundary_samples, boundary_.local_neumann_boundary, rhs_, time,
894 rhs_assembler_->set_bc(
895 boundary_.local_boundary, boundary_.boundary_nodes, boundary_samples, boundary_.local_neumann_boundary, current_rhs, velocity, time);
897 if (current_rhs.rows() != stacked_ndof())
899 const int old_rows = current_rhs.rows();
900 current_rhs.conservativeResize(stacked_ndof(), current_rhs.cols());
901 if (stacked_ndof() > old_rows)
902 current_rhs.bottomRows(stacked_ndof() - old_rows).setZero();
904 current_rhs.bottomRows(pressure_block_size()).setZero();
907 Eigen::VectorXd b = Eigen::VectorXd::Zero(stacked_ndof());
908 b.head(primary_ndof()) = (mass_ * bdf->weighted_sum_x_prevs()) / bdf->beta_dt();
909 for (
int i : boundary_.boundary_nodes)
913 solve_linear_system(solver, A, b, args[
"output"][
"advanced"][
"spectrum"].get<bool>() && t == time_steps, sol);
914 split_solution(sol, velocity, pressure);
915 bdf->update_quantities(velocity.col(0));
917 save_timestep(time, t, t0, dt, sol);
918 save_step_state(t0, dt, t, time_integrator.get());
919 logger().info(
"{}/{} t={}", t, time_steps, time);
920 notify_time_step(t, time_steps, t0, dt);
924 void StokesVarForm::solve_problem(Eigen::MatrixXd &sol)
926 stats.spectrum.setZero();
929 logger().info(
"Solving {}", primary_assembler_->name());
931 prepare_initial_solution(sol);
932 if (problem->is_time_dependent())
933 solve_transient_linear(sol);
936 time_integrator =
nullptr;
937 solve_static_linear(sol);
941 timings.solving_time = timer.getElapsedTime();
942 logger().info(
" took {}s", timings.solving_time);
947 json residual_solver_params(
const json &input)
950 params[
"solver"] =
"Newton";
951 params[
"line_search"][
"method"] =
"ResidualBacktracking";
953 if (!params.contains(
"Newton") || params[
"Newton"].is_null())
954 params[
"Newton"] = json::object();
955 params[
"Newton"][
"force_psd_projection"] =
false;
956 params[
"Newton"][
"use_psd_projection"] =
true;
962 std::vector<Eigen::Triplet<double>>
entries;
963 entries.reserve(velocity_mass.nonZeros() + extra_size);
964 for (
int k = 0; k < velocity_mass.outerSize(); ++k)
965 for (StiffnessMatrix::InnerIterator it(velocity_mass, k); it; ++it)
966 entries.emplace_back(it.row(), it.col(), it.value());
967 for (
int i = 0; i < extra_size; ++i)
968 entries.emplace_back(velocity_mass.rows() + i, velocity_mass.cols() + i, 1.0);
971 velocity_mass.rows() + extra_size,
972 velocity_mass.cols() + extra_size);
974 result.makeCompressed();
979 void NavierStokesVarForm::build_forms(Eigen::MatrixXd &sol,
const double t)
981 assert(sol.rows() == stacked_ndof());
982 assert(sol.cols() == 1);
984 auto stokes_assembler = std::make_shared<assembler::StokesVelocity>();
985 set_materials(*stokes_assembler, mesh_->dimension());
987 assert(navier_stokes_assembler);
989 stacked_form_ = std::make_shared<solver::StackedForm>();
990 const auto velocity_block = stacked_form_->add_block(primary_ndof());
991 const auto pressure_block = stacked_form_->add_block(pressure_space_.n_bases);
993 navier_stokes_form_ = std::make_shared<solver::NavierStokesForm>(
995 stokes_assembler, *navier_stokes_assembler, ass_vals_cache_, t, mesh_->is_volume());
996 stacked_form_->add(velocity_block, navier_stokes_form_);
998 velocity_rhs_ = rhs_.topRows(primary_ndof());
999 const int gdiscr_order = mesh_->orders().size() <= 0 ? 1 : mesh_->orders().maxCoeff();
1000 const QuadratureOrders boundary_samples = n_boundary_samples(
space_.disc_orders.maxCoeff(), gdiscr_order);
1001 body_form_ = std::make_shared<solver::BodyForm>(
1003 boundary_.boundary_nodes, boundary_.local_boundary,
1004 boundary_.local_neumann_boundary, boundary_samples,
1005 velocity_rhs_, *rhs_assembler_, mass_assembler_->density(),
1006 false, problem->is_time_dependent());
1007 body_form_->update_quantities(t, sol.topRows(primary_ndof()));
1008 stacked_form_->add(velocity_block, body_form_);
1010 mixed_form_ = std::make_shared<solver::MixedLinearForm>(
1011 space_.n_bases, pressure_space_.n_bases,
1012 space_.basis_list(), pressure_space_.basis_list(),
space_.geometry_basis_list(),
1013 *mixed_assembler_, ass_vals_cache_, pressure_ass_vals_cache_, t, mesh_->is_volume());
1014 stacked_form_->add(velocity_block, pressure_block, mixed_form_);
1016 if (use_avg_pressure)
1018 const auto average_block = stacked_form_->add_block(1);
1019 average_pressure_form_ = std::make_shared<solver::AveragePressureForm>(pressure_space_.n_bases);
1020 stacked_form_->add(pressure_block, average_block, average_pressure_form_);
1023 average_pressure_form_ =
nullptr;
1025 inertia_form_ =
nullptr;
1026 if (problem->is_time_dependent())
1028 assert(time_integrator);
1029 inertia_form_ = std::make_shared<solver::InertiaForm>(mass_, *time_integrator);
1030 if (!boundary_.boundary_nodes.empty())
1032 inertia_form_->set_x_tilde_updater(
1033 [
this, boundary_samples](
1035 const Eigen::VectorXd &,
1036 Eigen::VectorXd &target) {
1037 Eigen::MatrixXd projected_target = target;
1038 const std::vector<mesh::LocalBoundary> empty_neumann_boundary;
1039 rhs_assembler_->set_bc(
1040 boundary_.local_boundary, boundary_.boundary_nodes,
1041 boundary_samples, empty_neumann_boundary,
1042 projected_target, Eigen::MatrixXd(), time);
1043 assert(projected_target.cols() == 1);
1044 target = projected_target.col(0);
1047 stacked_form_->add(velocity_block, inertia_form_);
1048 update_transient_form_weights();
1051 forms_ = {stacked_form_};
1052 for (
const auto &form : forms_)
1053 form->set_output_dir(output_path);
1056 if (!boundary_.boundary_nodes.empty())
1058 auto stacked_al = std::make_shared<solver::StackedAugmentedLagrangianForm>();
1059 const auto velocity_al_block = stacked_al->add_block(primary_ndof());
1060 stacked_al->add_block(pressure_space_.n_bases);
1061 if (use_avg_pressure)
1062 stacked_al->add_block(1);
1065 std::make_shared<solver::BCLagrangianForm>(
1066 primary_ndof(), boundary_.boundary_nodes,
1067 boundary_.local_boundary, boundary_.local_neumann_boundary,
1068 boundary_samples, pure_mass_, *rhs_assembler_,
1069 0, problem->is_time_dependent(), t));
1070 al_forms_.push_back(stacked_al);
1073 const StiffnessMatrix residual_mass = append_identity_mass(pure_mass_, pressure_block_size());
1074 nl_problem_ = std::make_shared<solver::NLProblem>(
1075 stacked_ndof(),
nullptr, t, forms_, al_forms_,
1076 polysolve::linear::Solver::create(args[
"solver"][
"linear"],
logger()),
1077 units.characteristic_length(), 1,
1078 residual_mass, mesh_->dimension(),
true);
1079 nl_problem_->init(sol);
1080 nl_problem_->update_quantities(t, sol);
1081 stats.solver_info = json::array();
1084 void NavierStokesVarForm::update_transient_form_weights()
1086 assert(time_integrator);
1087 const double scaling = time_integrator->acceleration_scaling();
1088 navier_stokes_form_->set_weight(scaling);
1089 body_form_->set_weight(scaling);
1090 mixed_form_->set_row_weights(scaling, scaling);
1091 if (average_pressure_form_)
1092 average_pressure_form_->set_weight(scaling);
1095 void NavierStokesVarForm::solve_nonlinear_step(
const int step, Eigen::MatrixXd &sol)
1097 assert(nl_problem_);
1098 const json nonlinear_params = residual_solver_params(args[
"solver"][
"nonlinear"]);
1099 const json al_nonlinear_params = residual_solver_params(args[
"solver"][
"augmented_lagrangian"][
"nonlinear"]);
1100 std::shared_ptr<polysolve::nonlinear::Solver> nl_solver =
1101 polysolve::nonlinear::Solver::create(
1102 nonlinear_params, args[
"solver"][
"linear"], units.characteristic_length(),
logger());
1105 al_forms_, args[
"solver"][
"augmented_lagrangian"][
"initial_weight"],
1106 args[
"solver"][
"augmented_lagrangian"][
"scaling"],
1107 args[
"solver"][
"augmented_lagrangian"][
"max_weight"],
1108 args[
"solver"][
"augmented_lagrangian"][
"eta"],
1109 [](
const Eigen::VectorXd &) {});
1112 stats.solver_info.push_back(
1113 {{
"type", al_weight > 0 ?
"al" :
"rc"},
1115 {
"info", nl_solver->info()}});
1117 stats.solver_info.back()[
"weight"] = al_weight;
1118 save_subsolve(stats.solver_info.size(), step, sol);
1121 if (!al_forms_.empty())
1123 *nl_problem_, sol, al_nonlinear_params,
1124 args[
"solver"][
"linear"], units.characteristic_length(), nl_solver);
1125 al_solver.solve_reduced(
1126 *nl_problem_, sol, nonlinear_params,
1127 args[
"solver"][
"linear"], units.characteristic_length(), nl_solver);
1130 void NavierStokesVarForm::solve_problem(Eigen::MatrixXd &sol)
1132 stats.spectrum.setZero();
1135 logger().info(
"Solving {}", primary_assembler_->name());
1137 prepare_initial_solution(sol);
1138 if (!problem->is_time_dependent())
1140 time_integrator =
nullptr;
1141 build_forms(sol, 1.0);
1142 solve_nonlinear_step(0, sol);
1146 Eigen::MatrixXd velocity, pressure;
1147 split_solution(sol, velocity, pressure);
1149 args[
"time"][
"integrator"],
1153 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()),
1154 Eigen::MatrixXd::Zero(velocity.rows(), velocity.cols()), dt);
1155 time_integrator = bdf;
1157 build_forms(sol, t0 + dt);
1158 save_timestep(t0, 0, t0, dt, sol);
1159 for (
int step = 1; step <= time_steps; ++step)
1161 const double time = t0 + step * dt;
1162 logger().info(
"{}/{} steps, dt={}s t={}s", step, time_steps, dt, time);
1163 solve_nonlinear_step(step, sol);
1165 split_solution(sol, velocity, pressure);
1166 time_integrator->update_quantities(velocity.col(0));
1167 update_transient_form_weights();
1168 nl_problem_->update_quantities(t0 + (step + 1) * dt, sol);
1170 save_timestep(time, step, t0, dt, sol);
1171 save_step_state(t0, dt, step, time_integrator.get());
1172 notify_time_step(step, time_steps, t0, dt);
1177 timings.solving_time = timer.getElapsedTime();
1178 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
void update_nodes(const Eigen::VectorXi &in_node_to_node)
Update the node ids to reorder them.
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.
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
bool export_field(const std::string &field) const
std::vector< std::string > fields
Eigen::VectorXi element_ids
Eigen::MatrixXd local_points