svMultiPhysics
Loading...
Searching...
No Matches
mat_fun.h
1// SPDX-FileCopyrightText: Copyright (c) Stanford University, The Regents of the University of California, and others.
2// SPDX-License-Identifier: BSD-3-Clause
3
4#ifndef MAT_FUN_H
5#define MAT_FUN_H
6#include "eigen3/Eigen/Core"
7#include "eigen3/Eigen/Dense"
8#include "eigen3/unsupported/Eigen/CXX11/Tensor"
9#include <stdexcept>
10
11#include "Array.h"
12#include "consts.h"
13#include "Tensor4.h"
14#include "Vector.h"
16
17/// @brief The classes defined here duplicate the data structures in the
18/// Fortran MATFUN module defined in MATFUN.f.
19///
20/// This module defines data structures for generally performed matrix and tensor operations.
21///
22/// \todo [TODO:DaveP] this should just be a namespace?
23//
24namespace mat_fun {
25 /// @brief A 2nd order tensor, nsd x nsd, fixed size and stack allocated.
26 /// Used for the deformation gradient, stresses and similar quantities that
27 /// have a known size at compile time.
28 template<int nsd>
29 using Matrix = Eigen::Matrix<double, nsd, nsd>;
30
31 /// @brief A 4th order tensor, nsd x nsd x nsd x nsd, fixed size and stack
32 /// allocated. Used for the material elasticity tensor and other 4th order tensors
33 /// that have a known size at compile time.
34 template<int nsd>
35 using Tensor = Eigen::TensorFixedSize<double, Eigen::Sizes<nsd, nsd, nsd, nsd>>;
36
37 /// @brief One nsd-vector per element node, so nsd x eNoN. Row count is fixed
38 /// at compile time while column count is the element's node count, known only
39 /// at run time, so it is bounded by consts::maxNoN to stay stack allocated.
40 /// Used for shape function gradients and other per-node vector quantities.
41 template <int nsd>
42 using NodalMatrix = Eigen::Matrix<double, nsd, Eigen::Dynamic, 0, nsd, consts::maxNoN>;
43
44 /// @brief One scalar per element node, so eNoN entries. Dynamic length bounded
45 /// by consts::maxNoN to stay stack allocated, as for NodalMatrix. Used for shape
46 /// function values and other per-node scalar quantities.
47 using NodalVector = Eigen::Matrix<double, Eigen::Dynamic, 1, 0, consts::maxNoN, 1>;
48
49 // The eigen_view overloads below wrap an Array or Vector in an Eigen::Map that
50 // shares its storage, so the container must outlive the view.
51
52 /// @brief Read-only Eigen view of an Array, sharing its storage.
53 ///
54 /// @tparam rows Row count, fixed at compile time; the columns are taken from the Array.
55 template <int rows>
56 Eigen::Map<const Eigen::Matrix<double, rows, Eigen::Dynamic>>
57 eigen_view(const Array<double>& A) {
58 if (A.nrows() != rows) {
59 svmp::raise<svmp::FE::InvalidArgumentException>(
60 "A view of " + std::to_string(rows) + " rows was requested for an array with " +
61 std::to_string(A.nrows()) + " rows.");
62 }
63 return {A.data(), rows, A.ncols()};
64 }
65
66 /// @brief Read-only Eigen view of a whole Array, sharing its storage.
67 inline Eigen::Map<const Eigen::MatrixXd>
68 eigen_view(const Array<double>& A) {
69 return {A.data(), A.nrows(), A.ncols()};
70 }
71
72 /// @brief Read-only Eigen view of a band of rows of an Array, sharing its storage.
73 ///
74 /// Used where an Array contains several fields and only a contiguous band is viewed.
75 /// For example,
76 ///
77 /// A = [ A00, A01, A02 ; eigen_view_rows<2>(A, 1) = [ A10, A11, A12 ;
78 /// A10, A11, A12 ; A20, A21, A22 ]
79 /// A20, A21, A22 ;
80 /// A30, A31, A32 ]
81 ///
82 /// @param A The Array to view.
83 /// @param first Index of the band's first row within the Array.
84 /// @tparam rows Number of rows, fixed at compile time, typically nsd.
85 template <int rows>
86 Eigen::Map<const Eigen::Matrix<double, rows, Eigen::Dynamic>, 0, Eigen::OuterStride<>>
87 eigen_view_rows(const Array<double>& A, const int first) {
88 if (first < 0 || first + rows > A.nrows()) {
89 svmp::raise<svmp::FE::InvalidArgumentException>(
90 "A view of " + std::to_string(rows) + " rows starting at row " + std::to_string(first) +
91 " was requested for an array with " + std::to_string(A.nrows()) + " rows.");
92 }
93 return {A.data() + first, rows, A.ncols(), Eigen::OuterStride<>(A.nrows())};
94 }
95
96 /// @brief Writable Eigen view of a whole Array, sharing its storage.
97 inline Eigen::Map<Eigen::MatrixXd>
98 eigen_view_mutable(Array<double>& A) {
99 return {A.data(), A.nrows(), A.ncols()};
100 }
101
102 /// @brief Read-only Eigen view of a whole Vector, sharing its storage.
103 inline Eigen::Map<const Eigen::VectorXd>
105 return {v.data(), v.size()};
106 }
107
108 /// @brief Read-only Eigen view of a Vector, sharing its storage.
109 ///
110 /// @tparam rows Entry count, fixed at compile time.
111 template <int rows>
112 Eigen::Map<const Eigen::Matrix<double, rows, 1>>
114 if (v.size() != rows) {
115 svmp::raise<svmp::FE::InvalidArgumentException>(
116 "A view of " + std::to_string(rows) + " entries was requested for a vector with " +
117 std::to_string(v.size()) + " entries.");
118 }
119 return Eigen::Map<const Eigen::Matrix<double, rows, 1>>(v.data());
120 }
121
122 // Function to convert Array<double> to Eigen::Matrix
123 template <typename MatrixType>
124 MatrixType convert_to_eigen_matrix(const Array<double>& src) {
125 MatrixType mat;
126 for (int i = 0; i < mat.rows(); ++i)
127 for (int j = 0; j < mat.cols(); ++j)
128 mat(i, j) = src(i, j);
129 return mat;
130 }
131
132 // Function to convert Eigen::Matrix to Array<double>
133 template <typename MatrixType>
134 void convert_to_array(const MatrixType& mat, Array<double>& dest) {
135 for (int i = 0; i < mat.rows(); ++i)
136 for (int j = 0; j < mat.cols(); ++j)
137 dest(i, j) = mat(i, j);
138 }
139
140 // Function to convert a higher-dimensional array like Dm
141 template <typename MatrixType>
142 void copy_Dm(const MatrixType& mat, Array<double>& dest) {
143 if ((mat.rows() != dest.nrows()) || (mat.cols() != dest.ncols())) {
144 const std::string mat_dims = "(" + std::to_string(mat.rows()) + "x" + std::to_string(mat.cols()) + ")";
145 const std::string dest_dims = "(" + std::to_string(dest.nrows()) + "x" + std::to_string(dest.ncols()) + ")";
146 svmp::raise<svmp::FE::InvalidArgumentException>(
147 "The 'mat" + mat_dims + "' and 'dest" + dest_dims +
148 "' arrays have incompatible sizes.");
149 }
150
151 for (int i = 0; i < mat.rows(); ++i) {
152 for (int j = 0; j < mat.cols(); ++j) {
153 dest(i, j) = mat(i, j);
154 }
155 }
156 }
157
158 template <int nsd>
159 Eigen::Matrix<double, nsd, 1> cross_product(const Eigen::Matrix<double, nsd, 1>& u, const Eigen::Matrix<double, nsd, 1>& v) {
160 if constexpr (nsd == 2) {
161 return Eigen::Matrix<double, 2, 1>(v(1), - v(0));
162 }
163 else if constexpr (nsd == 3) {
164 return u.cross(v);
165 }
166 else {
167 throw std::runtime_error("[cross_product] Invalid number of spatial dimensions '" + std::to_string(nsd) + "'. Valid dimensions are 2 or 3.");
168 }
169 }
170
171 double mat_ddot(const Array<double>& A, const Array<double>& B, const int nd);
172
173 template <int nsd>
174 double double_dot_product(const Matrix<nsd>& A, const Matrix<nsd>& B) {
175 return A.cwiseProduct(B).sum();
176 }
177
178 double mat_det(const Array<double>& A, const int nd);
179 Array<double> mat_dev(const Array<double>& A, const int nd);
180
181 Array<double> mat_dyad_prod(const Vector<double>& u, const Vector<double>& v, const int nd);
182
183 Array<double> mat_id(const int nsd);
184 Array<double> mat_inv(const Array<double>& A, const int nd, bool debug = false);
185 Array<double> mat_inv_ge(const Array<double>& A, const int nd, bool debug = false);
186 Array<double> mat_inv_lp(const Array<double>& A, const int nd);
187
188 /// @brief Multiply a matrix by a vector, returning A*v.
189 ///
190 /// @param[in] A matrix with as many columns as v has entries.
191 /// @param[in] v vector.
192 /// @return the product, of size rows(A).
193 ///
194 /// Throws InvalidArgumentException if the sizes are incompatible.
195 Vector<double> mat_mul(const Array<double>& A, const Vector<double>& v);
196
197 /// @brief Multiply two matrices, returning A*B.
198 ///
199 /// @param[in] A left operand.
200 /// @param[in] B right operand, with as many rows as A has columns.
201 /// @return the product, of size rows(A) by cols(B).
202 ///
203 /// Throws InvalidArgumentException if the sizes are incompatible. The
204 /// result is freshly allocated, so the operands may alias it, as in
205 /// A = mat_mul(A, B).
206 Array<double> mat_mul(const Array<double>& A, const Array<double>& B);
207
208 /// @brief Multiply two matrices, writing A*B into an existing result.
209 ///
210 /// @param[in] A left operand.
211 /// @param[in] B right operand, with as many rows as A has columns.
212 /// @param[out] result the product. The caller sizes it rows(A) by cols(B).
213 ///
214 /// Throws InvalidArgumentException if the sizes are incompatible. Preferred
215 /// in loops, where it reuses the caller's storage instead of allocating a
216 /// result on every call. The result must not alias A or B.
217 void mat_mul(const Array<double>& A, const Array<double>& B, Array<double>& result);
218
219 /// @brief Matrix product with the operand shape supplied at compile time.
220 ///
221 /// Overloads of mat_mul rather than differently named helpers, so a call
222 /// site states the shape and otherwise reads exactly as before:
223 ///
224 /// @code
225 /// mat_mul(Dm, Bm.rslice(b), DBm); // runtime shape check
226 /// mat_mul<6, 6, 3>(Dm, Bm.rslice(b), DBm); // no check, same arguments
227 /// @endcode
228 ///
229 /// The generic mat_mul overload above will dispatch to this overload
230 /// when the shapes are known at compile time.
231 ///
232 /// @tparam M rows of A and of the result
233 /// @tparam K columns of A and rows of B, the contracted dimension
234 /// @tparam N columns of B and of the result
235 template <int M, int K, int N>
236 void mat_mul(const Array<double>& A, const Array<double>& B,
237 Array<double>& C)
238 {
239 Eigen::Map<const Eigen::Matrix<double, M, K>> a(A.data());
240 Eigen::Map<const Eigen::Matrix<double, K, N>> b(B.data());
241 Eigen::Map<Eigen::Matrix<double, M, N>> c(C.data());
242
243 c.noalias() = a * b;
244 }
245
246 /// @brief As above, but with the column count known only at run time.
247 ///
248 /// For operands with one column per element node, where the width depends on
249 /// the element type. The row counts are still compile-time, which is where
250 /// most of the benefit comes from.
251 template <int M, int K>
252 void mat_mul(const Array<double>& A, const Array<double>& B,
253 Array<double>& C)
254 {
255 Eigen::Map<const Eigen::Matrix<double, M, K>> a(A.data());
256 Eigen::Map<const Eigen::Matrix<double, K, Eigen::Dynamic>> b(B.data(), K, B.ncols());
257 Eigen::Map<Eigen::Matrix<double, M, Eigen::Dynamic>> c(C.data(), M, C.ncols());
258
259 c.noalias() = a * b;
260 }
261
262 Array<double> mat_symm(const Array<double>& A, const int nd);
263 Array<double> mat_symm_prod(const Vector<double>& u, const Vector<double>& v, const int nd);
264
265 double mat_trace(const Array<double>& A, const int nd);
266
267 Tensor4<double> ten_asym_prod12(const Array<double>& A, const Array<double>& B, const int nd);
268 Tensor4<double> ten_ddot(const Tensor4<double>& A, const Tensor4<double>& B, const int nd);
269 Tensor4<double> ten_ddot_2412(const Tensor4<double>& A, const Tensor4<double>& B, const int nd);
270 Tensor4<double> ten_ddot_3424(const Tensor4<double>& A, const Tensor4<double>& B, const int nd);
271
272 /**
273 * @brief Contracts two 4th order tensors A and B over two dimensions.
274 *
275 * For example, if dimsA = {0, 1} and dimsB = {2, 3} this is
276 * C_klmn = A_ijkl B_mnij (sum over i, j)
277 *
278 * @tparam nsd Number of spatial dimensions; each tensor is nsd^4.
279 * @param[in] A,B Fourth order tensors to contract.
280 * @param[in] dimsA,dimsB Indices of the contracted dimensions of A and B.
281 * @return The contracted tensor.
282 */
283 template <int nsd>
285 double_dot_product(const Tensor<nsd>& A, const std::array<int, 2>& dimsA,
286 const Tensor<nsd>& B, const std::array<int, 2>& dimsB) {
287
288 // Fast path for dimsA = dimsB = {2,3}: C_ijmn = A_ijkl * B_mnkl.
289 if (dimsA[0] == 2 && dimsA[1] == 3 && dimsB[0] == 2 && dimsB[1] == 3) {
290 constexpr int N = nsd * nsd;
291 Tensor<nsd> C;
292 Eigen::Map<const Eigen::Matrix<double, N, N>> a(A.data());
293 Eigen::Map<const Eigen::Matrix<double, N, N>> b(B.data());
294 Eigen::Map<Eigen::Matrix<double, N, N>> c(C.data());
295 c.noalias() = a * b.transpose();
296 return C;
297 }
298
299 // Define the contraction dimensions
300 Eigen::array<Eigen::IndexPair<int>, 2> contractionDims = {
301 Eigen::IndexPair<int>(dimsA[0], dimsB[0]), // Contract A's dimsA[0] with B's dimsB[0]
302 Eigen::IndexPair<int>(dimsA[1], dimsB[1]) // Contract A's dimsA[1] with B's dimsB[1]
303 };
304
305 // Return the double dot product
306 return A.contract(B, contractionDims);
307 }
308
309 Tensor4<double> ten_dyad_prod(const Array<double>& A, const Array<double>& B, const int nd);
310
311 /**
312 * @brief Compute the dyadic product of two 2nd order tensors A and B, C_ijkl = A_ij * B_kl
313 *
314 * @tparam nsd, the number of spatial dimensions
315 * @param A, the first 2nd order tensor
316 * @param B, the second 2nd order tensor
317 * @return Tensor<nsd>
318 */
319 template <int nsd>
322 // Initialize the result tensor
323 Tensor<nsd> C;
324 constexpr int N = nsd * nsd;
325
326 // Column-major storage flattens index pairs: c(ij,kl) = a(ij) * b(kl).
327 Eigen::Map<const Eigen::Matrix<double, N, 1>> a(A.data());
328 Eigen::Map<const Eigen::Matrix<double, N, 1>> b(B.data());
329 Eigen::Map<Eigen::Matrix<double, N, N>> c(C.data());
330 c.noalias() = a * b.transpose();
331 return C;
332 }
333
334 Tensor4<double> ten_ids(const int nd);
335
336 /**
337 * @brief Create a 4th order identity tensor:
338 * I_ijkl = 0.5 * (δ_ik * δ_jl + δ_il * δ_jk)
339 *
340 * @tparam nsd, the number of spatial dimensions
341 * @return Tensor<nsd>
342 */
343 template <int nsd>
346 // Initialize as zero
347 Tensor<nsd> I;
348 I.setZero();
349
350 // Set only non-zero entries
351 for (int i = 0; i < nsd; ++i) {
352 for (int j = 0; j < nsd; ++j) {
353 I(i,j,i,j) += 0.5;
354 I(i,j,j,i) += 0.5;
355 }
356 }
357
358 return I;
359 }
360
361 Array<double> ten_mddot(const Tensor4<double>& A, const Array<double>& B, const int nd);
362
363 Tensor4<double> ten_symm_prod(const Array<double>& A, const Array<double>& B, const int nd);
364
365 /// @brief Create a 4th order tensor from symmetric outer product of two matrices: C_ijkl = 0.5 * (A_ik * B_jl + A_il * B_jk)
366 ///
367 /// @tparam nsd Number of spatial dimensions.
368 /// @param[in] A,B Second order tensors.
369 /// @return The resulting 4th order tensor.
370 template <int nsd>
373
374 // Initialize the result tensor
375 Tensor<nsd> C;
376
377 // Compute the symmetric product: C_ijkl = 0.5 * (A_ik * B_jl + A_il * B_jk)
378 for (int l = 0; l < nsd; ++l) {
379 for (int k = 0; k < nsd; ++k) {
380 // blk views the (k,l) block of C, so blk(i,j) is C(i,j,k,l).
381 Eigen::Map<Eigen::Matrix<double, nsd, nsd>> blk(C.data() + nsd * nsd * (k + nsd * l));
382 blk.noalias() = 0.5 * (A.col(k) * B.col(l).transpose()
383 + A.col(l) * B.col(k).transpose());
384 }
385 }
386
387 // Return the symmetric product
388 return C;
389 }
390
391 Tensor4<double> ten_transpose(const Tensor4<double>& A, const int nd);
392
393 /**
394 * @brief Performs a tensor transpose operation on a 4th order tensor A, B_ijkl = A_klij
395 *
396 * @tparam nsd, the number of spatial dimensions
397 * @param A, the input 4th order tensor
398 * @return Tensor<nsd>
399 */
400 template <int nsd>
403
404 // Initialize the result tensor
405 Tensor<nsd> B;
406
407 // Permute the tensor indices to perform the transpose operation
408 for (int i = 0; i < nsd; ++i) {
409 for (int j = 0; j < nsd; ++j) {
410 for (int k = 0; k < nsd; ++k) {
411 for (int l = 0; l < nsd; ++l) {
412 B(i,j,k,l) = A(k,l,i,j);
413 }
414 }
415 }
416 }
417
418 return B;
419 }
420
421 Array<double> transpose(const Array<double>& A);
422
423 void ten_init(const int nd);
424
425};
426
427#endif
Exception hierarchy for error handling in the FE library.
The Tensor4 template class implements a simple interface to 4th order tensors.
Definition Tensor4.h:20
The Vector template class is used for storing int and double data.
Definition Vector.h:26
The classes defined here duplicate the data structures in the Fortran MATFUN module defined in MATFUN...
Definition mat_fun.cpp:15
Eigen::Matrix< double, nsd, nsd > Matrix
A 2nd order tensor, nsd x nsd, fixed size and stack allocated. Used for the deformation gradient,...
Definition mat_fun.h:29
Tensor< nsd > symmetric_dyadic_product(const Matrix< nsd > &A, const Matrix< nsd > &B)
Create a 4th order tensor from symmetric outer product of two matrices: C_ijkl = 0....
Definition mat_fun.h:372
Eigen::Map< Eigen::MatrixXd > eigen_view_mutable(Array< double > &A)
Writable Eigen view of a whole Array, sharing its storage.
Definition mat_fun.h:98
void ten_init(const int nd)
Initialize tensor index pointer.
Definition mat_fun.cpp:747
Tensor4< double > ten_symm_prod(const Array< double > &A, const Array< double > &B, const int nd)
Create a 4th order tensor from symmetric outer product of two matrices.
Definition mat_fun.cpp:839
Eigen::Map< const Eigen::Matrix< double, rows, Eigen::Dynamic > > eigen_view(const Array< double > &A)
Read-only Eigen view of an Array, sharing its storage.
Definition mat_fun.h:57
Array< double > ten_mddot(const Tensor4< double > &A, const Array< double > &B, const int nd)
Double dot product of a 4th order tensor and a 2nd order tensor.
Definition mat_fun.cpp:809
Eigen::Matrix< double, Eigen::Dynamic, 1, 0, consts::maxNoN, 1 > NodalVector
One scalar per element node, so eNoN entries. Dynamic length bounded by consts::maxNoN to stay stack ...
Definition mat_fun.h:47
Array< double > mat_symm(const Array< double > &A, const int nd)
Symmetric part of a matrix, S = (A + A.T)/2.
Definition mat_fun.cpp:542
Tensor4< double > ten_ids(const int nd)
Create a 4th order order symmetric identity tensor.
Definition mat_fun.cpp:790
Array< double > transpose(const Array< double > &A)
Reproduces Fortran TRANSPOSE.
Definition mat_fun.cpp:875
Vector< double > mat_mul(const Array< double > &A, const Vector< double > &v)
Multiply a matrix by a vector.
Definition mat_fun.cpp:433
double mat_trace(const Array< double > &A, const int nd)
Trace of second order matrix of rank nd.
Definition mat_fun.cpp:574
Tensor4< double > ten_ddot(const Tensor4< double > &A, const Tensor4< double > &B, const int nd)
Double dot product of 2 4th order tensors T_ijkl = A_ijmn * B_klmn.
Definition mat_fun.cpp:613
Tensor4< double > ten_dyad_prod(const Array< double > &A, const Array< double > &B, const int nd)
Create a 4th order tensor from outer product of two matrices.
Definition mat_fun.cpp:771
Array< double > mat_inv_lp(const Array< double > &A, const int nd)
This function computes inverse of a square matrix using Lapack functions (DGETRF + DGETRI).
Definition mat_fun.cpp:397
Array< double > mat_inv(const Array< double > &A, const int nd, bool debug)
This function computes inverse of a square matrix.
Definition mat_fun.cpp:110
Array< double > mat_inv_ge(const Array< double > &Ain, const int n, bool debug)
This function computes inverse of a square matrix using Gauss Elimination method.
Definition mat_fun.cpp:167
Eigen::Map< const Eigen::Matrix< double, rows, Eigen::Dynamic >, 0, Eigen::OuterStride<> > eigen_view_rows(const Array< double > &A, const int first)
Read-only Eigen view of a band of rows of an Array, sharing its storage.
Definition mat_fun.h:87
Array< double > mat_symm_prod(const Vector< double > &u, const Vector< double > &v, const int nd)
Create a matrix from symmetric product of two vectors.
Definition mat_fun.cpp:559
Array< double > mat_dyad_prod(const Vector< double > &u, const Vector< double > &v, const int nd)
Create a matrix from outer product of two vectors.
Definition mat_fun.cpp:82
Tensor< nsd > fourth_order_identity()
Create a 4th order identity tensor: I_ijkl = 0.5 * (δ_ik * δ_jl + δ_il * δ_jk).
Definition mat_fun.h:345
double mat_ddot(const Array< double > &A, const Array< double > &B, const int nd)
Double dot product of 2 square matrices.
Definition mat_fun.cpp:21
Tensor4< double > ten_ddot_2412(const Tensor4< double > &A, const Tensor4< double > &B, const int nd)
T_ijkl = A_imjn * B_mnkl.
Definition mat_fun.cpp:658
Eigen::TensorFixedSize< double, Eigen::Sizes< nsd, nsd, nsd, nsd > > Tensor
A 4th order tensor, nsd x nsd x nsd x nsd, fixed size and stack allocated. Used for the material elas...
Definition mat_fun.h:35
Tensor4< double > ten_asym_prod12(const Array< double > &A, const Array< double > &B, const int nd)
Create a 4th order tensor from antisymmetric outer product of two matrices.
Definition mat_fun.cpp:591
Eigen::Matrix< double, nsd, Eigen::Dynamic, 0, nsd, consts::maxNoN > NodalMatrix
One nsd-vector per element node, so nsd x eNoN. Row count is fixed at compile time while column count...
Definition mat_fun.h:42
Tensor< nsd > dyadic_product(const Matrix< nsd > &A, const Matrix< nsd > &B)
Compute the dyadic product of two 2nd order tensors A and B, C_ijkl = A_ij * B_kl.
Definition mat_fun.h:321