10#include <ipc/utils/eigen_ext.hpp>
20 using namespace basis;
22 using namespace utils;
36 if (!determinant_ready_)
40 : deformation_.determinant();
41 determinant_ready_ =
true;
50 if (type == native_type)
55 const int index =
static_cast<int>(type);
56 assert(index >= 0 && index < 3);
57 if (!computed_[index])
62 tensors_[index] = (native * deformation_.transpose()) /
determinant();
64 tensors_[index] =
inverse() * native;
70 computed_[index] =
true;
72 return tensors_[index];
76 const OutputData &data,
const bool need_stress,
const bool need_energy,
77 const std::function<
void(Eigen::Index,
OutputStress &)> &emit)
const
79 assert(data.
fun.cols() == 1);
83 for (Eigen::Index p = 0; p < data.
local_pts.rows(); ++p)
86 for (
int j = 0; j < data.
bs.
bases.size(); ++j)
87 for (
int d = 0; d <
size(); ++d)
88 for (
const auto &global : data.
bs.
bases[j].global())
89 gradient.row(d) += global.val *
vals.basis_values[j].grad.row(p) * data.
fun(global.index *
size() + d);
90 gradient = (gradient *
vals.jac_it[p]).eval();
104 Eigen::MatrixXd &all,
const std::function<Eigen::MatrixXd(
const Eigen::MatrixXd &)> &fun)
const
106 all.resize(data.
local_pts.rows(), all_size);
107 Eigen::MatrixXd tensor(
size(),
size());
111 all(p, 0) = stress.
energy;
113 all.row(p).setConstant(std::nan(
""));
116 tensor = stress.
tensor(type);
117 all.row(p) = fun(tensor);
135 const OutputData &data, std::vector<NamedMatrix> *scalar, std::vector<NamedMatrix> *tensor)
const
137 if (!scalar && !tensor)
142 scalar->emplace_back(
"von_mises", Eigen::MatrixXd(data.
local_pts.rows(), 1));
147 for (
const char *field : {
"cauchy_stess",
"pk1_stess",
"pk2_stess",
"F"})
148 tensor->emplace_back(field, Eigen::MatrixXd(data.
local_pts.rows(),
size() *
size()));
149 tensor->emplace_back(
"energy", Eigen::MatrixXd(data.
local_pts.rows(), 1));
158 for (
int k = 0; k < 3; ++k)
163 (*tensor)[k].second.row(p) = Eigen::Map<const Eigen::RowVectorXd>(value.data(),
size() *
size());
166 (*tensor)[k].second.row(p).setConstant(std::nan(
""));
169 (*tensor)[3].second.row(p) = Eigen::Map<const Eigen::RowVectorXd>(
F.data(),
size() *
size());
170 (*tensor)[4].second(p) = stress.
energy;
179 for (
int k = 0; k < 4; ++k)
188 template <
int Dimension,
int BasisCount,
typename Matrix>
189 void add_unit_weight_hessian(
const Eigen::MatrixBase<Matrix> &
hessian,
192 const int nb = BasisCount == Eigen::Dynamic ? n_bases : BasisCount;
193 const int dim = Dimension == Eigen::Dynamic ? dimension : Dimension;
195 for (
int i = 0; i < nb; ++i)
196 for (
int j = 0; j < nb; ++j)
197 for (
int n = 0; n < dim; ++n)
198 for (
int m = 0; m < dim; ++m)
199 writer.
add(
hessian(i * dim + m, j * dim + n));
202 class LocalThreadMatStorage
205 std::unique_ptr<MatrixCache>
cache =
nullptr;
210 LocalThreadMatStorage() =
delete;
212 LocalThreadMatStorage(
const int buffer_size,
const int rows,
const int cols)
214 init(buffer_size, rows, cols);
217 LocalThreadMatStorage(
const int buffer_size,
const MatrixCache &c)
219 init(buffer_size, c);
222 LocalThreadMatStorage(
const LocalThreadMatStorage &other)
227 LocalThreadMatStorage &operator=(
const LocalThreadMatStorage &other)
229 assert(other.cache !=
nullptr);
230 cache = other.cache->copy();
237 void init(
const int buffer_size,
const int rows,
const int cols)
241 cache = std::make_unique<SparseMatrixCache>();
242 cache->reserve(buffer_size);
243 cache->init(rows, cols);
246 void init(
const int buffer_size,
const MatrixCache &c)
248 if (
cache ==
nullptr)
250 cache->reserve(buffer_size);
255 class LocalThreadVecStorage
259 ElementAssemblyValues
vals;
262 LocalThreadVecStorage(
const int size)
269 class LocalThreadScalarStorage
273 ElementAssemblyValues
vals;
276 LocalThreadScalarStorage()
282 void split_mixed_solution(
284 const Eigen::MatrixXd &
x,
287 Eigen::MatrixXd &x_phi,
288 Eigen::MatrixXd &x_psi)
290 assert(split_solution);
292 split_solution(
x, x_phi, x_psi);
294 assert(x_phi.rows() == phi_ndof);
295 assert(x_phi.cols() == 1);
296 assert(x_psi.rows() == psi_ndof);
297 assert(x_psi.cols() == 1);
300 void split_mixed_previous_solution(
302 const Eigen::MatrixXd &
x,
305 Eigen::MatrixXd &x_phi,
306 Eigen::MatrixXd &x_psi)
315 split_mixed_solution(split_solution,
x, phi_ndof, psi_ndof, x_phi, x_psi);
318 std::pair<const ElementAssemblyValues &, const ElementAssemblyValues &> compute_mixed_element_values(
320 const bool is_volume,
321 const ElementBases &psi_basis,
322 const ElementBases &phi_basis,
323 const ElementBases &gbasis,
324 const AssemblyValsCache &psi_cache,
325 const AssemblyValsCache &phi_cache,
326 ElementAssemblyValues &psi_scratch,
327 ElementAssemblyValues &phi_scratch)
329 const auto *psi_vals = &psi_cache.get_or_compute(el_index, is_volume, psi_basis, gbasis, psi_scratch);
330 const auto *phi_vals = &phi_cache.get_or_compute(el_index, is_volume, phi_basis, gbasis, phi_scratch);
332 const auto same_quadrature = [&]() {
333 if (psi_vals->quadrature.weights.size() != phi_vals->quadrature.weights.size())
335 if (psi_vals->quadrature.points.rows() != phi_vals->quadrature.points.rows()
336 || psi_vals->quadrature.points.cols() != phi_vals->quadrature.points.cols())
338 return (psi_vals->quadrature.points - phi_vals->quadrature.points).cwiseAbs().maxCoeff() < 1
e-14;
341 if (same_quadrature())
342 return {*psi_vals, *phi_vals};
344 if (phi_vals->quadrature.weights.size() >= psi_vals->quadrature.weights.size())
346 const Quadrature
quadrature = phi_vals->quadrature;
347 psi_scratch.compute(el_index, is_volume,
quadrature.points, psi_basis, gbasis);
349 psi_vals = &psi_scratch;
353 const Quadrature
quadrature = psi_vals->quadrature;
354 phi_scratch.compute(el_index, is_volume,
quadrature.points, phi_basis, gbasis);
356 phi_vals = &phi_scratch;
359 assert(psi_vals->quadrature.weights.size() == phi_vals->quadrature.weights.size());
360 assert(psi_vals->quadrature.points.rows() == phi_vals->quadrature.points.rows());
361 return {*psi_vals, *phi_vals};
367 if (!body_params.is_array())
373 std::map<int, json> materials;
374 for (
int i = 0; i < body_params.size(); ++i)
376 json mat = body_params[i];
380 for (
int j = 0; j <
id.size(); ++j)
381 materials[
id[j]] = mat;
386 materials[mid] = mat;
390 std::set<int> missing;
392 std::map<int, int> body_element_count;
393 std::vector<int> eid_to_eid_in_body(body_ids.size());
394 for (
int e = 0; e < body_ids.size(); ++e)
396 const int bid = body_ids[e];
397 body_element_count.try_emplace(bid, 0);
398 eid_to_eid_in_body[e] = body_element_count[bid]++;
401 for (
int e = 0; e < body_ids.size(); ++e)
403 const int bid = body_ids[e];
404 const auto it = materials.find(bid);
405 if (it == materials.end())
411 json tmp = it->second;
416 for (
int bid : missing)
418 logger().warn(
"Missing material parameters for body {}", bid);
427 const bool is_volume,
429 const std::vector<ElementBases> &bases,
430 const std::vector<ElementBases> &gbases,
434 const bool is_mass)
const
438 const long int max_triplets_size = long(1e7);
439 const long int buffer_size = std::min(
long(max_triplets_size),
long(n_basis) *
size());
446 stiffness.resize(n_basis *
size(), n_basis *
size());
449 auto storage =
create_thread_storage(LocalThreadMatStorage(buffer_size, stiffness.rows(), stiffness.cols()));
451 const int n_bases = int(bases.size());
454 assert(
cache.is_mass() == is_mass);
462 for (
int e = start; e < end; ++e)
468 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
470 const int n_loc_bases = int(
vals.basis_values.size());
472 for (
int i = 0; i < n_loc_bases; ++i)
476 const auto &global_i =
vals.basis_values[i].global;
479 for (
int j = 0; j <= i; ++j)
483 const auto &global_j =
vals.basis_values[j].global;
487 assert(stiffness_val.size() ==
size() *
size());
491 for (
int n = 0; n <
size(); ++n)
493 for (
int m = 0; m <
size(); ++m)
495 const double local_value = stiffness_val(n *
size() + m);
498 for (
size_t ii = 0; ii < global_i.size(); ++ii)
500 const auto gi = global_i[ii].index *
size() + m;
501 const auto wi = global_i[ii].val;
503 for (
size_t jj = 0; jj < global_j.size(); ++jj)
505 const auto gj = global_j[jj].index *
size() + n;
506 const auto wj = global_j[jj].val;
509 local_storage.cache->add_value(e, gi, gj, local_value * wi * wj);
512 local_storage.cache->add_value(e, gj, gi, local_value * wj * wi);
515 if (local_storage.cache->entries_size() >= max_triplets_size)
517 local_storage.cache->prune();
518 logger().trace(
"cleaning memory. Current storage: {}. mat nnz: {}", local_storage.cache->capacity(), local_storage.cache->non_zeros());
536 logger().trace(
"done separate assembly {}s...", timer.getElapsedTime());
541 std::vector<LocalThreadMatStorage *> storages(storage.size());
543 for (
auto &local_storage : storage)
545 storages[index++] = &local_storage;
550 storages[i]->cache->prune();
553 logger().trace(
"done pruning triplets {}s...", timer.getElapsedTime());
556 std::vector<long int> offsets(storage.size());
559 long int triplet_count = 0;
560 for (
auto &local_storage : storage)
562 offsets[index++] = triplet_count;
563 triplet_count += local_storage.cache->triplet_count();
566 std::vector<Eigen::Triplet<double>> triplets;
568 assert(storages.size() >= 1);
569 if (storages[0]->
cache->is_dense())
573 Eigen::MatrixXd
tmp(stiffness);
574 for (
const LocalThreadMatStorage &local_storage : storage)
575 tmp += dynamic_cast<const DenseMatrixCache &>(*local_storage.
cache).mat();
576 stiffness =
tmp.sparseView();
577 stiffness.makeCompressed();
580 logger().trace(
"Serial assembly time: {}s...", timer.getElapsedTime());
582 else if (triplet_count >= triplets.max_size())
586 logger().warn(
"Cannot allocate space for triplets, switching to serial assembly.");
590 for (LocalThreadMatStorage &local_storage : storage)
591 stiffness += local_storage.
cache->get_matrix(false);
592 stiffness.makeCompressed();
595 logger().trace(
"Serial assembly time: {}s...", timer.getElapsedTime());
600 triplets.resize(triplet_count);
603 logger().trace(
"done allocate triplets {}s...", timer.getElapsedTime());
604 logger().trace(
"Triplets Count: {}", triplet_count);
609 const SparseMatrixCache &cache = dynamic_cast<const SparseMatrixCache &>(*storages[i]->cache);
610 long int offset = offsets[i];
612 std::copy(cache.entries().begin(), cache.entries().end(), triplets.begin() + offset);
613 offset += cache.entries().size();
615 if (cache.mat().nonZeros() > 0)
618 for (int k = 0; k < cache.mat().outerSize(); ++k)
620 for (Eigen::SparseMatrix<double>::InnerIterator it(cache.mat(), k); it; ++it)
622 assert(count < cache.mat().nonZeros());
623 triplets[offset + count++] = Eigen::Triplet<double>(it.row(), it.col(), it.value());
630 logger().trace(
"done concatenate triplets {}s...", timer.getElapsedTime());
634 stiffness.setFromTriplets(triplets.begin(), triplets.end());
637 logger().trace(
"done setFromTriplets assembly {}s...", timer.getElapsedTime());
640 catch (std::bad_alloc &ba)
654 const bool is_volume,
655 const int n_psi_basis,
656 const int n_phi_basis,
657 const std::vector<ElementBases> &psi_bases,
658 const std::vector<ElementBases> &phi_bases,
659 const std::vector<ElementBases> &gbases,
666 assert(phi_bases.size() == psi_bases.size());
668 const int max_triplets_size = int(1e7);
669 const int buffer_size = std::min(
long(max_triplets_size),
long(std::max(n_psi_basis, n_phi_basis)) * std::max(
rows(),
cols()));
672 stiffness.resize(n_phi_basis *
rows(), n_psi_basis *
cols());
675 auto storage =
create_thread_storage(LocalThreadMatStorage(buffer_size, stiffness.rows(), stiffness.cols()));
677 const int n_bases = int(phi_bases.size());
685 for (
int e = start; e < end; ++e)
692 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
693 local_storage.da = phi_vals.
det.array() *
quadrature.weights.array();
694 const int n_phi_loc_bases = int(phi_vals.
basis_values.size());
695 const int n_psi_loc_bases = int(psi_vals.
basis_values.size());
697 for (
int i = 0; i < n_psi_loc_bases; ++i)
701 for (
int j = 0; j < n_phi_loc_bases; ++j)
706 assert(stiffness_val.size() ==
rows() *
cols());
709 for (
int n = 0; n <
rows(); ++n)
711 for (
int m = 0; m <
cols(); ++m)
713 const double local_value = stiffness_val(n *
cols() + m);
715 for (
size_t ii = 0; ii < global_i.size(); ++ii)
717 const auto gi = global_i[ii].index *
cols() + m;
718 const auto wi = global_i[ii].val;
720 for (
size_t jj = 0; jj < global_j.size(); ++jj)
722 const auto gj = global_j[jj].index *
rows() + n;
723 const auto wj = global_j[jj].val;
725 local_storage.cache->add_value(e, gj, gi, local_value * wi * wj);
727 if (local_storage.cache->entries_size() >= max_triplets_size)
729 local_storage.cache->prune();
730 logger().debug(
"cleaning memory...");
742 logger().trace(
"done separate assembly {}s...", timer.getElapsedTime());
746 for (LocalThreadMatStorage &local_storage : storage)
747 stiffness += local_storage.
cache->get_matrix(false);
748 stiffness.makeCompressed();
750 logger().trace(
"done merge assembly {}s...", timer.getElapsedTime());
757 const bool is_volume,
758 const int n_psi_basis,
759 const int n_phi_basis,
760 const std::vector<ElementBases> &psi_bases,
761 const std::vector<ElementBases> &phi_bases,
762 const std::vector<ElementBases> &gbases,
767 const Eigen::MatrixXd &
x,
768 const Eigen::MatrixXd &x_prev,
774 assert(phi_bases.size() == psi_bases.size());
775 assert(phi_bases.size() == gbases.size());
777 const int phi_ndof = n_phi_basis *
rows();
778 const int psi_ndof = n_psi_basis *
cols();
779 Eigen::MatrixXd x_phi, x_psi;
780 Eigen::MatrixXd x_phi_prev, x_psi_prev;
781 split_mixed_solution(split_solution,
x, phi_ndof, psi_ndof, x_phi, x_psi);
782 split_mixed_previous_solution(split_solution, x_prev, phi_ndof, psi_ndof, x_phi_prev, x_psi_prev);
785 const int n_bases = int(phi_bases.size());
791 for (
int e = start; e < end; ++e)
793 const auto [psi_vals, phi_vals] = compute_mixed_element_values(
795 psi_bases[e], phi_bases[e], gbases[e],
796 psi_cache, phi_cache,
797 psi_scratch, local_storage.vals);
801 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
802 local_storage.da = phi_vals.
det.array() *
quadrature.weights.array();
810 for (
const LocalThreadScalarStorage &local_storage : storage)
811 res += local_storage.val;
816 const bool is_volume,
817 const int n_psi_basis,
818 const int n_phi_basis,
819 const std::vector<ElementBases> &psi_bases,
820 const std::vector<ElementBases> &phi_bases,
821 const std::vector<ElementBases> &gbases,
826 const Eigen::MatrixXd &
x,
827 const Eigen::MatrixXd &x_prev,
833 assert(phi_bases.size() == psi_bases.size());
834 assert(phi_bases.size() == gbases.size());
836 const int phi_ndof = n_phi_basis *
rows();
837 const int psi_ndof = n_psi_basis *
cols();
838 Eigen::MatrixXd x_phi, x_psi;
839 Eigen::MatrixXd x_phi_prev, x_psi_prev;
840 split_mixed_solution(split_solution,
x, phi_ndof, psi_ndof, x_phi, x_psi);
841 split_mixed_previous_solution(split_solution, x_prev, phi_ndof, psi_ndof, x_phi_prev, x_psi_prev);
844 const int n_bases = int(phi_bases.size());
845 Eigen::VectorXd out(phi_bases.size());
851 for (
int e = start; e < end; ++e)
853 const auto [psi_vals, phi_vals] = compute_mixed_element_values(
855 psi_bases[e], phi_bases[e], gbases[e],
856 psi_cache, phi_cache,
857 psi_scratch, local_storage.vals);
861 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
862 local_storage.da = phi_vals.
det.array() *
quadrature.weights.array();
871 is_volume, n_psi_basis, n_phi_basis,
872 psi_bases, phi_bases, gbases,
873 psi_cache, phi_cache, t, dt,
x, x_prev, split_solution);
874 assert(std::abs(assemble_val - out.sum()) < std::max(1e-10 * std::abs(assemble_val), 1e-10));
881 const bool is_volume,
882 const int n_psi_basis,
883 const int n_phi_basis,
884 const std::vector<ElementBases> &psi_bases,
885 const std::vector<ElementBases> &phi_bases,
886 const std::vector<ElementBases> &gbases,
891 const Eigen::MatrixXd &
x,
892 const Eigen::MatrixXd &x_prev,
894 Eigen::MatrixXd &grad)
const
899 assert(phi_bases.size() == psi_bases.size());
900 assert(phi_bases.size() == gbases.size());
902 const int phi_ndof = n_phi_basis *
rows();
903 const int psi_ndof = n_psi_basis *
cols();
904 Eigen::MatrixXd x_phi, x_psi;
905 Eigen::MatrixXd x_phi_prev, x_psi_prev;
906 split_mixed_solution(split_solution,
x, phi_ndof, psi_ndof, x_phi, x_psi);
907 split_mixed_previous_solution(split_solution, x_prev, phi_ndof, psi_ndof, x_phi_prev, x_psi_prev);
909 grad.resize(phi_ndof + psi_ndof, 1);
913 const int n_bases = int(phi_bases.size());
919 for (
int e = start; e < end; ++e)
921 const auto [psi_vals, phi_vals] = compute_mixed_element_values(
923 psi_bases[e], phi_bases[e], gbases[e],
924 psi_cache, phi_cache,
925 psi_scratch, local_storage.vals);
929 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
930 local_storage.da = phi_vals.
det.array() *
quadrature.weights.array();
935 const int n_phi_loc_bases = int(phi_vals.
basis_values.size());
936 const int n_psi_loc_bases = int(psi_vals.
basis_values.size());
937 assert(local_grad.size() == n_phi_loc_bases *
rows() + n_psi_loc_bases *
cols());
939 for (
int i = 0; i < n_phi_loc_bases; ++i)
942 for (
int d = 0; d <
rows(); ++d)
944 const double local_value = local_grad(i *
rows() + d);
945 for (
const auto &global : global_i)
946 local_storage.vec(global.index *
rows() + d) += local_value * global.val;
950 const int local_psi_offset = n_phi_loc_bases *
rows();
951 for (
int i = 0; i < n_psi_loc_bases; ++i)
954 for (
int d = 0; d <
cols(); ++d)
956 const double local_value = local_grad(local_psi_offset + i *
cols() + d);
957 for (
const auto &global : global_i)
958 local_storage.vec(phi_ndof + global.index *
cols() + d) += local_value * global.val;
964 for (
const LocalThreadVecStorage &local_storage : storage)
965 grad += local_storage.vec;
969 const bool is_volume,
970 const int n_psi_basis,
971 const int n_phi_basis,
972 const bool project_to_psd,
973 const std::vector<ElementBases> &psi_bases,
974 const std::vector<ElementBases> &phi_bases,
975 const std::vector<ElementBases> &gbases,
980 const Eigen::MatrixXd &
x,
981 const Eigen::MatrixXd &x_prev,
989 assert(phi_bases.size() == psi_bases.size());
990 assert(phi_bases.size() == gbases.size());
992 const int phi_ndof = n_phi_basis *
rows();
993 const int psi_ndof = n_psi_basis *
cols();
994 const int total_ndof = phi_ndof + psi_ndof;
995 Eigen::MatrixXd x_phi, x_psi;
996 Eigen::MatrixXd x_phi_prev, x_psi_prev;
997 split_mixed_solution(split_solution,
x, phi_ndof, psi_ndof, x_phi, x_psi);
998 split_mixed_previous_solution(split_solution, x_prev, phi_ndof, psi_ndof, x_phi_prev, x_psi_prev);
1000 const int max_triplets_size = int(1e7);
1001 const int buffer_size = std::min(max_triplets_size, total_ndof);
1003 mat_cache.
init(total_ndof);
1007 const int n_bases = int(phi_bases.size());
1013 for (
int e = start; e < end; ++e)
1015 const auto element_values = compute_mixed_element_values(
1017 psi_bases[e], phi_bases[e], gbases[e],
1018 psi_cache, phi_cache,
1019 psi_scratch, local_storage.vals);
1020 const auto &psi_vals = element_values.first;
1021 const auto &phi_vals = element_values.second;
1025 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
1026 local_storage.da = phi_vals.
det.array() *
quadrature.weights.array();
1029 MixedNonLinearAssemblerData(psi_vals, phi_vals, t, dt, x_phi, x_psi, x_phi_prev, x_psi_prev, local_storage.da), local_storage.hessian);
1030 local_storage.hessian.visit([&](
auto &local_hessian) {
1031 const int n_phi_loc_bases = int(phi_vals.
basis_values.size());
1032 const int n_psi_loc_bases = int(psi_vals.
basis_values.size());
1033 const int local_size = n_phi_loc_bases *
rows() + n_psi_loc_bases *
cols();
1034 assert(local_hessian.rows() == local_size);
1035 assert(local_hessian.cols() == local_size);
1038 local_hessian = ipc::project_to_psd(local_hessian);
1040 const auto local_index_data = [&](
1041 const int local_index,
1042 const std::vector<basis::Local2Global> *&global,
1044 int &component_count,
1045 int &global_offset) {
1046 assert(local_index >= 0);
1047 assert(local_index < local_size);
1049 const int phi_local_size = n_phi_loc_bases *
rows();
1050 if (local_index < phi_local_size)
1052 const int basis_index = local_index /
rows();
1054 component = local_index %
rows();
1055 component_count =
rows();
1060 const int psi_local_index = local_index - phi_local_size;
1061 const int basis_index = psi_local_index /
cols();
1063 component = psi_local_index %
cols();
1064 component_count =
cols();
1065 global_offset = phi_ndof;
1068 for (
int i = 0; i < local_size; ++i)
1070 const std::vector<basis::Local2Global> *global_i =
nullptr;
1071 int component_i = -1;
1072 int component_count_i = -1;
1073 int global_offset_i = -1;
1074 local_index_data(i, global_i, component_i, component_count_i, global_offset_i);
1076 for (
int j = 0; j < local_size; ++j)
1078 const double local_value = local_hessian(i, j);
1079 if (local_value == 0)
1082 const std::vector<basis::Local2Global> *global_j =
nullptr;
1083 int component_j = -1;
1084 int component_count_j = -1;
1085 int global_offset_j = -1;
1086 local_index_data(j, global_j, component_j, component_count_j, global_offset_j);
1088 for (
const auto &gi : *global_i)
1090 const int row = global_offset_i + gi.index * component_count_i + component_i;
1091 for (
const auto &gj : *global_j)
1093 const int col = global_offset_j + gj.index * component_count_j + component_j;
1094 local_storage.cache->add_value(e, row, col, local_value * gi.val * gj.val);
1098 if (local_storage.cache->entries_size() >= max_triplets_size)
1100 local_storage.cache->prune();
1101 logger().debug(
"cleaning memory...");
1109 for (LocalThreadMatStorage &local_storage : storage)
1111 local_storage.cache->prune();
1112 mat_cache += *local_storage.cache;
1118 const bool is_volume,
1119 const std::vector<ElementBases> &bases,
1120 const std::vector<ElementBases> &gbases,
1124 const Eigen::MatrixXd &displacement,
1125 const Eigen::MatrixXd &displacement_prev)
const
1128 const int n_bases = int(bases.size());
1133 for (
int e = start; e < end; ++e)
1139 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
1140 local_storage.da =
vals.det.array() *
quadrature.weights.array();
1143 local_storage.val +=
val;
1149 for (
const LocalThreadScalarStorage &local_storage : storage)
1150 res += local_storage.val;
1155 const bool is_volume,
1156 const std::vector<ElementBases> &bases,
1157 const std::vector<ElementBases> &gbases,
1161 const Eigen::MatrixXd &displacement,
1162 const Eigen::MatrixXd &displacement_prev)
const
1165 const int n_bases = int(bases.size());
1166 Eigen::VectorXd out(bases.size());
1171 for (
int e = start; e < end; ++e)
1177 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
1178 local_storage.da =
vals.det.array() *
quadrature.weights.array();
1187 is_volume, bases, gbases,
cache, t, dt, displacement, displacement_prev);
1188 assert(std::abs(assemble_val - out.sum()) < std::max(1e-10 * assemble_val, 1e-10));
1195 const bool is_volume,
1197 const std::vector<ElementBases> &bases,
1198 const std::vector<ElementBases> &gbases,
1202 const Eigen::MatrixXd &displacement,
1203 const Eigen::MatrixXd &displacement_prev,
1204 Eigen::MatrixXd &rhs)
const
1206 rhs.resize(n_basis *
size(), 1);
1211 const int n_bases = int(bases.size());
1216 for (
int e = start; e < end; ++e)
1224 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
1225 local_storage.da =
vals.det.array() *
quadrature.weights.array();
1226 const int n_loc_bases = int(
vals.basis_values.size());
1229 assert(
val.size() == n_loc_bases *
size());
1231 for (
int j = 0; j < n_loc_bases; ++j)
1233 const auto &global_j =
vals.basis_values[j].global;
1236 for (
int m = 0; m <
size(); ++m)
1238 const double local_value =
val(j *
size() + m);
1240 for (
size_t jj = 0; jj < global_j.size(); ++jj)
1242 const auto gj = global_j[jj].index *
size() + m;
1243 const auto wj = global_j[jj].val;
1245 local_storage.vec(gj) += local_value * wj;
1259 for (
const LocalThreadVecStorage &local_storage : storage)
1260 rhs += local_storage.
vec;
1264 const bool is_volume,
1266 const bool project_to_psd,
1267 const std::vector<ElementBases> &bases,
1268 const std::vector<ElementBases> &gbases,
1269 const AssemblyValsCache &
cache,
1272 const Eigen::MatrixXd &displacement,
1273 const Eigen::MatrixXd &displacement_prev,
1274 MatrixCache &mat_cache,
1277 const int dimension =
size();
1278 const int max_triplets_size = int(1e7);
1279 const int buffer_size = std::min(
long(max_triplets_size),
long(n_basis) *
size());
1285 const auto *sparse_cache =
dynamic_cast<const SparseMatrixCache *
>(&mat_cache);
1286 const bool cached = sparse_cache && sparse_cache->mapping_size() > 0;
1288 mat_cache.init(n_basis *
size());
1289 mat_cache.set_zero();
1293 const int n_bases = int(bases.size());
1294 const bool has_basis_cache =
cache.is_initialized();
1298 const auto assemble_elements = [&](
auto dimension_tag) {
1299 constexpr int Dimension =
decltype(dimension_tag)::value;
1300 const int dim = Dimension == Eigen::Dynamic ? dimension : Dimension;
1303 auto *cached_worker = cached ?
dynamic_cast<SparseMatrixCache *
>(local_storage.cache.get()) : nullptr;
1305 for (
int e = start;
e < end; ++
e)
1308 ElementAssemblyValues uncached_values;
1309 if (!has_basis_cache)
1310 cache.compute(e, is_volume, bases[e], gbases[e], uncached_values);
1311 const ElementAssemblyValues &
vals =
1312 has_basis_cache ?
cache.cached_values(e) : uncached_values;
1313 auto &
da = local_storage.da;
1317 assert(MAX_QUAD_POINTS == -1 ||
quadrature.weights.size() < MAX_QUAD_POINTS);
1319 const int n_loc_bases = int(
vals.basis_values.size());
1321 auto &local_hessian = local_storage.hessian;
1322 assemble_hessian(NonLinearAssemblerData(
vals, t, dt, displacement, displacement_prev,
da), local_hessian);
1323 local_hessian.visit([&](
auto &stiffness_val) {
1324 assert(stiffness_val.rows() == n_loc_bases * dim);
1325 assert(stiffness_val.cols() == n_loc_bases * dim);
1328 stiffness_val = ipc::project_to_psd(stiffness_val);
1347 const auto scatter_element = [&](
auto add_value) {
1348 for (
int i = 0; i < n_loc_bases; ++i)
1350 const auto &global_i =
vals.basis_values[i].global;
1352 for (
int j = 0; j < n_loc_bases; ++j)
1355 const auto &global_j =
vals.basis_values[j].global;
1357 for (
int n = 0; n <
dim; ++n)
1359 for (
int m = 0; m <
dim; ++m)
1361 const double local_value = stiffness_val(i * dim + m, j * dim + n);
1363 for (
size_t ii = 0; ii < global_i.size(); ++ii)
1365 const auto gi = global_i[ii].index *
dim + m;
1366 const auto wi = global_i[ii].val;
1368 for (
size_t jj = 0; jj < global_j.size(); ++jj)
1370 const auto gj = global_j[jj].index *
dim + n;
1371 const auto wj = global_j[jj].val;
1373 add_value(gi, gj, local_value * wi * wj);
1381 if (cached_worker &&
vals.has_single_unit_mapping())
1383 auto writer = cached_worker->cached_element_writer(e);
1384 if constexpr (Dimension != Eigen::Dynamic)
1386 if (n_loc_bases == Dimension + 1)
1387 add_unit_weight_hessian<Dimension, Dimension + 1>(stiffness_val, n_loc_bases, dim, writer);
1389 add_unit_weight_hessian<Dimension, Eigen::Dynamic>(stiffness_val, n_loc_bases, dim, writer);
1392 add_unit_weight_hessian<Eigen::Dynamic, Eigen::Dynamic>(stiffness_val, n_loc_bases, dim, writer);
1394 else if (cached_worker)
1396 scatter_element([writer = cached_worker->cached_element_writer(e)](
int,
int,
double value)
mutable { writer.add(value); });
1400 scatter_element([&](
int gi,
int gj,
double value) {
1401 local_storage.cache->add_value(e, gi, gj, value);
1402 if (local_storage.cache->entries_size() >= max_triplets_size)
1404 local_storage.cache->prune();
1405 logger().debug(
"cleaning memory...");
1414 assemble_elements(std::integral_constant<int, 2>{});
1415 else if (dimension == 3)
1416 assemble_elements(std::integral_constant<int, 3>{});
1418 assemble_elements(std::integral_constant<int, Eigen::Dynamic>{});
1421 logger().trace(
"done separate assembly {}s...", timer.getElapsedTime());
1426 for (LocalThreadMatStorage &local_storage : storage)
1428 local_storage.cache->prune();
1429 mat_cache += *local_storage.cache;
1431 hess = mat_cache.get_matrix();
1434 logger().trace(
"done merge assembly {}s...", timer.getElapsedTime());
1439#ifdef POLYFEM_WITH_MISO
1442 logger().error(
"Enable Bezier library to use the robust Jacobian check!");
std::unique_ptr< MatrixCache > cache
ElementAssemblyValues vals
void set_materials(const std::vector< int > &body_ids, const json &body_params, const Units &units, const io::ResourceIO &resources)
virtual void assemble(const bool is_volume, const int n_basis, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &cache, const double t, StiffnessMatrix &stiffness, const bool is_mass=false) const
virtual std::string name() const =0
virtual void add_multimaterial(const int index, const json ¶ms, const Units &units, const io::ResourceIO &resources)
Caches basis evaluation and geometric mapping at every element.
const ElementAssemblyValues & get_or_compute(const int el_index, const bool is_volume, const basis::ElementBases &basis, const basis::ElementBases &gbasis, ElementAssemblyValues &scratch) const
Returns cached values, or computes into scratch when the cache is empty.
Scratch for one output point. All tensor storage has a fixed 3x3 capacity.
const MatrixNd & deformation_
const MatrixNd & deformation() const
const MatrixNd & inverse()
const MatrixNd & tensor(ElasticityTensorType type)
virtual bool compute_output_stress(const OutputData &data, const ElementAssemblyValues &vals, Eigen::Index point, const MatrixNd &displacement_gradient, OutputStress &stress) const
Return false to use a material's legacy assign_stress_tensor implementation.
virtual void assign_stress_tensor(const OutputData &data, const int all_size, const ElasticityTensorType &type, Eigen::MatrixXd &all, const std::function< Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const
bool evaluate_output_stress(const OutputData &data, bool need_stress, bool need_energy, const std::function< void(Eigen::Index, OutputStress &)> &emit) const
void compute_von_mises_stresses(const OutputData &data, Eigen::MatrixXd &stresses) const
void compute_scalar_value(const OutputData &data, std::vector< NamedMatrix > &result) const override
void compute_tensor_value(const OutputData &data, std::vector< NamedMatrix > &result) const override
void compute_output_values(const OutputData &data, std::vector< NamedMatrix > *scalar, std::vector< NamedMatrix > *tensor) const override
Evaluate requested output families together using element-local scratch.
void set_use_robust_jacobian()
void compute_stress_tensor(const OutputData &data, const ElasticityTensorType &type, Eigen::MatrixXd &stresses) const
void compute_energy_density(const OutputData &data, Eigen::MatrixXd &energy) const
Elastic energy density at data.local_pts, one row per point.
stores per element basis values at given quadrature points and geometric mapping
std::vector< AssemblyValues > basis_values
void compute(const int el_index, const bool is_volume, const Eigen::MatrixXd &pts, const basis::ElementBases &basis, const basis::ElementBases &gbasis)
computes the per element values at the local (ref el) points (pts) sets basis_values,...
quadrature::Quadrature quadrature
void assemble(const bool is_volume, const int n_basis, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &cache, const double t, StiffnessMatrix &stiffness, const bool is_mass=false) const override
assembles the stiffness matrix for the given basis the bilinear form (local assembler) is encoded by ...
virtual int rows() const =0
void assemble(const bool is_volume, const int n_psi_basis, const int n_phi_basis, const std::vector< basis::ElementBases > &psi_bases, const std::vector< basis::ElementBases > &phi_bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &psi_cache, const AssemblyValsCache &phi_cache, const double t, StiffnessMatrix &stiffness) const
virtual int cols() const =0
void assemble_gradient(const bool is_volume, const int n_psi_basis, const int n_phi_basis, const std::vector< basis::ElementBases > &psi_bases, const std::vector< basis::ElementBases > &phi_bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &psi_cache, const AssemblyValsCache &phi_cache, const double t, const double dt, const Eigen::MatrixXd &x, const Eigen::MatrixXd &x_prev, const SolutionSplitter &split_solution, Eigen::MatrixXd &grad) const
virtual void compute_hessian(const MixedNonLinearAssemblerData &data, LocalHessian &hessian) const =0
virtual int rows() const =0
virtual double compute_energy(const MixedNonLinearAssemblerData &data) const =0
void assemble_hessian(const bool is_volume, const int n_psi_basis, const int n_phi_basis, const bool project_to_psd, const std::vector< basis::ElementBases > &psi_bases, const std::vector< basis::ElementBases > &phi_bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &psi_cache, const AssemblyValsCache &phi_cache, const double t, const double dt, const Eigen::MatrixXd &x, const Eigen::MatrixXd &x_prev, const SolutionSplitter &split_solution, utils::MatrixCache &mat_cache, StiffnessMatrix &hessian) const
Eigen::VectorXd assemble_energy_per_element(const bool is_volume, const int n_psi_basis, const int n_phi_basis, const std::vector< basis::ElementBases > &psi_bases, const std::vector< basis::ElementBases > &phi_bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &psi_cache, const AssemblyValsCache &phi_cache, const double t, const double dt, const Eigen::MatrixXd &x, const Eigen::MatrixXd &x_prev, const SolutionSplitter &split_solution) const
virtual Eigen::VectorXd compute_gradient(const MixedNonLinearAssemblerData &data) const =0
std::function< void(const Eigen::MatrixXd &x, Eigen::MatrixXd &x_phi, Eigen::MatrixXd &x_psi)> SolutionSplitter
double assemble_energy(const bool is_volume, const int n_psi_basis, const int n_phi_basis, const std::vector< basis::ElementBases > &psi_bases, const std::vector< basis::ElementBases > &phi_bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &psi_cache, const AssemblyValsCache &phi_cache, const double t, const double dt, const Eigen::MatrixXd &x, const Eigen::MatrixXd &x_prev, const SolutionSplitter &split_solution) const
virtual int cols() const =0
double assemble_energy(const bool is_volume, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &cache, const double t, const double dt, const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &displacement_prev) const override
Eigen::VectorXd assemble_energy_per_element(const bool is_volume, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &cache, const double t, const double dt, const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &displacement_prev) const override
virtual double compute_energy(const NonLinearAssemblerData &data) const =0
void assemble_gradient(const bool is_volume, const int n_basis, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &cache, const double t, const double dt, const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &displacement_prev, Eigen::MatrixXd &rhs) const override
void assemble_hessian(const bool is_volume, const int n_basis, const bool project_to_psd, const std::vector< basis::ElementBases > &bases, const std::vector< basis::ElementBases > &gbases, const AssemblyValsCache &cache, const double t, const double dt, const Eigen::MatrixXd &displacement, const Eigen::MatrixXd &displacement_prev, utils::MatrixCache &mat_cache, StiffnessMatrix &grad) const override
const basis::ElementBases & bs
const Eigen::MatrixXd & fun
const Eigen::MatrixXd & local_pts
const basis::ElementBases & gbs
std::vector< Basis > bases
one basis function per node in the element
Read-only interface to a hierarchical collection of simulation resources.
abstract class used for caching
virtual void set_zero()=0
virtual StiffnessMatrix get_matrix(const bool compute_mapping=true)=0
virtual void init(const size_t size)=0
constexpr const char * MATERIAL_ELEMENT_INDEX
auto & get_local_thread_storage(Storages &storage, int thread_id)
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic, 0, 3, 3 > inverse(const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic, 0, 3, 3 > &mat)
auto create_thread_storage(const LocalStorage &initial_local_storage)
T determinant(const Eigen::Matrix< T, rows, cols, option, maxRow, maxCol > &mat)
void maybe_parallel_for(int size, const std::function< void(int, int, int)> &partial_for)
spdlog::logger & logger()
Retrieves the current logger.
double von_mises_stress_for_stress_tensor(const Eigen::MatrixXd &stress)
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 3, 3 > MatrixNd
void log_and_throw_error(const std::string &msg)
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix