20#include <polysolve/linear/FEMSolver.hpp>
24 using namespace varform::internal;
58 const bool is_time_dependent =
args.contains(
"time") && !
args[
"time"].is_null();
59 const json &discr_orders =
args.at(
"space").at(
"discr_order");
61 const json &materials =
args.at(
"materials");
62 if (materials.is_array() && materials.empty())
64 const json &first_material = materials.is_array() ? materials.at(0) : materials;
68 log_and_throw_error(
"Bilaplacian solution and auxiliary fields must use different FE space IDs.");
70 if (discr_orders.is_array())
72 bool has_solution_space =
false;
73 bool has_auxiliary_space =
false;
74 for (
const json &entry : discr_orders)
76 const int fe_space_id = entry.at(
"fe_space").get<
int>();
80 if (!has_solution_space || !has_auxiliary_space)
81 log_and_throw_error(
"Bilaplacian discretization-order lists must explicitly name the solution and auxiliary FE spaces.");
84 if (materials.is_array())
86 for (
const json &material : materials)
90 log_and_throw_error(
"All Bilaplacian materials must use the same solution and auxiliary FE space IDs.");
100 if (!
args.contains(
"preset_problem"))
102 problem = std::make_shared<assembler::GenericScalarProblem>(
"GenericScalar");
105 tmp[
"is_time_dependent"] = is_time_dependent;
108 auto bc =
args[
"boundary_conditions"];
122 t0 = is_time_dependent ?
args[
"time"][
"t0"].get<
double>() : 0.0;
123 time_steps = is_time_dependent ?
args[
"time"][
"time_steps"].get<
int>() : 0;
124 dt = is_time_dependent ?
args[
"time"][
"dt"].get<
double>() : 0.0;
131 logger().error(
"Load the mesh first!");
134 if (solution.size() <= 0)
136 logger().error(
"Solve the problem first!");
140 logger().info(
"Saving json...");
141 const Eigen::MatrixXd stats_solution =
151 args[
"output"][
"advanced"][
"sol_at_node"], j);
152 out << j.dump(4) << std::endl;
160 for (
int e = 0; e < output_orders.size(); ++e)
162 if (
mesh_->is_prism(e))
182 if (!
args[
"output"][
"advanced"][
"compute_error"])
186 if (!
args[
"time"].is_null())
187 tend =
args[
"time"][
"tend"];
189 Eigen::MatrixXd value, pressure;
200 logger().error(
"Load the mesh first!");
203 if (solution.size() <= 0)
205 logger().error(
"Solve the problem first!");
212 const bool has_time =
args.contains(
"time") && !
args[
"time"].is_null();
213 double tend = has_time ?
args[
"time"][
"tend"].get<
double>() : 1.0;
227 Eigen::MatrixXd value, pressure;
231 if (!solution_path.empty())
233 const int primary_ndof = std::min<int>(value.rows(),
space_.
n_bases);
234 const Eigen::MatrixXd primary_solution = value.topRows(primary_ndof);
237 const Eigen::MatrixXd nodal_solution =
utils::unflatten(primary_solution, 1);
238 Eigen::MatrixXd reordered = Eigen::MatrixXd::Zero(nodal_solution.rows(), nodal_solution.cols());
242 if (node >= 0 && node < nodal_solution.rows() && input_node < reordered.rows())
243 reordered.row(input_node) = nodal_solution.row(node);
254 if (!nodes_path.empty())
259 for (
const auto &global : basis.global())
260 nodes.row(global.index) = global.node;
268 Eigen::MatrixXd stress;
269 Eigen::VectorXd mises;
274 if (!stress_path.empty())
276 if (!mises_path.empty())
296 const std::vector<basis::ElementBases> &bases,
298 const int fe_space_id)
300 json rhs_solver_params =
args[
"solver"][
"linear"];
301 if (!rhs_solver_params.contains(
"Pardiso"))
302 rhs_solver_params[
"Pardiso"] = {};
303 rhs_solver_params[
"Pardiso"][
"mtype"] = -2;
305 return std::make_shared<assembler::RhsAssembler>(
310 args[
"space"][
"advanced"][
"bc_method"],
322 Eigen::VectorXi space_disc_orders;
325 if (
args[
"space"][
"use_p_ref"])
329 args[
"space"][
"advanced"][
"B"],
330 args[
"space"][
"advanced"][
"h1_formula"],
331 args[
"space"][
"discr_order"],
332 args[
"space"][
"advanced"][
"discr_order_max"],
336 logger().info(
"min p: {} max p: {}", space_disc_orders.minCoeff(), space_disc_orders.maxCoeff());
343 args[
"space"][
"basis_type"],
344 args[
"space"][
"poly_basis_type"],
347 args[
"space"][
"advanced"][
"quadrature_order"],
348 args[
"space"][
"advanced"][
"mass_quadrature_order"],
349 args[
"space"][
"advanced"][
"use_corner_quadrature"],
350 args[
"space"][
"advanced"][
"n_harmonic_samples"],
351 args[
"space"][
"advanced"][
"integral_constraints"],
359 if (
args[
"space"][
"advanced"][
"count_flipped_els"])
362 const int n_samples = 10;
372 logger().info(
"Building cache...");
376 logger().info(
" took {}s", timer.getElapsedTime());
392 const bool use_corner_quadrature =
args[
"space"][
"advanced"][
"use_corner_quadrature"];
393 const int quadrature_order =
args[
"space"][
"advanced"][
"quadrature_order"].get<
int>();
394 const int mass_quadrature_order =
args[
"space"][
"advanced"][
"mass_quadrature_order"].get<
int>();
395 Eigen::VectorXi pressure_disc_orders;
398 const std::string pressure_basis_type =
args[
"space"][
"basis_type"].get<std::string>() ==
"Bernstein" ?
"Bernstein" :
"Lagrange";
402 pressure_disc_orders,
404 args[
"space"][
"poly_basis_type"],
408 mass_quadrature_order,
409 use_corner_quadrature,
410 args[
"space"][
"advanced"][
"n_harmonic_samples"],
411 args[
"space"][
"advanced"][
"integral_constraints"],
425 for (
const auto &lb : all_boundary)
468 delta = (max - min) / 2. + min;
470 p_params[
"bbox_center"] = {delta(0), delta(1), delta(2)};
472 p_params[
"bbox_center"] = {delta(0), delta(1)};
479 logger().info(
"Assigning rhs...");
489 const int prev_size =
rhs_.rows();
499 const int gdiscr_order =
mesh_->orders().size() <= 0 ? 1 :
mesh_->orders().maxCoeff();
501 tmp_rhs_assembler->set_bc(
509 if (!
problem->is_time_dependent())
519 logger().info(
"Assembling mass mat...");
522 for (
int k = 0; k <
mass_.outerSize(); ++k)
523 for (StiffnessMatrix::InnerIterator it(
mass_, k); it; ++it)
525 assert(it.col() == k);
529 if (
args[
"solver"][
"advanced"][
"lump_mass_matrix"])
554 if (!was_solution_loaded)
556 if (
problem->is_time_dependent())
560 sol.resize(
rhs_.size(), 1);
566 sol.conservativeResize(Eigen::NoChange, 1);
573 const int cols = std::max(1,
int(stacked.cols()));
576 const int primary_rows = std::min(
space_.
n_bases,
int(stacked.rows()));
577 if (primary_rows > 0)
578 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
582 if (pressure_rows > 0)
583 pressure.topRows(pressure_rows) = stacked.middleRows(
space_.
n_bases, pressure_rows);
591 logger().info(
"Assembling stiffness mat...");
600 main_stiffness, mixed_stiffness, aux_stiffness, stiffness);
607 stats.
mat_size = (
long long)stiffness.rows() * (
long long)stiffness.cols();
612 const std::unique_ptr<polysolve::linear::Solver> &solver,
615 const bool compute_spectrum,
616 Eigen::MatrixXd &sol)
626 args[
"output"][
"data"][
"stiffness_mat"],
636 auto solver = polysolve::linear::Solver::create(
args[
"solver"][
"linear"],
logger());
637 logger().info(
"{}...", solver->name());
638 const int gdiscr_order =
mesh_->orders().size() <= 0 ? 1 :
mesh_->orders().maxCoeff();
645 Eigen::VectorXd b =
rhs_;
651 auto solver = polysolve::linear::Solver::create(
args[
"solver"][
"linear"],
logger());
652 logger().info(
"{}...", solver->name());
654 Eigen::MatrixXd value, pressure;
657 args[
"time"][
"integrator"]);
660 Eigen::MatrixXd::Zero(value.rows(), value.cols()),
661 Eigen::MatrixXd::Zero(value.rows(), value.cols()),
667 Eigen::MatrixXd current_rhs =
rhs_;
671 const int gdiscr_order =
mesh_->orders().size() <= 0 ? 1 :
mesh_->orders().maxCoeff();
676 const double time =
t0 + t *
dt;
685 const int old_rows = current_rhs.rows();
686 current_rhs.conservativeResize(
stacked_ndof(), current_rhs.cols());
688 current_rhs.bottomRows(
stacked_ndof() - old_rows).setZero();
693 Eigen::VectorXd b = Eigen::VectorXd::Zero(
stacked_ndof());
701 bdf->update_quantities(value.col(0));
717 if (
problem->is_time_dependent())
731 const Eigen::MatrixXd &solution,
734 std::vector<io::OutputField> fields;
738 Eigen::MatrixXd value, pressure;
743 const int primary_ndof = std::min<int>(value.rows(),
space_.
n_bases);
744 const Eigen::MatrixXd primary_solution = value.topRows(primary_ndof);
746 const auto sample_dof_field = [&](
const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients =
nullptr) ->
bool {
747 if (dof_values.size() <= 0)
750 if (has_element_samples)
762 gradients->row(i).setZero();
766 Eigen::MatrixXd local_sol, local_grad;
769 element_id, sample.
local_points.row(i), dof_values, local_sol, local_grad);
770 values(i) = local_sol(0);
772 gradients->row(i) = local_grad;
775 if (output_rows > values.rows())
777 const int previous_rows = values.rows();
778 values.conservativeResize(output_rows, Eigen::NoChange);
779 values.bottomRows(output_rows - previous_rows).setZero();
782 gradients->conservativeResize(output_rows, Eigen::NoChange);
783 gradients->bottomRows(output_rows - previous_rows).setZero();
791 values.resize(sample.
node_ids.size(), 1);
792 for (
int i = 0; i < sample.
node_ids.size(); ++i)
794 const int node_id = sample.
node_ids(i);
795 if (node_id < 0 || node_id >= dof_values.rows())
797 values(i) = dof_values(node_id);
799 return sample.
points.rows() == 0 || sample.
points.rows() == values.rows();
805 const auto ¶view_options =
args[
"output"][
"paraview"][
"options"];
806 if (has_element_samples &&
problem->has_exact_sol() && sample.
points.rows() == output_rows)
808 Eigen::MatrixXd exact;
810 if (exact.rows() == output_rows)
816 Eigen::MatrixXd values;
817 if (sample_dof_field(primary_solution, values))
823 if ((paraview_options[
"nodes"] || (!options.
fields.empty() && options.
export_field(
"nodes")))
824 && has_element_samples
827 Eigen::MatrixXd dof_ids(primary_ndof, 1);
828 dof_ids.col(0).setLinSpaced(primary_ndof, 0, primary_ndof - 1);
829 Eigen::MatrixXd values;
830 if (sample_dof_field(dof_ids, values))
834 if ((paraview_options[
"jacobian_validity"] || (!options.
fields.empty() && options.
export_field(
"validity")))
835 && has_element_samples
836 &&
mesh_->dimension() == 1
840 Eigen::MatrixXd validity = Eigen::MatrixXd::Zero(output_rows, 1);
841 for (
int i = 0; i < sample.
element_ids.size(); ++i)
842 validity(i) = std::find(invalid_elements.begin(), invalid_elements.end(), sample.
element_ids(i)) != invalid_elements.end();
846 const bool export_solution_gradient =
848 if (options.
export_field(
"solution") || export_solution_gradient)
850 Eigen::MatrixXd values, gradients;
851 if (sample_dof_field(
853 export_solution_gradient ? &gradients :
nullptr))
857 if (export_solution_gradient)
862 if (paraview_options[
"material"] && has_element_samples)
864 const auto ¶ms = primary_assembler_->parameters();
865 std::map<std::string, Eigen::MatrixXd> param_values;
866 for (
const auto &[p, _] : params)
867 param_values[p].setZero(output_rows, 1);
869 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
870 const auto &density = mass_assembler_->density();
871 for (
int i = 0; i < sample.local_points.rows(); ++i)
873 const int element_id = sample.element_ids(i);
877 for (
const auto &[p, func] : params)
878 param_values.at(p)(i) = func(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
879 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
882 for (
const auto &[name, values] : param_values)
883 if (options.export_field(name))
885 if (options.export_field(
"rho"))
889 if (paraview_options[
"body_ids"] && options.export_field(
"body_ids") && has_element_samples)
891 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
892 for (
int i = 0; i < sample.element_ids.size(); ++i)
894 const int element_id = sample.element_ids(i);
896 ids(i) = mesh_->get_body_id(element_id);
901 const bool export_pressure_gradient =
902 !options.fields.empty() && options.export_field(
"pressure_gradient");
903 if (mesh_ && (options.export_field(
"pressure") || export_pressure_gradient || (!options.fields.empty() && options.export_field(
"auxiliary"))))
905 Eigen::MatrixXd values, gradients;
907 *mesh_, pressure_space_.basis_list(),
space_.geometry_basis_list(), sample, pressure, values,
908 export_pressure_gradient ? &gradients : nullptr))
910 if (options.export_field(
"pressure"))
912 if (export_pressure_gradient)
914 if (!options.fields.empty() && options.export_field(
"auxiliary"))
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)
Caches basis evaluation and geometric mapping at every element.
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
double solving_time
time to solve
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.
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
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.
std::vector< int > count_invalid(const int dim, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const Eigen::VectorXd &u, const unsigned max_iter)
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 primitive_ids
Eigen::VectorXi element_ids
Eigen::MatrixXd local_points