### Dynamic Matrix Initialization with Eigen Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialAdvancedInitialization.dox Initializes a dynamic-sized matrix and demonstrates its use in an expression, showcasing how Eigen's expression templates handle temporary objects efficiently. This example is part of the Eigen QuickStart guide. ```cpp #include #include int main() { Eigen::MatrixXf m = Eigen::MatrixXf::Random(3,3); std::cout << "m = \n" << m << std::endl; Eigen::MatrixXf result = m + Eigen::MatrixXf::Constant(3,3,1.2f); std::cout << "m + 1.2 = \n" << result << std::endl; return 0; } ``` -------------------------------- ### Define Installation Rules Source: https://gitlab.com/libeigen/eigen/-/blob/master/CMakeLists.txt Specifies the installation paths for Eigen headers, generated package configuration files, and the main library target. It handles both standard file installation and component-based exports. ```cmake install(FILES signature_of_eigen3_matrix_library DESTINATION ${INCLUDE_INSTALL_DIR} COMPONENT Devel) install(DIRECTORY Eigen DESTINATION ${INCLUDE_INSTALL_DIR} COMPONENT Devel) install(TARGETS eigen EXPORT Eigen3Targets) ``` -------------------------------- ### Complete Eigen AOCL Integration Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/UsingAOCL.dox A full C++ example showing how to enable multi-threading, perform matrix multiplication, execute vectorized math, and run LAPACK decompositions using AOCL. ```cpp #define EIGEN_USE_AOCL_MT #include #include int main() { const int n = 2048; Eigen::MatrixXd A = Eigen::MatrixXd::Random(n, n); Eigen::MatrixXd B = Eigen::MatrixXd::Random(n, n); Eigen::MatrixXd C = A * B; Eigen::VectorXd v = Eigen::VectorXd::LinSpaced(10000, 0, 10); Eigen::VectorXd result = v.array().sin(); Eigen::LLT llt(A); std::cout << "Matrix norm: " << C.norm() << std::endl; std::cout << "Vector result norm: " << result.norm() << std::endl; return 0; } ``` -------------------------------- ### Eigen Matrix-Free Solver Wrapper Example (C++) Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/MatrixfreeSolverExample.dox This C++ code demonstrates how to create a wrapper class for Eigen's matrix-free solvers. It shows the implementation of required methods like rows(), cols(), and operator* for integrating with iterative solvers. The example specifically wraps an Eigen::SparseMatrix. ```cpp #include #include #include // Define a simple matrix-free operator (e.g., a sparse matrix) Eigen::SparseMatrix A; // Wrapper class for matrix-free operations class MatrixFreeOperator { public: MatrixFreeOperator(const Eigen::SparseMatrix& mat) : m_matrix(mat) {} // Required methods for EigenBase Eigen::Index rows() const { return m_matrix.rows(); } Eigen::Index cols() const { return m_matrix.cols(); } // The actual matrix-vector product implementation // This is where the matrix-free logic resides template Eigen::Matrix operator*(const Eigen::MatrixBase& vec) const { // In a true matrix-free scenario, this would not directly use a sparse matrix. // For demonstration, we use the sparse matrix. return m_matrix * vec; } private: const Eigen::SparseMatrix& m_matrix; }; // Specialization of Eigen::internal::traits for the wrapper type namespace Eigen { namespace internal { template struct traits { typedef Scalar Scalar; typedef MatrixFreeOperator MatrixType; typedef Dense SizedType; typedef Matrix VectorType; }; // Generic product implementation specialization // This is often needed for complex matrix-free operations template struct generic_product_impl> { typedef Eigen::Matrix ResultType; static inline ResultType run(const MatrixFreeOperator& op, const Eigen::MatrixBase& vec) { return op * vec; // Calls the operator* overload in MatrixFreeOperator } }; } } int main() { // Setup a sample sparse matrix A.resize(3, 3); A.insert(0, 0) = 1.0; A.insert(0, 1) = 2.0; A.insert(1, 1) = 3.0; A.insert(2, 2) = 4.0; A.makeCompressed(); // Create the matrix-free operator wrapper MatrixFreeOperator mat_free_op(A); // Create a vector Eigen::VectorXd b(3); b << 1.0, 2.0, 3.0; // Use Eigen's ConjugateGradient with the matrix-free operator Eigen::ConjugateGradient cg; cg.compute(mat_free_op); if (cg.info() != Eigen::Success) { std::cerr << "CG decomposition failed!\n"; return 1; } Eigen::VectorXd x = cg.solve(b); std::cout << "Solution x:\n" << x << std::endl; // Verify the result (optional) Eigen::VectorXd Ax = A * x; std::cout << "A*x:\n" << Ax << std::endl; std::cout << "b:\n" << b << std::endl; return 0; } ``` -------------------------------- ### Inplace LU Decomposition Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/InplaceDecomposition.dox Demonstrates how to perform an inplace LU decomposition with partial pivoting using Eigen. This example shows initialization, decomposition, solving a linear system, and handling matrix modifications. ```APIDOC ## Inplace LU Decomposition with Partial Pivoting ### Description This section demonstrates the usage of inplace LU decomposition with partial pivoting in Eigen. It covers initialization, performing the decomposition, solving linear systems, and managing matrix modifications. ### Method This is a conceptual example illustrating library usage, not a direct API endpoint. ### Endpoint N/A (Library Feature) ### Parameters N/A ### Request Example ```cpp // Initialization of a 2x2 matrix A Eigen::Matrix2d A; A << 1, 2, 3, 4; // Declare an inplace LU object and construct it with matrix A Eigen::PartialPivLU> lu(A); // Solve Ax=b Eigen::Vector2d b(1, 1); Eigen::Vector2d x = lu.solve(b); // Recompute factorization after modifying A // A << 5, 6, // 7, 8; // lu.compute(A); ``` ### Response #### Success Response (Conceptual) - The `lu` object will contain the L and U factors within the memory of matrix `A`. - The `solve` method will return the solution vector `x`. #### Response Example ```cpp // After lu.compute(A), matrix A is modified to contain L and U factors. // The solve method returns the solution vector x. // Example output for solve: // x = // -1 // 1 ``` ### Error Handling - Modifying the input matrix `A` after decomposition invalidates the `lu` object. Re-computation using `lu.compute(A)` is necessary. - The user is responsible for ensuring the input matrix `A` remains valid as long as the `lu` object is in use. ``` -------------------------------- ### Eigen: Slicing Matrix Columns with Compile-Time Start and Stride Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialSlicingIndexing.dox This example shows how to select columns of a matrix 'A' using compile-time specified start and stride values. It extracts columns starting from the first (index 0) to the last, with a fixed step of 2. ```C++ A(all, seq(fix<0>,last,fix<2>)) ``` -------------------------------- ### SparseMatrix Initialization Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialSparse.dox Examples of how to declare and initialize SparseMatrix and SparseVector objects with different scalar types and storage orders. ```APIDOC ## POST /sparse/matrix/initialize ### Description Initializes a new sparse matrix or vector object with specified dimensions and storage order. ### Method POST ### Endpoint /sparse/matrix/initialize ### Parameters #### Request Body - **rows** (int) - Required - Number of rows in the matrix - **cols** (int) - Required - Number of columns in the matrix - **scalarType** (string) - Required - Data type (e.g., "double", "std::complex") - **storageOrder** (string) - Optional - "ColMajor" or "RowMajor" (Default: ColMajor) ### Request Example { "rows": 1000, "cols": 2000, "scalarType": "double", "storageOrder": "RowMajor" } ### Response #### Success Response (200) - **status** (string) - Confirmation of object creation #### Response Example { "status": "success", "object": "SparseMatrix" } ``` -------------------------------- ### EigenBase Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/FunctionsTakingEigenTypes.dox Demonstrates how to use EigenBase to accept the most generic Eigen objects, such as any matrix expression, dense or sparse matrix, or array. ```APIDOC ## EigenBase Example ### Description Prints the dimensions of the most generic object present in %Eigen. It could be any matrix expressions, any dense or sparse matrix and any array. ### Method N/A (Illustrative Example) ### Endpoint N/A (C++ Function Signature) ### Request Example ```cpp // Include function_taking_eigenbase.cpp content here ``` ### Response Example ``` // Include function_taking_eigenbase.out content here ``` ``` -------------------------------- ### MatrixBase Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/FunctionsTakingEigenTypes.dox Demonstrates using MatrixBase to accept matrix or matrix-expressions and calculate the inverse condition number. ```APIDOC ## MatrixBase Example ### Description Prints the inverse condition number of the given matrix or matrix-expression. ### Method N/A (Illustrative Example) ### Endpoint N/A (C++ Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Code Snippet ```cpp template void print_inv_cond(const MatrixBase& a) { const typename JacobiSVD::SingularValuesType& sing_vals = a.jacobiSvd().singularValues(); std::cout << "inv cond: " << sing_vals(sing_vals.size()-1) / sing_vals(0) << std::endl; } ``` ``` -------------------------------- ### Register Example Test Targets Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/doc/examples/SYCL/CMakeLists.txt This snippet iterates over all discovered .cpp files in the directory, creates internal test targets for each, and adds them as dependencies to the unsupported_examples target. ```cmake FILE(GLOB examples_SRCS "*.cpp") FOREACH(example_src ${examples_SRCS}) GET_FILENAME_COMPONENT(example ${example_src} NAME_WE) ei_add_test_internal(${example} example_${example}) ADD_DEPENDENCIES(unsupported_examples example_${example}) ENDFOREACH(example_src) ``` -------------------------------- ### Initialize Sparse Matrices and Vectors Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialSparse.dox Examples of declaring SparseMatrix and SparseVector objects with different scalar types and storage orders (Column-major vs Row-major). ```cpp SparseMatrix > mat(1000,2000); SparseMatrix mat(1000,2000); SparseVector > vec(1000); SparseVector vec(1000); ``` -------------------------------- ### Constructing Eigen Tensors Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/Eigen/src/Tensor/README.md Examples of initializing different types of tensors including standard Tensors, fixed-size tensors, and memory-mapped tensors. ```cpp Eigen::Tensor a(3, 4); Eigen::TensorFixedSize> b; float data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; Eigen::TensorMap> c(data, 3, 4); ``` -------------------------------- ### Multiple Templated Arguments Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/FunctionsTakingEigenTypes.dox Shows how to use multiple templated arguments to handle inputs of different types, such as a vector and an expression. ```APIDOC ## Multiple Templated Arguments Example ### Description Calculate the Euclidean distance between two points. Notice that we used two template parameters, one per argument. This permits the function to handle inputs of different types, e.g., `squaredist(v1,2*v2)` where the first argument `v1` is a vector and the second argument `2*v2` is an expression. ### Method N/A (Illustrative Example) ### Endpoint N/A (C++ Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Code Snippet ```cpp template typename DerivedA::Scalar squaredist(const MatrixBase& p1,const MatrixBase& p2) { return (p1-p2).squaredNorm(); } ``` ``` -------------------------------- ### ArrayBase Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/FunctionsTakingEigenTypes.dox Illustrates using ArrayBase to accept array or array-expressions and retrieve the maximum coefficient. ```APIDOC ## ArrayBase Example ### Description Prints the maximum coefficient of the array or array-expression. ### Method N/A (Illustrative Example) ### Endpoint N/A (C++ Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Code Snippet ```cpp template void print_max_coeff(const ArrayBase &a) { std::cout << "max: " << a.maxCoeff() << std::endl; } ``` ``` -------------------------------- ### Build Executable Examples with CMake Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/doc/examples/CMakeLists.txt This CMake script dynamically finds all C++ source files in the current directory, compiles them into individual executables, links them with Eigen and standard libraries, and sets up post-build commands to capture their output. It also adds these executables to a custom target for managing unsupported examples. ```cmake file(GLOB examples_SRCS "*.cpp") add_custom_target(unsupported_examples) foreach(example_src ${examples_SRCS}) get_filename_component(example ${example_src} NAME_WE) add_executable(example_${example} ${example_src}) if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO) target_link_libraries(example_${example} ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO}) endif() target_link_libraries(example_${example} Eigen3::Eigen) add_custom_command( TARGET example_${example} POST_BUILD COMMAND example_${example} ARGS >${CMAKE_CURRENT_BINARY_DIR}/${example}.out ) add_dependencies(unsupported_examples example_${example}) endforeach(example_src) ``` -------------------------------- ### Eigen N-D Scaling Initialization Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialGeometry.dox Provides examples of initializing N-dimensional scaling objects in Eigen using scalar values, vectors, or multiple components. ```cpp Scaling(sx, sy) Scaling(sx, sy, sz) Scaling(s) Scaling(vecN) ``` -------------------------------- ### Eigen: Coefficient Access and Resizing (C++) Source: https://context7.com/libeigen/eigen/llms.txt Illustrates accessing and modifying individual coefficients, querying matrix dimensions, and resizing matrices (both destructively and conservatively) using Eigen. Includes examples of block operations. ```cpp #include #include int main() { Eigen::MatrixXd m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; // Coefficient access double val = m(1, 2); // row 1, col 2 = 6 m(0, 0) = 100; // modify element // Vector-style access for vectors Eigen::VectorXd v(4); v << 1, 2, 3, 4; double elem = v(2); // or v[2] // Size queries std::cout << "Rows: " << m.rows() << ", Cols: " << m.cols() << "\n"; std::cout << "Size: " << m.size() << "\n"; // Resizing (destructive - values not preserved) Eigen::MatrixXd dynamic(2, 2); dynamic << 1, 2, 3, 4; dynamic.resize(3, 3); // Old values are lost // Conservative resize (preserves values where possible) Eigen::MatrixXd conserv(2, 2); conserv << 1, 2, 3, 4; conserv.conservativeResize(3, 3); // Block operations Eigen::Matrix4d big = Eigen::Matrix4d::Random(); Eigen::Matrix2d block = big.block<2,2>(1, 1); // Fixed-size block Eigen::MatrixXd dynBlock = big.block(0, 0, 2, 3); // Dynamic block // Corner operations Eigen::Matrix2d topLeft = big.topLeftCorner<2,2>(); Eigen::MatrixXd bottomRows = big.bottomRows(2); Eigen::MatrixXd leftCols = big.leftCols(2); // Row and column access Eigen::VectorXd col1 = big.col(1); Eigen::RowVectorXd row2 = big.row(2); std::cout << "Original matrix:\n" << m << "\n\n"; std::cout << "Block(1,1,2,2):\n" << block << "\n"; std::cout << "Column 1: " << col1.transpose() << std::endl; return 0; } ``` -------------------------------- ### DenseBase Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/FunctionsTakingEigenTypes.dox Shows how to use DenseBase to accept any dense matrix or array expression, excluding sparse objects and special matrix classes. ```APIDOC ## DenseBase Example ### Description Prints a sub-block of the dense expression. Accepts any dense matrix or array expression, but no sparse objects and no special matrix classes such as DiagonalMatrix. ### Method N/A (Illustrative Example) ### Endpoint N/A (C++ Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Code Snippet ```cpp template void print_block(const DenseBase& b, int x, int y, int r, int c) { std::cout << "block: " << b.block(x,y,r,c) << std::endl; } ``` ``` -------------------------------- ### Eigen Matrix and Array Conversion Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickReference.dox Illustrates the basic syntax for declaring Eigen Array and Matrix objects. While not a conversion itself, it shows the declaration context for objects that might be involved in conversions. ```C++ Array44f a1, a2; Matrix4f m1, m2; ``` -------------------------------- ### Eigen Matrix Storage Order Example (C++) Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/StorageOrders.dox Demonstrates how to define matrices with different storage orders (row-major and column-major) in Eigen and how they are laid out in memory. It shows that Eigen handles assignments between different storage orders automatically. ```cpp #include #include int main() { // Define a matrix with column-major storage (default) Eigen::Matrix3f Acolmajor; Acolmajor << 8, 2, 2, 9, 1, 4, 3, 5, 4; // Define a matrix with row-major storage Eigen::Matrix Arowmajor; Arowmajor << 8, 2, 2, 9, 1, 4, 3, 5, 4; // Assigning a row-major matrix to a column-major matrix // Eigen automatically reorders the elements. Eigen::Matrix3f B = Arowmajor; std::cout << "Column-major matrix A:\n" << Acolmajor << std::endl; std::cout << "Row-major matrix A:\n" << Arowmajor << std::endl; std::cout << "Assigned matrix B (from row-major):\n" << B << std::endl; // Accessing raw data pointers to show memory layout std::cout << "\nData pointer for Acolmajor:\n"; for (int i = 0; i < Acolmajor.size(); ++i) { std::cout << Acolmajor.data()[i] << " "; } std::cout << std::endl; std::cout << "Data pointer for Arowmajor:\n"; for (int i = 0; i < Arowmajor.size(); ++i) { std::cout << Arowmajor.data()[i] << " "; } std::cout << std::endl; return 0; } ``` -------------------------------- ### Defining a MatrixBase Addon File Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/CustomizingEigen_Plugins.dox Example of a header file containing custom methods to be injected into MatrixBase. This file defines various utility functions like distance calculations and component indexing. ```cpp inline Scalar at(uint i, uint j) const { return this->operator()(i,j); } inline Scalar& at(uint i, uint j) { return this->operator()(i,j); } inline RealScalar squaredLength() const { return squaredNorm(); } template inline Scalar squaredDistanceTo(const MatrixBase& other) const { return (derived() - other.derived()).squaredNorm(); } inline void scaleTo(RealScalar l) { RealScalar vl = norm(); if (vl>1e-9) derived() *= (l/vl); } ``` -------------------------------- ### Initialize Vectors and Matrices Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickReference.dox Demonstrates how to initialize vectors and matrices using unit vectors, identity matrices, and dynamic sizing. ```cpp Vector3f::UnitX(); Vector3f::UnitY(); Vector3f::UnitZ(); Vector4f::Unit(i); x.setUnit(i); x = Dynamic2D::Identity(rows, cols); x.setIdentity(rows, cols); MatrixXi M(3,3); M.setIdentity(); ``` -------------------------------- ### Configure Eigen Installation Path in CMake Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TopicCMakeGuide.dox Shows how to set CMake variables to guide `find_package` to a specific Eigen installation directory. This is useful when Eigen is not in a default location or when multiple versions are installed. ```sh cmake path-to-example-directory -DCMAKE_PREFIX_PATH=$HOME/mypackages ``` ```sh cmake path-to-example-directory -DEigen3_DIR=$HOME/mypackages/share/eigen3/cmake/ ``` -------------------------------- ### Eigen C++: First Program Example Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickStartGuide.dox Demonstrates a basic Eigen program that declares and manipulates a MatrixXd, a dynamic-sized matrix of doubles. It shows how to initialize, set elements, and print the matrix to standard output. Requires the Eigen/Dense header. ```cpp #include #include int main() { Eigen::MatrixXd m(2, 2); m(0, 0) = 3; m(1, 0) = 2.5; m(0, 1) = -1; m(1, 1) = m(0, 1); std::cout << m << std::endl; } ``` -------------------------------- ### Eigen Sparse Solver Initialization with Ordering Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/SparseLinearSystems.dox Demonstrates how to initialize a sparse solver in Eigen, specifying the matrix type and the ordering method. The ordering method is crucial for minimizing fill-in during factorization. ```C++ DirectSolverClassName, OrderingMethod > solver; ``` -------------------------------- ### Install Eigen CXX11 Headers (CMake) Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/Eigen/CXX11/CMakeLists.txt This CMake code snippet configures the installation of Eigen's CXX11 headers. It sets the list of headers to be installed and specifies the destination directory and component for the installation. This is useful for maintaining backward compatibility with older C++ standards. ```cmake set(Eigen_CXX11_HEADERS Tensor TensorSymmetry ThreadPool) install( FILES ${Eigen_CXX11_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/unsupported/Eigen/CXX11 COMPONENT Devel ) ``` -------------------------------- ### Eigen: Predefined Matrices and Initialization Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickReference.dox Provides examples of initializing fixed-size and dynamic-size matrices and vectors with common values like zero, one, constants, random numbers, or linearly spaced values. Includes both direct assignment and `set` methods. ```C++ typedef {Matrix3f|Array33f} FixedXD; FixedXD x; x = FixedXD::Zero(); x = FixedXD::Ones(); x = FixedXD::Constant(value); x = FixedXD::Random(); x = FixedXD::LinSpaced(size, low, high); x.setZero(); x.setOnes(); x.setConstant(value); x.setRandom(); x.setLinSpaced(size, low, high); typedef {MatrixXf|ArrayXXf} Dynamic2D; Dynamic2D x_dyn2d; x_dyn2d = Dynamic2D::Zero(rows, cols); x_dyn2d = Dynamic2D::Ones(rows, cols); x_dyn2d = Dynamic2D::Constant(rows, cols, value); x_dyn2d = Dynamic2D::Random(rows, cols); x_dyn2d.setZero(rows, cols); x_dyn2d.setOnes(rows, cols); x_dyn2d.setConstant(rows, cols, value); x_dyn2d.setRandom(rows, cols); typedef {VectorXf|ArrayXf} Dynamic1D; Dynamic1D x_dyn1d; x_dyn1d = Dynamic1D::Zero(size); x_dyn1d = Dynamic1D::Ones(size); x_dyn1d = Dynamic1D::Constant(size, value); x_dyn1d = Dynamic1D::Random(size); x_dyn1d = Dynamic1D::LinSpaced(size, low, high); x_dyn1d.setZero(size); x_dyn1d.setOnes(size); x_dyn1d.setConstant(size, value); x_dyn1d.setRandom(size); x_dyn1d.setLinSpaced(size, low, high); x = FixedXD::Identity(); x.setIdentity(); ``` -------------------------------- ### Initialize Special Matrices and Arrays Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialAdvancedInitialization.dox Illustrates the use of static methods such as Zero, Constant, and Random to initialize matrices and arrays. It also demonstrates the LinSpaced method for generating sequences. ```cpp MatrixXd m = MatrixXd::Zero(2, 3); MatrixXd n = MatrixXd::Constant(3, 3, 1.5); VectorXd v = VectorXd::LinSpaced(10, 0, 1); ``` -------------------------------- ### Install Eigen EulerAngles Headers with CMake Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/Eigen/src/EulerAngles/CMakeLists.txt This CMake code snippet finds all header files in the current directory and installs them to the appropriate include directory for the Eigen library. It specifically targets the unsupported EulerAngles module and assigns it to the 'Devel' component for installation. ```cmake file(GLOB Eigen_EulerAngles_SRCS "*.h") install( FILES ${Eigen_EulerAngles_SRCS} DESTINATION ${INCLUDE_INSTALL_DIR}/unsupported/Eigen/src/EulerAngles COMPONENT Devel ) ``` -------------------------------- ### Initialize and Resize Sparse Matrices Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/SparseQuickReference.dox Demonstrates how to declare, resize, and reserve memory for sparse matrices. It highlights the default column-major storage order and the importance of memory reservation for performance. ```cpp SparseMatrix sm1(1000,1000); SparseMatrix,RowMajor> sm2; sm1.resize(m,n); sm1.reserve(nnz); ``` -------------------------------- ### stridedSlice(start, stop, strides) Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/Eigen/src/Tensor/README.md Returns a sub-tensor by selecting elements using start, stop (exclusive), and strides for each dimension. ```APIDOC ## stridedSlice(const StartIndices& start, const StopIndices& stop, const Strides& strides) ### Description Returns a sub-tensor by selecting elements using start, stop (exclusive), and strides for each dimension. This operation supports assignment to the slice. ### Method Operation ### Parameters - **start** (StartIndices) - Required - Starting indices. - **stop** (StopIndices) - Required - Exclusive stop indices. - **strides** (Strides) - Required - Step size for each dimension. ### Request Example Eigen::array start = {1, 1}; Eigen::array stop = {4, 6}; Eigen::array strides = {2, 2}; Eigen::Tensor sub = a.stridedSlice(start, stop, strides); ``` -------------------------------- ### Handling Matrix Initialization Ambiguity Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/PreprocessorDirectives.dox Demonstrates how to safely initialize matrices when using EIGEN_INITIALIZE_MATRICES_BY_ZERO, as fixed-size constructors can be ambiguous. It shows the recommended pattern of using the default constructor followed by an explicit resize call. ```cpp Matrix v; v.resize(size); Matrix m; m.resize(rows, cols); ``` -------------------------------- ### Eigen N-D Affine Transformation Initialization Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialGeometry.dox Illustrates the construction of N-dimensional affine transformations in Eigen, showing how to combine translations, rotations, and scalings. ```cpp Transform t = concatenation_of_any_transformations; Transform t = Translation3f(p) * AngleAxisf(a,axis) * Scaling(s); ``` -------------------------------- ### Initialize Matrices and Vectors Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialMatrixClass.dox Illustrates various ways to construct and initialize matrices and vectors, including default constructors, size-based allocation, and C++11 initializer lists. ```cpp Matrix3f a; MatrixXf b; MatrixXf a(10,15); VectorXf b(30); Matrix3f a(3,3); Vector2d a(5.0, 6.0); Matrix b {1, 2, 3, 4, 5}; ``` -------------------------------- ### Configure Eigen Installation Paths (CMake) Source: https://gitlab.com/libeigen/eigen/-/blob/master/CMakeLists.txt This CMake script sets up installation directories for Eigen headers, package configuration files, and pkgconfig files. It includes backward compatibility for deprecated variables and ensures paths are relative to CMAKE_INSTALL_PREFIX. ```cmake include(GNUInstallDirs) if(EIGEN_INCLUDE_INSTALL_DIR) message(WARNING "EIGEN_INCLUDE_INSTALL_DIR is deprecated. Use INCLUDE_INSTALL_DIR instead.") endif() if(EIGEN_INCLUDE_INSTALL_DIR AND NOT INCLUDE_INSTALL_DIR) set(INCLUDE_INSTALL_DIR ${EIGEN_INCLUDE_INSTALL_DIR} CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where Eigen header files are installed") else() set(INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}/eigen3" CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where Eigen header files are installed" ) endif() set(CMAKEPACKAGE_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/eigen3/cmake" CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where Eigen3Config.cmake is installed" ) set(PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/pkgconfig" CACHE PATH "The directory relative to CMAKE_INSTALL_PREFIX where eigen3.pc is installed" ) foreach(var INCLUDE_INSTALL_DIR CMAKEPACKAGE_INSTALL_DIR PKGCONFIG_INSTALL_DIR) if(IS_ABSOLUTE "${${var}}") file(RELATIVE_PATH "${var}" "${CMAKE_INSTALL_PREFIX}" "${${var}}") endif() endforeach() ``` -------------------------------- ### Initialize Matrices and Vectors with Initializer Lists Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialMatrixClass.dox Demonstrates how to use C++11 initializer lists to construct matrices and vectors. Supports row-vectors, column-vectors, and multi-dimensional matrices. ```cpp Matrix c = {1, 2, 3, 4, 5}; MatrixXi a { {1, 2}, {3, 4} }; Matrix b { {2, 3, 4}, {5, 6, 7} }; VectorXd a {{1.5, 2.5, 3.5}}; RowVectorXd b {{1.0, 2.0, 3.0, 4.0}}; ``` -------------------------------- ### Eigen: Matrix and Array Resizing Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickReference.dox Demonstrates how to resize dynamic-size matrices and vectors in Eigen, with and without preserving data. Includes methods for setting specific dimensions, resizing based on another object, and conservative resizing. ```C++ vector.resize(size); vector.resizeLike(other_vector); vector.conservativeResize(size); matrix.resize(nb_rows, nb_cols); matrix.resize(Eigen::NoChange, nb_cols); matrix.resize(nb_rows, Eigen::NoChange); matrix.resizeLike(other_matrix); matrix.conservativeResize(nb_rows, nb_cols); ``` -------------------------------- ### Build Eigen Examples with CMake Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/examples/CMakeLists.txt This CMake script iterates through all C++ source files in the current directory, compiles them into separate executables, links them with the Eigen library and standard libraries if specified, and sets up a post-build command to run each example executable, redirecting its output. ```cmake file(GLOB examples_SRCS "*.cpp") foreach(example_src ${examples_SRCS}) get_filename_component(example ${example_src} NAME_WE) add_executable(${example} ${example_src}) if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO) target_link_libraries(${example} ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO}) endif() target_link_libraries(${example} Eigen3::Eigen) add_custom_command( TARGET ${example} POST_BUILD COMMAND ${example} ARGS >${CMAKE_CURRENT_BINARY_DIR}/${example}.out ) add_dependencies(all_examples ${example}) endforeach() ``` -------------------------------- ### EigenBase Example: Print Dimensions of Generic Eigen Object Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/FunctionsTakingEigenTypes.dox This example demonstrates how to use EigenBase as a generic parameter type for functions. It can accept any Eigen object, including matrices, arrays, and special matrix classes, and prints its dimensions. This showcases the most general way to handle Eigen types. ```cpp #include #include // Function to print dimensions of any Eigen object derived from EigenBase template void print_dimensions(const Eigen::EigenBase& obj) { std::cout << "Rows: " << obj.rows() << ", Cols: " << obj.cols() << std::endl; } int main() { Eigen::Matrix3d mat; mat << 1, 2, 3, 4, 5, 6, 7, 8, 9; print_dimensions(mat); Eigen::ArrayXXf arr(2, 2); arr << 1, 2, 3, 4; print_dimensions(arr); return 0; } ``` -------------------------------- ### Eigen: Create Matrices and Vectors in C++ Source: https://context7.com/libeigen/eigen/llms.txt Demonstrates how to create fixed-size and dynamic-size matrices and vectors using Eigen's Matrix and Vector classes. It covers initialization methods like comma initialization and the creation of special matrices such as identity, zeros, ones, random, and linearly spaced vectors. Requires C++14 or later. ```cpp #include #include int main() { // Fixed-size matrix (4x4 floats) Eigen::Matrix4f fixed; fixed << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16; // Dynamic-size matrix Eigen::MatrixXd dynamic(3, 3); dynamic << 1, 2, 3, 4, 5, 6, 7, 8, 9; // Vectors (column vectors by default) Eigen::Vector3d v(1.0, 2.0, 3.0); Eigen::VectorXd vd(5); vd << 1, 2, 3, 4, 5; // Row vector Eigen::RowVector3i rv(1, 2, 3); // Special matrices Eigen::Matrix3d identity = Eigen::Matrix3d::Identity(); Eigen::MatrixXd zeros = Eigen::MatrixXd::Zero(4, 4); Eigen::MatrixXd ones = Eigen::MatrixXd::Ones(3, 3); Eigen::MatrixXd random = Eigen::MatrixXd::Random(3, 3); Eigen::VectorXd linspace = Eigen::VectorXd::LinSpaced(5, 0, 1); std::cout << "Fixed matrix:\n" << fixed << "\n\n"; std::cout << "Dynamic matrix:\n" << dynamic << "\n\n"; std::cout << "Vector: " << v.transpose() << "\n"; std::cout << "Identity:\n" << identity << "\n"; std::cout << "LinSpaced: " << linspace.transpose() << std::endl; return 0; } ``` -------------------------------- ### Eigen: Matrix and Array Initialization Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickReference.dox Demonstrates various ways to construct and initialize matrices and arrays in Eigen. This includes default constructors, constructors with dimensions, and explicit initialization using comma initializers. Coefficients are uninitialized by default. ```C++ Vector4d v4; Vector2f v1(x, y); Array3i v2(x, y, z); Vector4d v3(x, y, z, w); VectorXf v5; // empty object ArrayXf v6(size); Matrix4f m1; MatrixXf m5; // empty object MatrixXf m6(nb_rows, nb_columns); Vector3f v1_comma; v1_comma << x, y, z; ArrayXf v2_comma(4); v2_comma << 1, 2, 3, 4; Matrix3f m1_comma; m1_comma << 1, 2, 3, 4, 5, 6, 7, 8, 9; ``` -------------------------------- ### slice(offsets, extents) Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/Eigen/src/Tensor/README.md Extracts a sub-tensor from the input tensor based on starting indices and dimensions. ```APIDOC ## slice(const StartIndices& offsets, const Sizes& extents) ### Description Returns a sub-tensor of the given tensor. For each dimension i, the slice is made of the coefficients stored between offset[i] and offset[i] + extents[i] in the input tensor. ### Method Operation ### Parameters - **offsets** (StartIndices) - Required - Starting indices for each dimension. - **extents** (Sizes) - Required - Number of elements to include in each dimension. ### Request Example Eigen::array offsets = {1, 0}; Eigen::array extents = {2, 2}; Eigen::Tensor slice = a.slice(offsets, extents); ``` -------------------------------- ### GET /tensor/element Source: https://gitlab.com/libeigen/eigen/-/blob/master/unsupported/Eigen/src/Tensor/README.md Access or modify a specific element within a tensor using index coordinates. ```APIDOC ## GET /tensor/element ### Description Accesses the element at a specific position in a tensor. The number of indices provided must match the rank of the tensor. ### Method GET (Access) / SET (Assignment) ### Parameters #### Path Parameters - **index0...N** (integer) - Required - The coordinates for the element position. ### Request Example // Accessing an element float val = t_3d(0, 1, 0); // Setting an element t_3d(0, 1, 0) = 12.0f; ### Response #### Success Response (200) - **value** (scalar) - The value stored at the specified tensor index. ``` -------------------------------- ### GET /math/accuracy/notes/{function} Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/CoeffwiseMathFunctionsTable.dox Retrieves specific implementation notes and accuracy warnings for a given mathematical function. ```APIDOC ## GET /math/accuracy/notes/{function} ### Description Provides detailed technical notes regarding specific implementation behaviors, such as argument reduction schemes, hardware delegation, or edge-case handling for a specific function. ### Method GET ### Endpoint /math/accuracy/notes/{function} ### Parameters #### Path Parameters - **function** (string) - Required - The name of the function (e.g., 'sin', 'exp2', 'erf') ### Response #### Success Response (200) - **note_id** (integer) - Reference ID for the note - **description** (string) - Detailed explanation of the accuracy behavior or limitation #### Response Example { "function": "exp2", "note_id": 2, "description": "The exp2 implementation for double shows a max error of 214 ULP near the overflow boundary (x ≈ 1022)." } ``` -------------------------------- ### General Sparse Solver Usage in C++ Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/SparseLinearSystems.dox Demonstrates the typical workflow for solving sparse linear systems Ax = b using Eigen's sparse solvers. It includes steps for matrix filling, solver initialization, decomposition, and solving, along with error checking. ```cpp #include // ... SparseMatrix A; // fill A VectorXd b, x; // fill b // solve Ax = b SolverClassName > solver; solver.compute(A); if(solver.info()!=Success) { // decomposition failed return; } x = solver.solve(b); if(solver.info()!=Success) { // solving failed return; } // solve for another right hand side: x1 = solver.solve(b1); ``` -------------------------------- ### Building Eigen with CMake Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/UsingAOCL.dox CMake configuration command to build and install the Eigen library with appropriate compiler settings for AOCL integration. ```cmake cmake .. -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DCMAKE_INSTALL_PREFIX=$PWD/install \ -DINCLUDE_INSTALL_DIR=$PWD/install/include \ && make install -j$(nproc) ``` -------------------------------- ### Configuring the Plugin Token Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/CustomizingEigen_Plugins.dox Shows how to define the EIGEN_MATRIXBASE_PLUGIN macro in a project configuration header to point to the custom addon file. ```cpp #define EIGEN_MATRIXBASE_PLUGIN "MatrixBaseAddons.h" ``` -------------------------------- ### Sparse Matrix Ordering and Factorization Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/SparseLinearSystems.dox Demonstrates how to configure a sparse solver with a specific ordering method and the process of factorizing the matrix. ```APIDOC ## Sparse Matrix Ordering and Factorization ### Description This section explains how to reorder the nonzero elements of a sparse matrix to minimize fill-in during factorization using various ordering methods (COLAMD, AMD, METIS). It also covers the `factorize()` step, which computes the factors of the coefficient matrix and should be called when matrix values change but the structure remains the same. ### Method Configuration via template parameters, followed by a call to `factorize()`. ### Endpoint N/A (Library Function) ### Parameters #### Template Parameters for Solver Class - **OrderingMethod** (Type) - Required - Specifies the ordering method to be used (e.g., COLAMD, AMD, METIS). ### Request Example ```cpp // Example of configuring a direct solver with an ordering method DirectSolverClassName, OrderingMethod > solver; // Call factorize() after matrix values change solver.factorize(); ``` ### Response N/A (Library Function) ``` -------------------------------- ### Eigen Transformation Type Conversions Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialGeometry.dox Provides examples of converting between different Eigen transformation types, such as converting matrices to rotations or affine transformations. ```cpp Rotation2Df r; r = Matrix2f(..); AngleAxisf aa; aa = Quaternionf(..); AngleAxisf aa; aa = Matrix3f(..); Matrix2f m; m = Rotation2Df(..); Matrix3f m; m = Quaternionf(..); Matrix3f m; m = Scaling(..); Affine3f m; m = AngleAxis3f(..); Affine3f m; m = Scaling(..); Affine3f m; m = Translation3f(..); Affine3f m; m = Matrix3f(..); ``` -------------------------------- ### Basic Matrix and Array Constructors Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/QuickReference.dox Demonstrates the constructors for 1D and 2D matrix and array objects, including fixed-size and dynamic-size options. ```APIDOC ## Basic Matrix and Array Constructors ### Description Constructors for 1D (vectors) and 2D (matrices) objects, both fixed-size and dynamic-size. ### 1D Objects (Vectors and Arrays) ```cpp Vector4d v4; // Fixed-size 4D vector Vector2f v1(x, y); // Fixed-size 2D vector initialized with x, y Array3i v2(x, y, z); // Fixed-size 3D array initialized with x, y, z Vector4d v3(x, y, z, w); // Fixed-size 4D vector initialized with x, y, z, w VectorXf v5; // Dynamic-size vector, uninitialized ArrayXf v6(size); // Dynamic-size array of specified size, uninitialized ``` ### 2D Objects (Matrices and Arrays) ```cpp Matrix4f m1; // Fixed-size 4x4 matrix, uninitialized MatrixXf m5; // Dynamic-size matrix, uninitialized MatrixXf m6(nb_rows, nb_columns); // Dynamic-size matrix with specified rows and columns, uninitialized ``` ### Notes By default, the coefficients are left uninitialized. ``` -------------------------------- ### Demonstrate Aliasing Issue in Transposition Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TutorialMatrixArithmetic.dox Example showing why direct assignment of a transpose to the same matrix (a = a.transpose()) can lead to incorrect results due to aliasing. ```cpp Matrix2d a(1, 2, 3, 4); a = a.transpose(); // This may not produce the expected result due to aliasing ``` -------------------------------- ### Configure and Query Eigen Threading Source: https://gitlab.com/libeigen/eigen/-/blob/master/doc/TopicMultithreading.dox Demonstrates how to set the number of threads for Eigen operations using environment variables, OpenMP, or Eigen's internal API, and how to query the current thread count. ```cpp // Set thread count via environment variable (shell command) // OMP_NUM_THREADS=n ./my_program // Set thread count via OpenMP API omp_set_num_threads(n); // Set thread count via Eigen API Eigen::setNbThreads(n); // Query current thread count int n = Eigen::nbThreads(); ```