PolyFEM
Loading...
Searching...
No Matches
Assembler.cpp
Go to the documentation of this file.
1#include "Assembler.hpp"
2#include "MatParams.hpp"
3
7
8#include <igl/Timer.h>
9
10#include <ipc/utils/eigen_ext.hpp>
11
12#include <algorithm>
13#include <cmath>
14#include <set>
15#include <type_traits>
16#include <utility>
17
18namespace polyfem::assembler
19{
20 using namespace basis;
21 using namespace quadrature;
22 using namespace utils;
23
25 {
26 if (!inverse_ready_)
27 {
28 inverse_ = deformation_.inverse();
29 inverse_ready_ = true;
30 }
31 return inverse_;
32 }
33
35 {
36 if (!determinant_ready_)
37 {
38 determinant_ = native_type == ElasticityTensorType::PK1
39 ? utils::determinant(deformation_)
40 : deformation_.determinant();
41 determinant_ready_ = true;
42 }
43 return determinant_;
44 }
45
47 {
48 if (type == ElasticityTensorType::F)
49 return deformation_;
50 if (type == native_type)
51 return native;
52 // Preserve the existing Cauchy-to-PK behavior for NaN inputs.
53 if (native_type == ElasticityTensorType::CAUCHY && (native.hasNaN() || deformation_.hasNaN()))
54 return deformation_;
55 const int index = static_cast<int>(type);
56 assert(index >= 0 && index < 3);
57 if (!computed_[index])
58 {
59 if (native_type == ElasticityTensorType::PK1)
60 {
62 tensors_[index] = (native * deformation_.transpose()) / determinant();
63 else
64 tensors_[index] = inverse() * native;
65 }
66 else if (type == ElasticityTensorType::PK1)
67 tensors_[index] = determinant() * native * inverse().transpose();
68 else
69 tensors_[index] = determinant() * inverse() * native * inverse().transpose();
70 computed_[index] = true;
71 }
72 return tensors_[index];
73 }
74
76 const OutputData &data, const bool need_stress, const bool need_energy,
77 const std::function<void(Eigen::Index, OutputStress &)> &emit) const
78 {
79 assert(data.fun.cols() == 1);
81 vals.compute(data.el_id, size() == 3, data.local_pts, data.bs, data.gbs);
82 MatrixNd gradient(size(), size());
83 for (Eigen::Index p = 0; p < data.local_pts.rows(); ++p)
84 {
85 gradient.setZero();
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();
91 const MatrixNd deformation = MatrixNd::Identity(size(), size()) + gradient;
92 OutputStress stress(deformation);
93 stress.needs_stress = need_stress;
94 stress.needs_energy = need_energy;
95 if ((need_stress || need_energy) && !compute_output_stress(data, vals, p, gradient, stress))
96 return false;
97 emit(p, stress);
98 }
99 return true;
100 }
101
103 const OutputData &data, const int all_size, const ElasticityTensorType &type,
104 Eigen::MatrixXd &all, const std::function<Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const
105 {
106 all.resize(data.local_pts.rows(), all_size);
107 Eigen::MatrixXd tensor(size(), size());
108 const bool supported = evaluate_output_stress(data, type != ElasticityTensorType::F && type != ElasticityTensorType::ENERGY,
109 type == ElasticityTensorType::ENERGY, [&](Eigen::Index p, OutputStress &stress) {
111 all(p, 0) = stress.energy;
112 else if (type != ElasticityTensorType::F && !stress.has_stress)
113 all.row(p).setConstant(std::nan(""));
114 else
115 {
116 tensor = stress.tensor(type);
117 all.row(p) = fun(tensor);
118 }
119 });
120 if (!supported)
121 log_and_throw_error("Output stress is not implemented by {}", name());
122 }
123
124 void ElasticityAssembler::compute_scalar_value(const OutputData &data, std::vector<NamedMatrix> &result) const
125 {
126 compute_output_values(data, &result, nullptr);
127 }
128
129 void ElasticityAssembler::compute_tensor_value(const OutputData &data, std::vector<NamedMatrix> &result) const
130 {
131 compute_output_values(data, nullptr, &result);
132 }
133
135 const OutputData &data, std::vector<NamedMatrix> *scalar, std::vector<NamedMatrix> *tensor) const
136 {
137 if (!scalar && !tensor)
138 return;
139 if (scalar)
140 {
141 scalar->clear();
142 scalar->emplace_back("von_mises", Eigen::MatrixXd(data.local_pts.rows(), 1));
143 }
144 if (tensor)
145 {
146 tensor->clear();
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));
150 }
151 const bool supported = evaluate_output_stress(data, true, tensor != nullptr, [&](Eigen::Index p, OutputStress &stress) {
152 if (scalar)
153 (*scalar)[0].second(p) = stress.has_stress
155 : std::nan("");
156 if (tensor)
157 {
158 for (int k = 0; k < 3; ++k)
159 {
160 if (stress.has_stress)
161 {
162 const auto &value = stress.tensor(static_cast<ElasticityTensorType>(k));
163 (*tensor)[k].second.row(p) = Eigen::Map<const Eigen::RowVectorXd>(value.data(), size() * size());
164 }
165 else
166 (*tensor)[k].second.row(p).setConstant(std::nan(""));
167 }
168 const auto &F = stress.deformation();
169 (*tensor)[3].second.row(p) = Eigen::Map<const Eigen::RowVectorXd>(F.data(), size() * size());
170 (*tensor)[4].second(p) = stress.energy;
171 }
172 });
173 if (!supported)
174 {
175 if (scalar)
176 compute_von_mises_stresses(data, (*scalar)[0].second);
177 if (tensor)
178 {
179 for (int k = 0; k < 4; ++k)
180 compute_stress_tensor(data, static_cast<ElasticityTensorType>(k), (*tensor)[k].second);
181 compute_energy_density(data, (*tensor)[4].second);
182 }
183 }
184 }
185
186 namespace
187 {
188 template <int Dimension, int BasisCount, typename Matrix>
189 void add_unit_weight_hessian(const Eigen::MatrixBase<Matrix> &hessian,
190 const int n_bases, const int dimension, SparseMatrixCache::CachedElementWriter writer)
191 {
192 const int nb = BasisCount == Eigen::Dynamic ? n_bases : BasisCount;
193 const int dim = Dimension == Eigen::Dynamic ? dimension : Dimension;
194 // Match the basis-pair/component order used to build the sparse mapping.
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));
200 }
201
202 class LocalThreadMatStorage
203 {
204 public:
205 std::unique_ptr<MatrixCache> cache = nullptr;
206 ElementAssemblyValues vals;
207 QuadratureVector da;
208 LocalHessian hessian;
209
210 LocalThreadMatStorage() = delete;
211
212 LocalThreadMatStorage(const int buffer_size, const int rows, const int cols)
213 {
214 init(buffer_size, rows, cols);
215 }
216
217 LocalThreadMatStorage(const int buffer_size, const MatrixCache &c)
218 {
219 init(buffer_size, c);
220 }
221
222 LocalThreadMatStorage(const LocalThreadMatStorage &other)
223 : cache(other.cache->copy()), vals(other.vals), da(other.da), hessian(other.hessian)
224 {
225 }
226
227 LocalThreadMatStorage &operator=(const LocalThreadMatStorage &other)
228 {
229 assert(other.cache != nullptr);
230 cache = other.cache->copy();
231 vals = other.vals;
232 da = other.da;
233 hessian = other.hessian;
234 return *this;
235 }
236
237 void init(const int buffer_size, const int rows, const int cols)
238 {
239 // assert(rows == cols);
240 // cache = std::make_unique<DenseMatrixCache>();
241 cache = std::make_unique<SparseMatrixCache>();
242 cache->reserve(buffer_size);
243 cache->init(rows, cols);
244 }
245
246 void init(const int buffer_size, const MatrixCache &c)
247 {
248 if (cache == nullptr)
249 cache = c.copy();
250 cache->reserve(buffer_size);
251 cache->init(c);
252 }
253 };
254
255 class LocalThreadVecStorage
256 {
257 public:
258 Eigen::MatrixXd vec;
259 ElementAssemblyValues vals;
260 QuadratureVector da;
261
262 LocalThreadVecStorage(const int size)
263 {
264 vec.resize(size, 1);
265 vec.setZero();
266 }
267 };
268
269 class LocalThreadScalarStorage
270 {
271 public:
272 double val;
273 ElementAssemblyValues vals;
274 QuadratureVector da;
275
276 LocalThreadScalarStorage()
277 {
278 val = 0;
279 }
280 };
281
282 void split_mixed_solution(
283 const MixedNLAssembler::SolutionSplitter &split_solution,
284 const Eigen::MatrixXd &x,
285 const int phi_ndof,
286 const int psi_ndof,
287 Eigen::MatrixXd &x_phi,
288 Eigen::MatrixXd &x_psi)
289 {
290 assert(split_solution);
291
292 split_solution(x, x_phi, x_psi);
293
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);
298 }
299
300 void split_mixed_previous_solution(
301 const MixedNLAssembler::SolutionSplitter &split_solution,
302 const Eigen::MatrixXd &x,
303 const int phi_ndof,
304 const int psi_ndof,
305 Eigen::MatrixXd &x_phi,
306 Eigen::MatrixXd &x_psi)
307 {
308 if (x.size() == 0)
309 {
310 x_phi.resize(0, 1);
311 x_psi.resize(0, 1);
312 return;
313 }
314
315 split_mixed_solution(split_solution, x, phi_ndof, psi_ndof, x_phi, x_psi);
316 }
317
318 std::pair<const ElementAssemblyValues &, const ElementAssemblyValues &> compute_mixed_element_values(
319 const int el_index,
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)
328 {
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);
331
332 const auto same_quadrature = [&]() {
333 if (psi_vals->quadrature.weights.size() != phi_vals->quadrature.weights.size())
334 return false;
335 if (psi_vals->quadrature.points.rows() != phi_vals->quadrature.points.rows()
336 || psi_vals->quadrature.points.cols() != phi_vals->quadrature.points.cols())
337 return false;
338 return (psi_vals->quadrature.points - phi_vals->quadrature.points).cwiseAbs().maxCoeff() < 1e-14;
339 };
340
341 if (same_quadrature())
342 return {*psi_vals, *phi_vals};
343
344 if (phi_vals->quadrature.weights.size() >= psi_vals->quadrature.weights.size())
345 {
346 const Quadrature quadrature = phi_vals->quadrature;
347 psi_scratch.compute(el_index, is_volume, quadrature.points, psi_basis, gbasis);
348 psi_scratch.quadrature = quadrature;
349 psi_vals = &psi_scratch;
350 }
351 else
352 {
353 const Quadrature quadrature = psi_vals->quadrature;
354 phi_scratch.compute(el_index, is_volume, quadrature.points, phi_basis, gbasis);
355 phi_scratch.quadrature = quadrature;
356 phi_vals = &phi_scratch;
357 }
358
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};
362 }
363 } // namespace
364
365 void Assembler::set_materials(const std::vector<int> &body_ids, const json &body_params, const Units &units, const io::ResourceIO &resources)
366 {
367 if (!body_params.is_array())
368 {
369 this->add_multimaterial(0, body_params, units, resources);
370 return;
371 }
373 std::map<int, json> materials;
374 for (int i = 0; i < body_params.size(); ++i)
375 {
376 json mat = body_params[i];
377 json id = mat["id"];
378 if (id.is_array())
379 {
380 for (int j = 0; j < id.size(); ++j)
381 materials[id[j]] = mat;
382 }
383 else
384 {
385 const int mid = id;
386 materials[mid] = mat;
387 }
388 }
389
390 std::set<int> missing;
391
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)
395 {
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]++;
399 }
400
401 for (int e = 0; e < body_ids.size(); ++e)
402 {
403 const int bid = body_ids[e];
404 const auto it = materials.find(bid);
405 if (it == materials.end())
406 {
407 missing.insert(bid);
408 continue;
409 }
410
411 json tmp = it->second;
412 tmp[MATERIAL_ELEMENT_INDEX] = eid_to_eid_in_body[e];
413 this->add_multimaterial(e, tmp, units, resources);
414 }
415
416 for (int bid : missing)
417 {
418 logger().warn("Missing material parameters for body {}", bid);
419 }
420 }
421
425
427 const bool is_volume,
428 const int n_basis,
429 const std::vector<ElementBases> &bases,
430 const std::vector<ElementBases> &gbases,
432 const double t,
433 StiffnessMatrix &stiffness,
434 const bool is_mass) const
435 {
436 assert(size() > 0);
437
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());
440 // #ifdef POLYFEM_WITH_TBB
441 // buffer_size /= tbb::task_scheduler_init::default_num_threads();
442 // #endif
443 // logger().trace("buffer_size {}", buffer_size);
444 try
445 {
446 stiffness.resize(n_basis * size(), n_basis * size());
447 stiffness.setZero();
448
449 auto storage = create_thread_storage(LocalThreadMatStorage(buffer_size, stiffness.rows(), stiffness.cols()));
450
451 const int n_bases = int(bases.size());
452 igl::Timer timer;
453 timer.start();
454 assert(cache.is_mass() == is_mass);
455
456 // (potentially parallel) loop over elements
457 // Note that n_bases is the number of elements since ach ElementBases object stores
458 // all local basis functions on a given element
459 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
460 LocalThreadMatStorage &local_storage = get_local_thread_storage(storage, thread_id);
461
462 for (int e = start; e < end; ++e)
463 {
464 const ElementAssemblyValues &vals = cache.get_or_compute(e, is_volume, bases[e], gbases[e], local_storage.vals);
465
466 const Quadrature &quadrature = vals.quadrature;
467
468 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
469 local_storage.da = vals.det.array() * quadrature.weights.array();
470 const int n_loc_bases = int(vals.basis_values.size());
471
472 for (int i = 0; i < n_loc_bases; ++i)
473 {
474 // const AssemblyValues &values_i = vals.basis_values[i];
475 // const Eigen::MatrixXd &gradi = values_i.grad_t_m;
476 const auto &global_i = vals.basis_values[i].global;
477
478 // loop over other bases up to the current one, taking advantage of symmetry
479 for (int j = 0; j <= i; ++j)
480 {
481 // const AssemblyValues &values_j = vals.basis_values[j];
482 // const Eigen::MatrixXd &gradj = values_j.grad_t_m;
483 const auto &global_j = vals.basis_values[j].global;
484
485 // compute local entry in stiffness matrix
486 const auto stiffness_val = assemble(LinearAssemblerData(vals, t, i, j, local_storage.da));
487 assert(stiffness_val.size() == size() * size());
488
489 // igl::Timer t1; t1.start();
490 // loop over dimensions of the problem
491 for (int n = 0; n < size(); ++n)
492 {
493 for (int m = 0; m < size(); ++m)
494 {
495 const double local_value = stiffness_val(n * size() + m);
496
497 // loop over the global nodes corresponding to local element (useful for non-conforming cases)
498 for (size_t ii = 0; ii < global_i.size(); ++ii)
499 {
500 const auto gi = global_i[ii].index * size() + m;
501 const auto wi = global_i[ii].val;
502
503 for (size_t jj = 0; jj < global_j.size(); ++jj)
504 {
505 const auto gj = global_j[jj].index * size() + n;
506 const auto wj = global_j[jj].val;
507
508 // add local value to the global matrix (weighted by corresponding nodes)
509 local_storage.cache->add_value(e, gi, gj, local_value * wi * wj);
510 if (j < i)
511 {
512 local_storage.cache->add_value(e, gj, gi, local_value * wj * wi);
513 }
514
515 if (local_storage.cache->entries_size() >= max_triplets_size)
516 {
517 local_storage.cache->prune();
518 logger().trace("cleaning memory. Current storage: {}. mat nnz: {}", local_storage.cache->capacity(), local_storage.cache->non_zeros());
519 }
520 }
521 }
522 }
523 }
524
525 // t1.stop();
526 // if (!vals.has_parameterization) { logger().trace("-- t1: " {}, t1.getElapsedTime()); }
527 }
528 }
529
530 // timer.stop();
531 // if (!vals.has_parameterization) { logger().trace("-- Timer: {}", timer.getElapsedTime()); }
532 }
533 });
534
535 timer.stop();
536 logger().trace("done separate assembly {}s...", timer.getElapsedTime());
537
538 // Assemble the stiffness matrix by concatenating the tuples in each local storage
539
540 // Collect thread storages
541 std::vector<LocalThreadMatStorage *> storages(storage.size());
542 long int index = 0;
543 for (auto &local_storage : storage)
544 {
545 storages[index++] = &local_storage;
546 }
547
548 timer.start();
549 maybe_parallel_for(storages.size(), [&](int i) {
550 storages[i]->cache->prune();
551 });
552 timer.stop();
553 logger().trace("done pruning triplets {}s...", timer.getElapsedTime());
554
555 // Prepares for parallel concatenation
556 std::vector<long int> offsets(storage.size());
557
558 index = 0;
559 long int triplet_count = 0;
560 for (auto &local_storage : storage)
561 {
562 offsets[index++] = triplet_count;
563 triplet_count += local_storage.cache->triplet_count();
564 }
565
566 std::vector<Eigen::Triplet<double>> triplets;
567
568 assert(storages.size() >= 1);
569 if (storages[0]->cache->is_dense())
570 {
571 timer.start();
572 // Serially merge local storages
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();
578 timer.stop();
579
580 logger().trace("Serial assembly time: {}s...", timer.getElapsedTime());
581 }
582 else if (triplet_count >= triplets.max_size())
583 {
584 // Serial fallback version in case the vector of triplets cannot be allocated
585
586 logger().warn("Cannot allocate space for triplets, switching to serial assembly.");
587
588 timer.start();
589 // Serially merge local storages
590 for (LocalThreadMatStorage &local_storage : storage)
591 stiffness += local_storage.cache->get_matrix(false); // will also prune
592 stiffness.makeCompressed();
593 timer.stop();
594
595 logger().trace("Serial assembly time: {}s...", timer.getElapsedTime());
596 }
597 else
598 {
599 timer.start();
600 triplets.resize(triplet_count);
601 timer.stop();
602
603 logger().trace("done allocate triplets {}s...", timer.getElapsedTime());
604 logger().trace("Triplets Count: {}", triplet_count);
605
606 timer.start();
607 // Parallel copy into triplets
608 maybe_parallel_for(storages.size(), [&](int i) {
609 const SparseMatrixCache &cache = dynamic_cast<const SparseMatrixCache &>(*storages[i]->cache);
610 long int offset = offsets[i];
611
612 std::copy(cache.entries().begin(), cache.entries().end(), triplets.begin() + offset);
613 offset += cache.entries().size();
614
615 if (cache.mat().nonZeros() > 0)
616 {
617 long int count = 0;
618 for (int k = 0; k < cache.mat().outerSize(); ++k)
619 {
620 for (Eigen::SparseMatrix<double>::InnerIterator it(cache.mat(), k); it; ++it)
621 {
622 assert(count < cache.mat().nonZeros());
623 triplets[offset + count++] = Eigen::Triplet<double>(it.row(), it.col(), it.value());
624 }
625 }
626 }
627 });
628
629 timer.stop();
630 logger().trace("done concatenate triplets {}s...", timer.getElapsedTime());
631
632 timer.start();
633 // Sort and assemble
634 stiffness.setFromTriplets(triplets.begin(), triplets.end());
635 timer.stop();
636
637 logger().trace("done setFromTriplets assembly {}s...", timer.getElapsedTime());
638 }
639 }
640 catch (std::bad_alloc &ba)
641 {
642 log_and_throw_error("bad alloc {}", ba.what());
643 }
644
645 // stiffness.resize(n_basis*size(), n_basis*size());
646 // stiffness.setFromTriplets(entries.begin(), entries.end());
647 }
648
652
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,
660 const AssemblyValsCache &psi_cache,
661 const AssemblyValsCache &phi_cache,
662 const double t,
663 StiffnessMatrix &stiffness) const
664 {
665 assert(size() > 0);
666 assert(phi_bases.size() == psi_bases.size());
667
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()));
670 // logger().debug("buffer_size {}", buffer_size);
671
672 stiffness.resize(n_phi_basis * rows(), n_psi_basis * cols());
673 stiffness.setZero();
674
675 auto storage = create_thread_storage(LocalThreadMatStorage(buffer_size, stiffness.rows(), stiffness.cols()));
676
677 const int n_bases = int(phi_bases.size());
678 igl::Timer timer;
679 timer.start();
680
681 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
682 LocalThreadMatStorage &local_storage = get_local_thread_storage(storage, thread_id);
683 ElementAssemblyValues psi_scratch, phi_scratch;
684
685 for (int e = start; e < end; ++e)
686 {
687 const ElementAssemblyValues &psi_vals = psi_cache.get_or_compute(e, is_volume, psi_bases[e], gbases[e], psi_scratch);
688 const ElementAssemblyValues &phi_vals = phi_cache.get_or_compute(e, is_volume, phi_bases[e], gbases[e], phi_scratch);
689
690 const Quadrature &quadrature = phi_vals.quadrature;
691
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());
696
697 for (int i = 0; i < n_psi_loc_bases; ++i)
698 {
699 const auto &global_i = psi_vals.basis_values[i].global;
700
701 for (int j = 0; j < n_phi_loc_bases; ++j)
702 {
703 const auto &global_j = phi_vals.basis_values[j].global;
704
705 const auto stiffness_val = assemble(MixedAssemblerData(psi_vals, phi_vals, t, i, j, local_storage.da));
706 assert(stiffness_val.size() == rows() * cols());
707
708 // igl::Timer t1; t1.start();
709 for (int n = 0; n < rows(); ++n)
710 {
711 for (int m = 0; m < cols(); ++m)
712 {
713 const double local_value = stiffness_val(n * cols() + m);
714
715 for (size_t ii = 0; ii < global_i.size(); ++ii)
716 {
717 const auto gi = global_i[ii].index * cols() + m;
718 const auto wi = global_i[ii].val;
719
720 for (size_t jj = 0; jj < global_j.size(); ++jj)
721 {
722 const auto gj = global_j[jj].index * rows() + n;
723 const auto wj = global_j[jj].val;
724
725 local_storage.cache->add_value(e, gj, gi, local_value * wi * wj);
726
727 if (local_storage.cache->entries_size() >= max_triplets_size)
728 {
729 local_storage.cache->prune();
730 logger().debug("cleaning memory...");
731 }
732 }
733 }
734 }
735 }
736 }
737 }
738 }
739 });
740
741 timer.stop();
742 logger().trace("done separate assembly {}s...", timer.getElapsedTime());
743
744 timer.start();
745 // Serially merge local storages
746 for (LocalThreadMatStorage &local_storage : storage)
747 stiffness += local_storage.cache->get_matrix(false); // will also prune
748 stiffness.makeCompressed();
749 timer.stop();
750 logger().trace("done merge assembly {}s...", timer.getElapsedTime());
751
752 // stiffness.resize(n_basis*size(), n_basis*size());
753 // stiffness.setFromTriplets(entries.begin(), entries.end());
754 }
755
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,
763 const AssemblyValsCache &psi_cache,
764 const AssemblyValsCache &phi_cache,
765 const double t,
766 const double dt,
767 const Eigen::MatrixXd &x,
768 const Eigen::MatrixXd &x_prev,
769 const SolutionSplitter &split_solution) const
770 {
771 assert(size() > 0);
772 assert(rows() > 0);
773 assert(cols() > 0);
774 assert(phi_bases.size() == psi_bases.size());
775 assert(phi_bases.size() == gbases.size());
776
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);
783
784 auto storage = create_thread_storage(LocalThreadScalarStorage());
785 const int n_bases = int(phi_bases.size());
786
787 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
788 LocalThreadScalarStorage &local_storage = get_local_thread_storage(storage, thread_id);
789 ElementAssemblyValues psi_scratch;
790
791 for (int e = start; e < end; ++e)
792 {
793 const auto [psi_vals, phi_vals] = compute_mixed_element_values(
794 e, is_volume,
795 psi_bases[e], phi_bases[e], gbases[e],
796 psi_cache, phi_cache,
797 psi_scratch, local_storage.vals);
798
799 const Quadrature &quadrature = phi_vals.quadrature;
800 assert(psi_vals.quadrature.weights.size() == quadrature.weights.size());
801 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
802 local_storage.da = phi_vals.det.array() * quadrature.weights.array();
803
804 local_storage.val += compute_energy(
805 MixedNonLinearAssemblerData(psi_vals, phi_vals, t, dt, x_phi, x_psi, x_phi_prev, x_psi_prev, local_storage.da));
806 }
807 });
808
809 double res = 0;
810 for (const LocalThreadScalarStorage &local_storage : storage)
811 res += local_storage.val;
812 return res;
813 }
814
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,
822 const AssemblyValsCache &psi_cache,
823 const AssemblyValsCache &phi_cache,
824 const double t,
825 const double dt,
826 const Eigen::MatrixXd &x,
827 const Eigen::MatrixXd &x_prev,
828 const SolutionSplitter &split_solution) const
829 {
830 assert(size() > 0);
831 assert(rows() > 0);
832 assert(cols() > 0);
833 assert(phi_bases.size() == psi_bases.size());
834 assert(phi_bases.size() == gbases.size());
835
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);
842
843 auto storage = create_thread_storage(LocalThreadScalarStorage());
844 const int n_bases = int(phi_bases.size());
845 Eigen::VectorXd out(phi_bases.size());
846
847 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
848 LocalThreadScalarStorage &local_storage = get_local_thread_storage(storage, thread_id);
849 ElementAssemblyValues psi_scratch;
850
851 for (int e = start; e < end; ++e)
852 {
853 const auto [psi_vals, phi_vals] = compute_mixed_element_values(
854 e, is_volume,
855 psi_bases[e], phi_bases[e], gbases[e],
856 psi_cache, phi_cache,
857 psi_scratch, local_storage.vals);
858
859 const Quadrature &quadrature = phi_vals.quadrature;
860 assert(psi_vals.quadrature.weights.size() == quadrature.weights.size());
861 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
862 local_storage.da = phi_vals.det.array() * quadrature.weights.array();
863
864 out(e) = compute_energy(
865 MixedNonLinearAssemblerData(psi_vals, phi_vals, t, dt, x_phi, x_psi, x_phi_prev, x_psi_prev, local_storage.da));
866 }
867 });
868
869#ifndef NDEBUG
870 const double assemble_val = assemble_energy(
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));
875#endif
876
877 return out;
878 }
879
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,
887 const AssemblyValsCache &psi_cache,
888 const AssemblyValsCache &phi_cache,
889 const double t,
890 const double dt,
891 const Eigen::MatrixXd &x,
892 const Eigen::MatrixXd &x_prev,
893 const SolutionSplitter &split_solution,
894 Eigen::MatrixXd &grad) const
895 {
896 assert(size() > 0);
897 assert(rows() > 0);
898 assert(cols() > 0);
899 assert(phi_bases.size() == psi_bases.size());
900 assert(phi_bases.size() == gbases.size());
901
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);
908
909 grad.resize(phi_ndof + psi_ndof, 1);
910 grad.setZero();
911
912 auto storage = create_thread_storage(LocalThreadVecStorage(grad.size()));
913 const int n_bases = int(phi_bases.size());
914
915 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
916 LocalThreadVecStorage &local_storage = get_local_thread_storage(storage, thread_id);
917 ElementAssemblyValues psi_scratch;
918
919 for (int e = start; e < end; ++e)
920 {
921 const auto [psi_vals, phi_vals] = compute_mixed_element_values(
922 e, is_volume,
923 psi_bases[e], phi_bases[e], gbases[e],
924 psi_cache, phi_cache,
925 psi_scratch, local_storage.vals);
926
927 const Quadrature &quadrature = phi_vals.quadrature;
928 assert(psi_vals.quadrature.weights.size() == quadrature.weights.size());
929 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
930 local_storage.da = phi_vals.det.array() * quadrature.weights.array();
931
932 const Eigen::VectorXd local_grad = compute_gradient(
933 MixedNonLinearAssemblerData(psi_vals, phi_vals, t, dt, x_phi, x_psi, x_phi_prev, x_psi_prev, local_storage.da));
934
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());
938
939 for (int i = 0; i < n_phi_loc_bases; ++i)
940 {
941 const auto &global_i = phi_vals.basis_values[i].global;
942 for (int d = 0; d < rows(); ++d)
943 {
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;
947 }
948 }
949
950 const int local_psi_offset = n_phi_loc_bases * rows();
951 for (int i = 0; i < n_psi_loc_bases; ++i)
952 {
953 const auto &global_i = psi_vals.basis_values[i].global;
954 for (int d = 0; d < cols(); ++d)
955 {
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;
959 }
960 }
961 }
962 });
963
964 for (const LocalThreadVecStorage &local_storage : storage)
965 grad += local_storage.vec;
966 }
967
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,
976 const AssemblyValsCache &psi_cache,
977 const AssemblyValsCache &phi_cache,
978 const double t,
979 const double dt,
980 const Eigen::MatrixXd &x,
981 const Eigen::MatrixXd &x_prev,
982 const SolutionSplitter &split_solution,
983 MatrixCache &mat_cache,
985 {
986 assert(size() > 0);
987 assert(rows() > 0);
988 assert(cols() > 0);
989 assert(phi_bases.size() == psi_bases.size());
990 assert(phi_bases.size() == gbases.size());
991
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);
999
1000 const int max_triplets_size = int(1e7);
1001 const int buffer_size = std::min(max_triplets_size, total_ndof);
1002
1003 mat_cache.init(total_ndof);
1004 mat_cache.set_zero();
1005
1006 auto storage = create_thread_storage(LocalThreadMatStorage(buffer_size, mat_cache));
1007 const int n_bases = int(phi_bases.size());
1008
1009 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
1010 LocalThreadMatStorage &local_storage = get_local_thread_storage(storage, thread_id);
1011 ElementAssemblyValues psi_scratch;
1012
1013 for (int e = start; e < end; ++e)
1014 {
1015 const auto element_values = compute_mixed_element_values(
1016 e, is_volume,
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;
1022
1023 const Quadrature &quadrature = phi_vals.quadrature;
1024 assert(psi_vals.quadrature.weights.size() == quadrature.weights.size());
1025 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
1026 local_storage.da = phi_vals.det.array() * quadrature.weights.array();
1027
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);
1036
1037 if (project_to_psd)
1038 local_hessian = ipc::project_to_psd(local_hessian);
1039
1040 const auto local_index_data = [&](
1041 const int local_index,
1042 const std::vector<basis::Local2Global> *&global,
1043 int &component,
1044 int &component_count,
1045 int &global_offset) {
1046 assert(local_index >= 0);
1047 assert(local_index < local_size);
1048
1049 const int phi_local_size = n_phi_loc_bases * rows();
1050 if (local_index < phi_local_size)
1051 {
1052 const int basis_index = local_index / rows();
1053 global = &phi_vals.basis_values[basis_index].global;
1054 component = local_index % rows();
1055 component_count = rows();
1056 global_offset = 0;
1057 return;
1058 }
1059
1060 const int psi_local_index = local_index - phi_local_size;
1061 const int basis_index = psi_local_index / cols();
1062 global = &psi_vals.basis_values[basis_index].global;
1063 component = psi_local_index % cols();
1064 component_count = cols();
1065 global_offset = phi_ndof;
1066 };
1067
1068 for (int i = 0; i < local_size; ++i)
1069 {
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);
1075
1076 for (int j = 0; j < local_size; ++j)
1077 {
1078 const double local_value = local_hessian(i, j);
1079 if (local_value == 0)
1080 continue;
1081
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);
1087
1088 for (const auto &gi : *global_i)
1089 {
1090 const int row = global_offset_i + gi.index * component_count_i + component_i;
1091 for (const auto &gj : *global_j)
1092 {
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);
1095 }
1096 }
1097
1098 if (local_storage.cache->entries_size() >= max_triplets_size)
1099 {
1100 local_storage.cache->prune();
1101 logger().debug("cleaning memory...");
1102 }
1103 }
1104 }
1105 });
1106 }
1107 });
1108
1109 for (LocalThreadMatStorage &local_storage : storage)
1110 {
1111 local_storage.cache->prune();
1112 mat_cache += *local_storage.cache;
1113 }
1114 hessian = mat_cache.get_matrix();
1115 }
1116
1118 const bool is_volume,
1119 const std::vector<ElementBases> &bases,
1120 const std::vector<ElementBases> &gbases,
1121 const AssemblyValsCache &cache,
1122 const double t,
1123 const double dt,
1124 const Eigen::MatrixXd &displacement,
1125 const Eigen::MatrixXd &displacement_prev) const
1126 {
1127 auto storage = create_thread_storage(LocalThreadScalarStorage());
1128 const int n_bases = int(bases.size());
1129
1130 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
1131 LocalThreadScalarStorage &local_storage = get_local_thread_storage(storage, thread_id);
1132
1133 for (int e = start; e < end; ++e)
1134 {
1135 const ElementAssemblyValues &vals = cache.get_or_compute(e, is_volume, bases[e], gbases[e], local_storage.vals);
1136
1137 const Quadrature &quadrature = vals.quadrature;
1138
1139 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
1140 local_storage.da = vals.det.array() * quadrature.weights.array();
1141
1142 const double val = compute_energy(NonLinearAssemblerData(vals, t, dt, displacement, displacement_prev, local_storage.da));
1143 local_storage.val += val;
1144 }
1145 });
1146
1147 double res = 0;
1148 // Serially merge local storages
1149 for (const LocalThreadScalarStorage &local_storage : storage)
1150 res += local_storage.val;
1151 return res;
1152 }
1153
1155 const bool is_volume,
1156 const std::vector<ElementBases> &bases,
1157 const std::vector<ElementBases> &gbases,
1158 const AssemblyValsCache &cache,
1159 const double t,
1160 const double dt,
1161 const Eigen::MatrixXd &displacement,
1162 const Eigen::MatrixXd &displacement_prev) const
1163 {
1164 auto storage = create_thread_storage(LocalThreadScalarStorage());
1165 const int n_bases = int(bases.size());
1166 Eigen::VectorXd out(bases.size());
1167
1168 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
1169 LocalThreadScalarStorage &local_storage = get_local_thread_storage(storage, thread_id);
1170
1171 for (int e = start; e < end; ++e)
1172 {
1173 const ElementAssemblyValues &vals = cache.get_or_compute(e, is_volume, bases[e], gbases[e], local_storage.vals);
1174
1175 const Quadrature &quadrature = vals.quadrature;
1176
1177 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
1178 local_storage.da = vals.det.array() * quadrature.weights.array();
1179
1180 const double val = compute_energy(NonLinearAssemblerData(vals, t, dt, displacement, displacement_prev, local_storage.da));
1181 out[e] = val;
1182 }
1183 });
1184
1185#ifndef NDEBUG
1186 const double assemble_val = assemble_energy(
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));
1189#endif
1190
1191 return out;
1192 }
1193
1195 const bool is_volume,
1196 const int n_basis,
1197 const std::vector<ElementBases> &bases,
1198 const std::vector<ElementBases> &gbases,
1199 const AssemblyValsCache &cache,
1200 const double t,
1201 const double dt,
1202 const Eigen::MatrixXd &displacement,
1203 const Eigen::MatrixXd &displacement_prev,
1204 Eigen::MatrixXd &rhs) const
1205 {
1206 rhs.resize(n_basis * size(), 1);
1207 rhs.setZero();
1208
1209 auto storage = create_thread_storage(LocalThreadVecStorage(rhs.size()));
1210
1211 const int n_bases = int(bases.size());
1212
1213 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
1214 LocalThreadVecStorage &local_storage = get_local_thread_storage(storage, thread_id);
1215
1216 for (int e = start; e < end; ++e)
1217 {
1218 // igl::Timer timer; timer.start();
1219
1220 const ElementAssemblyValues &vals = cache.get_or_compute(e, is_volume, bases[e], gbases[e], local_storage.vals);
1221
1222 const Quadrature &quadrature = vals.quadrature;
1223
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());
1227
1228 const auto val = assemble_gradient(NonLinearAssemblerData(vals, t, dt, displacement, displacement_prev, local_storage.da));
1229 assert(val.size() == n_loc_bases * size());
1230
1231 for (int j = 0; j < n_loc_bases; ++j)
1232 {
1233 const auto &global_j = vals.basis_values[j].global;
1234
1235 // igl::Timer t1; t1.start();
1236 for (int m = 0; m < size(); ++m)
1237 {
1238 const double local_value = val(j * size() + m);
1239
1240 for (size_t jj = 0; jj < global_j.size(); ++jj)
1241 {
1242 const auto gj = global_j[jj].index * size() + m;
1243 const auto wj = global_j[jj].val;
1244
1245 local_storage.vec(gj) += local_value * wj;
1246 }
1247 }
1248
1249 // t1.stop();
1250 // if (!vals.has_parameterization) { logger().trace("-- t1: ", t1.getElapsedTime()); }
1251 }
1252
1253 // timer.stop();
1254 // if (!vals.has_parameterization) { logger().trace("-- Timer: ", timer.getElapsedTime()); }
1255 }
1256 });
1257
1258 // Serially merge local storages
1259 for (const LocalThreadVecStorage &local_storage : storage)
1260 rhs += local_storage.vec;
1261 }
1262
1264 const bool is_volume,
1265 const int n_basis,
1266 const bool project_to_psd,
1267 const std::vector<ElementBases> &bases,
1268 const std::vector<ElementBases> &gbases,
1269 const AssemblyValsCache &cache,
1270 const double t,
1271 const double dt,
1272 const Eigen::MatrixXd &displacement,
1273 const Eigen::MatrixXd &displacement_prev,
1274 MatrixCache &mat_cache,
1275 StiffnessMatrix &hess) const
1276 {
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());
1280 // logger().trace("buffer_size {}", buffer_size);
1281
1282 // hess.resize(n_basis * size(), n_basis * size());
1283 // hess.setZero();
1284
1285 const auto *sparse_cache = dynamic_cast<const SparseMatrixCache *>(&mat_cache);
1286 const bool cached = sparse_cache && sparse_cache->mapping_size() > 0;
1287
1288 mat_cache.init(n_basis * size());
1289 mat_cache.set_zero();
1290
1291 auto storage = create_thread_storage(LocalThreadMatStorage(buffer_size, mat_cache));
1292
1293 const int n_bases = int(bases.size());
1294 const bool has_basis_cache = cache.is_initialized();
1295 igl::Timer timer;
1296 timer.start();
1297
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;
1301 maybe_parallel_for(n_bases, [&](int start, int end, int thread_id) {
1302 LocalThreadMatStorage &local_storage = get_local_thread_storage(storage, thread_id);
1303 auto *cached_worker = cached ? dynamic_cast<SparseMatrixCache *>(local_storage.cache.get()) : nullptr;
1304
1305 for (int e = start; e < end; ++e)
1306 {
1307 // Keep the uncached element data local to this iteration.
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;
1314
1315 const Quadrature &quadrature = vals.quadrature;
1316
1317 assert(MAX_QUAD_POINTS == -1 || quadrature.weights.size() < MAX_QUAD_POINTS);
1318 da = vals.det.array() * quadrature.weights.array();
1319 const int n_loc_bases = int(vals.basis_values.size());
1320
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);
1326
1327 if (project_to_psd)
1328 stiffness_val = ipc::project_to_psd(stiffness_val);
1329
1330 // bool has_nan = false;
1331 // for(int k = 0; k < stiffness_val.size(); ++k)
1332 // {
1333 // if(std::isnan(stiffness_val(k)))
1334 // {
1335 // has_nan = true;
1336 // break;
1337 // }
1338 // }
1339
1340 // if(has_nan)
1341 // {
1342 // local_storage.entries.emplace_back(0, 0, std::nan(""));
1343 // break;
1344 // }
1345
1346 // Visit contributions in the same order used to build the sparse mapping.
1347 const auto scatter_element = [&](auto add_value) {
1348 for (int i = 0; i < n_loc_bases; ++i)
1349 {
1350 const auto &global_i = vals.basis_values[i].global;
1351
1352 for (int j = 0; j < n_loc_bases; ++j)
1353 // for(int j = 0; j <= i; ++j)
1354 {
1355 const auto &global_j = vals.basis_values[j].global;
1356
1357 for (int n = 0; n < dim; ++n)
1358 {
1359 for (int m = 0; m < dim; ++m)
1360 {
1361 const double local_value = stiffness_val(i * dim + m, j * dim + n);
1362
1363 for (size_t ii = 0; ii < global_i.size(); ++ii)
1364 {
1365 const auto gi = global_i[ii].index * dim + m;
1366 const auto wi = global_i[ii].val;
1367
1368 for (size_t jj = 0; jj < global_j.size(); ++jj)
1369 {
1370 const auto gj = global_j[jj].index * dim + n;
1371 const auto wj = global_j[jj].val;
1372
1373 add_value(gi, gj, local_value * wi * wj);
1374 }
1375 }
1376 }
1377 }
1378 }
1379 }
1380 };
1381 if (cached_worker && vals.has_single_unit_mapping())
1382 {
1383 auto writer = cached_worker->cached_element_writer(e);
1384 if constexpr (Dimension != Eigen::Dynamic)
1385 {
1386 if (n_loc_bases == Dimension + 1)
1387 add_unit_weight_hessian<Dimension, Dimension + 1>(stiffness_val, n_loc_bases, dim, writer);
1388 else
1389 add_unit_weight_hessian<Dimension, Eigen::Dynamic>(stiffness_val, n_loc_bases, dim, writer);
1390 }
1391 else
1392 add_unit_weight_hessian<Eigen::Dynamic, Eigen::Dynamic>(stiffness_val, n_loc_bases, dim, writer);
1393 }
1394 else if (cached_worker)
1395 {
1396 scatter_element([writer = cached_worker->cached_element_writer(e)](int, int, double value) mutable { writer.add(value); });
1397 }
1398 else
1399 {
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)
1403 {
1404 local_storage.cache->prune();
1405 logger().debug("cleaning memory...");
1406 }
1407 });
1408 }
1409 });
1410 }
1411 });
1412 };
1413 if (dimension == 2)
1414 assemble_elements(std::integral_constant<int, 2>{});
1415 else if (dimension == 3)
1416 assemble_elements(std::integral_constant<int, 3>{});
1417 else
1418 assemble_elements(std::integral_constant<int, Eigen::Dynamic>{});
1419
1420 timer.stop();
1421 logger().trace("done separate assembly {}s...", timer.getElapsedTime());
1422
1423 timer.start();
1424
1425 // Serially merge local storages
1426 for (LocalThreadMatStorage &local_storage : storage)
1427 {
1428 local_storage.cache->prune();
1429 mat_cache += *local_storage.cache;
1430 }
1431 hess = mat_cache.get_matrix();
1432
1433 timer.stop();
1434 logger().trace("done merge assembly {}s...", timer.getElapsedTime());
1435 }
1436
1438 {
1439#ifdef POLYFEM_WITH_MISO
1440 use_robust_jacobian = true;
1441#else
1442 logger().error("Enable Bezier library to use the robust Jacobian check!");
1443#endif
1444 }
1445} // namespace polyfem::assembler
LocalHessian hessian
Eigen::MatrixXd vec
double val
QuadratureVector da
std::unique_ptr< MatrixCache > cache
ElementAssemblyValues vals
Quadrature quadrature
int x
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
Definition Assembler.hpp:72
virtual std::string name() const =0
virtual void add_multimaterial(const int index, const json &params, 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 & tensor(ElasticityTensorType type)
Definition Assembler.cpp:46
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
Definition Assembler.cpp:75
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 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
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,...
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 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
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
list tmp
Definition p_bases.py:366
Used for test only.
constexpr const char * MATERIAL_ELEMENT_INDEX
Definition MatParams.hpp:10
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.
Definition Logger.cpp:44
nlohmann::json json
Definition Common.hpp:9
double von_mises_stress_for_stress_tensor(const Eigen::MatrixXd &stress)
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 3, 3 > MatrixNd
Definition Types.hpp:14
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73
Eigen::SparseMatrix< double, Eigen::ColMajor > StiffnessMatrix
Definition Types.hpp:24