### Install pyBKT from source Source: https://github.com/cahlr/pybkt/blob/master/README.md Clone the pyBKT repository and install it manually using the setup.py script. This method is an alternative if pip installation encounters issues. ```bash git clone https://github.com/CAHLR/pyBKT.git cd pyBKT python3 setup.py install ``` -------------------------------- ### Build Eigen Examples Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/examples/CMakeLists.txt This snippet iterates through all .cpp files in the examples directory, compiles them into executables, links necessary libraries, and sets up post-build commands to run the examples and capture their output. It also adds dependencies to ensure all examples are built. ```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() add_custom_command( TARGET ${example} POST_BUILD COMMAND ${example} ARGS >${CMAKE_CURRENT_BINARY_DIR}/${example}.out ) add_dependencies(all_examples ${example}) endforeach(example_src) ``` -------------------------------- ### Configure and Install Pkgconfig File Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/CMakeLists.txt Configures the eigen3.pc.in template and installs the resulting eigen3.pc file if EIGEN_BUILD_PKGCONFIG is enabled. ```cmake if(EIGEN_BUILD_PKGCONFIG) configure_file(eigen3.pc.in eigen3.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/eigen3.pc DESTINATION ${PKGCONFIG_INSTALL_DIR} ) endif() ``` -------------------------------- ### Build Sparse Example with Qt Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/special_examples/CMakeLists.txt Adds an executable for a sparse matrix example and links it with Qt libraries. A post-build command generates a JPEG visualization. ```cmake if(QT4_FOUND) add_executable(Tutorial_sparse_example Tutorial_sparse_example.cpp Tutorial_sparse_example_details.cpp) target_link_libraries(Tutorial_sparse_example ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO} ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY}) add_custom_command( TARGET Tutorial_sparse_example POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/../html/ COMMAND Tutorial_sparse_example ARGS ${CMAKE_CURRENT_BINARY_DIR}/../html/Tutorial_sparse_example.jpeg ) add_dependencies(all_examples Tutorial_sparse_example) endif(QT4_FOUND) ``` -------------------------------- ### Find and Build Unsupported Eigen Examples Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/unsupported/doc/examples/CMakeLists.txt This snippet finds all C++ source files in the current directory, creates an executable for each, links them to specified libraries, and sets up a post-build command to capture the executable's output. It also adds each example to a custom target for unified building. ```cmake FILE(GLOB examples_SRCS "*.cpp") ADD_CUSTOM_TARGET(unsupported_examples) INCLUDE_DIRECTORIES(../../../unsupported ../../../unsupported/test) 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() 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) ``` -------------------------------- ### Matrix Block Operations Example Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialBlockOperations.dox Illustrates the usage of various matrix block operations. Ensure the 'Tutorial_BlockOperations_corner.cpp' file is available for this example. ```cpp #include #include "Eigen/Dense" int main() { Eigen::MatrixXi matrix(4,4); matrix << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15; std::cout << "Top right corner (2,2):\n" << matrix.topRightCorner(2,2) << std::endl; std::cout << "Bottom left corner (2,2):\n" << matrix.bottomLeftCorner(2,2) << std::endl; std::cout << "Top rows (2):\n" << matrix.topRows(2) << std::endl; std::cout << "Bottom rows (2):\n" << matrix.bottomRows(2) << std::endl; std::cout << "Left columns (2):\n" << matrix.leftCols(2) << std::endl; std::cout << "Right columns (2):\n" << matrix.rightCols(2) << std::endl; return 0; } ``` -------------------------------- ### Install Eigen Configuration Files Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/CMakeLists.txt This command installs the necessary CMake configuration files for Eigen, including the main config file, version file, and the UseEigen3.cmake script, to the specified installation directory. ```cmake install ( FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/UseEigen3.cmake ${CMAKE_CURRENT_BINARY_DIR}/Eigen3Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/Eigen3ConfigVersion.cmake DESTINATION ${CMAKEPACKAGE_INSTALL_DIR} ) ``` -------------------------------- ### Fetch Datasets for pyBKT Source: https://github.com/cahlr/pybkt/blob/master/README.md Fetch example datasets (Assistments and CognitiveTutor) for use with pyBKT. These can be downloaded from provided URLs. ```python # Fetch Assistments and CognitiveTutor data (optional - if you have your own dataset, that's fine too!) model.fetch_dataset('https://raw.githubusercontent.com/CAHLR/pyBKT-examples/master/data/as.csv', '.') model.fetch_dataset('https://raw.githubusercontent.com/CAHLR/pyBKT-examples/master/data/ct.csv', '.') ``` -------------------------------- ### Set Pkgconfig Installation Directory Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/CMakeLists.txt Defines the installation directory for the eigen3.pc file. ```cmake set(PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/pkgconfig" CACHE STRING "The directory relative to CMAKE_PREFIX_PATH where eigen3.pc is installed" ) ``` -------------------------------- ### Row-Major vs. Column-Major Storage Example Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/StorageOrders.dox Demonstrates how a matrix is laid out in memory for both row-major and column-major storage orders using PlainObjectBase::data(). ```cpp #include #include int main() { // Define a 3x4 matrix with row-major storage Eigen::Matrix Arowmajor; Arowmajor << 8, 2, 2, 9, 9, 1, 4, 4, 3, 5, 4, 5; // Define a 3x4 matrix with column-major storage (default) Eigen::Matrix Acolmajor; Acolmajor = Arowmajor; // Print the data pointers and the data itself std::cout << "Arowmajor data: " << Arowmajor.data() << std::endl; for(int i=0; i #include "Eigen/Dense" int main() { Eigen::VectorXi vector(8); vector << 0, 1, 2, 3, 4, 5, 6, 7; std::cout << "Head (4 elements):\n" << vector.head(4) << std::endl; std::cout << "Tail (4 elements):\n" << vector.tail(4) << std::endl; std::cout << "Segment (4 elements starting at 2):\n" << vector.segment(2,4) << std::endl; return 0; } ``` -------------------------------- ### Matrix-free Conjugate Gradient Example Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/MatrixfreeSolverExample.dox This C++ code demonstrates a complete example of wrapping an Eigen::SparseMatrix to be used with a matrix-free Conjugate Gradient solver. It requires implementing specific methods for the wrapper class and specializing Eigen::internal::traits. ```cpp #include #include #include #include // Define a matrix-free wrapper for Eigen::SparseMatrix // This class provides the necessary interface for Eigen's iterative solvers // to operate in a matrix-free manner. template class SparseMatrixWrapper { public: typedef Scalar Scalar; typedef Index Index; SparseMatrixWrapper(const Eigen::SparseMatrix& mat) : m_mat(mat) {} // Required methods for matrix-free operations Index rows() const { return m_mat.rows(); } Index cols() const { return m_mat.cols(); } // The actual matrix-vector product is implemented via a specialization // of Eigen::internal::generic_product_impl. // This method is a placeholder and its implementation is delegated. template typename Eigen::internal::product_type, Rhs>::type operator*(const Eigen::MatrixBase& rhs) const { // This is where the actual matrix-vector product logic would go. // For this example, we rely on the specialization of generic_product_impl. return Eigen::internal::generic_product_impl, Rhs>:: rightTriangularProduct(*this, rhs); } private: const Eigen::SparseMatrix& m_mat; }; // Specialization of Eigen::internal::traits for our wrapper class namespace Eigen { namespace internal { template struct traits> { typedef Scalar Scalar; typedef Index Index; typedef void StorageKind; typedef void Compilemma; // Define the matrix type for the product typedef typename SparseMatrixWrapper::template operator*>>::type ProductType; }; // Specialization of Eigen::internal::generic_product_impl to define the matrix-vector product // This is the core of the matrix-free implementation. template class generic_product_impl, Eigen::DenseBase>> { typedef SparseMatrixWrapper Matrix; typedef Eigen::DenseBase> Vector; public: typedef typename traits::Scalar Scalar; typedef typename traits::Index Index; // Perform the matrix-vector product using the underlying SparseMatrix static inline void rightTriangularProduct(const Matrix& mat, const Vector& vec, Eigen::DenseBase>& result) { // The actual matrix-vector product is performed here. // We access the underlying SparseMatrix and perform the multiplication. result = mat.m_mat * vec; } }; } } int main() { // Create a sample sparse matrix Eigen::SparseMatrix mat(4, 4); mat.reserve(8); mat.insert(0, 0) = 1.0; mat.insert(0, 1) = 2.0; mat.insert(1, 1) = 3.0; mat.insert(1, 2) = 4.0; mat.insert(2, 2) = 5.0; mat.insert(2, 3) = 6.0; mat.insert(3, 3) = 7.0; mat.insert(3, 0) = 8.0; mat.makeCompressed(); // Wrap the sparse matrix for matrix-free operations SparseMatrixWrapper mat_wrapper(mat); // Create a dense vector Eigen::VectorXd vec(4); vec << 1.0, 2.0, 3.0, 4.0; // Use ConjugateGradient with the matrix-free wrapper Eigen::ConjugateGradient, Eigen::Lower | Eigen::Upper> cg; cg.compute(mat_wrapper); // Solve the system Ax = b Eigen::VectorXd x = cg.solve(vec); // Output the result std::cout << "Matrix-free CG solution:\n" << x << std::endl; // Verify the result by comparing with direct multiplication Eigen::VectorXd direct_result = mat * vec; std::cout << "Direct multiplication result:\n" << direct_result << std::endl; return 0; } ``` -------------------------------- ### Install pyBKT using pip Source: https://github.com/cahlr/pybkt/blob/master/README.md Install the pyBKT library using pip. This command will typically install the C++/Python version if dependencies are met, otherwise it will fall back to the pure Python version. ```bash pip install pyBKT ``` -------------------------------- ### Converting Transformations Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialGeometry.dox Examples of converting between different rotation and transformation types. ```cpp Rotation2Df r; r = Matrix2f(..); // assumes a pure rotation matrix AngleAxisf aa; aa = Quaternionf(..); AngleAxisf aa; aa = Matrix3f(..); // assumes a pure rotation matrix 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(..); ``` -------------------------------- ### DenseStorage Constructor Example Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/InsideEigenExample.dox Demonstrates the DenseStorage constructor which allocates aligned memory for matrix coefficients. It uses internal::aligned_new for platform-specific alignment when vectorization is enabled. ```cpp inline DenseStorage(int size, int rows, int) : m_data(internal::aligned_new(size)), m_rows(rows) {} ``` -------------------------------- ### Build C++11 Random Example Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/special_examples/CMakeLists.txt Adds an executable for a C++11 random number generation example, links standard libraries, and sets the C++11 standard. A post-build command redirects output to a file. ```cmake if(EIGEN_COMPILER_SUPPORT_CPP11) add_executable(random_cpp11 random_cpp11.cpp) target_link_libraries(random_cpp11 ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO}) add_dependencies(all_examples random_cpp11) ei_add_target_property(random_cpp11 COMPILE_FLAGS "-std=c++11") add_custom_command( TARGET random_cpp11 POST_BUILD COMMAND random_cpp11 ARGS >${CMAKE_CURRENT_BINARY_DIR}/random_cpp11.out ) endif() ``` -------------------------------- ### Sparse Matrix Construction Examples Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialSparse.dox Demonstrates how to declare sparse matrices and vectors with different scalar types, storage orders, and sizes. Specifies column-major, row-major, and complex number types. ```cpp SparseMatrix > mat(1000,2000); // declares a 1000x2000 column-major compressed sparse matrix of complex SparseMatrix mat(1000,2000); // declares a 1000x2000 row-major compressed sparse matrix of double SparseVector > vec(1000); // declares a column sparse vector of complex of size 1000 SparseVector vec(1000); // declares a row sparse vector of double of size 1000 ``` -------------------------------- ### Initialize Matrix for Inplace LU Decomposition Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/InplaceDecomposition.dox Initializes a 2x2 matrix for an inplace LU decomposition example. ```cpp #include #include int main() { Eigen::MatrixXf A(2,2); A << 1, 2, 3, 4; ``` -------------------------------- ### Install libomp for OS X Source: https://github.com/cahlr/pybkt/blob/master/README.md On OS X, install libomp using homebrew to enable fast C++ inferencing. This is an optional step. ```bash brew install libomp ``` -------------------------------- ### Example Usage of makeCirculant Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/CustomizingEigen_NullaryExpr.dox Demonstrates the creation and usage of a circulant matrix using the makeCirculant function and its associated functor. ```cpp #include #include "../Eigen/Core" #include "../Eigen/LU" using namespace Eigen; // ... (circulant_helper, circulant_func, makeCirculant definitions) ... int main() { Vector v; v << 1, 2, 4, 8; MatrixXd m = makeCirculant(v); std::cout << "Circulant matrix:\n" << m << std::endl; } ``` -------------------------------- ### Example MatrixBaseAddons.h Plugin Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/CustomizingEigen_Plugins.dox This header file defines several custom methods for MatrixBase, including accessors, vector operations, and arithmetic operators. These methods become available to all Eigen matrices and expressions. ```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 Scalar at(uint i) const { return this->operator[](i); } inline Scalar& at(uint i) { return this->operator[](i); } inline RealScalar squaredLength() const { return squaredNorm(); } inline RealScalar length() const { return norm(); } inline RealScalar invLength(void) const { return fast_inv_sqrt(squaredNorm()); } template inline Scalar squaredDistanceTo(const MatrixBase& other) const { return (derived() - other.derived()).squaredNorm(); } template inline RealScalar distanceTo(const MatrixBase& other) const { return internal::sqrt(derived().squaredDistanceTo(other)); } inline void scaleTo(RealScalar l) { RealScalar vl = norm(); if (vl>1e-9) derived() *= (l/vl); } inline Transpose transposed() {return this->transpose();} inline const Transpose transposed() const {return this->transpose();} inline uint minComponentId(void) const { int i; this->minCoeff(&i); return i; } inline uint maxComponentId(void) const { int i; this->maxCoeff(&i); return i; } template void makeFloor(const MatrixBase& other) { derived() = derived().cwiseMin(other.derived()); } template void makeCeil(const MatrixBase& other) { derived() = derived().cwiseMax(other.derived()); } const CwiseBinaryOp, const Derived, const ConstantReturnType> operator+(const Scalar& scalar) const { return CwiseBinaryOp, const Derived, const ConstantReturnType>(derived(), Constant(rows(),cols(),scalar)); } friend const CwiseBinaryOp, const ConstantReturnType, Derived> operator+(const Scalar& scalar, const MatrixBase& mat) { return CwiseBinaryOp, const ConstantReturnType, Derived>(Constant(rows(),cols(),scalar), mat.derived()); } ``` -------------------------------- ### Eigen Array Operations with MKL VML Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/UsingIntelMKL.dox These examples demonstrate Eigen's array operations that can be accelerated by Intel MKL's VML routines when EIGEN_USE_MKL_VML is defined. Ensure v1 and v2 are dense vectors. ```cpp v2=v1.array().sin(); v2=v1.array().asin(); v2=v1.array().cos(); v2=v1.array().acos(); v2=v1.array().tan(); v2=v1.array().exp(); v2=v1.array().log(); v2=v1.array().sqrt(); v2=v1.array().square(); v2=v1.array().pow(1.5); ``` -------------------------------- ### Example Usage of Indexing Function Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/CustomizingEigen_NullaryExpr.dox Demonstrates using the indexing function to select specific rows and columns from a matrix, mimicking MatLab's indexing capabilities. ```cpp #include #include "../Eigen/Core" using namespace Eigen; // ... (indexing_functor, indexing definitions) ... int main() { MatrixXd m(4, 4); m << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16; std::cout << "Original matrix:\n" << m << std::endl; Matrix rows; rows << 0, 2; Matrix cols; cols << 1, 3, 0; MatrixXd sub = indexing(m, rows, cols); std::cout << "Submatrix:\n" << sub << std::endl; } ``` -------------------------------- ### Printing Matrix Blocks Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialBlockOperations.dox Demonstrates using both dynamic-size and fixed-size .block() methods to access and print sub-matrices. This example shows blocks used as rvalues. ```cpp #include #include int main() { Eigen::MatrixXf mat(4, 4); mat << Eigen::Matrixf::Random(4, 4); std::cout << "Original matrix:\n" << mat << std::endl; // Dynamic-size block std::cout << "Top-left 2x2 block (dynamic):\n" << mat.block(0, 0, 2, 2) << std::endl; // Fixed-size block std::cout << "Bottom-right 2x2 block (fixed):\n" << mat.block<2, 2>(2, 2) << std::endl; return 0; } ``` -------------------------------- ### Matrix and Array Conversion Example Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickReference.dox Illustrates the declaration of Eigen matrix and array objects. Note that direct conversion between Matrix and Array types is not shown here, but their distinct nature is implied. ```cpp Array44f a1, a1; Matrix4f m1, m2; ``` -------------------------------- ### Get number of dimensions of a Tensor Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/unsupported/Eigen/CXX11/src/Tensor/README.md The `NumDimensions` constant provides the number of dimensions (rank) of a tensor. This example shows how to access and print it. ```cpp Eigen::Tensor a(3, 4); cout << "Dims " << a.NumDimensions; ``` -------------------------------- ### Get tensor dimensions using Dimensions object Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/unsupported/Eigen/CXX11/src/Tensor/README.md This example shows how to obtain the dimensions of a tensor and access them using the `dimensions()` method, which returns a `Dimensions` object. ```cpp Eigen::Tensor a(3, 4); const Eigen::Tensor::Dimensions& d = a.dimensions(); cout << "Dim size: " << d.size << ", dim 0: " << d[0] << ", dim 1: " << d[1]; ``` -------------------------------- ### Slice Vector with Stride using Map Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialReshapeSlicing.dox Create a view of a vector that skips elements, effectively taking a slice with a specified stride. This example selects every third element starting from the first. ```cpp #include #include int main() { Eigen::VectorXf vec = Eigen::VectorXf::LinSpaced(15,0,1); std::cout << "Original vector:\n" << vec.transpose() << std::endl; // Take every 3rd element starting from the first Eigen::VectorXf sliced_vec = vec.array().cwise_indices( [&](int i){ return i % 3 == 0; } ); std::cout << "Sliced vector (every 3rd element):\n" << sliced_vec.transpose() << std::endl; return 0; } ``` -------------------------------- ### Eigen Basic Usage and Size Operations Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/AsciiQuickReference.txt Shows how to get the size of vectors and matrices, and access elements. Note that Eigen is 0-based indexed while Matlab is 1-based. ```cpp // Basic usage // Eigen // Matlab // comments x.size() // length(x) // vector size C.rows() // size(C,1) // number of rows C.cols() // size(C,2) // number of columns x(i) // x(i+1) // Matlab is 1-based C(i,j) // C(i+1,j+1) // ``` -------------------------------- ### Matrix multiplication with destination resizing (Eigen 3.3+) Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TopicAliasing.dox Starting from Eigen 3.3, aliasing is not assumed if the destination matrix is resized, even if the product is not directly assigned to the destination. This example demonstrates a case that would be wrong without explicit evaluation. ```cpp #include #include "Eigen/Core" int main() { Eigen::MatrixXf matA(2,2); matA << 1, 2, 3, 4; Eigen::MatrixXf matB(2,2); matB << 5, 6, 7, 8; // WRONG: matB is resized, and the product is not directly assigned to matB // Eigen 3.3+ does not assume aliasing here. matB = matA * matA; std::cout << "matB = matA * matA; (resized destination, WRONG)\n" << matB << std::endl; return 0; } ``` -------------------------------- ### Sparse Matrix Initialization Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/SparseQuickReference.dox Demonstrates how to initialize sparse matrices with different storage orders and dimensions. Default is ColMajor. ```cpp SparseMatrix sm1(1000,1000); SparseMatrix,RowMajor> sm2; ``` -------------------------------- ### Initialize pyBKT model for parameter fixing Source: https://github.com/cahlr/pybkt/blob/master/README.md Initializes a pyBKT Model instance, preparing for parameter fixing during the fitting process. This setup is a prerequisite for using the `fixed=True` option in `model.fit`. ```python from pyBKT.models import * import numpy as np model = Model() ``` -------------------------------- ### Basic Eigen Vector Addition Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/InsideEigenExample.dox A simple C++ program demonstrating vector addition using Eigen's VectorXf. This example is used to explain Eigen's compilation and optimization strategies. ```cpp #include int main() { int size = 50; // VectorXf is a vector of floats, with dynamic size. Eigen::VectorXf u(size), v(size), w(size); u = v + w; } ``` -------------------------------- ### Basic Matrix Initialization and Access Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickStartGuide.dox Demonstrates declaring a dynamic-size matrix (MatrixXd), initializing its elements, and accessing them using 0-based indexing. ```cpp #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; } ``` -------------------------------- ### Initializing N-D Scaling Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialGeometry.dox Demonstrates various ways to initialize N-dimensional scaling transformations. ```cpp Scaling(sx, sy) Scaling(sx, sy, sz) Scaling(s) Scaling(vecN) ``` -------------------------------- ### Add Support for GMP's mpq_class Type Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/CustomizingEigen_CustomScalar.dox This example demonstrates how to integrate GMP's `mpq_class` with Eigen, including customizing pivot selection for LU factorization by defining a custom scalar score. ```cpp #include #include #include namespace Eigen { template<> struct NumTraits : GenericNumTraits { typedef mpq_class Real; typedef mpq_class NonInteger; typedef mpq_class Nested; static inline Real epsilon() { return 0; } static inline Real dummy_precision() { return 0; } static inline int digits10() { return 0; } enum { IsInteger = 0, IsSigned = 1, IsComplex = 0, RequireInitialization = 1, ReadCost = 6, AddCost = 150, MulCost = 100 }; }; namespace internal { template<> struct scalar_score_coeff_op { struct result_type : boost::totally_ordered1 { std::size_t len; result_type(int i = 0) : len(i) {} // Eigen uses Score(0) and Score() result_type(mpq_class const& q) : len(mpz_size(q.get_num_mpz_t())+ mpz_size(q.get_den_mpz_t())-1) {} friend bool operator<(result_type x, result_type y) { // 0 is the worst possible pivot if (x.len == 0) return y.len > 0; if (y.len == 0) return false; // Prefer a pivot with a small representation return x.len > y.len; } friend bool operator==(result_type x, result_type y) { // Only used to test if the score is 0 return x.len == y.len; } }; result_type operator()(mpq_class const& x) const { return x; } }; } } ``` -------------------------------- ### Validate Installation Paths Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/CMakeLists.txt Ensures that installation directories are relative to CMAKE_PREFIX_PATH and not absolute paths. ```cmake foreach(var INCLUDE_INSTALL_DIR CMAKEPACKAGE_INSTALL_DIR PKGCONFIG_INSTALL_DIR) if(IS_ABSOLUTE "${${var}}") message(FATAL_ERROR "${var} must be relative to CMAKE_PREFIX_PATH. Got: ${${var}}") endif() endforeach() ``` -------------------------------- ### Vector Initialization Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickReference.dox Demonstrates the creation of unit vectors along X, Y, and Z axes. Also shows identity matrix creation. ```C++ Vector3f::UnitX() // 1 0 0 Vector3f::UnitY() // 0 1 0 Vector3f::UnitZ() // 0 0 1 ``` ```C++ x = Dynamic2D::Identity(rows, cols); x.setIdentity(rows, cols); ``` ```C++ VectorXf::Unit(size,i) VectorXf::Unit(4,1) == Vector4f(0,1,0,0) == Vector4f::UnitY() ``` -------------------------------- ### Set CMake Package Installation Directory Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/CMakeLists.txt Defines the installation directory for Eigen3Config.cmake files. ```cmake set(CMAKEPACKAGE_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/eigen3/cmake" CACHE STRING "The directory relative to CMAKE_PREFIX_PATH where Eigen3Config.cmake is installed" ) ``` -------------------------------- ### Get Tensor Size Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/unsupported/Eigen/CXX11/src/Tensor/README.md Use `size()` to get the total number of elements in a tensor. The result can be treated as an integer. ```cpp Eigen::Tensor a(3, 4); cout << "Size: " << a.size(); => Size: 12 ``` -------------------------------- ### Initialize and use pyBKT Roster for student tracking Source: https://github.com/cahlr/pybkt/blob/master/README.md Demonstrates initializing a pyBKT Roster with students and a model, then updating and querying individual student states for mastery and correctness probabilities. ```python from pyBKT.models import * import numpy as np # Create a backend pyBKT model and fit it on the CT data model = Model() model.fit(data_path = 'ct.csv') # Create a Roster with two students, Jeff and Bob, who are participating in the roster # for one skill (Calculate Unit Rate) using the pyBKT model above. roster = Roster(students = ['Jeff', 'Bob'], skills = 'Calculate unit rate', model = model) # Initial mastery state (prior) for Jeff, should be unmastered with low probability of mastery # get_state_type returns whether a student has mastered the skill or not # get_mastery_prob returns the probability a student has mastered the skill print("Jeff's mastery (t = 0):", roster.get_state_type('Calculate unit rate', 'Jeff')) print("Jeff's probability of mastery (t = 0):", roster.get_mastery_prob('Calculate unit rate', 'Jeff')) # We can update Jeff's state by adding one or more responses to a particular skill. In this case, # we observed a correct response for the one skill in the roster. jeff_new_state = roster.update_state('Calculate unit rate', 'Jeff', 1) # Check the updated mastery state and probability. print("Jeff's mastery (t = 1):", roster.get_state_type('Calculate unit rate', 'Jeff')) print("Jeff's probability of mastery (t = 1):", roster.get_mastery_prob('Calculate unit rate', 'Jeff')) # We can update his state with multiple correct responses (ten of them). roster.update_state('Calculate unit rate', 'Jeff', np.ones(10)) # After 10 consecutive correct responses, he should have mastered the skill. print("Jeff's mastery (t = 11):", roster.get_state_type('Calculate unit rate', 'Jeff')) print("Jeff's probability of mastery (t = 11):", roster.get_mastery_prob('Calculate unit rate', 'Jeff')) # Programmatically check whether he has mastered the skill if roster.get_state_type('Calculate unit rate', 'Jeff') == StateType.MASTERED: print("Jeff has mastered the skill!") # We can update Bob's state with two correct responses. roster.update_state('Calculate unit rate', 'Bob', np.ones(2)) # He should remain unmastered. print("Bob's mastery (t = 2):", roster.get_state_type('Calculate unit rate', 'Bob')) print("Bob's probability of mastery (t = 2):", roster.get_mastery_prob('Calculate unit rate', 'Bob')) # We can print aggregate statistics for mastery and correctness. print("Both students' probabilites of correctness:", roster.get_correct_probs('Calculate unit rate')) print("Both students' probabilites of mastery:", roster.get_mastery_probs('Calculate unit rate')) # Add a new student, Sarah. roster.add_student('Calculate unit rate', 'Sarah') # Update Sarah's state with a sequence of correct and incorrect responses. sarah_new_state = roster.update_state('Calculate unit rate', 'Sarah', np.array([1, 0, 1, 0, 1, 1, 1])) # Print Sarah's correctness and mastery probability. print("Sarah's correctness probability:", sarah_new_state.get_correct_prob() print("Sarah's mastery probability:", sarah_new_state.get_mastery_prob()) # Delete Bob from the roster. roster.remove_student('Calculate unit rate', 'Bob') # Reset student's state (i.e. latent and observable). roster.reset_state('Calculate unit rate', 'Jeff') # Jeff should be back to the initial prior as the mastery probability and should be unmastered. print("Jeff's mastery (t' = 0):", roster.get_state_type('Calculate unit rate', 'Jeff')) print("Jeff's probability of mastery (t' = 0):", roster.get_mastery_prob('Calculate unit rate', 'Jeff')) ``` -------------------------------- ### Matrix Operations: Random Initialization and Linear Mapping Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickStartGuide.dox Shows how to create a matrix with random values and apply a linear transformation to scale these values. ```cpp Eigen::MatrixXd m = Eigen::MatrixXd::Random(3,3); m = (m + Eigen::MatrixXd::Constant(3,3,1.2)) * 10; std::cout << m << std::endl; ``` -------------------------------- ### Dynamic Matrix Dimension Examples Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickReference.dox Examples of declaring Eigen matrices with dynamic dimensions. These matrices are typically allocated on the heap. ```cpp Matrix // Dynamic number of columns (heap allocation) Matrix // Dynamic number of rows (heap allocation) Matrix // Fully dynamic, row major (heap allocation) Matrix // Fully fixed (usually allocated on stack) ``` -------------------------------- ### Specifying Eigen Installation Directory Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TopicCMakeGuide.dox If you have multiple Eigen installations, you can direct CMake to a specific one by setting the Eigen3_DIR variable. ```sh cmake path-to-example-directory -DEigen3_DIR=$HOME/mypackages/share/eigen3/cmake/ ``` -------------------------------- ### Matrix and Vector Initialization and Operations Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickStartGuide.dox Illustrates creating a dynamic-size vector and initializing its elements using the comma-initializer. It also shows matrix-vector multiplication. ```cpp Eigen::VectorXd v(3); v << 1, 2, 3; std::cout << "v=\n" << v << std::endl; std::cout << "m*v=\n" << m*v << std::endl; ``` -------------------------------- ### Dynamic Matrix Initialization and Operation Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialAdvancedInitialization.dox Demonstrates initializing a dynamic matrix and performing an element-wise addition with a constant matrix. This showcases the use of expression templates for temporary objects. ```cpp #include #include int main() { Eigen::MatrixXf m(2,2); m << 1, 2, 3, 4; std::cout << "m is:\n" << m << std::endl; Eigen::MatrixXf m2 = Eigen::MatrixXf::Constant(3,3,1.2); std::cout << "m2 is:\n" << m2 << std::endl; std::cout << "m + m2.topRight(2,2):\n" << (m + m2.topRight(2,2)) << std::endl; return 0; } ``` -------------------------------- ### Configure Eigen OpenGL Demo Build Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/demos/opengl/CMakeLists.txt This snippet finds and configures Qt4 and OpenGL, includes necessary Qt files, and sets up include directories for the OpenGL demo. It is conditional on both Qt4 and OpenGL being found. ```cmake find_package(Qt4) find_package(OpenGL) if(QT4_FOUND AND OPENGL_FOUND) set(QT_USE_QTOPENGL TRUE) include(${QT_USE_FILE}) set(CMAKE_INCLUDE_CURRENT_DIR ON) include_directories( ${QT_INCLUDE_DIR} ) set(quaternion_demo_SRCS gpuhelper.cpp icosphere.cpp camera.cpp trackball.cpp quaternion_demo.cpp) qt4_automoc(${quaternion_demo_SRCS}) add_executable(quaternion_demo ${quaternion_demo_SRCS}) add_dependencies(demos quaternion_demo) target_link_libraries(quaternion_demo ${QT_QTCORE_LIBRARY} ${QT_QTGUI_LIBRARY} ${QT_QTOPENGL_LIBRARY} ${OPENGL_LIBRARIES} ) else() message(STATUS "OpenGL demo disabled because Qt4 and/or OpenGL have not been found.") endif() ``` -------------------------------- ### Eigen Matrix Initialization Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/AsciiQuickReference.txt Demonstrates initializing matrices with specific values or by stacking other matrices. The `fill` method sets all elements to a single value. ```cpp A << 1, 2, 3, // Initialize A. The elements can also be 4, 5, 6, // matrices, which are stacked along cols 7, 8, 9; // and then the rows are stacked. B << A, A, A; // B is three horizontally stacked A's. A.fill(10); // Fill A with all 10's. ``` -------------------------------- ### Eigen Matrix Resizing Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/AsciiQuickReference.txt Illustrates how to resize matrices at runtime. Resizing to a smaller fixed dimension can cause a runtime error if assertions are enabled. ```cpp A.resize(4, 4); // Runtime error if assertions are on. B.resize(4, 9); // Runtime error if assertions are on. A.resize(3, 3); // Ok; size didn't change. B.resize(3, 9); // Ok; only dynamic cols changed. ``` -------------------------------- ### Filter and Collect Files for Installation Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/Eigen/CMakeLists.txt Iterates through Eigen_directory_files, filtering out .txt files, hidden files, and files within the 'src' directory. The remaining files are collected for installation. ```cmake foreach(f ${Eigen_directory_files}) if(NOT f MATCHES "\.txt" AND NOT f MATCHES "${ESCAPED_CMAKE_CURRENT_SOURCE_DIR}/[.].+" AND NOT f MATCHES "${ESCAPED_CMAKE_CURRENT_SOURCE_DIR}/src") list(APPEND Eigen_directory_files_to_install ${f}) endif() endforeach(f ${Eigen_directory_files}) ``` -------------------------------- ### Example Usage of Generic Covariance Function Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/FunctionsTakingEigenTypes.dox Demonstrates how to call the generic covariance function with randomly generated matrices. This example assumes the 'cov' function is defined elsewhere and accessible. ```cpp MatrixXf x = MatrixXf::Random(100,3); MatrixXf y = MatrixXf::Random(100,3); MatrixXf C; cov(x, y, C); ``` -------------------------------- ### Install Eigen Header Files Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/Eigen/CMakeLists.txt Installs the filtered header files to the specified include directory with the Eigen component. This ensures the library's headers are available to projects using it. ```cmake install(FILES ${Eigen_directory_files_to_install} DESTINATION ${INCLUDE_INSTALL_DIR}/Eigen COMPONENT Devel ) ``` -------------------------------- ### TensorMap Class Constructors Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/unsupported/Eigen/CXX11/src/Tensor/README.md Shows how to create TensorMap instances to view existing memory as a tensor. ```APIDOC ## Constructor `TensorMap>(data, size0, size1, ...)` Constructor for a Tensor. The constructor must be passed a pointer to the storage for the data, and "rank" size attributes. The storage has to be large enough to hold all the data. ```cpp // Map a tensor of ints on top of stack-allocated storage. int storage[128]; // 2 x 4 x 2 x 8 = 128 TensorMap> t_4d(storage, 2, 4, 2, 8); // The same storage can be viewed as a different tensor. // You can also pass the sizes as an array. TensorMap> t_2d(storage, 16, 8); // You can also map fixed-size tensors. Here we get a 1d view of // the 2d fixed-size tensor. TensorFixedSize> t_4x3; TensorMap> t_12(t_4x3.data(), 12); ``` ``` -------------------------------- ### Convenience Typedef for RowVector2i Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialMatrixClass.dox An example of a convenience typedef for a 2-element row vector of integers. ```cpp typedef Matrix RowVector2i; ``` -------------------------------- ### Mixed Fixed and Dynamic Sized Matrix Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialMatrixClass.dox Illustrates creating a matrix with a fixed number of rows and a dynamic number of columns. ```cpp Matrix ``` -------------------------------- ### Include SparseLU Module Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialSparse.dox Include this header for Sparse LU factorization to solve general square sparse systems. ```cpp #include ``` -------------------------------- ### Convenience Typedef for Vector3f Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialMatrixClass.dox An example of a convenience typedef for a 3-element column vector of floats. ```cpp typedef Matrix Vector3f; ``` -------------------------------- ### Array Arithmetic Operators Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickReference.dox Provides examples of arithmetic operations that can be performed element-wise on Eigen arrays. ```C++ array1 * array2 array1 / array2 array1 *= array2 array1 /= array2 array1 + scalar array1 - scalar array1 += scalar array1 -= scalar ``` -------------------------------- ### Convenience Typedef for Matrix4f Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialMatrixClass.dox An example of a convenience typedef provided by Eigen for a 4x4 matrix of floats. ```cpp typedef Matrix Matrix4f; ``` -------------------------------- ### Applying Transformation to Vector Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialGeometry.dox Shows how to apply a generic transformation to a vector. ```cpp gen * vector; ``` -------------------------------- ### Initializing N-D Translation Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TutorialGeometry.dox Demonstrates various ways to initialize N-dimensional translation transformations. ```cpp Translation(tx, ty) Translation(tx, ty, tz) Translation(s) Translation(vecN) ``` -------------------------------- ### Optimized matrix products Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/QuickReference.dox Demonstrates optimized matrix products involving diagonal matrices, triangular views, and self-adjoint views. Uses 'noalias' for performance. ```cpp mat3 += scalar * vec1.asDiagonal() * mat1; mat3 += scalar * mat1 * vec1.asDiagonal(); mat3.noalias() += scalar * mat1.triangularView() * mat2; mat3.noalias() += scalar * mat2 * mat1.triangularView(); mat3.noalias() += scalar * mat1.selfadjointView() * mat2; mat3.noalias() += scalar * mat2 * mat1.selfadjointView(); mat1.selfadjointView().rankUpdate(mat2); mat1.selfadjointView().rankUpdate(mat2.adjoint(), scalar); ``` -------------------------------- ### Multiple Templated Arguments: Example Usage Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/FunctionsTakingEigenTypes.dox Demonstrates calling the squaredist function with arguments of different types, such as a vector and an expression. ```cpp squaredist(v1,2*v2) ``` -------------------------------- ### Checking for Eigen Package Availability Source: https://github.com/cahlr/pybkt/blob/master/source-cpp/pyBKT/Eigen/doc/TopicCMakeGuide.dox This example shows how to conditionally use Eigen if it's found by `find_package` without the `REQUIRED` option. ```cmake find_package (Eigen3 3.3 NO_MODULE) if (TARGET Eigen3::Eigen) # Use the imported target endif (TARGET Eigen3::Eigen) ```