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, space_disc_ordersq;
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());
344 args[
"space"][
"basis_type"],
345 args[
"space"][
"poly_basis_type"],
348 args[
"space"][
"advanced"][
"quadrature_order"],
349 args[
"space"][
"advanced"][
"mass_quadrature_order"],
350 args[
"space"][
"advanced"][
"use_corner_quadrature"],
351 args[
"space"][
"advanced"][
"n_harmonic_samples"],
352 args[
"space"][
"advanced"][
"integral_constraints"],
360 if (
args[
"space"][
"advanced"][
"count_flipped_els"])
363 const int n_samples = 10;
373 logger().info(
"Building cache...");
377 logger().info(
" took {}s", timer.getElapsedTime());
393 const bool use_corner_quadrature =
args[
"space"][
"advanced"][
"use_corner_quadrature"];
394 const int quadrature_order =
args[
"space"][
"advanced"][
"quadrature_order"].get<
int>();
395 const int mass_quadrature_order =
args[
"space"][
"advanced"][
"mass_quadrature_order"].get<
int>();
396 Eigen::VectorXi pressure_disc_orders, pressure_disc_ordersq;
399 const std::string pressure_basis_type =
args[
"space"][
"basis_type"].get<std::string>() ==
"Bernstein" ?
"Bernstein" :
"Lagrange";
403 pressure_disc_orders,
404 pressure_disc_ordersq,
406 args[
"space"][
"poly_basis_type"],
410 mass_quadrature_order,
411 use_corner_quadrature,
412 args[
"space"][
"advanced"][
"n_harmonic_samples"],
413 args[
"space"][
"advanced"][
"integral_constraints"],
427 for (
const auto &lb : all_boundary)
470 delta = (max - min) / 2. + min;
472 p_params[
"bbox_center"] = {delta(0), delta(1), delta(2)};
474 p_params[
"bbox_center"] = {delta(0), delta(1)};
481 logger().info(
"Assigning rhs...");
491 const int prev_size =
rhs_.rows();
501 const int gdiscr_order =
mesh_->orders().size() <= 0 ? 1 :
mesh_->orders().maxCoeff();
503 tmp_rhs_assembler->set_bc(
511 if (!
problem->is_time_dependent())
521 logger().info(
"Assembling mass mat...");
524 for (
int k = 0; k <
mass_.outerSize(); ++k)
525 for (StiffnessMatrix::InnerIterator it(
mass_, k); it; ++it)
527 assert(it.col() == k);
531 if (
args[
"solver"][
"advanced"][
"lump_mass_matrix"])
556 if (!was_solution_loaded)
558 if (
problem->is_time_dependent())
562 sol.resize(
rhs_.size(), 1);
568 sol.conservativeResize(Eigen::NoChange, 1);
575 const int cols = std::max(1,
int(stacked.cols()));
578 const int primary_rows = std::min(
space_.
n_bases,
int(stacked.rows()));
579 if (primary_rows > 0)
580 primary.topRows(primary_rows) = stacked.topRows(primary_rows);
584 if (pressure_rows > 0)
585 pressure.topRows(pressure_rows) = stacked.middleRows(
space_.
n_bases, pressure_rows);
593 logger().info(
"Assembling stiffness mat...");
602 main_stiffness, mixed_stiffness, aux_stiffness, stiffness);
609 stats.
mat_size = (
long long)stiffness.rows() * (
long long)stiffness.cols();
614 const std::unique_ptr<polysolve::linear::Solver> &solver,
617 const bool compute_spectrum,
618 Eigen::MatrixXd &sol)
628 args[
"output"][
"data"][
"stiffness_mat"],
638 auto solver = polysolve::linear::Solver::create(
args[
"solver"][
"linear"],
logger());
639 logger().info(
"{}...", solver->name());
640 const int gdiscr_order =
mesh_->orders().size() <= 0 ? 1 :
mesh_->orders().maxCoeff();
647 Eigen::VectorXd b =
rhs_;
653 auto solver = polysolve::linear::Solver::create(
args[
"solver"][
"linear"],
logger());
654 logger().info(
"{}...", solver->name());
656 Eigen::MatrixXd value, pressure;
659 args[
"time"][
"integrator"]);
662 Eigen::MatrixXd::Zero(value.rows(), value.cols()),
663 Eigen::MatrixXd::Zero(value.rows(), value.cols()),
669 Eigen::MatrixXd current_rhs =
rhs_;
673 const int gdiscr_order =
mesh_->orders().size() <= 0 ? 1 :
mesh_->orders().maxCoeff();
678 const double time =
t0 + t *
dt;
687 const int old_rows = current_rhs.rows();
688 current_rhs.conservativeResize(
stacked_ndof(), current_rhs.cols());
690 current_rhs.bottomRows(
stacked_ndof() - old_rows).setZero();
695 Eigen::VectorXd b = Eigen::VectorXd::Zero(
stacked_ndof());
703 bdf->update_quantities(value.col(0));
719 if (
problem->is_time_dependent())
733 const Eigen::MatrixXd &solution,
736 std::vector<io::OutputField> fields;
740 Eigen::MatrixXd value, pressure;
745 const int primary_ndof = std::min<int>(value.rows(),
space_.
n_bases);
746 const Eigen::MatrixXd primary_solution = value.topRows(primary_ndof);
748 const auto sample_dof_field = [&](
const Eigen::MatrixXd &dof_values, Eigen::MatrixXd &values, Eigen::MatrixXd *gradients =
nullptr) ->
bool {
749 if (dof_values.size() <= 0)
752 if (has_element_samples)
764 gradients->row(i).setZero();
768 Eigen::MatrixXd local_sol, local_grad;
771 element_id, sample.
local_points.row(i), dof_values, local_sol, local_grad);
772 values(i) = local_sol(0);
774 gradients->row(i) = local_grad;
777 if (output_rows > values.rows())
779 const int previous_rows = values.rows();
780 values.conservativeResize(output_rows, Eigen::NoChange);
781 values.bottomRows(output_rows - previous_rows).setZero();
784 gradients->conservativeResize(output_rows, Eigen::NoChange);
785 gradients->bottomRows(output_rows - previous_rows).setZero();
793 values.resize(sample.
node_ids.size(), 1);
794 for (
int i = 0; i < sample.
node_ids.size(); ++i)
796 const int node_id = sample.
node_ids(i);
797 if (node_id < 0 || node_id >= dof_values.rows())
799 values(i) = dof_values(node_id);
801 return sample.
points.rows() == 0 || sample.
points.rows() == values.rows();
807 const auto ¶view_options =
args[
"output"][
"paraview"][
"options"];
808 if (has_element_samples &&
problem->has_exact_sol() && sample.
points.rows() == output_rows)
810 Eigen::MatrixXd exact;
812 if (exact.rows() == output_rows)
818 Eigen::MatrixXd values;
819 if (sample_dof_field(primary_solution, values))
825 if ((paraview_options[
"nodes"] || (!options.
fields.empty() && options.
export_field(
"nodes")))
826 && has_element_samples
829 Eigen::MatrixXd dof_ids(primary_ndof, 1);
830 dof_ids.col(0).setLinSpaced(primary_ndof, 0, primary_ndof - 1);
831 Eigen::MatrixXd values;
832 if (sample_dof_field(dof_ids, values))
836 if ((paraview_options[
"jacobian_validity"] || (!options.
fields.empty() && options.
export_field(
"validity")))
837 && has_element_samples
838 &&
mesh_->dimension() == 1
842 Eigen::MatrixXd validity = Eigen::MatrixXd::Zero(output_rows, 1);
843 for (
int i = 0; i < sample.
element_ids.size(); ++i)
844 validity(i) = std::find(invalid_elements.begin(), invalid_elements.end(), sample.
element_ids(i)) != invalid_elements.end();
848 const bool export_solution_gradient =
850 if (options.
export_field(
"solution") || export_solution_gradient)
852 Eigen::MatrixXd values, gradients;
853 if (sample_dof_field(
855 export_solution_gradient ? &gradients :
nullptr))
859 if (export_solution_gradient)
864 if (paraview_options[
"material"] && has_element_samples)
866 const auto ¶ms = primary_assembler_->parameters();
867 std::map<std::string, Eigen::MatrixXd> param_values;
868 for (
const auto &[p, _] : params)
869 param_values[p].setZero(output_rows, 1);
871 Eigen::MatrixXd rhos = Eigen::MatrixXd::Zero(output_rows, 1);
872 const auto &density = mass_assembler_->density();
873 for (
int i = 0; i < sample.local_points.rows(); ++i)
875 const int element_id = sample.element_ids(i);
879 for (
const auto &[p, func] : params)
880 param_values.at(p)(i) = func(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
881 rhos(i) = density(sample.local_points.row(i), sample.points.row(i), sample.time, element_id);
884 for (
const auto &[name, values] : param_values)
885 if (options.export_field(name))
887 if (options.export_field(
"rho"))
891 if (paraview_options[
"body_ids"] && options.export_field(
"body_ids") && has_element_samples)
893 Eigen::MatrixXd ids = Eigen::MatrixXd::Zero(output_rows, 1);
894 for (
int i = 0; i < sample.element_ids.size(); ++i)
896 const int element_id = sample.element_ids(i);
898 ids(i) = mesh_->get_body_id(element_id);
903 const bool export_pressure_gradient =
904 !options.fields.empty() && options.export_field(
"pressure_gradient");
905 if (mesh_ && (options.export_field(
"pressure") || export_pressure_gradient || (!options.fields.empty() && options.export_field(
"auxiliary"))))
907 Eigen::MatrixXd values, gradients;
909 *mesh_, pressure_space_.basis_list(),
space_.geometry_basis_list(), sample, pressure, values,
910 export_pressure_gradient ? &gradients : nullptr))
912 if (options.export_field(
"pressure"))
914 if (export_pressure_gradient)
916 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